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 =
488         isl::manage(isl_union_map_domain(Existing.Written.copy()));
489     auto BothWritten =
490         Existing.Written.domain().intersect(Proposed.Written.domain());
491     auto ExistingKnownWritten = filterKnownValInst(Existing.Written);
492     auto ProposedKnownWritten = filterKnownValInst(Proposed.Written);
493     auto CommonWritten =
494         ExistingKnownWritten.intersect(ProposedKnownWritten).domain();
495 
496     if (!BothWritten.is_subset(CommonWritten)) {
497       if (OS) {
498         auto Conflicting = BothWritten.subtract(CommonWritten);
499         auto ExistingConflictingWritten =
500             Existing.Written.intersect_domain(Conflicting);
501         auto ProposedConflictingWritten =
502             Proposed.Written.intersect_domain(Conflicting);
503 
504         OS->indent(Indent) << "Proposed writes at the same time as an already "
505                               "Existing write\n";
506         OS->indent(Indent) << "Conflicting writes: " << Conflicting << "\n";
507         if (!ExistingConflictingWritten.is_empty())
508           OS->indent(Indent)
509               << "Exiting write:      " << ExistingConflictingWritten << "\n";
510         if (!ProposedConflictingWritten.is_empty())
511           OS->indent(Indent)
512               << "Proposed write:     " << ProposedConflictingWritten << "\n";
513       }
514       return true;
515     }
516 
517     return false;
518   }
519 };
520 
521 /// Implementation of the DeLICM/DePRE transformation.
522 class DeLICMImpl : public ZoneAlgorithm {
523 private:
524   /// Knowledge before any transformation took place.
525   Knowledge OriginalZone;
526 
527   /// Current knowledge of the SCoP including all already applied
528   /// transformations.
529   Knowledge Zone;
530 
531   /// Number of StoreInsts something can be mapped to.
532   int NumberOfCompatibleTargets = 0;
533 
534   /// The number of StoreInsts to which at least one value or PHI has been
535   /// mapped to.
536   int NumberOfTargetsMapped = 0;
537 
538   /// The number of llvm::Value mapped to some array element.
539   int NumberOfMappedValueScalars = 0;
540 
541   /// The number of PHIs mapped to some array element.
542   int NumberOfMappedPHIScalars = 0;
543 
544   /// Determine whether two knowledges are conflicting with each other.
545   ///
546   /// @see Knowledge::isConflicting
547   bool isConflicting(const Knowledge &Proposed) {
548     raw_ostream *OS = nullptr;
549     DEBUG(OS = &llvm::dbgs());
550     return Knowledge::isConflicting(Zone, Proposed, OS, 4);
551   }
552 
553   /// Determine whether @p SAI is a scalar that can be mapped to an array
554   /// element.
555   bool isMappable(const ScopArrayInfo *SAI) {
556     assert(SAI);
557 
558     if (SAI->isValueKind()) {
559       auto *MA = S->getValueDef(SAI);
560       if (!MA) {
561         DEBUG(dbgs()
562               << "    Reject because value is read-only within the scop\n");
563         return false;
564       }
565 
566       // Mapping if value is used after scop is not supported. The code
567       // generator would need to reload the scalar after the scop, but it
568       // does not have the information to where it is mapped to. Only the
569       // MemoryAccesses have that information, not the ScopArrayInfo.
570       auto Inst = MA->getAccessInstruction();
571       for (auto User : Inst->users()) {
572         if (!isa<Instruction>(User))
573           return false;
574         auto UserInst = cast<Instruction>(User);
575 
576         if (!S->contains(UserInst)) {
577           DEBUG(dbgs() << "    Reject because value is escaping\n");
578           return false;
579         }
580       }
581 
582       return true;
583     }
584 
585     if (SAI->isPHIKind()) {
586       auto *MA = S->getPHIRead(SAI);
587       assert(MA);
588 
589       // Mapping of an incoming block from before the SCoP is not supported by
590       // the code generator.
591       auto PHI = cast<PHINode>(MA->getAccessInstruction());
592       for (auto Incoming : PHI->blocks()) {
593         if (!S->contains(Incoming)) {
594           DEBUG(dbgs() << "    Reject because at least one incoming block is "
595                           "not in the scop region\n");
596           return false;
597         }
598       }
599 
600       return true;
601     }
602 
603     DEBUG(dbgs() << "    Reject ExitPHI or other non-value\n");
604     return false;
605   }
606 
607   /// Compute the uses of a MemoryKind::Value and its lifetime (from its
608   /// definition to the last use).
609   ///
610   /// @param SAI The ScopArrayInfo representing the value's storage.
611   ///
612   /// @return { DomainDef[] -> DomainUse[] }, { DomainDef[] -> Zone[] }
613   ///         First element is the set of uses for each definition.
614   ///         The second is the lifetime of each definition.
615   std::tuple<isl::union_map, isl::map>
616   computeValueUses(const ScopArrayInfo *SAI) {
617     assert(SAI->isValueKind());
618 
619     // { DomainRead[] }
620     auto Reads = makeEmptyUnionSet();
621 
622     // Find all uses.
623     for (auto *MA : S->getValueUses(SAI))
624       Reads =
625           give(isl_union_set_add_set(Reads.take(), getDomainFor(MA).take()));
626 
627     // { DomainRead[] -> Scatter[] }
628     auto ReadSchedule = getScatterFor(Reads);
629 
630     auto *DefMA = S->getValueDef(SAI);
631     assert(DefMA);
632 
633     // { DomainDef[] }
634     auto Writes = getDomainFor(DefMA);
635 
636     // { DomainDef[] -> Scatter[] }
637     auto WriteScatter = getScatterFor(Writes);
638 
639     // { Scatter[] -> DomainDef[] }
640     auto ReachDef = getScalarReachingDefinition(DefMA->getStatement());
641 
642     // { [DomainDef[] -> Scatter[]] -> DomainUse[] }
643     auto Uses = give(
644         isl_union_map_apply_range(isl_union_map_from_map(isl_map_range_map(
645                                       isl_map_reverse(ReachDef.take()))),
646                                   isl_union_map_reverse(ReadSchedule.take())));
647 
648     // { DomainDef[] -> Scatter[] }
649     auto UseScatter =
650         singleton(give(isl_union_set_unwrap(isl_union_map_domain(Uses.copy()))),
651                   give(isl_space_map_from_domain_and_range(
652                       isl_set_get_space(Writes.keep()), ScatterSpace.copy())));
653 
654     // { DomainDef[] -> Zone[] }
655     auto Lifetime = betweenScatter(WriteScatter, UseScatter, false, true);
656 
657     // { DomainDef[] -> DomainRead[] }
658     auto DefUses = give(isl_union_map_domain_factor_domain(Uses.take()));
659 
660     return std::make_pair(DefUses, Lifetime);
661   }
662 
663   /// Try to map a MemoryKind::Value to a given array element.
664   ///
665   /// @param SAI       Representation of the scalar's memory to map.
666   /// @param TargetElt { Scatter[] -> Element[] }
667   ///                  Suggestion where to map a scalar to when at a timepoint.
668   ///
669   /// @return true if the scalar was successfully mapped.
670   bool tryMapValue(const ScopArrayInfo *SAI, isl::map TargetElt) {
671     assert(SAI->isValueKind());
672 
673     auto *DefMA = S->getValueDef(SAI);
674     assert(DefMA->isValueKind());
675     assert(DefMA->isMustWrite());
676     auto *V = DefMA->getAccessValue();
677     auto *DefInst = DefMA->getAccessInstruction();
678 
679     // Stop if the scalar has already been mapped.
680     if (!DefMA->getLatestScopArrayInfo()->isValueKind())
681       return false;
682 
683     // { DomainDef[] -> Scatter[] }
684     auto DefSched = getScatterFor(DefMA);
685 
686     // Where each write is mapped to, according to the suggestion.
687     // { DomainDef[] -> Element[] }
688     auto DefTarget = give(isl_map_apply_domain(
689         TargetElt.copy(), isl_map_reverse(DefSched.copy())));
690     simplify(DefTarget);
691     DEBUG(dbgs() << "    Def Mapping: " << DefTarget << '\n');
692 
693     auto OrigDomain = getDomainFor(DefMA);
694     auto MappedDomain = give(isl_map_domain(DefTarget.copy()));
695     if (!isl_set_is_subset(OrigDomain.keep(), MappedDomain.keep())) {
696       DEBUG(dbgs()
697             << "    Reject because mapping does not encompass all instances\n");
698       return false;
699     }
700 
701     // { DomainDef[] -> Zone[] }
702     isl::map Lifetime;
703 
704     // { DomainDef[] -> DomainUse[] }
705     isl::union_map DefUses;
706 
707     std::tie(DefUses, Lifetime) = computeValueUses(SAI);
708     DEBUG(dbgs() << "    Lifetime: " << Lifetime << '\n');
709 
710     /// { [Element[] -> Zone[]] }
711     auto EltZone = give(
712         isl_map_wrap(isl_map_apply_domain(Lifetime.copy(), DefTarget.copy())));
713     simplify(EltZone);
714 
715     // When known knowledge is disabled, just return the unknown value. It will
716     // either get filtered out or conflict with itself.
717     // { DomainDef[] -> ValInst[] }
718     isl::map ValInst;
719     if (DelicmComputeKnown)
720       ValInst = makeValInst(V, DefMA->getStatement(),
721                             LI->getLoopFor(DefInst->getParent()));
722     else
723       ValInst = makeUnknownForDomain(DefMA->getStatement());
724 
725     // { DomainDef[] -> [Element[] -> Zone[]] }
726     auto EltKnownTranslator =
727         give(isl_map_range_product(DefTarget.copy(), Lifetime.copy()));
728 
729     // { [Element[] -> Zone[]] -> ValInst[] }
730     auto EltKnown =
731         give(isl_map_apply_domain(ValInst.copy(), EltKnownTranslator.take()));
732     simplify(EltKnown);
733 
734     // { DomainDef[] -> [Element[] -> Scatter[]] }
735     auto WrittenTranslator =
736         give(isl_map_range_product(DefTarget.copy(), DefSched.take()));
737 
738     // { [Element[] -> Scatter[]] -> ValInst[] }
739     auto DefEltSched =
740         give(isl_map_apply_domain(ValInst.copy(), WrittenTranslator.take()));
741     simplify(DefEltSched);
742 
743     Knowledge Proposed(EltZone, nullptr, filterKnownValInst(EltKnown),
744                        DefEltSched);
745     if (isConflicting(Proposed))
746       return false;
747 
748     // { DomainUse[] -> Element[] }
749     auto UseTarget = give(
750         isl_union_map_apply_range(isl_union_map_reverse(DefUses.take()),
751                                   isl_union_map_from_map(DefTarget.copy())));
752 
753     mapValue(SAI, std::move(DefTarget), std::move(UseTarget),
754              std::move(Lifetime), std::move(Proposed));
755     return true;
756   }
757 
758   /// After a scalar has been mapped, update the global knowledge.
759   void applyLifetime(Knowledge Proposed) {
760     Zone.learnFrom(std::move(Proposed));
761   }
762 
763   /// Map a MemoryKind::Value scalar to an array element.
764   ///
765   /// Callers must have ensured that the mapping is valid and not conflicting.
766   ///
767   /// @param SAI       The ScopArrayInfo representing the scalar's memory to
768   ///                  map.
769   /// @param DefTarget { DomainDef[] -> Element[] }
770   ///                  The array element to map the scalar to.
771   /// @param UseTarget { DomainUse[] -> Element[] }
772   ///                  The array elements the uses are mapped to.
773   /// @param Lifetime  { DomainDef[] -> Zone[] }
774   ///                  The lifetime of each llvm::Value definition for
775   ///                  reporting.
776   /// @param Proposed  Mapping constraints for reporting.
777   void mapValue(const ScopArrayInfo *SAI, isl::map DefTarget,
778                 isl::union_map UseTarget, isl::map Lifetime,
779                 Knowledge Proposed) {
780     // Redirect the read accesses.
781     for (auto *MA : S->getValueUses(SAI)) {
782       // { DomainUse[] }
783       auto Domain = getDomainFor(MA);
784 
785       // { DomainUse[] -> Element[] }
786       auto NewAccRel = give(isl_union_map_intersect_domain(
787           UseTarget.copy(), isl_union_set_from_set(Domain.take())));
788       simplify(NewAccRel);
789 
790       assert(isl_union_map_n_map(NewAccRel.keep()) == 1);
791       MA->setNewAccessRelation(isl::map::from_union_map(NewAccRel));
792     }
793 
794     auto *WA = S->getValueDef(SAI);
795     WA->setNewAccessRelation(DefTarget);
796     applyLifetime(Proposed);
797 
798     MappedValueScalars++;
799     NumberOfMappedValueScalars += 1;
800   }
801 
802   isl::map makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
803                        bool IsCertain = true) {
804     // When known knowledge is disabled, just return the unknown value. It will
805     // either get filtered out or conflict with itself.
806     if (!DelicmComputeKnown)
807       return makeUnknownForDomain(UserStmt);
808     return ZoneAlgorithm::makeValInst(Val, UserStmt, Scope, IsCertain);
809   }
810 
811   /// Express the incoming values of a PHI for each incoming statement in an
812   /// isl::union_map.
813   ///
814   /// @param SAI The PHI scalar represented by a ScopArrayInfo.
815   ///
816   /// @return { PHIWriteDomain[] -> ValInst[] }
817   isl::union_map determinePHIWrittenValues(const ScopArrayInfo *SAI) {
818     auto Result = makeEmptyUnionMap();
819 
820     // Collect the incoming values.
821     for (auto *MA : S->getPHIIncomings(SAI)) {
822       // { DomainWrite[] -> ValInst[] }
823       isl::union_map ValInst;
824       auto *WriteStmt = MA->getStatement();
825 
826       auto Incoming = MA->getIncoming();
827       assert(!Incoming.empty());
828       if (Incoming.size() == 1) {
829         ValInst = makeValInst(Incoming[0].second, WriteStmt,
830                               LI->getLoopFor(Incoming[0].first));
831       } else {
832         // If the PHI is in a subregion's exit node it can have multiple
833         // incoming values (+ maybe another incoming edge from an unrelated
834         // block). We cannot directly represent it as a single llvm::Value.
835         // We currently model it as unknown value, but modeling as the PHIInst
836         // itself could be OK, too.
837         ValInst = makeUnknownForDomain(WriteStmt);
838       }
839 
840       Result = give(isl_union_map_union(Result.take(), ValInst.take()));
841     }
842 
843     assert(isl_union_map_is_single_valued(Result.keep()) == isl_bool_true &&
844            "Cannot have multiple incoming values for same incoming statement");
845     return Result;
846   }
847 
848   /// Try to map a MemoryKind::PHI scalar to a given array element.
849   ///
850   /// @param SAI       Representation of the scalar's memory to map.
851   /// @param TargetElt { Scatter[] -> Element[] }
852   ///                  Suggestion where to map the scalar to when at a
853   ///                  timepoint.
854   ///
855   /// @return true if the PHI scalar has been mapped.
856   bool tryMapPHI(const ScopArrayInfo *SAI, isl::map TargetElt) {
857     auto *PHIRead = S->getPHIRead(SAI);
858     assert(PHIRead->isPHIKind());
859     assert(PHIRead->isRead());
860 
861     // Skip if already been mapped.
862     if (!PHIRead->getLatestScopArrayInfo()->isPHIKind())
863       return false;
864 
865     // { DomainRead[] -> Scatter[] }
866     auto PHISched = getScatterFor(PHIRead);
867 
868     // { DomainRead[] -> Element[] }
869     auto PHITarget =
870         give(isl_map_apply_range(PHISched.copy(), TargetElt.copy()));
871     simplify(PHITarget);
872     DEBUG(dbgs() << "    Mapping: " << PHITarget << '\n');
873 
874     auto OrigDomain = getDomainFor(PHIRead);
875     auto MappedDomain = give(isl_map_domain(PHITarget.copy()));
876     if (!isl_set_is_subset(OrigDomain.keep(), MappedDomain.keep())) {
877       DEBUG(dbgs()
878             << "    Reject because mapping does not encompass all instances\n");
879       return false;
880     }
881 
882     // { DomainRead[] -> DomainWrite[] }
883     auto PerPHIWrites = computePerPHI(SAI);
884 
885     // { DomainWrite[] -> Element[] }
886     auto WritesTarget = give(isl_union_map_reverse(isl_union_map_apply_domain(
887         PerPHIWrites.copy(), isl_union_map_from_map(PHITarget.copy()))));
888     simplify(WritesTarget);
889 
890     // { DomainWrite[] }
891     auto UniverseWritesDom = give(isl_union_set_empty(ParamSpace.copy()));
892 
893     for (auto *MA : S->getPHIIncomings(SAI))
894       UniverseWritesDom = give(isl_union_set_add_set(UniverseWritesDom.take(),
895                                                      getDomainFor(MA).take()));
896 
897     auto RelevantWritesTarget = WritesTarget;
898     if (DelicmOverapproximateWrites)
899       WritesTarget = expandMapping(WritesTarget, UniverseWritesDom);
900 
901     auto ExpandedWritesDom = give(isl_union_map_domain(WritesTarget.copy()));
902     if (!DelicmPartialWrites &&
903         !isl_union_set_is_subset(UniverseWritesDom.keep(),
904                                  ExpandedWritesDom.keep())) {
905       DEBUG(dbgs() << "    Reject because did not find PHI write mapping for "
906                       "all instances\n");
907       if (DelicmOverapproximateWrites)
908         DEBUG(dbgs() << "      Relevant Mapping:    " << RelevantWritesTarget
909                      << '\n');
910       DEBUG(dbgs() << "      Deduced Mapping:     " << WritesTarget << '\n');
911       DEBUG(dbgs() << "      Missing instances:    "
912                    << give(isl_union_set_subtract(UniverseWritesDom.copy(),
913                                                   ExpandedWritesDom.copy()))
914                    << '\n');
915       return false;
916     }
917 
918     //  { DomainRead[] -> Scatter[] }
919     auto PerPHIWriteScatter = give(isl_map_from_union_map(
920         isl_union_map_apply_range(PerPHIWrites.copy(), Schedule.copy())));
921 
922     // { DomainRead[] -> Zone[] }
923     auto Lifetime = betweenScatter(PerPHIWriteScatter, PHISched, false, true);
924     simplify(Lifetime);
925     DEBUG(dbgs() << "    Lifetime: " << Lifetime << "\n");
926 
927     // { DomainWrite[] -> Zone[] }
928     auto WriteLifetime = give(isl_union_map_apply_domain(
929         isl_union_map_from_map(Lifetime.copy()), PerPHIWrites.copy()));
930 
931     // { DomainWrite[] -> ValInst[] }
932     auto WrittenValue = determinePHIWrittenValues(SAI);
933 
934     // { DomainWrite[] -> [Element[] -> Scatter[]] }
935     auto WrittenTranslator =
936         give(isl_union_map_range_product(WritesTarget.copy(), Schedule.copy()));
937 
938     // { [Element[] -> Scatter[]] -> ValInst[] }
939     auto Written = give(isl_union_map_apply_domain(WrittenValue.copy(),
940                                                    WrittenTranslator.copy()));
941     simplify(Written);
942 
943     // { DomainWrite[] -> [Element[] -> Zone[]] }
944     auto LifetimeTranslator = give(
945         isl_union_map_range_product(WritesTarget.copy(), WriteLifetime.copy()));
946 
947     // { DomainWrite[] -> ValInst[] }
948     auto WrittenKnownValue = filterKnownValInst(WrittenValue);
949 
950     // { [Element[] -> Zone[]] -> ValInst[] }
951     auto EltLifetimeInst = give(isl_union_map_apply_domain(
952         WrittenKnownValue.copy(), LifetimeTranslator.copy()));
953     simplify(EltLifetimeInst);
954 
955     // { [Element[] -> Zone[] }
956     auto Occupied = give(isl_union_map_range(LifetimeTranslator.copy()));
957     simplify(Occupied);
958 
959     Knowledge Proposed(Occupied, nullptr, EltLifetimeInst, Written);
960     if (isConflicting(Proposed))
961       return false;
962 
963     mapPHI(SAI, std::move(PHITarget), std::move(WritesTarget),
964            std::move(Lifetime), std::move(Proposed));
965     return true;
966   }
967 
968   /// Map a MemoryKind::PHI scalar to an array element.
969   ///
970   /// Callers must have ensured that the mapping is valid and not conflicting
971   /// with the common knowledge.
972   ///
973   /// @param SAI         The ScopArrayInfo representing the scalar's memory to
974   ///                    map.
975   /// @param ReadTarget  { DomainRead[] -> Element[] }
976   ///                    The array element to map the scalar to.
977   /// @param WriteTarget { DomainWrite[] -> Element[] }
978   ///                    New access target for each PHI incoming write.
979   /// @param Lifetime    { DomainRead[] -> Zone[] }
980   ///                    The lifetime of each PHI for reporting.
981   /// @param Proposed    Mapping constraints for reporting.
982   void mapPHI(const ScopArrayInfo *SAI, isl::map ReadTarget,
983               isl::union_map WriteTarget, isl::map Lifetime,
984               Knowledge Proposed) {
985     // { Element[] }
986     isl::space ElementSpace = ReadTarget.get_space().range();
987 
988     // Redirect the PHI incoming writes.
989     for (auto *MA : S->getPHIIncomings(SAI)) {
990       // { DomainWrite[] }
991       auto Domain = getDomainFor(MA);
992 
993       // { DomainWrite[] -> Element[] }
994       auto NewAccRel = give(isl_union_map_intersect_domain(
995           WriteTarget.copy(), isl_union_set_from_set(Domain.copy())));
996       simplify(NewAccRel);
997 
998       isl::space NewAccRelSpace =
999           Domain.get_space().map_from_domain_and_range(ElementSpace);
1000       isl::map NewAccRelMap = singleton(NewAccRel, NewAccRelSpace);
1001       MA->setNewAccessRelation(NewAccRelMap);
1002     }
1003 
1004     // Redirect the PHI read.
1005     auto *PHIRead = S->getPHIRead(SAI);
1006     PHIRead->setNewAccessRelation(ReadTarget);
1007     applyLifetime(Proposed);
1008 
1009     MappedPHIScalars++;
1010     NumberOfMappedPHIScalars++;
1011   }
1012 
1013   /// Search and map scalars to memory overwritten by @p TargetStoreMA.
1014   ///
1015   /// Start trying to map scalars that are used in the same statement as the
1016   /// store. For every successful mapping, try to also map scalars of the
1017   /// statements where those are written. Repeat, until no more mapping
1018   /// opportunity is found.
1019   ///
1020   /// There is currently no preference in which order scalars are tried.
1021   /// Ideally, we would direct it towards a load instruction of the same array
1022   /// element.
1023   bool collapseScalarsToStore(MemoryAccess *TargetStoreMA) {
1024     assert(TargetStoreMA->isLatestArrayKind());
1025     assert(TargetStoreMA->isMustWrite());
1026 
1027     auto TargetStmt = TargetStoreMA->getStatement();
1028 
1029     // { DomTarget[] }
1030     auto TargetDom = getDomainFor(TargetStmt);
1031 
1032     // { DomTarget[] -> Element[] }
1033     auto TargetAccRel = getAccessRelationFor(TargetStoreMA);
1034 
1035     // { Zone[] -> DomTarget[] }
1036     // For each point in time, find the next target store instance.
1037     auto Target =
1038         computeScalarReachingOverwrite(Schedule, TargetDom, false, true);
1039 
1040     // { Zone[] -> Element[] }
1041     // Use the target store's write location as a suggestion to map scalars to.
1042     auto EltTarget =
1043         give(isl_map_apply_range(Target.take(), TargetAccRel.take()));
1044     simplify(EltTarget);
1045     DEBUG(dbgs() << "    Target mapping is " << EltTarget << '\n');
1046 
1047     // Stack of elements not yet processed.
1048     SmallVector<MemoryAccess *, 16> Worklist;
1049 
1050     // Set of scalars already tested.
1051     SmallPtrSet<const ScopArrayInfo *, 16> Closed;
1052 
1053     // Lambda to add all scalar reads to the work list.
1054     auto ProcessAllIncoming = [&](ScopStmt *Stmt) {
1055       for (auto *MA : *Stmt) {
1056         if (!MA->isLatestScalarKind())
1057           continue;
1058         if (!MA->isRead())
1059           continue;
1060 
1061         Worklist.push_back(MA);
1062       }
1063     };
1064 
1065     auto *WrittenVal = TargetStoreMA->getAccessInstruction()->getOperand(0);
1066     if (auto *WrittenValInputMA = TargetStmt->lookupInputAccessOf(WrittenVal))
1067       Worklist.push_back(WrittenValInputMA);
1068     else
1069       ProcessAllIncoming(TargetStmt);
1070 
1071     auto AnyMapped = false;
1072     auto &DL = S->getRegion().getEntry()->getModule()->getDataLayout();
1073     auto StoreSize =
1074         DL.getTypeAllocSize(TargetStoreMA->getAccessValue()->getType());
1075 
1076     while (!Worklist.empty()) {
1077       auto *MA = Worklist.pop_back_val();
1078 
1079       auto *SAI = MA->getScopArrayInfo();
1080       if (Closed.count(SAI))
1081         continue;
1082       Closed.insert(SAI);
1083       DEBUG(dbgs() << "\n    Trying to map " << MA << " (SAI: " << SAI
1084                    << ")\n");
1085 
1086       // Skip non-mappable scalars.
1087       if (!isMappable(SAI))
1088         continue;
1089 
1090       auto MASize = DL.getTypeAllocSize(MA->getAccessValue()->getType());
1091       if (MASize > StoreSize) {
1092         DEBUG(dbgs() << "    Reject because storage size is insufficient\n");
1093         continue;
1094       }
1095 
1096       // Try to map MemoryKind::Value scalars.
1097       if (SAI->isValueKind()) {
1098         if (!tryMapValue(SAI, EltTarget))
1099           continue;
1100 
1101         auto *DefAcc = S->getValueDef(SAI);
1102         ProcessAllIncoming(DefAcc->getStatement());
1103 
1104         AnyMapped = true;
1105         continue;
1106       }
1107 
1108       // Try to map MemoryKind::PHI scalars.
1109       if (SAI->isPHIKind()) {
1110         if (!tryMapPHI(SAI, EltTarget))
1111           continue;
1112         // Add inputs of all incoming statements to the worklist. Prefer the
1113         // input accesses of the incoming blocks.
1114         for (auto *PHIWrite : S->getPHIIncomings(SAI)) {
1115           auto *PHIWriteStmt = PHIWrite->getStatement();
1116           bool FoundAny = false;
1117           for (auto Incoming : PHIWrite->getIncoming()) {
1118             auto *IncomingInputMA =
1119                 PHIWriteStmt->lookupInputAccessOf(Incoming.second);
1120             if (!IncomingInputMA)
1121               continue;
1122 
1123             Worklist.push_back(IncomingInputMA);
1124             FoundAny = true;
1125           }
1126 
1127           if (!FoundAny)
1128             ProcessAllIncoming(PHIWrite->getStatement());
1129         }
1130 
1131         AnyMapped = true;
1132         continue;
1133       }
1134     }
1135 
1136     if (AnyMapped) {
1137       TargetsMapped++;
1138       NumberOfTargetsMapped++;
1139     }
1140     return AnyMapped;
1141   }
1142 
1143   /// Compute when an array element is unused.
1144   ///
1145   /// @return { [Element[] -> Zone[]] }
1146   isl::union_set computeLifetime() const {
1147     // { Element[] -> Zone[] }
1148     auto ArrayUnused = computeArrayUnused(Schedule, AllMustWrites, AllReads,
1149                                           false, false, true);
1150 
1151     auto Result = give(isl_union_map_wrap(ArrayUnused.copy()));
1152 
1153     simplify(Result);
1154     return Result;
1155   }
1156 
1157   /// Determine when an array element is written to, and which value instance is
1158   /// written.
1159   ///
1160   /// @return { [Element[] -> Scatter[]] -> ValInst[] }
1161   isl::union_map computeWritten() const {
1162     // { [Element[] -> Scatter[]] -> ValInst[] }
1163     auto EltWritten = applyDomainRange(AllWriteValInst, Schedule);
1164 
1165     simplify(EltWritten);
1166     return EltWritten;
1167   }
1168 
1169   /// Determine whether an access touches at most one element.
1170   ///
1171   /// The accessed element could be a scalar or accessing an array with constant
1172   /// subscript, such that all instances access only that element.
1173   ///
1174   /// @param MA The access to test.
1175   ///
1176   /// @return True, if zero or one elements are accessed; False if at least two
1177   ///         different elements are accessed.
1178   bool isScalarAccess(MemoryAccess *MA) {
1179     auto Map = getAccessRelationFor(MA);
1180     auto Set = give(isl_map_range(Map.take()));
1181     return isl_set_is_singleton(Set.keep()) == isl_bool_true;
1182   }
1183 
1184   /// Print mapping statistics to @p OS.
1185   void printStatistics(llvm::raw_ostream &OS, int Indent = 0) const {
1186     OS.indent(Indent) << "Statistics {\n";
1187     OS.indent(Indent + 4) << "Compatible overwrites: "
1188                           << NumberOfCompatibleTargets << "\n";
1189     OS.indent(Indent + 4) << "Overwrites mapped to:  " << NumberOfTargetsMapped
1190                           << '\n';
1191     OS.indent(Indent + 4) << "Value scalars mapped:  "
1192                           << NumberOfMappedValueScalars << '\n';
1193     OS.indent(Indent + 4) << "PHI scalars mapped:    "
1194                           << NumberOfMappedPHIScalars << '\n';
1195     OS.indent(Indent) << "}\n";
1196   }
1197 
1198   /// Return whether at least one transformation been applied.
1199   bool isModified() const { return NumberOfTargetsMapped > 0; }
1200 
1201 public:
1202   DeLICMImpl(Scop *S, LoopInfo *LI) : ZoneAlgorithm("polly-delicm", S, LI) {}
1203 
1204   /// Calculate the lifetime (definition to last use) of every array element.
1205   ///
1206   /// @return True if the computed lifetimes (#Zone) is usable.
1207   bool computeZone() {
1208     // Check that nothing strange occurs.
1209     collectCompatibleElts();
1210 
1211     isl::union_set EltUnused;
1212     isl::union_map EltKnown, EltWritten;
1213 
1214     {
1215       IslMaxOperationsGuard MaxOpGuard(IslCtx.get(), DelicmMaxOps);
1216 
1217       computeCommon();
1218 
1219       EltUnused = computeLifetime();
1220       EltKnown = computeKnown(true, false);
1221       EltWritten = computeWritten();
1222     }
1223     DeLICMAnalyzed++;
1224 
1225     if (!EltUnused || !EltKnown || !EltWritten) {
1226       assert(isl_ctx_last_error(IslCtx.get()) == isl_error_quota &&
1227              "The only reason that these things have not been computed should "
1228              "be if the max-operations limit hit");
1229       DeLICMOutOfQuota++;
1230       DEBUG(dbgs() << "DeLICM analysis exceeded max_operations\n");
1231       DebugLoc Begin, End;
1232       getDebugLocations(getBBPairForRegion(&S->getRegion()), Begin, End);
1233       OptimizationRemarkAnalysis R(DEBUG_TYPE, "OutOfQuota", Begin,
1234                                    S->getEntry());
1235       R << "maximal number of operations exceeded during zone analysis";
1236       S->getFunction().getContext().diagnose(R);
1237       return false;
1238     }
1239 
1240     Zone = OriginalZone = Knowledge(nullptr, EltUnused, EltKnown, EltWritten);
1241     DEBUG(dbgs() << "Computed Zone:\n"; OriginalZone.print(dbgs(), 4));
1242 
1243     assert(Zone.isUsable() && OriginalZone.isUsable());
1244     return true;
1245   }
1246 
1247   /// Try to map as many scalars to unused array elements as possible.
1248   ///
1249   /// Multiple scalars might be mappable to intersecting unused array element
1250   /// zones, but we can only chose one. This is a greedy algorithm, therefore
1251   /// the first processed element claims it.
1252   void greedyCollapse() {
1253     bool Modified = false;
1254 
1255     for (auto &Stmt : *S) {
1256       for (auto *MA : Stmt) {
1257         if (!MA->isLatestArrayKind())
1258           continue;
1259         if (!MA->isWrite())
1260           continue;
1261 
1262         if (MA->isMayWrite()) {
1263           DEBUG(dbgs() << "Access " << MA
1264                        << " pruned because it is a MAY_WRITE\n");
1265           OptimizationRemarkMissed R(DEBUG_TYPE, "TargetMayWrite",
1266                                      MA->getAccessInstruction());
1267           R << "Skipped possible mapping target because it is not an "
1268                "unconditional overwrite";
1269           S->getFunction().getContext().diagnose(R);
1270           continue;
1271         }
1272 
1273         if (Stmt.getNumIterators() == 0) {
1274           DEBUG(dbgs() << "Access " << MA
1275                        << " pruned because it is not in a loop\n");
1276           OptimizationRemarkMissed R(DEBUG_TYPE, "WriteNotInLoop",
1277                                      MA->getAccessInstruction());
1278           R << "skipped possible mapping target because it is not in a loop";
1279           S->getFunction().getContext().diagnose(R);
1280           continue;
1281         }
1282 
1283         if (isScalarAccess(MA)) {
1284           DEBUG(dbgs() << "Access " << MA
1285                        << " pruned because it writes only a single element\n");
1286           OptimizationRemarkMissed R(DEBUG_TYPE, "ScalarWrite",
1287                                      MA->getAccessInstruction());
1288           R << "skipped possible mapping target because the memory location "
1289                "written to does not depend on its outer loop";
1290           S->getFunction().getContext().diagnose(R);
1291           continue;
1292         }
1293 
1294         if (!isa<StoreInst>(MA->getAccessInstruction())) {
1295           DEBUG(dbgs() << "Access " << MA
1296                        << " pruned because it is not a StoreInst\n");
1297           OptimizationRemarkMissed R(DEBUG_TYPE, "NotAStore",
1298                                      MA->getAccessInstruction());
1299           R << "skipped possible mapping target because non-store instructions "
1300                "are not supported";
1301           S->getFunction().getContext().diagnose(R);
1302           continue;
1303         }
1304 
1305         // Check for more than one element acces per statement instance.
1306         // Currently we expect write accesses to be functional, eg. disallow
1307         //
1308         //   { Stmt[0] -> [i] : 0 <= i < 2 }
1309         //
1310         // This may occur when some accesses to the element write/read only
1311         // parts of the element, eg. a single byte. Polly then divides each
1312         // element into subelements of the smallest access length, normal access
1313         // then touch multiple of such subelements. It is very common when the
1314         // array is accesses with memset, memcpy or memmove which take i8*
1315         // arguments.
1316         isl::union_map AccRel = MA->getLatestAccessRelation();
1317         if (!AccRel.is_single_valued().is_true()) {
1318           DEBUG(dbgs() << "Access " << MA
1319                        << " is incompatible because it writes multiple "
1320                           "elements per instance\n");
1321           OptimizationRemarkMissed R(DEBUG_TYPE, "NonFunctionalAccRel",
1322                                      MA->getAccessInstruction());
1323           R << "skipped possible mapping target because it writes more than "
1324                "one element";
1325           S->getFunction().getContext().diagnose(R);
1326           continue;
1327         }
1328 
1329         isl::union_set TouchedElts = AccRel.range();
1330         if (!TouchedElts.is_subset(CompatibleElts)) {
1331           DEBUG(
1332               dbgs()
1333               << "Access " << MA
1334               << " is incompatible because it touches incompatible elements\n");
1335           OptimizationRemarkMissed R(DEBUG_TYPE, "IncompatibleElts",
1336                                      MA->getAccessInstruction());
1337           R << "skipped possible mapping target because a target location "
1338                "cannot be reliably analyzed";
1339           S->getFunction().getContext().diagnose(R);
1340           continue;
1341         }
1342 
1343         assert(isCompatibleAccess(MA));
1344         NumberOfCompatibleTargets++;
1345         DEBUG(dbgs() << "Analyzing target access " << MA << "\n");
1346         if (collapseScalarsToStore(MA))
1347           Modified = true;
1348       }
1349     }
1350 
1351     if (Modified)
1352       DeLICMScopsModified++;
1353   }
1354 
1355   /// Dump the internal information about a performed DeLICM to @p OS.
1356   void print(llvm::raw_ostream &OS, int Indent = 0) {
1357     if (!Zone.isUsable()) {
1358       OS.indent(Indent) << "Zone not computed\n";
1359       return;
1360     }
1361 
1362     printStatistics(OS, Indent);
1363     if (!isModified()) {
1364       OS.indent(Indent) << "No modification has been made\n";
1365       return;
1366     }
1367     printAccesses(OS, Indent);
1368   }
1369 };
1370 
1371 class DeLICM : public ScopPass {
1372 private:
1373   DeLICM(const DeLICM &) = delete;
1374   const DeLICM &operator=(const DeLICM &) = delete;
1375 
1376   /// The pass implementation, also holding per-scop data.
1377   std::unique_ptr<DeLICMImpl> Impl;
1378 
1379   void collapseToUnused(Scop &S) {
1380     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1381     Impl = make_unique<DeLICMImpl>(&S, &LI);
1382 
1383     if (!Impl->computeZone()) {
1384       DEBUG(dbgs() << "Abort because cannot reliably compute lifetimes\n");
1385       return;
1386     }
1387 
1388     DEBUG(dbgs() << "Collapsing scalars to unused array elements...\n");
1389     Impl->greedyCollapse();
1390 
1391     DEBUG(dbgs() << "\nFinal Scop:\n");
1392     DEBUG(dbgs() << S);
1393   }
1394 
1395 public:
1396   static char ID;
1397   explicit DeLICM() : ScopPass(ID) {}
1398 
1399   virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
1400     AU.addRequiredTransitive<ScopInfoRegionPass>();
1401     AU.addRequired<LoopInfoWrapperPass>();
1402     AU.setPreservesAll();
1403   }
1404 
1405   virtual bool runOnScop(Scop &S) override {
1406     // Free resources for previous scop's computation, if not yet done.
1407     releaseMemory();
1408 
1409     collapseToUnused(S);
1410 
1411     auto ScopStats = S.getStatistics();
1412     NumValueWrites += ScopStats.NumValueWrites;
1413     NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
1414     NumPHIWrites += ScopStats.NumPHIWrites;
1415     NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
1416     NumSingletonWrites += ScopStats.NumSingletonWrites;
1417     NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
1418 
1419     return false;
1420   }
1421 
1422   virtual void printScop(raw_ostream &OS, Scop &S) const override {
1423     if (!Impl)
1424       return;
1425     assert(Impl->getScop() == &S);
1426 
1427     OS << "DeLICM result:\n";
1428     Impl->print(OS);
1429   }
1430 
1431   virtual void releaseMemory() override { Impl.reset(); }
1432 };
1433 
1434 char DeLICM::ID;
1435 } // anonymous namespace
1436 
1437 Pass *polly::createDeLICMPass() { return new DeLICM(); }
1438 
1439 INITIALIZE_PASS_BEGIN(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false,
1440                       false)
1441 INITIALIZE_PASS_DEPENDENCY(ScopInfoWrapperPass)
1442 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1443 INITIALIZE_PASS_END(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false,
1444                     false)
1445 
1446 bool polly::isConflicting(
1447     isl::union_set ExistingOccupied, isl::union_set ExistingUnused,
1448     isl::union_map ExistingKnown, isl::union_map ExistingWrites,
1449     isl::union_set ProposedOccupied, isl::union_set ProposedUnused,
1450     isl::union_map ProposedKnown, isl::union_map ProposedWrites,
1451     llvm::raw_ostream *OS, unsigned Indent) {
1452   Knowledge Existing(std::move(ExistingOccupied), std::move(ExistingUnused),
1453                      std::move(ExistingKnown), std::move(ExistingWrites));
1454   Knowledge Proposed(std::move(ProposedOccupied), std::move(ProposedUnused),
1455                      std::move(ProposedKnown), std::move(ProposedWrites));
1456 
1457   return Knowledge::isConflicting(Existing, Proposed, OS, Indent);
1458 }
1459