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 "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/RegionInfo.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "isl/aff.h"
33 #include "isl/ast.h"
34 #include "isl/ast_build.h"
35 #include "isl/set.h"
36 #include <deque>
37 
38 using namespace llvm;
39 using namespace polly;
40 
41 static cl::opt<bool> Aligned("enable-polly-aligned",
42                              cl::desc("Assumed aligned memory accesses."),
43                              cl::Hidden, cl::init(false), cl::ZeroOrMore,
44                              cl::cat(PollyCategory));
45 
46 static cl::opt<bool> DebugPrinting(
47     "polly-codegen-add-debug-printing",
48     cl::desc("Add printf calls that show the values loaded/stored."),
49     cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
50 
51 BlockGenerator::BlockGenerator(PollyIRBuilder &B, LoopInfo &LI,
52                                ScalarEvolution &SE, DominatorTree &DT,
53                                ScalarAllocaMapTy &ScalarMap,
54                                ScalarAllocaMapTy &PHIOpMap,
55                                EscapeUsersAllocaMapTy &EscapeMap,
56                                ValueMapT &GlobalMap,
57                                IslExprBuilder *ExprBuilder)
58     : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
59       EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap),
60       EscapeMap(EscapeMap), GlobalMap(GlobalMap) {}
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 
90   BBMap[Old] = Expanded;
91   return Expanded;
92 }
93 
94 Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
95                                    LoopToScevMapT &LTS, Loop *L) const {
96   // Constants that do not reference any named value can always remain
97   // unchanged. Handle them early to avoid expensive map lookups. We do not take
98   // the fast-path for external constants which are referenced through globals
99   // as these may need to be rewritten when distributing code accross different
100   // LLVM modules.
101   if (isa<Constant>(Old) && !isa<GlobalValue>(Old))
102     return Old;
103 
104   // Inline asm is like a constant to us.
105   if (isa<InlineAsm>(Old))
106     return Old;
107 
108   if (Value *New = GlobalMap.lookup(Old)) {
109     if (Value *NewRemapped = GlobalMap.lookup(New))
110       New = NewRemapped;
111     if (Old->getType()->getScalarSizeInBits() <
112         New->getType()->getScalarSizeInBits())
113       New = Builder.CreateTruncOrBitCast(New, Old->getType());
114 
115     return New;
116   }
117 
118   if (Value *New = BBMap.lookup(Old))
119     return New;
120 
121   if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
122     return New;
123 
124   // A scop-constant value defined by a global or a function parameter.
125   if (isa<GlobalValue>(Old) || isa<Argument>(Old))
126     return Old;
127 
128   // A scop-constant value defined by an instruction executed outside the scop.
129   if (const Instruction *Inst = dyn_cast<Instruction>(Old))
130     if (!Stmt.getParent()->contains(Inst->getParent()))
131       return Old;
132 
133   // The scalar dependence is neither available nor SCEVCodegenable.
134   llvm_unreachable("Unexpected scalar dependence in region!");
135   return nullptr;
136 }
137 
138 void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
139                                     ValueMapT &BBMap, LoopToScevMapT &LTS) {
140   // We do not generate debug intrinsics as we did not investigate how to
141   // copy them correctly. At the current state, they just crash the code
142   // generation as the meta-data operands are not correctly copied.
143   if (isa<DbgInfoIntrinsic>(Inst))
144     return;
145 
146   Instruction *NewInst = Inst->clone();
147 
148   // Replace old operands with the new ones.
149   for (Value *OldOperand : Inst->operands()) {
150     Value *NewOperand =
151         getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
152 
153     if (!NewOperand) {
154       assert(!isa<StoreInst>(NewInst) &&
155              "Store instructions are always needed!");
156       delete NewInst;
157       return;
158     }
159 
160     NewInst->replaceUsesOfWith(OldOperand, NewOperand);
161   }
162 
163   Builder.Insert(NewInst);
164   BBMap[Inst] = NewInst;
165 
166   if (!NewInst->getType()->isVoidTy())
167     NewInst->setName("p_" + Inst->getName());
168 }
169 
170 Value *
171 BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
172                                          ValueMapT &BBMap, LoopToScevMapT &LTS,
173                                          isl_id_to_ast_expr *NewAccesses) {
174   const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
175   return generateLocationAccessed(
176       Stmt, getLoopForStmt(Stmt),
177       Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS,
178       NewAccesses, MA.getId(), MA.getAccessValue()->getType());
179 }
180 
181 Value *BlockGenerator::generateLocationAccessed(
182     ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
183     LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
184     Type *ExpectedType) {
185   isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
186 
187   if (AccessExpr) {
188     AccessExpr = isl_ast_expr_address_of(AccessExpr);
189     auto Address = ExprBuilder->create(AccessExpr);
190 
191     // Cast the address of this memory access to a pointer type that has the
192     // same element type as the original access, but uses the address space of
193     // the newly generated pointer.
194     auto OldPtrTy = ExpectedType->getPointerTo();
195     auto NewPtrTy = Address->getType();
196     OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
197                                 NewPtrTy->getPointerAddressSpace());
198 
199     if (OldPtrTy != NewPtrTy)
200       Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
201     return Address;
202   }
203   assert(
204       Pointer &&
205       "If expression was not generated, must use the original pointer value");
206   return getNewValue(Stmt, Pointer, BBMap, LTS, L);
207 }
208 
209 Value *
210 BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L,
211                                    LoopToScevMapT &LTS, ValueMapT &BBMap,
212                                    __isl_keep isl_id_to_ast_expr *NewAccesses) {
213   if (Access.isLatestArrayKind())
214     return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
215                                     LTS, NewAccesses, Access.getId(),
216                                     Access.getAccessValue()->getType());
217 
218   if (Access.isLatestValueKind() || Access.isLatestExitPHIKind())
219     return getOrCreateScalarAlloca(Access.getBaseAddr());
220 
221   if (Access.isLatestPHIKind())
222     return getOrCreatePHIAlloca(Access.getBaseAddr());
223 
224   llvm_unreachable("Unknown access type");
225 }
226 
227 Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
228   auto *StmtBB = Stmt.getEntryBlock();
229   return LI.getLoopFor(StmtBB);
230 }
231 
232 Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, LoadInst *Load,
233                                           ValueMapT &BBMap, LoopToScevMapT &LTS,
234                                           isl_id_to_ast_expr *NewAccesses) {
235   if (Value *PreloadLoad = GlobalMap.lookup(Load))
236     return PreloadLoad;
237 
238   Value *NewPointer =
239       generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
240   Value *ScalarLoad = Builder.CreateAlignedLoad(
241       NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
242 
243   if (DebugPrinting)
244     RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
245                                           ": ", ScalarLoad, "\n");
246 
247   return ScalarLoad;
248 }
249 
250 void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
251                                          ValueMapT &BBMap, LoopToScevMapT &LTS,
252                                          isl_id_to_ast_expr *NewAccesses) {
253   Value *NewPointer =
254       generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
255   Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
256                                     getLoopForStmt(Stmt));
257 
258   if (DebugPrinting)
259     RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to  ", NewPointer,
260                                           ": ", ValueOperand, "\n");
261 
262   Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
263 }
264 
265 bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
266   Loop *L = getLoopForStmt(Stmt);
267   return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
268          canSynthesize(Inst, *Stmt.getParent(), &LI, &SE, L);
269 }
270 
271 void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
272                                      ValueMapT &BBMap, LoopToScevMapT &LTS,
273                                      isl_id_to_ast_expr *NewAccesses) {
274   // Terminator instructions control the control flow. They are explicitly
275   // expressed in the clast and do not need to be copied.
276   if (Inst->isTerminator())
277     return;
278 
279   // Synthesizable statements will be generated on-demand.
280   if (canSyntheziseInStmt(Stmt, Inst))
281     return;
282 
283   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
284     Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
285     // Compute NewLoad before its insertion in BBMap to make the insertion
286     // deterministic.
287     BBMap[Load] = NewLoad;
288     return;
289   }
290 
291   if (auto *Store = dyn_cast<StoreInst>(Inst)) {
292     generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
293     return;
294   }
295 
296   if (auto *PHI = dyn_cast<PHINode>(Inst)) {
297     copyPHIInstruction(Stmt, PHI, BBMap, LTS);
298     return;
299   }
300 
301   // Skip some special intrinsics for which we do not adjust the semantics to
302   // the new schedule. All others are handled like every other instruction.
303   if (isIgnoredIntrinsic(Inst))
304     return;
305 
306   copyInstScalar(Stmt, Inst, BBMap, LTS);
307 }
308 
309 void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) {
310   auto NewBB = Builder.GetInsertBlock();
311   for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) {
312     Instruction *NewInst = &*I;
313 
314     if (!isInstructionTriviallyDead(NewInst))
315       continue;
316 
317     for (auto Pair : BBMap)
318       if (Pair.second == NewInst) {
319         BBMap.erase(Pair.first);
320       }
321 
322     NewInst->eraseFromParent();
323     I = NewBB->rbegin();
324   }
325 }
326 
327 void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
328                               isl_id_to_ast_expr *NewAccesses) {
329   assert(Stmt.isBlockStmt() &&
330          "Only block statements can be copied by the block generator");
331 
332   ValueMapT BBMap;
333 
334   BasicBlock *BB = Stmt.getBasicBlock();
335   copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
336   removeDeadInstructions(BB, BBMap);
337 }
338 
339 BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
340   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
341                                   &*Builder.GetInsertPoint(), &DT, &LI);
342   CopyBB->setName("polly.stmt." + BB->getName());
343   return CopyBB;
344 }
345 
346 BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
347                                    ValueMapT &BBMap, LoopToScevMapT &LTS,
348                                    isl_id_to_ast_expr *NewAccesses) {
349   BasicBlock *CopyBB = splitBB(BB);
350   Builder.SetInsertPoint(&CopyBB->front());
351   generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
352 
353   copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
354 
355   // After a basic block was copied store all scalars that escape this block in
356   // their alloca.
357   generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
358   return CopyBB;
359 }
360 
361 void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
362                             ValueMapT &BBMap, LoopToScevMapT &LTS,
363                             isl_id_to_ast_expr *NewAccesses) {
364   EntryBB = &CopyBB->getParent()->getEntryBlock();
365 
366   for (Instruction &Inst : *BB)
367     copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
368 }
369 
370 Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
371                                          ScalarAllocaMapTy &Map,
372                                          const char *NameExt) {
373   // If no alloca was found create one and insert it in the entry block.
374   if (!Map.count(ScalarBase)) {
375     auto *Ty = ScalarBase->getType();
376     auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
377     EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
378     NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt());
379     Map[ScalarBase] = NewAddr;
380   }
381 
382   auto Addr = Map[ScalarBase];
383 
384   if (auto NewAddr = GlobalMap.lookup(Addr))
385     return NewAddr;
386 
387   return Addr;
388 }
389 
390 Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
391   assert(!Access.isArrayKind() && "Trying to get alloca for array kind");
392 
393   if (Access.isPHIKind())
394     return getOrCreatePHIAlloca(Access.getBaseAddr());
395   else
396     return getOrCreateScalarAlloca(Access.getBaseAddr());
397 }
398 
399 Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
400   assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
401 
402   if (Array->isPHIKind())
403     return getOrCreatePHIAlloca(Array->getBasePtr());
404   else
405     return getOrCreateScalarAlloca(Array->getBasePtr());
406 }
407 
408 Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
409   return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
410 }
411 
412 Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
413   return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
414 }
415 
416 void BlockGenerator::handleOutsideUsers(const Scop &S, Instruction *Inst) {
417   // If there are escape users we get the alloca for this instruction and put it
418   // in the EscapeMap for later finalization. Lastly, if the instruction was
419   // copied multiple times we already did this and can exit.
420   if (EscapeMap.count(Inst))
421     return;
422 
423   EscapeUserVectorTy EscapeUsers;
424   for (User *U : Inst->users()) {
425 
426     // Non-instruction user will never escape.
427     Instruction *UI = dyn_cast<Instruction>(U);
428     if (!UI)
429       continue;
430 
431     if (S.contains(UI))
432       continue;
433 
434     EscapeUsers.push_back(UI);
435   }
436 
437   // Exit if no escape uses were found.
438   if (EscapeUsers.empty())
439     return;
440 
441   // Get or create an escape alloca for this instruction.
442   auto *ScalarAddr = getOrCreateScalarAlloca(Inst);
443 
444   // Remember that this instruction has escape uses and the escape alloca.
445   EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
446 }
447 
448 void BlockGenerator::generateScalarLoads(
449     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
450     __isl_keep isl_id_to_ast_expr *NewAccesses) {
451   for (MemoryAccess *MA : Stmt) {
452     if (MA->isOriginalArrayKind() || MA->isWrite())
453       continue;
454 
455     auto *Address =
456         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
457     assert((!isa<Instruction>(Address) ||
458             DT.dominates(cast<Instruction>(Address)->getParent(),
459                          Builder.GetInsertBlock())) &&
460            "Domination violation");
461     BBMap[MA->getBaseAddr()] =
462         Builder.CreateLoad(Address, Address->getName() + ".reload");
463   }
464 }
465 
466 void BlockGenerator::generateScalarStores(
467     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
468     __isl_keep isl_id_to_ast_expr *NewAccesses) {
469   Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
470 
471   assert(Stmt.isBlockStmt() && "Region statements need to use the "
472                                "generateScalarStores() function in the "
473                                "RegionGenerator");
474 
475   for (MemoryAccess *MA : Stmt) {
476     if (MA->isOriginalArrayKind() || MA->isRead())
477       continue;
478 
479     Value *Val = MA->getAccessValue();
480     if (MA->isAnyPHIKind()) {
481       assert(MA->getIncoming().size() >= 1 &&
482              "Block statements have exactly one exiting block, or multiple but "
483              "with same incoming block and value");
484       assert(std::all_of(MA->getIncoming().begin(), MA->getIncoming().end(),
485                          [&](std::pair<BasicBlock *, Value *> p) -> bool {
486                            return p.first == Stmt.getBasicBlock();
487                          }) &&
488              "Incoming block must be statement's block");
489       Val = MA->getIncoming()[0].second;
490     }
491     auto Address =
492         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
493 
494     Val = getNewValue(Stmt, Val, BBMap, LTS, L);
495     assert((!isa<Instruction>(Val) ||
496             DT.dominates(cast<Instruction>(Val)->getParent(),
497                          Builder.GetInsertBlock())) &&
498            "Domination violation");
499     assert((!isa<Instruction>(Address) ||
500             DT.dominates(cast<Instruction>(Address)->getParent(),
501                          Builder.GetInsertBlock())) &&
502            "Domination violation");
503     Builder.CreateStore(Val, Address);
504   }
505 }
506 
507 void BlockGenerator::createScalarInitialization(Scop &S) {
508   BasicBlock *ExitBB = S.getExit();
509 
510   // The split block __just before__ the region and optimized region.
511   BasicBlock *SplitBB = S.getEnteringBlock();
512   BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
513   assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
514 
515   // Get the start block of the __optimized__ region.
516   BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
517   if (StartBB == S.getEntry())
518     StartBB = SplitBBTerm->getSuccessor(1);
519 
520   Builder.SetInsertPoint(&*StartBB->begin());
521 
522   for (auto &Array : S.arrays()) {
523     if (Array->getNumberOfDimensions() != 0)
524       continue;
525     if (Array->isPHIKind()) {
526       // For PHI nodes, the only values we need to store are the ones that
527       // reach the PHI node from outside the region. In general there should
528       // only be one such incoming edge and this edge should enter through
529       // 'SplitBB'.
530       auto PHI = cast<PHINode>(Array->getBasePtr());
531 
532       for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
533         if (!S.contains(*BI) && *BI != SplitBB)
534           llvm_unreachable("Incoming edges from outside the scop should always "
535                            "come from SplitBB");
536 
537       int Idx = PHI->getBasicBlockIndex(SplitBB);
538       if (Idx < 0)
539         continue;
540 
541       Value *ScalarValue = PHI->getIncomingValue(Idx);
542 
543       Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
544       continue;
545     }
546 
547     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
548 
549     if (Inst && S.contains(Inst))
550       continue;
551 
552     // PHI nodes that are not marked as such in their SAI object are either exit
553     // PHI nodes we model as common scalars but without initialization, or
554     // incoming phi nodes that need to be initialized. Check if the first is the
555     // case for Inst and do not create and initialize memory if so.
556     if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
557       if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
558         continue;
559 
560     Builder.CreateStore(Array->getBasePtr(),
561                         getOrCreateScalarAlloca(Array->getBasePtr()));
562   }
563 }
564 
565 void BlockGenerator::createScalarFinalization(Scop &S) {
566   // The exit block of the __unoptimized__ region.
567   BasicBlock *ExitBB = S.getExitingBlock();
568   // The merge block __just after__ the region and the optimized region.
569   BasicBlock *MergeBB = S.getExit();
570 
571   // The exit block of the __optimized__ region.
572   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
573   if (OptExitBB == ExitBB)
574     OptExitBB = *(++pred_begin(MergeBB));
575 
576   Builder.SetInsertPoint(OptExitBB->getTerminator());
577   for (const auto &EscapeMapping : EscapeMap) {
578     // Extract the escaping instruction and the escaping users as well as the
579     // alloca the instruction was demoted to.
580     Instruction *EscapeInst = EscapeMapping.first;
581     const auto &EscapeMappingValue = EscapeMapping.second;
582     const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
583     Value *ScalarAddr = EscapeMappingValue.first;
584 
585     // Reload the demoted instruction in the optimized version of the SCoP.
586     Value *EscapeInstReload =
587         Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
588     EscapeInstReload =
589         Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
590 
591     // Create the merge PHI that merges the optimized and unoptimized version.
592     PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
593                                         EscapeInst->getName() + ".merge");
594     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
595 
596     // Add the respective values to the merge PHI.
597     MergePHI->addIncoming(EscapeInstReload, OptExitBB);
598     MergePHI->addIncoming(EscapeInst, ExitBB);
599 
600     // The information of scalar evolution about the escaping instruction needs
601     // to be revoked so the new merged instruction will be used.
602     if (SE.isSCEVable(EscapeInst->getType()))
603       SE.forgetValue(EscapeInst);
604 
605     // Replace all uses of the demoted instruction with the merge PHI.
606     for (Instruction *EUser : EscapeUsers)
607       EUser->replaceUsesOfWith(EscapeInst, MergePHI);
608   }
609 }
610 
611 void BlockGenerator::findOutsideUsers(Scop &S) {
612   for (auto &Array : S.arrays()) {
613 
614     if (Array->getNumberOfDimensions() != 0)
615       continue;
616 
617     if (Array->isPHIKind())
618       continue;
619 
620     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
621 
622     if (!Inst)
623       continue;
624 
625     // Scop invariant hoisting moves some of the base pointers out of the scop.
626     // We can ignore these, as the invariant load hoisting already registers the
627     // relevant outside users.
628     if (!S.contains(Inst))
629       continue;
630 
631     handleOutsideUsers(S, Inst);
632   }
633 }
634 
635 void BlockGenerator::createExitPHINodeMerges(Scop &S) {
636   if (S.hasSingleExitEdge())
637     return;
638 
639   auto *ExitBB = S.getExitingBlock();
640   auto *MergeBB = S.getExit();
641   auto *AfterMergeBB = MergeBB->getSingleSuccessor();
642   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
643   if (OptExitBB == ExitBB)
644     OptExitBB = *(++pred_begin(MergeBB));
645 
646   Builder.SetInsertPoint(OptExitBB->getTerminator());
647 
648   for (auto &SAI : S.arrays()) {
649     auto *Val = SAI->getBasePtr();
650 
651     // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
652     // the original PHI's value or the reloaded incoming values from the
653     // generated code. An llvm::Value is merged between the original code's
654     // value or the generated one.
655     if (!SAI->isValueKind() && !SAI->isExitPHIKind())
656       continue;
657 
658     PHINode *PHI = dyn_cast<PHINode>(Val);
659     if (!PHI)
660       continue;
661 
662     if (PHI->getParent() != AfterMergeBB)
663       continue;
664 
665     std::string Name = PHI->getName();
666     Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
667     Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
668     Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
669     Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
670     assert((!isa<Instruction>(OriginalValue) ||
671             cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
672            "Original value must no be one we just generated.");
673     auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
674     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
675     MergePHI->addIncoming(Reload, OptExitBB);
676     MergePHI->addIncoming(OriginalValue, ExitBB);
677     int Idx = PHI->getBasicBlockIndex(MergeBB);
678     PHI->setIncomingValue(Idx, MergePHI);
679   }
680 }
681 
682 void BlockGenerator::invalidateScalarEvolution(Scop &S) {
683   for (auto &Stmt : S)
684     if (Stmt.isBlockStmt())
685       for (auto &Inst : *Stmt.getBasicBlock())
686         SE.forgetValue(&Inst);
687     else if (Stmt.isRegionStmt())
688       for (auto *BB : Stmt.getRegion()->blocks())
689         for (auto &Inst : *BB)
690           SE.forgetValue(&Inst);
691     else
692       llvm_unreachable("Unexpected statement type found");
693 }
694 
695 void BlockGenerator::finalizeSCoP(Scop &S) {
696   findOutsideUsers(S);
697   createScalarInitialization(S);
698   createExitPHINodeMerges(S);
699   createScalarFinalization(S);
700   invalidateScalarEvolution(S);
701 }
702 
703 VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
704                                            std::vector<LoopToScevMapT> &VLTS,
705                                            isl_map *Schedule)
706     : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
707   assert(Schedule && "No statement domain provided");
708 }
709 
710 Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
711                                             ValueMapT &VectorMap,
712                                             VectorValueMapT &ScalarMaps,
713                                             Loop *L) {
714   if (Value *NewValue = VectorMap.lookup(Old))
715     return NewValue;
716 
717   int Width = getVectorWidth();
718 
719   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
720 
721   for (int Lane = 0; Lane < Width; Lane++)
722     Vector = Builder.CreateInsertElement(
723         Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
724         Builder.getInt32(Lane));
725 
726   VectorMap[Old] = Vector;
727 
728   return Vector;
729 }
730 
731 Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
732   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
733   assert(PointerTy && "PointerType expected");
734 
735   Type *ScalarType = PointerTy->getElementType();
736   VectorType *VectorType = VectorType::get(ScalarType, Width);
737 
738   return PointerType::getUnqual(VectorType);
739 }
740 
741 Value *VectorBlockGenerator::generateStrideOneLoad(
742     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
743     __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
744   unsigned VectorWidth = getVectorWidth();
745   auto *Pointer = Load->getPointerOperand();
746   Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
747   unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
748 
749   Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
750                                                VLTS[Offset], NewAccesses);
751   Value *VectorPtr =
752       Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
753   LoadInst *VecLoad =
754       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
755   if (!Aligned)
756     VecLoad->setAlignment(8);
757 
758   if (NegativeStride) {
759     SmallVector<Constant *, 16> Indices;
760     for (int i = VectorWidth - 1; i >= 0; i--)
761       Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
762     Constant *SV = llvm::ConstantVector::get(Indices);
763     Value *RevVecLoad = Builder.CreateShuffleVector(
764         VecLoad, VecLoad, SV, Load->getName() + "_reverse");
765     return RevVecLoad;
766   }
767 
768   return VecLoad;
769 }
770 
771 Value *VectorBlockGenerator::generateStrideZeroLoad(
772     ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
773     __isl_keep isl_id_to_ast_expr *NewAccesses) {
774   auto *Pointer = Load->getPointerOperand();
775   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
776   Value *NewPointer =
777       generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
778   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
779                                            Load->getName() + "_p_vec_p");
780   LoadInst *ScalarLoad =
781       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
782 
783   if (!Aligned)
784     ScalarLoad->setAlignment(8);
785 
786   Constant *SplatVector = Constant::getNullValue(
787       VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
788 
789   Value *VectorLoad = Builder.CreateShuffleVector(
790       ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
791   return VectorLoad;
792 }
793 
794 Value *VectorBlockGenerator::generateUnknownStrideLoad(
795     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
796     __isl_keep isl_id_to_ast_expr *NewAccesses) {
797   int VectorWidth = getVectorWidth();
798   auto *Pointer = Load->getPointerOperand();
799   VectorType *VectorType = VectorType::get(
800       dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
801 
802   Value *Vector = UndefValue::get(VectorType);
803 
804   for (int i = 0; i < VectorWidth; i++) {
805     Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
806                                                  VLTS[i], NewAccesses);
807     Value *ScalarLoad =
808         Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
809     Vector = Builder.CreateInsertElement(
810         Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
811   }
812 
813   return Vector;
814 }
815 
816 void VectorBlockGenerator::generateLoad(
817     ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
818     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
819   if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
820     VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
821                                                 Load->getName() + "_p");
822     return;
823   }
824 
825   if (!VectorType::isValidElementType(Load->getType())) {
826     for (int i = 0; i < getVectorWidth(); i++)
827       ScalarMaps[i][Load] =
828           generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
829     return;
830   }
831 
832   const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
833 
834   // Make sure we have scalar values available to access the pointer to
835   // the data location.
836   extractScalarValues(Load, VectorMap, ScalarMaps);
837 
838   Value *NewLoad;
839   if (Access.isStrideZero(isl_map_copy(Schedule)))
840     NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
841   else if (Access.isStrideOne(isl_map_copy(Schedule)))
842     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
843   else if (Access.isStrideX(isl_map_copy(Schedule), -1))
844     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
845   else
846     NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
847 
848   VectorMap[Load] = NewLoad;
849 }
850 
851 void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
852                                          ValueMapT &VectorMap,
853                                          VectorValueMapT &ScalarMaps) {
854   int VectorWidth = getVectorWidth();
855   Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
856                                      ScalarMaps, getLoopForStmt(Stmt));
857 
858   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
859 
860   const CastInst *Cast = dyn_cast<CastInst>(Inst);
861   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
862   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
863 }
864 
865 void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
866                                           ValueMapT &VectorMap,
867                                           VectorValueMapT &ScalarMaps) {
868   Loop *L = getLoopForStmt(Stmt);
869   Value *OpZero = Inst->getOperand(0);
870   Value *OpOne = Inst->getOperand(1);
871 
872   Value *NewOpZero, *NewOpOne;
873   NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
874   NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
875 
876   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
877                                        Inst->getName() + "p_vec");
878   VectorMap[Inst] = NewInst;
879 }
880 
881 void VectorBlockGenerator::copyStore(
882     ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
883     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
884   const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
885 
886   auto *Pointer = Store->getPointerOperand();
887   Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
888                                  ScalarMaps, getLoopForStmt(Stmt));
889 
890   // Make sure we have scalar values available to access the pointer to
891   // the data location.
892   extractScalarValues(Store, VectorMap, ScalarMaps);
893 
894   if (Access.isStrideOne(isl_map_copy(Schedule))) {
895     Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
896     Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
897                                                  VLTS[0], NewAccesses);
898 
899     Value *VectorPtr =
900         Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
901     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
902 
903     if (!Aligned)
904       Store->setAlignment(8);
905   } else {
906     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
907       Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
908       Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
909                                                    VLTS[i], NewAccesses);
910       Builder.CreateStore(Scalar, NewPointer);
911     }
912   }
913 }
914 
915 bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
916                                              ValueMapT &VectorMap) {
917   for (Value *Operand : Inst->operands())
918     if (VectorMap.count(Operand))
919       return true;
920   return false;
921 }
922 
923 bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
924                                                ValueMapT &VectorMap,
925                                                VectorValueMapT &ScalarMaps) {
926   bool HasVectorOperand = false;
927   int VectorWidth = getVectorWidth();
928 
929   for (Value *Operand : Inst->operands()) {
930     ValueMapT::iterator VecOp = VectorMap.find(Operand);
931 
932     if (VecOp == VectorMap.end())
933       continue;
934 
935     HasVectorOperand = true;
936     Value *NewVector = VecOp->second;
937 
938     for (int i = 0; i < VectorWidth; ++i) {
939       ValueMapT &SM = ScalarMaps[i];
940 
941       // If there is one scalar extracted, all scalar elements should have
942       // already been extracted by the code here. So no need to check for the
943       // existence of all of them.
944       if (SM.count(Operand))
945         break;
946 
947       SM[Operand] =
948           Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
949     }
950   }
951 
952   return HasVectorOperand;
953 }
954 
955 void VectorBlockGenerator::copyInstScalarized(
956     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
957     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
958   bool HasVectorOperand;
959   int VectorWidth = getVectorWidth();
960 
961   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
962 
963   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
964     BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
965                                     VLTS[VectorLane], NewAccesses);
966 
967   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
968     return;
969 
970   // Make the result available as vector value.
971   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
972   Value *Vector = UndefValue::get(VectorType);
973 
974   for (int i = 0; i < VectorWidth; i++)
975     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
976                                          Builder.getInt32(i));
977 
978   VectorMap[Inst] = Vector;
979 }
980 
981 int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
982 
983 void VectorBlockGenerator::copyInstruction(
984     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
985     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
986   // Terminator instructions control the control flow. They are explicitly
987   // expressed in the clast and do not need to be copied.
988   if (Inst->isTerminator())
989     return;
990 
991   if (canSyntheziseInStmt(Stmt, Inst))
992     return;
993 
994   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
995     generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
996     return;
997   }
998 
999   if (hasVectorOperands(Inst, VectorMap)) {
1000     if (auto *Store = dyn_cast<StoreInst>(Inst)) {
1001       copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
1002       return;
1003     }
1004 
1005     if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1006       copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
1007       return;
1008     }
1009 
1010     if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1011       copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
1012       return;
1013     }
1014 
1015     // Falltrough: We generate scalar instructions, if we don't know how to
1016     // generate vector code.
1017   }
1018 
1019   copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
1020 }
1021 
1022 void VectorBlockGenerator::generateScalarVectorLoads(
1023     ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1024   for (MemoryAccess *MA : Stmt) {
1025     if (MA->isArrayKind() || MA->isWrite())
1026       continue;
1027 
1028     auto *Address = getOrCreateAlloca(*MA);
1029     Type *VectorPtrType = getVectorPtrTy(Address, 1);
1030     Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1031                                              Address->getName() + "_p_vec_p");
1032     auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1033     Constant *SplatVector = Constant::getNullValue(
1034         VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1035 
1036     Value *VectorVal = Builder.CreateShuffleVector(
1037         Val, Val, SplatVector, Address->getName() + "_p_splat");
1038     VectorBlockMap[MA->getBaseAddr()] = VectorVal;
1039   }
1040 }
1041 
1042 void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1043   for (MemoryAccess *MA : Stmt) {
1044     if (MA->isArrayKind() || MA->isRead())
1045       continue;
1046 
1047     llvm_unreachable("Scalar stores not expected in vector loop");
1048   }
1049 }
1050 
1051 void VectorBlockGenerator::copyStmt(
1052     ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1053   assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
1054                                "the vector block generator");
1055 
1056   BasicBlock *BB = Stmt.getBasicBlock();
1057   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1058                                   &*Builder.GetInsertPoint(), &DT, &LI);
1059   CopyBB->setName("polly.stmt." + BB->getName());
1060   Builder.SetInsertPoint(&CopyBB->front());
1061 
1062   // Create two maps that store the mapping from the original instructions of
1063   // the old basic block to their copies in the new basic block. Those maps
1064   // are basic block local.
1065   //
1066   // As vector code generation is supported there is one map for scalar values
1067   // and one for vector values.
1068   //
1069   // In case we just do scalar code generation, the vectorMap is not used and
1070   // the scalarMap has just one dimension, which contains the mapping.
1071   //
1072   // In case vector code generation is done, an instruction may either appear
1073   // in the vector map once (as it is calculating >vectorwidth< values at a
1074   // time. Or (if the values are calculated using scalar operations), it
1075   // appears once in every dimension of the scalarMap.
1076   VectorValueMapT ScalarBlockMap(getVectorWidth());
1077   ValueMapT VectorBlockMap;
1078 
1079   generateScalarVectorLoads(Stmt, VectorBlockMap);
1080 
1081   for (Instruction &Inst : *BB)
1082     copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1083 
1084   verifyNoScalarStores(Stmt);
1085 }
1086 
1087 BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1088                                              BasicBlock *BBCopy) {
1089 
1090   BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1091   BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1092 
1093   if (BBCopyIDom)
1094     DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1095 
1096   return BBCopyIDom;
1097 }
1098 
1099 // This is to determine whether an llvm::Value (defined in @p BB) is usable when
1100 // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1101 // does not work in cases where the exit block has edges from outside the
1102 // region. In that case the llvm::Value would never be usable in in the exit
1103 // block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1104 // for the subregion's exiting edges only. We need to determine whether an
1105 // llvm::Value is usable in there. We do this by checking whether it dominates
1106 // all exiting blocks individually.
1107 static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1108                                       BasicBlock *BB) {
1109   for (auto ExitingBB : predecessors(R->getExit())) {
1110     // Check for non-subregion incoming edges.
1111     if (!R->contains(ExitingBB))
1112       continue;
1113 
1114     if (!DT.dominates(BB, ExitingBB))
1115       return false;
1116   }
1117 
1118   return true;
1119 }
1120 
1121 // Find the direct dominator of the subregion's exit block if the subregion was
1122 // simplified.
1123 static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1124   BasicBlock *Common = nullptr;
1125   for (auto ExitingBB : predecessors(R->getExit())) {
1126     // Check for non-subregion incoming edges.
1127     if (!R->contains(ExitingBB))
1128       continue;
1129 
1130     // First exiting edge.
1131     if (!Common) {
1132       Common = ExitingBB;
1133       continue;
1134     }
1135 
1136     Common = DT.findNearestCommonDominator(Common, ExitingBB);
1137   }
1138 
1139   assert(Common && R->contains(Common));
1140   return Common;
1141 }
1142 
1143 void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
1144                                isl_id_to_ast_expr *IdToAstExp) {
1145   assert(Stmt.isRegionStmt() &&
1146          "Only region statements can be copied by the region generator");
1147 
1148   // Forget all old mappings.
1149   BlockMap.clear();
1150   RegionMaps.clear();
1151   IncompletePHINodeMap.clear();
1152 
1153   // Collection of all values related to this subregion.
1154   ValueMapT ValueMap;
1155 
1156   // The region represented by the statement.
1157   Region *R = Stmt.getRegion();
1158 
1159   // Create a dedicated entry for the region where we can reload all demoted
1160   // inputs.
1161   BasicBlock *EntryBB = R->getEntry();
1162   BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1163                                        &*Builder.GetInsertPoint(), &DT, &LI);
1164   EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1165   Builder.SetInsertPoint(&EntryBBCopy->front());
1166 
1167   ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1168   generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1169 
1170   for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1171     if (!R->contains(*PI))
1172       BlockMap[*PI] = EntryBBCopy;
1173 
1174   // Iterate over all blocks in the region in a breadth-first search.
1175   std::deque<BasicBlock *> Blocks;
1176   SmallPtrSet<BasicBlock *, 8> SeenBlocks;
1177   Blocks.push_back(EntryBB);
1178   SeenBlocks.insert(EntryBB);
1179 
1180   while (!Blocks.empty()) {
1181     BasicBlock *BB = Blocks.front();
1182     Blocks.pop_front();
1183 
1184     // First split the block and update dominance information.
1185     BasicBlock *BBCopy = splitBB(BB);
1186     BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1187 
1188     // Get the mapping for this block and initialize it with either the scalar
1189     // loads from the generated entering block (which dominates all blocks of
1190     // this subregion) or the maps of the immediate dominator, if part of the
1191     // subregion. The latter necessarily includes the former.
1192     ValueMapT *InitBBMap;
1193     if (BBCopyIDom) {
1194       assert(RegionMaps.count(BBCopyIDom));
1195       InitBBMap = &RegionMaps[BBCopyIDom];
1196     } else
1197       InitBBMap = &EntryBBMap;
1198     auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1199     ValueMapT &RegionMap = Inserted.first->second;
1200 
1201     // Copy the block with the BlockGenerator.
1202     Builder.SetInsertPoint(&BBCopy->front());
1203     copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1204 
1205     // In order to remap PHI nodes we store also basic block mappings.
1206     BlockMap[BB] = BBCopy;
1207 
1208     // Add values to incomplete PHI nodes waiting for this block to be copied.
1209     for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1210       addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1211     IncompletePHINodeMap[BB].clear();
1212 
1213     // And continue with new successors inside the region.
1214     for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1215       if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1216         Blocks.push_back(*SI);
1217 
1218     // Remember value in case it is visible after this subregion.
1219     if (isDominatingSubregionExit(DT, R, BB))
1220       ValueMap.insert(RegionMap.begin(), RegionMap.end());
1221   }
1222 
1223   // Now create a new dedicated region exit block and add it to the region map.
1224   BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1225                                       &*Builder.GetInsertPoint(), &DT, &LI);
1226   ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1227   BlockMap[R->getExit()] = ExitBBCopy;
1228 
1229   BasicBlock *ExitDomBBCopy = BlockMap.lookup(findExitDominator(DT, R));
1230   assert(ExitDomBBCopy && "Common exit dominator must be within region; at "
1231                           "least the entry node must match");
1232   DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1233 
1234   // As the block generator doesn't handle control flow we need to add the
1235   // region control flow by hand after all blocks have been copied.
1236   for (BasicBlock *BB : SeenBlocks) {
1237 
1238     BasicBlock *BBCopy = BlockMap[BB];
1239     TerminatorInst *TI = BB->getTerminator();
1240     if (isa<UnreachableInst>(TI)) {
1241       while (!BBCopy->empty())
1242         BBCopy->begin()->eraseFromParent();
1243       new UnreachableInst(BBCopy->getContext(), BBCopy);
1244       continue;
1245     }
1246 
1247     Instruction *BICopy = BBCopy->getTerminator();
1248 
1249     ValueMapT &RegionMap = RegionMaps[BBCopy];
1250     RegionMap.insert(BlockMap.begin(), BlockMap.end());
1251 
1252     Builder.SetInsertPoint(BICopy);
1253     copyInstScalar(Stmt, TI, RegionMap, LTS);
1254     BICopy->eraseFromParent();
1255   }
1256 
1257   // Add counting PHI nodes to all loops in the region that can be used as
1258   // replacement for SCEVs refering to the old loop.
1259   for (BasicBlock *BB : SeenBlocks) {
1260     Loop *L = LI.getLoopFor(BB);
1261     if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1262       continue;
1263 
1264     BasicBlock *BBCopy = BlockMap[BB];
1265     Value *NullVal = Builder.getInt32(0);
1266     PHINode *LoopPHI =
1267         PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1268     Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1269         LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1270     LoopPHI->insertBefore(&BBCopy->front());
1271     LoopPHIInc->insertBefore(BBCopy->getTerminator());
1272 
1273     for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1274       if (!R->contains(PredBB))
1275         continue;
1276       if (L->contains(PredBB))
1277         LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1278       else
1279         LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1280     }
1281 
1282     for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1283       if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1284         LoopPHI->addIncoming(NullVal, PredBBCopy);
1285 
1286     LTS[L] = SE.getUnknown(LoopPHI);
1287   }
1288 
1289   // Continue generating code in the exit block.
1290   Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1291 
1292   // Write values visible to other statements.
1293   generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1294   BlockMap.clear();
1295   RegionMaps.clear();
1296   IncompletePHINodeMap.clear();
1297 }
1298 
1299 PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1300                                        ValueMapT &BBMap, Loop *L) {
1301   ScopStmt *Stmt = MA->getStatement();
1302   Region *SubR = Stmt->getRegion();
1303   auto Incoming = MA->getIncoming();
1304 
1305   PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1306   PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1307   BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1308 
1309   // This can happen if the subregion is simplified after the ScopStmts
1310   // have been created; simplification happens as part of CodeGeneration.
1311   if (OrigPHI->getParent() != SubR->getExit()) {
1312     BasicBlock *FormerExit = SubR->getExitingBlock();
1313     if (FormerExit)
1314       NewSubregionExit = BlockMap.lookup(FormerExit);
1315   }
1316 
1317   PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1318                                     "polly." + OrigPHI->getName(),
1319                                     NewSubregionExit->getFirstNonPHI());
1320 
1321   // Add the incoming values to the PHI.
1322   for (auto &Pair : Incoming) {
1323     BasicBlock *OrigIncomingBlock = Pair.first;
1324     BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock);
1325     Builder.SetInsertPoint(NewIncomingBlock->getTerminator());
1326     assert(RegionMaps.count(NewIncomingBlock));
1327     ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock];
1328 
1329     Value *OrigIncomingValue = Pair.second;
1330     Value *NewIncomingValue =
1331         getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1332     NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock);
1333   }
1334 
1335   return NewPHI;
1336 }
1337 
1338 Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1339                                       ValueMapT &BBMap) {
1340   ScopStmt *Stmt = MA->getStatement();
1341 
1342   // TODO: Add some test cases that ensure this is really the right choice.
1343   Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1344 
1345   if (MA->isAnyPHIKind()) {
1346     auto Incoming = MA->getIncoming();
1347     assert(!Incoming.empty() &&
1348            "PHI WRITEs must have originate from at least one incoming block");
1349 
1350     // If there is only one incoming value, we do not need to create a PHI.
1351     if (Incoming.size() == 1) {
1352       Value *OldVal = Incoming[0].second;
1353       return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1354     }
1355 
1356     return buildExitPHI(MA, LTS, BBMap, L);
1357   }
1358 
1359   // MK_Value accesses leaving the subregion must dominate the exit block; just
1360   // pass the copied value
1361   Value *OldVal = MA->getAccessValue();
1362   return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1363 }
1364 
1365 void RegionGenerator::generateScalarStores(
1366     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1367     __isl_keep isl_id_to_ast_expr *NewAccesses) {
1368   assert(Stmt.getRegion() &&
1369          "Block statements need to use the generateScalarStores() "
1370          "function in the BlockGenerator");
1371 
1372   for (MemoryAccess *MA : Stmt) {
1373     if (MA->isOriginalArrayKind() || MA->isRead())
1374       continue;
1375 
1376     Value *NewVal = getExitScalar(MA, LTS, BBMap);
1377     Value *Address =
1378         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
1379     assert((!isa<Instruction>(NewVal) ||
1380             DT.dominates(cast<Instruction>(NewVal)->getParent(),
1381                          Builder.GetInsertBlock())) &&
1382            "Domination violation");
1383     assert((!isa<Instruction>(Address) ||
1384             DT.dominates(cast<Instruction>(Address)->getParent(),
1385                          Builder.GetInsertBlock())) &&
1386            "Domination violation");
1387     Builder.CreateStore(NewVal, Address);
1388   }
1389 }
1390 
1391 void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1392                                       PHINode *PHICopy, BasicBlock *IncomingBB,
1393                                       LoopToScevMapT &LTS) {
1394   Region *StmtR = Stmt.getRegion();
1395 
1396   // If the incoming block was not yet copied mark this PHI as incomplete.
1397   // Once the block will be copied the incoming value will be added.
1398   BasicBlock *BBCopy = BlockMap[IncomingBB];
1399   if (!BBCopy) {
1400     assert(StmtR->contains(IncomingBB) &&
1401            "Bad incoming block for PHI in non-affine region");
1402     IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1403     return;
1404   }
1405 
1406   Value *OpCopy = nullptr;
1407   if (StmtR->contains(IncomingBB)) {
1408     assert(RegionMaps.count(BBCopy) &&
1409            "Incoming PHI block did not have a BBMap");
1410     ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1411 
1412     Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1413 
1414     // If the current insert block is different from the PHIs incoming block
1415     // change it, otherwise do not.
1416     auto IP = Builder.GetInsertPoint();
1417     if (IP->getParent() != BBCopy)
1418       Builder.SetInsertPoint(BBCopy->getTerminator());
1419     OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1420     if (IP->getParent() != BBCopy)
1421       Builder.SetInsertPoint(&*IP);
1422   } else {
1423 
1424     if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1425       return;
1426 
1427     Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
1428     OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1429                           BlockMap[IncomingBB]->getTerminator());
1430   }
1431 
1432   assert(OpCopy && "Incoming PHI value was not copied properly");
1433   assert(BBCopy && "Incoming PHI block was not copied properly");
1434   PHICopy->addIncoming(OpCopy, BBCopy);
1435 }
1436 
1437 void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1438                                          ValueMapT &BBMap,
1439                                          LoopToScevMapT &LTS) {
1440   unsigned NumIncoming = PHI->getNumIncomingValues();
1441   PHINode *PHICopy =
1442       Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1443   PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1444   BBMap[PHI] = PHICopy;
1445 
1446   for (unsigned u = 0; u < NumIncoming; u++)
1447     addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
1448 }
1449