Polly 24.0.0git
DeLICM.cpp
Go to the documentation of this file.
1//===------ DeLICM.cpp -----------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Undo the effect of Loop Invariant Code Motion (LICM) and
10// GVN Partial Redundancy Elimination (PRE) on SCoP-level.
11//
12// Namely, remove register/scalar dependencies by mapping them back to array
13// elements.
14//
15//===----------------------------------------------------------------------===//
16
17#include "polly/DeLICM.h"
18#include "polly/Options.h"
19#include "polly/ScopDetection.h"
20#include "polly/ScopInfo.h"
24#include "polly/ZoneAlgo.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/IR/Module.h"
27
29#define DEBUG_TYPE "polly-delicm"
30
31using namespace polly;
32using namespace llvm;
33
34namespace {
35
36static cl::opt<bool> PollyPrintDeLICM("polly-print-delicm",
37 cl::desc("Polly - Print DeLICM/DePRE"),
38 cl::cat(PollyCategory));
39
40cl::opt<int>
41 DelicmMaxOps("polly-delicm-max-ops",
42 cl::desc("Maximum number of isl operations to invest for "
43 "lifetime analysis; 0=no limit"),
44 cl::init(1500000), cl::cat(PollyCategory));
45
46cl::opt<bool> DelicmOverapproximateWrites(
47 "polly-delicm-overapproximate-writes",
48 cl::desc(
49 "Do more PHI writes than necessary in order to avoid partial accesses"),
50 cl::init(false), cl::Hidden, cl::cat(PollyCategory));
51
52cl::opt<cl::boolOrDefault> DelicmPartialWrites(
53 "polly-delicm-partial-writes",
54 cl::desc("Allow partial writes (default: true; false with "
55 "-polly-optimize-for-vectorization)"),
56 cl::init(cl::boolOrDefault::BOU_UNSET), cl::Hidden, cl::cat(PollyCategory));
57
58/// Partial PHI writes become conditional stores reloaded in the next iteration,
59/// which the LoopVectorizer cannot vectorize.
60static bool allowPartialPHIWrites() {
61 if (DelicmPartialWrites != cl::boolOrDefault::BOU_UNSET)
62 return DelicmPartialWrites == cl::boolOrDefault::BOU_TRUE;
64}
65
66cl::opt<bool>
67 DelicmComputeKnown("polly-delicm-compute-known",
68 cl::desc("Compute known content of array elements"),
69 cl::init(true), cl::Hidden, cl::cat(PollyCategory));
70
71STATISTIC(DeLICMAnalyzed, "Number of successfully analyzed SCoPs");
72STATISTIC(DeLICMOutOfQuota,
73 "Analyses aborted because max_operations was reached");
74STATISTIC(MappedValueScalars, "Number of mapped Value scalars");
75STATISTIC(MappedPHIScalars, "Number of mapped PHI scalars");
76STATISTIC(TargetsMapped, "Number of stores used for at least one mapping");
77STATISTIC(DeLICMScopsModified, "Number of SCoPs optimized");
78
79STATISTIC(NumValueWrites, "Number of scalar value writes after DeLICM");
80STATISTIC(NumValueWritesInLoops,
81 "Number of scalar value writes nested in affine loops after DeLICM");
82STATISTIC(NumPHIWrites, "Number of scalar phi writes after DeLICM");
83STATISTIC(NumPHIWritesInLoops,
84 "Number of scalar phi writes nested in affine loops after DeLICM");
85STATISTIC(NumSingletonWrites, "Number of singleton writes after DeLICM");
86STATISTIC(NumSingletonWritesInLoops,
87 "Number of singleton writes nested in affine loops after DeLICM");
88
89isl::union_map computeReachingOverwrite(isl::union_map Schedule,
90 isl::union_map Writes,
91 bool InclPrevWrite,
92 bool InclOverwrite) {
93 return computeReachingWrite(Schedule, Writes, true, InclPrevWrite,
94 InclOverwrite);
95}
96
97/// Compute the next overwrite for a scalar.
98///
99/// @param Schedule { DomainWrite[] -> Scatter[] }
100/// Schedule of (at least) all writes. Instances not in @p
101/// Writes are ignored.
102/// @param Writes { DomainWrite[] }
103/// The element instances that write to the scalar.
104/// @param InclPrevWrite Whether to extend the timepoints to include
105/// the timepoint where the previous write happens.
106/// @param InclOverwrite Whether the reaching overwrite includes the timepoint
107/// of the overwrite itself.
108///
109/// @return { Scatter[] -> DomainDef[] }
110isl::union_map computeScalarReachingOverwrite(isl::union_map Schedule,
111 isl::union_set Writes,
112 bool InclPrevWrite,
113 bool InclOverwrite) {
114
115 // { DomainWrite[] }
116 auto WritesMap = isl::union_map::from_domain(Writes);
117
118 // { [Element[] -> Scatter[]] -> DomainWrite[] }
119 auto Result = computeReachingOverwrite(
120 std::move(Schedule), std::move(WritesMap), InclPrevWrite, InclOverwrite);
121
122 return Result.domain_factor_range();
123}
124
125/// Overload of computeScalarReachingOverwrite, with only one writing statement.
126/// Consequently, the result consists of only one map space.
127///
128/// @param Schedule { DomainWrite[] -> Scatter[] }
129/// @param Writes { DomainWrite[] }
130/// @param InclPrevWrite Include the previous write to result.
131/// @param InclOverwrite Include the overwrite to the result.
132///
133/// @return { Scatter[] -> DomainWrite[] }
134isl::map computeScalarReachingOverwrite(isl::union_map Schedule,
135 isl::set Writes, bool InclPrevWrite,
136 bool InclOverwrite) {
137 isl::space ScatterSpace = getScatterSpace(Schedule);
138 isl::space DomSpace = Writes.get_space();
139
140 isl::union_map ReachOverwrite = computeScalarReachingOverwrite(
141 Schedule, isl::union_set(Writes), InclPrevWrite, InclOverwrite);
142
143 isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomSpace);
144 return singleton(std::move(ReachOverwrite), ResultSpace);
145}
146
147/// Try to find a 'natural' extension of a mapped to elements outside its
148/// domain.
149///
150/// @param Relevant The map with mapping that may not be modified.
151/// @param Universe The domain to which @p Relevant needs to be extended.
152///
153/// @return A map with that associates the domain elements of @p Relevant to the
154/// same elements and in addition the elements of @p Universe to some
155/// undefined elements. The function prefers to return simple maps.
156isl::union_map expandMapping(isl::union_map Relevant, isl::union_set Universe) {
157 Relevant = Relevant.coalesce();
158 isl::union_set RelevantDomain = Relevant.domain();
159 isl::union_map Simplified = Relevant.gist_domain(RelevantDomain);
160 Simplified = Simplified.coalesce();
161 return Simplified.intersect_domain(Universe);
162}
163
164/// Represent the knowledge of the contents of any array elements in any zone or
165/// the knowledge we would add when mapping a scalar to an array element.
166///
167/// Every array element at every zone unit has one of two states:
168///
169/// - Unused: Not occupied by any value so a transformation can change it to
170/// other values.
171///
172/// - Occupied: The element contains a value that is still needed.
173///
174/// The union of Unused and Unknown zones forms the universe, the set of all
175/// elements at every timepoint. The universe can easily be derived from the
176/// array elements that are accessed someway. Arrays that are never accessed
177/// also never play a role in any computation and can hence be ignored. With a
178/// given universe, only one of the sets needs to stored implicitly. Computing
179/// the complement is also an expensive operation, hence this class has been
180/// designed that only one of sets is needed while the other is assumed to be
181/// implicit. It can still be given, but is mostly ignored.
182///
183/// There are two use cases for the Knowledge class:
184///
185/// 1) To represent the knowledge of the current state of ScopInfo. The unused
186/// state means that an element is currently unused: there is no read of it
187/// before the next overwrite. Also called 'Existing'.
188///
189/// 2) To represent the requirements for mapping a scalar to array elements. The
190/// unused state means that there is no change/requirement. Also called
191/// 'Proposed'.
192///
193/// In addition to these states at unit zones, Knowledge needs to know when
194/// values are written. This is because written values may have no lifetime (one
195/// reason is that the value is never read). Such writes would therefore never
196/// conflict, but overwrite values that might still be required. Another source
197/// of problems are multiple writes to the same element at the same timepoint,
198/// because their order is undefined.
199class Knowledge final {
200private:
201 /// { [Element[] -> Zone[]] }
202 /// Set of array elements and when they are alive.
203 /// Can contain a nullptr; in this case the set is implicitly defined as the
204 /// complement of #Unused.
205 ///
206 /// The set of alive array elements is represented as zone, as the set of live
207 /// values can differ depending on how the elements are interpreted.
208 /// Assuming a value X is written at timestep [0] and read at timestep [1]
209 /// without being used at any later point, then the value is alive in the
210 /// interval ]0,1[. This interval cannot be represented by an integer set, as
211 /// it does not contain any integer point. Zones allow us to represent this
212 /// interval and can be converted to sets of timepoints when needed (e.g., in
213 /// isConflicting when comparing to the write sets).
214 /// @see convertZoneToTimepoints and this file's comment for more details.
215 isl::union_set Occupied;
216
217 /// { [Element[] -> Zone[]] }
218 /// Set of array elements when they are not alive, i.e. their memory can be
219 /// used for other purposed. Can contain a nullptr; in this case the set is
220 /// implicitly defined as the complement of #Occupied.
221 isl::union_set Unused;
222
223 /// { [Element[] -> Zone[]] -> ValInst[] }
224 /// Maps to the known content for each array element at any interval.
225 ///
226 /// Any element/interval can map to multiple known elements. This is due to
227 /// multiple llvm::Value referring to the same content. Examples are
228 ///
229 /// - A value stored and loaded again. The LoadInst represents the same value
230 /// as the StoreInst's value operand.
231 ///
232 /// - A PHINode is equal to any one of the incoming values. In case of
233 /// LCSSA-form, it is always equal to its single incoming value.
234 ///
235 /// Two Knowledges are considered not conflicting if at least one of the known
236 /// values match. Not known values are not stored as an unnamed tuple (as
237 /// #Written does), but maps to nothing.
238 ///
239 /// Known values are usually just defined for #Occupied elements. Knowing
240 /// #Unused contents has no advantage as it can be overwritten.
241 isl::union_map Known;
242
243 /// { [Element[] -> Scatter[]] -> ValInst[] }
244 /// The write actions currently in the scop or that would be added when
245 /// mapping a scalar. Maps to the value that is written.
246 ///
247 /// Written values that cannot be identified are represented by an unknown
248 /// ValInst[] (an unnamed tuple of 0 dimension). It conflicts with itself.
249 isl::union_map Written;
250
251 /// Check whether this Knowledge object is well-formed.
252 void checkConsistency() const {
253#ifndef NDEBUG
254 // Default-initialized object
255 if (Occupied.is_null() && Unused.is_null() && Known.is_null() &&
256 Written.is_null())
257 return;
258
259 assert(!Occupied.is_null() || !Unused.is_null());
260 assert(!Known.is_null());
261 assert(!Written.is_null());
262
263 // If not all fields are defined, we cannot derived the universe.
264 if (Occupied.is_null() || Unused.is_null())
265 return;
266
267 assert(Occupied.is_disjoint(Unused));
268 auto Universe = Occupied.unite(Unused);
269
270 assert(!Known.domain().is_subset(Universe).is_false());
271 assert(!Written.domain().is_subset(Universe).is_false());
272#endif
273 }
274
275public:
276 /// Initialize a nullptr-Knowledge. This is only provided for convenience; do
277 /// not use such an object.
278 Knowledge() {}
279
280 /// Create a new object with the given members.
281 Knowledge(isl::union_set Occupied, isl::union_set Unused,
282 isl::union_map Known, isl::union_map Written)
283 : Occupied(std::move(Occupied)), Unused(std::move(Unused)),
284 Known(std::move(Known)), Written(std::move(Written)) {
285 checkConsistency();
286 }
287
288 /// Return whether this object was not default-constructed.
289 bool isUsable() const {
290 return (Occupied.is_null() || Unused.is_null()) && !Known.is_null() &&
291 !Written.is_null();
292 }
293
294 /// Print the content of this object to @p OS.
295 void print(llvm::raw_ostream &OS, unsigned Indent = 0) const {
296 if (isUsable()) {
297 if (!Occupied.is_null())
298 OS.indent(Indent) << "Occupied: " << Occupied << "\n";
299 else
300 OS.indent(Indent) << "Occupied: <Everything else not in Unused>\n";
301 if (!Unused.is_null())
302 OS.indent(Indent) << "Unused: " << Unused << "\n";
303 else
304 OS.indent(Indent) << "Unused: <Everything else not in Occupied>\n";
305 OS.indent(Indent) << "Known: " << Known << "\n";
306 OS.indent(Indent) << "Written : " << Written << '\n';
307 } else {
308 OS.indent(Indent) << "Invalid knowledge\n";
309 }
310 }
311
312 /// Combine two knowledges, this and @p That.
313 void learnFrom(Knowledge That) {
314 assert(!isConflicting(*this, That));
315 assert(!Unused.is_null() && !That.Occupied.is_null());
316 assert(
317 That.Unused.is_null() &&
318 "This function is only prepared to learn occupied elements from That");
319 assert(Occupied.is_null() && "This function does not implement "
320 "`this->Occupied = "
321 "this->Occupied.unite(That.Occupied);`");
322
323 Unused = Unused.subtract(That.Occupied);
324 Known = Known.unite(That.Known);
325 Written = Written.unite(That.Written);
326
327 checkConsistency();
328 }
329
330 /// Determine whether two Knowledges conflict with each other.
331 ///
332 /// In theory @p Existing and @p Proposed are symmetric, but the
333 /// implementation is constrained by the implicit interpretation. That is, @p
334 /// Existing must have #Unused defined (use case 1) and @p Proposed must have
335 /// #Occupied defined (use case 1).
336 ///
337 /// A conflict is defined as non-preserved semantics when they are merged. For
338 /// instance, when for the same array and zone they assume different
339 /// llvm::Values.
340 ///
341 /// @param Existing One of the knowledges with #Unused defined.
342 /// @param Proposed One of the knowledges with #Occupied defined.
343 /// @param OS Dump the conflict reason to this output stream; use
344 /// nullptr to not output anything.
345 /// @param Indent Indention for the conflict reason.
346 ///
347 /// @return True, iff the two knowledges are conflicting.
348 static bool isConflicting(const Knowledge &Existing,
349 const Knowledge &Proposed,
350 llvm::raw_ostream *OS = nullptr,
351 unsigned Indent = 0) {
352 assert(!Existing.Unused.is_null());
353 assert(!Proposed.Occupied.is_null());
354
355#ifndef NDEBUG
356 if (!Existing.Occupied.is_null() && !Proposed.Unused.is_null()) {
357 auto ExistingUniverse = Existing.Occupied.unite(Existing.Unused);
358 auto ProposedUniverse = Proposed.Occupied.unite(Proposed.Unused);
359 assert(ExistingUniverse.is_equal(ProposedUniverse) &&
360 "Both inputs' Knowledges must be over the same universe");
361 }
362#endif
363
364 // Do the Existing and Proposed lifetimes conflict?
365 //
366 // Lifetimes are described as the cross-product of array elements and zone
367 // intervals in which they are alive (the space { [Element[] -> Zone[]] }).
368 // In the following we call this "element/lifetime interval".
369 //
370 // In order to not conflict, one of the following conditions must apply for
371 // each element/lifetime interval:
372 //
373 // 1. If occupied in one of the knowledges, it is unused in the other.
374 //
375 // - or -
376 //
377 // 2. Both contain the same value.
378 //
379 // Instead of partitioning the element/lifetime intervals into a part that
380 // both Knowledges occupy (which requires an expensive subtraction) and for
381 // these to check whether they are known to be the same value, we check only
382 // the second condition and ensure that it also applies when then first
383 // condition is true. This is done by adding a wildcard value to
384 // Proposed.Known and Existing.Unused such that they match as a common known
385 // value. We use the "unknown ValInst" for this purpose. Every
386 // Existing.Unused may match with an unknown Proposed.Occupied because these
387 // never are in conflict with each other.
388 auto ProposedOccupiedAnyVal = makeUnknownForDomain(Proposed.Occupied);
389 auto ProposedValues = Proposed.Known.unite(ProposedOccupiedAnyVal);
390
391 auto ExistingUnusedAnyVal = makeUnknownForDomain(Existing.Unused);
392 auto ExistingValues = Existing.Known.unite(ExistingUnusedAnyVal);
393
394 auto MatchingVals = ExistingValues.intersect(ProposedValues);
395 auto Matches = MatchingVals.domain();
396
397 // Any Proposed.Occupied must either have a match between the known values
398 // of Existing and Occupied, or be in Existing.Unused. In the latter case,
399 // the previously added "AnyVal" will match each other.
400 if (!Proposed.Occupied.is_subset(Matches)) {
401 if (OS) {
402 auto Conflicting = Proposed.Occupied.subtract(Matches);
403 auto ExistingConflictingKnown =
404 Existing.Known.intersect_domain(Conflicting);
405 auto ProposedConflictingKnown =
406 Proposed.Known.intersect_domain(Conflicting);
407
408 OS->indent(Indent) << "Proposed lifetime conflicting with Existing's\n";
409 OS->indent(Indent) << "Conflicting occupied: " << Conflicting << "\n";
410 if (!ExistingConflictingKnown.is_empty())
411 OS->indent(Indent)
412 << "Existing Known: " << ExistingConflictingKnown << "\n";
413 if (!ProposedConflictingKnown.is_empty())
414 OS->indent(Indent)
415 << "Proposed Known: " << ProposedConflictingKnown << "\n";
416 }
417 return true;
418 }
419
420 // Do the writes in Existing conflict with occupied values in Proposed?
421 //
422 // In order to not conflict, it must either write to unused lifetime or
423 // write the same value. To check, we remove the writes that write into
424 // Proposed.Unused (they never conflict) and then see whether the written
425 // value is already in Proposed.Known. If there are multiple known values
426 // and a written value is known under different names, it is enough when one
427 // of the written values (assuming that they are the same value under
428 // different names, e.g. a PHINode and one of the incoming values) matches
429 // one of the known names.
430 //
431 // We convert here the set of lifetimes to actual timepoints. A lifetime is
432 // in conflict with a set of write timepoints, if either a live timepoint is
433 // clearly within the lifetime or if a write happens at the beginning of the
434 // lifetime (where it would conflict with the value that actually writes the
435 // value alive). There is no conflict at the end of a lifetime, as the alive
436 // value will always be read, before it is overwritten again. The last
437 // property holds in Polly for all scalar values and we expect all users of
438 // Knowledge to check this property also for accesses to MemoryKind::Array.
439 auto ProposedFixedDefs =
440 convertZoneToTimepoints(Proposed.Occupied, true, false);
441 auto ProposedFixedKnown =
442 convertZoneToTimepoints(Proposed.Known, isl::dim::in, true, false);
443
444 auto ExistingConflictingWrites =
445 Existing.Written.intersect_domain(ProposedFixedDefs);
446 auto ExistingConflictingWritesDomain = ExistingConflictingWrites.domain();
447
448 auto CommonWrittenVal =
449 ProposedFixedKnown.intersect(ExistingConflictingWrites);
450 auto CommonWrittenValDomain = CommonWrittenVal.domain();
451
452 if (!ExistingConflictingWritesDomain.is_subset(CommonWrittenValDomain)) {
453 if (OS) {
454 auto ExistingConflictingWritten =
455 ExistingConflictingWrites.subtract_domain(CommonWrittenValDomain);
456 auto ProposedConflictingKnown = ProposedFixedKnown.subtract_domain(
457 ExistingConflictingWritten.domain());
458
459 OS->indent(Indent)
460 << "Proposed a lifetime where there is an Existing write into it\n";
461 OS->indent(Indent) << "Existing conflicting writes: "
462 << ExistingConflictingWritten << "\n";
463 if (!ProposedConflictingKnown.is_empty())
464 OS->indent(Indent)
465 << "Proposed conflicting known: " << ProposedConflictingKnown
466 << "\n";
467 }
468 return true;
469 }
470
471 // Do the writes in Proposed conflict with occupied values in Existing?
472 auto ExistingAvailableDefs =
473 convertZoneToTimepoints(Existing.Unused, true, false);
474 auto ExistingKnownDefs =
475 convertZoneToTimepoints(Existing.Known, isl::dim::in, true, false);
476
477 auto ProposedWrittenDomain = Proposed.Written.domain();
478 auto KnownIdentical = ExistingKnownDefs.intersect(Proposed.Written);
479 auto IdenticalOrUnused =
480 ExistingAvailableDefs.unite(KnownIdentical.domain());
481 if (!ProposedWrittenDomain.is_subset(IdenticalOrUnused)) {
482 if (OS) {
483 auto Conflicting = ProposedWrittenDomain.subtract(IdenticalOrUnused);
484 auto ExistingConflictingKnown =
485 ExistingKnownDefs.intersect_domain(Conflicting);
486 auto ProposedConflictingWritten =
487 Proposed.Written.intersect_domain(Conflicting);
488
489 OS->indent(Indent) << "Proposed writes into range used by Existing\n";
490 OS->indent(Indent) << "Proposed conflicting writes: "
491 << ProposedConflictingWritten << "\n";
492 if (!ExistingConflictingKnown.is_empty())
493 OS->indent(Indent)
494 << "Existing conflicting known: " << ExistingConflictingKnown
495 << "\n";
496 }
497 return true;
498 }
499
500 // Does Proposed write at the same time as Existing already does (order of
501 // writes is undefined)? Writing the same value is permitted.
502 auto ExistingWrittenDomain = Existing.Written.domain();
503 auto BothWritten =
504 Existing.Written.domain().intersect(Proposed.Written.domain());
505 auto ExistingKnownWritten = filterKnownValInst(Existing.Written);
506 auto ProposedKnownWritten = filterKnownValInst(Proposed.Written);
507 auto CommonWritten =
508 ExistingKnownWritten.intersect(ProposedKnownWritten).domain();
509
510 if (!BothWritten.is_subset(CommonWritten)) {
511 if (OS) {
512 auto Conflicting = BothWritten.subtract(CommonWritten);
513 auto ExistingConflictingWritten =
514 Existing.Written.intersect_domain(Conflicting);
515 auto ProposedConflictingWritten =
516 Proposed.Written.intersect_domain(Conflicting);
517
518 OS->indent(Indent) << "Proposed writes at the same time as an already "
519 "Existing write\n";
520 OS->indent(Indent) << "Conflicting writes: " << Conflicting << "\n";
521 if (!ExistingConflictingWritten.is_empty())
522 OS->indent(Indent)
523 << "Exiting write: " << ExistingConflictingWritten << "\n";
524 if (!ProposedConflictingWritten.is_empty())
525 OS->indent(Indent)
526 << "Proposed write: " << ProposedConflictingWritten << "\n";
527 }
528 return true;
529 }
530
531 return false;
532 }
533};
534
535/// Implementation of the DeLICM/DePRE transformation.
536class DeLICMImpl final : public ZoneAlgorithm {
537private:
538 /// Knowledge before any transformation took place.
539 Knowledge OriginalZone;
540
541 /// Current knowledge of the SCoP including all already applied
542 /// transformations.
543 Knowledge Zone;
544
545 /// Number of StoreInsts something can be mapped to.
546 int NumberOfCompatibleTargets = 0;
547
548 /// The number of StoreInsts to which at least one value or PHI has been
549 /// mapped to.
550 int NumberOfTargetsMapped = 0;
551
552 /// The number of llvm::Value mapped to some array element.
553 int NumberOfMappedValueScalars = 0;
554
555 /// The number of PHIs mapped to some array element.
556 int NumberOfMappedPHIScalars = 0;
557
558 /// Shared ISL operations budget guarding the expensive zone analysis
559 /// (computeZone) and the scalar-to-store collapsing (greedyCollapse). It is
560 /// constructed dormant (AutoEnter=false) and armed narrowly around each
561 /// dangerous region via IslQuotaScope, so the same budget covers both
562 /// regions without ever nesting two armed scopes.
563 IslMaxOperationsGuard MaxOpGuard;
564
565 /// Determine whether two knowledges are conflicting with each other.
566 ///
567 /// @see Knowledge::isConflicting
568 bool isConflicting(const Knowledge &Proposed) {
569 raw_ostream *OS = nullptr;
570 POLLY_DEBUG(OS = &llvm::dbgs());
571 return Knowledge::isConflicting(Zone, Proposed, OS, 4);
572 }
573
574 /// Determine whether @p SAI is a scalar that can be mapped to an array
575 /// element.
576 bool isMappable(const ScopArrayInfo *SAI) {
577 assert(SAI);
578
579 if (SAI->isValueKind()) {
580 auto *MA = S->getValueDef(SAI);
581 if (!MA) {
583 dbgs()
584 << " Reject because value is read-only within the scop\n");
585 return false;
586 }
587
588 // Mapping if value is used after scop is not supported. The code
589 // generator would need to reload the scalar after the scop, but it
590 // does not have the information to where it is mapped to. Only the
591 // MemoryAccesses have that information, not the ScopArrayInfo.
592 auto Inst = MA->getAccessInstruction();
593 for (Instruction *UserInst : Inst->users()) {
594
595 if (!S->contains(UserInst)) {
596 POLLY_DEBUG(dbgs() << " Reject because value is escaping\n");
597 return false;
598 }
599 }
600
601 return true;
602 }
603
604 if (SAI->isPHIKind()) {
605 auto *MA = S->getPHIRead(SAI);
606 assert(MA);
607
608 // Mapping of an incoming block from before the SCoP is not supported by
609 // the code generator.
610 auto PHI = cast<PHINode>(MA->getAccessInstruction());
611 for (auto Incoming : PHI->blocks()) {
612 if (!S->contains(Incoming)) {
613 POLLY_DEBUG(dbgs()
614 << " Reject because at least one incoming block is "
615 "not in the scop region\n");
616 return false;
617 }
618 }
619
620 return true;
621 }
622
623 POLLY_DEBUG(dbgs() << " Reject ExitPHI or other non-value\n");
624 return false;
625 }
626
627 /// Compute the uses of a MemoryKind::Value and its lifetime (from its
628 /// definition to the last use).
629 ///
630 /// @param SAI The ScopArrayInfo representing the value's storage.
631 ///
632 /// @return { DomainDef[] -> DomainUse[] }, { DomainDef[] -> Zone[] }
633 /// First element is the set of uses for each definition.
634 /// The second is the lifetime of each definition.
635 std::tuple<isl::union_map, isl::map>
636 computeValueUses(const ScopArrayInfo *SAI) {
637 assert(SAI->isValueKind());
638
639 // { DomainRead[] }
640 auto Reads = makeEmptyUnionSet();
641
642 // Find all uses.
643 for (auto *MA : S->getValueUses(SAI))
644 Reads = Reads.unite(getDomainFor(MA));
645
646 // { DomainRead[] -> Scatter[] }
647 auto ReadSchedule = getScatterFor(Reads);
648
649 auto *DefMA = S->getValueDef(SAI);
650 assert(DefMA);
651
652 // { DomainDef[] }
653 auto Writes = getDomainFor(DefMA);
654
655 // { DomainDef[] -> Scatter[] }
656 auto WriteScatter = getScatterFor(Writes);
657
658 // { Scatter[] -> DomainDef[] }
659 auto ReachDef = getScalarReachingDefinition(DefMA->getStatement());
660
661 // { [DomainDef[] -> Scatter[]] -> DomainUse[] }
662 auto Uses = isl::union_map(ReachDef.reverse().range_map())
663 .apply_range(ReadSchedule.reverse());
664
665 // { DomainDef[] -> Scatter[] }
666 auto UseScatter =
667 singleton(Uses.domain().unwrap(),
668 Writes.get_space().map_from_domain_and_range(ScatterSpace));
669
670 // { DomainDef[] -> Zone[] }
671 auto Lifetime = betweenScatter(WriteScatter, UseScatter, false, true);
672
673 // { DomainDef[] -> DomainRead[] }
674 auto DefUses = Uses.domain_factor_domain();
675
676 return std::make_pair(DefUses, Lifetime);
677 }
678
679 /// Try to map a MemoryKind::Value to a given array element.
680 ///
681 /// @param SAI Representation of the scalar's memory to map.
682 /// @param TargetElt { Scatter[] -> Element[] }
683 /// Suggestion where to map a scalar to when at a timepoint.
684 ///
685 /// @return true if the scalar was successfully mapped.
686 bool tryMapValue(const ScopArrayInfo *SAI, isl::map TargetElt) {
687 assert(SAI->isValueKind());
688
689 auto *DefMA = S->getValueDef(SAI);
690 assert(DefMA->isValueKind());
691 assert(DefMA->isMustWrite());
692 auto *V = DefMA->getAccessValue();
693 auto *DefInst = DefMA->getAccessInstruction();
694
695 // Stop if the scalar has already been mapped.
696 if (!DefMA->getLatestScopArrayInfo()->isValueKind())
697 return false;
698
699 // { DomainDef[] -> Scatter[] }
700 auto DefSched = getScatterFor(DefMA);
701
702 // Where each write is mapped to, according to the suggestion.
703 // { DomainDef[] -> Element[] }
704 auto DefTarget = TargetElt.apply_domain(DefSched.reverse());
705 simplify(DefTarget);
706 POLLY_DEBUG(dbgs() << " Def Mapping: " << DefTarget << '\n');
707
708 auto OrigDomain = getDomainFor(DefMA);
709 auto MappedDomain = DefTarget.domain();
710 if (!OrigDomain.is_subset(MappedDomain)) {
712 dbgs()
713 << " Reject because mapping does not encompass all instances\n");
714 return false;
715 }
716
717 // { DomainDef[] -> Zone[] }
718 isl::map Lifetime;
719
720 // { DomainDef[] -> DomainUse[] }
721 isl::union_map DefUses;
722
723 std::tie(DefUses, Lifetime) = computeValueUses(SAI);
724 POLLY_DEBUG(dbgs() << " Lifetime: " << Lifetime << '\n');
725
726 /// { [Element[] -> Zone[]] }
727 auto EltZone = Lifetime.apply_domain(DefTarget).wrap();
728 simplify(EltZone);
729
730 // When known knowledge is disabled, just return the unknown value. It will
731 // either get filtered out or conflict with itself.
732 // { DomainDef[] -> ValInst[] }
733 isl::map ValInst;
734 if (DelicmComputeKnown)
735 ValInst = makeValInst(V, DefMA->getStatement(),
736 LI->getLoopFor(DefInst->getParent()));
737 else
738 ValInst = makeUnknownForDomain(DefMA->getStatement());
739
740 // { DomainDef[] -> [Element[] -> Zone[]] }
741 auto EltKnownTranslator = DefTarget.range_product(Lifetime);
742
743 // { [Element[] -> Zone[]] -> ValInst[] }
744 auto EltKnown = ValInst.apply_domain(EltKnownTranslator);
745 simplify(EltKnown);
746
747 // { DomainDef[] -> [Element[] -> Scatter[]] }
748 auto WrittenTranslator = DefTarget.range_product(DefSched);
749
750 // { [Element[] -> Scatter[]] -> ValInst[] }
751 auto DefEltSched = ValInst.apply_domain(WrittenTranslator);
752 simplify(DefEltSched);
753
754 Knowledge Proposed(EltZone, {}, filterKnownValInst(EltKnown), DefEltSched);
755 if (isConflicting(Proposed))
756 return false;
757
758 // { DomainUse[] -> Element[] }
759 auto UseTarget = DefUses.reverse().apply_range(DefTarget);
760
761 mapValue(SAI, std::move(DefTarget), std::move(UseTarget),
762 std::move(Lifetime), std::move(Proposed));
763 return true;
764 }
765
766 /// After a scalar has been mapped, update the global knowledge.
767 void applyLifetime(Knowledge Proposed) {
768 Zone.learnFrom(std::move(Proposed));
769 }
770
771 /// Map a MemoryKind::Value scalar to an array element.
772 ///
773 /// Callers must have ensured that the mapping is valid and not conflicting.
774 ///
775 /// @param SAI The ScopArrayInfo representing the scalar's memory to
776 /// map.
777 /// @param DefTarget { DomainDef[] -> Element[] }
778 /// The array element to map the scalar to.
779 /// @param UseTarget { DomainUse[] -> Element[] }
780 /// The array elements the uses are mapped to.
781 /// @param Lifetime { DomainDef[] -> Zone[] }
782 /// The lifetime of each llvm::Value definition for
783 /// reporting.
784 /// @param Proposed Mapping constraints for reporting.
785 void mapValue(const ScopArrayInfo *SAI, isl::map DefTarget,
786 isl::union_map UseTarget, isl::map Lifetime,
787 Knowledge Proposed) {
788 // Redirect the read accesses.
789 for (auto *MA : S->getValueUses(SAI)) {
790 // { DomainUse[] }
791 auto Domain = getDomainFor(MA);
792
793 // { DomainUse[] -> Element[] }
794 auto NewAccRel = UseTarget.intersect_domain(Domain);
795 simplify(NewAccRel);
796
797 assert(isl_union_map_n_map(NewAccRel.get()) == 1);
798 MA->setNewAccessRelation(isl::map::from_union_map(NewAccRel));
799 }
800
801 auto *WA = S->getValueDef(SAI);
802 WA->setNewAccessRelation(DefTarget);
803 applyLifetime(Proposed);
804
805 MappedValueScalars++;
806 NumberOfMappedValueScalars += 1;
807 }
808
809 isl::map makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
810 bool IsCertain = true) {
811 // When known knowledge is disabled, just return the unknown value. It will
812 // either get filtered out or conflict with itself.
813 if (!DelicmComputeKnown)
814 return makeUnknownForDomain(UserStmt);
815 return ZoneAlgorithm::makeValInst(Val, UserStmt, Scope, IsCertain);
816 }
817
818 /// Express the incoming values of a PHI for each incoming statement in an
819 /// isl::union_map.
820 ///
821 /// @param SAI The PHI scalar represented by a ScopArrayInfo.
822 ///
823 /// @return { PHIWriteDomain[] -> ValInst[] }
824 isl::union_map determinePHIWrittenValues(const ScopArrayInfo *SAI) {
825 auto Result = makeEmptyUnionMap();
826
827 // Collect the incoming values.
828 for (auto *MA : S->getPHIIncomings(SAI)) {
829 // { DomainWrite[] -> ValInst[] }
830 isl::union_map ValInst;
831 auto *WriteStmt = MA->getStatement();
832
833 auto Incoming = MA->getIncoming();
834 assert(!Incoming.empty());
835 if (Incoming.size() == 1) {
836 ValInst = makeValInst(Incoming[0].second, WriteStmt,
837 LI->getLoopFor(Incoming[0].first));
838 } else {
839 // If the PHI is in a subregion's exit node it can have multiple
840 // incoming values (+ maybe another incoming edge from an unrelated
841 // block). We cannot directly represent it as a single llvm::Value.
842 // We currently model it as unknown value, but modeling as the PHIInst
843 // itself could be OK, too.
844 ValInst = makeUnknownForDomain(WriteStmt);
845 }
846
847 Result = Result.unite(ValInst);
848 }
849
850 assert(Result.is_single_valued() &&
851 "Cannot have multiple incoming values for same incoming statement");
852 return Result;
853 }
854
855 /// Try to map a MemoryKind::PHI scalar to a given array element.
856 ///
857 /// @param SAI Representation of the scalar's memory to map.
858 /// @param TargetElt { Scatter[] -> Element[] }
859 /// Suggestion where to map the scalar to when at a
860 /// timepoint.
861 ///
862 /// @return true if the PHI scalar has been mapped.
863 bool tryMapPHI(const ScopArrayInfo *SAI, isl::map TargetElt) {
864 auto *PHIRead = S->getPHIRead(SAI);
865 assert(PHIRead->isPHIKind());
866 assert(PHIRead->isRead());
867
868 // Skip if already been mapped.
869 if (!PHIRead->getLatestScopArrayInfo()->isPHIKind())
870 return false;
871
872 // { DomainRead[] -> Scatter[] }
873 auto PHISched = getScatterFor(PHIRead);
874
875 // { DomainRead[] -> Element[] }
876 auto PHITarget = PHISched.apply_range(TargetElt);
877 simplify(PHITarget);
878 POLLY_DEBUG(dbgs() << " Mapping: " << PHITarget << '\n');
879
880 auto OrigDomain = getDomainFor(PHIRead);
881 auto MappedDomain = PHITarget.domain();
882 if (!OrigDomain.is_subset(MappedDomain)) {
884 dbgs()
885 << " Reject because mapping does not encompass all instances\n");
886 return false;
887 }
888
889 // { DomainRead[] -> DomainWrite[] }
890 auto PerPHIWrites = computePerPHI(SAI);
891 if (PerPHIWrites.is_null()) {
893 dbgs() << " Reject because cannot determine incoming values\n");
894 return false;
895 }
896
897 // { DomainWrite[] -> Element[] }
898 auto WritesTarget = PerPHIWrites.apply_domain(PHITarget).reverse();
899 simplify(WritesTarget);
900
901 // { DomainWrite[] }
902 auto UniverseWritesDom = isl::union_set::empty(ParamSpace.ctx());
903
904 for (auto *MA : S->getPHIIncomings(SAI))
905 UniverseWritesDom = UniverseWritesDom.unite(getDomainFor(MA));
906
907 auto RelevantWritesTarget = WritesTarget;
908 if (DelicmOverapproximateWrites)
909 WritesTarget = expandMapping(WritesTarget, UniverseWritesDom);
910
911 auto ExpandedWritesDom = WritesTarget.domain();
912 if (!allowPartialPHIWrites() &&
913 !UniverseWritesDom.is_subset(ExpandedWritesDom)) {
915 dbgs() << " Reject because did not find PHI write mapping for "
916 "all instances\n");
917 if (DelicmOverapproximateWrites)
918 POLLY_DEBUG(dbgs() << " Relevant Mapping: "
919 << RelevantWritesTarget << '\n');
920 POLLY_DEBUG(dbgs() << " Deduced Mapping: " << WritesTarget
921 << '\n');
922 POLLY_DEBUG(dbgs() << " Missing instances: "
923 << UniverseWritesDom.subtract(ExpandedWritesDom)
924 << '\n');
925 return false;
926 }
927
928 // { DomainRead[] -> Scatter[] }
929 isl::union_map PerPHIWriteScatterUmap = PerPHIWrites.apply_range(Schedule);
930 isl::map PerPHIWriteScatter =
931 singleton(PerPHIWriteScatterUmap, PHISched.get_space());
932
933 // { DomainRead[] -> Zone[] }
934 auto Lifetime = betweenScatter(PerPHIWriteScatter, PHISched, false, true);
935 simplify(Lifetime);
936 POLLY_DEBUG(dbgs() << " Lifetime: " << Lifetime << "\n");
937
938 // { DomainWrite[] -> Zone[] }
939 auto WriteLifetime = isl::union_map(Lifetime).apply_domain(PerPHIWrites);
940
941 // { DomainWrite[] -> ValInst[] }
942 auto WrittenValue = determinePHIWrittenValues(SAI);
943
944 // { DomainWrite[] -> [Element[] -> Scatter[]] }
945 auto WrittenTranslator = WritesTarget.range_product(Schedule);
946
947 // { [Element[] -> Scatter[]] -> ValInst[] }
948 auto Written = WrittenValue.apply_domain(WrittenTranslator);
949 simplify(Written);
950
951 // { DomainWrite[] -> [Element[] -> Zone[]] }
952 auto LifetimeTranslator = WritesTarget.range_product(WriteLifetime);
953
954 // { DomainWrite[] -> ValInst[] }
955 auto WrittenKnownValue = filterKnownValInst(WrittenValue);
956
957 // { [Element[] -> Zone[]] -> ValInst[] }
958 auto EltLifetimeInst = WrittenKnownValue.apply_domain(LifetimeTranslator);
959 simplify(EltLifetimeInst);
960
961 // { [Element[] -> Zone[] }
962 auto Occupied = LifetimeTranslator.range();
963 simplify(Occupied);
964
965 Knowledge Proposed(Occupied, {}, EltLifetimeInst, Written);
966 if (isConflicting(Proposed))
967 return false;
968
969 mapPHI(SAI, std::move(PHITarget), std::move(WritesTarget),
970 std::move(Lifetime), std::move(Proposed));
971 return true;
972 }
973
974 /// Map a MemoryKind::PHI scalar to an array element.
975 ///
976 /// Callers must have ensured that the mapping is valid and not conflicting
977 /// with the common knowledge.
978 ///
979 /// @param SAI The ScopArrayInfo representing the scalar's memory to
980 /// map.
981 /// @param ReadTarget { DomainRead[] -> Element[] }
982 /// The array element to map the scalar to.
983 /// @param WriteTarget { DomainWrite[] -> Element[] }
984 /// New access target for each PHI incoming write.
985 /// @param Lifetime { DomainRead[] -> Zone[] }
986 /// The lifetime of each PHI for reporting.
987 /// @param Proposed Mapping constraints for reporting.
988 void mapPHI(const ScopArrayInfo *SAI, isl::map ReadTarget,
989 isl::union_map WriteTarget, isl::map Lifetime,
990 Knowledge Proposed) {
991 // { Element[] }
992 isl::space ElementSpace = ReadTarget.get_space().range();
993
994 // Redirect the PHI incoming writes.
995 for (auto *MA : S->getPHIIncomings(SAI)) {
996 // { DomainWrite[] }
997 auto Domain = getDomainFor(MA);
998
999 // { DomainWrite[] -> Element[] }
1000 auto NewAccRel = WriteTarget.intersect_domain(Domain);
1001 simplify(NewAccRel);
1002
1003 isl::space NewAccRelSpace =
1004 Domain.get_space().map_from_domain_and_range(ElementSpace);
1005 isl::map NewAccRelMap = singleton(NewAccRel, NewAccRelSpace);
1006 MA->setNewAccessRelation(NewAccRelMap);
1007 }
1008
1009 // Redirect the PHI read.
1010 auto *PHIRead = S->getPHIRead(SAI);
1011 PHIRead->setNewAccessRelation(ReadTarget);
1012 applyLifetime(Proposed);
1013
1014 MappedPHIScalars++;
1015 NumberOfMappedPHIScalars++;
1016 }
1017
1018 /// Search and map scalars to memory overwritten by @p TargetStoreMA.
1019 ///
1020 /// Start trying to map scalars that are used in the same statement as the
1021 /// store. For every successful mapping, try to also map scalars of the
1022 /// statements where those are written. Repeat, until no more mapping
1023 /// opportunity is found.
1024 ///
1025 /// There is currently no preference in which order scalars are tried.
1026 /// Ideally, we would direct it towards a load instruction of the same array
1027 /// element.
1028 bool collapseScalarsToStore(MemoryAccess *TargetStoreMA) {
1029 assert(TargetStoreMA->isLatestArrayKind());
1030 assert(TargetStoreMA->isMustWrite());
1031
1032 auto TargetStmt = TargetStoreMA->getStatement();
1033
1034 // { DomTarget[] }
1035 auto TargetDom = getDomainFor(TargetStmt);
1036
1037 // { DomTarget[] -> Element[] }
1038 auto TargetAccRel = getAccessRelationFor(TargetStoreMA);
1039
1040 // { Zone[] -> DomTarget[] }
1041 // For each point in time, find the next target store instance. This can be
1042 // expensive for SCoPs with many modular/quasi-affine constraints, so bound
1043 // it with the shared ISL operations budget.
1044 isl::map Target;
1045 {
1046 IslQuotaScope MaxOpScope = MaxOpGuard.enter();
1047 Target = computeScalarReachingOverwrite(Schedule, TargetDom, false, true);
1048
1049 if (MaxOpScope.hasQuotaExceeded()) {
1050 DeLICMOutOfQuota++;
1051 assert(
1052 isl_ctx_last_error(IslCtx.get()) == isl_error_quota &&
1053 "The only reason that these things have not been computed should "
1054 "be if the max-operations limit hit");
1056 dbgs() << "collapseScalarsToStore exceeded max_operations\n");
1057 DebugLoc Begin, End;
1058 getDebugLocations(getBBPairForRegion(&S->getRegion()), Begin, End);
1059 OptimizationRemarkAnalysis R(DEBUG_TYPE, "OutOfQuota", Begin,
1060 S->getEntry());
1061 R << "maximal number of operations exceeded during "
1062 "collapseScalarsToStore";
1063 S->getFunction().getContext().diagnose(R);
1064 return false;
1065 }
1066
1067 if (Target.is_null())
1068 return false;
1069 }
1070
1071 // { Zone[] -> Element[] }
1072 // Use the target store's write location as a suggestion to map scalars to.
1073 auto EltTarget = Target.apply_range(TargetAccRel);
1074 simplify(EltTarget);
1075 POLLY_DEBUG(dbgs() << " Target mapping is " << EltTarget << '\n');
1076
1077 // Stack of elements not yet processed.
1078 SmallVector<MemoryAccess *, 16> Worklist;
1079
1080 // Set of scalars already tested.
1081 SmallPtrSet<const ScopArrayInfo *, 16> Closed;
1082
1083 // Lambda to add all scalar reads to the work list.
1084 auto ProcessAllIncoming = [&](ScopStmt *Stmt) {
1085 for (auto *MA : *Stmt) {
1086 if (!MA->isLatestScalarKind())
1087 continue;
1088 if (!MA->isRead())
1089 continue;
1090
1091 Worklist.push_back(MA);
1092 }
1093 };
1094
1095 auto *WrittenVal = TargetStoreMA->getAccessInstruction()->getOperand(0);
1096 if (auto *WrittenValInputMA = TargetStmt->lookupInputAccessOf(WrittenVal))
1097 Worklist.push_back(WrittenValInputMA);
1098 else
1099 ProcessAllIncoming(TargetStmt);
1100
1101 auto AnyMapped = false;
1102 auto &DL = S->getRegion().getEntry()->getModule()->getDataLayout();
1103 auto StoreSize =
1104 DL.getTypeAllocSize(TargetStoreMA->getAccessValue()->getType());
1105
1106 while (!Worklist.empty()) {
1107 auto *MA = Worklist.pop_back_val();
1108
1109 auto *SAI = MA->getScopArrayInfo();
1110 if (Closed.count(SAI))
1111 continue;
1112 Closed.insert(SAI);
1113 POLLY_DEBUG(dbgs() << "\n Trying to map " << MA << " (SAI: " << SAI
1114 << ")\n");
1115
1116 // Skip non-mappable scalars.
1117 if (!isMappable(SAI))
1118 continue;
1119
1120 auto MASize = DL.getTypeAllocSize(MA->getAccessValue()->getType());
1121 if (MASize > StoreSize) {
1123 dbgs() << " Reject because storage size is insufficient\n");
1124 continue;
1125 }
1126
1127 // Try to map MemoryKind::Value scalars.
1128 if (SAI->isValueKind()) {
1129 if (!tryMapValue(SAI, EltTarget))
1130 continue;
1131
1132 auto *DefAcc = S->getValueDef(SAI);
1133 ProcessAllIncoming(DefAcc->getStatement());
1134
1135 AnyMapped = true;
1136 continue;
1137 }
1138
1139 // Try to map MemoryKind::PHI scalars.
1140 if (SAI->isPHIKind()) {
1141 if (!tryMapPHI(SAI, EltTarget))
1142 continue;
1143 // Add inputs of all incoming statements to the worklist. Prefer the
1144 // input accesses of the incoming blocks.
1145 for (auto *PHIWrite : S->getPHIIncomings(SAI)) {
1146 auto *PHIWriteStmt = PHIWrite->getStatement();
1147 bool FoundAny = false;
1148 for (auto Incoming : PHIWrite->getIncoming()) {
1149 auto *IncomingInputMA =
1150 PHIWriteStmt->lookupInputAccessOf(Incoming.second);
1151 if (!IncomingInputMA)
1152 continue;
1153
1154 Worklist.push_back(IncomingInputMA);
1155 FoundAny = true;
1156 }
1157
1158 if (!FoundAny)
1159 ProcessAllIncoming(PHIWrite->getStatement());
1160 }
1161
1162 AnyMapped = true;
1163 continue;
1164 }
1165 }
1166
1167 if (AnyMapped) {
1168 TargetsMapped++;
1169 NumberOfTargetsMapped++;
1170 }
1171 return AnyMapped;
1172 }
1173
1174 /// Compute when an array element is unused.
1175 ///
1176 /// @return { [Element[] -> Zone[]] }
1177 isl::union_set computeLifetime() const {
1178 // { Element[] -> Zone[] }
1179 auto ArrayUnused = computeArrayUnused(Schedule, AllMustWrites, AllReads,
1180 false, false, true);
1181
1182 auto Result = ArrayUnused.wrap();
1183
1184 simplify(Result);
1185 return Result;
1186 }
1187
1188 /// Determine when an array element is written to, and which value instance is
1189 /// written.
1190 ///
1191 /// @return { [Element[] -> Scatter[]] -> ValInst[] }
1192 isl::union_map computeWritten() const {
1193 // { [Element[] -> Scatter[]] -> ValInst[] }
1194 auto EltWritten = applyDomainRange(AllWriteValInst, Schedule);
1195
1196 simplify(EltWritten);
1197 return EltWritten;
1198 }
1199
1200 /// Determine whether an access touches at most one element.
1201 ///
1202 /// The accessed element could be a scalar or accessing an array with constant
1203 /// subscript, such that all instances access only that element.
1204 ///
1205 /// @param MA The access to test.
1206 ///
1207 /// @return True, if zero or one elements are accessed; False if at least two
1208 /// different elements are accessed.
1209 bool isScalarAccess(MemoryAccess *MA) {
1210 auto Map = getAccessRelationFor(MA);
1211 auto Set = Map.range();
1212 return Set.is_singleton();
1213 }
1214
1215 /// Print mapping statistics to @p OS.
1216 void printStatistics(llvm::raw_ostream &OS, int Indent = 0) const {
1217 OS.indent(Indent) << "Statistics {\n";
1218 OS.indent(Indent + 4) << "Compatible overwrites: "
1219 << NumberOfCompatibleTargets << "\n";
1220 OS.indent(Indent + 4) << "Overwrites mapped to: " << NumberOfTargetsMapped
1221 << '\n';
1222 OS.indent(Indent + 4) << "Value scalars mapped: "
1223 << NumberOfMappedValueScalars << '\n';
1224 OS.indent(Indent + 4) << "PHI scalars mapped: "
1225 << NumberOfMappedPHIScalars << '\n';
1226 OS.indent(Indent) << "}\n";
1227 }
1228
1229public:
1230 DeLICMImpl(Scop *S, LoopInfo *LI)
1231 : ZoneAlgorithm("polly-delicm", S, LI),
1232 MaxOpGuard(IslCtx.get(), DelicmMaxOps, /*AutoEnter=*/false) {}
1233
1234 /// Calculate the lifetime (definition to last use) of every array element.
1235 ///
1236 /// @return True if the computed lifetimes (#Zone) is usable.
1237 bool computeZone() {
1238 // Check that nothing strange occurs.
1239 collectCompatibleElts();
1240
1241 isl::union_set EltUnused;
1242 isl::union_map EltKnown, EltWritten;
1243
1244 {
1245 IslQuotaScope MaxOpScope = MaxOpGuard.enter();
1246
1247 computeCommon();
1248
1249 EltUnused = computeLifetime();
1250 EltKnown = computeKnown(true, false);
1251 EltWritten = computeWritten();
1252 }
1253 DeLICMAnalyzed++;
1254
1255 if (EltUnused.is_null() || EltKnown.is_null() || EltWritten.is_null()) {
1256 assert(isl_ctx_last_error(IslCtx.get()) == isl_error_quota &&
1257 "The only reason that these things have not been computed should "
1258 "be if the max-operations limit hit");
1259 DeLICMOutOfQuota++;
1260 POLLY_DEBUG(dbgs() << "DeLICM analysis exceeded max_operations\n");
1261 DebugLoc Begin, End;
1262 getDebugLocations(getBBPairForRegion(&S->getRegion()), Begin, End);
1263 OptimizationRemarkAnalysis R(DEBUG_TYPE, "OutOfQuota", Begin,
1264 S->getEntry());
1265 R << "maximal number of operations exceeded during zone analysis";
1266 S->getFunction().getContext().diagnose(R);
1267 return false;
1268 }
1269
1270 Zone = OriginalZone = Knowledge({}, EltUnused, EltKnown, EltWritten);
1271 POLLY_DEBUG(dbgs() << "Computed Zone:\n"; OriginalZone.print(dbgs(), 4));
1272
1273 assert(Zone.isUsable() && OriginalZone.isUsable());
1274 return true;
1275 }
1276
1277 /// Try to map as many scalars to unused array elements as possible.
1278 ///
1279 /// Multiple scalars might be mappable to intersecting unused array element
1280 /// zones, but we can only chose one. This is a greedy algorithm, therefore
1281 /// the first processed element claims it.
1282 void greedyCollapse() {
1283 bool Modified = false;
1284 bool MaxOpQuotaExceeded = false;
1285
1286 for (auto &Stmt : *S) {
1287 for (auto *MA : Stmt) {
1288 if (!MA->isLatestArrayKind())
1289 continue;
1290 if (!MA->isWrite())
1291 continue;
1292
1293 if (MA->isMayWrite()) {
1294 POLLY_DEBUG(dbgs() << "Access " << MA
1295 << " pruned because it is a MAY_WRITE\n");
1296 OptimizationRemarkMissed R(DEBUG_TYPE, "TargetMayWrite",
1297 MA->getAccessInstruction());
1298 R << "Skipped possible mapping target because it is not an "
1299 "unconditional overwrite";
1300 S->getFunction().getContext().diagnose(R);
1301 continue;
1302 }
1303
1304 if (Stmt.getNumIterators() == 0) {
1305 POLLY_DEBUG(dbgs() << "Access " << MA
1306 << " pruned because it is not in a loop\n");
1307 OptimizationRemarkMissed R(DEBUG_TYPE, "WriteNotInLoop",
1308 MA->getAccessInstruction());
1309 R << "skipped possible mapping target because it is not in a loop";
1310 S->getFunction().getContext().diagnose(R);
1311 continue;
1312 }
1313
1314 if (isScalarAccess(MA)) {
1315 POLLY_DEBUG(dbgs()
1316 << "Access " << MA
1317 << " pruned because it writes only a single element\n");
1318 OptimizationRemarkMissed R(DEBUG_TYPE, "ScalarWrite",
1319 MA->getAccessInstruction());
1320 R << "skipped possible mapping target because the memory location "
1321 "written to does not depend on its outer loop";
1322 S->getFunction().getContext().diagnose(R);
1323 continue;
1324 }
1325
1326 if (!isa<StoreInst>(MA->getAccessInstruction())) {
1327 POLLY_DEBUG(dbgs() << "Access " << MA
1328 << " pruned because it is not a StoreInst\n");
1329 OptimizationRemarkMissed R(DEBUG_TYPE, "NotAStore",
1330 MA->getAccessInstruction());
1331 R << "skipped possible mapping target because non-store instructions "
1332 "are not supported";
1333 S->getFunction().getContext().diagnose(R);
1334 continue;
1335 }
1336
1337 // Check for more than one element access per statement instance.
1338 // Currently we expect write accesses to be functional, eg. disallow
1339 //
1340 // { Stmt[0] -> [i] : 0 <= i < 2 }
1341 //
1342 // This may occur when some accesses to the element write/read only
1343 // parts of the element, eg. a single byte. Polly then divides each
1344 // element into subelements of the smallest access length, normal access
1345 // then touch multiple of such subelements. It is very common when the
1346 // array is accesses with memset, memcpy or memmove which take i8*
1347 // arguments.
1349 if (!AccRel.is_single_valued().is_true()) {
1350 POLLY_DEBUG(dbgs() << "Access " << MA
1351 << " is incompatible because it writes multiple "
1352 "elements per instance\n");
1353 OptimizationRemarkMissed R(DEBUG_TYPE, "NonFunctionalAccRel",
1354 MA->getAccessInstruction());
1355 R << "skipped possible mapping target because it writes more than "
1356 "one element";
1357 S->getFunction().getContext().diagnose(R);
1358 continue;
1359 }
1360
1361 isl::union_set TouchedElts = AccRel.range();
1362 if (!TouchedElts.is_subset(CompatibleElts)) {
1364 dbgs()
1365 << "Access " << MA
1366 << " is incompatible because it touches incompatible elements\n");
1367 OptimizationRemarkMissed R(DEBUG_TYPE, "IncompatibleElts",
1368 MA->getAccessInstruction());
1369 R << "skipped possible mapping target because a target location "
1370 "cannot be reliably analyzed";
1371 S->getFunction().getContext().diagnose(R);
1372 continue;
1373 }
1374
1375 assert(isCompatibleAccess(MA));
1376 NumberOfCompatibleTargets++;
1377 POLLY_DEBUG(dbgs() << "Analyzing target access " << MA << "\n");
1378 if (collapseScalarsToStore(MA))
1379 Modified = true;
1380 else if (MaxOpGuard.hasQuotaExceeded()) {
1381 MaxOpQuotaExceeded = true;
1382 break;
1383 }
1384 }
1385 if (MaxOpQuotaExceeded)
1386 break;
1387 }
1388
1389 if (Modified)
1390 DeLICMScopsModified++;
1391 }
1392
1393 /// Dump the internal information about a performed DeLICM to @p OS.
1394 void print(llvm::raw_ostream &OS, int Indent = 0) {
1395 if (!Zone.isUsable()) {
1396 OS.indent(Indent) << "Zone not computed\n";
1397 return;
1398 }
1399
1400 printStatistics(OS, Indent);
1401 if (!isModified()) {
1402 OS.indent(Indent) << "No modification has been made\n";
1403 return;
1404 }
1405 printAccesses(OS, Indent);
1406 }
1407
1408 /// Return whether at least one transformation been applied.
1409 bool isModified() const {
1410 return NumberOfTargetsMapped > 0 || NumberOfMappedValueScalars > 0 ||
1411 NumberOfMappedPHIScalars > 0;
1412 }
1413};
1414
1415static std::unique_ptr<DeLICMImpl> collapseToUnused(Scop &S, LoopInfo &LI) {
1416 std::unique_ptr<DeLICMImpl> Impl = std::make_unique<DeLICMImpl>(&S, &LI);
1417
1418 if (!Impl->computeZone()) {
1419 POLLY_DEBUG(dbgs() << "Abort because cannot reliably compute lifetimes\n");
1420 return Impl;
1421 }
1422
1423 POLLY_DEBUG(dbgs() << "Collapsing scalars to unused array elements...\n");
1424 Impl->greedyCollapse();
1425
1426 POLLY_DEBUG(dbgs() << "\nFinal Scop:\n");
1427 POLLY_DEBUG(dbgs() << S);
1428
1429 return Impl;
1430}
1431
1432static std::unique_ptr<DeLICMImpl> runDeLICMImpl(Scop &S, LoopInfo &LI) {
1433 std::unique_ptr<DeLICMImpl> Impl = collapseToUnused(S, LI);
1434
1435 Scop::ScopStatistics ScopStats = S.getStatistics();
1436 NumValueWrites += ScopStats.NumValueWrites;
1437 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
1438 NumPHIWrites += ScopStats.NumPHIWrites;
1439 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
1440 NumSingletonWrites += ScopStats.NumSingletonWrites;
1441 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
1442
1443 return Impl;
1444}
1445} // anonymous namespace
1446
1448 isl::union_set ExistingOccupied, isl::union_set ExistingUnused,
1449 isl::union_map ExistingKnown, isl::union_map ExistingWrites,
1450 isl::union_set ProposedOccupied, isl::union_set ProposedUnused,
1451 isl::union_map ProposedKnown, isl::union_map ProposedWrites,
1452 llvm::raw_ostream *OS, unsigned Indent) {
1453 Knowledge Existing(std::move(ExistingOccupied), std::move(ExistingUnused),
1454 std::move(ExistingKnown), std::move(ExistingWrites));
1455 Knowledge Proposed(std::move(ProposedOccupied), std::move(ProposedUnused),
1456 std::move(ProposedKnown), std::move(ProposedWrites));
1457
1458 return Knowledge::isConflicting(Existing, Proposed, OS, Indent);
1459}
1460
1462 LoopInfo &LI = *S.getLI();
1463 std::unique_ptr<DeLICMImpl> Impl = runDeLICMImpl(S, LI);
1464
1465 if (PollyPrintDeLICM) {
1466 outs() << "Printing analysis 'Polly - DeLICM/DePRE' for region: '"
1467 << S.getName() << "' in function '" << S.getFunction().getName()
1468 << "':\n";
1469 if (Impl) {
1470 assert(Impl->getScop() == &S);
1471
1472 outs() << "DeLICM result:\n";
1473 Impl->print(outs());
1474 }
1475 }
1476
1477 return Impl->isModified();
1478}
#define DEBUG_TYPE
llvm::cl::OptionCategory PollyCategory
#define POLLY_DEBUG(X)
Definition PollyDebug.h:23
STATISTIC(ScopFound, "Number of valid Scops")
bool is_true() const
Definition cpp-checked.h:77
bool is_false() const
Definition cpp-checked.h:76
isl::checked::set wrap() const
isl::checked::map apply_range(isl::checked::map map2) const
isl::checked::space get_space() const
isl::checked::map apply_domain(isl::checked::map map2) const
bool is_null() const
isl::checked::space range() const
isl::checked::union_set range() const
isl::checked::union_map reverse() const
isl::checked::union_map unite(isl::checked::union_map umap2) const
isl::checked::union_set domain() const
isl::checked::union_map apply_range(isl::checked::union_map umap2) const
isl::checked::space get_space() const
isl::checked::union_map apply_domain(isl::checked::union_map umap2) const
isl::checked::union_map intersect_domain(isl::checked::space space) const
isl::checked::union_map coalesce() const
isl::checked::union_map gist_domain(isl::checked::union_set uset) const
boolean is_single_valued() const
isl::checked::union_map intersect(isl::checked::union_map umap2) const
isl::checked::union_set subtract(isl::checked::union_set uset2) const
boolean is_disjoint(const isl::checked::union_set &uset2) const
boolean is_subset(const isl::checked::union_set &uset2) const
isl::checked::union_set unite(isl::checked::union_set uset2) const
isl::checked::union_set intersect(isl::checked::union_set uset2) const
static isl::map from_union_map(isl::union_map umap)
static isl::union_map from_domain(isl::union_set uset)
static isl::union_set empty(isl::ctx ctx)
Scoped limit of ISL operations.
Definition GICHelper.h:424
bool hasQuotaExceeded() const
Return whether the current quota has exceeded.
Definition GICHelper.h:483
IslQuotaScope enter(bool AllowReturnNull=true)
Enter a scope that can handle out-of-quota errors.
Definition GICHelper.h:477
Scope guard for code that allows arbitrary isl function to return an error if the max-operations quot...
Definition GICHelper.h:357
bool hasQuotaExceeded() const
Return whether the current quota has exceeded.
Definition GICHelper.h:404
Represent memory accesses in statements.
Definition ScopInfo.h:428
isl::map getLatestAccessRelation() const
Return the newest access relation of this access.
Definition ScopInfo.h:786
bool isLatestArrayKind() const
Whether storage memory is either an custom .s2a/.phiops alloca (false) or an existing pointer into an...
Definition ScopInfo.h:947
bool isWrite() const
Is this a write memory access?
Definition ScopInfo.h:766
Instruction * getAccessInstruction() const
Return the access instruction of this memory access.
Definition ScopInfo.h:882
bool isMustWrite() const
Is this a must-write memory access?
Definition ScopInfo.h:760
ScopStmt * getStatement() const
Get the statement that contains this memory access.
Definition ScopInfo.h:1028
bool isMayWrite() const
Is this a may-write memory access?
Definition ScopInfo.h:763
Value * getAccessValue() const
Return the access value of this memory access.
Definition ScopInfo.h:864
A class to store information about arrays in the SCoP.
Definition ScopInfo.h:216
bool isValueKind() const
Is this array info modeling an llvm::Value?
Definition ScopInfo.h:322
bool isPHIKind() const
Is this array info modeling special PHI node memory?
Definition ScopInfo.h:334
Statement of the Scop.
Definition ScopInfo.h:1137
Static Control Part.
Definition ScopInfo.h:1627
Base class for algorithms based on zones, like DeLICM.
Definition ZoneAlgo.h:44
isl::map makeValInst(llvm::Value *Val, ScopStmt *UserStmt, llvm::Loop *Scope, bool IsCertain=true)
Create a mapping from a statement instance to the instance of an llvm::Value that can be used in ther...
Definition ZoneAlgo.cpp:755
enum isl_error isl_ctx_last_error(isl_ctx *ctx)
Definition isl_ctx.c:333
@ isl_error_quota
Definition ctx.h:82
#define S(TYPE, NAME)
#define assert(exp)
isl::map betweenScatter(isl::map From, isl::map To, bool InclFrom, bool InclTo)
Construct a range of timepoints between two timepoints.
Definition ISLTools.cpp:119
isl::union_map makeUnknownForDomain(isl::union_set Domain)
Create a domain-to-unknown value mapping.
Definition ZoneAlgo.cpp:229
isl::union_map computeReachingWrite(isl::union_map Schedule, isl::union_map Writes, bool Reverse, bool InclPrevDef, bool InclNextDef)
Compute the reaching definition statement or the next overwrite for each definition of an array eleme...
Definition ISLTools.cpp:313
isl::union_map computeArrayUnused(isl::union_map Schedule, isl::union_map Writes, isl::union_map Reads, bool ReadEltInSameInst, bool InclLastRead, bool InclWrite)
Compute the timepoints where the contents of an array element are not used.
Definition ISLTools.cpp:366
void getDebugLocations(const BBPair &P, DebugLoc &Begin, DebugLoc &End)
Set the begin and end source location for the region limited by P.
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:151
@ PHI
MemoryKind::PHI: Models PHI nodes within the SCoP.
Definition ScopInfo.h:188
bool isConflicting(isl::union_set ExistingOccupied, isl::union_set ExistingUnused, isl::union_map ExistingKnown, isl::union_map ExistingWrites, isl::union_set ProposedOccupied, isl::union_set ProposedUnused, isl::union_map ProposedKnown, isl::union_map ProposedWrites, llvm::raw_ostream *OS=nullptr, unsigned Indent=0)
Determine whether two lifetimes are conflicting.
Definition DeLICM.cpp:1447
void simplify(isl::set &Set)
Simplify a set inplace.
Definition ISLTools.cpp:289
BBPair getBBPairForRegion(const Region *R)
Return the region delimiters (entry & exit block) of R.
bool PollyOptimizeForVectorization
Bypass some of Polly's profitability checks and add vectorize.enable metadata to vectorizable loops a...
isl::union_map applyDomainRange(isl::union_map UMap, isl::union_map Func)
Apply a map to the 'middle' of another relation.
Definition ISLTools.cpp:517
bool runDeLICM(Scop &S)
Definition DeLICM.cpp:1461
isl::union_set convertZoneToTimepoints(isl::union_set Zone, bool InclStart, bool InclEnd)
Convert a zone (range between timepoints) to timepoints.
Definition ISLTools.cpp:410
isl::map singleton(isl::union_map UMap, isl::space ExpectedSpace)
If by construction a union map is known to contain only a single map, return it.
Definition ISLTools.cpp:135
isl::union_map filterKnownValInst(const isl::union_map &UMap)
Return only the mappings that map to known values.
Definition ZoneAlgo.cpp:254
isl::space getScatterSpace(const isl::union_map &Schedule)
Return the scatter space of a Schedule.
Definition ISLTools.cpp:174
static TupleKindPtr Domain("Domain")
isl_size isl_union_map_n_map(__isl_keep isl_union_map *umap)