1 //===- MaximalStaticExpansion.cpp -----------------------------------------===//
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 // This pass fully expand the memory accesses of a Scop to get rid of
11 // dependencies.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/DependenceInfo.h"
16 #include "polly/LinkAllPasses.h"
17 #include "polly/ScopInfo.h"
18 #include "polly/ScopPass.h"
19 #include "polly/Support/GICHelper.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/Pass.h"
24 #include "isl/isl-noexceptions.h"
25 #include "isl/union_map.h"
26 #include <cassert>
27 #include <limits>
28 #include <string>
29 #include <vector>
30 
31 using namespace llvm;
32 using namespace polly;
33 
34 #define DEBUG_TYPE "polly-mse"
35 
36 namespace {
37 
38 class MaximalStaticExpander : public ScopPass {
39 public:
40   static char ID;
41 
42   explicit MaximalStaticExpander() : ScopPass(ID) {}
43 
44   ~MaximalStaticExpander() override = default;
45 
46   /// Expand the accesses of the SCoP.
47   ///
48   /// @param S The SCoP that must be expanded.
49   bool runOnScop(Scop &S) override;
50 
51   /// Print the SCoP.
52   ///
53   /// @param OS The stream where to print.
54   /// @param S The SCop that must be printed.
55   void printScop(raw_ostream &OS, Scop &S) const override;
56 
57   /// Register all analyses and transformations required.
58   void getAnalysisUsage(AnalysisUsage &AU) const override;
59 
60 private:
61   /// OptimizationRemarkEmitter object for displaying diagnostic remarks.
62   OptimizationRemarkEmitter *ORE;
63 
64   /// Emit remark
65   void emitRemark(StringRef Msg, Instruction *Inst);
66 
67   /// Return true if the SAI in parameter is expandable.
68   ///
69   /// @param SAI the SAI that need to be checked.
70   /// @param Writes A set that will contains all the write accesses.
71   /// @param Reads A set that will contains all the read accesses.
72   /// @param S The SCop in which the SAI is in.
73   /// @param Dependences The RAW dependences of the SCop.
74   bool isExpandable(const ScopArrayInfo *SAI,
75                     SmallPtrSetImpl<MemoryAccess *> &Writes,
76                     SmallPtrSetImpl<MemoryAccess *> &Reads, Scop &S,
77                     const isl::union_map &Dependences);
78 
79   /// Expand the MemoryAccess according to its domain.
80   ///
81   /// @param S The SCop in which the memory access appears in.
82   /// @param MA The memory access that need to be expanded.
83   ScopArrayInfo *expandAccess(Scop &S, MemoryAccess *MA);
84 
85   /// Filter the dependences to have only one related to current memory access.
86   ///
87   /// @param S The SCop in which the memory access appears in.
88   /// @param MapDependences The dependences to filter.
89   /// @param MA The memory access that need to be expanded.
90   isl::union_map filterDependences(Scop &S,
91                                    const isl::union_map &MapDependences,
92                                    MemoryAccess *MA);
93 
94   /// Expand the MemoryAccess according to Dependences and already expanded
95   /// MemoryAccesses.
96   ///
97   /// @param The SCop in which the memory access appears in.
98   /// @param The memory access that need to be expanded.
99   /// @param Dependences The RAW dependences of the SCop.
100   /// @param ExpandedSAI The expanded SAI created during write expansion.
101   /// @param Reverse if true, the Dependences union_map is reversed before
102   /// intersection.
103   void mapAccess(Scop &S, SmallPtrSetImpl<MemoryAccess *> &Accesses,
104                  const isl::union_map &Dependences, ScopArrayInfo *ExpandedSAI,
105                  bool Reverse);
106 
107   /// Expand PHI memory accesses.
108   ///
109   /// @param The SCop in which the memory access appears in.
110   /// @param The ScopArrayInfo representing the PHI accesses to expand.
111   /// @param Dependences The RAW dependences of the SCop.
112   void expandPhi(Scop &S, const ScopArrayInfo *SAI,
113                  const isl::union_map &Dependences);
114 };
115 
116 } // namespace
117 
118 #ifndef NDEBUG
119 /// Whether a dimension of a set is bounded (lower and upper) by a constant,
120 /// i.e. there are two constants Min and Max, such that every value x of the
121 /// chosen dimensions is Min <= x <= Max.
122 static bool isDimBoundedByConstant(isl::set Set, unsigned dim) {
123   auto ParamDims = Set.dim(isl::dim::param);
124   Set = Set.project_out(isl::dim::param, 0, ParamDims);
125   Set = Set.project_out(isl::dim::set, 0, dim);
126   auto SetDims = Set.dim(isl::dim::set);
127   Set = Set.project_out(isl::dim::set, 1, SetDims - 1);
128   return bool(Set.is_bounded());
129 }
130 #endif
131 
132 /// If @p PwAff maps to a constant, return said constant. If @p Max/@p Min, it
133 /// can also be a piecewise constant and it would return the minimum/maximum
134 /// value. Otherwise, return NaN.
135 static isl::val getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
136   assert(!Max || !Min);
137   isl::val Result;
138   PwAff.foreach_piece([=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
139     if (Result && Result.is_nan())
140       return isl::stat::ok;
141 
142     // TODO: If Min/Max, we can also determine a minimum/maximum value if
143     // Set is constant-bounded.
144     if (!Aff.is_cst()) {
145       Result = isl::val::nan(Aff.get_ctx());
146       return isl::stat::error;
147     }
148 
149     auto ThisVal = Aff.get_constant_val();
150     if (!Result) {
151       Result = ThisVal;
152       return isl::stat::ok;
153     }
154 
155     if (Result.eq(ThisVal))
156       return isl::stat::ok;
157 
158     if (Max && ThisVal.gt(Result)) {
159       Result = ThisVal;
160       return isl::stat::ok;
161     }
162 
163     if (Min && ThisVal.lt(Result)) {
164       Result = ThisVal;
165       return isl::stat::ok;
166     }
167 
168     // Not compatible
169     Result = isl::val::nan(Aff.get_ctx());
170     return isl::stat::error;
171   });
172   return Result;
173 }
174 
175 char MaximalStaticExpander::ID = 0;
176 
177 isl::union_map MaximalStaticExpander::filterDependences(
178     Scop &S, const isl::union_map &Dependences, MemoryAccess *MA) {
179   auto SAI = MA->getLatestScopArrayInfo();
180 
181   auto AccessDomainSet = MA->getAccessRelation().domain();
182   auto AccessDomainId = AccessDomainSet.get_tuple_id();
183 
184   isl::union_map MapDependences = isl::union_map::empty(S.getParamSpace());
185 
186   Dependences.foreach_map([&MapDependences, &AccessDomainId,
187                            &SAI](isl::map Map) -> isl::stat {
188     // Filter out Statement to Statement dependences.
189     if (!Map.can_curry())
190       return isl::stat::ok;
191 
192     // Intersect with the relevant SAI.
193     auto TmpMapDomainId =
194         Map.get_space().domain().unwrap().range().get_tuple_id(isl::dim::set);
195 
196     ScopArrayInfo *UserSAI =
197         static_cast<ScopArrayInfo *>(TmpMapDomainId.get_user());
198 
199     if (SAI != UserSAI)
200       return isl::stat::ok;
201 
202     // Get the correct S1[] -> S2[] dependence.
203     auto NewMap = Map.factor_domain();
204     auto NewMapDomainId = NewMap.domain().get_tuple_id();
205 
206     if (AccessDomainId.keep() != NewMapDomainId.keep())
207       return isl::stat::ok;
208 
209     // Add the corresponding map to MapDependences.
210     MapDependences = MapDependences.add_map(NewMap);
211 
212     return isl::stat::ok;
213   });
214 
215   return MapDependences;
216 }
217 
218 bool MaximalStaticExpander::isExpandable(
219     const ScopArrayInfo *SAI, SmallPtrSetImpl<MemoryAccess *> &Writes,
220     SmallPtrSetImpl<MemoryAccess *> &Reads, Scop &S,
221     const isl::union_map &Dependences) {
222   if (SAI->isValueKind()) {
223     Writes.insert(S.getValueDef(SAI));
224     for (auto MA : S.getValueUses(SAI))
225       Reads.insert(MA);
226     return true;
227   } else if (SAI->isPHIKind()) {
228     auto Read = S.getPHIRead(SAI);
229 
230     auto StmtDomain = isl::union_set(Read->getStatement()->getDomain());
231 
232     auto Writes = S.getPHIIncomings(SAI);
233 
234     // Get the domain where all the writes are writing to.
235     auto WriteDomain = isl::union_set::empty(S.getParamSpace());
236 
237     for (auto Write : Writes) {
238       auto MapDeps = filterDependences(S, Dependences, Write);
239       MapDeps.foreach_map([&WriteDomain](isl::map Map) -> isl::stat {
240         WriteDomain = WriteDomain.add_set(Map.range());
241         return isl::stat::ok;
242       });
243     }
244 
245     // For now, read from original scalar is not possible.
246     if (!StmtDomain.is_equal(WriteDomain)) {
247       emitRemark(SAI->getName() + " read from its original value.",
248                  Read->getAccessInstruction());
249       return false;
250     }
251 
252     return true;
253   } else if (SAI->isExitPHIKind()) {
254     // For now, we are not able to expand ExitPhi.
255     emitRemark(SAI->getName() + " is a ExitPhi node.",
256                S.getEnteringBlock()->getFirstNonPHI());
257     return false;
258   }
259 
260   int NumberWrites = 0;
261   for (ScopStmt &Stmt : S) {
262     auto StmtReads = isl::union_map::empty(S.getParamSpace());
263     auto StmtWrites = isl::union_map::empty(S.getParamSpace());
264 
265     for (MemoryAccess *MA : Stmt) {
266       // Check if the current MemoryAccess involved the current SAI.
267       if (SAI != MA->getLatestScopArrayInfo())
268         continue;
269 
270       // For now, we are not able to expand array where read come after write
271       // (to the same location) in a same statement.
272       auto AccRel = isl::union_map(MA->getAccessRelation());
273       if (MA->isRead()) {
274         // Reject load after store to same location.
275         if (!StmtWrites.is_disjoint(AccRel)) {
276           emitRemark(SAI->getName() + " has read after write to the same "
277                                       "element in same statement. The "
278                                       "dependences found during analysis may "
279                                       "be wrong because Polly is not able to "
280                                       "handle such case for now.",
281                      MA->getAccessInstruction());
282           return false;
283         }
284 
285         StmtReads = give(isl_union_map_union(StmtReads.take(), AccRel.take()));
286       } else {
287         StmtWrites =
288             give(isl_union_map_union(StmtWrites.take(), AccRel.take()));
289       }
290 
291       // For now, we are not able to expand MayWrite.
292       if (MA->isMayWrite()) {
293         emitRemark(SAI->getName() + " has a maywrite access.",
294                    MA->getAccessInstruction());
295         return false;
296       }
297 
298       // For now, we are not able to expand SAI with more than one write.
299       if (MA->isMustWrite()) {
300         Writes.insert(MA);
301         NumberWrites++;
302         if (NumberWrites > 1) {
303           emitRemark(SAI->getName() + " has more than 1 write access.",
304                      MA->getAccessInstruction());
305           return false;
306         }
307       }
308 
309       // Check if it is possible to expand this read.
310       if (MA->isRead()) {
311         // Get the domain of the current ScopStmt.
312         auto StmtDomain = Stmt.getDomain();
313 
314         // Get the domain of the future Read access.
315         auto ReadDomainSet = MA->getAccessRelation().domain();
316         auto ReadDomain = isl::union_set(ReadDomainSet);
317 
318         // Get the dependences relevant for this MA
319         auto MapDependences = filterDependences(S, Dependences.reverse(), MA);
320         unsigned NumberElementMap = isl_union_map_n_map(MapDependences.get());
321 
322         if (NumberElementMap == 0) {
323           emitRemark("The expansion of " + SAI->getName() +
324                          " would lead to a read from the original array.",
325                      MA->getAccessInstruction());
326           return false;
327         }
328 
329         auto DepsDomain = MapDependences.domain();
330 
331         // If there are multiple maps in the Deps, we cannot handle this case
332         // for now.
333         if (NumberElementMap != 1) {
334           emitRemark(SAI->getName() +
335                          " has too many dependences to be handle for now.",
336                      MA->getAccessInstruction());
337           return false;
338         }
339 
340         auto DepsDomainSet = isl::set(DepsDomain);
341 
342         // For now, read from the original array is not possible.
343         if (!StmtDomain.is_subset(DepsDomainSet)) {
344           emitRemark("The expansion of " + SAI->getName() +
345                          " would lead to a read from the original array.",
346                      MA->getAccessInstruction());
347           return false;
348         }
349 
350         Reads.insert(MA);
351       }
352     }
353   }
354 
355   // No need to expand SAI with no write.
356   if (NumberWrites == 0) {
357     emitRemark(SAI->getName() + " has 0 write access.",
358                S.getEnteringBlock()->getFirstNonPHI());
359     return false;
360   }
361 
362   return true;
363 }
364 
365 void MaximalStaticExpander::mapAccess(Scop &S,
366                                       SmallPtrSetImpl<MemoryAccess *> &Accesses,
367                                       const isl::union_map &Dependences,
368                                       ScopArrayInfo *ExpandedSAI,
369                                       bool Reverse) {
370   for (auto MA : Accesses) {
371     // Get the current AM.
372     auto CurrentAccessMap = MA->getAccessRelation();
373 
374     // Get RAW dependences for the current WA.
375     auto DomainSet = MA->getAccessRelation().domain();
376     auto Domain = isl::union_set(DomainSet);
377 
378     // Get the dependences relevant for this MA.
379     isl::union_map MapDependences =
380         filterDependences(S, Reverse ? Dependences.reverse() : Dependences, MA);
381 
382     // If no dependences, no need to modify anything.
383     if (MapDependences.is_empty())
384       return;
385 
386     assert(isl_union_map_n_map(MapDependences.get()) == 1 &&
387            "There are more than one RAW dependencies in the union map.");
388     auto NewAccessMap = isl::map::from_union_map(MapDependences);
389 
390     auto Id = ExpandedSAI->getBasePtrId();
391 
392     // Replace the out tuple id with the one of the access array.
393     NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, Id);
394 
395     // Set the new access relation.
396     MA->setNewAccessRelation(NewAccessMap);
397   }
398 }
399 
400 ScopArrayInfo *MaximalStaticExpander::expandAccess(Scop &S, MemoryAccess *MA) {
401   // Get the current AM.
402   auto CurrentAccessMap = MA->getAccessRelation();
403 
404   unsigned in_dimensions = CurrentAccessMap.dim(isl::dim::in);
405 
406   // Get domain from the current AM.
407   auto Domain = CurrentAccessMap.domain();
408 
409   // Create a new AM from the domain.
410   auto NewAccessMap = isl::map::from_domain(Domain);
411 
412   // Add dimensions to the new AM according to the current in_dim.
413   NewAccessMap = NewAccessMap.add_dims(isl::dim::out, in_dimensions);
414 
415   // Create the string representing the name of the new SAI.
416   // One new SAI for each statement so that each write go to a different memory
417   // cell.
418   auto CurrentStmtDomain = MA->getStatement()->getDomain();
419   auto CurrentStmtName = CurrentStmtDomain.get_tuple_name();
420   auto CurrentOutId = CurrentAccessMap.get_tuple_id(isl::dim::out);
421   std::string CurrentOutIdString =
422       MA->getScopArrayInfo()->getName() + "_" + CurrentStmtName + "_expanded";
423 
424   // Set the tuple id for the out dimension.
425   NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, CurrentOutId);
426 
427   // Create the size vector.
428   std::vector<unsigned> Sizes;
429   for (unsigned i = 0; i < in_dimensions; i++) {
430     assert(isDimBoundedByConstant(CurrentStmtDomain, i) &&
431            "Domain boundary are not constant.");
432     auto UpperBound = getConstant(CurrentStmtDomain.dim_max(i), true, false);
433     assert(!UpperBound.is_null() && UpperBound.is_pos() &&
434            !UpperBound.is_nan() &&
435            "The upper bound is not a positive integer.");
436     assert(UpperBound.le(isl::val(CurrentAccessMap.get_ctx(),
437                                   std::numeric_limits<int>::max() - 1)) &&
438            "The upper bound overflow a int.");
439     Sizes.push_back(UpperBound.get_num_si() + 1);
440   }
441 
442   // Get the ElementType of the current SAI.
443   auto ElementType = MA->getLatestScopArrayInfo()->getElementType();
444 
445   // Create (or get if already existing) the new expanded SAI.
446   auto ExpandedSAI =
447       S.createScopArrayInfo(ElementType, CurrentOutIdString, Sizes);
448   ExpandedSAI->setIsOnHeap(true);
449 
450   // Get the out Id of the expanded Array.
451   auto NewOutId = ExpandedSAI->getBasePtrId();
452 
453   // Set the out id of the new AM to the new SAI id.
454   NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, NewOutId);
455 
456   // Add constraints to linked output with input id.
457   auto SpaceMap = NewAccessMap.get_space();
458   auto ConstraintBasicMap =
459       isl::basic_map::equal(SpaceMap, SpaceMap.dim(isl::dim::in));
460   NewAccessMap = isl::map(ConstraintBasicMap);
461 
462   // Set the new access relation map.
463   MA->setNewAccessRelation(NewAccessMap);
464 
465   return ExpandedSAI;
466 }
467 
468 void MaximalStaticExpander::expandPhi(Scop &S, const ScopArrayInfo *SAI,
469                                       const isl::union_map &Dependences) {
470   SmallPtrSet<MemoryAccess *, 4> Writes;
471   for (auto MA : S.getPHIIncomings(SAI))
472     Writes.insert(MA);
473   auto Read = S.getPHIRead(SAI);
474   auto ExpandedSAI = expandAccess(S, Read);
475 
476   mapAccess(S, Writes, Dependences, ExpandedSAI, false);
477 }
478 
479 void MaximalStaticExpander::emitRemark(StringRef Msg, Instruction *Inst) {
480   ORE->emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ExpansionRejection", Inst)
481             << Msg);
482 }
483 
484 bool MaximalStaticExpander::runOnScop(Scop &S) {
485   // Get the ORE from OptimizationRemarkEmitterWrapperPass.
486   ORE = &(getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
487 
488   // Get the RAW Dependences.
489   auto &DI = getAnalysis<DependenceInfo>();
490   auto &D = DI.getDependences(Dependences::AL_Reference);
491   auto Dependences = isl::give(D.getDependences(Dependences::TYPE_RAW));
492 
493   SmallVector<ScopArrayInfo *, 4> CurrentSAI(S.arrays().begin(),
494                                              S.arrays().end());
495 
496   for (auto SAI : CurrentSAI) {
497     SmallPtrSet<MemoryAccess *, 4> AllWrites;
498     SmallPtrSet<MemoryAccess *, 4> AllReads;
499     if (!isExpandable(SAI, AllWrites, AllReads, S, Dependences))
500       continue;
501 
502     if (SAI->isValueKind() || SAI->isArrayKind()) {
503       assert(AllWrites.size() == 1 || SAI->isValueKind());
504 
505       auto TheWrite = *(AllWrites.begin());
506       ScopArrayInfo *ExpandedArray = expandAccess(S, TheWrite);
507 
508       mapAccess(S, AllReads, Dependences, ExpandedArray, true);
509     } else if (SAI->isPHIKind()) {
510       expandPhi(S, SAI, Dependences);
511     }
512   }
513 
514   return false;
515 }
516 
517 void MaximalStaticExpander::printScop(raw_ostream &OS, Scop &S) const {
518   S.print(OS, false);
519 }
520 
521 void MaximalStaticExpander::getAnalysisUsage(AnalysisUsage &AU) const {
522   ScopPass::getAnalysisUsage(AU);
523   AU.addRequired<DependenceInfo>();
524   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
525 }
526 
527 Pass *polly::createMaximalStaticExpansionPass() {
528   return new MaximalStaticExpander();
529 }
530 
531 INITIALIZE_PASS_BEGIN(MaximalStaticExpander, "polly-mse",
532                       "Polly - Maximal static expansion of SCoP", false, false);
533 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
534 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
535 INITIALIZE_PASS_END(MaximalStaticExpander, "polly-mse",
536                     "Polly - Maximal static expansion of SCoP", false, false)
537