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