1 //===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===// 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 #include "llvm/Analysis/MustExecute.h" 11 #include "llvm/Analysis/InstructionSimplify.h" 12 #include "llvm/Analysis/LoopInfo.h" 13 #include "llvm/Analysis/Passes.h" 14 #include "llvm/Analysis/ValueTracking.h" 15 #include "llvm/IR/AssemblyAnnotationWriter.h" 16 #include "llvm/IR/DataLayout.h" 17 #include "llvm/IR/InstIterator.h" 18 #include "llvm/IR/LLVMContext.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/Support/ErrorHandling.h" 21 #include "llvm/Support/FormattedStream.h" 22 #include "llvm/Support/raw_ostream.h" 23 using namespace llvm; 24 25 const DenseMap<BasicBlock *, ColorVector> & 26 LoopSafetyInfo::getBlockColors() const { 27 return BlockColors; 28 } 29 30 void LoopSafetyInfo::copyColors(BasicBlock *New, BasicBlock *Old) { 31 ColorVector &ColorsForNewBlock = BlockColors[New]; 32 ColorVector &ColorsForOldBlock = BlockColors[Old]; 33 ColorsForNewBlock = ColorsForOldBlock; 34 } 35 36 bool SimpleLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const { 37 (void)BB; 38 return anyBlockMayThrow(); 39 } 40 41 bool SimpleLoopSafetyInfo::anyBlockMayThrow() const { 42 return MayThrow; 43 } 44 45 void SimpleLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) { 46 assert(CurLoop != nullptr && "CurLoop can't be null"); 47 BasicBlock *Header = CurLoop->getHeader(); 48 // Iterate over header and compute safety info. 49 HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header); 50 MayThrow = HeaderMayThrow; 51 // Iterate over loop instructions and compute safety info. 52 // Skip header as it has been computed and stored in HeaderMayThrow. 53 // The first block in loopinfo.Blocks is guaranteed to be the header. 54 assert(Header == *CurLoop->getBlocks().begin() && 55 "First block must be header"); 56 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()), 57 BBE = CurLoop->block_end(); 58 (BB != BBE) && !MayThrow; ++BB) 59 MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB); 60 61 computeBlockColors(CurLoop); 62 } 63 64 bool ICFLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const { 65 return ICF.hasICF(BB); 66 } 67 68 bool ICFLoopSafetyInfo::anyBlockMayThrow() const { 69 return MayThrow; 70 } 71 72 void ICFLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) { 73 assert(CurLoop != nullptr && "CurLoop can't be null"); 74 ICF.clear(); 75 MayThrow = false; 76 // Figure out the fact that at least one block may throw. 77 for (auto &BB : CurLoop->blocks()) 78 if (ICF.hasICF(&*BB)) { 79 MayThrow = true; 80 break; 81 } 82 computeBlockColors(CurLoop); 83 } 84 85 void ICFLoopSafetyInfo::insertInstructionTo(const BasicBlock *BB) { 86 ICF.invalidateBlock(BB); 87 } 88 89 void ICFLoopSafetyInfo::removeInstruction(const Instruction *Inst) { 90 // TODO: So far we just conservatively drop cache, but maybe we can not do it 91 // when Inst is not an ICF instruction. Follow-up on that. 92 ICF.invalidateBlock(Inst->getParent()); 93 } 94 95 void LoopSafetyInfo::computeBlockColors(const Loop *CurLoop) { 96 // Compute funclet colors if we might sink/hoist in a function with a funclet 97 // personality routine. 98 Function *Fn = CurLoop->getHeader()->getParent(); 99 if (Fn->hasPersonalityFn()) 100 if (Constant *PersonalityFn = Fn->getPersonalityFn()) 101 if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn))) 102 BlockColors = colorEHFunclets(*Fn); 103 } 104 105 /// Return true if we can prove that the given ExitBlock is not reached on the 106 /// first iteration of the given loop. That is, the backedge of the loop must 107 /// be executed before the ExitBlock is executed in any dynamic execution trace. 108 static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock, 109 const DominatorTree *DT, 110 const Loop *CurLoop) { 111 auto *CondExitBlock = ExitBlock->getSinglePredecessor(); 112 if (!CondExitBlock) 113 // expect unique exits 114 return false; 115 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block"); 116 auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator()); 117 if (!BI || !BI->isConditional()) 118 return false; 119 // If condition is constant and false leads to ExitBlock then we always 120 // execute the true branch. 121 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) 122 return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock; 123 auto *Cond = dyn_cast<CmpInst>(BI->getCondition()); 124 if (!Cond) 125 return false; 126 // todo: this would be a lot more powerful if we used scev, but all the 127 // plumbing is currently missing to pass a pointer in from the pass 128 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known 129 auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0)); 130 auto *RHS = Cond->getOperand(1); 131 if (!LHS || LHS->getParent() != CurLoop->getHeader()) 132 return false; 133 auto DL = ExitBlock->getModule()->getDataLayout(); 134 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader()); 135 auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(), 136 IVStart, RHS, 137 {DL, /*TLI*/ nullptr, 138 DT, /*AC*/ nullptr, BI}); 139 auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull); 140 if (!SimpleCst) 141 return false; 142 if (ExitBlock == BI->getSuccessor(0)) 143 return SimpleCst->isZeroValue(); 144 assert(ExitBlock == BI->getSuccessor(1) && "implied by above"); 145 return SimpleCst->isAllOnesValue(); 146 } 147 148 /// Collect all blocks from \p CurLoop which lie on all possible paths from 149 /// the header of \p CurLoop (inclusive) to BB (exclusive) into the set 150 /// \p Predecessors. If \p BB is the header, \p Predecessors will be empty. 151 static void collectTransitivePredecessors( 152 const Loop *CurLoop, const BasicBlock *BB, 153 SmallPtrSetImpl<const BasicBlock *> &Predecessors) { 154 assert(Predecessors.empty() && "Garbage in predecessors set?"); 155 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!"); 156 if (BB == CurLoop->getHeader()) 157 return; 158 SmallVector<const BasicBlock *, 4> WorkList; 159 for (auto *Pred : predecessors(BB)) { 160 Predecessors.insert(Pred); 161 WorkList.push_back(Pred); 162 } 163 while (!WorkList.empty()) { 164 auto *Pred = WorkList.pop_back_val(); 165 assert(CurLoop->contains(Pred) && "Should only reach loop blocks!"); 166 // We are not interested in backedges and we don't want to leave loop. 167 if (Pred == CurLoop->getHeader()) 168 continue; 169 // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all 170 // blocks of this inner loop, even those that are always executed AFTER the 171 // BB. It may make our analysis more conservative than it could be, see test 172 // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll. 173 // We can ignore backedge of all loops containing BB to get a sligtly more 174 // optimistic result. 175 for (auto *PredPred : predecessors(Pred)) 176 if (Predecessors.insert(PredPred).second) 177 WorkList.push_back(PredPred); 178 } 179 } 180 181 bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop, 182 const BasicBlock *BB, 183 const DominatorTree *DT) const { 184 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!"); 185 186 // Fast path: header is always reached once the loop is entered. 187 if (BB == CurLoop->getHeader()) 188 return true; 189 190 // Collect all transitive predecessors of BB in the same loop. This set will 191 // be a subset of the blocks within the loop. 192 SmallPtrSet<const BasicBlock *, 4> Predecessors; 193 collectTransitivePredecessors(CurLoop, BB, Predecessors); 194 195 // Make sure that all successors of all predecessors of BB are either: 196 // 1) BB, 197 // 2) Also predecessors of BB, 198 // 3) Exit blocks which are not taken on 1st iteration. 199 // Memoize blocks we've already checked. 200 SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors; 201 for (auto *Pred : Predecessors) { 202 // Predecessor block may throw, so it has a side exit. 203 if (blockMayThrow(Pred)) 204 return false; 205 for (auto *Succ : successors(Pred)) 206 if (CheckedSuccessors.insert(Succ).second && 207 Succ != BB && !Predecessors.count(Succ)) 208 // By discharging conditions that are not executed on the 1st iteration, 209 // we guarantee that *at least* on the first iteration all paths from 210 // header that *may* execute will lead us to the block of interest. So 211 // that if we had virtually peeled one iteration away, in this peeled 212 // iteration the set of predecessors would contain only paths from 213 // header to BB without any exiting edges that may execute. 214 // 215 // TODO: We only do it for exiting edges currently. We could use the 216 // same function to skip some of the edges within the loop if we know 217 // that they will not be taken on the 1st iteration. 218 // 219 // TODO: If we somehow know the number of iterations in loop, the same 220 // check may be done for any arbitrary N-th iteration as long as N is 221 // not greater than minimum number of iterations in this loop. 222 if (CurLoop->contains(Succ) || 223 !CanProveNotTakenFirstIteration(Succ, DT, CurLoop)) 224 return false; 225 } 226 227 // All predecessors can only lead us to BB. 228 return true; 229 } 230 231 /// Returns true if the instruction in a loop is guaranteed to execute at least 232 /// once. 233 bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst, 234 const DominatorTree *DT, 235 const Loop *CurLoop) const { 236 // If the instruction is in the header block for the loop (which is very 237 // common), it is always guaranteed to dominate the exit blocks. Since this 238 // is a common case, and can save some work, check it now. 239 if (Inst.getParent() == CurLoop->getHeader()) 240 // If there's a throw in the header block, we can't guarantee we'll reach 241 // Inst unless we can prove that Inst comes before the potential implicit 242 // exit. At the moment, we use a (cheap) hack for the common case where 243 // the instruction of interest is the first one in the block. 244 return !HeaderMayThrow || 245 Inst.getParent()->getFirstNonPHIOrDbg() == &Inst; 246 247 // If there is a path from header to exit or latch that doesn't lead to our 248 // instruction's block, return false. 249 return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT); 250 } 251 252 bool ICFLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst, 253 const DominatorTree *DT, 254 const Loop *CurLoop) const { 255 return !ICF.isDominatedByICFIFromSameBlock(&Inst) && 256 allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT); 257 } 258 259 namespace { 260 struct MustExecutePrinter : public FunctionPass { 261 262 static char ID; // Pass identification, replacement for typeid 263 MustExecutePrinter() : FunctionPass(ID) { 264 initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry()); 265 } 266 void getAnalysisUsage(AnalysisUsage &AU) const override { 267 AU.setPreservesAll(); 268 AU.addRequired<DominatorTreeWrapperPass>(); 269 AU.addRequired<LoopInfoWrapperPass>(); 270 } 271 bool runOnFunction(Function &F) override; 272 }; 273 } 274 275 char MustExecutePrinter::ID = 0; 276 INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute", 277 "Instructions which execute on loop entry", false, true) 278 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 279 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 280 INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute", 281 "Instructions which execute on loop entry", false, true) 282 283 FunctionPass *llvm::createMustExecutePrinter() { 284 return new MustExecutePrinter(); 285 } 286 287 static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) { 288 // TODO: merge these two routines. For the moment, we display the best 289 // result obtained by *either* implementation. This is a bit unfair since no 290 // caller actually gets the full power at the moment. 291 SimpleLoopSafetyInfo LSI; 292 LSI.computeLoopSafetyInfo(L); 293 return LSI.isGuaranteedToExecute(I, DT, L) || 294 isGuaranteedToExecuteForEveryIteration(&I, L); 295 } 296 297 namespace { 298 /// An assembly annotator class to print must execute information in 299 /// comments. 300 class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter { 301 DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec; 302 303 public: 304 MustExecuteAnnotatedWriter(const Function &F, 305 DominatorTree &DT, LoopInfo &LI) { 306 for (auto &I: instructions(F)) { 307 Loop *L = LI.getLoopFor(I.getParent()); 308 while (L) { 309 if (isMustExecuteIn(I, L, &DT)) { 310 MustExec[&I].push_back(L); 311 } 312 L = L->getParentLoop(); 313 }; 314 } 315 } 316 MustExecuteAnnotatedWriter(const Module &M, 317 DominatorTree &DT, LoopInfo &LI) { 318 for (auto &F : M) 319 for (auto &I: instructions(F)) { 320 Loop *L = LI.getLoopFor(I.getParent()); 321 while (L) { 322 if (isMustExecuteIn(I, L, &DT)) { 323 MustExec[&I].push_back(L); 324 } 325 L = L->getParentLoop(); 326 }; 327 } 328 } 329 330 331 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override { 332 if (!MustExec.count(&V)) 333 return; 334 335 const auto &Loops = MustExec.lookup(&V); 336 const auto NumLoops = Loops.size(); 337 if (NumLoops > 1) 338 OS << " ; (mustexec in " << NumLoops << " loops: "; 339 else 340 OS << " ; (mustexec in: "; 341 342 bool first = true; 343 for (const Loop *L : Loops) { 344 if (!first) 345 OS << ", "; 346 first = false; 347 OS << L->getHeader()->getName(); 348 } 349 OS << ")"; 350 } 351 }; 352 } // namespace 353 354 bool MustExecutePrinter::runOnFunction(Function &F) { 355 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 356 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 357 358 MustExecuteAnnotatedWriter Writer(F, DT, LI); 359 F.print(dbgs(), &Writer); 360 361 return false; 362 } 363