Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 1 | //===- JumpThreading.cpp - Thread control through conditional blocks ------===// |
| 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 | // |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 10 | // This file implements the Jump Threading pass. |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #define DEBUG_TYPE "jump-threading" |
| 15 | #include "llvm/Transforms/Scalar.h" |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 16 | #include "llvm/IntrinsicInst.h" |
Owen Anderson | 1ff50b3 | 2009-07-03 00:54:20 +0000 | [diff] [blame] | 17 | #include "llvm/LLVMContext.h" |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 18 | #include "llvm/Pass.h" |
Chris Lattner | ef0c674 | 2008-12-01 04:48:07 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/ConstantFolding.h" |
Chris Lattner | 2cc6751 | 2008-04-21 02:57:57 +0000 | [diff] [blame] | 20 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 21 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | 433a0db | 2009-10-10 09:05:58 +0000 | [diff] [blame] | 22 | #include "llvm/Transforms/Utils/SSAUpdater.h" |
Chris Lattner | ef0c674 | 2008-12-01 04:48:07 +0000 | [diff] [blame] | 23 | #include "llvm/Target/TargetData.h" |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/DenseMap.h" |
| 25 | #include "llvm/ADT/Statistic.h" |
| 26 | #include "llvm/ADT/STLExtras.h" |
| 27 | #include "llvm/ADT/SmallPtrSet.h" |
| 28 | #include "llvm/ADT/SmallSet.h" |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 29 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 30 | #include "llvm/Support/Debug.h" |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 31 | #include "llvm/Support/raw_ostream.h" |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 32 | using namespace llvm; |
| 33 | |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 34 | STATISTIC(NumThreads, "Number of jumps threaded"); |
| 35 | STATISTIC(NumFolds, "Number of terminators folded"); |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 36 | STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi"); |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 37 | |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 38 | static cl::opt<unsigned> |
| 39 | Threshold("jump-threading-threshold", |
| 40 | cl::desc("Max block size to duplicate for jump threading"), |
| 41 | cl::init(6), cl::Hidden); |
| 42 | |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 43 | namespace { |
Chris Lattner | 94019f8 | 2008-05-09 04:43:13 +0000 | [diff] [blame] | 44 | /// This pass performs 'jump threading', which looks at blocks that have |
| 45 | /// multiple predecessors and multiple successors. If one or more of the |
| 46 | /// predecessors of the block can be proven to always jump to one of the |
| 47 | /// successors, we forward the edge from the predecessor to the successor by |
| 48 | /// duplicating the contents of this block. |
| 49 | /// |
| 50 | /// An example of when this can occur is code like this: |
| 51 | /// |
| 52 | /// if () { ... |
| 53 | /// X = 4; |
| 54 | /// } |
| 55 | /// if (X < 3) { |
| 56 | /// |
| 57 | /// In this case, the unconditional branch at the end of the first if can be |
| 58 | /// revectored to the false side of the second if. |
| 59 | /// |
Chris Lattner | 3e8b663 | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 60 | class JumpThreading : public FunctionPass { |
Chris Lattner | ef0c674 | 2008-12-01 04:48:07 +0000 | [diff] [blame] | 61 | TargetData *TD; |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 62 | #ifdef NDEBUG |
| 63 | SmallPtrSet<BasicBlock*, 16> LoopHeaders; |
| 64 | #else |
| 65 | SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders; |
| 66 | #endif |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 67 | public: |
| 68 | static char ID; // Pass identification |
Dan Gohman | ae73dc1 | 2008-09-04 17:05:41 +0000 | [diff] [blame] | 69 | JumpThreading() : FunctionPass(&ID) {} |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 70 | |
Chris Lattner | ef0c674 | 2008-12-01 04:48:07 +0000 | [diff] [blame] | 71 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
Chris Lattner | ef0c674 | 2008-12-01 04:48:07 +0000 | [diff] [blame] | 72 | } |
| 73 | |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 74 | bool runOnFunction(Function &F); |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 75 | void FindLoopHeaders(Function &F); |
| 76 | |
Chris Lattner | c7bcbf6 | 2008-11-27 07:20:04 +0000 | [diff] [blame] | 77 | bool ProcessBlock(BasicBlock *BB); |
Chris Lattner | bdbf1a1 | 2009-10-11 04:33:43 +0000 | [diff] [blame] | 78 | bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB); |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 79 | bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB, |
| 80 | BasicBlock *PredBB); |
| 81 | |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 82 | BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 83 | bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB); |
Chris Lattner | 3cda3cd | 2008-12-04 06:31:07 +0000 | [diff] [blame] | 84 | bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB); |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 85 | |
Chris Lattner | d38c14e | 2008-04-22 06:36:15 +0000 | [diff] [blame] | 86 | bool ProcessJumpOnPHI(PHINode *PN); |
Chris Lattner | ae65b3c | 2008-04-22 20:46:09 +0000 | [diff] [blame] | 87 | bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd); |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 88 | bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB); |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 89 | |
| 90 | bool SimplifyPartiallyRedundantLoad(LoadInst *LI); |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 91 | }; |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 92 | } |
| 93 | |
Dan Gohman | 844731a | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 94 | char JumpThreading::ID = 0; |
| 95 | static RegisterPass<JumpThreading> |
| 96 | X("jump-threading", "Jump Threading"); |
| 97 | |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 98 | // Public interface to the Jump Threading pass |
| 99 | FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); } |
| 100 | |
| 101 | /// runOnFunction - Top level algorithm. |
| 102 | /// |
| 103 | bool JumpThreading::runOnFunction(Function &F) { |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 104 | DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n"); |
Dan Gohman | 02a436c | 2009-07-24 18:13:53 +0000 | [diff] [blame] | 105 | TD = getAnalysisIfAvailable<TargetData>(); |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 106 | |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 107 | FindLoopHeaders(F); |
| 108 | |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 109 | bool AnotherIteration = true, EverChanged = false; |
| 110 | while (AnotherIteration) { |
| 111 | AnotherIteration = false; |
| 112 | bool Changed = false; |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 113 | for (Function::iterator I = F.begin(), E = F.end(); I != E;) { |
| 114 | BasicBlock *BB = I; |
| 115 | while (ProcessBlock(BB)) |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 116 | Changed = true; |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 117 | |
| 118 | ++I; |
| 119 | |
| 120 | // If the block is trivially dead, zap it. This eliminates the successor |
| 121 | // edges which simplifies the CFG. |
| 122 | if (pred_begin(BB) == pred_end(BB) && |
Chris Lattner | 20fa76e | 2008-12-08 22:44:07 +0000 | [diff] [blame] | 123 | BB != &BB->getParent()->getEntryBlock()) { |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 124 | DEBUG(errs() << " JT: Deleting dead block '" << BB->getName() |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 125 | << "' with terminator: " << *BB->getTerminator() << '\n'); |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 126 | LoopHeaders.erase(BB); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 127 | DeleteDeadBlock(BB); |
| 128 | Changed = true; |
| 129 | } |
| 130 | } |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 131 | AnotherIteration = Changed; |
| 132 | EverChanged |= Changed; |
| 133 | } |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 134 | |
| 135 | LoopHeaders.clear(); |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 136 | return EverChanged; |
Chris Lattner | 8383a7b | 2008-04-20 20:35:01 +0000 | [diff] [blame] | 137 | } |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 138 | |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 139 | /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to |
| 140 | /// thread across it. |
| 141 | static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) { |
| 142 | /// Ignore PHI nodes, these will be flattened when duplication happens. |
| 143 | BasicBlock::const_iterator I = BB->getFirstNonPHI(); |
| 144 | |
| 145 | // Sum up the cost of each instruction until we get to the terminator. Don't |
| 146 | // include the terminator because the copy won't include it. |
| 147 | unsigned Size = 0; |
| 148 | for (; !isa<TerminatorInst>(I); ++I) { |
| 149 | // Debugger intrinsics don't incur code size. |
| 150 | if (isa<DbgInfoIntrinsic>(I)) continue; |
| 151 | |
| 152 | // If this is a pointer->pointer bitcast, it is free. |
| 153 | if (isa<BitCastInst>(I) && isa<PointerType>(I->getType())) |
| 154 | continue; |
| 155 | |
| 156 | // All other instructions count for at least one unit. |
| 157 | ++Size; |
| 158 | |
| 159 | // Calls are more expensive. If they are non-intrinsic calls, we model them |
| 160 | // as having cost of 4. If they are a non-vector intrinsic, we model them |
| 161 | // as having cost of 2 total, and if they are a vector intrinsic, we model |
| 162 | // them as having cost 1. |
| 163 | if (const CallInst *CI = dyn_cast<CallInst>(I)) { |
| 164 | if (!isa<IntrinsicInst>(CI)) |
| 165 | Size += 3; |
| 166 | else if (!isa<VectorType>(CI->getType())) |
| 167 | Size += 1; |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | // Threading through a switch statement is particularly profitable. If this |
| 172 | // block ends in a switch, decrease its cost to make it more likely to happen. |
| 173 | if (isa<SwitchInst>(I)) |
| 174 | Size = Size > 6 ? Size-6 : 0; |
| 175 | |
| 176 | return Size; |
| 177 | } |
| 178 | |
| 179 | |
| 180 | |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 181 | /// FindLoopHeaders - We do not want jump threading to turn proper loop |
| 182 | /// structures into irreducible loops. Doing this breaks up the loop nesting |
| 183 | /// hierarchy and pessimizes later transformations. To prevent this from |
| 184 | /// happening, we first have to find the loop headers. Here we approximate this |
| 185 | /// by finding targets of backedges in the CFG. |
| 186 | /// |
| 187 | /// Note that there definitely are cases when we want to allow threading of |
| 188 | /// edges across a loop header. For example, threading a jump from outside the |
| 189 | /// loop (the preheader) to an exit block of the loop is definitely profitable. |
| 190 | /// It is also almost always profitable to thread backedges from within the loop |
| 191 | /// to exit blocks, and is often profitable to thread backedges to other blocks |
| 192 | /// within the loop (forming a nested loop). This simple analysis is not rich |
| 193 | /// enough to track all of these properties and keep it up-to-date as the CFG |
| 194 | /// mutates, so we don't allow any of these transformations. |
| 195 | /// |
| 196 | void JumpThreading::FindLoopHeaders(Function &F) { |
| 197 | SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; |
| 198 | FindFunctionBackedges(F, Edges); |
| 199 | |
| 200 | for (unsigned i = 0, e = Edges.size(); i != e; ++i) |
| 201 | LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second)); |
| 202 | } |
| 203 | |
| 204 | |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 205 | /// FactorCommonPHIPreds - If there are multiple preds with the same incoming |
| 206 | /// value for the PHI, factor them together so we get one block to thread for |
| 207 | /// the whole group. |
| 208 | /// This is important for things like "phi i1 [true, true, false, true, x]" |
| 209 | /// where we only need to clone the block for the true blocks once. |
| 210 | /// |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 211 | BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) { |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 212 | SmallVector<BasicBlock*, 16> CommonPreds; |
| 213 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 214 | if (PN->getIncomingValue(i) == Val) |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 215 | CommonPreds.push_back(PN->getIncomingBlock(i)); |
| 216 | |
| 217 | if (CommonPreds.size() == 1) |
| 218 | return CommonPreds[0]; |
| 219 | |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 220 | DEBUG(errs() << " Factoring out " << CommonPreds.size() |
| 221 | << " common predecessors.\n"); |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 222 | return SplitBlockPredecessors(PN->getParent(), |
| 223 | &CommonPreds[0], CommonPreds.size(), |
| 224 | ".thr_comm", this); |
| 225 | } |
| 226 | |
| 227 | |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 228 | /// GetBestDestForBranchOnUndef - If we determine that the specified block ends |
| 229 | /// in an undefined jump, decide which block is best to revector to. |
| 230 | /// |
| 231 | /// Since we can pick an arbitrary destination, we pick the successor with the |
| 232 | /// fewest predecessors. This should reduce the in-degree of the others. |
| 233 | /// |
| 234 | static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) { |
| 235 | TerminatorInst *BBTerm = BB->getTerminator(); |
| 236 | unsigned MinSucc = 0; |
| 237 | BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); |
| 238 | // Compute the successor with the minimum number of predecessors. |
| 239 | unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); |
| 240 | for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { |
| 241 | TestBB = BBTerm->getSuccessor(i); |
| 242 | unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); |
| 243 | if (NumPreds < MinNumPreds) |
| 244 | MinSucc = i; |
| 245 | } |
| 246 | |
| 247 | return MinSucc; |
| 248 | } |
| 249 | |
Chris Lattner | c7bcbf6 | 2008-11-27 07:20:04 +0000 | [diff] [blame] | 250 | /// ProcessBlock - If there are any predecessors whose control can be threaded |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 251 | /// through to a successor, transform them now. |
Chris Lattner | c7bcbf6 | 2008-11-27 07:20:04 +0000 | [diff] [blame] | 252 | bool JumpThreading::ProcessBlock(BasicBlock *BB) { |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 253 | // If this block has a single predecessor, and if that pred has a single |
| 254 | // successor, merge the blocks. This encourages recursive jump threading |
| 255 | // because now the condition in this block can be threaded through |
| 256 | // predecessors of our predecessor block. |
| 257 | if (BasicBlock *SinglePred = BB->getSinglePredecessor()) |
Chris Lattner | f5102a0 | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 258 | if (SinglePred->getTerminator()->getNumSuccessors() == 1 && |
| 259 | SinglePred != BB) { |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 260 | // If SinglePred was a loop header, BB becomes one. |
| 261 | if (LoopHeaders.erase(SinglePred)) |
| 262 | LoopHeaders.insert(BB); |
| 263 | |
Chris Lattner | 3d86d24 | 2008-11-27 19:25:19 +0000 | [diff] [blame] | 264 | // Remember if SinglePred was the entry block of the function. If so, we |
| 265 | // will need to move BB back to the entry position. |
| 266 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 267 | MergeBasicBlockIntoOnlyPred(BB); |
Chris Lattner | 3d86d24 | 2008-11-27 19:25:19 +0000 | [diff] [blame] | 268 | |
| 269 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 270 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 271 | return true; |
| 272 | } |
| 273 | |
Matthijs Kooijman | 6e7b322 | 2008-05-20 07:26:45 +0000 | [diff] [blame] | 274 | // See if this block ends with a branch or switch. If so, see if the |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 275 | // condition is a phi node. If so, and if an entry of the phi node is a |
| 276 | // constant, we can thread the block. |
| 277 | Value *Condition; |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 278 | if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { |
| 279 | // Can't thread an unconditional jump. |
| 280 | if (BI->isUnconditional()) return false; |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 281 | Condition = BI->getCondition(); |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 282 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 283 | Condition = SI->getCondition(); |
| 284 | else |
| 285 | return false; // Must be an invoke. |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 286 | |
| 287 | // If the terminator of this block is branching on a constant, simplify the |
Chris Lattner | 037c781 | 2008-04-21 18:25:01 +0000 | [diff] [blame] | 288 | // terminator to an unconditional branch. This can occur due to threading in |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 289 | // other blocks. |
| 290 | if (isa<ConstantInt>(Condition)) { |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 291 | DEBUG(errs() << " In block '" << BB->getName() |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 292 | << "' folding terminator: " << *BB->getTerminator() << '\n'); |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 293 | ++NumFolds; |
| 294 | ConstantFoldTerminator(BB); |
| 295 | return true; |
| 296 | } |
| 297 | |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 298 | // If the terminator is branching on an undef, we can pick any of the |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 299 | // successors to branch to. Let GetBestDestForJumpOnUndef decide. |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 300 | if (isa<UndefValue>(Condition)) { |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 301 | unsigned BestSucc = GetBestDestForJumpOnUndef(BB); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 302 | |
| 303 | // Fold the branch/switch. |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 304 | TerminatorInst *BBTerm = BB->getTerminator(); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 305 | for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 306 | if (i == BestSucc) continue; |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 307 | BBTerm->getSuccessor(i)->removePredecessor(BB); |
| 308 | } |
| 309 | |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 310 | DEBUG(errs() << " In block '" << BB->getName() |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 311 | << "' folding undef terminator: " << *BBTerm << '\n'); |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 312 | BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 313 | BBTerm->eraseFromParent(); |
| 314 | return true; |
| 315 | } |
| 316 | |
| 317 | Instruction *CondInst = dyn_cast<Instruction>(Condition); |
| 318 | |
| 319 | // If the condition is an instruction defined in another block, see if a |
| 320 | // predecessor has the same condition: |
| 321 | // br COND, BBX, BBY |
| 322 | // BBX: |
| 323 | // br COND, BBZ, BBW |
| 324 | if (!Condition->hasOneUse() && // Multiple uses. |
| 325 | (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition. |
| 326 | pred_iterator PI = pred_begin(BB), E = pred_end(BB); |
| 327 | if (isa<BranchInst>(BB->getTerminator())) { |
| 328 | for (; PI != E; ++PI) |
| 329 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
| 330 | if (PBI->isConditional() && PBI->getCondition() == Condition && |
| 331 | ProcessBranchOnDuplicateCond(*PI, BB)) |
| 332 | return true; |
Chris Lattner | 3cda3cd | 2008-12-04 06:31:07 +0000 | [diff] [blame] | 333 | } else { |
| 334 | assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator"); |
| 335 | for (; PI != E; ++PI) |
| 336 | if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator())) |
| 337 | if (PSI->getCondition() == Condition && |
| 338 | ProcessSwitchOnDuplicateCond(*PI, BB)) |
| 339 | return true; |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 340 | } |
| 341 | } |
| 342 | |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 343 | // All the rest of our checks depend on the condition being an instruction. |
| 344 | if (CondInst == 0) |
| 345 | return false; |
| 346 | |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 347 | // See if this is a phi node in the current block. |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 348 | if (PHINode *PN = dyn_cast<PHINode>(CondInst)) |
| 349 | if (PN->getParent() == BB) |
| 350 | return ProcessJumpOnPHI(PN); |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 351 | |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 352 | // If this is a conditional branch whose condition is and/or of a phi, try to |
| 353 | // simplify it. |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 354 | if ((CondInst->getOpcode() == Instruction::And || |
| 355 | CondInst->getOpcode() == Instruction::Or) && |
| 356 | isa<BranchInst>(BB->getTerminator()) && |
| 357 | ProcessBranchOnLogical(CondInst, BB, |
| 358 | CondInst->getOpcode() == Instruction::And)) |
| 359 | return true; |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 360 | |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 361 | if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) { |
| 362 | if (isa<PHINode>(CondCmp->getOperand(0))) { |
| 363 | // If we have "br (phi != 42)" and the phi node has any constant values |
| 364 | // as operands, we can thread through this block. |
| 365 | // |
| 366 | // If we have "br (cmp phi, x)" and the phi node contains x such that the |
| 367 | // comparison uniquely identifies the branch target, we can thread |
| 368 | // through this block. |
| 369 | |
| 370 | if (ProcessBranchOnCompare(CondCmp, BB)) |
| 371 | return true; |
| 372 | } |
Chris Lattner | 79c740f | 2009-06-19 16:27:56 +0000 | [diff] [blame] | 373 | |
| 374 | // If we have a comparison, loop over the predecessors to see if there is |
| 375 | // a condition with the same value. |
| 376 | pred_iterator PI = pred_begin(BB), E = pred_end(BB); |
| 377 | for (; PI != E; ++PI) |
| 378 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
| 379 | if (PBI->isConditional() && *PI != BB) { |
| 380 | if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) { |
| 381 | if (CI->getOperand(0) == CondCmp->getOperand(0) && |
| 382 | CI->getOperand(1) == CondCmp->getOperand(1) && |
| 383 | CI->getPredicate() == CondCmp->getPredicate()) { |
| 384 | // TODO: Could handle things like (x != 4) --> (x == 17) |
| 385 | if (ProcessBranchOnDuplicateCond(*PI, BB)) |
| 386 | return true; |
| 387 | } |
| 388 | } |
| 389 | } |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 390 | } |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 391 | |
| 392 | // Check for some cases that are worth simplifying. Right now we want to look |
| 393 | // for loads that are used by a switch or by the condition for the branch. If |
| 394 | // we see one, check to see if it's partially redundant. If so, insert a PHI |
| 395 | // which can then be used to thread the values. |
| 396 | // |
| 397 | // This is particularly important because reg2mem inserts loads and stores all |
| 398 | // over the place, and this blocks jump threading if we don't zap them. |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 399 | Value *SimplifyValue = CondInst; |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 400 | if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) |
| 401 | if (isa<Constant>(CondCmp->getOperand(1))) |
| 402 | SimplifyValue = CondCmp->getOperand(0); |
| 403 | |
| 404 | if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue)) |
| 405 | if (SimplifyPartiallyRedundantLoad(LI)) |
| 406 | return true; |
| 407 | |
| 408 | // TODO: If we have: "br (X > 0)" and we have a predecessor where we know |
| 409 | // "(X == 4)" thread through this block. |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 410 | |
Chris Lattner | d38c14e | 2008-04-22 06:36:15 +0000 | [diff] [blame] | 411 | return false; |
| 412 | } |
| 413 | |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 414 | /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that |
| 415 | /// block that jump on exactly the same condition. This means that we almost |
| 416 | /// always know the direction of the edge in the DESTBB: |
| 417 | /// PREDBB: |
| 418 | /// br COND, DESTBB, BBY |
| 419 | /// DESTBB: |
| 420 | /// br COND, BBZ, BBW |
| 421 | /// |
| 422 | /// If DESTBB has multiple predecessors, we can't just constant fold the branch |
| 423 | /// in DESTBB, we have to thread over it. |
| 424 | bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB, |
| 425 | BasicBlock *BB) { |
| 426 | BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator()); |
| 427 | |
| 428 | // If both successors of PredBB go to DESTBB, we don't know anything. We can |
| 429 | // fold the branch to an unconditional one, which allows other recursive |
| 430 | // simplifications. |
| 431 | bool BranchDir; |
| 432 | if (PredBI->getSuccessor(1) != BB) |
| 433 | BranchDir = true; |
| 434 | else if (PredBI->getSuccessor(0) != BB) |
| 435 | BranchDir = false; |
| 436 | else { |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 437 | DEBUG(errs() << " In block '" << PredBB->getName() |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 438 | << "' folding terminator: " << *PredBB->getTerminator() << '\n'); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 439 | ++NumFolds; |
| 440 | ConstantFoldTerminator(PredBB); |
| 441 | return true; |
| 442 | } |
| 443 | |
| 444 | BranchInst *DestBI = cast<BranchInst>(BB->getTerminator()); |
| 445 | |
| 446 | // If the dest block has one predecessor, just fix the branch condition to a |
| 447 | // constant and fold it. |
| 448 | if (BB->getSinglePredecessor()) { |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 449 | DEBUG(errs() << " In block '" << BB->getName() |
| 450 | << "' folding condition to '" << BranchDir << "': " |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 451 | << *BB->getTerminator() << '\n'); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 452 | ++NumFolds; |
Owen Anderson | 1d0be15 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 453 | DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), |
| 454 | BranchDir)); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 455 | ConstantFoldTerminator(BB); |
| 456 | return true; |
| 457 | } |
Chris Lattner | bdbf1a1 | 2009-10-11 04:33:43 +0000 | [diff] [blame] | 458 | |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 459 | |
| 460 | // Next, figure out which successor we are threading to. |
| 461 | BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir); |
| 462 | |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 463 | // Ok, try to thread it! |
Chris Lattner | bdbf1a1 | 2009-10-11 04:33:43 +0000 | [diff] [blame] | 464 | return ThreadEdge(BB, PredBB, SuccBB); |
Chris Lattner | 421fa9e | 2008-12-03 07:48:08 +0000 | [diff] [blame] | 465 | } |
| 466 | |
Chris Lattner | 3cda3cd | 2008-12-04 06:31:07 +0000 | [diff] [blame] | 467 | /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that |
| 468 | /// block that switch on exactly the same condition. This means that we almost |
| 469 | /// always know the direction of the edge in the DESTBB: |
| 470 | /// PREDBB: |
| 471 | /// switch COND [... DESTBB, BBY ... ] |
| 472 | /// DESTBB: |
| 473 | /// switch COND [... BBZ, BBW ] |
| 474 | /// |
| 475 | /// Optimizing switches like this is very important, because simplifycfg builds |
| 476 | /// switches out of repeated 'if' conditions. |
| 477 | bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, |
| 478 | BasicBlock *DestBB) { |
Chris Lattner | 2c7ed11 | 2009-01-19 21:20:34 +0000 | [diff] [blame] | 479 | // Can't thread edge to self. |
| 480 | if (PredBB == DestBB) |
| 481 | return false; |
| 482 | |
Chris Lattner | 3cda3cd | 2008-12-04 06:31:07 +0000 | [diff] [blame] | 483 | SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator()); |
| 484 | SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator()); |
| 485 | |
| 486 | // There are a variety of optimizations that we can potentially do on these |
| 487 | // blocks: we order them from most to least preferable. |
| 488 | |
| 489 | // If DESTBB *just* contains the switch, then we can forward edges from PREDBB |
| 490 | // directly to their destination. This does not introduce *any* code size |
Dale Johannesen | 6b23339 | 2009-03-17 00:38:24 +0000 | [diff] [blame] | 491 | // growth. Skip debug info first. |
| 492 | BasicBlock::iterator BBI = DestBB->begin(); |
| 493 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 494 | BBI++; |
Chris Lattner | 3cda3cd | 2008-12-04 06:31:07 +0000 | [diff] [blame] | 495 | |
| 496 | // FIXME: Thread if it just contains a PHI. |
Dale Johannesen | 6b23339 | 2009-03-17 00:38:24 +0000 | [diff] [blame] | 497 | if (isa<SwitchInst>(BBI)) { |
Chris Lattner | 3cda3cd | 2008-12-04 06:31:07 +0000 | [diff] [blame] | 498 | bool MadeChange = false; |
| 499 | // Ignore the default edge for now. |
| 500 | for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) { |
| 501 | ConstantInt *DestVal = DestSI->getCaseValue(i); |
| 502 | BasicBlock *DestSucc = DestSI->getSuccessor(i); |
| 503 | |
| 504 | // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if |
| 505 | // PredSI has an explicit case for it. If so, forward. If it is covered |
| 506 | // by the default case, we can't update PredSI. |
| 507 | unsigned PredCase = PredSI->findCaseValue(DestVal); |
| 508 | if (PredCase == 0) continue; |
| 509 | |
| 510 | // If PredSI doesn't go to DestBB on this value, then it won't reach the |
| 511 | // case on this condition. |
| 512 | if (PredSI->getSuccessor(PredCase) != DestBB && |
| 513 | DestSI->getSuccessor(i) != DestBB) |
| 514 | continue; |
| 515 | |
| 516 | // Otherwise, we're safe to make the change. Make sure that the edge from |
| 517 | // DestSI to DestSucc is not critical and has no PHI nodes. |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 518 | DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI); |
| 519 | DEBUG(errs() << "THROUGH: " << *DestSI); |
Chris Lattner | 3cda3cd | 2008-12-04 06:31:07 +0000 | [diff] [blame] | 520 | |
| 521 | // If the destination has PHI nodes, just split the edge for updating |
| 522 | // simplicity. |
| 523 | if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){ |
| 524 | SplitCriticalEdge(DestSI, i, this); |
| 525 | DestSucc = DestSI->getSuccessor(i); |
| 526 | } |
| 527 | FoldSingleEntryPHINodes(DestSucc); |
| 528 | PredSI->setSuccessor(PredCase, DestSucc); |
| 529 | MadeChange = true; |
| 530 | } |
| 531 | |
| 532 | if (MadeChange) |
| 533 | return true; |
| 534 | } |
| 535 | |
| 536 | return false; |
| 537 | } |
| 538 | |
| 539 | |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 540 | /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant |
| 541 | /// load instruction, eliminate it by replacing it with a PHI node. This is an |
| 542 | /// important optimization that encourages jump threading, and needs to be run |
| 543 | /// interlaced with other jump threading tasks. |
| 544 | bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) { |
| 545 | // Don't hack volatile loads. |
| 546 | if (LI->isVolatile()) return false; |
| 547 | |
| 548 | // If the load is defined in a block with exactly one predecessor, it can't be |
| 549 | // partially redundant. |
| 550 | BasicBlock *LoadBB = LI->getParent(); |
| 551 | if (LoadBB->getSinglePredecessor()) |
| 552 | return false; |
| 553 | |
| 554 | Value *LoadedPtr = LI->getOperand(0); |
| 555 | |
| 556 | // If the loaded operand is defined in the LoadBB, it can't be available. |
| 557 | // FIXME: Could do PHI translation, that would be fun :) |
| 558 | if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr)) |
| 559 | if (PtrOp->getParent() == LoadBB) |
| 560 | return false; |
| 561 | |
| 562 | // Scan a few instructions up from the load, to see if it is obviously live at |
| 563 | // the entry to its block. |
| 564 | BasicBlock::iterator BBIt = LI; |
| 565 | |
Chris Lattner | 52c9585 | 2008-11-27 08:10:05 +0000 | [diff] [blame] | 566 | if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, |
| 567 | BBIt, 6)) { |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 568 | // If the value if the load is locally available within the block, just use |
| 569 | // it. This frequently occurs for reg2mem'd allocas. |
| 570 | //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n"; |
Chris Lattner | 2a99b48 | 2009-01-09 06:08:12 +0000 | [diff] [blame] | 571 | |
| 572 | // If the returned value is the load itself, replace with an undef. This can |
| 573 | // only happen in dead loops. |
Owen Anderson | 9e9a0d5 | 2009-07-30 23:03:37 +0000 | [diff] [blame] | 574 | if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType()); |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 575 | LI->replaceAllUsesWith(AvailableVal); |
| 576 | LI->eraseFromParent(); |
| 577 | return true; |
| 578 | } |
| 579 | |
| 580 | // Otherwise, if we scanned the whole block and got to the top of the block, |
| 581 | // we know the block is locally transparent to the load. If not, something |
| 582 | // might clobber its value. |
| 583 | if (BBIt != LoadBB->begin()) |
| 584 | return false; |
| 585 | |
| 586 | |
| 587 | SmallPtrSet<BasicBlock*, 8> PredsScanned; |
| 588 | typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy; |
| 589 | AvailablePredsTy AvailablePreds; |
| 590 | BasicBlock *OneUnavailablePred = 0; |
| 591 | |
| 592 | // If we got here, the loaded value is transparent through to the start of the |
| 593 | // block. Check to see if it is available in any of the predecessor blocks. |
| 594 | for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB); |
| 595 | PI != PE; ++PI) { |
| 596 | BasicBlock *PredBB = *PI; |
| 597 | |
| 598 | // If we already scanned this predecessor, skip it. |
| 599 | if (!PredsScanned.insert(PredBB)) |
| 600 | continue; |
| 601 | |
| 602 | // Scan the predecessor to see if the value is available in the pred. |
| 603 | BBIt = PredBB->end(); |
Chris Lattner | 52c9585 | 2008-11-27 08:10:05 +0000 | [diff] [blame] | 604 | Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6); |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 605 | if (!PredAvailable) { |
| 606 | OneUnavailablePred = PredBB; |
| 607 | continue; |
| 608 | } |
| 609 | |
| 610 | // If so, this load is partially redundant. Remember this info so that we |
| 611 | // can create a PHI node. |
| 612 | AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable)); |
| 613 | } |
| 614 | |
| 615 | // If the loaded value isn't available in any predecessor, it isn't partially |
| 616 | // redundant. |
| 617 | if (AvailablePreds.empty()) return false; |
| 618 | |
| 619 | // Okay, the loaded value is available in at least one (and maybe all!) |
| 620 | // predecessors. If the value is unavailable in more than one unique |
| 621 | // predecessor, we want to insert a merge block for those common predecessors. |
| 622 | // This ensures that we only have to insert one reload, thus not increasing |
| 623 | // code size. |
| 624 | BasicBlock *UnavailablePred = 0; |
| 625 | |
| 626 | // If there is exactly one predecessor where the value is unavailable, the |
| 627 | // already computed 'OneUnavailablePred' block is it. If it ends in an |
| 628 | // unconditional branch, we know that it isn't a critical edge. |
| 629 | if (PredsScanned.size() == AvailablePreds.size()+1 && |
| 630 | OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { |
| 631 | UnavailablePred = OneUnavailablePred; |
| 632 | } else if (PredsScanned.size() != AvailablePreds.size()) { |
| 633 | // Otherwise, we had multiple unavailable predecessors or we had a critical |
| 634 | // edge from the one. |
| 635 | SmallVector<BasicBlock*, 8> PredsToSplit; |
| 636 | SmallPtrSet<BasicBlock*, 8> AvailablePredSet; |
| 637 | |
| 638 | for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i) |
| 639 | AvailablePredSet.insert(AvailablePreds[i].first); |
| 640 | |
| 641 | // Add all the unavailable predecessors to the PredsToSplit list. |
| 642 | for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB); |
| 643 | PI != PE; ++PI) |
| 644 | if (!AvailablePredSet.count(*PI)) |
| 645 | PredsToSplit.push_back(*PI); |
| 646 | |
| 647 | // Split them out to their own block. |
| 648 | UnavailablePred = |
| 649 | SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(), |
| 650 | "thread-split", this); |
| 651 | } |
| 652 | |
| 653 | // If the value isn't available in all predecessors, then there will be |
| 654 | // exactly one where it isn't available. Insert a load on that edge and add |
| 655 | // it to the AvailablePreds list. |
| 656 | if (UnavailablePred) { |
| 657 | assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && |
| 658 | "Can't handle critical edge here!"); |
| 659 | Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", |
| 660 | UnavailablePred->getTerminator()); |
| 661 | AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal)); |
| 662 | } |
| 663 | |
| 664 | // Now we know that each predecessor of this block has a value in |
| 665 | // AvailablePreds, sort them for efficient access as we're walking the preds. |
Chris Lattner | a352200 | 2008-12-01 06:52:57 +0000 | [diff] [blame] | 666 | array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); |
Chris Lattner | 69e067f | 2008-11-27 05:07:53 +0000 | [diff] [blame] | 667 | |
| 668 | // Create a PHI node at the start of the block for the PRE'd load value. |
| 669 | PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin()); |
| 670 | PN->takeName(LI); |
| 671 | |
| 672 | // Insert new entries into the PHI for each predecessor. A single block may |
| 673 | // have multiple entries here. |
| 674 | for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E; |
| 675 | ++PI) { |
| 676 | AvailablePredsTy::iterator I = |
| 677 | std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(), |
| 678 | std::make_pair(*PI, (Value*)0)); |
| 679 | |
| 680 | assert(I != AvailablePreds.end() && I->first == *PI && |
| 681 | "Didn't find entry for predecessor!"); |
| 682 | |
| 683 | PN->addIncoming(I->second, I->first); |
| 684 | } |
| 685 | |
| 686 | //cerr << "PRE: " << *LI << *PN << "\n"; |
| 687 | |
| 688 | LI->replaceAllUsesWith(PN); |
| 689 | LI->eraseFromParent(); |
| 690 | |
| 691 | return true; |
| 692 | } |
| 693 | |
| 694 | |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 695 | /// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in |
Chris Lattner | d38c14e | 2008-04-22 06:36:15 +0000 | [diff] [blame] | 696 | /// the current block. See if there are any simplifications we can do based on |
| 697 | /// inputs to the phi node. |
| 698 | /// |
| 699 | bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) { |
Chris Lattner | 6b65f47 | 2009-10-11 04:40:21 +0000 | [diff] [blame] | 700 | BasicBlock *BB = PN->getParent(); |
| 701 | |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 702 | // See if the phi node has any constant integer or undef values. If so, we |
| 703 | // can determine where the corresponding predecessor will branch. |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 704 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 705 | Value *PredVal = PN->getIncomingValue(i); |
Chris Lattner | 6b65f47 | 2009-10-11 04:40:21 +0000 | [diff] [blame] | 706 | |
| 707 | // Check to see if this input is a constant integer. If so, the direction |
| 708 | // of the branch is predictable. |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 709 | if (ConstantInt *CI = dyn_cast<ConstantInt>(PredVal)) { |
Chris Lattner | 6b65f47 | 2009-10-11 04:40:21 +0000 | [diff] [blame] | 710 | // Merge any common predecessors that will act the same. |
| 711 | BasicBlock *PredBB = FactorCommonPHIPreds(PN, CI); |
| 712 | |
| 713 | BasicBlock *SuccBB; |
| 714 | if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) |
| 715 | SuccBB = BI->getSuccessor(CI->isZero()); |
| 716 | else { |
| 717 | SwitchInst *SI = cast<SwitchInst>(BB->getTerminator()); |
| 718 | SuccBB = SI->getSuccessor(SI->findCaseValue(CI)); |
| 719 | } |
| 720 | |
| 721 | // Ok, try to thread it! |
| 722 | return ThreadEdge(BB, PredBB, SuccBB); |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 723 | } |
| 724 | |
Chris Lattner | 6b65f47 | 2009-10-11 04:40:21 +0000 | [diff] [blame] | 725 | // If the input is an undef, then it doesn't matter which way it will go. |
| 726 | // Pick an arbitrary dest and thread the edge. |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 727 | if (UndefValue *UV = dyn_cast<UndefValue>(PredVal)) { |
Chris Lattner | 6b65f47 | 2009-10-11 04:40:21 +0000 | [diff] [blame] | 728 | // Merge any common predecessors that will act the same. |
| 729 | BasicBlock *PredBB = FactorCommonPHIPreds(PN, UV); |
| 730 | BasicBlock *SuccBB = |
| 731 | BB->getTerminator()->getSuccessor(GetBestDestForJumpOnUndef(BB)); |
| 732 | |
| 733 | // Ok, try to thread it! |
| 734 | return ThreadEdge(BB, PredBB, SuccBB); |
Chris Lattner | e33583b | 2009-10-11 04:18:15 +0000 | [diff] [blame] | 735 | } |
Chris Lattner | 6b65f47 | 2009-10-11 04:40:21 +0000 | [diff] [blame] | 736 | } |
Chris Lattner | f9065a9 | 2008-04-20 21:18:09 +0000 | [diff] [blame] | 737 | |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 738 | // If the incoming values are all variables, we don't know the destination of |
| 739 | // any predecessors. However, if any of the predecessor blocks end in an |
| 740 | // unconditional branch, we can *duplicate* the jump into that block in order |
| 741 | // to further encourage jump threading and to eliminate cases where we have |
| 742 | // branch on a phi of an icmp (branch on icmp is much better). |
| 743 | |
| 744 | // We don't want to do this tranformation for switches, because we don't |
| 745 | // really want to duplicate a switch. |
| 746 | if (isa<SwitchInst>(BB->getTerminator())) |
| 747 | return false; |
| 748 | |
| 749 | // Look for unconditional branch predecessors. |
| 750 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 751 | BasicBlock *PredBB = PN->getIncomingBlock(i); |
| 752 | if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator())) |
| 753 | if (PredBr->isUnconditional() && |
| 754 | // Try to duplicate BB into PredBB. |
| 755 | DuplicateCondBranchOnPHIIntoPred(BB, PredBB)) |
| 756 | return true; |
| 757 | } |
| 758 | |
Chris Lattner | 6b65f47 | 2009-10-11 04:40:21 +0000 | [diff] [blame] | 759 | return false; |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 760 | } |
| 761 | |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 762 | |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 763 | /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch |
| 764 | /// whose condition is an AND/OR where one side is PN. If PN has constant |
| 765 | /// operands that permit us to evaluate the condition for some operand, thread |
| 766 | /// through the block. For example with: |
| 767 | /// br (and X, phi(Y, Z, false)) |
| 768 | /// the predecessor corresponding to the 'false' will always jump to the false |
| 769 | /// destination of the branch. |
| 770 | /// |
Chris Lattner | ae65b3c | 2008-04-22 20:46:09 +0000 | [diff] [blame] | 771 | bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB, |
| 772 | bool isAnd) { |
| 773 | // If this is a binary operator tree of the same AND/OR opcode, check the |
| 774 | // LHS/RHS. |
| 775 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) |
Duncan Sands | 43e2a03 | 2008-05-27 11:50:51 +0000 | [diff] [blame] | 776 | if ((isAnd && BO->getOpcode() == Instruction::And) || |
| 777 | (!isAnd && BO->getOpcode() == Instruction::Or)) { |
Chris Lattner | ae65b3c | 2008-04-22 20:46:09 +0000 | [diff] [blame] | 778 | if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd)) |
| 779 | return true; |
| 780 | if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd)) |
| 781 | return true; |
| 782 | } |
| 783 | |
| 784 | // If this isn't a PHI node, we can't handle it. |
| 785 | PHINode *PN = dyn_cast<PHINode>(V); |
| 786 | if (!PN || PN->getParent() != BB) return false; |
| 787 | |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 788 | // We can only do the simplification for phi nodes of 'false' with AND or |
| 789 | // 'true' with OR. See if we have any entries in the phi for this. |
| 790 | unsigned PredNo = ~0U; |
Owen Anderson | 1d0be15 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 791 | ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()), |
| 792 | !isAnd); |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 793 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 794 | if (PN->getIncomingValue(i) == PredCst) { |
| 795 | PredNo = i; |
| 796 | break; |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | // If no match, bail out. |
| 801 | if (PredNo == ~0U) |
| 802 | return false; |
| 803 | |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 804 | // If so, we can actually do this threading. Merge any common predecessors |
| 805 | // that will act the same. |
| 806 | BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst); |
| 807 | |
| 808 | // Next, figure out which successor we are threading to. If this was an AND, |
| 809 | // the constant must be FALSE, and we must be targeting the 'false' block. |
| 810 | // If this is an OR, the constant must be TRUE, and we must be targeting the |
| 811 | // 'true' block. |
| 812 | BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd); |
| 813 | |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 814 | // Ok, try to thread it! |
Chris Lattner | bdbf1a1 | 2009-10-11 04:33:43 +0000 | [diff] [blame] | 815 | return ThreadEdge(BB, PredBB, SuccBB); |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 816 | } |
| 817 | |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 818 | /// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right |
| 819 | /// hand sides of the compare instruction, try to determine the result. If the |
| 820 | /// result can not be determined, a null pointer is returned. |
| 821 | static Constant *GetResultOfComparison(CmpInst::Predicate pred, |
Owen Anderson | 1ff50b3 | 2009-07-03 00:54:20 +0000 | [diff] [blame] | 822 | Value *LHS, Value *RHS, |
Owen Anderson | e922c02 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 823 | LLVMContext &Context) { |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 824 | if (Constant *CLHS = dyn_cast<Constant>(LHS)) |
| 825 | if (Constant *CRHS = dyn_cast<Constant>(RHS)) |
Owen Anderson | baf3c40 | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 826 | return ConstantExpr::getCompare(pred, CLHS, CRHS); |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 827 | |
| 828 | if (LHS == RHS) |
| 829 | if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType())) |
| 830 | return ICmpInst::isTrueWhenEqual(pred) ? |
Owen Anderson | 5defacc | 2009-07-31 17:39:07 +0000 | [diff] [blame] | 831 | ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context); |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 832 | |
| 833 | return 0; |
| 834 | } |
| 835 | |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 836 | /// ProcessBranchOnCompare - We found a branch on a comparison between a phi |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 837 | /// node and a value. If we can identify when the comparison is true between |
| 838 | /// the phi inputs and the value, we can fold the compare for that edge and |
| 839 | /// thread through it. |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 840 | bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) { |
| 841 | PHINode *PN = cast<PHINode>(Cmp->getOperand(0)); |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 842 | Value *RHS = Cmp->getOperand(1); |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 843 | |
| 844 | // If the phi isn't in the current block, an incoming edge to this block |
| 845 | // doesn't control the destination. |
| 846 | if (PN->getParent() != BB) |
| 847 | return false; |
| 848 | |
| 849 | // We can do this simplification if any comparisons fold to true or false. |
| 850 | // See if any do. |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 851 | Value *PredVal = 0; |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 852 | bool TrueDirection = false; |
| 853 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 854 | PredVal = PN->getIncomingValue(i); |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 855 | |
Owen Anderson | 1ff50b3 | 2009-07-03 00:54:20 +0000 | [diff] [blame] | 856 | Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal, |
Owen Anderson | e922c02 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 857 | RHS, Cmp->getContext()); |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 858 | if (!Res) { |
| 859 | PredVal = 0; |
| 860 | continue; |
| 861 | } |
| 862 | |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 863 | // If this folded to a constant expr, we can't do anything. |
| 864 | if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) { |
| 865 | TrueDirection = ResC->getZExtValue(); |
| 866 | break; |
| 867 | } |
| 868 | // If this folded to undef, just go the false way. |
| 869 | if (isa<UndefValue>(Res)) { |
| 870 | TrueDirection = false; |
| 871 | break; |
| 872 | } |
| 873 | |
| 874 | // Otherwise, we can't fold this input. |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 875 | PredVal = 0; |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 876 | } |
| 877 | |
| 878 | // If no match, bail out. |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 879 | if (PredVal == 0) |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 880 | return false; |
| 881 | |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 882 | // If so, we can actually do this threading. Merge any common predecessors |
| 883 | // that will act the same. |
Nick Lewycky | 9683f18 | 2009-06-19 04:56:29 +0000 | [diff] [blame] | 884 | BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal); |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 885 | |
| 886 | // Next, get our successor. |
| 887 | BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection); |
| 888 | |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 889 | // Ok, try to thread it! |
Chris Lattner | bdbf1a1 | 2009-10-11 04:33:43 +0000 | [diff] [blame] | 890 | return ThreadEdge(BB, PredBB, SuccBB); |
| 891 | } |
| 892 | |
Chris Lattner | a5ddb59 | 2008-04-22 21:40:39 +0000 | [diff] [blame] | 893 | |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 894 | /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new |
| 895 | /// predecessor to the PHIBB block. If it has PHI nodes, add entries for |
| 896 | /// NewPred using the entries from OldPred (suitably mapped). |
| 897 | static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, |
| 898 | BasicBlock *OldPred, |
| 899 | BasicBlock *NewPred, |
| 900 | DenseMap<Instruction*, Value*> &ValueMap) { |
| 901 | for (BasicBlock::iterator PNI = PHIBB->begin(); |
| 902 | PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) { |
| 903 | // Ok, we have a PHI node. Figure out what the incoming value was for the |
| 904 | // DestBlock. |
| 905 | Value *IV = PN->getIncomingValueForBlock(OldPred); |
| 906 | |
| 907 | // Remap the value if necessary. |
| 908 | if (Instruction *Inst = dyn_cast<Instruction>(IV)) { |
| 909 | DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst); |
| 910 | if (I != ValueMap.end()) |
| 911 | IV = I->second; |
| 912 | } |
| 913 | |
| 914 | PN->addIncoming(IV, NewPred); |
| 915 | } |
| 916 | } |
Chris Lattner | 6bf7750 | 2008-04-22 07:05:46 +0000 | [diff] [blame] | 917 | |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 918 | /// ThreadEdge - We have decided that it is safe and profitable to thread an |
| 919 | /// edge from PredBB to SuccBB across BB. Transform the IR to reflect this |
| 920 | /// change. |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 921 | bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, |
Chris Lattner | bdbf1a1 | 2009-10-11 04:33:43 +0000 | [diff] [blame] | 922 | BasicBlock *SuccBB) { |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 923 | // If threading to the same block as we come from, we would infinite loop. |
| 924 | if (SuccBB == BB) { |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 925 | DEBUG(errs() << " Not threading across BB '" << BB->getName() |
| 926 | << "' - would thread to self!\n"); |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 927 | return false; |
| 928 | } |
| 929 | |
| 930 | // If threading this would thread across a loop header, don't thread the edge. |
| 931 | // See the comments above FindLoopHeaders for justifications and caveats. |
| 932 | if (LoopHeaders.count(BB)) { |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 933 | DEBUG(errs() << " Not threading from '" << PredBB->getName() |
| 934 | << "' across loop header BB '" << BB->getName() |
| 935 | << "' to dest BB '" << SuccBB->getName() |
| 936 | << "' - it might create an irreducible loop!\n"); |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 937 | return false; |
| 938 | } |
| 939 | |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 940 | unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB); |
| 941 | if (JumpThreadCost > Threshold) { |
| 942 | DEBUG(errs() << " Not threading BB '" << BB->getName() |
| 943 | << "' - Cost is too high: " << JumpThreadCost << "\n"); |
| 944 | return false; |
| 945 | } |
| 946 | |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 947 | // And finally, do it! |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 948 | DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '" |
Daniel Dunbar | 460f656 | 2009-07-26 09:48:23 +0000 | [diff] [blame] | 949 | << SuccBB->getName() << "' with cost: " << JumpThreadCost |
Daniel Dunbar | 93b67e4 | 2009-07-26 07:49:05 +0000 | [diff] [blame] | 950 | << ", across block:\n " |
| 951 | << *BB << "\n"); |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 952 | |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 953 | // We are going to have to map operands from the original BB block to the new |
| 954 | // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to |
| 955 | // account for entry from PredBB. |
| 956 | DenseMap<Instruction*, Value*> ValueMapping; |
| 957 | |
Owen Anderson | 1d0be15 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 958 | BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), |
| 959 | BB->getName()+".thread", |
| 960 | BB->getParent(), BB); |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 961 | NewBB->moveAfter(PredBB); |
| 962 | |
| 963 | BasicBlock::iterator BI = BB->begin(); |
| 964 | for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) |
| 965 | ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); |
| 966 | |
| 967 | // Clone the non-phi instructions of BB into NewBB, keeping track of the |
| 968 | // mapping and using it to remap operands in the cloned instructions. |
| 969 | for (; !isa<TerminatorInst>(BI); ++BI) { |
Nick Lewycky | 6776064 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 970 | Instruction *New = BI->clone(); |
Daniel Dunbar | 460f656 | 2009-07-26 09:48:23 +0000 | [diff] [blame] | 971 | New->setName(BI->getName()); |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 972 | NewBB->getInstList().push_back(New); |
| 973 | ValueMapping[BI] = New; |
| 974 | |
| 975 | // Remap operands to patch up intra-block references. |
| 976 | for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) |
Dan Gohman | f530c92 | 2009-07-02 00:17:47 +0000 | [diff] [blame] | 977 | if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { |
| 978 | DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); |
| 979 | if (I != ValueMapping.end()) |
| 980 | New->setOperand(i, I->second); |
| 981 | } |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 982 | } |
| 983 | |
| 984 | // We didn't copy the terminator from BB over to NewBB, because there is now |
| 985 | // an unconditional jump to SuccBB. Insert the unconditional jump. |
| 986 | BranchInst::Create(SuccBB, NewBB); |
| 987 | |
| 988 | // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the |
| 989 | // PHI nodes for NewBB now. |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 990 | AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping); |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 991 | |
Chris Lattner | 433a0db | 2009-10-10 09:05:58 +0000 | [diff] [blame] | 992 | // If there were values defined in BB that are used outside the block, then we |
| 993 | // now have to update all uses of the value to use either the original value, |
| 994 | // the cloned value, or some PHI derived value. This can require arbitrary |
| 995 | // PHI insertion, of which we are prepared to do, clean these up now. |
| 996 | SSAUpdater SSAUpdate; |
| 997 | SmallVector<Use*, 16> UsesToRename; |
| 998 | for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) { |
| 999 | // Scan all uses of this instruction to see if it is used outside of its |
| 1000 | // block, and if so, record them in UsesToRename. |
| 1001 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; |
| 1002 | ++UI) { |
| 1003 | Instruction *User = cast<Instruction>(*UI); |
| 1004 | if (PHINode *UserPN = dyn_cast<PHINode>(User)) { |
| 1005 | if (UserPN->getIncomingBlock(UI) == BB) |
| 1006 | continue; |
| 1007 | } else if (User->getParent() == BB) |
| 1008 | continue; |
| 1009 | |
| 1010 | UsesToRename.push_back(&UI.getUse()); |
| 1011 | } |
| 1012 | |
| 1013 | // If there are no uses outside the block, we're done with this instruction. |
| 1014 | if (UsesToRename.empty()) |
| 1015 | continue; |
| 1016 | |
| 1017 | DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n"); |
| 1018 | |
| 1019 | // We found a use of I outside of BB. Rename all uses of I that are outside |
| 1020 | // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks |
| 1021 | // with the two values we know. |
| 1022 | SSAUpdate.Initialize(I); |
| 1023 | SSAUpdate.AddAvailableValue(BB, I); |
| 1024 | SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]); |
| 1025 | |
| 1026 | while (!UsesToRename.empty()) |
| 1027 | SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); |
| 1028 | DEBUG(errs() << "\n"); |
| 1029 | } |
| 1030 | |
| 1031 | |
Chris Lattner | ef0c674 | 2008-12-01 04:48:07 +0000 | [diff] [blame] | 1032 | // Ok, NewBB is good to go. Update the terminator of PredBB to jump to |
Chris Lattner | bd3401f | 2008-04-20 22:39:42 +0000 | [diff] [blame] | 1033 | // NewBB instead of BB. This eliminates predecessors from BB, which requires |
| 1034 | // us to simplify any PHI nodes in BB. |
| 1035 | TerminatorInst *PredTerm = PredBB->getTerminator(); |
| 1036 | for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) |
| 1037 | if (PredTerm->getSuccessor(i) == BB) { |
| 1038 | BB->removePredecessor(PredBB); |
| 1039 | PredTerm->setSuccessor(i, NewBB); |
| 1040 | } |
Chris Lattner | ef0c674 | 2008-12-01 04:48:07 +0000 | [diff] [blame] | 1041 | |
| 1042 | // At this point, the IR is fully up to date and consistent. Do a quick scan |
| 1043 | // over the new instructions and zap any that are constants or dead. This |
| 1044 | // frequently happens because of phi translation. |
| 1045 | BI = NewBB->begin(); |
| 1046 | for (BasicBlock::iterator E = NewBB->end(); BI != E; ) { |
| 1047 | Instruction *Inst = BI++; |
Owen Anderson | 5089551 | 2009-07-06 18:42:36 +0000 | [diff] [blame] | 1048 | if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) { |
Chris Lattner | ef0c674 | 2008-12-01 04:48:07 +0000 | [diff] [blame] | 1049 | Inst->replaceAllUsesWith(C); |
| 1050 | Inst->eraseFromParent(); |
| 1051 | continue; |
| 1052 | } |
| 1053 | |
| 1054 | RecursivelyDeleteTriviallyDeadInstructions(Inst); |
| 1055 | } |
Mike Stump | fe095f3 | 2009-05-04 18:40:41 +0000 | [diff] [blame] | 1056 | |
| 1057 | // Threaded an edge! |
| 1058 | ++NumThreads; |
| 1059 | return true; |
Chris Lattner | 177480b | 2008-04-20 21:13:06 +0000 | [diff] [blame] | 1060 | } |
Chris Lattner | 78c552e | 2009-10-11 07:24:57 +0000 | [diff] [blame^] | 1061 | |
| 1062 | /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch |
| 1063 | /// to BB which contains an i1 PHI node and a conditional branch on that PHI. |
| 1064 | /// If we can duplicate the contents of BB up into PredBB do so now, this |
| 1065 | /// improves the odds that the branch will be on an analyzable instruction like |
| 1066 | /// a compare. |
| 1067 | bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB, |
| 1068 | BasicBlock *PredBB) { |
| 1069 | // If BB is a loop header, then duplicating this block outside the loop would |
| 1070 | // cause us to transform this into an irreducible loop, don't do this. |
| 1071 | // See the comments above FindLoopHeaders for justifications and caveats. |
| 1072 | if (LoopHeaders.count(BB)) { |
| 1073 | DEBUG(errs() << " Not duplicating loop header '" << BB->getName() |
| 1074 | << "' into predecessor block '" << PredBB->getName() |
| 1075 | << "' - it might create an irreducible loop!\n"); |
| 1076 | return false; |
| 1077 | } |
| 1078 | |
| 1079 | unsigned DuplicationCost = getJumpThreadDuplicationCost(BB); |
| 1080 | if (DuplicationCost > Threshold) { |
| 1081 | DEBUG(errs() << " Not duplicating BB '" << BB->getName() |
| 1082 | << "' - Cost is too high: " << DuplicationCost << "\n"); |
| 1083 | return false; |
| 1084 | } |
| 1085 | |
| 1086 | // Okay, we decided to do this! Clone all the instructions in BB onto the end |
| 1087 | // of PredBB. |
| 1088 | DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '" |
| 1089 | << PredBB->getName() << "' to eliminate branch on phi. Cost: " |
| 1090 | << DuplicationCost << " block is:" << *BB << "\n"); |
| 1091 | |
| 1092 | // We are going to have to map operands from the original BB block into the |
| 1093 | // PredBB block. Evaluate PHI nodes in BB. |
| 1094 | DenseMap<Instruction*, Value*> ValueMapping; |
| 1095 | |
| 1096 | BasicBlock::iterator BI = BB->begin(); |
| 1097 | for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) |
| 1098 | ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); |
| 1099 | |
| 1100 | BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator()); |
| 1101 | |
| 1102 | // Clone the non-phi instructions of BB into PredBB, keeping track of the |
| 1103 | // mapping and using it to remap operands in the cloned instructions. |
| 1104 | for (; BI != BB->end(); ++BI) { |
| 1105 | Instruction *New = BI->clone(); |
| 1106 | New->setName(BI->getName()); |
| 1107 | PredBB->getInstList().insert(OldPredBranch, New); |
| 1108 | ValueMapping[BI] = New; |
| 1109 | |
| 1110 | // Remap operands to patch up intra-block references. |
| 1111 | for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) |
| 1112 | if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { |
| 1113 | DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); |
| 1114 | if (I != ValueMapping.end()) |
| 1115 | New->setOperand(i, I->second); |
| 1116 | } |
| 1117 | } |
| 1118 | |
| 1119 | // Check to see if the targets of the branch had PHI nodes. If so, we need to |
| 1120 | // add entries to the PHI nodes for branch from PredBB now. |
| 1121 | BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator()); |
| 1122 | AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB, |
| 1123 | ValueMapping); |
| 1124 | AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB, |
| 1125 | ValueMapping); |
| 1126 | |
| 1127 | // If there were values defined in BB that are used outside the block, then we |
| 1128 | // now have to update all uses of the value to use either the original value, |
| 1129 | // the cloned value, or some PHI derived value. This can require arbitrary |
| 1130 | // PHI insertion, of which we are prepared to do, clean these up now. |
| 1131 | SSAUpdater SSAUpdate; |
| 1132 | SmallVector<Use*, 16> UsesToRename; |
| 1133 | for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) { |
| 1134 | // Scan all uses of this instruction to see if it is used outside of its |
| 1135 | // block, and if so, record them in UsesToRename. |
| 1136 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; |
| 1137 | ++UI) { |
| 1138 | Instruction *User = cast<Instruction>(*UI); |
| 1139 | if (PHINode *UserPN = dyn_cast<PHINode>(User)) { |
| 1140 | if (UserPN->getIncomingBlock(UI) == BB) |
| 1141 | continue; |
| 1142 | } else if (User->getParent() == BB) |
| 1143 | continue; |
| 1144 | |
| 1145 | UsesToRename.push_back(&UI.getUse()); |
| 1146 | } |
| 1147 | |
| 1148 | // If there are no uses outside the block, we're done with this instruction. |
| 1149 | if (UsesToRename.empty()) |
| 1150 | continue; |
| 1151 | |
| 1152 | DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n"); |
| 1153 | |
| 1154 | // We found a use of I outside of BB. Rename all uses of I that are outside |
| 1155 | // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks |
| 1156 | // with the two values we know. |
| 1157 | SSAUpdate.Initialize(I); |
| 1158 | SSAUpdate.AddAvailableValue(BB, I); |
| 1159 | SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]); |
| 1160 | |
| 1161 | while (!UsesToRename.empty()) |
| 1162 | SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); |
| 1163 | DEBUG(errs() << "\n"); |
| 1164 | } |
| 1165 | |
| 1166 | // PredBB no longer jumps to BB, remove entries in the PHI node for the edge |
| 1167 | // that we nuked. |
| 1168 | BB->removePredecessor(PredBB); |
| 1169 | |
| 1170 | // Remove the unconditional branch at the end of the PredBB block. |
| 1171 | OldPredBranch->eraseFromParent(); |
| 1172 | |
| 1173 | ++NumDupes; |
| 1174 | return true; |
| 1175 | } |
| 1176 | |
| 1177 | |