Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 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 | |
Philip Reames | e4b728e | 2018-03-29 19:22:12 +0000 | [diff] [blame] | 10 | #include "llvm/Analysis/MustExecute.h" |
Philip Reames | 23aed5e | 2018-03-20 22:45:23 +0000 | [diff] [blame] | 11 | #include "llvm/Analysis/InstructionSimplify.h" |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 12 | #include "llvm/Analysis/LoopInfo.h" |
| 13 | #include "llvm/Analysis/Passes.h" |
| 14 | #include "llvm/Analysis/ValueTracking.h" |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 15 | #include "llvm/IR/AssemblyAnnotationWriter.h" |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 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" |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 21 | #include "llvm/Support/FormattedStream.h" |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 22 | #include "llvm/Support/raw_ostream.h" |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 23 | using namespace llvm; |
| 24 | |
Philip Reames | 23aed5e | 2018-03-20 22:45:23 +0000 | [diff] [blame] | 25 | /// Computes loop safety information, checks loop body & header |
| 26 | /// for the possibility of may throw exception. |
| 27 | /// |
| 28 | void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) { |
| 29 | assert(CurLoop != nullptr && "CurLoop cant be null"); |
| 30 | BasicBlock *Header = CurLoop->getHeader(); |
| 31 | // Setting default safety values. |
| 32 | SafetyInfo->MayThrow = false; |
| 33 | SafetyInfo->HeaderMayThrow = false; |
| 34 | // Iterate over header and compute safety info. |
| 35 | SafetyInfo->HeaderMayThrow = |
| 36 | !isGuaranteedToTransferExecutionToSuccessor(Header); |
| 37 | |
| 38 | SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow; |
| 39 | // Iterate over loop instructions and compute safety info. |
| 40 | // Skip header as it has been computed and stored in HeaderMayThrow. |
| 41 | // The first block in loopinfo.Blocks is guaranteed to be the header. |
| 42 | assert(Header == *CurLoop->getBlocks().begin() && |
| 43 | "First block must be header"); |
| 44 | for (Loop::block_iterator BB = std::next(CurLoop->block_begin()), |
| 45 | BBE = CurLoop->block_end(); |
| 46 | (BB != BBE) && !SafetyInfo->MayThrow; ++BB) |
| 47 | SafetyInfo->MayThrow |= |
| 48 | !isGuaranteedToTransferExecutionToSuccessor(*BB); |
| 49 | |
| 50 | // Compute funclet colors if we might sink/hoist in a function with a funclet |
| 51 | // personality routine. |
| 52 | Function *Fn = CurLoop->getHeader()->getParent(); |
| 53 | if (Fn->hasPersonalityFn()) |
| 54 | if (Constant *PersonalityFn = Fn->getPersonalityFn()) |
| 55 | if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn))) |
| 56 | SafetyInfo->BlockColors = colorEHFunclets(*Fn); |
| 57 | } |
| 58 | |
| 59 | /// Return true if we can prove that the given ExitBlock is not reached on the |
| 60 | /// first iteration of the given loop. That is, the backedge of the loop must |
| 61 | /// be executed before the ExitBlock is executed in any dynamic execution trace. |
| 62 | static bool CanProveNotTakenFirstIteration(BasicBlock *ExitBlock, |
| 63 | const DominatorTree *DT, |
| 64 | const Loop *CurLoop) { |
| 65 | auto *CondExitBlock = ExitBlock->getSinglePredecessor(); |
| 66 | if (!CondExitBlock) |
| 67 | // expect unique exits |
| 68 | return false; |
| 69 | assert(CurLoop->contains(CondExitBlock) && "meaning of exit block"); |
| 70 | auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator()); |
| 71 | if (!BI || !BI->isConditional()) |
| 72 | return false; |
| 73 | auto *Cond = dyn_cast<CmpInst>(BI->getCondition()); |
| 74 | if (!Cond) |
| 75 | return false; |
| 76 | // todo: this would be a lot more powerful if we used scev, but all the |
| 77 | // plumbing is currently missing to pass a pointer in from the pass |
| 78 | // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known |
| 79 | auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0)); |
| 80 | auto *RHS = Cond->getOperand(1); |
| 81 | if (!LHS || LHS->getParent() != CurLoop->getHeader()) |
| 82 | return false; |
| 83 | auto DL = ExitBlock->getModule()->getDataLayout(); |
| 84 | auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader()); |
| 85 | auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(), |
| 86 | IVStart, RHS, |
| 87 | {DL, /*TLI*/ nullptr, |
| 88 | DT, /*AC*/ nullptr, BI}); |
| 89 | auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull); |
| 90 | if (!SimpleCst) |
| 91 | return false; |
| 92 | if (ExitBlock == BI->getSuccessor(0)) |
| 93 | return SimpleCst->isZeroValue(); |
| 94 | assert(ExitBlock == BI->getSuccessor(1) && "implied by above"); |
| 95 | return SimpleCst->isAllOnesValue(); |
| 96 | } |
| 97 | |
| 98 | /// Returns true if the instruction in a loop is guaranteed to execute at least |
| 99 | /// once. |
| 100 | bool llvm::isGuaranteedToExecute(const Instruction &Inst, |
| 101 | const DominatorTree *DT, const Loop *CurLoop, |
| 102 | const LoopSafetyInfo *SafetyInfo) { |
| 103 | // We have to check to make sure that the instruction dominates all |
| 104 | // of the exit blocks. If it doesn't, then there is a path out of the loop |
| 105 | // which does not execute this instruction, so we can't hoist it. |
| 106 | |
| 107 | // If the instruction is in the header block for the loop (which is very |
| 108 | // common), it is always guaranteed to dominate the exit blocks. Since this |
| 109 | // is a common case, and can save some work, check it now. |
| 110 | if (Inst.getParent() == CurLoop->getHeader()) |
| 111 | // If there's a throw in the header block, we can't guarantee we'll reach |
| 112 | // Inst. |
| 113 | return !SafetyInfo->HeaderMayThrow; |
| 114 | |
| 115 | // Somewhere in this loop there is an instruction which may throw and make us |
| 116 | // exit the loop. |
| 117 | if (SafetyInfo->MayThrow) |
| 118 | return false; |
| 119 | |
| 120 | // Note: There are two styles of reasoning intermixed below for |
| 121 | // implementation efficiency reasons. They are: |
| 122 | // 1) If we can prove that the instruction dominates all exit blocks, then we |
| 123 | // know the instruction must have executed on *some* iteration before we |
| 124 | // exit. We do not prove *which* iteration the instruction must execute on. |
| 125 | // 2) If we can prove that the instruction dominates the latch and all exits |
| 126 | // which might be taken on the first iteration, we know the instruction must |
| 127 | // execute on the first iteration. This second style allows a conditional |
| 128 | // exit before the instruction of interest which is provably not taken on the |
| 129 | // first iteration. This is a quite common case for range check like |
| 130 | // patterns. TODO: support loops with multiple latches. |
| 131 | |
| 132 | const bool InstDominatesLatch = |
| 133 | CurLoop->getLoopLatch() != nullptr && |
| 134 | DT->dominates(Inst.getParent(), CurLoop->getLoopLatch()); |
| 135 | |
| 136 | // Get the exit blocks for the current loop. |
| 137 | SmallVector<BasicBlock *, 8> ExitBlocks; |
| 138 | CurLoop->getExitBlocks(ExitBlocks); |
| 139 | |
| 140 | // Verify that the block dominates each of the exit blocks of the loop. |
| 141 | for (BasicBlock *ExitBlock : ExitBlocks) |
| 142 | if (!DT->dominates(Inst.getParent(), ExitBlock)) |
| 143 | if (!InstDominatesLatch || |
| 144 | !CanProveNotTakenFirstIteration(ExitBlock, DT, CurLoop)) |
| 145 | return false; |
| 146 | |
| 147 | // As a degenerate case, if the loop is statically infinite then we haven't |
| 148 | // proven anything since there are no exit blocks. |
| 149 | if (ExitBlocks.empty()) |
| 150 | return false; |
| 151 | |
| 152 | // FIXME: In general, we have to prove that the loop isn't an infinite loop. |
| 153 | // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is |
| 154 | // just a special case of this.) |
| 155 | return true; |
| 156 | } |
| 157 | |
| 158 | |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 159 | namespace { |
| 160 | struct MustExecutePrinter : public FunctionPass { |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 161 | |
| 162 | static char ID; // Pass identification, replacement for typeid |
| 163 | MustExecutePrinter() : FunctionPass(ID) { |
| 164 | initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry()); |
| 165 | } |
| 166 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 167 | AU.setPreservesAll(); |
| 168 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 169 | AU.addRequired<LoopInfoWrapperPass>(); |
| 170 | } |
| 171 | bool runOnFunction(Function &F) override; |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 172 | }; |
| 173 | } |
| 174 | |
| 175 | char MustExecutePrinter::ID = 0; |
| 176 | INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute", |
| 177 | "Instructions which execute on loop entry", false, true) |
| 178 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 179 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 180 | INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute", |
| 181 | "Instructions which execute on loop entry", false, true) |
| 182 | |
| 183 | FunctionPass *llvm::createMustExecutePrinter() { |
| 184 | return new MustExecutePrinter(); |
| 185 | } |
| 186 | |
Benjamin Kramer | 1fc0da4 | 2018-04-04 11:45:11 +0000 | [diff] [blame^] | 187 | static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) { |
Philip Reames | 37a1a29 | 2018-03-20 23:00:54 +0000 | [diff] [blame] | 188 | // TODO: merge these two routines. For the moment, we display the best |
| 189 | // result obtained by *either* implementation. This is a bit unfair since no |
| 190 | // caller actually gets the full power at the moment. |
| 191 | LoopSafetyInfo LSI; |
| 192 | computeLoopSafetyInfo(&LSI, L); |
| 193 | return isGuaranteedToExecute(I, DT, L, &LSI) || |
| 194 | isGuaranteedToExecuteForEveryIteration(&I, L); |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 195 | } |
| 196 | |
Benjamin Kramer | 1fc0da4 | 2018-04-04 11:45:11 +0000 | [diff] [blame^] | 197 | namespace { |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 198 | /// \brief An assembly annotator class to print must execute information in |
| 199 | /// comments. |
| 200 | class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter { |
| 201 | DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec; |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 202 | |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 203 | public: |
| 204 | MustExecuteAnnotatedWriter(const Function &F, |
| 205 | DominatorTree &DT, LoopInfo &LI) { |
| 206 | for (auto &I: instructions(F)) { |
| 207 | Loop *L = LI.getLoopFor(I.getParent()); |
| 208 | while (L) { |
| 209 | if (isMustExecuteIn(I, L, &DT)) { |
| 210 | MustExec[&I].push_back(L); |
| 211 | } |
| 212 | L = L->getParentLoop(); |
| 213 | }; |
| 214 | } |
| 215 | } |
| 216 | MustExecuteAnnotatedWriter(const Module &M, |
| 217 | DominatorTree &DT, LoopInfo &LI) { |
| 218 | for (auto &F : M) |
| 219 | for (auto &I: instructions(F)) { |
| 220 | Loop *L = LI.getLoopFor(I.getParent()); |
| 221 | while (L) { |
| 222 | if (isMustExecuteIn(I, L, &DT)) { |
| 223 | MustExec[&I].push_back(L); |
| 224 | } |
| 225 | L = L->getParentLoop(); |
| 226 | }; |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | |
| 231 | void printInfoComment(const Value &V, formatted_raw_ostream &OS) override { |
| 232 | if (!MustExec.count(&V)) |
| 233 | return; |
| 234 | |
| 235 | const auto &Loops = MustExec.lookup(&V); |
| 236 | const auto NumLoops = Loops.size(); |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 237 | if (NumLoops > 1) |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 238 | OS << " ; (mustexec in " << NumLoops << " loops: "; |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 239 | else |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 240 | OS << " ; (mustexec in: "; |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 241 | |
| 242 | bool first = true; |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 243 | for (const Loop *L : Loops) { |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 244 | if (!first) |
| 245 | OS << ", "; |
| 246 | first = false; |
| 247 | OS << L->getHeader()->getName(); |
| 248 | } |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 249 | OS << ")"; |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 250 | } |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 251 | }; |
Benjamin Kramer | 1fc0da4 | 2018-04-04 11:45:11 +0000 | [diff] [blame^] | 252 | } // namespace |
Philip Reames | ce998ad | 2018-03-20 18:43:44 +0000 | [diff] [blame] | 253 | |
| 254 | bool MustExecutePrinter::runOnFunction(Function &F) { |
| 255 | auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 256 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 257 | |
| 258 | MustExecuteAnnotatedWriter Writer(F, DT, LI); |
| 259 | F.print(dbgs(), &Writer); |
| 260 | |
| 261 | return false; |
Philip Reames | 89f2241 | 2018-03-20 17:09:21 +0000 | [diff] [blame] | 262 | } |