1 //===--- BlockGenerators.cpp - Generate code for statements -----*- 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 // This file implements the BlockGenerator and VectorBlockGenerator classes,
11 // which generate sequential code and vectorized code for a polyhedral
12 // statement, respectively.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "polly/CodeGen/BlockGenerators.h"
17 #include "polly/CodeGen/CodeGeneration.h"
18 #include "polly/CodeGen/IslExprBuilder.h"
19 #include "polly/CodeGen/RuntimeDebugBuilder.h"
20 #include "polly/Options.h"
21 #include "polly/ScopInfo.h"
22 #include "polly/Support/GICHelper.h"
23 #include "polly/Support/SCEVValidator.h"
24 #include "polly/Support/ScopHelper.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/RegionInfo.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "isl/aff.h"
33 #include "isl/ast.h"
34 #include "isl/ast_build.h"
35 #include "isl/set.h"
36 #include <deque>
37 
38 using namespace llvm;
39 using namespace polly;
40 
41 static cl::opt<bool> Aligned("enable-polly-aligned",
42                              cl::desc("Assumed aligned memory accesses."),
43                              cl::Hidden, cl::init(false), cl::ZeroOrMore,
44                              cl::cat(PollyCategory));
45 
46 bool PollyDebugPrinting;
47 static cl::opt<bool, true> DebugPrintingX(
48     "polly-codegen-add-debug-printing",
49     cl::desc("Add printf calls that show the values loaded/stored."),
50     cl::location(PollyDebugPrinting), cl::Hidden, cl::init(false),
51     cl::ZeroOrMore, cl::cat(PollyCategory));
52 
53 BlockGenerator::BlockGenerator(
54     PollyIRBuilder &B, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT,
55     AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap,
56     ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock)
57     : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
58       EntryBB(nullptr), ScalarMap(ScalarMap), EscapeMap(EscapeMap),
59       GlobalMap(GlobalMap), StartBlock(StartBlock) {}
60 
61 Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
62                                              ValueMapT &BBMap,
63                                              LoopToScevMapT &LTS,
64                                              Loop *L) const {
65   if (!SE.isSCEVable(Old->getType()))
66     return nullptr;
67 
68   const SCEV *Scev = SE.getSCEVAtScope(Old, L);
69   if (!Scev)
70     return nullptr;
71 
72   if (isa<SCEVCouldNotCompute>(Scev))
73     return nullptr;
74 
75   const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE);
76   ValueMapT VTV;
77   VTV.insert(BBMap.begin(), BBMap.end());
78   VTV.insert(GlobalMap.begin(), GlobalMap.end());
79 
80   Scop &S = *Stmt.getParent();
81   const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
82   auto IP = Builder.GetInsertPoint();
83 
84   assert(IP != Builder.GetInsertBlock()->end() &&
85          "Only instructions can be insert points for SCEVExpander");
86   Value *Expanded =
87       expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV,
88                     StartBlock->getSinglePredecessor());
89 
90   BBMap[Old] = Expanded;
91   return Expanded;
92 }
93 
94 Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
95                                    LoopToScevMapT &LTS, Loop *L) const {
96   // Constants that do not reference any named value can always remain
97   // unchanged. Handle them early to avoid expensive map lookups. We do not take
98   // the fast-path for external constants which are referenced through globals
99   // as these may need to be rewritten when distributing code accross different
100   // LLVM modules.
101   if (isa<Constant>(Old) && !isa<GlobalValue>(Old))
102     return Old;
103 
104   // Inline asm is like a constant to us.
105   if (isa<InlineAsm>(Old))
106     return Old;
107 
108   if (Value *New = GlobalMap.lookup(Old)) {
109     if (Value *NewRemapped = GlobalMap.lookup(New))
110       New = NewRemapped;
111     if (Old->getType()->getScalarSizeInBits() <
112         New->getType()->getScalarSizeInBits())
113       New = Builder.CreateTruncOrBitCast(New, Old->getType());
114 
115     return New;
116   }
117 
118   if (Value *New = BBMap.lookup(Old))
119     return New;
120 
121   if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
122     return New;
123 
124   // A scop-constant value defined by a global or a function parameter.
125   if (isa<GlobalValue>(Old) || isa<Argument>(Old))
126     return Old;
127 
128   // A scop-constant value defined by an instruction executed outside the scop.
129   if (const Instruction *Inst = dyn_cast<Instruction>(Old))
130     if (!Stmt.getParent()->contains(Inst->getParent()))
131       return Old;
132 
133   // The scalar dependence is neither available nor SCEVCodegenable.
134   llvm_unreachable("Unexpected scalar dependence in region!");
135   return nullptr;
136 }
137 
138 void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
139                                     ValueMapT &BBMap, LoopToScevMapT &LTS) {
140   // We do not generate debug intrinsics as we did not investigate how to
141   // copy them correctly. At the current state, they just crash the code
142   // generation as the meta-data operands are not correctly copied.
143   if (isa<DbgInfoIntrinsic>(Inst))
144     return;
145 
146   Instruction *NewInst = Inst->clone();
147 
148   // Replace old operands with the new ones.
149   for (Value *OldOperand : Inst->operands()) {
150     Value *NewOperand =
151         getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
152 
153     if (!NewOperand) {
154       assert(!isa<StoreInst>(NewInst) &&
155              "Store instructions are always needed!");
156       delete NewInst;
157       return;
158     }
159 
160     NewInst->replaceUsesOfWith(OldOperand, NewOperand);
161   }
162 
163   Builder.Insert(NewInst);
164   BBMap[Inst] = NewInst;
165 
166   if (!NewInst->getType()->isVoidTy())
167     NewInst->setName("p_" + Inst->getName());
168 }
169 
170 Value *
171 BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
172                                          ValueMapT &BBMap, LoopToScevMapT &LTS,
173                                          isl_id_to_ast_expr *NewAccesses) {
174   const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
175   return generateLocationAccessed(
176       Stmt, getLoopForStmt(Stmt),
177       Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS,
178       NewAccesses, MA.getId(), MA.getAccessValue()->getType());
179 }
180 
181 Value *BlockGenerator::generateLocationAccessed(
182     ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
183     LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
184     Type *ExpectedType) {
185   isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
186 
187   if (AccessExpr) {
188     AccessExpr = isl_ast_expr_address_of(AccessExpr);
189     auto Address = ExprBuilder->create(AccessExpr);
190 
191     // Cast the address of this memory access to a pointer type that has the
192     // same element type as the original access, but uses the address space of
193     // the newly generated pointer.
194     auto OldPtrTy = ExpectedType->getPointerTo();
195     auto NewPtrTy = Address->getType();
196     OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
197                                 NewPtrTy->getPointerAddressSpace());
198 
199     if (OldPtrTy != NewPtrTy)
200       Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
201     return Address;
202   }
203   assert(
204       Pointer &&
205       "If expression was not generated, must use the original pointer value");
206   return getNewValue(Stmt, Pointer, BBMap, LTS, L);
207 }
208 
209 Value *
210 BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L,
211                                    LoopToScevMapT &LTS, ValueMapT &BBMap,
212                                    __isl_keep isl_id_to_ast_expr *NewAccesses) {
213   if (Access.isLatestArrayKind())
214     return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
215                                     LTS, NewAccesses, Access.getId(),
216                                     Access.getAccessValue()->getType());
217 
218   return getOrCreateAlloca(Access);
219 }
220 
221 Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
222   auto *StmtBB = Stmt.getEntryBlock();
223   return LI.getLoopFor(StmtBB);
224 }
225 
226 Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load,
227                                          ValueMapT &BBMap, LoopToScevMapT &LTS,
228                                          isl_id_to_ast_expr *NewAccesses) {
229   if (Value *PreloadLoad = GlobalMap.lookup(Load))
230     return PreloadLoad;
231 
232   Value *NewPointer =
233       generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
234   Value *ScalarLoad = Builder.CreateAlignedLoad(
235       NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
236 
237   if (PollyDebugPrinting)
238     RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
239                                           ": ", ScalarLoad, "\n");
240 
241   return ScalarLoad;
242 }
243 
244 void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
245                                         ValueMapT &BBMap, LoopToScevMapT &LTS,
246                                         isl_id_to_ast_expr *NewAccesses) {
247   Value *NewPointer =
248       generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
249   Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
250                                     getLoopForStmt(Stmt));
251 
252   if (PollyDebugPrinting)
253     RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to  ", NewPointer,
254                                           ": ", ValueOperand, "\n");
255 
256   Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
257 }
258 
259 bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
260   Loop *L = getLoopForStmt(Stmt);
261   return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
262          canSynthesize(Inst, *Stmt.getParent(), &SE, L);
263 }
264 
265 void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
266                                      ValueMapT &BBMap, LoopToScevMapT &LTS,
267                                      isl_id_to_ast_expr *NewAccesses) {
268   // Terminator instructions control the control flow. They are explicitly
269   // expressed in the clast and do not need to be copied.
270   if (Inst->isTerminator())
271     return;
272 
273   // Synthesizable statements will be generated on-demand.
274   if (canSyntheziseInStmt(Stmt, Inst))
275     return;
276 
277   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
278     Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
279     // Compute NewLoad before its insertion in BBMap to make the insertion
280     // deterministic.
281     BBMap[Load] = NewLoad;
282     return;
283   }
284 
285   if (auto *Store = dyn_cast<StoreInst>(Inst)) {
286     // Identified as redundant by -polly-simplify.
287     if (!Stmt.getArrayAccessOrNULLFor(Store))
288       return;
289 
290     generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
291     return;
292   }
293 
294   if (auto *PHI = dyn_cast<PHINode>(Inst)) {
295     copyPHIInstruction(Stmt, PHI, BBMap, LTS);
296     return;
297   }
298 
299   // Skip some special intrinsics for which we do not adjust the semantics to
300   // the new schedule. All others are handled like every other instruction.
301   if (isIgnoredIntrinsic(Inst))
302     return;
303 
304   copyInstScalar(Stmt, Inst, BBMap, LTS);
305 }
306 
307 void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) {
308   auto NewBB = Builder.GetInsertBlock();
309   for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) {
310     Instruction *NewInst = &*I;
311 
312     if (!isInstructionTriviallyDead(NewInst))
313       continue;
314 
315     for (auto Pair : BBMap)
316       if (Pair.second == NewInst) {
317         BBMap.erase(Pair.first);
318       }
319 
320     NewInst->eraseFromParent();
321     I = NewBB->rbegin();
322   }
323 }
324 
325 void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
326                               isl_id_to_ast_expr *NewAccesses) {
327   assert(Stmt.isBlockStmt() &&
328          "Only block statements can be copied by the block generator");
329 
330   ValueMapT BBMap;
331 
332   BasicBlock *BB = Stmt.getBasicBlock();
333   copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
334   removeDeadInstructions(BB, BBMap);
335 }
336 
337 BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
338   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
339                                   &*Builder.GetInsertPoint(), &DT, &LI);
340   CopyBB->setName("polly.stmt." + BB->getName());
341   return CopyBB;
342 }
343 
344 BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
345                                    ValueMapT &BBMap, LoopToScevMapT &LTS,
346                                    isl_id_to_ast_expr *NewAccesses) {
347   BasicBlock *CopyBB = splitBB(BB);
348   Builder.SetInsertPoint(&CopyBB->front());
349   generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
350 
351   copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
352 
353   // After a basic block was copied store all scalars that escape this block in
354   // their alloca.
355   generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
356   return CopyBB;
357 }
358 
359 void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
360                             ValueMapT &BBMap, LoopToScevMapT &LTS,
361                             isl_id_to_ast_expr *NewAccesses) {
362   EntryBB = &CopyBB->getParent()->getEntryBlock();
363 
364   for (Instruction &Inst : *BB)
365     copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
366 }
367 
368 Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
369   assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
370 
371   return getOrCreateAlloca(Access.getLatestScopArrayInfo());
372 }
373 
374 Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
375   assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
376 
377   auto &Addr = ScalarMap[Array];
378 
379   if (Addr) {
380     // Allow allocas to be (temporarily) redirected once by adding a new
381     // old-alloca-addr to new-addr mapping to GlobalMap. This funcitionality
382     // is used for example by the OpenMP code generation where a first use
383     // of a scalar while still in the host code allocates a normal alloca with
384     // getOrCreateAlloca. When the values of this scalar are accessed during
385     // the generation of the parallel subfunction, these values are copied over
386     // to the parallel subfunction and each request for a scalar alloca slot
387     // must be forwared to the temporary in-subfunction slot. This mapping is
388     // removed when the subfunction has been generated and again normal host
389     // code is generated. Due to the following reasons it is not possible to
390     // perform the GlobalMap lookup right after creating the alloca below, but
391     // instead we need to check GlobalMap at each call to getOrCreateAlloca:
392     //
393     //   1) GlobalMap may be changed multiple times (for each parallel loop),
394     //   2) The temporary mapping is commonly only known after the initial
395     //      alloca has already been generated, and
396     //   3) The original alloca value must be restored after leaving the
397     //      sub-function.
398     if (Value *NewAddr = GlobalMap.lookup(&*Addr))
399       return NewAddr;
400     return Addr;
401   }
402 
403   Type *Ty = Array->getElementType();
404   Value *ScalarBase = Array->getBasePtr();
405   std::string NameExt;
406   if (Array->isPHIKind())
407     NameExt = ".phiops";
408   else
409     NameExt = ".s2a";
410 
411   const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout();
412 
413   Addr = new AllocaInst(Ty, DL.getAllocaAddrSpace(),
414                         ScalarBase->getName() + NameExt);
415   EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
416   Addr->insertBefore(&*EntryBB->getFirstInsertionPt());
417 
418   return Addr;
419 }
420 
421 void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) {
422   Instruction *Inst = cast<Instruction>(Array->getBasePtr());
423 
424   // If there are escape users we get the alloca for this instruction and put it
425   // in the EscapeMap for later finalization. Lastly, if the instruction was
426   // copied multiple times we already did this and can exit.
427   if (EscapeMap.count(Inst))
428     return;
429 
430   EscapeUserVectorTy EscapeUsers;
431   for (User *U : Inst->users()) {
432 
433     // Non-instruction user will never escape.
434     Instruction *UI = dyn_cast<Instruction>(U);
435     if (!UI)
436       continue;
437 
438     if (S.contains(UI))
439       continue;
440 
441     EscapeUsers.push_back(UI);
442   }
443 
444   // Exit if no escape uses were found.
445   if (EscapeUsers.empty())
446     return;
447 
448   // Get or create an escape alloca for this instruction.
449   auto *ScalarAddr = getOrCreateAlloca(Array);
450 
451   // Remember that this instruction has escape uses and the escape alloca.
452   EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
453 }
454 
455 void BlockGenerator::generateScalarLoads(
456     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
457     __isl_keep isl_id_to_ast_expr *NewAccesses) {
458   for (MemoryAccess *MA : Stmt) {
459     if (MA->isOriginalArrayKind() || MA->isWrite())
460       continue;
461 
462 #ifndef NDEBUG
463     auto *StmtDom = Stmt.getDomain();
464     auto *AccDom = isl_map_domain(MA->getAccessRelation());
465     assert(isl_set_is_subset(StmtDom, AccDom) &&
466            "Scalar must be loaded in all statement instances");
467     isl_set_free(StmtDom);
468     isl_set_free(AccDom);
469 #endif
470 
471     auto *Address =
472         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
473     assert((!isa<Instruction>(Address) ||
474             DT.dominates(cast<Instruction>(Address)->getParent(),
475                          Builder.GetInsertBlock())) &&
476            "Domination violation");
477     BBMap[MA->getAccessValue()] =
478         Builder.CreateLoad(Address, Address->getName() + ".reload");
479   }
480 }
481 
482 void BlockGenerator::generateScalarStores(
483     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
484     __isl_keep isl_id_to_ast_expr *NewAccesses) {
485   Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
486 
487   assert(Stmt.isBlockStmt() &&
488          "Region statements need to use the generateScalarStores() function in "
489          "the RegionGenerator");
490 
491   for (MemoryAccess *MA : Stmt) {
492     if (MA->isOriginalArrayKind() || MA->isRead())
493       continue;
494 
495 #ifndef NDEBUG
496     auto *StmtDom = Stmt.getDomain();
497     auto *AccDom = isl_map_domain(MA->getAccessRelation());
498     assert(isl_set_is_subset(StmtDom, AccDom) &&
499            "Scalar must be stored in all statement instances");
500     isl_set_free(StmtDom);
501     isl_set_free(AccDom);
502 #endif
503 
504     Value *Val = MA->getAccessValue();
505     if (MA->isAnyPHIKind()) {
506       assert(MA->getIncoming().size() >= 1 &&
507              "Block statements have exactly one exiting block, or multiple but "
508              "with same incoming block and value");
509       assert(std::all_of(MA->getIncoming().begin(), MA->getIncoming().end(),
510                          [&](std::pair<BasicBlock *, Value *> p) -> bool {
511                            return p.first == Stmt.getBasicBlock();
512                          }) &&
513              "Incoming block must be statement's block");
514       Val = MA->getIncoming()[0].second;
515     }
516     auto Address =
517         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
518 
519     Val = getNewValue(Stmt, Val, BBMap, LTS, L);
520     assert((!isa<Instruction>(Val) ||
521             DT.dominates(cast<Instruction>(Val)->getParent(),
522                          Builder.GetInsertBlock())) &&
523            "Domination violation");
524     assert((!isa<Instruction>(Address) ||
525             DT.dominates(cast<Instruction>(Address)->getParent(),
526                          Builder.GetInsertBlock())) &&
527            "Domination violation");
528     Builder.CreateStore(Val, Address);
529   }
530 }
531 
532 void BlockGenerator::createScalarInitialization(Scop &S) {
533   BasicBlock *ExitBB = S.getExit();
534   BasicBlock *PreEntryBB = S.getEnteringBlock();
535 
536   Builder.SetInsertPoint(&*StartBlock->begin());
537 
538   for (auto &Array : S.arrays()) {
539     if (Array->getNumberOfDimensions() != 0)
540       continue;
541     if (Array->isPHIKind()) {
542       // For PHI nodes, the only values we need to store are the ones that
543       // reach the PHI node from outside the region. In general there should
544       // only be one such incoming edge and this edge should enter through
545       // 'PreEntryBB'.
546       auto PHI = cast<PHINode>(Array->getBasePtr());
547 
548       for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
549         if (!S.contains(*BI) && *BI != PreEntryBB)
550           llvm_unreachable("Incoming edges from outside the scop should always "
551                            "come from PreEntryBB");
552 
553       int Idx = PHI->getBasicBlockIndex(PreEntryBB);
554       if (Idx < 0)
555         continue;
556 
557       Value *ScalarValue = PHI->getIncomingValue(Idx);
558 
559       Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
560       continue;
561     }
562 
563     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
564 
565     if (Inst && S.contains(Inst))
566       continue;
567 
568     // PHI nodes that are not marked as such in their SAI object are either exit
569     // PHI nodes we model as common scalars but without initialization, or
570     // incoming phi nodes that need to be initialized. Check if the first is the
571     // case for Inst and do not create and initialize memory if so.
572     if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
573       if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
574         continue;
575 
576     Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
577   }
578 }
579 
580 void BlockGenerator::createScalarFinalization(Scop &S) {
581   // The exit block of the __unoptimized__ region.
582   BasicBlock *ExitBB = S.getExitingBlock();
583   // The merge block __just after__ the region and the optimized region.
584   BasicBlock *MergeBB = S.getExit();
585 
586   // The exit block of the __optimized__ region.
587   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
588   if (OptExitBB == ExitBB)
589     OptExitBB = *(++pred_begin(MergeBB));
590 
591   Builder.SetInsertPoint(OptExitBB->getTerminator());
592   for (const auto &EscapeMapping : EscapeMap) {
593     // Extract the escaping instruction and the escaping users as well as the
594     // alloca the instruction was demoted to.
595     Instruction *EscapeInst = EscapeMapping.first;
596     const auto &EscapeMappingValue = EscapeMapping.second;
597     const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
598     Value *ScalarAddr = EscapeMappingValue.first;
599 
600     // Reload the demoted instruction in the optimized version of the SCoP.
601     Value *EscapeInstReload =
602         Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
603     EscapeInstReload =
604         Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
605 
606     // Create the merge PHI that merges the optimized and unoptimized version.
607     PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
608                                         EscapeInst->getName() + ".merge");
609     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
610 
611     // Add the respective values to the merge PHI.
612     MergePHI->addIncoming(EscapeInstReload, OptExitBB);
613     MergePHI->addIncoming(EscapeInst, ExitBB);
614 
615     // The information of scalar evolution about the escaping instruction needs
616     // to be revoked so the new merged instruction will be used.
617     if (SE.isSCEVable(EscapeInst->getType()))
618       SE.forgetValue(EscapeInst);
619 
620     // Replace all uses of the demoted instruction with the merge PHI.
621     for (Instruction *EUser : EscapeUsers)
622       EUser->replaceUsesOfWith(EscapeInst, MergePHI);
623   }
624 }
625 
626 void BlockGenerator::findOutsideUsers(Scop &S) {
627   for (auto &Array : S.arrays()) {
628 
629     if (Array->getNumberOfDimensions() != 0)
630       continue;
631 
632     if (Array->isPHIKind())
633       continue;
634 
635     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
636 
637     if (!Inst)
638       continue;
639 
640     // Scop invariant hoisting moves some of the base pointers out of the scop.
641     // We can ignore these, as the invariant load hoisting already registers the
642     // relevant outside users.
643     if (!S.contains(Inst))
644       continue;
645 
646     handleOutsideUsers(S, Array);
647   }
648 }
649 
650 void BlockGenerator::createExitPHINodeMerges(Scop &S) {
651   if (S.hasSingleExitEdge())
652     return;
653 
654   auto *ExitBB = S.getExitingBlock();
655   auto *MergeBB = S.getExit();
656   auto *AfterMergeBB = MergeBB->getSingleSuccessor();
657   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
658   if (OptExitBB == ExitBB)
659     OptExitBB = *(++pred_begin(MergeBB));
660 
661   Builder.SetInsertPoint(OptExitBB->getTerminator());
662 
663   for (auto &SAI : S.arrays()) {
664     auto *Val = SAI->getBasePtr();
665 
666     // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
667     // the original PHI's value or the reloaded incoming values from the
668     // generated code. An llvm::Value is merged between the original code's
669     // value or the generated one.
670     if (!SAI->isExitPHIKind())
671       continue;
672 
673     PHINode *PHI = dyn_cast<PHINode>(Val);
674     if (!PHI)
675       continue;
676 
677     if (PHI->getParent() != AfterMergeBB)
678       continue;
679 
680     std::string Name = PHI->getName();
681     Value *ScalarAddr = getOrCreateAlloca(SAI);
682     Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
683     Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
684     Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
685     assert((!isa<Instruction>(OriginalValue) ||
686             cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
687            "Original value must no be one we just generated.");
688     auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
689     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
690     MergePHI->addIncoming(Reload, OptExitBB);
691     MergePHI->addIncoming(OriginalValue, ExitBB);
692     int Idx = PHI->getBasicBlockIndex(MergeBB);
693     PHI->setIncomingValue(Idx, MergePHI);
694   }
695 }
696 
697 void BlockGenerator::invalidateScalarEvolution(Scop &S) {
698   for (auto &Stmt : S)
699     if (Stmt.isCopyStmt())
700       continue;
701     else if (Stmt.isBlockStmt())
702       for (auto &Inst : *Stmt.getBasicBlock())
703         SE.forgetValue(&Inst);
704     else if (Stmt.isRegionStmt())
705       for (auto *BB : Stmt.getRegion()->blocks())
706         for (auto &Inst : *BB)
707           SE.forgetValue(&Inst);
708     else
709       llvm_unreachable("Unexpected statement type found");
710 }
711 
712 void BlockGenerator::finalizeSCoP(Scop &S) {
713   findOutsideUsers(S);
714   createScalarInitialization(S);
715   createExitPHINodeMerges(S);
716   createScalarFinalization(S);
717   invalidateScalarEvolution(S);
718 }
719 
720 VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
721                                            std::vector<LoopToScevMapT> &VLTS,
722                                            isl_map *Schedule)
723     : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
724   assert(Schedule && "No statement domain provided");
725 }
726 
727 Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
728                                             ValueMapT &VectorMap,
729                                             VectorValueMapT &ScalarMaps,
730                                             Loop *L) {
731   if (Value *NewValue = VectorMap.lookup(Old))
732     return NewValue;
733 
734   int Width = getVectorWidth();
735 
736   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
737 
738   for (int Lane = 0; Lane < Width; Lane++)
739     Vector = Builder.CreateInsertElement(
740         Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
741         Builder.getInt32(Lane));
742 
743   VectorMap[Old] = Vector;
744 
745   return Vector;
746 }
747 
748 Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
749   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
750   assert(PointerTy && "PointerType expected");
751 
752   Type *ScalarType = PointerTy->getElementType();
753   VectorType *VectorType = VectorType::get(ScalarType, Width);
754 
755   return PointerType::getUnqual(VectorType);
756 }
757 
758 Value *VectorBlockGenerator::generateStrideOneLoad(
759     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
760     __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
761   unsigned VectorWidth = getVectorWidth();
762   auto *Pointer = Load->getPointerOperand();
763   Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
764   unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
765 
766   Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
767                                                VLTS[Offset], NewAccesses);
768   Value *VectorPtr =
769       Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
770   LoadInst *VecLoad =
771       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
772   if (!Aligned)
773     VecLoad->setAlignment(8);
774 
775   if (NegativeStride) {
776     SmallVector<Constant *, 16> Indices;
777     for (int i = VectorWidth - 1; i >= 0; i--)
778       Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
779     Constant *SV = llvm::ConstantVector::get(Indices);
780     Value *RevVecLoad = Builder.CreateShuffleVector(
781         VecLoad, VecLoad, SV, Load->getName() + "_reverse");
782     return RevVecLoad;
783   }
784 
785   return VecLoad;
786 }
787 
788 Value *VectorBlockGenerator::generateStrideZeroLoad(
789     ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
790     __isl_keep isl_id_to_ast_expr *NewAccesses) {
791   auto *Pointer = Load->getPointerOperand();
792   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
793   Value *NewPointer =
794       generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
795   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
796                                            Load->getName() + "_p_vec_p");
797   LoadInst *ScalarLoad =
798       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
799 
800   if (!Aligned)
801     ScalarLoad->setAlignment(8);
802 
803   Constant *SplatVector = Constant::getNullValue(
804       VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
805 
806   Value *VectorLoad = Builder.CreateShuffleVector(
807       ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
808   return VectorLoad;
809 }
810 
811 Value *VectorBlockGenerator::generateUnknownStrideLoad(
812     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
813     __isl_keep isl_id_to_ast_expr *NewAccesses) {
814   int VectorWidth = getVectorWidth();
815   auto *Pointer = Load->getPointerOperand();
816   VectorType *VectorType = VectorType::get(
817       dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
818 
819   Value *Vector = UndefValue::get(VectorType);
820 
821   for (int i = 0; i < VectorWidth; i++) {
822     Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
823                                                  VLTS[i], NewAccesses);
824     Value *ScalarLoad =
825         Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
826     Vector = Builder.CreateInsertElement(
827         Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
828   }
829 
830   return Vector;
831 }
832 
833 void VectorBlockGenerator::generateLoad(
834     ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
835     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
836   if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
837     VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
838                                                 Load->getName() + "_p");
839     return;
840   }
841 
842   if (!VectorType::isValidElementType(Load->getType())) {
843     for (int i = 0; i < getVectorWidth(); i++)
844       ScalarMaps[i][Load] =
845           generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
846     return;
847   }
848 
849   const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
850 
851   // Make sure we have scalar values available to access the pointer to
852   // the data location.
853   extractScalarValues(Load, VectorMap, ScalarMaps);
854 
855   Value *NewLoad;
856   if (Access.isStrideZero(isl_map_copy(Schedule)))
857     NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
858   else if (Access.isStrideOne(isl_map_copy(Schedule)))
859     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
860   else if (Access.isStrideX(isl_map_copy(Schedule), -1))
861     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
862   else
863     NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
864 
865   VectorMap[Load] = NewLoad;
866 }
867 
868 void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
869                                          ValueMapT &VectorMap,
870                                          VectorValueMapT &ScalarMaps) {
871   int VectorWidth = getVectorWidth();
872   Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
873                                      ScalarMaps, getLoopForStmt(Stmt));
874 
875   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
876 
877   const CastInst *Cast = dyn_cast<CastInst>(Inst);
878   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
879   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
880 }
881 
882 void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
883                                           ValueMapT &VectorMap,
884                                           VectorValueMapT &ScalarMaps) {
885   Loop *L = getLoopForStmt(Stmt);
886   Value *OpZero = Inst->getOperand(0);
887   Value *OpOne = Inst->getOperand(1);
888 
889   Value *NewOpZero, *NewOpOne;
890   NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
891   NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
892 
893   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
894                                        Inst->getName() + "p_vec");
895   VectorMap[Inst] = NewInst;
896 }
897 
898 void VectorBlockGenerator::copyStore(
899     ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
900     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
901   const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
902 
903   auto *Pointer = Store->getPointerOperand();
904   Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
905                                  ScalarMaps, getLoopForStmt(Stmt));
906 
907   // Make sure we have scalar values available to access the pointer to
908   // the data location.
909   extractScalarValues(Store, VectorMap, ScalarMaps);
910 
911   if (Access.isStrideOne(isl_map_copy(Schedule))) {
912     Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
913     Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
914                                                  VLTS[0], NewAccesses);
915 
916     Value *VectorPtr =
917         Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
918     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
919 
920     if (!Aligned)
921       Store->setAlignment(8);
922   } else {
923     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
924       Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
925       Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
926                                                    VLTS[i], NewAccesses);
927       Builder.CreateStore(Scalar, NewPointer);
928     }
929   }
930 }
931 
932 bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
933                                              ValueMapT &VectorMap) {
934   for (Value *Operand : Inst->operands())
935     if (VectorMap.count(Operand))
936       return true;
937   return false;
938 }
939 
940 bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
941                                                ValueMapT &VectorMap,
942                                                VectorValueMapT &ScalarMaps) {
943   bool HasVectorOperand = false;
944   int VectorWidth = getVectorWidth();
945 
946   for (Value *Operand : Inst->operands()) {
947     ValueMapT::iterator VecOp = VectorMap.find(Operand);
948 
949     if (VecOp == VectorMap.end())
950       continue;
951 
952     HasVectorOperand = true;
953     Value *NewVector = VecOp->second;
954 
955     for (int i = 0; i < VectorWidth; ++i) {
956       ValueMapT &SM = ScalarMaps[i];
957 
958       // If there is one scalar extracted, all scalar elements should have
959       // already been extracted by the code here. So no need to check for the
960       // existence of all of them.
961       if (SM.count(Operand))
962         break;
963 
964       SM[Operand] =
965           Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
966     }
967   }
968 
969   return HasVectorOperand;
970 }
971 
972 void VectorBlockGenerator::copyInstScalarized(
973     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
974     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
975   bool HasVectorOperand;
976   int VectorWidth = getVectorWidth();
977 
978   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
979 
980   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
981     BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
982                                     VLTS[VectorLane], NewAccesses);
983 
984   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
985     return;
986 
987   // Make the result available as vector value.
988   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
989   Value *Vector = UndefValue::get(VectorType);
990 
991   for (int i = 0; i < VectorWidth; i++)
992     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
993                                          Builder.getInt32(i));
994 
995   VectorMap[Inst] = Vector;
996 }
997 
998 int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
999 
1000 void VectorBlockGenerator::copyInstruction(
1001     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1002     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1003   // Terminator instructions control the control flow. They are explicitly
1004   // expressed in the clast and do not need to be copied.
1005   if (Inst->isTerminator())
1006     return;
1007 
1008   if (canSyntheziseInStmt(Stmt, Inst))
1009     return;
1010 
1011   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
1012     generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
1013     return;
1014   }
1015 
1016   if (hasVectorOperands(Inst, VectorMap)) {
1017     if (auto *Store = dyn_cast<StoreInst>(Inst)) {
1018       // Identified as redundant by -polly-simplify.
1019       if (!Stmt.getArrayAccessOrNULLFor(Store))
1020         return;
1021 
1022       copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
1023       return;
1024     }
1025 
1026     if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1027       copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
1028       return;
1029     }
1030 
1031     if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1032       copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
1033       return;
1034     }
1035 
1036     // Falltrough: We generate scalar instructions, if we don't know how to
1037     // generate vector code.
1038   }
1039 
1040   copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
1041 }
1042 
1043 void VectorBlockGenerator::generateScalarVectorLoads(
1044     ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1045   for (MemoryAccess *MA : Stmt) {
1046     if (MA->isArrayKind() || MA->isWrite())
1047       continue;
1048 
1049     auto *Address = getOrCreateAlloca(*MA);
1050     Type *VectorPtrType = getVectorPtrTy(Address, 1);
1051     Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1052                                              Address->getName() + "_p_vec_p");
1053     auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1054     Constant *SplatVector = Constant::getNullValue(
1055         VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1056 
1057     Value *VectorVal = Builder.CreateShuffleVector(
1058         Val, Val, SplatVector, Address->getName() + "_p_splat");
1059     VectorBlockMap[MA->getAccessValue()] = VectorVal;
1060   }
1061 }
1062 
1063 void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1064   for (MemoryAccess *MA : Stmt) {
1065     if (MA->isArrayKind() || MA->isRead())
1066       continue;
1067 
1068     llvm_unreachable("Scalar stores not expected in vector loop");
1069   }
1070 }
1071 
1072 void VectorBlockGenerator::copyStmt(
1073     ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1074   assert(Stmt.isBlockStmt() &&
1075          "TODO: Only block statements can be copied by the vector block "
1076          "generator");
1077 
1078   BasicBlock *BB = Stmt.getBasicBlock();
1079   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1080                                   &*Builder.GetInsertPoint(), &DT, &LI);
1081   CopyBB->setName("polly.stmt." + BB->getName());
1082   Builder.SetInsertPoint(&CopyBB->front());
1083 
1084   // Create two maps that store the mapping from the original instructions of
1085   // the old basic block to their copies in the new basic block. Those maps
1086   // are basic block local.
1087   //
1088   // As vector code generation is supported there is one map for scalar values
1089   // and one for vector values.
1090   //
1091   // In case we just do scalar code generation, the vectorMap is not used and
1092   // the scalarMap has just one dimension, which contains the mapping.
1093   //
1094   // In case vector code generation is done, an instruction may either appear
1095   // in the vector map once (as it is calculating >vectorwidth< values at a
1096   // time. Or (if the values are calculated using scalar operations), it
1097   // appears once in every dimension of the scalarMap.
1098   VectorValueMapT ScalarBlockMap(getVectorWidth());
1099   ValueMapT VectorBlockMap;
1100 
1101   generateScalarVectorLoads(Stmt, VectorBlockMap);
1102 
1103   for (Instruction &Inst : *BB)
1104     copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1105 
1106   verifyNoScalarStores(Stmt);
1107 }
1108 
1109 BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1110                                              BasicBlock *BBCopy) {
1111 
1112   BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1113   BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1114 
1115   if (BBCopyIDom)
1116     DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1117 
1118   return BBCopyIDom;
1119 }
1120 
1121 // This is to determine whether an llvm::Value (defined in @p BB) is usable when
1122 // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1123 // does not work in cases where the exit block has edges from outside the
1124 // region. In that case the llvm::Value would never be usable in in the exit
1125 // block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1126 // for the subregion's exiting edges only. We need to determine whether an
1127 // llvm::Value is usable in there. We do this by checking whether it dominates
1128 // all exiting blocks individually.
1129 static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1130                                       BasicBlock *BB) {
1131   for (auto ExitingBB : predecessors(R->getExit())) {
1132     // Check for non-subregion incoming edges.
1133     if (!R->contains(ExitingBB))
1134       continue;
1135 
1136     if (!DT.dominates(BB, ExitingBB))
1137       return false;
1138   }
1139 
1140   return true;
1141 }
1142 
1143 // Find the direct dominator of the subregion's exit block if the subregion was
1144 // simplified.
1145 static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1146   BasicBlock *Common = nullptr;
1147   for (auto ExitingBB : predecessors(R->getExit())) {
1148     // Check for non-subregion incoming edges.
1149     if (!R->contains(ExitingBB))
1150       continue;
1151 
1152     // First exiting edge.
1153     if (!Common) {
1154       Common = ExitingBB;
1155       continue;
1156     }
1157 
1158     Common = DT.findNearestCommonDominator(Common, ExitingBB);
1159   }
1160 
1161   assert(Common && R->contains(Common));
1162   return Common;
1163 }
1164 
1165 void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
1166                                isl_id_to_ast_expr *IdToAstExp) {
1167   assert(Stmt.isRegionStmt() &&
1168          "Only region statements can be copied by the region generator");
1169 
1170   // Forget all old mappings.
1171   BlockMap.clear();
1172   RegionMaps.clear();
1173   IncompletePHINodeMap.clear();
1174 
1175   // Collection of all values related to this subregion.
1176   ValueMapT ValueMap;
1177 
1178   // The region represented by the statement.
1179   Region *R = Stmt.getRegion();
1180 
1181   // Create a dedicated entry for the region where we can reload all demoted
1182   // inputs.
1183   BasicBlock *EntryBB = R->getEntry();
1184   BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1185                                        &*Builder.GetInsertPoint(), &DT, &LI);
1186   EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1187   Builder.SetInsertPoint(&EntryBBCopy->front());
1188 
1189   ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1190   generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1191 
1192   for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1193     if (!R->contains(*PI))
1194       BlockMap[*PI] = EntryBBCopy;
1195 
1196   // Iterate over all blocks in the region in a breadth-first search.
1197   std::deque<BasicBlock *> Blocks;
1198   SmallSetVector<BasicBlock *, 8> SeenBlocks;
1199   Blocks.push_back(EntryBB);
1200   SeenBlocks.insert(EntryBB);
1201 
1202   while (!Blocks.empty()) {
1203     BasicBlock *BB = Blocks.front();
1204     Blocks.pop_front();
1205 
1206     // First split the block and update dominance information.
1207     BasicBlock *BBCopy = splitBB(BB);
1208     BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1209 
1210     // Get the mapping for this block and initialize it with either the scalar
1211     // loads from the generated entering block (which dominates all blocks of
1212     // this subregion) or the maps of the immediate dominator, if part of the
1213     // subregion. The latter necessarily includes the former.
1214     ValueMapT *InitBBMap;
1215     if (BBCopyIDom) {
1216       assert(RegionMaps.count(BBCopyIDom));
1217       InitBBMap = &RegionMaps[BBCopyIDom];
1218     } else
1219       InitBBMap = &EntryBBMap;
1220     auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1221     ValueMapT &RegionMap = Inserted.first->second;
1222 
1223     // Copy the block with the BlockGenerator.
1224     Builder.SetInsertPoint(&BBCopy->front());
1225     copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1226 
1227     // In order to remap PHI nodes we store also basic block mappings.
1228     BlockMap[BB] = BBCopy;
1229 
1230     // Add values to incomplete PHI nodes waiting for this block to be copied.
1231     for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1232       addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1233     IncompletePHINodeMap[BB].clear();
1234 
1235     // And continue with new successors inside the region.
1236     for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1237       if (R->contains(*SI) && SeenBlocks.insert(*SI))
1238         Blocks.push_back(*SI);
1239 
1240     // Remember value in case it is visible after this subregion.
1241     if (isDominatingSubregionExit(DT, R, BB))
1242       ValueMap.insert(RegionMap.begin(), RegionMap.end());
1243   }
1244 
1245   // Now create a new dedicated region exit block and add it to the region map.
1246   BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1247                                       &*Builder.GetInsertPoint(), &DT, &LI);
1248   ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1249   BlockMap[R->getExit()] = ExitBBCopy;
1250 
1251   BasicBlock *ExitDomBBCopy = BlockMap.lookup(findExitDominator(DT, R));
1252   assert(ExitDomBBCopy &&
1253          "Common exit dominator must be within region; at least the entry node "
1254          "must match");
1255   DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1256 
1257   // As the block generator doesn't handle control flow we need to add the
1258   // region control flow by hand after all blocks have been copied.
1259   for (BasicBlock *BB : SeenBlocks) {
1260 
1261     BasicBlock *BBCopy = BlockMap[BB];
1262     TerminatorInst *TI = BB->getTerminator();
1263     if (isa<UnreachableInst>(TI)) {
1264       while (!BBCopy->empty())
1265         BBCopy->begin()->eraseFromParent();
1266       new UnreachableInst(BBCopy->getContext(), BBCopy);
1267       continue;
1268     }
1269 
1270     Instruction *BICopy = BBCopy->getTerminator();
1271 
1272     ValueMapT &RegionMap = RegionMaps[BBCopy];
1273     RegionMap.insert(BlockMap.begin(), BlockMap.end());
1274 
1275     Builder.SetInsertPoint(BICopy);
1276     copyInstScalar(Stmt, TI, RegionMap, LTS);
1277     BICopy->eraseFromParent();
1278   }
1279 
1280   // Add counting PHI nodes to all loops in the region that can be used as
1281   // replacement for SCEVs refering to the old loop.
1282   for (BasicBlock *BB : SeenBlocks) {
1283     Loop *L = LI.getLoopFor(BB);
1284     if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1285       continue;
1286 
1287     BasicBlock *BBCopy = BlockMap[BB];
1288     Value *NullVal = Builder.getInt32(0);
1289     PHINode *LoopPHI =
1290         PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1291     Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1292         LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1293     LoopPHI->insertBefore(&BBCopy->front());
1294     LoopPHIInc->insertBefore(BBCopy->getTerminator());
1295 
1296     for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1297       if (!R->contains(PredBB))
1298         continue;
1299       if (L->contains(PredBB))
1300         LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1301       else
1302         LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1303     }
1304 
1305     for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1306       if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1307         LoopPHI->addIncoming(NullVal, PredBBCopy);
1308 
1309     LTS[L] = SE.getUnknown(LoopPHI);
1310   }
1311 
1312   // Continue generating code in the exit block.
1313   Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1314 
1315   // Write values visible to other statements.
1316   generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1317   BlockMap.clear();
1318   RegionMaps.clear();
1319   IncompletePHINodeMap.clear();
1320 }
1321 
1322 PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1323                                        ValueMapT &BBMap, Loop *L) {
1324   ScopStmt *Stmt = MA->getStatement();
1325   Region *SubR = Stmt->getRegion();
1326   auto Incoming = MA->getIncoming();
1327 
1328   PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1329   PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1330   BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1331 
1332   // This can happen if the subregion is simplified after the ScopStmts
1333   // have been created; simplification happens as part of CodeGeneration.
1334   if (OrigPHI->getParent() != SubR->getExit()) {
1335     BasicBlock *FormerExit = SubR->getExitingBlock();
1336     if (FormerExit)
1337       NewSubregionExit = BlockMap.lookup(FormerExit);
1338   }
1339 
1340   PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1341                                     "polly." + OrigPHI->getName(),
1342                                     NewSubregionExit->getFirstNonPHI());
1343 
1344   // Add the incoming values to the PHI.
1345   for (auto &Pair : Incoming) {
1346     BasicBlock *OrigIncomingBlock = Pair.first;
1347     BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock);
1348     Builder.SetInsertPoint(NewIncomingBlock->getTerminator());
1349     assert(RegionMaps.count(NewIncomingBlock));
1350     ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock];
1351 
1352     Value *OrigIncomingValue = Pair.second;
1353     Value *NewIncomingValue =
1354         getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1355     NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock);
1356   }
1357 
1358   return NewPHI;
1359 }
1360 
1361 Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1362                                       ValueMapT &BBMap) {
1363   ScopStmt *Stmt = MA->getStatement();
1364 
1365   // TODO: Add some test cases that ensure this is really the right choice.
1366   Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1367 
1368   if (MA->isAnyPHIKind()) {
1369     auto Incoming = MA->getIncoming();
1370     assert(!Incoming.empty() &&
1371            "PHI WRITEs must have originate from at least one incoming block");
1372 
1373     // If there is only one incoming value, we do not need to create a PHI.
1374     if (Incoming.size() == 1) {
1375       Value *OldVal = Incoming[0].second;
1376       return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1377     }
1378 
1379     return buildExitPHI(MA, LTS, BBMap, L);
1380   }
1381 
1382   // MemoryKind::Value accesses leaving the subregion must dominate the exit
1383   // block; just pass the copied value.
1384   Value *OldVal = MA->getAccessValue();
1385   return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1386 }
1387 
1388 void RegionGenerator::generateScalarStores(
1389     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1390     __isl_keep isl_id_to_ast_expr *NewAccesses) {
1391   assert(Stmt.getRegion() &&
1392          "Block statements need to use the generateScalarStores() "
1393          "function in the BlockGenerator");
1394 
1395   for (MemoryAccess *MA : Stmt) {
1396     if (MA->isOriginalArrayKind() || MA->isRead())
1397       continue;
1398 
1399     Value *NewVal = getExitScalar(MA, LTS, BBMap);
1400     Value *Address =
1401         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
1402     assert((!isa<Instruction>(NewVal) ||
1403             DT.dominates(cast<Instruction>(NewVal)->getParent(),
1404                          Builder.GetInsertBlock())) &&
1405            "Domination violation");
1406     assert((!isa<Instruction>(Address) ||
1407             DT.dominates(cast<Instruction>(Address)->getParent(),
1408                          Builder.GetInsertBlock())) &&
1409            "Domination violation");
1410     Builder.CreateStore(NewVal, Address);
1411   }
1412 }
1413 
1414 void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
1415                                       PHINode *PHICopy, BasicBlock *IncomingBB,
1416                                       LoopToScevMapT &LTS) {
1417   // If the incoming block was not yet copied mark this PHI as incomplete.
1418   // Once the block will be copied the incoming value will be added.
1419   BasicBlock *BBCopy = BlockMap[IncomingBB];
1420   if (!BBCopy) {
1421     assert(Stmt.contains(IncomingBB) &&
1422            "Bad incoming block for PHI in non-affine region");
1423     IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1424     return;
1425   }
1426 
1427   assert(RegionMaps.count(BBCopy) && "Incoming PHI block did not have a BBMap");
1428   ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1429 
1430   Value *OpCopy = nullptr;
1431 
1432   if (Stmt.contains(IncomingBB)) {
1433     Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1434 
1435     // If the current insert block is different from the PHIs incoming block
1436     // change it, otherwise do not.
1437     auto IP = Builder.GetInsertPoint();
1438     if (IP->getParent() != BBCopy)
1439       Builder.SetInsertPoint(BBCopy->getTerminator());
1440     OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1441     if (IP->getParent() != BBCopy)
1442       Builder.SetInsertPoint(&*IP);
1443   } else {
1444     // All edges from outside the non-affine region become a single edge
1445     // in the new copy of the non-affine region. Make sure to only add the
1446     // corresponding edge the first time we encounter a basic block from
1447     // outside the non-affine region.
1448     if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1449       return;
1450 
1451     // Get the reloaded value.
1452     OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1453   }
1454 
1455   assert(OpCopy && "Incoming PHI value was not copied properly");
1456   assert(BBCopy && "Incoming PHI block was not copied properly");
1457   PHICopy->addIncoming(OpCopy, BBCopy);
1458 }
1459 
1460 void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1461                                          ValueMapT &BBMap,
1462                                          LoopToScevMapT &LTS) {
1463   unsigned NumIncoming = PHI->getNumIncomingValues();
1464   PHINode *PHICopy =
1465       Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1466   PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1467   BBMap[PHI] = PHICopy;
1468 
1469   for (BasicBlock *IncomingBB : PHI->blocks())
1470     addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1471 }
1472