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.isCopyStmt())
685       continue;
686     else if (Stmt.isBlockStmt())
687       for (auto &Inst : *Stmt.getBasicBlock())
688         SE.forgetValue(&Inst);
689     else if (Stmt.isRegionStmt())
690       for (auto *BB : Stmt.getRegion()->blocks())
691         for (auto &Inst : *BB)
692           SE.forgetValue(&Inst);
693     else
694       llvm_unreachable("Unexpected statement type found");
695 }
696 
697 void BlockGenerator::finalizeSCoP(Scop &S) {
698   findOutsideUsers(S);
699   createScalarInitialization(S);
700   createExitPHINodeMerges(S);
701   createScalarFinalization(S);
702   invalidateScalarEvolution(S);
703 }
704 
705 VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
706                                            std::vector<LoopToScevMapT> &VLTS,
707                                            isl_map *Schedule)
708     : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
709   assert(Schedule && "No statement domain provided");
710 }
711 
712 Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
713                                             ValueMapT &VectorMap,
714                                             VectorValueMapT &ScalarMaps,
715                                             Loop *L) {
716   if (Value *NewValue = VectorMap.lookup(Old))
717     return NewValue;
718 
719   int Width = getVectorWidth();
720 
721   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
722 
723   for (int Lane = 0; Lane < Width; Lane++)
724     Vector = Builder.CreateInsertElement(
725         Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
726         Builder.getInt32(Lane));
727 
728   VectorMap[Old] = Vector;
729 
730   return Vector;
731 }
732 
733 Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
734   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
735   assert(PointerTy && "PointerType expected");
736 
737   Type *ScalarType = PointerTy->getElementType();
738   VectorType *VectorType = VectorType::get(ScalarType, Width);
739 
740   return PointerType::getUnqual(VectorType);
741 }
742 
743 Value *VectorBlockGenerator::generateStrideOneLoad(
744     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
745     __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
746   unsigned VectorWidth = getVectorWidth();
747   auto *Pointer = Load->getPointerOperand();
748   Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
749   unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
750 
751   Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
752                                                VLTS[Offset], NewAccesses);
753   Value *VectorPtr =
754       Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
755   LoadInst *VecLoad =
756       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
757   if (!Aligned)
758     VecLoad->setAlignment(8);
759 
760   if (NegativeStride) {
761     SmallVector<Constant *, 16> Indices;
762     for (int i = VectorWidth - 1; i >= 0; i--)
763       Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
764     Constant *SV = llvm::ConstantVector::get(Indices);
765     Value *RevVecLoad = Builder.CreateShuffleVector(
766         VecLoad, VecLoad, SV, Load->getName() + "_reverse");
767     return RevVecLoad;
768   }
769 
770   return VecLoad;
771 }
772 
773 Value *VectorBlockGenerator::generateStrideZeroLoad(
774     ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
775     __isl_keep isl_id_to_ast_expr *NewAccesses) {
776   auto *Pointer = Load->getPointerOperand();
777   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
778   Value *NewPointer =
779       generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
780   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
781                                            Load->getName() + "_p_vec_p");
782   LoadInst *ScalarLoad =
783       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
784 
785   if (!Aligned)
786     ScalarLoad->setAlignment(8);
787 
788   Constant *SplatVector = Constant::getNullValue(
789       VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
790 
791   Value *VectorLoad = Builder.CreateShuffleVector(
792       ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
793   return VectorLoad;
794 }
795 
796 Value *VectorBlockGenerator::generateUnknownStrideLoad(
797     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
798     __isl_keep isl_id_to_ast_expr *NewAccesses) {
799   int VectorWidth = getVectorWidth();
800   auto *Pointer = Load->getPointerOperand();
801   VectorType *VectorType = VectorType::get(
802       dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
803 
804   Value *Vector = UndefValue::get(VectorType);
805 
806   for (int i = 0; i < VectorWidth; i++) {
807     Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
808                                                  VLTS[i], NewAccesses);
809     Value *ScalarLoad =
810         Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
811     Vector = Builder.CreateInsertElement(
812         Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
813   }
814 
815   return Vector;
816 }
817 
818 void VectorBlockGenerator::generateLoad(
819     ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
820     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
821   if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
822     VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
823                                                 Load->getName() + "_p");
824     return;
825   }
826 
827   if (!VectorType::isValidElementType(Load->getType())) {
828     for (int i = 0; i < getVectorWidth(); i++)
829       ScalarMaps[i][Load] =
830           generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
831     return;
832   }
833 
834   const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
835 
836   // Make sure we have scalar values available to access the pointer to
837   // the data location.
838   extractScalarValues(Load, VectorMap, ScalarMaps);
839 
840   Value *NewLoad;
841   if (Access.isStrideZero(isl_map_copy(Schedule)))
842     NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
843   else if (Access.isStrideOne(isl_map_copy(Schedule)))
844     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
845   else if (Access.isStrideX(isl_map_copy(Schedule), -1))
846     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
847   else
848     NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
849 
850   VectorMap[Load] = NewLoad;
851 }
852 
853 void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
854                                          ValueMapT &VectorMap,
855                                          VectorValueMapT &ScalarMaps) {
856   int VectorWidth = getVectorWidth();
857   Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
858                                      ScalarMaps, getLoopForStmt(Stmt));
859 
860   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
861 
862   const CastInst *Cast = dyn_cast<CastInst>(Inst);
863   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
864   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
865 }
866 
867 void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
868                                           ValueMapT &VectorMap,
869                                           VectorValueMapT &ScalarMaps) {
870   Loop *L = getLoopForStmt(Stmt);
871   Value *OpZero = Inst->getOperand(0);
872   Value *OpOne = Inst->getOperand(1);
873 
874   Value *NewOpZero, *NewOpOne;
875   NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
876   NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
877 
878   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
879                                        Inst->getName() + "p_vec");
880   VectorMap[Inst] = NewInst;
881 }
882 
883 void VectorBlockGenerator::copyStore(
884     ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
885     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
886   const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
887 
888   auto *Pointer = Store->getPointerOperand();
889   Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
890                                  ScalarMaps, getLoopForStmt(Stmt));
891 
892   // Make sure we have scalar values available to access the pointer to
893   // the data location.
894   extractScalarValues(Store, VectorMap, ScalarMaps);
895 
896   if (Access.isStrideOne(isl_map_copy(Schedule))) {
897     Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
898     Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
899                                                  VLTS[0], NewAccesses);
900 
901     Value *VectorPtr =
902         Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
903     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
904 
905     if (!Aligned)
906       Store->setAlignment(8);
907   } else {
908     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
909       Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
910       Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
911                                                    VLTS[i], NewAccesses);
912       Builder.CreateStore(Scalar, NewPointer);
913     }
914   }
915 }
916 
917 bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
918                                              ValueMapT &VectorMap) {
919   for (Value *Operand : Inst->operands())
920     if (VectorMap.count(Operand))
921       return true;
922   return false;
923 }
924 
925 bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
926                                                ValueMapT &VectorMap,
927                                                VectorValueMapT &ScalarMaps) {
928   bool HasVectorOperand = false;
929   int VectorWidth = getVectorWidth();
930 
931   for (Value *Operand : Inst->operands()) {
932     ValueMapT::iterator VecOp = VectorMap.find(Operand);
933 
934     if (VecOp == VectorMap.end())
935       continue;
936 
937     HasVectorOperand = true;
938     Value *NewVector = VecOp->second;
939 
940     for (int i = 0; i < VectorWidth; ++i) {
941       ValueMapT &SM = ScalarMaps[i];
942 
943       // If there is one scalar extracted, all scalar elements should have
944       // already been extracted by the code here. So no need to check for the
945       // existence of all of them.
946       if (SM.count(Operand))
947         break;
948 
949       SM[Operand] =
950           Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
951     }
952   }
953 
954   return HasVectorOperand;
955 }
956 
957 void VectorBlockGenerator::copyInstScalarized(
958     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
959     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
960   bool HasVectorOperand;
961   int VectorWidth = getVectorWidth();
962 
963   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
964 
965   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
966     BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
967                                     VLTS[VectorLane], NewAccesses);
968 
969   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
970     return;
971 
972   // Make the result available as vector value.
973   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
974   Value *Vector = UndefValue::get(VectorType);
975 
976   for (int i = 0; i < VectorWidth; i++)
977     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
978                                          Builder.getInt32(i));
979 
980   VectorMap[Inst] = Vector;
981 }
982 
983 int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
984 
985 void VectorBlockGenerator::copyInstruction(
986     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
987     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
988   // Terminator instructions control the control flow. They are explicitly
989   // expressed in the clast and do not need to be copied.
990   if (Inst->isTerminator())
991     return;
992 
993   if (canSyntheziseInStmt(Stmt, Inst))
994     return;
995 
996   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
997     generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
998     return;
999   }
1000 
1001   if (hasVectorOperands(Inst, VectorMap)) {
1002     if (auto *Store = dyn_cast<StoreInst>(Inst)) {
1003       copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
1004       return;
1005     }
1006 
1007     if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1008       copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
1009       return;
1010     }
1011 
1012     if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1013       copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
1014       return;
1015     }
1016 
1017     // Falltrough: We generate scalar instructions, if we don't know how to
1018     // generate vector code.
1019   }
1020 
1021   copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
1022 }
1023 
1024 void VectorBlockGenerator::generateScalarVectorLoads(
1025     ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1026   for (MemoryAccess *MA : Stmt) {
1027     if (MA->isArrayKind() || MA->isWrite())
1028       continue;
1029 
1030     auto *Address = getOrCreateAlloca(*MA);
1031     Type *VectorPtrType = getVectorPtrTy(Address, 1);
1032     Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1033                                              Address->getName() + "_p_vec_p");
1034     auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1035     Constant *SplatVector = Constant::getNullValue(
1036         VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1037 
1038     Value *VectorVal = Builder.CreateShuffleVector(
1039         Val, Val, SplatVector, Address->getName() + "_p_splat");
1040     VectorBlockMap[MA->getBaseAddr()] = VectorVal;
1041   }
1042 }
1043 
1044 void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1045   for (MemoryAccess *MA : Stmt) {
1046     if (MA->isArrayKind() || MA->isRead())
1047       continue;
1048 
1049     llvm_unreachable("Scalar stores not expected in vector loop");
1050   }
1051 }
1052 
1053 void VectorBlockGenerator::copyStmt(
1054     ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1055   assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
1056                                "the vector block generator");
1057 
1058   BasicBlock *BB = Stmt.getBasicBlock();
1059   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1060                                   &*Builder.GetInsertPoint(), &DT, &LI);
1061   CopyBB->setName("polly.stmt." + BB->getName());
1062   Builder.SetInsertPoint(&CopyBB->front());
1063 
1064   // Create two maps that store the mapping from the original instructions of
1065   // the old basic block to their copies in the new basic block. Those maps
1066   // are basic block local.
1067   //
1068   // As vector code generation is supported there is one map for scalar values
1069   // and one for vector values.
1070   //
1071   // In case we just do scalar code generation, the vectorMap is not used and
1072   // the scalarMap has just one dimension, which contains the mapping.
1073   //
1074   // In case vector code generation is done, an instruction may either appear
1075   // in the vector map once (as it is calculating >vectorwidth< values at a
1076   // time. Or (if the values are calculated using scalar operations), it
1077   // appears once in every dimension of the scalarMap.
1078   VectorValueMapT ScalarBlockMap(getVectorWidth());
1079   ValueMapT VectorBlockMap;
1080 
1081   generateScalarVectorLoads(Stmt, VectorBlockMap);
1082 
1083   for (Instruction &Inst : *BB)
1084     copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1085 
1086   verifyNoScalarStores(Stmt);
1087 }
1088 
1089 BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1090                                              BasicBlock *BBCopy) {
1091 
1092   BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1093   BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1094 
1095   if (BBCopyIDom)
1096     DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1097 
1098   return BBCopyIDom;
1099 }
1100 
1101 // This is to determine whether an llvm::Value (defined in @p BB) is usable when
1102 // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1103 // does not work in cases where the exit block has edges from outside the
1104 // region. In that case the llvm::Value would never be usable in in the exit
1105 // block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1106 // for the subregion's exiting edges only. We need to determine whether an
1107 // llvm::Value is usable in there. We do this by checking whether it dominates
1108 // all exiting blocks individually.
1109 static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1110                                       BasicBlock *BB) {
1111   for (auto ExitingBB : predecessors(R->getExit())) {
1112     // Check for non-subregion incoming edges.
1113     if (!R->contains(ExitingBB))
1114       continue;
1115 
1116     if (!DT.dominates(BB, ExitingBB))
1117       return false;
1118   }
1119 
1120   return true;
1121 }
1122 
1123 // Find the direct dominator of the subregion's exit block if the subregion was
1124 // simplified.
1125 static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1126   BasicBlock *Common = nullptr;
1127   for (auto ExitingBB : predecessors(R->getExit())) {
1128     // Check for non-subregion incoming edges.
1129     if (!R->contains(ExitingBB))
1130       continue;
1131 
1132     // First exiting edge.
1133     if (!Common) {
1134       Common = ExitingBB;
1135       continue;
1136     }
1137 
1138     Common = DT.findNearestCommonDominator(Common, ExitingBB);
1139   }
1140 
1141   assert(Common && R->contains(Common));
1142   return Common;
1143 }
1144 
1145 void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
1146                                isl_id_to_ast_expr *IdToAstExp) {
1147   assert(Stmt.isRegionStmt() &&
1148          "Only region statements can be copied by the region generator");
1149 
1150   // Forget all old mappings.
1151   BlockMap.clear();
1152   RegionMaps.clear();
1153   IncompletePHINodeMap.clear();
1154 
1155   // Collection of all values related to this subregion.
1156   ValueMapT ValueMap;
1157 
1158   // The region represented by the statement.
1159   Region *R = Stmt.getRegion();
1160 
1161   // Create a dedicated entry for the region where we can reload all demoted
1162   // inputs.
1163   BasicBlock *EntryBB = R->getEntry();
1164   BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1165                                        &*Builder.GetInsertPoint(), &DT, &LI);
1166   EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1167   Builder.SetInsertPoint(&EntryBBCopy->front());
1168 
1169   ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1170   generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1171 
1172   for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1173     if (!R->contains(*PI))
1174       BlockMap[*PI] = EntryBBCopy;
1175 
1176   // Iterate over all blocks in the region in a breadth-first search.
1177   std::deque<BasicBlock *> Blocks;
1178   SmallPtrSet<BasicBlock *, 8> SeenBlocks;
1179   Blocks.push_back(EntryBB);
1180   SeenBlocks.insert(EntryBB);
1181 
1182   while (!Blocks.empty()) {
1183     BasicBlock *BB = Blocks.front();
1184     Blocks.pop_front();
1185 
1186     // First split the block and update dominance information.
1187     BasicBlock *BBCopy = splitBB(BB);
1188     BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1189 
1190     // Get the mapping for this block and initialize it with either the scalar
1191     // loads from the generated entering block (which dominates all blocks of
1192     // this subregion) or the maps of the immediate dominator, if part of the
1193     // subregion. The latter necessarily includes the former.
1194     ValueMapT *InitBBMap;
1195     if (BBCopyIDom) {
1196       assert(RegionMaps.count(BBCopyIDom));
1197       InitBBMap = &RegionMaps[BBCopyIDom];
1198     } else
1199       InitBBMap = &EntryBBMap;
1200     auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1201     ValueMapT &RegionMap = Inserted.first->second;
1202 
1203     // Copy the block with the BlockGenerator.
1204     Builder.SetInsertPoint(&BBCopy->front());
1205     copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1206 
1207     // In order to remap PHI nodes we store also basic block mappings.
1208     BlockMap[BB] = BBCopy;
1209 
1210     // Add values to incomplete PHI nodes waiting for this block to be copied.
1211     for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1212       addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1213     IncompletePHINodeMap[BB].clear();
1214 
1215     // And continue with new successors inside the region.
1216     for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1217       if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1218         Blocks.push_back(*SI);
1219 
1220     // Remember value in case it is visible after this subregion.
1221     if (isDominatingSubregionExit(DT, R, BB))
1222       ValueMap.insert(RegionMap.begin(), RegionMap.end());
1223   }
1224 
1225   // Now create a new dedicated region exit block and add it to the region map.
1226   BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1227                                       &*Builder.GetInsertPoint(), &DT, &LI);
1228   ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1229   BlockMap[R->getExit()] = ExitBBCopy;
1230 
1231   BasicBlock *ExitDomBBCopy = BlockMap.lookup(findExitDominator(DT, R));
1232   assert(ExitDomBBCopy && "Common exit dominator must be within region; at "
1233                           "least the entry node must match");
1234   DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1235 
1236   // As the block generator doesn't handle control flow we need to add the
1237   // region control flow by hand after all blocks have been copied.
1238   for (BasicBlock *BB : SeenBlocks) {
1239 
1240     BasicBlock *BBCopy = BlockMap[BB];
1241     TerminatorInst *TI = BB->getTerminator();
1242     if (isa<UnreachableInst>(TI)) {
1243       while (!BBCopy->empty())
1244         BBCopy->begin()->eraseFromParent();
1245       new UnreachableInst(BBCopy->getContext(), BBCopy);
1246       continue;
1247     }
1248 
1249     Instruction *BICopy = BBCopy->getTerminator();
1250 
1251     ValueMapT &RegionMap = RegionMaps[BBCopy];
1252     RegionMap.insert(BlockMap.begin(), BlockMap.end());
1253 
1254     Builder.SetInsertPoint(BICopy);
1255     copyInstScalar(Stmt, TI, RegionMap, LTS);
1256     BICopy->eraseFromParent();
1257   }
1258 
1259   // Add counting PHI nodes to all loops in the region that can be used as
1260   // replacement for SCEVs refering to the old loop.
1261   for (BasicBlock *BB : SeenBlocks) {
1262     Loop *L = LI.getLoopFor(BB);
1263     if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1264       continue;
1265 
1266     BasicBlock *BBCopy = BlockMap[BB];
1267     Value *NullVal = Builder.getInt32(0);
1268     PHINode *LoopPHI =
1269         PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1270     Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1271         LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1272     LoopPHI->insertBefore(&BBCopy->front());
1273     LoopPHIInc->insertBefore(BBCopy->getTerminator());
1274 
1275     for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1276       if (!R->contains(PredBB))
1277         continue;
1278       if (L->contains(PredBB))
1279         LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1280       else
1281         LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1282     }
1283 
1284     for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1285       if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1286         LoopPHI->addIncoming(NullVal, PredBBCopy);
1287 
1288     LTS[L] = SE.getUnknown(LoopPHI);
1289   }
1290 
1291   // Continue generating code in the exit block.
1292   Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1293 
1294   // Write values visible to other statements.
1295   generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1296   BlockMap.clear();
1297   RegionMaps.clear();
1298   IncompletePHINodeMap.clear();
1299 }
1300 
1301 PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1302                                        ValueMapT &BBMap, Loop *L) {
1303   ScopStmt *Stmt = MA->getStatement();
1304   Region *SubR = Stmt->getRegion();
1305   auto Incoming = MA->getIncoming();
1306 
1307   PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1308   PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1309   BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1310 
1311   // This can happen if the subregion is simplified after the ScopStmts
1312   // have been created; simplification happens as part of CodeGeneration.
1313   if (OrigPHI->getParent() != SubR->getExit()) {
1314     BasicBlock *FormerExit = SubR->getExitingBlock();
1315     if (FormerExit)
1316       NewSubregionExit = BlockMap.lookup(FormerExit);
1317   }
1318 
1319   PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1320                                     "polly." + OrigPHI->getName(),
1321                                     NewSubregionExit->getFirstNonPHI());
1322 
1323   // Add the incoming values to the PHI.
1324   for (auto &Pair : Incoming) {
1325     BasicBlock *OrigIncomingBlock = Pair.first;
1326     BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock);
1327     Builder.SetInsertPoint(NewIncomingBlock->getTerminator());
1328     assert(RegionMaps.count(NewIncomingBlock));
1329     ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock];
1330 
1331     Value *OrigIncomingValue = Pair.second;
1332     Value *NewIncomingValue =
1333         getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1334     NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock);
1335   }
1336 
1337   return NewPHI;
1338 }
1339 
1340 Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1341                                       ValueMapT &BBMap) {
1342   ScopStmt *Stmt = MA->getStatement();
1343 
1344   // TODO: Add some test cases that ensure this is really the right choice.
1345   Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1346 
1347   if (MA->isAnyPHIKind()) {
1348     auto Incoming = MA->getIncoming();
1349     assert(!Incoming.empty() &&
1350            "PHI WRITEs must have originate from at least one incoming block");
1351 
1352     // If there is only one incoming value, we do not need to create a PHI.
1353     if (Incoming.size() == 1) {
1354       Value *OldVal = Incoming[0].second;
1355       return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1356     }
1357 
1358     return buildExitPHI(MA, LTS, BBMap, L);
1359   }
1360 
1361   // MK_Value accesses leaving the subregion must dominate the exit block; just
1362   // pass the copied value
1363   Value *OldVal = MA->getAccessValue();
1364   return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1365 }
1366 
1367 void RegionGenerator::generateScalarStores(
1368     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1369     __isl_keep isl_id_to_ast_expr *NewAccesses) {
1370   assert(Stmt.getRegion() &&
1371          "Block statements need to use the generateScalarStores() "
1372          "function in the BlockGenerator");
1373 
1374   for (MemoryAccess *MA : Stmt) {
1375     if (MA->isOriginalArrayKind() || MA->isRead())
1376       continue;
1377 
1378     Value *NewVal = getExitScalar(MA, LTS, BBMap);
1379     Value *Address =
1380         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
1381     assert((!isa<Instruction>(NewVal) ||
1382             DT.dominates(cast<Instruction>(NewVal)->getParent(),
1383                          Builder.GetInsertBlock())) &&
1384            "Domination violation");
1385     assert((!isa<Instruction>(Address) ||
1386             DT.dominates(cast<Instruction>(Address)->getParent(),
1387                          Builder.GetInsertBlock())) &&
1388            "Domination violation");
1389     Builder.CreateStore(NewVal, Address);
1390   }
1391 }
1392 
1393 void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1394                                       PHINode *PHICopy, BasicBlock *IncomingBB,
1395                                       LoopToScevMapT &LTS) {
1396   Region *StmtR = Stmt.getRegion();
1397 
1398   // If the incoming block was not yet copied mark this PHI as incomplete.
1399   // Once the block will be copied the incoming value will be added.
1400   BasicBlock *BBCopy = BlockMap[IncomingBB];
1401   if (!BBCopy) {
1402     assert(StmtR->contains(IncomingBB) &&
1403            "Bad incoming block for PHI in non-affine region");
1404     IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1405     return;
1406   }
1407 
1408   Value *OpCopy = nullptr;
1409   if (StmtR->contains(IncomingBB)) {
1410     assert(RegionMaps.count(BBCopy) &&
1411            "Incoming PHI block did not have a BBMap");
1412     ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1413 
1414     Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1415 
1416     // If the current insert block is different from the PHIs incoming block
1417     // change it, otherwise do not.
1418     auto IP = Builder.GetInsertPoint();
1419     if (IP->getParent() != BBCopy)
1420       Builder.SetInsertPoint(BBCopy->getTerminator());
1421     OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1422     if (IP->getParent() != BBCopy)
1423       Builder.SetInsertPoint(&*IP);
1424   } else {
1425 
1426     if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1427       return;
1428 
1429     Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
1430     OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1431                           BlockMap[IncomingBB]->getTerminator());
1432   }
1433 
1434   assert(OpCopy && "Incoming PHI value was not copied properly");
1435   assert(BBCopy && "Incoming PHI block was not copied properly");
1436   PHICopy->addIncoming(OpCopy, BBCopy);
1437 }
1438 
1439 void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1440                                          ValueMapT &BBMap,
1441                                          LoopToScevMapT &LTS) {
1442   unsigned NumIncoming = PHI->getNumIncomingValues();
1443   PHINode *PHICopy =
1444       Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1445   PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1446   BBMap[PHI] = PHICopy;
1447 
1448   for (unsigned u = 0; u < NumIncoming; u++)
1449     addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
1450 }
1451