1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Jump Threading pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "jump-threading"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/Pass.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
27 STATISTIC(NumThreads, "Number of jumps threaded");
28 STATISTIC(NumFolds, "Number of terminators folded");
30 static cl::opt<unsigned>
31 Threshold("jump-threading-threshold",
32 cl::desc("Max block size to duplicate for jump threading"),
33 cl::init(6), cl::Hidden);
36 /// This pass performs 'jump threading', which looks at blocks that have
37 /// multiple predecessors and multiple successors. If one or more of the
38 /// predecessors of the block can be proven to always jump to one of the
39 /// successors, we forward the edge from the predecessor to the successor by
40 /// duplicating the contents of this block.
42 /// An example of when this can occur is code like this:
49 /// In this case, the unconditional branch at the end of the first if can be
50 /// revectored to the false side of the second if.
52 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
54 static char ID; // Pass identification
55 JumpThreading() : FunctionPass((intptr_t)&ID) {}
57 bool runOnFunction(Function &F);
58 bool ThreadBlock(BasicBlock *BB);
59 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
60 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
62 bool ProcessJumpOnPHI(PHINode *PN);
63 bool ProcessJumpOnLogicalPHI(PHINode *PN, bool isAnd);
65 char JumpThreading::ID = 0;
66 RegisterPass<JumpThreading> X("jump-threading", "Jump Threading");
69 // Public interface to the Jump Threading pass
70 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
72 /// runOnFunction - Top level algorithm.
74 bool JumpThreading::runOnFunction(Function &F) {
75 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
77 bool AnotherIteration = true, EverChanged = false;
78 while (AnotherIteration) {
79 AnotherIteration = false;
81 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
82 while (ThreadBlock(I))
84 AnotherIteration = Changed;
85 EverChanged |= Changed;
90 /// FactorCommonPHIPreds - If there are multiple preds with the same incoming
91 /// value for the PHI, factor them together so we get one block to thread for
93 /// This is important for things like "phi i1 [true, true, false, true, x]"
94 /// where we only need to clone the block for the true blocks once.
96 BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
97 SmallVector<BasicBlock*, 16> CommonPreds;
98 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
99 if (PN->getIncomingValue(i) == CstVal)
100 CommonPreds.push_back(PN->getIncomingBlock(i));
102 if (CommonPreds.size() == 1)
103 return CommonPreds[0];
105 DOUT << " Factoring out " << CommonPreds.size()
106 << " common predecessors.\n";
107 return SplitBlockPredecessors(PN->getParent(),
108 &CommonPreds[0], CommonPreds.size(),
113 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
114 /// thread across it.
115 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
116 BasicBlock::const_iterator I = BB->begin();
117 /// Ignore PHI nodes, these will be flattened when duplication happens.
118 while (isa<PHINode>(*I)) ++I;
120 // Sum up the cost of each instruction until we get to the terminator. Don't
121 // include the terminator because the copy won't include it.
123 for (; !isa<TerminatorInst>(I); ++I) {
124 // Debugger intrinsics don't incur code size.
125 if (isa<DbgInfoIntrinsic>(I)) continue;
127 // If this is a pointer->pointer bitcast, it is free.
128 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
131 // All other instructions count for at least one unit.
134 // Calls are more expensive. If they are non-intrinsic calls, we model them
135 // as having cost of 4. If they are a non-vector intrinsic, we model them
136 // as having cost of 2 total, and if they are a vector intrinsic, we model
137 // them as having cost 1.
138 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
139 if (!isa<IntrinsicInst>(CI))
141 else if (isa<VectorType>(CI->getType()))
146 // Threading through a switch statement is particularly profitable. If this
147 // block ends in a switch, decrease its cost to make it more likely to happen.
148 if (isa<SwitchInst>(I))
149 Size = Size > 6 ? Size-6 : 0;
155 /// ThreadBlock - If there are any predecessors whose control can be threaded
156 /// through to a successor, transform them now.
157 bool JumpThreading::ThreadBlock(BasicBlock *BB) {
158 // See if this block ends with a branch of switch. If so, see if the
159 // condition is a phi node. If so, and if an entry of the phi node is a
160 // constant, we can thread the block.
162 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
163 // Can't thread an unconditional jump.
164 if (BI->isUnconditional()) return false;
165 Condition = BI->getCondition();
166 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
167 Condition = SI->getCondition();
169 return false; // Must be an invoke.
171 // If the terminator of this block is branching on a constant, simplify the
172 // terminator to an unconditional branch. This can occur due to threading in
174 if (isa<ConstantInt>(Condition)) {
175 DOUT << " In block '" << BB->getNameStart()
176 << "' folding terminator: " << *BB->getTerminator();
178 ConstantFoldTerminator(BB);
182 // If there is only a single predecessor of this block, nothing to fold.
183 if (BB->getSinglePredecessor())
186 // See if this is a phi node in the current block.
187 PHINode *PN = dyn_cast<PHINode>(Condition);
188 if (PN && PN->getParent() == BB)
189 return ProcessJumpOnPHI(PN);
191 // If this is a conditional branch whose condition is and/or of a phi, try to
193 if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
194 if ((CondI->getOpcode() == Instruction::And ||
195 CondI->getOpcode() == Instruction::Or) &&
196 isa<BranchInst>(BB->getTerminator())) {
197 if (PHINode *PN = dyn_cast<PHINode>(CondI->getOperand(0)))
198 if (PN->getParent() == BB &&
199 ProcessJumpOnLogicalPHI(PN, CondI->getOpcode() == Instruction::And))
201 if (PHINode *PN = dyn_cast<PHINode>(CondI->getOperand(1)))
202 if (PN->getParent() == BB &&
203 ProcessJumpOnLogicalPHI(PN, CondI->getOpcode() == Instruction::And))
211 /// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
212 /// the current block. See if there are any simplifications we can do based on
213 /// inputs to the phi node.
215 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
216 // See if the phi node has any constant values. If so, we can determine where
217 // the corresponding predecessor will branch.
218 unsigned PredNo = ~0U;
219 ConstantInt *PredCst = 0;
220 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
221 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i)))) {
227 // If no incoming value has a constant, we don't know the destination of any
232 // See if the cost of duplicating this block is low enough.
233 BasicBlock *BB = PN->getParent();
234 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
235 if (JumpThreadCost > Threshold) {
236 DOUT << " Not threading BB '" << BB->getNameStart()
237 << "' - Cost is too high: " << JumpThreadCost << "\n";
241 // If so, we can actually do this threading. Merge any common predecessors
242 // that will act the same.
243 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
245 // Next, figure out which successor we are threading to.
247 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
248 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
250 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
251 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
254 // And finally, do it!
255 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
256 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
257 << ", across block:\n "
260 ThreadEdge(BB, PredBB, SuccBB);
265 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
266 /// whose condition is an AND/OR where one side is PN. If PN has constant
267 /// operands that permit us to evaluate the condition for some operand, thread
268 /// through the block. For example with:
269 /// br (and X, phi(Y, Z, false))
270 /// the predecessor corresponding to the 'false' will always jump to the false
271 /// destination of the branch.
273 bool JumpThreading::ProcessJumpOnLogicalPHI(PHINode *PN, bool isAnd) {
275 // We can only do the simplification for phi nodes of 'false' with AND or
276 // 'true' with OR. See if we have any entries in the phi for this.
277 unsigned PredNo = ~0U;
278 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
279 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
280 if (PN->getIncomingValue(i) == PredCst) {
286 // If no match, bail out.
290 // See if the cost of duplicating this block is low enough.
291 BasicBlock *BB = PN->getParent();
292 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
293 if (JumpThreadCost > Threshold) {
294 DOUT << " Not threading BB '" << BB->getNameStart()
295 << "' - Cost is too high: " << JumpThreadCost << "\n";
299 // If so, we can actually do this threading. Merge any common predecessors
300 // that will act the same.
301 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
303 // Next, figure out which successor we are threading to. If this was an AND,
304 // the constant must be FALSE, and we must be targeting the 'false' block.
305 // If this is an OR, the constant must be TRUE, and we must be targeting the
307 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
309 // And finally, do it!
310 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
311 << "' to '" << SuccBB->getNameStart() << "' with cost: "
312 << JumpThreadCost << ", across block:\n "
315 ThreadEdge(BB, PredBB, SuccBB);
321 /// ThreadEdge - We have decided that it is safe and profitable to thread an
322 /// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
324 void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
325 BasicBlock *SuccBB) {
327 // Jump Threading can not update SSA properties correctly if the values
328 // defined in the duplicated block are used outside of the block itself. For
329 // this reason, we spill all values that are used outside of BB to the stack.
330 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
331 if (I->isUsedOutsideOfBlock(BB)) {
332 // We found a use of I outside of BB. Create a new stack slot to
333 // break this inter-block usage pattern.
334 DemoteRegToStack(*I);
337 // We are going to have to map operands from the original BB block to the new
338 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
339 // account for entry from PredBB.
340 DenseMap<Instruction*, Value*> ValueMapping;
343 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
344 NewBB->moveAfter(PredBB);
346 BasicBlock::iterator BI = BB->begin();
347 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
348 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
350 // Clone the non-phi instructions of BB into NewBB, keeping track of the
351 // mapping and using it to remap operands in the cloned instructions.
352 for (; !isa<TerminatorInst>(BI); ++BI) {
353 Instruction *New = BI->clone();
354 New->setName(BI->getNameStart());
355 NewBB->getInstList().push_back(New);
356 ValueMapping[BI] = New;
358 // Remap operands to patch up intra-block references.
359 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
360 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
361 if (Value *Remapped = ValueMapping[Inst])
362 New->setOperand(i, Remapped);
365 // We didn't copy the terminator from BB over to NewBB, because there is now
366 // an unconditional jump to SuccBB. Insert the unconditional jump.
367 BranchInst::Create(SuccBB, NewBB);
369 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
370 // PHI nodes for NewBB now.
371 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
372 PHINode *PN = cast<PHINode>(PNI);
373 // Ok, we have a PHI node. Figure out what the incoming value was for the
375 Value *IV = PN->getIncomingValueForBlock(BB);
377 // Remap the value if necessary.
378 if (Instruction *Inst = dyn_cast<Instruction>(IV))
379 if (Value *MappedIV = ValueMapping[Inst])
381 PN->addIncoming(IV, NewBB);
384 // Finally, NewBB is good to go. Update the terminator of PredBB to jump to
385 // NewBB instead of BB. This eliminates predecessors from BB, which requires
386 // us to simplify any PHI nodes in BB.
387 TerminatorInst *PredTerm = PredBB->getTerminator();
388 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
389 if (PredTerm->getSuccessor(i) == BB) {
390 BB->removePredecessor(PredBB);
391 PredTerm->setSuccessor(i, NewBB);