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