blob: 72c4acbaa5f3eb2220638e1ebb519a7d41743742 [file] [log] [blame]
Chris Lattneree99d152008-04-20 20:35:01 +00001//===- 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 Lattner6c2a5502008-04-20 21:13:06 +000010// This file implements the Jump Threading pass.
Chris Lattneree99d152008-04-20 20:35:01 +000011//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "jump-threading"
15#include "llvm/Transforms/Scalar.h"
Chris Lattner6c2a5502008-04-20 21:13:06 +000016#include "llvm/IntrinsicInst.h"
Chris Lattneree99d152008-04-20 20:35:01 +000017#include "llvm/Pass.h"
Chris Lattneree23b832008-04-20 22:39:42 +000018#include "llvm/ADT/DenseMap.h"
Chris Lattneree99d152008-04-20 20:35:01 +000019#include "llvm/ADT/Statistic.h"
Chris Lattnerd980e342008-04-21 02:57:57 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattneree23b832008-04-20 22:39:42 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattneree99d152008-04-20 20:35:01 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Compiler.h"
Chris Lattner6c2a5502008-04-20 21:13:06 +000024#include "llvm/Support/Debug.h"
Chris Lattneree99d152008-04-20 20:35:01 +000025using namespace llvm;
26
Chris Lattneree23b832008-04-20 22:39:42 +000027STATISTIC(NumThreads, "Number of jumps threaded");
28STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattneree99d152008-04-20 20:35:01 +000029
Chris Lattner6c2a5502008-04-20 21:13:06 +000030static cl::opt<unsigned>
31Threshold("jump-threading-threshold",
32 cl::desc("Max block size to duplicate for jump threading"),
33 cl::init(6), cl::Hidden);
34
Chris Lattneree99d152008-04-20 20:35:01 +000035namespace {
Chris Lattner6c2a5502008-04-20 21:13:06 +000036 /// 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.
41 ///
42 /// An example of when this can occur is code like this:
43 ///
44 /// if () { ...
45 /// X = 4;
46 /// }
47 /// if (X < 3) {
48 ///
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.
51 ///
Chris Lattneree99d152008-04-20 20:35:01 +000052 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
53 public:
54 static char ID; // Pass identification
55 JumpThreading() : FunctionPass((intptr_t)&ID) {}
56
57 bool runOnFunction(Function &F);
Chris Lattneree23b832008-04-20 22:39:42 +000058 bool ThreadBlock(BasicBlock *BB);
59 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattnerfddc5022008-04-22 07:05:46 +000060 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
61
Chris Lattnercbc3a3e2008-04-22 06:36:15 +000062 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerdfdff6c2008-04-22 20:46:09 +000063 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattneree99d152008-04-20 20:35:01 +000064 };
65 char JumpThreading::ID = 0;
66 RegisterPass<JumpThreading> X("jump-threading", "Jump Threading");
67}
68
69// Public interface to the Jump Threading pass
70FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
71
72/// runOnFunction - Top level algorithm.
73///
74bool JumpThreading::runOnFunction(Function &F) {
Chris Lattner6c2a5502008-04-20 21:13:06 +000075 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattneree23b832008-04-20 22:39:42 +000076
77 bool AnotherIteration = true, EverChanged = false;
78 while (AnotherIteration) {
79 AnotherIteration = false;
80 bool Changed = false;
81 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
82 while (ThreadBlock(I))
83 Changed = true;
84 AnotherIteration = Changed;
85 EverChanged |= Changed;
86 }
87 return EverChanged;
Chris Lattneree99d152008-04-20 20:35:01 +000088}
Chris Lattner6c2a5502008-04-20 21:13:06 +000089
Chris Lattnerfddc5022008-04-22 07:05:46 +000090/// 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
92/// the whole group.
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.
95///
96BasicBlock *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));
101
102 if (CommonPreds.size() == 1)
103 return CommonPreds[0];
104
105 DOUT << " Factoring out " << CommonPreds.size()
106 << " common predecessors.\n";
107 return SplitBlockPredecessors(PN->getParent(),
108 &CommonPreds[0], CommonPreds.size(),
109 ".thr_comm", this);
110}
111
112
Chris Lattner6c2a5502008-04-20 21:13:06 +0000113/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
114/// thread across it.
Chris Lattneree23b832008-04-20 22:39:42 +0000115static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
116 BasicBlock::const_iterator I = BB->begin();
Chris Lattner6c2a5502008-04-20 21:13:06 +0000117 /// Ignore PHI nodes, these will be flattened when duplication happens.
118 while (isa<PHINode>(*I)) ++I;
119
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.
122 unsigned Size = 0;
123 for (; !isa<TerminatorInst>(I); ++I) {
124 // Debugger intrinsics don't incur code size.
125 if (isa<DbgInfoIntrinsic>(I)) continue;
126
127 // If this is a pointer->pointer bitcast, it is free.
128 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
129 continue;
130
131 // All other instructions count for at least one unit.
132 ++Size;
133
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))
140 Size += 3;
141 else if (isa<VectorType>(CI->getType()))
142 Size += 1;
143 }
144 }
145
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;
150
151 return Size;
152}
153
154
155/// ThreadBlock - If there are any predecessors whose control can be threaded
156/// through to a successor, transform them now.
Chris Lattneree23b832008-04-20 22:39:42 +0000157bool JumpThreading::ThreadBlock(BasicBlock *BB) {
Chris Lattner6c2a5502008-04-20 21:13:06 +0000158 // 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.
161 Value *Condition;
Chris Lattneree23b832008-04-20 22:39:42 +0000162 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
163 // Can't thread an unconditional jump.
164 if (BI->isUnconditional()) return false;
Chris Lattner6c2a5502008-04-20 21:13:06 +0000165 Condition = BI->getCondition();
Chris Lattneree23b832008-04-20 22:39:42 +0000166 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner6c2a5502008-04-20 21:13:06 +0000167 Condition = SI->getCondition();
168 else
169 return false; // Must be an invoke.
Chris Lattneree23b832008-04-20 22:39:42 +0000170
171 // If the terminator of this block is branching on a constant, simplify the
Chris Lattnerb192cc82008-04-21 18:25:01 +0000172 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattneree23b832008-04-20 22:39:42 +0000173 // other blocks.
174 if (isa<ConstantInt>(Condition)) {
175 DOUT << " In block '" << BB->getNameStart()
176 << "' folding terminator: " << *BB->getTerminator();
177 ++NumFolds;
178 ConstantFoldTerminator(BB);
179 return true;
180 }
181
182 // If there is only a single predecessor of this block, nothing to fold.
183 if (BB->getSinglePredecessor())
184 return false;
Chris Lattner6c2a5502008-04-20 21:13:06 +0000185
186 // See if this is a phi node in the current block.
187 PHINode *PN = dyn_cast<PHINode>(Condition);
Chris Lattnercbc3a3e2008-04-22 06:36:15 +0000188 if (PN && PN->getParent() == BB)
189 return ProcessJumpOnPHI(PN);
Chris Lattner6c2a5502008-04-20 21:13:06 +0000190
Chris Lattnerfddc5022008-04-22 07:05:46 +0000191 // If this is a conditional branch whose condition is and/or of a phi, try to
192 // simplify it.
193 if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
194 if ((CondI->getOpcode() == Instruction::And ||
195 CondI->getOpcode() == Instruction::Or) &&
Chris Lattnerdfdff6c2008-04-22 20:46:09 +0000196 isa<BranchInst>(BB->getTerminator()) &&
197 ProcessBranchOnLogical(CondI, BB,
198 CondI->getOpcode() == Instruction::And))
199 return true;
Chris Lattnerfddc5022008-04-22 07:05:46 +0000200 }
201
Chris Lattnercbc3a3e2008-04-22 06:36:15 +0000202 return false;
203}
204
205/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
206/// the current block. See if there are any simplifications we can do based on
207/// inputs to the phi node.
208///
209bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattner0add3212008-04-20 21:18:09 +0000210 // See if the phi node has any constant values. If so, we can determine where
211 // the corresponding predecessor will branch.
212 unsigned PredNo = ~0U;
Chris Lattneree23b832008-04-20 22:39:42 +0000213 ConstantInt *PredCst = 0;
Chris Lattner0add3212008-04-20 21:18:09 +0000214 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattneree23b832008-04-20 22:39:42 +0000215 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i)))) {
Chris Lattner0add3212008-04-20 21:18:09 +0000216 PredNo = i;
217 break;
218 }
219 }
220
221 // If no incoming value has a constant, we don't know the destination of any
222 // predecessors.
223 if (PredNo == ~0U)
224 return false;
225
Chris Lattner6c2a5502008-04-20 21:13:06 +0000226 // See if the cost of duplicating this block is low enough.
Chris Lattnercbc3a3e2008-04-22 06:36:15 +0000227 BasicBlock *BB = PN->getParent();
Chris Lattner6c2a5502008-04-20 21:13:06 +0000228 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
229 if (JumpThreadCost > Threshold) {
Chris Lattneree23b832008-04-20 22:39:42 +0000230 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattner0add3212008-04-20 21:18:09 +0000231 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner6c2a5502008-04-20 21:13:06 +0000232 return false;
233 }
Chris Lattner6c2a5502008-04-20 21:13:06 +0000234
Chris Lattnerfddc5022008-04-22 07:05:46 +0000235 // If so, we can actually do this threading. Merge any common predecessors
236 // that will act the same.
237 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
238
239 // Next, figure out which successor we are threading to.
Chris Lattneree23b832008-04-20 22:39:42 +0000240 BasicBlock *SuccBB;
241 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
242 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
243 else {
244 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
245 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
246 }
247
Chris Lattnerfddc5022008-04-22 07:05:46 +0000248 // And finally, do it!
Chris Lattneree23b832008-04-20 22:39:42 +0000249 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
250 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
251 << ", across block:\n "
Chris Lattnerfddc5022008-04-22 07:05:46 +0000252 << *BB << "\n";
Chris Lattneree23b832008-04-20 22:39:42 +0000253
254 ThreadEdge(BB, PredBB, SuccBB);
255 ++NumThreads;
256 return true;
257}
258
Chris Lattnerfddc5022008-04-22 07:05:46 +0000259/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
260/// whose condition is an AND/OR where one side is PN. If PN has constant
261/// operands that permit us to evaluate the condition for some operand, thread
262/// through the block. For example with:
263/// br (and X, phi(Y, Z, false))
264/// the predecessor corresponding to the 'false' will always jump to the false
265/// destination of the branch.
266///
Chris Lattnerdfdff6c2008-04-22 20:46:09 +0000267bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
268 bool isAnd) {
269 // If this is a binary operator tree of the same AND/OR opcode, check the
270 // LHS/RHS.
271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
272 if (isAnd && BO->getOpcode() == Instruction::And ||
273 !isAnd && BO->getOpcode() == Instruction::Or) {
274 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
275 return true;
276 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
277 return true;
278 }
279
280 // If this isn't a PHI node, we can't handle it.
281 PHINode *PN = dyn_cast<PHINode>(V);
282 if (!PN || PN->getParent() != BB) return false;
283
Chris Lattnerfddc5022008-04-22 07:05:46 +0000284 // We can only do the simplification for phi nodes of 'false' with AND or
285 // 'true' with OR. See if we have any entries in the phi for this.
286 unsigned PredNo = ~0U;
287 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
288 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
289 if (PN->getIncomingValue(i) == PredCst) {
290 PredNo = i;
291 break;
292 }
293 }
294
295 // If no match, bail out.
296 if (PredNo == ~0U)
297 return false;
298
299 // See if the cost of duplicating this block is low enough.
Chris Lattnerfddc5022008-04-22 07:05:46 +0000300 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
301 if (JumpThreadCost > Threshold) {
302 DOUT << " Not threading BB '" << BB->getNameStart()
303 << "' - Cost is too high: " << JumpThreadCost << "\n";
304 return false;
305 }
306
307 // If so, we can actually do this threading. Merge any common predecessors
308 // that will act the same.
309 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
310
311 // Next, figure out which successor we are threading to. If this was an AND,
312 // the constant must be FALSE, and we must be targeting the 'false' block.
313 // If this is an OR, the constant must be TRUE, and we must be targeting the
314 // 'true' block.
315 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
316
317 // And finally, do it!
318 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
319 << "' to '" << SuccBB->getNameStart() << "' with cost: "
320 << JumpThreadCost << ", across block:\n "
321 << *BB << "\n";
322
323 ThreadEdge(BB, PredBB, SuccBB);
324 ++NumThreads;
325 return true;
326}
327
328
Chris Lattneree23b832008-04-20 22:39:42 +0000329/// ThreadEdge - We have decided that it is safe and profitable to thread an
330/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
331/// change.
332void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
333 BasicBlock *SuccBB) {
334
335 // Jump Threading can not update SSA properties correctly if the values
336 // defined in the duplicated block are used outside of the block itself. For
337 // this reason, we spill all values that are used outside of BB to the stack.
338 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
339 if (I->isUsedOutsideOfBlock(BB)) {
340 // We found a use of I outside of BB. Create a new stack slot to
341 // break this inter-block usage pattern.
342 DemoteRegToStack(*I);
343 }
344
345 // We are going to have to map operands from the original BB block to the new
346 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
347 // account for entry from PredBB.
348 DenseMap<Instruction*, Value*> ValueMapping;
349
350 BasicBlock *NewBB =
351 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
352 NewBB->moveAfter(PredBB);
353
354 BasicBlock::iterator BI = BB->begin();
355 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
356 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
357
358 // Clone the non-phi instructions of BB into NewBB, keeping track of the
359 // mapping and using it to remap operands in the cloned instructions.
360 for (; !isa<TerminatorInst>(BI); ++BI) {
361 Instruction *New = BI->clone();
362 New->setName(BI->getNameStart());
363 NewBB->getInstList().push_back(New);
364 ValueMapping[BI] = New;
365
366 // Remap operands to patch up intra-block references.
367 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
368 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
369 if (Value *Remapped = ValueMapping[Inst])
370 New->setOperand(i, Remapped);
371 }
372
373 // We didn't copy the terminator from BB over to NewBB, because there is now
374 // an unconditional jump to SuccBB. Insert the unconditional jump.
375 BranchInst::Create(SuccBB, NewBB);
376
377 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
378 // PHI nodes for NewBB now.
379 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
380 PHINode *PN = cast<PHINode>(PNI);
381 // Ok, we have a PHI node. Figure out what the incoming value was for the
382 // DestBlock.
383 Value *IV = PN->getIncomingValueForBlock(BB);
384
385 // Remap the value if necessary.
386 if (Instruction *Inst = dyn_cast<Instruction>(IV))
387 if (Value *MappedIV = ValueMapping[Inst])
388 IV = MappedIV;
389 PN->addIncoming(IV, NewBB);
390 }
391
392 // Finally, NewBB is good to go. Update the terminator of PredBB to jump to
393 // NewBB instead of BB. This eliminates predecessors from BB, which requires
394 // us to simplify any PHI nodes in BB.
395 TerminatorInst *PredTerm = PredBB->getTerminator();
396 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
397 if (PredTerm->getSuccessor(i) == BB) {
398 BB->removePredecessor(PredBB);
399 PredTerm->setSuccessor(i, NewBB);
400 }
Chris Lattner6c2a5502008-04-20 21:13:06 +0000401}