1 //===- ScopBuilder.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 // Create a polyhedral description for a static control flow region.
11 //
12 // The pass creates a polyhedral description of the Scops detected by the SCoP
13 // detection derived from their LLVM-IR code.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "polly/ScopBuilder.h"
18 #include "polly/Options.h"
19 #include "polly/ScopDetection.h"
20 #include "polly/ScopDetectionDiagnostic.h"
21 #include "polly/ScopInfo.h"
22 #include "polly/Support/SCEVValidator.h"
23 #include "polly/Support/ScopHelper.h"
24 #include "polly/Support/VirtualInstruction.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/EquivalenceClasses.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
34 #include "llvm/Analysis/RegionInfo.h"
35 #include "llvm/Analysis/RegionIterator.h"
36 #include "llvm/Analysis/ScalarEvolution.h"
37 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/DiagnosticInfo.h"
44 #include "llvm/IR/Dominators.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Operator.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/Use.h"
53 #include "llvm/IR/Value.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cassert>
61 #include <string>
62 #include <tuple>
63 #include <vector>
64 
65 using namespace llvm;
66 using namespace polly;
67 
68 #define DEBUG_TYPE "polly-scops"
69 
70 STATISTIC(ScopFound, "Number of valid Scops");
71 STATISTIC(RichScopFound, "Number of Scops containing a loop");
72 STATISTIC(InfeasibleScops,
73           "Number of SCoPs with statically infeasible context.");
74 
75 bool polly::ModelReadOnlyScalars;
76 
77 static cl::opt<bool, true> XModelReadOnlyScalars(
78     "polly-analyze-read-only-scalars",
79     cl::desc("Model read-only scalar values in the scop description"),
80     cl::location(ModelReadOnlyScalars), cl::Hidden, cl::ZeroOrMore,
81     cl::init(true), cl::cat(PollyCategory));
82 
83 static cl::opt<bool> UnprofitableScalarAccs(
84     "polly-unprofitable-scalar-accs",
85     cl::desc("Count statements with scalar accesses as not optimizable"),
86     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
87 
88 static cl::opt<bool> DetectFortranArrays(
89     "polly-detect-fortran-arrays",
90     cl::desc("Detect Fortran arrays and use this for code generation"),
91     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
92 
93 static cl::opt<bool> DetectReductions("polly-detect-reductions",
94                                       cl::desc("Detect and exploit reductions"),
95                                       cl::Hidden, cl::ZeroOrMore,
96                                       cl::init(true), cl::cat(PollyCategory));
97 
98 // Multiplicative reductions can be disabled separately as these kind of
99 // operations can overflow easily. Additive reductions and bit operations
100 // are in contrast pretty stable.
101 static cl::opt<bool> DisableMultiplicativeReductions(
102     "polly-disable-multiplicative-reductions",
103     cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
104     cl::init(false), cl::cat(PollyCategory));
105 
106 enum class GranularityChoice { BasicBlocks, ScalarIndepependence };
107 
108 static cl::opt<GranularityChoice> StmtGranularity(
109     "polly-stmt-granularity",
110     cl::desc(
111         "Algorithm to use for splitting basic blocks into multiple statements"),
112     cl::values(clEnumValN(GranularityChoice::BasicBlocks, "bb",
113                           "One statement per basic block"),
114                clEnumValN(GranularityChoice::ScalarIndepependence,
115                           "scalar-indep", "Scalar independence heuristic")),
116     cl::init(GranularityChoice::BasicBlocks), cl::cat(PollyCategory));
117 
118 void ScopBuilder::buildPHIAccesses(ScopStmt *PHIStmt, PHINode *PHI,
119                                    Region *NonAffineSubRegion,
120                                    bool IsExitBlock) {
121   // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
122   // true, are not modeled as ordinary PHI nodes as they are not part of the
123   // region. However, we model the operands in the predecessor blocks that are
124   // part of the region as regular scalar accesses.
125 
126   // If we can synthesize a PHI we can skip it, however only if it is in
127   // the region. If it is not it can only be in the exit block of the region.
128   // In this case we model the operands but not the PHI itself.
129   auto *Scope = LI.getLoopFor(PHI->getParent());
130   if (!IsExitBlock && canSynthesize(PHI, *scop, &SE, Scope))
131     return;
132 
133   // PHI nodes are modeled as if they had been demoted prior to the SCoP
134   // detection. Hence, the PHI is a load of a new memory location in which the
135   // incoming value was written at the end of the incoming basic block.
136   bool OnlyNonAffineSubRegionOperands = true;
137   for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
138     Value *Op = PHI->getIncomingValue(u);
139     BasicBlock *OpBB = PHI->getIncomingBlock(u);
140     ScopStmt *OpStmt = scop->getLastStmtFor(OpBB);
141 
142     // Do not build PHI dependences inside a non-affine subregion, but make
143     // sure that the necessary scalar values are still made available.
144     if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB)) {
145       auto *OpInst = dyn_cast<Instruction>(Op);
146       if (!OpInst || !NonAffineSubRegion->contains(OpInst))
147         ensureValueRead(Op, OpStmt);
148       continue;
149     }
150 
151     OnlyNonAffineSubRegionOperands = false;
152     ensurePHIWrite(PHI, OpStmt, OpBB, Op, IsExitBlock);
153   }
154 
155   if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
156     addPHIReadAccess(PHIStmt, PHI);
157   }
158 }
159 
160 void ScopBuilder::buildScalarDependences(ScopStmt *UserStmt,
161                                          Instruction *Inst) {
162   assert(!isa<PHINode>(Inst));
163 
164   // Pull-in required operands.
165   for (Use &Op : Inst->operands())
166     ensureValueRead(Op.get(), UserStmt);
167 }
168 
169 void ScopBuilder::buildEscapingDependences(Instruction *Inst) {
170   // Check for uses of this instruction outside the scop. Because we do not
171   // iterate over such instructions and therefore did not "ensure" the existence
172   // of a write, we must determine such use here.
173   if (scop->isEscaping(Inst))
174     ensureValueWrite(Inst);
175 }
176 
177 /// Check that a value is a Fortran Array descriptor.
178 ///
179 /// We check if V has the following structure:
180 /// %"struct.array1_real(kind=8)" = type { i8*, i<zz>, i<zz>,
181 ///                                   [<num> x %struct.descriptor_dimension] }
182 ///
183 ///
184 /// %struct.descriptor_dimension = type { i<zz>, i<zz>, i<zz> }
185 ///
186 /// 1. V's type name starts with "struct.array"
187 /// 2. V's type has layout as shown.
188 /// 3. Final member of V's type has name "struct.descriptor_dimension",
189 /// 4. "struct.descriptor_dimension" has layout as shown.
190 /// 5. Consistent use of i<zz> where <zz> is some fixed integer number.
191 ///
192 /// We are interested in such types since this is the code that dragonegg
193 /// generates for Fortran array descriptors.
194 ///
195 /// @param V the Value to be checked.
196 ///
197 /// @returns True if V is a Fortran array descriptor, False otherwise.
198 bool isFortranArrayDescriptor(Value *V) {
199   PointerType *PTy = dyn_cast<PointerType>(V->getType());
200 
201   if (!PTy)
202     return false;
203 
204   Type *Ty = PTy->getElementType();
205   assert(Ty && "Ty expected to be initialized");
206   auto *StructArrTy = dyn_cast<StructType>(Ty);
207 
208   if (!(StructArrTy && StructArrTy->hasName()))
209     return false;
210 
211   if (!StructArrTy->getName().startswith("struct.array"))
212     return false;
213 
214   if (StructArrTy->getNumElements() != 4)
215     return false;
216 
217   const ArrayRef<Type *> ArrMemberTys = StructArrTy->elements();
218 
219   // i8* match
220   if (ArrMemberTys[0] != Type::getInt8PtrTy(V->getContext()))
221     return false;
222 
223   // Get a reference to the int type and check that all the members
224   // share the same int type
225   Type *IntTy = ArrMemberTys[1];
226   if (ArrMemberTys[2] != IntTy)
227     return false;
228 
229   // type: [<num> x %struct.descriptor_dimension]
230   ArrayType *DescriptorDimArrayTy = dyn_cast<ArrayType>(ArrMemberTys[3]);
231   if (!DescriptorDimArrayTy)
232     return false;
233 
234   // type: %struct.descriptor_dimension := type { ixx, ixx, ixx }
235   StructType *DescriptorDimTy =
236       dyn_cast<StructType>(DescriptorDimArrayTy->getElementType());
237 
238   if (!(DescriptorDimTy && DescriptorDimTy->hasName()))
239     return false;
240 
241   if (DescriptorDimTy->getName() != "struct.descriptor_dimension")
242     return false;
243 
244   if (DescriptorDimTy->getNumElements() != 3)
245     return false;
246 
247   for (auto MemberTy : DescriptorDimTy->elements()) {
248     if (MemberTy != IntTy)
249       return false;
250   }
251 
252   return true;
253 }
254 
255 Value *ScopBuilder::findFADAllocationVisible(MemAccInst Inst) {
256   // match: 4.1 & 4.2 store/load
257   if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst))
258     return nullptr;
259 
260   // match: 4
261   if (Inst.getAlignment() != 8)
262     return nullptr;
263 
264   Value *Address = Inst.getPointerOperand();
265 
266   const BitCastInst *Bitcast = nullptr;
267   // [match: 3]
268   if (auto *Slot = dyn_cast<GetElementPtrInst>(Address)) {
269     Value *TypedMem = Slot->getPointerOperand();
270     // match: 2
271     Bitcast = dyn_cast<BitCastInst>(TypedMem);
272   } else {
273     // match: 2
274     Bitcast = dyn_cast<BitCastInst>(Address);
275   }
276 
277   if (!Bitcast)
278     return nullptr;
279 
280   auto *MallocMem = Bitcast->getOperand(0);
281 
282   // match: 1
283   auto *MallocCall = dyn_cast<CallInst>(MallocMem);
284   if (!MallocCall)
285     return nullptr;
286 
287   Function *MallocFn = MallocCall->getCalledFunction();
288   if (!(MallocFn && MallocFn->hasName() && MallocFn->getName() == "malloc"))
289     return nullptr;
290 
291   // Find all uses the malloc'd memory.
292   // We are looking for a "store" into a struct with the type being the Fortran
293   // descriptor type
294   for (auto user : MallocMem->users()) {
295     /// match: 5
296     auto *MallocStore = dyn_cast<StoreInst>(user);
297     if (!MallocStore)
298       continue;
299 
300     auto *DescriptorGEP =
301         dyn_cast<GEPOperator>(MallocStore->getPointerOperand());
302     if (!DescriptorGEP)
303       continue;
304 
305     // match: 5
306     auto DescriptorType =
307         dyn_cast<StructType>(DescriptorGEP->getSourceElementType());
308     if (!(DescriptorType && DescriptorType->hasName()))
309       continue;
310 
311     Value *Descriptor = dyn_cast<Value>(DescriptorGEP->getPointerOperand());
312 
313     if (!Descriptor)
314       continue;
315 
316     if (!isFortranArrayDescriptor(Descriptor))
317       continue;
318 
319     return Descriptor;
320   }
321 
322   return nullptr;
323 }
324 
325 Value *ScopBuilder::findFADAllocationInvisible(MemAccInst Inst) {
326   // match: 3
327   if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst))
328     return nullptr;
329 
330   Value *Slot = Inst.getPointerOperand();
331 
332   LoadInst *MemLoad = nullptr;
333   // [match: 2]
334   if (auto *SlotGEP = dyn_cast<GetElementPtrInst>(Slot)) {
335     // match: 1
336     MemLoad = dyn_cast<LoadInst>(SlotGEP->getPointerOperand());
337   } else {
338     // match: 1
339     MemLoad = dyn_cast<LoadInst>(Slot);
340   }
341 
342   if (!MemLoad)
343     return nullptr;
344 
345   auto *BitcastOperator =
346       dyn_cast<BitCastOperator>(MemLoad->getPointerOperand());
347   if (!BitcastOperator)
348     return nullptr;
349 
350   Value *Descriptor = dyn_cast<Value>(BitcastOperator->getOperand(0));
351   if (!Descriptor)
352     return nullptr;
353 
354   if (!isFortranArrayDescriptor(Descriptor))
355     return nullptr;
356 
357   return Descriptor;
358 }
359 
360 bool ScopBuilder::buildAccessMultiDimFixed(MemAccInst Inst, ScopStmt *Stmt) {
361   Value *Val = Inst.getValueOperand();
362   Type *ElementType = Val->getType();
363   Value *Address = Inst.getPointerOperand();
364   const SCEV *AccessFunction =
365       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
366   const SCEVUnknown *BasePointer =
367       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
368   enum MemoryAccess::AccessType AccType =
369       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
370 
371   if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
372     auto *Src = BitCast->getOperand(0);
373     auto *SrcTy = Src->getType();
374     auto *DstTy = BitCast->getType();
375     // Do not try to delinearize non-sized (opaque) pointers.
376     if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
377         (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
378       return false;
379     }
380     if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
381         DL.getTypeAllocSize(SrcTy->getPointerElementType()) ==
382             DL.getTypeAllocSize(DstTy->getPointerElementType()))
383       Address = Src;
384   }
385 
386   auto *GEP = dyn_cast<GetElementPtrInst>(Address);
387   if (!GEP)
388     return false;
389 
390   std::vector<const SCEV *> Subscripts;
391   std::vector<int> Sizes;
392   std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
393   auto *BasePtr = GEP->getOperand(0);
394 
395   if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
396     BasePtr = BasePtrCast->getOperand(0);
397 
398   // Check for identical base pointers to ensure that we do not miss index
399   // offsets that have been added before this GEP is applied.
400   if (BasePtr != BasePointer->getValue())
401     return false;
402 
403   std::vector<const SCEV *> SizesSCEV;
404 
405   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
406 
407   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
408   for (auto *Subscript : Subscripts) {
409     InvariantLoadsSetTy AccessILS;
410     if (!isAffineExpr(&scop->getRegion(), SurroundingLoop, Subscript, SE,
411                       &AccessILS))
412       return false;
413 
414     for (LoadInst *LInst : AccessILS)
415       if (!ScopRIL.count(LInst))
416         return false;
417   }
418 
419   if (Sizes.empty())
420     return false;
421 
422   SizesSCEV.push_back(nullptr);
423 
424   for (auto V : Sizes)
425     SizesSCEV.push_back(SE.getSCEV(
426         ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
427 
428   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
429                  true, Subscripts, SizesSCEV, Val);
430   return true;
431 }
432 
433 bool ScopBuilder::buildAccessMultiDimParam(MemAccInst Inst, ScopStmt *Stmt) {
434   if (!PollyDelinearize)
435     return false;
436 
437   Value *Address = Inst.getPointerOperand();
438   Value *Val = Inst.getValueOperand();
439   Type *ElementType = Val->getType();
440   unsigned ElementSize = DL.getTypeAllocSize(ElementType);
441   enum MemoryAccess::AccessType AccType =
442       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
443 
444   const SCEV *AccessFunction =
445       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
446   const SCEVUnknown *BasePointer =
447       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
448 
449   assert(BasePointer && "Could not find base pointer");
450 
451   auto &InsnToMemAcc = scop->getInsnToMemAccMap();
452   auto AccItr = InsnToMemAcc.find(Inst);
453   if (AccItr == InsnToMemAcc.end())
454     return false;
455 
456   std::vector<const SCEV *> Sizes = {nullptr};
457 
458   Sizes.insert(Sizes.end(), AccItr->second.Shape->DelinearizedSizes.begin(),
459                AccItr->second.Shape->DelinearizedSizes.end());
460 
461   // In case only the element size is contained in the 'Sizes' array, the
462   // access does not access a real multi-dimensional array. Hence, we allow
463   // the normal single-dimensional access construction to handle this.
464   if (Sizes.size() == 1)
465     return false;
466 
467   // Remove the element size. This information is already provided by the
468   // ElementSize parameter. In case the element size of this access and the
469   // element size used for delinearization differs the delinearization is
470   // incorrect. Hence, we invalidate the scop.
471   //
472   // TODO: Handle delinearization with differing element sizes.
473   auto DelinearizedSize =
474       cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
475   Sizes.pop_back();
476   if (ElementSize != DelinearizedSize)
477     scop->invalidate(DELINEARIZATION, Inst->getDebugLoc(), Inst->getParent());
478 
479   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
480                  true, AccItr->second.DelinearizedSubscripts, Sizes, Val);
481   return true;
482 }
483 
484 bool ScopBuilder::buildAccessMemIntrinsic(MemAccInst Inst, ScopStmt *Stmt) {
485   auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
486 
487   if (MemIntr == nullptr)
488     return false;
489 
490   auto *L = LI.getLoopFor(Inst->getParent());
491   auto *LengthVal = SE.getSCEVAtScope(MemIntr->getLength(), L);
492   assert(LengthVal);
493 
494   // Check if the length val is actually affine or if we overapproximate it
495   InvariantLoadsSetTy AccessILS;
496   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
497 
498   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
499   bool LengthIsAffine = isAffineExpr(&scop->getRegion(), SurroundingLoop,
500                                      LengthVal, SE, &AccessILS);
501   for (LoadInst *LInst : AccessILS)
502     if (!ScopRIL.count(LInst))
503       LengthIsAffine = false;
504   if (!LengthIsAffine)
505     LengthVal = nullptr;
506 
507   auto *DestPtrVal = MemIntr->getDest();
508   assert(DestPtrVal);
509 
510   auto *DestAccFunc = SE.getSCEVAtScope(DestPtrVal, L);
511   assert(DestAccFunc);
512   // Ignore accesses to "NULL".
513   // TODO: We could use this to optimize the region further, e.g., intersect
514   //       the context with
515   //          isl_set_complement(isl_set_params(getDomain()))
516   //       as we know it would be undefined to execute this instruction anyway.
517   if (DestAccFunc->isZero())
518     return true;
519 
520   auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(DestAccFunc));
521   assert(DestPtrSCEV);
522   DestAccFunc = SE.getMinusSCEV(DestAccFunc, DestPtrSCEV);
523   addArrayAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
524                  IntegerType::getInt8Ty(DestPtrVal->getContext()),
525                  LengthIsAffine, {DestAccFunc, LengthVal}, {nullptr},
526                  Inst.getValueOperand());
527 
528   auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
529   if (!MemTrans)
530     return true;
531 
532   auto *SrcPtrVal = MemTrans->getSource();
533   assert(SrcPtrVal);
534 
535   auto *SrcAccFunc = SE.getSCEVAtScope(SrcPtrVal, L);
536   assert(SrcAccFunc);
537   // Ignore accesses to "NULL".
538   // TODO: See above TODO
539   if (SrcAccFunc->isZero())
540     return true;
541 
542   auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(SrcAccFunc));
543   assert(SrcPtrSCEV);
544   SrcAccFunc = SE.getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
545   addArrayAccess(Stmt, Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
546                  IntegerType::getInt8Ty(SrcPtrVal->getContext()),
547                  LengthIsAffine, {SrcAccFunc, LengthVal}, {nullptr},
548                  Inst.getValueOperand());
549 
550   return true;
551 }
552 
553 bool ScopBuilder::buildAccessCallInst(MemAccInst Inst, ScopStmt *Stmt) {
554   auto *CI = dyn_cast_or_null<CallInst>(Inst);
555 
556   if (CI == nullptr)
557     return false;
558 
559   if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
560     return true;
561 
562   bool ReadOnly = false;
563   auto *AF = SE.getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
564   auto *CalledFunction = CI->getCalledFunction();
565   switch (AA.getModRefBehavior(CalledFunction)) {
566   case FMRB_UnknownModRefBehavior:
567     llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
568   case FMRB_DoesNotAccessMemory:
569     return true;
570   case FMRB_DoesNotReadMemory:
571   case FMRB_OnlyAccessesInaccessibleMem:
572   case FMRB_OnlyAccessesInaccessibleOrArgMem:
573     return false;
574   case FMRB_OnlyReadsMemory:
575     GlobalReads.emplace_back(Stmt, CI);
576     return true;
577   case FMRB_OnlyReadsArgumentPointees:
578     ReadOnly = true;
579   // Fall through
580   case FMRB_OnlyAccessesArgumentPointees: {
581     auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
582     Loop *L = LI.getLoopFor(Inst->getParent());
583     for (const auto &Arg : CI->arg_operands()) {
584       if (!Arg->getType()->isPointerTy())
585         continue;
586 
587       auto *ArgSCEV = SE.getSCEVAtScope(Arg, L);
588       if (ArgSCEV->isZero())
589         continue;
590 
591       auto *ArgBasePtr = cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
592       addArrayAccess(Stmt, Inst, AccType, ArgBasePtr->getValue(),
593                      ArgBasePtr->getType(), false, {AF}, {nullptr}, CI);
594     }
595     return true;
596   }
597   }
598 
599   return true;
600 }
601 
602 void ScopBuilder::buildAccessSingleDim(MemAccInst Inst, ScopStmt *Stmt) {
603   Value *Address = Inst.getPointerOperand();
604   Value *Val = Inst.getValueOperand();
605   Type *ElementType = Val->getType();
606   enum MemoryAccess::AccessType AccType =
607       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
608 
609   const SCEV *AccessFunction =
610       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
611   const SCEVUnknown *BasePointer =
612       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
613 
614   assert(BasePointer && "Could not find base pointer");
615   AccessFunction = SE.getMinusSCEV(AccessFunction, BasePointer);
616 
617   // Check if the access depends on a loop contained in a non-affine subregion.
618   bool isVariantInNonAffineLoop = false;
619   SetVector<const Loop *> Loops;
620   findLoops(AccessFunction, Loops);
621   for (const Loop *L : Loops)
622     if (Stmt->contains(L)) {
623       isVariantInNonAffineLoop = true;
624       break;
625     }
626 
627   InvariantLoadsSetTy AccessILS;
628 
629   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
630   bool IsAffine = !isVariantInNonAffineLoop &&
631                   isAffineExpr(&scop->getRegion(), SurroundingLoop,
632                                AccessFunction, SE, &AccessILS);
633 
634   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
635   for (LoadInst *LInst : AccessILS)
636     if (!ScopRIL.count(LInst))
637       IsAffine = false;
638 
639   if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
640     AccType = MemoryAccess::MAY_WRITE;
641 
642   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
643                  IsAffine, {AccessFunction}, {nullptr}, Val);
644 }
645 
646 void ScopBuilder::buildMemoryAccess(MemAccInst Inst, ScopStmt *Stmt) {
647   if (buildAccessMemIntrinsic(Inst, Stmt))
648     return;
649 
650   if (buildAccessCallInst(Inst, Stmt))
651     return;
652 
653   if (buildAccessMultiDimFixed(Inst, Stmt))
654     return;
655 
656   if (buildAccessMultiDimParam(Inst, Stmt))
657     return;
658 
659   buildAccessSingleDim(Inst, Stmt);
660 }
661 
662 void ScopBuilder::buildAccessFunctions() {
663   for (auto &Stmt : *scop) {
664     if (Stmt.isBlockStmt()) {
665       buildAccessFunctions(&Stmt, *Stmt.getBasicBlock());
666       continue;
667     }
668 
669     Region *R = Stmt.getRegion();
670     for (BasicBlock *BB : R->blocks())
671       buildAccessFunctions(&Stmt, *BB, R);
672   }
673 
674   // Build write accesses for values that are used after the SCoP.
675   // The instructions defining them might be synthesizable and therefore not
676   // contained in any statement, hence we iterate over the original instructions
677   // to identify all escaping values.
678   for (BasicBlock *BB : scop->getRegion().blocks()) {
679     for (Instruction &Inst : *BB)
680       buildEscapingDependences(&Inst);
681   }
682 }
683 
684 bool ScopBuilder::shouldModelInst(Instruction *Inst, Loop *L) {
685   return !isa<TerminatorInst>(Inst) && !isIgnoredIntrinsic(Inst) &&
686          !canSynthesize(Inst, *scop, &SE, L);
687 }
688 
689 void ScopBuilder::buildSequentialBlockStmts(BasicBlock *BB) {
690   Loop *SurroundingLoop = LI.getLoopFor(BB);
691 
692   int Count = 0;
693   std::vector<Instruction *> Instructions;
694   for (Instruction &Inst : *BB) {
695     if (shouldModelInst(&Inst, SurroundingLoop))
696       Instructions.push_back(&Inst);
697     if (Inst.getMetadata("polly_split_after")) {
698       scop->addScopStmt(BB, SurroundingLoop, Instructions, Count);
699       Count++;
700       Instructions.clear();
701     }
702   }
703 
704   scop->addScopStmt(BB, SurroundingLoop, Instructions, Count);
705 }
706 
707 /// Is @p Inst an ordered instruction?
708 ///
709 /// An unordered instruction is an instruction, such that a sequence of
710 /// unordered instructions can be permuted without changing semantics. Any
711 /// instruction for which this is not always the case is ordered.
712 static bool isOrderedInstruction(Instruction *Inst) {
713   return Inst->mayHaveSideEffects() || Inst->mayReadOrWriteMemory();
714 }
715 
716 /// Join instructions to the same statement if one uses the scalar result of the
717 /// other.
718 static void joinOperandTree(EquivalenceClasses<Instruction *> &UnionFind,
719                             ArrayRef<Instruction *> ModeledInsts) {
720   for (Instruction *Inst : ModeledInsts) {
721     if (isa<PHINode>(Inst))
722       continue;
723 
724     for (Use &Op : Inst->operands()) {
725       Instruction *OpInst = dyn_cast<Instruction>(Op.get());
726       if (!OpInst)
727         continue;
728 
729       // Check if OpInst is in the BB and is a modeled instruction.
730       auto OpVal = UnionFind.findValue(OpInst);
731       if (OpVal == UnionFind.end())
732         continue;
733 
734       UnionFind.unionSets(Inst, OpInst);
735     }
736   }
737 }
738 
739 /// Join instructions that are used as incoming value in successor PHIs into the
740 /// epilogue.
741 static void
742 joinIncomingPHIValuesIntoEpilogue(EquivalenceClasses<Instruction *> &UnionFind,
743                                   ArrayRef<Instruction *> ModeledInsts,
744                                   BasicBlock *BB) {
745   for (BasicBlock *Succ : successors(BB)) {
746     for (Instruction &SuccInst : *Succ) {
747       PHINode *SuccPHI = dyn_cast<PHINode>(&SuccInst);
748       if (!SuccPHI)
749         break;
750 
751       Value *IncomingVal = SuccPHI->getIncomingValueForBlock(BB);
752       Instruction *IncomingInst = dyn_cast<Instruction>(IncomingVal);
753       if (!IncomingInst)
754         continue;
755       if (IncomingInst->getParent() != BB)
756         continue;
757       if (UnionFind.findValue(IncomingInst) == UnionFind.end())
758         continue;
759 
760       UnionFind.unionSets(nullptr, IncomingInst);
761     }
762   }
763 }
764 
765 /// Ensure that the order of ordered instructions does not change.
766 ///
767 /// If we encounter an ordered instruction enclosed in instructions belonging to
768 /// a different statement (which might as well contain ordered instructions, but
769 /// this is not tested here), join them.
770 static void
771 joinOrderedInstructions(EquivalenceClasses<Instruction *> &UnionFind,
772                         ArrayRef<Instruction *> ModeledInsts) {
773   SetVector<Instruction *> SeenLeaders;
774   for (Instruction *Inst : ModeledInsts) {
775     if (!isOrderedInstruction(Inst))
776       continue;
777 
778     Instruction *Leader = UnionFind.getLeaderValue(Inst);
779     bool Inserted = SeenLeaders.insert(Leader);
780     if (Inserted)
781       continue;
782 
783     // Merge statements to close holes. Say, we have already seen statements A
784     // and B, in this order. Then we see an instruction of A again and we would
785     // see the pattern "A B A". This function joins all statements until the
786     // only seen occurrence of A.
787     for (Instruction *Prev : reverse(SeenLeaders)) {
788       // Items added to 'SeenLeaders' are leaders, but may have lost their
789       // leadership status when merged into another statement.
790       Instruction *PrevLeader = UnionFind.getLeaderValue(SeenLeaders.back());
791       if (PrevLeader == Leader)
792         break;
793       UnionFind.unionSets(Prev, Leader);
794     }
795   }
796 }
797 
798 /// Also ensure that the epilogue is the last statement relative to all ordered
799 /// instructions.
800 ///
801 /// This is basically joinOrderedInstructions() but using the epilogue as
802 /// 'ordered instruction'.
803 static void joinAllAfterEpilogue(EquivalenceClasses<Instruction *> &UnionFind,
804                                  ArrayRef<Instruction *> ModeledInsts) {
805   bool EpilogueSeen = false;
806   for (Instruction *Inst : ModeledInsts) {
807     auto PHIWritesLeader = UnionFind.findLeader(nullptr);
808     auto InstLeader = UnionFind.findLeader(Inst);
809 
810     if (PHIWritesLeader == InstLeader)
811       EpilogueSeen = true;
812 
813     if (!isOrderedInstruction(Inst))
814       continue;
815 
816     if (EpilogueSeen)
817       UnionFind.unionSets(PHIWritesLeader, InstLeader);
818   }
819 }
820 
821 void ScopBuilder::buildEqivClassBlockStmts(BasicBlock *BB) {
822   Loop *L = LI.getLoopFor(BB);
823 
824   // Extracting out modeled instructions saves us from checking
825   // shouldModelInst() repeatedly.
826   SmallVector<Instruction *, 32> ModeledInsts;
827   EquivalenceClasses<Instruction *> UnionFind;
828   for (Instruction &Inst : *BB) {
829     if (!shouldModelInst(&Inst, L))
830       continue;
831     ModeledInsts.push_back(&Inst);
832     UnionFind.insert(&Inst);
833   }
834 
835   // 'nullptr' represents the last statement for a basic block. It contains no
836   // instructions, but holds the PHI write accesses for successor basic blocks.
837   // If a PHI has an incoming value defined in this BB, it can also be merged
838   // with other statements.
839   // TODO: We wouldn't need this if we would add PHIWrites into the statement
840   // that defines the incoming value (if in the BB) instead of always the last,
841   // so we could unconditionally always add a last statement.
842   UnionFind.insert(nullptr);
843 
844   joinOperandTree(UnionFind, ModeledInsts);
845   joinIncomingPHIValuesIntoEpilogue(UnionFind, ModeledInsts, BB);
846   joinOrderedInstructions(UnionFind, ModeledInsts);
847   joinAllAfterEpilogue(UnionFind, ModeledInsts);
848 
849   // The list of instructions for statement (statement represented by the leader
850   // instruction). The order of statements instructions is reversed such that
851   // the epilogue is first. This makes it easier to ensure that the epilogue is
852   // the last statement.
853   MapVector<Instruction *, std::vector<Instruction *>> LeaderToInstList;
854 
855   // Ensure that the epilogue is last.
856   LeaderToInstList[nullptr];
857 
858   // Collect the instructions of all leaders. UnionFind's member iterator
859   // unfortunately are not in any specific order.
860   for (Instruction &Inst : reverse(*BB)) {
861     auto LeaderIt = UnionFind.findLeader(&Inst);
862     if (LeaderIt == UnionFind.member_end())
863       continue;
864 
865     std::vector<Instruction *> &InstList = LeaderToInstList[*LeaderIt];
866     InstList.push_back(&Inst);
867   }
868 
869   // Finally build the statements.
870   int Count = 0;
871   for (auto &Instructions : reverse(LeaderToInstList)) {
872     std::vector<Instruction *> &InstList = Instructions.second;
873     std::reverse(InstList.begin(), InstList.end());
874     scop->addScopStmt(BB, L, std::move(InstList), Count);
875     Count += 1;
876   }
877 }
878 
879 void ScopBuilder::buildStmts(Region &SR) {
880   if (scop->isNonAffineSubRegion(&SR)) {
881     std::vector<Instruction *> Instructions;
882     Loop *SurroundingLoop =
883         getFirstNonBoxedLoopFor(SR.getEntry(), LI, scop->getBoxedLoops());
884     for (Instruction &Inst : *SR.getEntry())
885       if (shouldModelInst(&Inst, SurroundingLoop))
886         Instructions.push_back(&Inst);
887     scop->addScopStmt(&SR, SurroundingLoop, Instructions);
888     return;
889   }
890 
891   for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
892     if (I->isSubRegion())
893       buildStmts(*I->getNodeAs<Region>());
894     else {
895       BasicBlock *BB = I->getNodeAs<BasicBlock>();
896       switch (StmtGranularity) {
897       case GranularityChoice::BasicBlocks:
898         buildSequentialBlockStmts(BB);
899         break;
900       case GranularityChoice::ScalarIndepependence:
901         buildEqivClassBlockStmts(BB);
902         break;
903       }
904     }
905 }
906 
907 void ScopBuilder::buildAccessFunctions(ScopStmt *Stmt, BasicBlock &BB,
908                                        Region *NonAffineSubRegion) {
909   assert(
910       Stmt &&
911       "The exit BB is the only one that cannot be represented by a statement");
912   assert(Stmt->represents(&BB));
913 
914   // We do not build access functions for error blocks, as they may contain
915   // instructions we can not model.
916   if (isErrorBlock(BB, scop->getRegion(), LI, DT))
917     return;
918 
919   auto BuildAccessesForInst = [this, Stmt,
920                                NonAffineSubRegion](Instruction *Inst) {
921     PHINode *PHI = dyn_cast<PHINode>(Inst);
922     if (PHI)
923       buildPHIAccesses(Stmt, PHI, NonAffineSubRegion, false);
924 
925     if (auto MemInst = MemAccInst::dyn_cast(*Inst)) {
926       assert(Stmt && "Cannot build access function in non-existing statement");
927       buildMemoryAccess(MemInst, Stmt);
928     }
929 
930     // PHI nodes have already been modeled above and TerminatorInsts that are
931     // not part of a non-affine subregion are fully modeled and regenerated
932     // from the polyhedral domains. Hence, they do not need to be modeled as
933     // explicit data dependences.
934     if (!PHI)
935       buildScalarDependences(Stmt, Inst);
936   };
937 
938   const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads();
939   bool IsEntryBlock = (Stmt->getEntryBlock() == &BB);
940   if (IsEntryBlock) {
941     for (Instruction *Inst : Stmt->getInstructions())
942       BuildAccessesForInst(Inst);
943     if (Stmt->isRegionStmt())
944       BuildAccessesForInst(BB.getTerminator());
945   } else {
946     for (Instruction &Inst : BB) {
947       if (isIgnoredIntrinsic(&Inst))
948         continue;
949 
950       // Invariant loads already have been processed.
951       if (isa<LoadInst>(Inst) && RIL.count(cast<LoadInst>(&Inst)))
952         continue;
953 
954       BuildAccessesForInst(&Inst);
955     }
956   }
957 }
958 
959 MemoryAccess *ScopBuilder::addMemoryAccess(
960     ScopStmt *Stmt, Instruction *Inst, MemoryAccess::AccessType AccType,
961     Value *BaseAddress, Type *ElementType, bool Affine, Value *AccessValue,
962     ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes,
963     MemoryKind Kind) {
964   bool isKnownMustAccess = false;
965 
966   // Accesses in single-basic block statements are always executed.
967   if (Stmt->isBlockStmt())
968     isKnownMustAccess = true;
969 
970   if (Stmt->isRegionStmt()) {
971     // Accesses that dominate the exit block of a non-affine region are always
972     // executed. In non-affine regions there may exist MemoryKind::Values that
973     // do not dominate the exit. MemoryKind::Values will always dominate the
974     // exit and MemoryKind::PHIs only if there is at most one PHI_WRITE in the
975     // non-affine region.
976     if (Inst && DT.dominates(Inst->getParent(), Stmt->getRegion()->getExit()))
977       isKnownMustAccess = true;
978   }
979 
980   // Non-affine PHI writes do not "happen" at a particular instruction, but
981   // after exiting the statement. Therefore they are guaranteed to execute and
982   // overwrite the old value.
983   if (Kind == MemoryKind::PHI || Kind == MemoryKind::ExitPHI)
984     isKnownMustAccess = true;
985 
986   if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
987     AccType = MemoryAccess::MAY_WRITE;
988 
989   auto *Access = new MemoryAccess(Stmt, Inst, AccType, BaseAddress, ElementType,
990                                   Affine, Subscripts, Sizes, AccessValue, Kind);
991 
992   scop->addAccessFunction(Access);
993   Stmt->addAccess(Access);
994   return Access;
995 }
996 
997 void ScopBuilder::addArrayAccess(ScopStmt *Stmt, MemAccInst MemAccInst,
998                                  MemoryAccess::AccessType AccType,
999                                  Value *BaseAddress, Type *ElementType,
1000                                  bool IsAffine,
1001                                  ArrayRef<const SCEV *> Subscripts,
1002                                  ArrayRef<const SCEV *> Sizes,
1003                                  Value *AccessValue) {
1004   ArrayBasePointers.insert(BaseAddress);
1005   auto *MemAccess = addMemoryAccess(Stmt, MemAccInst, AccType, BaseAddress,
1006                                     ElementType, IsAffine, AccessValue,
1007                                     Subscripts, Sizes, MemoryKind::Array);
1008 
1009   if (!DetectFortranArrays)
1010     return;
1011 
1012   if (Value *FAD = findFADAllocationInvisible(MemAccInst))
1013     MemAccess->setFortranArrayDescriptor(FAD);
1014   else if (Value *FAD = findFADAllocationVisible(MemAccInst))
1015     MemAccess->setFortranArrayDescriptor(FAD);
1016 }
1017 
1018 void ScopBuilder::ensureValueWrite(Instruction *Inst) {
1019   // Find the statement that defines the value of Inst. That statement has to
1020   // write the value to make it available to those statements that read it.
1021   ScopStmt *Stmt = scop->getStmtFor(Inst);
1022 
1023   // It is possible that the value is synthesizable within a loop (such that it
1024   // is not part of any statement), but not after the loop (where you need the
1025   // number of loop round-trips to synthesize it). In LCSSA-form a PHI node will
1026   // avoid this. In case the IR has no such PHI, use the last statement (where
1027   // the value is synthesizable) to write the value.
1028   if (!Stmt)
1029     Stmt = scop->getLastStmtFor(Inst->getParent());
1030 
1031   // Inst not defined within this SCoP.
1032   if (!Stmt)
1033     return;
1034 
1035   // Do not process further if the instruction is already written.
1036   if (Stmt->lookupValueWriteOf(Inst))
1037     return;
1038 
1039   addMemoryAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, Inst, Inst->getType(),
1040                   true, Inst, ArrayRef<const SCEV *>(),
1041                   ArrayRef<const SCEV *>(), MemoryKind::Value);
1042 }
1043 
1044 void ScopBuilder::ensureValueRead(Value *V, ScopStmt *UserStmt) {
1045   // TODO: Make ScopStmt::ensureValueRead(Value*) offer the same functionality
1046   // to be able to replace this one. Currently, there is a split responsibility.
1047   // In a first step, the MemoryAccess is created, but without the
1048   // AccessRelation. In the second step by ScopStmt::buildAccessRelations(), the
1049   // AccessRelation is created. At least for scalar accesses, there is no new
1050   // information available at ScopStmt::buildAccessRelations(), so we could
1051   // create the AccessRelation right away. This is what
1052   // ScopStmt::ensureValueRead(Value*) does.
1053 
1054   auto *Scope = UserStmt->getSurroundingLoop();
1055   auto VUse = VirtualUse::create(scop.get(), UserStmt, Scope, V, false);
1056   switch (VUse.getKind()) {
1057   case VirtualUse::Constant:
1058   case VirtualUse::Block:
1059   case VirtualUse::Synthesizable:
1060   case VirtualUse::Hoisted:
1061   case VirtualUse::Intra:
1062     // Uses of these kinds do not need a MemoryAccess.
1063     break;
1064 
1065   case VirtualUse::ReadOnly:
1066     // Add MemoryAccess for invariant values only if requested.
1067     if (!ModelReadOnlyScalars)
1068       break;
1069 
1070     LLVM_FALLTHROUGH;
1071   case VirtualUse::Inter:
1072 
1073     // Do not create another MemoryAccess for reloading the value if one already
1074     // exists.
1075     if (UserStmt->lookupValueReadOf(V))
1076       break;
1077 
1078     addMemoryAccess(UserStmt, nullptr, MemoryAccess::READ, V, V->getType(),
1079                     true, V, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
1080                     MemoryKind::Value);
1081 
1082     // Inter-statement uses need to write the value in their defining statement.
1083     if (VUse.isInter())
1084       ensureValueWrite(cast<Instruction>(V));
1085     break;
1086   }
1087 }
1088 
1089 void ScopBuilder::ensurePHIWrite(PHINode *PHI, ScopStmt *IncomingStmt,
1090                                  BasicBlock *IncomingBlock,
1091                                  Value *IncomingValue, bool IsExitBlock) {
1092   // As the incoming block might turn out to be an error statement ensure we
1093   // will create an exit PHI SAI object. It is needed during code generation
1094   // and would be created later anyway.
1095   if (IsExitBlock)
1096     scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
1097                                    MemoryKind::ExitPHI);
1098 
1099   // This is possible if PHI is in the SCoP's entry block. The incoming blocks
1100   // from outside the SCoP's region have no statement representation.
1101   if (!IncomingStmt)
1102     return;
1103 
1104   // Take care for the incoming value being available in the incoming block.
1105   // This must be done before the check for multiple PHI writes because multiple
1106   // exiting edges from subregion each can be the effective written value of the
1107   // subregion. As such, all of them must be made available in the subregion
1108   // statement.
1109   ensureValueRead(IncomingValue, IncomingStmt);
1110 
1111   // Do not add more than one MemoryAccess per PHINode and ScopStmt.
1112   if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
1113     assert(Acc->getAccessInstruction() == PHI);
1114     Acc->addIncoming(IncomingBlock, IncomingValue);
1115     return;
1116   }
1117 
1118   MemoryAccess *Acc = addMemoryAccess(
1119       IncomingStmt, PHI, MemoryAccess::MUST_WRITE, PHI, PHI->getType(), true,
1120       PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
1121       IsExitBlock ? MemoryKind::ExitPHI : MemoryKind::PHI);
1122   assert(Acc);
1123   Acc->addIncoming(IncomingBlock, IncomingValue);
1124 }
1125 
1126 void ScopBuilder::addPHIReadAccess(ScopStmt *PHIStmt, PHINode *PHI) {
1127   addMemoryAccess(PHIStmt, PHI, MemoryAccess::READ, PHI, PHI->getType(), true,
1128                   PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
1129                   MemoryKind::PHI);
1130 }
1131 
1132 void ScopBuilder::buildDomain(ScopStmt &Stmt) {
1133   isl::id Id = isl::id::alloc(scop->getIslCtx(), Stmt.getBaseName(), &Stmt);
1134 
1135   Stmt.Domain = scop->getDomainConditions(&Stmt);
1136   Stmt.Domain = Stmt.Domain.set_tuple_id(Id);
1137 }
1138 
1139 void ScopBuilder::collectSurroundingLoops(ScopStmt &Stmt) {
1140   isl::set Domain = Stmt.getDomain();
1141   for (unsigned u = 0, e = Domain.dim(isl::dim::set); u < e; u++) {
1142     isl::id DimId = Domain.get_dim_id(isl::dim::set, u);
1143     Stmt.NestLoops.push_back(static_cast<Loop *>(DimId.get_user()));
1144   }
1145 }
1146 
1147 /// Return the reduction type for a given binary operator.
1148 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
1149                                                     const Instruction *Load) {
1150   if (!BinOp)
1151     return MemoryAccess::RT_NONE;
1152   switch (BinOp->getOpcode()) {
1153   case Instruction::FAdd:
1154     if (!BinOp->isFast())
1155       return MemoryAccess::RT_NONE;
1156     // Fall through
1157   case Instruction::Add:
1158     return MemoryAccess::RT_ADD;
1159   case Instruction::Or:
1160     return MemoryAccess::RT_BOR;
1161   case Instruction::Xor:
1162     return MemoryAccess::RT_BXOR;
1163   case Instruction::And:
1164     return MemoryAccess::RT_BAND;
1165   case Instruction::FMul:
1166     if (!BinOp->isFast())
1167       return MemoryAccess::RT_NONE;
1168     // Fall through
1169   case Instruction::Mul:
1170     if (DisableMultiplicativeReductions)
1171       return MemoryAccess::RT_NONE;
1172     return MemoryAccess::RT_MUL;
1173   default:
1174     return MemoryAccess::RT_NONE;
1175   }
1176 }
1177 
1178 void ScopBuilder::checkForReductions(ScopStmt &Stmt) {
1179   SmallVector<MemoryAccess *, 2> Loads;
1180   SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1181 
1182   // First collect candidate load-store reduction chains by iterating over all
1183   // stores and collecting possible reduction loads.
1184   for (MemoryAccess *StoreMA : Stmt) {
1185     if (StoreMA->isRead())
1186       continue;
1187 
1188     Loads.clear();
1189     collectCandidateReductionLoads(StoreMA, Loads);
1190     for (MemoryAccess *LoadMA : Loads)
1191       Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1192   }
1193 
1194   // Then check each possible candidate pair.
1195   for (const auto &CandidatePair : Candidates) {
1196     bool Valid = true;
1197     isl::map LoadAccs = CandidatePair.first->getAccessRelation();
1198     isl::map StoreAccs = CandidatePair.second->getAccessRelation();
1199 
1200     // Skip those with obviously unequal base addresses.
1201     if (!LoadAccs.has_equal_space(StoreAccs)) {
1202       continue;
1203     }
1204 
1205     // And check if the remaining for overlap with other memory accesses.
1206     isl::map AllAccsRel = LoadAccs.unite(StoreAccs);
1207     AllAccsRel = AllAccsRel.intersect_domain(Stmt.getDomain());
1208     isl::set AllAccs = AllAccsRel.range();
1209 
1210     for (MemoryAccess *MA : Stmt) {
1211       if (MA == CandidatePair.first || MA == CandidatePair.second)
1212         continue;
1213 
1214       isl::map AccRel =
1215           MA->getAccessRelation().intersect_domain(Stmt.getDomain());
1216       isl::set Accs = AccRel.range();
1217 
1218       if (AllAccs.has_equal_space(Accs)) {
1219         isl::set OverlapAccs = Accs.intersect(AllAccs);
1220         Valid = Valid && OverlapAccs.is_empty();
1221       }
1222     }
1223 
1224     if (!Valid)
1225       continue;
1226 
1227     const LoadInst *Load =
1228         dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1229     MemoryAccess::ReductionType RT =
1230         getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1231 
1232     // If no overlapping access was found we mark the load and store as
1233     // reduction like.
1234     CandidatePair.first->markAsReductionLike(RT);
1235     CandidatePair.second->markAsReductionLike(RT);
1236   }
1237 }
1238 
1239 void ScopBuilder::collectCandidateReductionLoads(
1240     MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1241   ScopStmt *Stmt = StoreMA->getStatement();
1242 
1243   auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1244   if (!Store)
1245     return;
1246 
1247   // Skip if there is not one binary operator between the load and the store
1248   auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
1249   if (!BinOp)
1250     return;
1251 
1252   // Skip if the binary operators has multiple uses
1253   if (BinOp->getNumUses() != 1)
1254     return;
1255 
1256   // Skip if the opcode of the binary operator is not commutative/associative
1257   if (!BinOp->isCommutative() || !BinOp->isAssociative())
1258     return;
1259 
1260   // Skip if the binary operator is outside the current SCoP
1261   if (BinOp->getParent() != Store->getParent())
1262     return;
1263 
1264   // Skip if it is a multiplicative reduction and we disabled them
1265   if (DisableMultiplicativeReductions &&
1266       (BinOp->getOpcode() == Instruction::Mul ||
1267        BinOp->getOpcode() == Instruction::FMul))
1268     return;
1269 
1270   // Check the binary operator operands for a candidate load
1271   auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1272   auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1273   if (!PossibleLoad0 && !PossibleLoad1)
1274     return;
1275 
1276   // A load is only a candidate if it cannot escape (thus has only this use)
1277   if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
1278     if (PossibleLoad0->getParent() == Store->getParent())
1279       Loads.push_back(&Stmt->getArrayAccessFor(PossibleLoad0));
1280   if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
1281     if (PossibleLoad1->getParent() == Store->getParent())
1282       Loads.push_back(&Stmt->getArrayAccessFor(PossibleLoad1));
1283 }
1284 
1285 void ScopBuilder::buildAccessRelations(ScopStmt &Stmt) {
1286   for (MemoryAccess *Access : Stmt.MemAccs) {
1287     Type *ElementType = Access->getElementType();
1288 
1289     MemoryKind Ty;
1290     if (Access->isPHIKind())
1291       Ty = MemoryKind::PHI;
1292     else if (Access->isExitPHIKind())
1293       Ty = MemoryKind::ExitPHI;
1294     else if (Access->isValueKind())
1295       Ty = MemoryKind::Value;
1296     else
1297       Ty = MemoryKind::Array;
1298 
1299     auto *SAI = scop->getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1300                                                ElementType, Access->Sizes, Ty);
1301     Access->buildAccessRelation(SAI);
1302     scop->addAccessData(Access);
1303   }
1304 }
1305 
1306 #ifndef NDEBUG
1307 static void verifyUse(Scop *S, Use &Op, LoopInfo &LI) {
1308   auto PhysUse = VirtualUse::create(S, Op, &LI, false);
1309   auto VirtUse = VirtualUse::create(S, Op, &LI, true);
1310   assert(PhysUse.getKind() == VirtUse.getKind());
1311 }
1312 
1313 /// Check the consistency of every statement's MemoryAccesses.
1314 ///
1315 /// The check is carried out by expecting the "physical" kind of use (derived
1316 /// from the BasicBlocks instructions resides in) to be same as the "virtual"
1317 /// kind of use (derived from a statement's MemoryAccess).
1318 ///
1319 /// The "physical" uses are taken by ensureValueRead to determine whether to
1320 /// create MemoryAccesses. When done, the kind of scalar access should be the
1321 /// same no matter which way it was derived.
1322 ///
1323 /// The MemoryAccesses might be changed by later SCoP-modifying passes and hence
1324 /// can intentionally influence on the kind of uses (not corresponding to the
1325 /// "physical" anymore, hence called "virtual"). The CodeGenerator therefore has
1326 /// to pick up the virtual uses. But here in the code generator, this has not
1327 /// happened yet, such that virtual and physical uses are equivalent.
1328 static void verifyUses(Scop *S, LoopInfo &LI, DominatorTree &DT) {
1329   for (auto *BB : S->getRegion().blocks()) {
1330     for (auto &Inst : *BB) {
1331       auto *Stmt = S->getStmtFor(&Inst);
1332       if (!Stmt)
1333         continue;
1334 
1335       if (isIgnoredIntrinsic(&Inst))
1336         continue;
1337 
1338       // Branch conditions are encoded in the statement domains.
1339       if (isa<TerminatorInst>(&Inst) && Stmt->isBlockStmt())
1340         continue;
1341 
1342       // Verify all uses.
1343       for (auto &Op : Inst.operands())
1344         verifyUse(S, Op, LI);
1345 
1346       // Stores do not produce values used by other statements.
1347       if (isa<StoreInst>(Inst))
1348         continue;
1349 
1350       // For every value defined in the block, also check that a use of that
1351       // value in the same statement would not be an inter-statement use. It can
1352       // still be synthesizable or load-hoisted, but these kind of instructions
1353       // are not directly copied in code-generation.
1354       auto VirtDef =
1355           VirtualUse::create(S, Stmt, Stmt->getSurroundingLoop(), &Inst, true);
1356       assert(VirtDef.getKind() == VirtualUse::Synthesizable ||
1357              VirtDef.getKind() == VirtualUse::Intra ||
1358              VirtDef.getKind() == VirtualUse::Hoisted);
1359     }
1360   }
1361 
1362   if (S->hasSingleExitEdge())
1363     return;
1364 
1365   // PHINodes in the SCoP region's exit block are also uses to be checked.
1366   if (!S->getRegion().isTopLevelRegion()) {
1367     for (auto &Inst : *S->getRegion().getExit()) {
1368       if (!isa<PHINode>(Inst))
1369         break;
1370 
1371       for (auto &Op : Inst.operands())
1372         verifyUse(S, Op, LI);
1373     }
1374   }
1375 }
1376 #endif
1377 
1378 /// Return the block that is the representing block for @p RN.
1379 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1380   return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1381                            : RN->getNodeAs<BasicBlock>();
1382 }
1383 
1384 void ScopBuilder::buildScop(Region &R, AssumptionCache &AC,
1385                             OptimizationRemarkEmitter &ORE) {
1386   scop.reset(new Scop(R, SE, LI, DT, *SD.getDetectionContext(&R), ORE));
1387 
1388   buildStmts(R);
1389 
1390   // Create all invariant load instructions first. These are categorized as
1391   // 'synthesizable', therefore are not part of any ScopStmt but need to be
1392   // created somewhere.
1393   const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads();
1394   for (BasicBlock *BB : scop->getRegion().blocks()) {
1395     if (isErrorBlock(*BB, scop->getRegion(), LI, DT))
1396       continue;
1397 
1398     for (Instruction &Inst : *BB) {
1399       LoadInst *Load = dyn_cast<LoadInst>(&Inst);
1400       if (!Load)
1401         continue;
1402 
1403       if (!RIL.count(Load))
1404         continue;
1405 
1406       // Invariant loads require a MemoryAccess to be created in some statement.
1407       // It is not important to which statement the MemoryAccess is added
1408       // because it will later be removed from the ScopStmt again. We chose the
1409       // first statement of the basic block the LoadInst is in.
1410       ArrayRef<ScopStmt *> List = scop->getStmtListFor(BB);
1411       assert(!List.empty());
1412       ScopStmt *RILStmt = List.front();
1413       buildMemoryAccess(Load, RILStmt);
1414     }
1415   }
1416   buildAccessFunctions();
1417 
1418   // In case the region does not have an exiting block we will later (during
1419   // code generation) split the exit block. This will move potential PHI nodes
1420   // from the current exit block into the new region exiting block. Hence, PHI
1421   // nodes that are at this point not part of the region will be.
1422   // To handle these PHI nodes later we will now model their operands as scalar
1423   // accesses. Note that we do not model anything in the exit block if we have
1424   // an exiting block in the region, as there will not be any splitting later.
1425   if (!R.isTopLevelRegion() && !scop->hasSingleExitEdge()) {
1426     for (Instruction &Inst : *R.getExit()) {
1427       PHINode *PHI = dyn_cast<PHINode>(&Inst);
1428       if (!PHI)
1429         break;
1430 
1431       buildPHIAccesses(nullptr, PHI, nullptr, true);
1432     }
1433   }
1434 
1435   // Create memory accesses for global reads since all arrays are now known.
1436   auto *AF = SE.getConstant(IntegerType::getInt64Ty(SE.getContext()), 0);
1437   for (auto GlobalReadPair : GlobalReads) {
1438     ScopStmt *GlobalReadStmt = GlobalReadPair.first;
1439     Instruction *GlobalRead = GlobalReadPair.second;
1440     for (auto *BP : ArrayBasePointers)
1441       addArrayAccess(GlobalReadStmt, MemAccInst(GlobalRead), MemoryAccess::READ,
1442                      BP, BP->getType(), false, {AF}, {nullptr}, GlobalRead);
1443   }
1444 
1445   scop->buildInvariantEquivalenceClasses();
1446 
1447   /// A map from basic blocks to their invalid domains.
1448   DenseMap<BasicBlock *, isl::set> InvalidDomainMap;
1449 
1450   if (!scop->buildDomains(&R, DT, LI, InvalidDomainMap)) {
1451     DEBUG(dbgs() << "Bailing-out because buildDomains encountered problems\n");
1452     return;
1453   }
1454 
1455   scop->addUserAssumptions(AC, DT, LI, InvalidDomainMap);
1456 
1457   // Initialize the invalid domain.
1458   for (ScopStmt &Stmt : scop->Stmts)
1459     if (Stmt.isBlockStmt())
1460       Stmt.setInvalidDomain(InvalidDomainMap[Stmt.getEntryBlock()]);
1461     else
1462       Stmt.setInvalidDomain(InvalidDomainMap[getRegionNodeBasicBlock(
1463           Stmt.getRegion()->getNode())]);
1464 
1465   // Remove empty statements.
1466   // Exit early in case there are no executable statements left in this scop.
1467   scop->removeStmtNotInDomainMap();
1468   scop->simplifySCoP(false);
1469   if (scop->isEmpty()) {
1470     DEBUG(dbgs() << "Bailing-out because SCoP is empty\n");
1471     return;
1472   }
1473 
1474   // The ScopStmts now have enough information to initialize themselves.
1475   for (ScopStmt &Stmt : *scop) {
1476     buildDomain(Stmt);
1477     collectSurroundingLoops(Stmt);
1478     buildAccessRelations(Stmt);
1479 
1480     if (DetectReductions)
1481       checkForReductions(Stmt);
1482   }
1483 
1484   // Check early for a feasible runtime context.
1485   if (!scop->hasFeasibleRuntimeContext()) {
1486     DEBUG(dbgs() << "Bailing-out because of unfeasible context (early)\n");
1487     return;
1488   }
1489 
1490   // Check early for profitability. Afterwards it cannot change anymore,
1491   // only the runtime context could become infeasible.
1492   if (!scop->isProfitable(UnprofitableScalarAccs)) {
1493     scop->invalidate(PROFITABLE, DebugLoc());
1494     DEBUG(dbgs() << "Bailing-out because SCoP is not considered profitable\n");
1495     return;
1496   }
1497 
1498   scop->buildSchedule(LI);
1499 
1500   scop->finalizeAccesses();
1501 
1502   scop->realignParams();
1503   scop->addUserContext();
1504 
1505   // After the context was fully constructed, thus all our knowledge about
1506   // the parameters is in there, we add all recorded assumptions to the
1507   // assumed/invalid context.
1508   scop->addRecordedAssumptions();
1509 
1510   scop->simplifyContexts();
1511   if (!scop->buildAliasChecks(AA)) {
1512     DEBUG(dbgs() << "Bailing-out because could not build alias checks\n");
1513     return;
1514   }
1515 
1516   scop->hoistInvariantLoads();
1517   scop->canonicalizeDynamicBasePtrs();
1518   scop->verifyInvariantLoads();
1519   scop->simplifySCoP(true);
1520 
1521   // Check late for a feasible runtime context because profitability did not
1522   // change.
1523   if (!scop->hasFeasibleRuntimeContext()) {
1524     DEBUG(dbgs() << "Bailing-out because of unfeasible context (late)\n");
1525     return;
1526   }
1527 
1528 #ifndef NDEBUG
1529   verifyUses(scop.get(), LI, DT);
1530 #endif
1531 }
1532 
1533 ScopBuilder::ScopBuilder(Region *R, AssumptionCache &AC, AliasAnalysis &AA,
1534                          const DataLayout &DL, DominatorTree &DT, LoopInfo &LI,
1535                          ScopDetection &SD, ScalarEvolution &SE,
1536                          OptimizationRemarkEmitter &ORE)
1537     : AA(AA), DL(DL), DT(DT), LI(LI), SD(SD), SE(SE) {
1538   DebugLoc Beg, End;
1539   auto P = getBBPairForRegion(R);
1540   getDebugLocations(P, Beg, End);
1541 
1542   std::string Msg = "SCoP begins here.";
1543   ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEntry", Beg, P.first)
1544            << Msg);
1545 
1546   buildScop(*R, AC, ORE);
1547 
1548   DEBUG(dbgs() << *scop);
1549 
1550   if (!scop->hasFeasibleRuntimeContext()) {
1551     InfeasibleScops++;
1552     Msg = "SCoP ends here but was dismissed.";
1553     DEBUG(dbgs() << "SCoP detected but dismissed\n");
1554     scop.reset();
1555   } else {
1556     Msg = "SCoP ends here.";
1557     ++ScopFound;
1558     if (scop->getMaxLoopDepth() > 0)
1559       ++RichScopFound;
1560   }
1561 
1562   if (R->isTopLevelRegion())
1563     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.first)
1564              << Msg);
1565   else
1566     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.second)
1567              << Msg);
1568 }
1569