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