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