1 //===- ScopHelper.cpp - Some Helper Functions for Scop.  ------------------===//
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 // Small functions that help with Scop and LLVM-IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "polly/Support/ScopHelper.h"
15 #include "polly/Options.h"
16 #include "polly/ScopInfo.h"
17 #include "polly/Support/SCEVValidator.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/RegionInfo.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Analysis/ScalarEvolutionExpander.h"
22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 
28 using namespace llvm;
29 using namespace polly;
30 
31 #define DEBUG_TYPE "polly-scop-helper"
32 
33 static cl::opt<bool> PollyAllowErrorBlocks(
34     "polly-allow-error-blocks",
35     cl::desc("Allow to speculate on the execution of 'error blocks'."),
36     cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
37 
38 bool polly::hasInvokeEdge(const PHINode *PN) {
39   for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
40     if (InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i)))
41       if (II->getParent() == PN->getIncomingBlock(i))
42         return true;
43 
44   return false;
45 }
46 
47 // Ensures that there is just one predecessor to the entry node from outside the
48 // region.
49 // The identity of the region entry node is preserved.
50 static void simplifyRegionEntry(Region *R, DominatorTree *DT, LoopInfo *LI,
51                                 RegionInfo *RI) {
52   BasicBlock *EnteringBB = R->getEnteringBlock();
53   BasicBlock *Entry = R->getEntry();
54 
55   // Before (one of):
56   //
57   //                       \    /            //
58   //                      EnteringBB         //
59   //                        |    \------>    //
60   //   \   /                |                //
61   //   Entry <--\         Entry <--\         //
62   //   /   \    /         /   \    /         //
63   //        ....               ....          //
64 
65   // Create single entry edge if the region has multiple entry edges.
66   if (!EnteringBB) {
67     SmallVector<BasicBlock *, 4> Preds;
68     for (BasicBlock *P : predecessors(Entry))
69       if (!R->contains(P))
70         Preds.push_back(P);
71 
72     BasicBlock *NewEntering =
73         SplitBlockPredecessors(Entry, Preds, ".region_entering", DT, LI);
74 
75     if (RI) {
76       // The exit block of predecessing regions must be changed to NewEntering
77       for (BasicBlock *ExitPred : predecessors(NewEntering)) {
78         Region *RegionOfPred = RI->getRegionFor(ExitPred);
79         if (RegionOfPred->getExit() != Entry)
80           continue;
81 
82         while (!RegionOfPred->isTopLevelRegion() &&
83                RegionOfPred->getExit() == Entry) {
84           RegionOfPred->replaceExit(NewEntering);
85           RegionOfPred = RegionOfPred->getParent();
86         }
87       }
88 
89       // Make all ancestors use EnteringBB as entry; there might be edges to it
90       Region *AncestorR = R->getParent();
91       RI->setRegionFor(NewEntering, AncestorR);
92       while (!AncestorR->isTopLevelRegion() && AncestorR->getEntry() == Entry) {
93         AncestorR->replaceEntry(NewEntering);
94         AncestorR = AncestorR->getParent();
95       }
96     }
97 
98     EnteringBB = NewEntering;
99   }
100   assert(R->getEnteringBlock() == EnteringBB);
101 
102   // After:
103   //
104   //    \    /       //
105   //  EnteringBB     //
106   //      |          //
107   //      |          //
108   //    Entry <--\   //
109   //    /   \    /   //
110   //         ....    //
111 }
112 
113 // Ensure that the region has a single block that branches to the exit node.
114 static void simplifyRegionExit(Region *R, DominatorTree *DT, LoopInfo *LI,
115                                RegionInfo *RI) {
116   BasicBlock *ExitBB = R->getExit();
117   BasicBlock *ExitingBB = R->getExitingBlock();
118 
119   // Before:
120   //
121   //   (Region)   ______/  //
122   //      \  |   /         //
123   //       ExitBB          //
124   //       /    \          //
125 
126   if (!ExitingBB) {
127     SmallVector<BasicBlock *, 4> Preds;
128     for (BasicBlock *P : predecessors(ExitBB))
129       if (R->contains(P))
130         Preds.push_back(P);
131 
132     //  Preds[0] Preds[1]      otherBB //
133     //         \  |  ________/         //
134     //          \ | /                  //
135     //           BB                    //
136     ExitingBB =
137         SplitBlockPredecessors(ExitBB, Preds, ".region_exiting", DT, LI);
138     // Preds[0] Preds[1]      otherBB  //
139     //        \  /           /         //
140     // BB.region_exiting    /          //
141     //                  \  /           //
142     //                   BB            //
143 
144     if (RI)
145       RI->setRegionFor(ExitingBB, R);
146 
147     // Change the exit of nested regions, but not the region itself,
148     R->replaceExitRecursive(ExitingBB);
149     R->replaceExit(ExitBB);
150   }
151   assert(ExitingBB == R->getExitingBlock());
152 
153   // After:
154   //
155   //     \   /                //
156   //    ExitingBB     _____/  //
157   //          \      /        //
158   //           ExitBB         //
159   //           /    \         //
160 }
161 
162 void polly::simplifyRegion(Region *R, DominatorTree *DT, LoopInfo *LI,
163                            RegionInfo *RI) {
164   assert(R && !R->isTopLevelRegion());
165   assert(!RI || RI == R->getRegionInfo());
166   assert((!RI || DT) &&
167          "RegionInfo requires DominatorTree to be updated as well");
168 
169   simplifyRegionEntry(R, DT, LI, RI);
170   simplifyRegionExit(R, DT, LI, RI);
171   assert(R->isSimple());
172 }
173 
174 // Split the block into two successive blocks.
175 //
176 // Like llvm::SplitBlock, but also preserves RegionInfo
177 static BasicBlock *splitBlock(BasicBlock *Old, Instruction *SplitPt,
178                               DominatorTree *DT, llvm::LoopInfo *LI,
179                               RegionInfo *RI) {
180   assert(Old && SplitPt);
181 
182   // Before:
183   //
184   //  \   /  //
185   //   Old   //
186   //  /   \  //
187 
188   BasicBlock *NewBlock = llvm::SplitBlock(Old, SplitPt, DT, LI);
189 
190   if (RI) {
191     Region *R = RI->getRegionFor(Old);
192     RI->setRegionFor(NewBlock, R);
193   }
194 
195   // After:
196   //
197   //   \   /    //
198   //    Old     //
199   //     |      //
200   //  NewBlock  //
201   //   /   \    //
202 
203   return NewBlock;
204 }
205 
206 void polly::splitEntryBlockForAlloca(BasicBlock *EntryBlock, Pass *P) {
207   // Find first non-alloca instruction. Every basic block has a non-alloc
208   // instruction, as every well formed basic block has a terminator.
209   BasicBlock::iterator I = EntryBlock->begin();
210   while (isa<AllocaInst>(I))
211     ++I;
212 
213   auto *DTWP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
214   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
215   auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
216   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
217   RegionInfoPass *RIP = P->getAnalysisIfAvailable<RegionInfoPass>();
218   RegionInfo *RI = RIP ? &RIP->getRegionInfo() : nullptr;
219 
220   // splitBlock updates DT, LI and RI.
221   splitBlock(EntryBlock, &*I, DT, LI, RI);
222 }
223 
224 /// The SCEVExpander will __not__ generate any code for an existing SDiv/SRem
225 /// instruction but just use it, if it is referenced as a SCEVUnknown. We want
226 /// however to generate new code if the instruction is in the analyzed region
227 /// and we generate code outside/in front of that region. Hence, we generate the
228 /// code for the SDiv/SRem operands in front of the analyzed region and then
229 /// create a new SDiv/SRem operation there too.
230 struct ScopExpander : SCEVVisitor<ScopExpander, const SCEV *> {
231   friend struct SCEVVisitor<ScopExpander, const SCEV *>;
232 
233   explicit ScopExpander(const Region &R, ScalarEvolution &SE,
234                         const DataLayout &DL, const char *Name, ValueMapT *VMap,
235                         BasicBlock *RTCBB)
236       : Expander(SCEVExpander(SE, DL, Name)), SE(SE), Name(Name), R(R),
237         VMap(VMap), RTCBB(RTCBB) {}
238 
239   Value *expandCodeFor(const SCEV *E, Type *Ty, Instruction *I) {
240     // If we generate code in the region we will immediately fall back to the
241     // SCEVExpander, otherwise we will stop at all unknowns in the SCEV and if
242     // needed replace them by copies computed in the entering block.
243     if (!R.contains(I))
244       E = visit(E);
245     return Expander.expandCodeFor(E, Ty, I);
246   }
247 
248 private:
249   SCEVExpander Expander;
250   ScalarEvolution &SE;
251   const char *Name;
252   const Region &R;
253   ValueMapT *VMap;
254   BasicBlock *RTCBB;
255 
256   const SCEV *visitGenericInst(const SCEVUnknown *E, Instruction *Inst,
257                                Instruction *IP) {
258     if (!Inst || !R.contains(Inst))
259       return E;
260 
261     assert(!Inst->mayThrow() && !Inst->mayReadOrWriteMemory() &&
262            !isa<PHINode>(Inst));
263 
264     auto *InstClone = Inst->clone();
265     for (auto &Op : Inst->operands()) {
266       assert(SE.isSCEVable(Op->getType()));
267       auto *OpSCEV = SE.getSCEV(Op);
268       auto *OpClone = expandCodeFor(OpSCEV, Op->getType(), IP);
269       InstClone->replaceUsesOfWith(Op, OpClone);
270     }
271 
272     InstClone->setName(Name + Inst->getName());
273     InstClone->insertBefore(IP);
274     return SE.getSCEV(InstClone);
275   }
276 
277   const SCEV *visitUnknown(const SCEVUnknown *E) {
278 
279     // If a value mapping was given try if the underlying value is remapped.
280     Value *NewVal = VMap ? VMap->lookup(E->getValue()) : nullptr;
281     if (NewVal) {
282       auto *NewE = SE.getSCEV(NewVal);
283 
284       // While the mapped value might be different the SCEV representation might
285       // not be. To this end we will check before we go into recursion here.
286       if (E != NewE)
287         return visit(NewE);
288     }
289 
290     Instruction *Inst = dyn_cast<Instruction>(E->getValue());
291     Instruction *IP;
292     if (Inst && !R.contains(Inst))
293       IP = Inst;
294     else if (Inst && RTCBB->getParent() == Inst->getFunction())
295       IP = RTCBB->getTerminator();
296     else
297       IP = RTCBB->getParent()->getEntryBlock().getTerminator();
298 
299     if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
300                   Inst->getOpcode() != Instruction::SDiv))
301       return visitGenericInst(E, Inst, IP);
302 
303     const SCEV *LHSScev = SE.getSCEV(Inst->getOperand(0));
304     const SCEV *RHSScev = SE.getSCEV(Inst->getOperand(1));
305 
306     if (!SE.isKnownNonZero(RHSScev))
307       RHSScev = SE.getUMaxExpr(RHSScev, SE.getConstant(E->getType(), 1));
308 
309     Value *LHS = expandCodeFor(LHSScev, E->getType(), IP);
310     Value *RHS = expandCodeFor(RHSScev, E->getType(), IP);
311 
312     Inst = BinaryOperator::Create((Instruction::BinaryOps)Inst->getOpcode(),
313                                   LHS, RHS, Inst->getName() + Name, IP);
314     return SE.getSCEV(Inst);
315   }
316 
317   /// The following functions will just traverse the SCEV and rebuild it with
318   /// the new operands returned by the traversal.
319   ///
320   ///{
321   const SCEV *visitConstant(const SCEVConstant *E) { return E; }
322   const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
323     return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
324   }
325   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
326     return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
327   }
328   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
329     return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
330   }
331   const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
332     auto *RHSScev = visit(E->getRHS());
333     if (!SE.isKnownNonZero(RHSScev))
334       RHSScev = SE.getUMaxExpr(RHSScev, SE.getConstant(E->getType(), 1));
335     return SE.getUDivExpr(visit(E->getLHS()), RHSScev);
336   }
337   const SCEV *visitAddExpr(const SCEVAddExpr *E) {
338     SmallVector<const SCEV *, 4> NewOps;
339     for (const SCEV *Op : E->operands())
340       NewOps.push_back(visit(Op));
341     return SE.getAddExpr(NewOps);
342   }
343   const SCEV *visitMulExpr(const SCEVMulExpr *E) {
344     SmallVector<const SCEV *, 4> NewOps;
345     for (const SCEV *Op : E->operands())
346       NewOps.push_back(visit(Op));
347     return SE.getMulExpr(NewOps);
348   }
349   const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
350     SmallVector<const SCEV *, 4> NewOps;
351     for (const SCEV *Op : E->operands())
352       NewOps.push_back(visit(Op));
353     return SE.getUMaxExpr(NewOps);
354   }
355   const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
356     SmallVector<const SCEV *, 4> NewOps;
357     for (const SCEV *Op : E->operands())
358       NewOps.push_back(visit(Op));
359     return SE.getSMaxExpr(NewOps);
360   }
361   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
362     SmallVector<const SCEV *, 4> NewOps;
363     for (const SCEV *Op : E->operands())
364       NewOps.push_back(visit(Op));
365     return SE.getAddRecExpr(NewOps, E->getLoop(), E->getNoWrapFlags());
366   }
367   ///}
368 };
369 
370 Value *polly::expandCodeFor(Scop &S, ScalarEvolution &SE, const DataLayout &DL,
371                             const char *Name, const SCEV *E, Type *Ty,
372                             Instruction *IP, ValueMapT *VMap,
373                             BasicBlock *RTCBB) {
374   ScopExpander Expander(S.getRegion(), SE, DL, Name, VMap, RTCBB);
375   return Expander.expandCodeFor(E, Ty, IP);
376 }
377 
378 bool polly::isErrorBlock(BasicBlock &BB, const Region &R, LoopInfo &LI,
379                          const DominatorTree &DT) {
380   if (!PollyAllowErrorBlocks)
381     return false;
382 
383   if (isa<UnreachableInst>(BB.getTerminator()))
384     return true;
385 
386   if (LI.isLoopHeader(&BB))
387     return false;
388 
389   // Basic blocks that are always executed are not considered error blocks,
390   // as their execution can not be a rare event.
391   bool DominatesAllPredecessors = true;
392   for (auto Pred : predecessors(R.getExit()))
393     if (R.contains(Pred) && !DT.dominates(&BB, Pred))
394       DominatesAllPredecessors = false;
395 
396   if (DominatesAllPredecessors)
397     return false;
398 
399   // FIXME: This is a simple heuristic to determine if the load is executed
400   //        in a conditional. However, we actually would need the control
401   //        condition, i.e., the post dominance frontier. Alternatively we
402   //        could walk up the dominance tree until we find a block that is
403   //        not post dominated by the load and check if it is a conditional
404   //        or a loop header.
405   auto *DTNode = DT.getNode(&BB);
406   auto *IDomBB = DTNode->getIDom()->getBlock();
407   if (LI.isLoopHeader(IDomBB))
408     return false;
409 
410   for (Instruction &Inst : BB)
411     if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
412       if (isIgnoredIntrinsic(CI))
413         return false;
414 
415       if (!CI->doesNotAccessMemory())
416         return true;
417       if (CI->doesNotReturn())
418         return true;
419     }
420 
421   return false;
422 }
423 
424 Value *polly::getConditionFromTerminator(TerminatorInst *TI) {
425   if (BranchInst *BR = dyn_cast<BranchInst>(TI)) {
426     if (BR->isUnconditional())
427       return ConstantInt::getTrue(Type::getInt1Ty(TI->getContext()));
428 
429     return BR->getCondition();
430   }
431 
432   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
433     return SI->getCondition();
434 
435   return nullptr;
436 }
437 
438 bool polly::isHoistableLoad(LoadInst *LInst, Region &R, LoopInfo &LI,
439                             ScalarEvolution &SE, const DominatorTree &DT) {
440   Loop *L = LI.getLoopFor(LInst->getParent());
441   auto *Ptr = LInst->getPointerOperand();
442   const SCEV *PtrSCEV = SE.getSCEVAtScope(Ptr, L);
443   while (L && R.contains(L)) {
444     if (!SE.isLoopInvariant(PtrSCEV, L))
445       return false;
446     L = L->getParentLoop();
447   }
448 
449   for (auto *User : Ptr->users()) {
450     auto *UserI = dyn_cast<Instruction>(User);
451     if (!UserI || !R.contains(UserI))
452       continue;
453     if (!UserI->mayWriteToMemory())
454       continue;
455 
456     auto &BB = *UserI->getParent();
457     if (DT.dominates(&BB, LInst->getParent()))
458       return false;
459 
460     bool DominatesAllPredecessors = true;
461     for (auto Pred : predecessors(R.getExit()))
462       if (R.contains(Pred) && !DT.dominates(&BB, Pred))
463         DominatesAllPredecessors = false;
464 
465     if (!DominatesAllPredecessors)
466       continue;
467 
468     return false;
469   }
470 
471   return true;
472 }
473 
474 bool polly::isIgnoredIntrinsic(const Value *V) {
475   if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
476     switch (IT->getIntrinsicID()) {
477     // Lifetime markers are supported/ignored.
478     case llvm::Intrinsic::lifetime_start:
479     case llvm::Intrinsic::lifetime_end:
480     // Invariant markers are supported/ignored.
481     case llvm::Intrinsic::invariant_start:
482     case llvm::Intrinsic::invariant_end:
483     // Some misc annotations are supported/ignored.
484     case llvm::Intrinsic::var_annotation:
485     case llvm::Intrinsic::ptr_annotation:
486     case llvm::Intrinsic::annotation:
487     case llvm::Intrinsic::donothing:
488     case llvm::Intrinsic::assume:
489     case llvm::Intrinsic::expect:
490     // Some debug info intrisics are supported/ignored.
491     case llvm::Intrinsic::dbg_value:
492     case llvm::Intrinsic::dbg_declare:
493       return true;
494     default:
495       break;
496     }
497   }
498   return false;
499 }
500 
501 bool polly::canSynthesize(const Value *V, const Scop &S, ScalarEvolution *SE,
502                           Loop *Scope) {
503   if (!V || !SE->isSCEVable(V->getType()))
504     return false;
505 
506   if (const SCEV *Scev = SE->getSCEVAtScope(const_cast<Value *>(V), Scope))
507     if (!isa<SCEVCouldNotCompute>(Scev))
508       if (!hasScalarDepsInsideRegion(Scev, &S.getRegion(), Scope, false))
509         return true;
510 
511   return false;
512 }
513 
514 llvm::BasicBlock *polly::getUseBlock(llvm::Use &U) {
515   Instruction *UI = dyn_cast<Instruction>(U.getUser());
516   if (!UI)
517     return nullptr;
518 
519   if (PHINode *PHI = dyn_cast<PHINode>(UI))
520     return PHI->getIncomingBlock(U);
521 
522   return UI->getParent();
523 }
524 
525 std::tuple<std::vector<const SCEV *>, std::vector<int>>
526 polly::getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
527   std::vector<const SCEV *> Subscripts;
528   std::vector<int> Sizes;
529 
530   Type *Ty = GEP->getPointerOperandType();
531 
532   bool DroppedFirstDim = false;
533 
534   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
535 
536     const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
537 
538     if (i == 1) {
539       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
540         Ty = PtrTy->getElementType();
541       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
542         Ty = ArrayTy->getElementType();
543       } else {
544         Subscripts.clear();
545         Sizes.clear();
546         break;
547       }
548       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
549         if (Const->getValue()->isZero()) {
550           DroppedFirstDim = true;
551           continue;
552         }
553       Subscripts.push_back(Expr);
554       continue;
555     }
556 
557     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
558     if (!ArrayTy) {
559       Subscripts.clear();
560       Sizes.clear();
561       break;
562     }
563 
564     Subscripts.push_back(Expr);
565     if (!(DroppedFirstDim && i == 2))
566       Sizes.push_back(ArrayTy->getNumElements());
567 
568     Ty = ArrayTy->getElementType();
569   }
570 
571   return std::make_tuple(Subscripts, Sizes);
572 }
573 
574 llvm::Loop *polly::getFirstNonBoxedLoopFor(llvm::Loop *L, llvm::LoopInfo &LI,
575                                            const BoxedLoopsSetTy &BoxedLoops) {
576   while (BoxedLoops.count(L))
577     L = L->getParentLoop();
578   return L;
579 }
580 
581 llvm::Loop *polly::getFirstNonBoxedLoopFor(llvm::BasicBlock *BB,
582                                            llvm::LoopInfo &LI,
583                                            const BoxedLoopsSetTy &BoxedLoops) {
584   Loop *L = LI.getLoopFor(BB);
585   return getFirstNonBoxedLoopFor(L, LI, BoxedLoops);
586 }
587