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