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/Analysis/Utils/Local.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.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 =
562         Stmt.getDomain().intersect_params(Stmt.getParent()->getContext());
563     auto AccDom = MA->getAccessRelation().domain();
564     assert(!StmtDom.is_subset(AccDom).is_false() &&
565            "Scalar must be loaded in all statement instances");
566 #endif
567 
568     auto *Address =
569         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
570     assert((!isa<Instruction>(Address) ||
571             DT.dominates(cast<Instruction>(Address)->getParent(),
572                          Builder.GetInsertBlock())) &&
573            "Domination violation");
574     BBMap[MA->getAccessValue()] =
575         Builder.CreateLoad(Address, Address->getName() + ".reload");
576   }
577 }
578 
579 Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt,
580                                               const isl::set &Subdomain) {
581   isl::ast_build AstBuild = Stmt.getAstBuild();
582   isl::set Domain = Stmt.getDomain();
583 
584   isl::union_map USchedule = AstBuild.get_schedule();
585   USchedule = USchedule.intersect_domain(Domain);
586 
587   assert(!USchedule.is_empty());
588   isl::map Schedule = isl::map::from_union_map(USchedule);
589 
590   isl::set ScheduledDomain = Schedule.range();
591   isl::set ScheduledSet = Subdomain.apply(Schedule);
592 
593   isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
594 
595   isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
596   Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
597   IsInSetExpr = Builder.CreateICmpNE(
598       IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
599 
600   return IsInSetExpr;
601 }
602 
603 void BlockGenerator::generateConditionalExecution(
604     ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
605     const std::function<void()> &GenThenFunc) {
606   isl::set StmtDom = Stmt.getDomain();
607 
608   // If the condition is a tautology, don't generate a condition around the
609   // code.
610   bool IsPartialWrite =
611       !StmtDom.intersect_params(Stmt.getParent()->getContext())
612            .is_subset(Subdomain);
613   if (!IsPartialWrite) {
614     GenThenFunc();
615     return;
616   }
617 
618   // Generate the condition.
619   Value *Cond = buildContainsCondition(Stmt, Subdomain);
620 
621   // Don't call GenThenFunc if it is never executed. An ast index expression
622   // might not be defined in this case.
623   if (auto *Const = dyn_cast<ConstantInt>(Cond))
624     if (Const->isZero())
625       return;
626 
627   BasicBlock *HeadBlock = Builder.GetInsertBlock();
628   StringRef BlockName = HeadBlock->getName();
629 
630   // Generate the conditional block.
631   SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr,
632                             &DT, &LI);
633   BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator());
634   BasicBlock *ThenBlock = Branch->getSuccessor(0);
635   BasicBlock *TailBlock = Branch->getSuccessor(1);
636 
637   // Assign descriptive names.
638   if (auto *CondInst = dyn_cast<Instruction>(Cond))
639     CondInst->setName("polly." + Subject + ".cond");
640   ThenBlock->setName(BlockName + "." + Subject + ".partial");
641   TailBlock->setName(BlockName + ".cont");
642 
643   // Put the client code into the conditional block and continue in the merge
644   // block afterwards.
645   Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt());
646   GenThenFunc();
647   Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt());
648 }
649 
650 void BlockGenerator::generateScalarStores(
651     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
652     __isl_keep isl_id_to_ast_expr *NewAccesses) {
653   Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
654 
655   assert(Stmt.isBlockStmt() &&
656          "Region statements need to use the generateScalarStores() function in "
657          "the RegionGenerator");
658 
659   for (MemoryAccess *MA : Stmt) {
660     if (MA->isOriginalArrayKind() || MA->isRead())
661       continue;
662 
663     isl::set AccDom = MA->getAccessRelation().domain();
664     std::string Subject = MA->getId().get_name();
665 
666     generateConditionalExecution(
667         Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
668           Value *Val = MA->getAccessValue();
669           if (MA->isAnyPHIKind()) {
670             assert(MA->getIncoming().size() >= 1 &&
671                    "Block statements have exactly one exiting block, or "
672                    "multiple but "
673                    "with same incoming block and value");
674             assert(std::all_of(MA->getIncoming().begin(),
675                                MA->getIncoming().end(),
676                                [&](std::pair<BasicBlock *, Value *> p) -> bool {
677                                  return p.first == Stmt.getBasicBlock();
678                                }) &&
679                    "Incoming block must be statement's block");
680             Val = MA->getIncoming()[0].second;
681           }
682           auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
683                                             BBMap, NewAccesses);
684 
685           Val = getNewValue(Stmt, Val, BBMap, LTS, L);
686           assert((!isa<Instruction>(Val) ||
687                   DT.dominates(cast<Instruction>(Val)->getParent(),
688                                Builder.GetInsertBlock())) &&
689                  "Domination violation");
690           assert((!isa<Instruction>(Address) ||
691                   DT.dominates(cast<Instruction>(Address)->getParent(),
692                                Builder.GetInsertBlock())) &&
693                  "Domination violation");
694 
695           // The new Val might have a different type than the old Val due to
696           // ScalarEvolution looking through bitcasts.
697           if (Val->getType() != Address->getType()->getPointerElementType())
698             Address = Builder.CreateBitOrPointerCast(
699                 Address, Val->getType()->getPointerTo());
700 
701           Builder.CreateStore(Val, Address);
702         });
703   }
704 }
705 
706 void BlockGenerator::createScalarInitialization(Scop &S) {
707   BasicBlock *ExitBB = S.getExit();
708   BasicBlock *PreEntryBB = S.getEnteringBlock();
709 
710   Builder.SetInsertPoint(&*StartBlock->begin());
711 
712   for (auto &Array : S.arrays()) {
713     if (Array->getNumberOfDimensions() != 0)
714       continue;
715     if (Array->isPHIKind()) {
716       // For PHI nodes, the only values we need to store are the ones that
717       // reach the PHI node from outside the region. In general there should
718       // only be one such incoming edge and this edge should enter through
719       // 'PreEntryBB'.
720       auto PHI = cast<PHINode>(Array->getBasePtr());
721 
722       for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
723         if (!S.contains(*BI) && *BI != PreEntryBB)
724           llvm_unreachable("Incoming edges from outside the scop should always "
725                            "come from PreEntryBB");
726 
727       int Idx = PHI->getBasicBlockIndex(PreEntryBB);
728       if (Idx < 0)
729         continue;
730 
731       Value *ScalarValue = PHI->getIncomingValue(Idx);
732 
733       Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
734       continue;
735     }
736 
737     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
738 
739     if (Inst && S.contains(Inst))
740       continue;
741 
742     // PHI nodes that are not marked as such in their SAI object are either exit
743     // PHI nodes we model as common scalars but without initialization, or
744     // incoming phi nodes that need to be initialized. Check if the first is the
745     // case for Inst and do not create and initialize memory if so.
746     if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
747       if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
748         continue;
749 
750     Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
751   }
752 }
753 
754 void BlockGenerator::createScalarFinalization(Scop &S) {
755   // The exit block of the __unoptimized__ region.
756   BasicBlock *ExitBB = S.getExitingBlock();
757   // The merge block __just after__ the region and the optimized region.
758   BasicBlock *MergeBB = S.getExit();
759 
760   // The exit block of the __optimized__ region.
761   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
762   if (OptExitBB == ExitBB)
763     OptExitBB = *(++pred_begin(MergeBB));
764 
765   Builder.SetInsertPoint(OptExitBB->getTerminator());
766   for (const auto &EscapeMapping : EscapeMap) {
767     // Extract the escaping instruction and the escaping users as well as the
768     // alloca the instruction was demoted to.
769     Instruction *EscapeInst = EscapeMapping.first;
770     const auto &EscapeMappingValue = EscapeMapping.second;
771     const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
772     Value *ScalarAddr = EscapeMappingValue.first;
773 
774     // Reload the demoted instruction in the optimized version of the SCoP.
775     Value *EscapeInstReload =
776         Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
777     EscapeInstReload =
778         Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
779 
780     // Create the merge PHI that merges the optimized and unoptimized version.
781     PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
782                                         EscapeInst->getName() + ".merge");
783     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
784 
785     // Add the respective values to the merge PHI.
786     MergePHI->addIncoming(EscapeInstReload, OptExitBB);
787     MergePHI->addIncoming(EscapeInst, ExitBB);
788 
789     // The information of scalar evolution about the escaping instruction needs
790     // to be revoked so the new merged instruction will be used.
791     if (SE.isSCEVable(EscapeInst->getType()))
792       SE.forgetValue(EscapeInst);
793 
794     // Replace all uses of the demoted instruction with the merge PHI.
795     for (Instruction *EUser : EscapeUsers)
796       EUser->replaceUsesOfWith(EscapeInst, MergePHI);
797   }
798 }
799 
800 void BlockGenerator::findOutsideUsers(Scop &S) {
801   for (auto &Array : S.arrays()) {
802 
803     if (Array->getNumberOfDimensions() != 0)
804       continue;
805 
806     if (Array->isPHIKind())
807       continue;
808 
809     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
810 
811     if (!Inst)
812       continue;
813 
814     // Scop invariant hoisting moves some of the base pointers out of the scop.
815     // We can ignore these, as the invariant load hoisting already registers the
816     // relevant outside users.
817     if (!S.contains(Inst))
818       continue;
819 
820     handleOutsideUsers(S, Array);
821   }
822 }
823 
824 void BlockGenerator::createExitPHINodeMerges(Scop &S) {
825   if (S.hasSingleExitEdge())
826     return;
827 
828   auto *ExitBB = S.getExitingBlock();
829   auto *MergeBB = S.getExit();
830   auto *AfterMergeBB = MergeBB->getSingleSuccessor();
831   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
832   if (OptExitBB == ExitBB)
833     OptExitBB = *(++pred_begin(MergeBB));
834 
835   Builder.SetInsertPoint(OptExitBB->getTerminator());
836 
837   for (auto &SAI : S.arrays()) {
838     auto *Val = SAI->getBasePtr();
839 
840     // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
841     // the original PHI's value or the reloaded incoming values from the
842     // generated code. An llvm::Value is merged between the original code's
843     // value or the generated one.
844     if (!SAI->isExitPHIKind())
845       continue;
846 
847     PHINode *PHI = dyn_cast<PHINode>(Val);
848     if (!PHI)
849       continue;
850 
851     if (PHI->getParent() != AfterMergeBB)
852       continue;
853 
854     std::string Name = PHI->getName();
855     Value *ScalarAddr = getOrCreateAlloca(SAI);
856     Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
857     Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
858     Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
859     assert((!isa<Instruction>(OriginalValue) ||
860             cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
861            "Original value must no be one we just generated.");
862     auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
863     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
864     MergePHI->addIncoming(Reload, OptExitBB);
865     MergePHI->addIncoming(OriginalValue, ExitBB);
866     int Idx = PHI->getBasicBlockIndex(MergeBB);
867     PHI->setIncomingValue(Idx, MergePHI);
868   }
869 }
870 
871 void BlockGenerator::invalidateScalarEvolution(Scop &S) {
872   for (auto &Stmt : S)
873     if (Stmt.isCopyStmt())
874       continue;
875     else if (Stmt.isBlockStmt())
876       for (auto &Inst : *Stmt.getBasicBlock())
877         SE.forgetValue(&Inst);
878     else if (Stmt.isRegionStmt())
879       for (auto *BB : Stmt.getRegion()->blocks())
880         for (auto &Inst : *BB)
881           SE.forgetValue(&Inst);
882     else
883       llvm_unreachable("Unexpected statement type found");
884 
885   // Invalidate SCEV of loops surrounding the EscapeUsers.
886   for (const auto &EscapeMapping : EscapeMap) {
887     const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
888     for (Instruction *EUser : EscapeUsers) {
889       if (Loop *L = LI.getLoopFor(EUser->getParent()))
890         while (L) {
891           SE.forgetLoop(L);
892           L = L->getParentLoop();
893         }
894     }
895   }
896 }
897 
898 void BlockGenerator::finalizeSCoP(Scop &S) {
899   findOutsideUsers(S);
900   createScalarInitialization(S);
901   createExitPHINodeMerges(S);
902   createScalarFinalization(S);
903   invalidateScalarEvolution(S);
904 }
905 
906 VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
907                                            std::vector<LoopToScevMapT> &VLTS,
908                                            isl_map *Schedule)
909     : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
910   assert(Schedule && "No statement domain provided");
911 }
912 
913 Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
914                                             ValueMapT &VectorMap,
915                                             VectorValueMapT &ScalarMaps,
916                                             Loop *L) {
917   if (Value *NewValue = VectorMap.lookup(Old))
918     return NewValue;
919 
920   int Width = getVectorWidth();
921 
922   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
923 
924   for (int Lane = 0; Lane < Width; Lane++)
925     Vector = Builder.CreateInsertElement(
926         Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
927         Builder.getInt32(Lane));
928 
929   VectorMap[Old] = Vector;
930 
931   return Vector;
932 }
933 
934 Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
935   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
936   assert(PointerTy && "PointerType expected");
937 
938   Type *ScalarType = PointerTy->getElementType();
939   VectorType *VectorType = VectorType::get(ScalarType, Width);
940 
941   return PointerType::getUnqual(VectorType);
942 }
943 
944 Value *VectorBlockGenerator::generateStrideOneLoad(
945     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
946     __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
947   unsigned VectorWidth = getVectorWidth();
948   auto *Pointer = Load->getPointerOperand();
949   Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
950   unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
951 
952   Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
953                                                VLTS[Offset], NewAccesses);
954   Value *VectorPtr =
955       Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
956   LoadInst *VecLoad =
957       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
958   if (!Aligned)
959     VecLoad->setAlignment(8);
960 
961   if (NegativeStride) {
962     SmallVector<Constant *, 16> Indices;
963     for (int i = VectorWidth - 1; i >= 0; i--)
964       Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
965     Constant *SV = llvm::ConstantVector::get(Indices);
966     Value *RevVecLoad = Builder.CreateShuffleVector(
967         VecLoad, VecLoad, SV, Load->getName() + "_reverse");
968     return RevVecLoad;
969   }
970 
971   return VecLoad;
972 }
973 
974 Value *VectorBlockGenerator::generateStrideZeroLoad(
975     ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
976     __isl_keep isl_id_to_ast_expr *NewAccesses) {
977   auto *Pointer = Load->getPointerOperand();
978   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
979   Value *NewPointer =
980       generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
981   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
982                                            Load->getName() + "_p_vec_p");
983   LoadInst *ScalarLoad =
984       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
985 
986   if (!Aligned)
987     ScalarLoad->setAlignment(8);
988 
989   Constant *SplatVector = Constant::getNullValue(
990       VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
991 
992   Value *VectorLoad = Builder.CreateShuffleVector(
993       ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
994   return VectorLoad;
995 }
996 
997 Value *VectorBlockGenerator::generateUnknownStrideLoad(
998     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
999     __isl_keep isl_id_to_ast_expr *NewAccesses) {
1000   int VectorWidth = getVectorWidth();
1001   auto *Pointer = Load->getPointerOperand();
1002   VectorType *VectorType = VectorType::get(
1003       dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
1004 
1005   Value *Vector = UndefValue::get(VectorType);
1006 
1007   for (int i = 0; i < VectorWidth; i++) {
1008     Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
1009                                                  VLTS[i], NewAccesses);
1010     Value *ScalarLoad =
1011         Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
1012     Vector = Builder.CreateInsertElement(
1013         Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
1014   }
1015 
1016   return Vector;
1017 }
1018 
1019 void VectorBlockGenerator::generateLoad(
1020     ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
1021     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1022   if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
1023     VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
1024                                                 Load->getName() + "_p");
1025     return;
1026   }
1027 
1028   if (!VectorType::isValidElementType(Load->getType())) {
1029     for (int i = 0; i < getVectorWidth(); i++)
1030       ScalarMaps[i][Load] =
1031           generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
1032     return;
1033   }
1034 
1035   const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
1036 
1037   // Make sure we have scalar values available to access the pointer to
1038   // the data location.
1039   extractScalarValues(Load, VectorMap, ScalarMaps);
1040 
1041   Value *NewLoad;
1042   if (Access.isStrideZero(isl::manage_copy(Schedule)))
1043     NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
1044   else if (Access.isStrideOne(isl::manage_copy(Schedule)))
1045     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
1046   else if (Access.isStrideX(isl::manage_copy(Schedule), -1))
1047     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
1048   else
1049     NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
1050 
1051   VectorMap[Load] = NewLoad;
1052 }
1053 
1054 void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
1055                                          ValueMapT &VectorMap,
1056                                          VectorValueMapT &ScalarMaps) {
1057   int VectorWidth = getVectorWidth();
1058   Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
1059                                      ScalarMaps, getLoopForStmt(Stmt));
1060 
1061   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
1062 
1063   const CastInst *Cast = dyn_cast<CastInst>(Inst);
1064   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
1065   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
1066 }
1067 
1068 void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
1069                                           ValueMapT &VectorMap,
1070                                           VectorValueMapT &ScalarMaps) {
1071   Loop *L = getLoopForStmt(Stmt);
1072   Value *OpZero = Inst->getOperand(0);
1073   Value *OpOne = Inst->getOperand(1);
1074 
1075   Value *NewOpZero, *NewOpOne;
1076   NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
1077   NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
1078 
1079   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
1080                                        Inst->getName() + "p_vec");
1081   VectorMap[Inst] = NewInst;
1082 }
1083 
1084 void VectorBlockGenerator::copyStore(
1085     ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
1086     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1087   const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
1088 
1089   auto *Pointer = Store->getPointerOperand();
1090   Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
1091                                  ScalarMaps, getLoopForStmt(Stmt));
1092 
1093   // Make sure we have scalar values available to access the pointer to
1094   // the data location.
1095   extractScalarValues(Store, VectorMap, ScalarMaps);
1096 
1097   if (Access.isStrideOne(isl::manage_copy(Schedule))) {
1098     Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
1099     Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
1100                                                  VLTS[0], NewAccesses);
1101 
1102     Value *VectorPtr =
1103         Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
1104     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
1105 
1106     if (!Aligned)
1107       Store->setAlignment(8);
1108   } else {
1109     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
1110       Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
1111       Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
1112                                                    VLTS[i], NewAccesses);
1113       Builder.CreateStore(Scalar, NewPointer);
1114     }
1115   }
1116 }
1117 
1118 bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
1119                                              ValueMapT &VectorMap) {
1120   for (Value *Operand : Inst->operands())
1121     if (VectorMap.count(Operand))
1122       return true;
1123   return false;
1124 }
1125 
1126 bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
1127                                                ValueMapT &VectorMap,
1128                                                VectorValueMapT &ScalarMaps) {
1129   bool HasVectorOperand = false;
1130   int VectorWidth = getVectorWidth();
1131 
1132   for (Value *Operand : Inst->operands()) {
1133     ValueMapT::iterator VecOp = VectorMap.find(Operand);
1134 
1135     if (VecOp == VectorMap.end())
1136       continue;
1137 
1138     HasVectorOperand = true;
1139     Value *NewVector = VecOp->second;
1140 
1141     for (int i = 0; i < VectorWidth; ++i) {
1142       ValueMapT &SM = ScalarMaps[i];
1143 
1144       // If there is one scalar extracted, all scalar elements should have
1145       // already been extracted by the code here. So no need to check for the
1146       // existence of all of them.
1147       if (SM.count(Operand))
1148         break;
1149 
1150       SM[Operand] =
1151           Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
1152     }
1153   }
1154 
1155   return HasVectorOperand;
1156 }
1157 
1158 void VectorBlockGenerator::copyInstScalarized(
1159     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1160     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1161   bool HasVectorOperand;
1162   int VectorWidth = getVectorWidth();
1163 
1164   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
1165 
1166   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
1167     BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
1168                                     VLTS[VectorLane], NewAccesses);
1169 
1170   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
1171     return;
1172 
1173   // Make the result available as vector value.
1174   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
1175   Value *Vector = UndefValue::get(VectorType);
1176 
1177   for (int i = 0; i < VectorWidth; i++)
1178     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
1179                                          Builder.getInt32(i));
1180 
1181   VectorMap[Inst] = Vector;
1182 }
1183 
1184 int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
1185 
1186 void VectorBlockGenerator::copyInstruction(
1187     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1188     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1189   // Terminator instructions control the control flow. They are explicitly
1190   // expressed in the clast and do not need to be copied.
1191   if (Inst->isTerminator())
1192     return;
1193 
1194   if (canSyntheziseInStmt(Stmt, Inst))
1195     return;
1196 
1197   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
1198     generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
1199     return;
1200   }
1201 
1202   if (hasVectorOperands(Inst, VectorMap)) {
1203     if (auto *Store = dyn_cast<StoreInst>(Inst)) {
1204       // Identified as redundant by -polly-simplify.
1205       if (!Stmt.getArrayAccessOrNULLFor(Store))
1206         return;
1207 
1208       copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
1209       return;
1210     }
1211 
1212     if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1213       copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
1214       return;
1215     }
1216 
1217     if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1218       copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
1219       return;
1220     }
1221 
1222     // Fallthrough: We generate scalar instructions, if we don't know how to
1223     // generate vector code.
1224   }
1225 
1226   copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
1227 }
1228 
1229 void VectorBlockGenerator::generateScalarVectorLoads(
1230     ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1231   for (MemoryAccess *MA : Stmt) {
1232     if (MA->isArrayKind() || MA->isWrite())
1233       continue;
1234 
1235     auto *Address = getOrCreateAlloca(*MA);
1236     Type *VectorPtrType = getVectorPtrTy(Address, 1);
1237     Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1238                                              Address->getName() + "_p_vec_p");
1239     auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1240     Constant *SplatVector = Constant::getNullValue(
1241         VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1242 
1243     Value *VectorVal = Builder.CreateShuffleVector(
1244         Val, Val, SplatVector, Address->getName() + "_p_splat");
1245     VectorBlockMap[MA->getAccessValue()] = VectorVal;
1246   }
1247 }
1248 
1249 void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1250   for (MemoryAccess *MA : Stmt) {
1251     if (MA->isArrayKind() || MA->isRead())
1252       continue;
1253 
1254     llvm_unreachable("Scalar stores not expected in vector loop");
1255   }
1256 }
1257 
1258 void VectorBlockGenerator::copyStmt(
1259     ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1260   assert(Stmt.isBlockStmt() &&
1261          "TODO: Only block statements can be copied by the vector block "
1262          "generator");
1263 
1264   BasicBlock *BB = Stmt.getBasicBlock();
1265   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1266                                   &*Builder.GetInsertPoint(), &DT, &LI);
1267   CopyBB->setName("polly.stmt." + BB->getName());
1268   Builder.SetInsertPoint(&CopyBB->front());
1269 
1270   // Create two maps that store the mapping from the original instructions of
1271   // the old basic block to their copies in the new basic block. Those maps
1272   // are basic block local.
1273   //
1274   // As vector code generation is supported there is one map for scalar values
1275   // and one for vector values.
1276   //
1277   // In case we just do scalar code generation, the vectorMap is not used and
1278   // the scalarMap has just one dimension, which contains the mapping.
1279   //
1280   // In case vector code generation is done, an instruction may either appear
1281   // in the vector map once (as it is calculating >vectorwidth< values at a
1282   // time. Or (if the values are calculated using scalar operations), it
1283   // appears once in every dimension of the scalarMap.
1284   VectorValueMapT ScalarBlockMap(getVectorWidth());
1285   ValueMapT VectorBlockMap;
1286 
1287   generateScalarVectorLoads(Stmt, VectorBlockMap);
1288 
1289   for (Instruction &Inst : *BB)
1290     copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1291 
1292   verifyNoScalarStores(Stmt);
1293 }
1294 
1295 BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1296                                              BasicBlock *BBCopy) {
1297 
1298   BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1299   BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
1300 
1301   if (BBCopyIDom)
1302     DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1303 
1304   return StartBlockMap.lookup(BBIDom);
1305 }
1306 
1307 // This is to determine whether an llvm::Value (defined in @p BB) is usable when
1308 // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1309 // does not work in cases where the exit block has edges from outside the
1310 // region. In that case the llvm::Value would never be usable in in the exit
1311 // block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1312 // for the subregion's exiting edges only. We need to determine whether an
1313 // llvm::Value is usable in there. We do this by checking whether it dominates
1314 // all exiting blocks individually.
1315 static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1316                                       BasicBlock *BB) {
1317   for (auto ExitingBB : predecessors(R->getExit())) {
1318     // Check for non-subregion incoming edges.
1319     if (!R->contains(ExitingBB))
1320       continue;
1321 
1322     if (!DT.dominates(BB, ExitingBB))
1323       return false;
1324   }
1325 
1326   return true;
1327 }
1328 
1329 // Find the direct dominator of the subregion's exit block if the subregion was
1330 // simplified.
1331 static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1332   BasicBlock *Common = nullptr;
1333   for (auto ExitingBB : predecessors(R->getExit())) {
1334     // Check for non-subregion incoming edges.
1335     if (!R->contains(ExitingBB))
1336       continue;
1337 
1338     // First exiting edge.
1339     if (!Common) {
1340       Common = ExitingBB;
1341       continue;
1342     }
1343 
1344     Common = DT.findNearestCommonDominator(Common, ExitingBB);
1345   }
1346 
1347   assert(Common && R->contains(Common));
1348   return Common;
1349 }
1350 
1351 void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
1352                                isl_id_to_ast_expr *IdToAstExp) {
1353   assert(Stmt.isRegionStmt() &&
1354          "Only region statements can be copied by the region generator");
1355 
1356   // Forget all old mappings.
1357   StartBlockMap.clear();
1358   EndBlockMap.clear();
1359   RegionMaps.clear();
1360   IncompletePHINodeMap.clear();
1361 
1362   // Collection of all values related to this subregion.
1363   ValueMapT ValueMap;
1364 
1365   // The region represented by the statement.
1366   Region *R = Stmt.getRegion();
1367 
1368   // Create a dedicated entry for the region where we can reload all demoted
1369   // inputs.
1370   BasicBlock *EntryBB = R->getEntry();
1371   BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1372                                        &*Builder.GetInsertPoint(), &DT, &LI);
1373   EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1374   Builder.SetInsertPoint(&EntryBBCopy->front());
1375 
1376   ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1377   generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1378 
1379   for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1380     if (!R->contains(*PI)) {
1381       StartBlockMap[*PI] = EntryBBCopy;
1382       EndBlockMap[*PI] = EntryBBCopy;
1383     }
1384 
1385   // Iterate over all blocks in the region in a breadth-first search.
1386   std::deque<BasicBlock *> Blocks;
1387   SmallSetVector<BasicBlock *, 8> SeenBlocks;
1388   Blocks.push_back(EntryBB);
1389   SeenBlocks.insert(EntryBB);
1390 
1391   while (!Blocks.empty()) {
1392     BasicBlock *BB = Blocks.front();
1393     Blocks.pop_front();
1394 
1395     // First split the block and update dominance information.
1396     BasicBlock *BBCopy = splitBB(BB);
1397     BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1398 
1399     // Get the mapping for this block and initialize it with either the scalar
1400     // loads from the generated entering block (which dominates all blocks of
1401     // this subregion) or the maps of the immediate dominator, if part of the
1402     // subregion. The latter necessarily includes the former.
1403     ValueMapT *InitBBMap;
1404     if (BBCopyIDom) {
1405       assert(RegionMaps.count(BBCopyIDom));
1406       InitBBMap = &RegionMaps[BBCopyIDom];
1407     } else
1408       InitBBMap = &EntryBBMap;
1409     auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1410     ValueMapT &RegionMap = Inserted.first->second;
1411 
1412     // Copy the block with the BlockGenerator.
1413     Builder.SetInsertPoint(&BBCopy->front());
1414     copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1415 
1416     // In order to remap PHI nodes we store also basic block mappings.
1417     StartBlockMap[BB] = BBCopy;
1418     EndBlockMap[BB] = Builder.GetInsertBlock();
1419 
1420     // Add values to incomplete PHI nodes waiting for this block to be copied.
1421     for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1422       addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1423     IncompletePHINodeMap[BB].clear();
1424 
1425     // And continue with new successors inside the region.
1426     for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1427       if (R->contains(*SI) && SeenBlocks.insert(*SI))
1428         Blocks.push_back(*SI);
1429 
1430     // Remember value in case it is visible after this subregion.
1431     if (isDominatingSubregionExit(DT, R, BB))
1432       ValueMap.insert(RegionMap.begin(), RegionMap.end());
1433   }
1434 
1435   // Now create a new dedicated region exit block and add it to the region map.
1436   BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1437                                       &*Builder.GetInsertPoint(), &DT, &LI);
1438   ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1439   StartBlockMap[R->getExit()] = ExitBBCopy;
1440   EndBlockMap[R->getExit()] = ExitBBCopy;
1441 
1442   BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
1443   assert(ExitDomBBCopy &&
1444          "Common exit dominator must be within region; at least the entry node "
1445          "must match");
1446   DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1447 
1448   // As the block generator doesn't handle control flow we need to add the
1449   // region control flow by hand after all blocks have been copied.
1450   for (BasicBlock *BB : SeenBlocks) {
1451 
1452     BasicBlock *BBCopyStart = StartBlockMap[BB];
1453     BasicBlock *BBCopyEnd = EndBlockMap[BB];
1454     TerminatorInst *TI = BB->getTerminator();
1455     if (isa<UnreachableInst>(TI)) {
1456       while (!BBCopyEnd->empty())
1457         BBCopyEnd->begin()->eraseFromParent();
1458       new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1459       continue;
1460     }
1461 
1462     Instruction *BICopy = BBCopyEnd->getTerminator();
1463 
1464     ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1465     RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end());
1466 
1467     Builder.SetInsertPoint(BICopy);
1468     copyInstScalar(Stmt, TI, RegionMap, LTS);
1469     BICopy->eraseFromParent();
1470   }
1471 
1472   // Add counting PHI nodes to all loops in the region that can be used as
1473   // replacement for SCEVs referring to the old loop.
1474   for (BasicBlock *BB : SeenBlocks) {
1475     Loop *L = LI.getLoopFor(BB);
1476     if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1477       continue;
1478 
1479     BasicBlock *BBCopy = StartBlockMap[BB];
1480     Value *NullVal = Builder.getInt32(0);
1481     PHINode *LoopPHI =
1482         PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1483     Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1484         LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1485     LoopPHI->insertBefore(&BBCopy->front());
1486     LoopPHIInc->insertBefore(BBCopy->getTerminator());
1487 
1488     for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1489       if (!R->contains(PredBB))
1490         continue;
1491       if (L->contains(PredBB))
1492         LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1493       else
1494         LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1495     }
1496 
1497     for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1498       if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1499         LoopPHI->addIncoming(NullVal, PredBBCopy);
1500 
1501     LTS[L] = SE.getUnknown(LoopPHI);
1502   }
1503 
1504   // Continue generating code in the exit block.
1505   Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1506 
1507   // Write values visible to other statements.
1508   generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1509   StartBlockMap.clear();
1510   EndBlockMap.clear();
1511   RegionMaps.clear();
1512   IncompletePHINodeMap.clear();
1513 }
1514 
1515 PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1516                                        ValueMapT &BBMap, Loop *L) {
1517   ScopStmt *Stmt = MA->getStatement();
1518   Region *SubR = Stmt->getRegion();
1519   auto Incoming = MA->getIncoming();
1520 
1521   PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1522   PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1523   BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1524 
1525   // This can happen if the subregion is simplified after the ScopStmts
1526   // have been created; simplification happens as part of CodeGeneration.
1527   if (OrigPHI->getParent() != SubR->getExit()) {
1528     BasicBlock *FormerExit = SubR->getExitingBlock();
1529     if (FormerExit)
1530       NewSubregionExit = StartBlockMap.lookup(FormerExit);
1531   }
1532 
1533   PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1534                                     "polly." + OrigPHI->getName(),
1535                                     NewSubregionExit->getFirstNonPHI());
1536 
1537   // Add the incoming values to the PHI.
1538   for (auto &Pair : Incoming) {
1539     BasicBlock *OrigIncomingBlock = Pair.first;
1540     BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1541     BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1542     Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator());
1543     assert(RegionMaps.count(NewIncomingBlockStart));
1544     assert(RegionMaps.count(NewIncomingBlockEnd));
1545     ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1546 
1547     Value *OrigIncomingValue = Pair.second;
1548     Value *NewIncomingValue =
1549         getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1550     NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1551   }
1552 
1553   return NewPHI;
1554 }
1555 
1556 Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1557                                       ValueMapT &BBMap) {
1558   ScopStmt *Stmt = MA->getStatement();
1559 
1560   // TODO: Add some test cases that ensure this is really the right choice.
1561   Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1562 
1563   if (MA->isAnyPHIKind()) {
1564     auto Incoming = MA->getIncoming();
1565     assert(!Incoming.empty() &&
1566            "PHI WRITEs must have originate from at least one incoming block");
1567 
1568     // If there is only one incoming value, we do not need to create a PHI.
1569     if (Incoming.size() == 1) {
1570       Value *OldVal = Incoming[0].second;
1571       return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1572     }
1573 
1574     return buildExitPHI(MA, LTS, BBMap, L);
1575   }
1576 
1577   // MemoryKind::Value accesses leaving the subregion must dominate the exit
1578   // block; just pass the copied value.
1579   Value *OldVal = MA->getAccessValue();
1580   return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1581 }
1582 
1583 void RegionGenerator::generateScalarStores(
1584     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1585     __isl_keep isl_id_to_ast_expr *NewAccesses) {
1586   assert(Stmt.getRegion() &&
1587          "Block statements need to use the generateScalarStores() "
1588          "function in the BlockGenerator");
1589 
1590   for (MemoryAccess *MA : Stmt) {
1591     if (MA->isOriginalArrayKind() || MA->isRead())
1592       continue;
1593 
1594     isl::set AccDom = MA->getAccessRelation().domain();
1595     std::string Subject = MA->getId().get_name();
1596     generateConditionalExecution(
1597         Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1598           Value *NewVal = getExitScalar(MA, LTS, BBMap);
1599           Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1600                                               BBMap, NewAccesses);
1601           assert((!isa<Instruction>(NewVal) ||
1602                   DT.dominates(cast<Instruction>(NewVal)->getParent(),
1603                                Builder.GetInsertBlock())) &&
1604                  "Domination violation");
1605           assert((!isa<Instruction>(Address) ||
1606                   DT.dominates(cast<Instruction>(Address)->getParent(),
1607                                Builder.GetInsertBlock())) &&
1608                  "Domination violation");
1609           Builder.CreateStore(NewVal, Address);
1610         });
1611   }
1612 }
1613 
1614 void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
1615                                       PHINode *PHICopy, BasicBlock *IncomingBB,
1616                                       LoopToScevMapT &LTS) {
1617   // If the incoming block was not yet copied mark this PHI as incomplete.
1618   // Once the block will be copied the incoming value will be added.
1619   BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1620   BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1621   if (!BBCopyStart) {
1622     assert(!BBCopyEnd);
1623     assert(Stmt.represents(IncomingBB) &&
1624            "Bad incoming block for PHI in non-affine region");
1625     IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1626     return;
1627   }
1628 
1629   assert(RegionMaps.count(BBCopyStart) &&
1630          "Incoming PHI block did not have a BBMap");
1631   ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1632 
1633   Value *OpCopy = nullptr;
1634 
1635   if (Stmt.represents(IncomingBB)) {
1636     Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1637 
1638     // If the current insert block is different from the PHIs incoming block
1639     // change it, otherwise do not.
1640     auto IP = Builder.GetInsertPoint();
1641     if (IP->getParent() != BBCopyEnd)
1642       Builder.SetInsertPoint(BBCopyEnd->getTerminator());
1643     OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1644     if (IP->getParent() != BBCopyEnd)
1645       Builder.SetInsertPoint(&*IP);
1646   } else {
1647     // All edges from outside the non-affine region become a single edge
1648     // in the new copy of the non-affine region. Make sure to only add the
1649     // corresponding edge the first time we encounter a basic block from
1650     // outside the non-affine region.
1651     if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1652       return;
1653 
1654     // Get the reloaded value.
1655     OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1656   }
1657 
1658   assert(OpCopy && "Incoming PHI value was not copied properly");
1659   PHICopy->addIncoming(OpCopy, BBCopyEnd);
1660 }
1661 
1662 void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1663                                          ValueMapT &BBMap,
1664                                          LoopToScevMapT &LTS) {
1665   unsigned NumIncoming = PHI->getNumIncomingValues();
1666   PHINode *PHICopy =
1667       Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1668   PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1669   BBMap[PHI] = PHICopy;
1670 
1671   for (BasicBlock *IncomingBB : PHI->blocks())
1672     addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1673 }
1674