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