blob: f134946019ceadff0fd69ec0149601c4b4c1aca3 [file] [log] [blame]
Chris Lattner8383a7b2008-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 Lattner177480b2008-04-20 21:13:06 +000010// This file implements the Jump Threading pass.
Chris Lattner8383a7b2008-04-20 20:35:01 +000011//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "jump-threading"
15#include "llvm/Transforms/Scalar.h"
Chris Lattner177480b2008-04-20 21:13:06 +000016#include "llvm/IntrinsicInst.h"
Owen Anderson1ff50b32009-07-03 00:54:20 +000017#include "llvm/LLVMContext.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000018#include "llvm/Pass.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000019#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattner433a0db2009-10-10 09:05:58 +000022#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000023#include "llvm/Target/TargetData.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000024#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 Lattner8383a7b2008-04-20 20:35:01 +000029#include "llvm/Support/CommandLine.h"
Chris Lattner177480b2008-04-20 21:13:06 +000030#include "llvm/Support/Debug.h"
Daniel Dunbar93b67e42009-07-26 07:49:05 +000031#include "llvm/Support/raw_ostream.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000032using namespace llvm;
33
Chris Lattnerbd3401f2008-04-20 22:39:42 +000034STATISTIC(NumThreads, "Number of jumps threaded");
35STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner78c552e2009-10-11 07:24:57 +000036STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
Chris Lattner8383a7b2008-04-20 20:35:01 +000037
Chris Lattner177480b2008-04-20 21:13:06 +000038static cl::opt<unsigned>
39Threshold("jump-threading-threshold",
40 cl::desc("Max block size to duplicate for jump threading"),
41 cl::init(6), cl::Hidden);
42
Chris Lattner8383a7b2008-04-20 20:35:01 +000043namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000044 /// 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 Lattner3e8b6632009-09-02 06:11:42 +000060 class JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000061 TargetData *TD;
Mike Stumpfe095f32009-05-04 18:40:41 +000062#ifdef NDEBUG
63 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
64#else
65 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
66#endif
Chris Lattner8383a7b2008-04-20 20:35:01 +000067 public:
68 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000069 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000070
71 bool runOnFunction(Function &F);
Mike Stumpfe095f32009-05-04 18:40:41 +000072 void FindLoopHeaders(Function &F);
73
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000074 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbdbf1a12009-10-11 04:33:43 +000075 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner78c552e2009-10-11 07:24:57 +000076 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
77 BasicBlock *PredBB);
78
Nick Lewycky9683f182009-06-19 04:56:29 +000079 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val);
Chris Lattner421fa9e2008-12-03 07:48:08 +000080 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner3cda3cd2008-12-04 06:31:07 +000081 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000082
Chris Lattnerd38c14e2008-04-22 06:36:15 +000083 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerae65b3c2008-04-22 20:46:09 +000084 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattnera5ddb592008-04-22 21:40:39 +000085 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner69e067f2008-11-27 05:07:53 +000086
87 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000088 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000089}
90
Dan Gohman844731a2008-05-13 00:00:25 +000091char JumpThreading::ID = 0;
92static RegisterPass<JumpThreading>
93X("jump-threading", "Jump Threading");
94
Chris Lattner8383a7b2008-04-20 20:35:01 +000095// Public interface to the Jump Threading pass
96FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
97
98/// runOnFunction - Top level algorithm.
99///
100bool JumpThreading::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000101 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000102 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000103
Mike Stumpfe095f32009-05-04 18:40:41 +0000104 FindLoopHeaders(F);
105
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000106 bool AnotherIteration = true, EverChanged = false;
107 while (AnotherIteration) {
108 AnotherIteration = false;
109 bool Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000110 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
111 BasicBlock *BB = I;
112 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000113 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000114
115 ++I;
116
117 // If the block is trivially dead, zap it. This eliminates the successor
118 // edges which simplifies the CFG.
119 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000120 BB != &BB->getParent()->getEntryBlock()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000121 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000122 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000123 LoopHeaders.erase(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000124 DeleteDeadBlock(BB);
125 Changed = true;
126 }
127 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000128 AnotherIteration = Changed;
129 EverChanged |= Changed;
130 }
Mike Stumpfe095f32009-05-04 18:40:41 +0000131
132 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000133 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000134}
Chris Lattner177480b2008-04-20 21:13:06 +0000135
Chris Lattner78c552e2009-10-11 07:24:57 +0000136/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
137/// thread across it.
138static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
139 /// Ignore PHI nodes, these will be flattened when duplication happens.
140 BasicBlock::const_iterator I = BB->getFirstNonPHI();
141
142 // Sum up the cost of each instruction until we get to the terminator. Don't
143 // include the terminator because the copy won't include it.
144 unsigned Size = 0;
145 for (; !isa<TerminatorInst>(I); ++I) {
146 // Debugger intrinsics don't incur code size.
147 if (isa<DbgInfoIntrinsic>(I)) continue;
148
149 // If this is a pointer->pointer bitcast, it is free.
150 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
151 continue;
152
153 // All other instructions count for at least one unit.
154 ++Size;
155
156 // Calls are more expensive. If they are non-intrinsic calls, we model them
157 // as having cost of 4. If they are a non-vector intrinsic, we model them
158 // as having cost of 2 total, and if they are a vector intrinsic, we model
159 // them as having cost 1.
160 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
161 if (!isa<IntrinsicInst>(CI))
162 Size += 3;
163 else if (!isa<VectorType>(CI->getType()))
164 Size += 1;
165 }
166 }
167
168 // Threading through a switch statement is particularly profitable. If this
169 // block ends in a switch, decrease its cost to make it more likely to happen.
170 if (isa<SwitchInst>(I))
171 Size = Size > 6 ? Size-6 : 0;
172
173 return Size;
174}
175
176
177
Mike Stumpfe095f32009-05-04 18:40:41 +0000178/// FindLoopHeaders - We do not want jump threading to turn proper loop
179/// structures into irreducible loops. Doing this breaks up the loop nesting
180/// hierarchy and pessimizes later transformations. To prevent this from
181/// happening, we first have to find the loop headers. Here we approximate this
182/// by finding targets of backedges in the CFG.
183///
184/// Note that there definitely are cases when we want to allow threading of
185/// edges across a loop header. For example, threading a jump from outside the
186/// loop (the preheader) to an exit block of the loop is definitely profitable.
187/// It is also almost always profitable to thread backedges from within the loop
188/// to exit blocks, and is often profitable to thread backedges to other blocks
189/// within the loop (forming a nested loop). This simple analysis is not rich
190/// enough to track all of these properties and keep it up-to-date as the CFG
191/// mutates, so we don't allow any of these transformations.
192///
193void JumpThreading::FindLoopHeaders(Function &F) {
194 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
195 FindFunctionBackedges(F, Edges);
196
197 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
198 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
199}
200
201
Chris Lattner6bf77502008-04-22 07:05:46 +0000202/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
203/// value for the PHI, factor them together so we get one block to thread for
204/// the whole group.
205/// This is important for things like "phi i1 [true, true, false, true, x]"
206/// where we only need to clone the block for the true blocks once.
207///
Nick Lewycky9683f182009-06-19 04:56:29 +0000208BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
Chris Lattner6bf77502008-04-22 07:05:46 +0000209 SmallVector<BasicBlock*, 16> CommonPreds;
210 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Nick Lewycky9683f182009-06-19 04:56:29 +0000211 if (PN->getIncomingValue(i) == Val)
Chris Lattner6bf77502008-04-22 07:05:46 +0000212 CommonPreds.push_back(PN->getIncomingBlock(i));
213
214 if (CommonPreds.size() == 1)
215 return CommonPreds[0];
216
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000217 DEBUG(errs() << " Factoring out " << CommonPreds.size()
218 << " common predecessors.\n");
Chris Lattner6bf77502008-04-22 07:05:46 +0000219 return SplitBlockPredecessors(PN->getParent(),
220 &CommonPreds[0], CommonPreds.size(),
221 ".thr_comm", this);
222}
223
224
Chris Lattnere33583b2009-10-11 04:18:15 +0000225/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
226/// in an undefined jump, decide which block is best to revector to.
227///
228/// Since we can pick an arbitrary destination, we pick the successor with the
229/// fewest predecessors. This should reduce the in-degree of the others.
230///
231static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
232 TerminatorInst *BBTerm = BB->getTerminator();
233 unsigned MinSucc = 0;
234 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
235 // Compute the successor with the minimum number of predecessors.
236 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
237 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
238 TestBB = BBTerm->getSuccessor(i);
239 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
240 if (NumPreds < MinNumPreds)
241 MinSucc = i;
242 }
243
244 return MinSucc;
245}
246
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000247/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000248/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000249bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000250 // If this block has a single predecessor, and if that pred has a single
251 // successor, merge the blocks. This encourages recursive jump threading
252 // because now the condition in this block can be threaded through
253 // predecessors of our predecessor block.
254 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
Chris Lattnerf5102a02008-11-28 19:54:49 +0000255 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
256 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000257 // If SinglePred was a loop header, BB becomes one.
258 if (LoopHeaders.erase(SinglePred))
259 LoopHeaders.insert(BB);
260
Chris Lattner3d86d242008-11-27 19:25:19 +0000261 // Remember if SinglePred was the entry block of the function. If so, we
262 // will need to move BB back to the entry position.
263 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000264 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000265
266 if (isEntry && BB != &BB->getParent()->getEntryBlock())
267 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000268 return true;
269 }
270
Matthijs Kooijman6e7b3222008-05-20 07:26:45 +0000271 // See if this block ends with a branch or switch. If so, see if the
Chris Lattner177480b2008-04-20 21:13:06 +0000272 // condition is a phi node. If so, and if an entry of the phi node is a
273 // constant, we can thread the block.
274 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000275 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
276 // Can't thread an unconditional jump.
277 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000278 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000279 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000280 Condition = SI->getCondition();
281 else
282 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000283
284 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000285 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000286 // other blocks.
287 if (isa<ConstantInt>(Condition)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000288 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000289 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000290 ++NumFolds;
291 ConstantFoldTerminator(BB);
292 return true;
293 }
294
Chris Lattner421fa9e2008-12-03 07:48:08 +0000295 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000296 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000297 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000298 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000299
300 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000301 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000302 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000303 if (i == BestSucc) continue;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000304 BBTerm->getSuccessor(i)->removePredecessor(BB);
305 }
306
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000307 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000308 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000309 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000310 BBTerm->eraseFromParent();
311 return true;
312 }
313
314 Instruction *CondInst = dyn_cast<Instruction>(Condition);
315
316 // If the condition is an instruction defined in another block, see if a
317 // predecessor has the same condition:
318 // br COND, BBX, BBY
319 // BBX:
320 // br COND, BBZ, BBW
321 if (!Condition->hasOneUse() && // Multiple uses.
322 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
323 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
324 if (isa<BranchInst>(BB->getTerminator())) {
325 for (; PI != E; ++PI)
326 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
327 if (PBI->isConditional() && PBI->getCondition() == Condition &&
328 ProcessBranchOnDuplicateCond(*PI, BB))
329 return true;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000330 } else {
331 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
332 for (; PI != E; ++PI)
333 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
334 if (PSI->getCondition() == Condition &&
335 ProcessSwitchOnDuplicateCond(*PI, BB))
336 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000337 }
338 }
339
Chris Lattner421fa9e2008-12-03 07:48:08 +0000340 // All the rest of our checks depend on the condition being an instruction.
341 if (CondInst == 0)
342 return false;
343
Chris Lattner177480b2008-04-20 21:13:06 +0000344 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000345 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
346 if (PN->getParent() == BB)
347 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000348
Chris Lattner6bf77502008-04-22 07:05:46 +0000349 // If this is a conditional branch whose condition is and/or of a phi, try to
350 // simplify it.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000351 if ((CondInst->getOpcode() == Instruction::And ||
352 CondInst->getOpcode() == Instruction::Or) &&
353 isa<BranchInst>(BB->getTerminator()) &&
354 ProcessBranchOnLogical(CondInst, BB,
355 CondInst->getOpcode() == Instruction::And))
356 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000357
Nick Lewycky9683f182009-06-19 04:56:29 +0000358 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
359 if (isa<PHINode>(CondCmp->getOperand(0))) {
360 // If we have "br (phi != 42)" and the phi node has any constant values
361 // as operands, we can thread through this block.
362 //
363 // If we have "br (cmp phi, x)" and the phi node contains x such that the
364 // comparison uniquely identifies the branch target, we can thread
365 // through this block.
366
367 if (ProcessBranchOnCompare(CondCmp, BB))
368 return true;
369 }
Chris Lattner79c740f2009-06-19 16:27:56 +0000370
371 // If we have a comparison, loop over the predecessors to see if there is
372 // a condition with the same value.
373 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
374 for (; PI != E; ++PI)
375 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
376 if (PBI->isConditional() && *PI != BB) {
377 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
378 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
379 CI->getOperand(1) == CondCmp->getOperand(1) &&
380 CI->getPredicate() == CondCmp->getPredicate()) {
381 // TODO: Could handle things like (x != 4) --> (x == 17)
382 if (ProcessBranchOnDuplicateCond(*PI, BB))
383 return true;
384 }
385 }
386 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000387 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000388
389 // Check for some cases that are worth simplifying. Right now we want to look
390 // for loads that are used by a switch or by the condition for the branch. If
391 // we see one, check to see if it's partially redundant. If so, insert a PHI
392 // which can then be used to thread the values.
393 //
394 // This is particularly important because reg2mem inserts loads and stores all
395 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000396 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000397 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
398 if (isa<Constant>(CondCmp->getOperand(1)))
399 SimplifyValue = CondCmp->getOperand(0);
400
401 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
402 if (SimplifyPartiallyRedundantLoad(LI))
403 return true;
404
405 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
406 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000407
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000408 return false;
409}
410
Chris Lattner421fa9e2008-12-03 07:48:08 +0000411/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
412/// block that jump on exactly the same condition. This means that we almost
413/// always know the direction of the edge in the DESTBB:
414/// PREDBB:
415/// br COND, DESTBB, BBY
416/// DESTBB:
417/// br COND, BBZ, BBW
418///
419/// If DESTBB has multiple predecessors, we can't just constant fold the branch
420/// in DESTBB, we have to thread over it.
421bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
422 BasicBlock *BB) {
423 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
424
425 // If both successors of PredBB go to DESTBB, we don't know anything. We can
426 // fold the branch to an unconditional one, which allows other recursive
427 // simplifications.
428 bool BranchDir;
429 if (PredBI->getSuccessor(1) != BB)
430 BranchDir = true;
431 else if (PredBI->getSuccessor(0) != BB)
432 BranchDir = false;
433 else {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000434 DEBUG(errs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000435 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000436 ++NumFolds;
437 ConstantFoldTerminator(PredBB);
438 return true;
439 }
440
441 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
442
443 // If the dest block has one predecessor, just fix the branch condition to a
444 // constant and fold it.
445 if (BB->getSinglePredecessor()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000446 DEBUG(errs() << " In block '" << BB->getName()
447 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000448 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000449 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000450 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000451 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
452 BranchDir));
Chris Lattner421fa9e2008-12-03 07:48:08 +0000453 ConstantFoldTerminator(BB);
Chris Lattner5a06cf62009-10-11 18:39:58 +0000454 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000455 return true;
456 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000457
Chris Lattner421fa9e2008-12-03 07:48:08 +0000458
459 // Next, figure out which successor we are threading to.
460 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
461
Mike Stumpfe095f32009-05-04 18:40:41 +0000462 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000463 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000464}
465
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000466/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
467/// block that switch on exactly the same condition. This means that we almost
468/// always know the direction of the edge in the DESTBB:
469/// PREDBB:
470/// switch COND [... DESTBB, BBY ... ]
471/// DESTBB:
472/// switch COND [... BBZ, BBW ]
473///
474/// Optimizing switches like this is very important, because simplifycfg builds
475/// switches out of repeated 'if' conditions.
476bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
477 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000478 // Can't thread edge to self.
479 if (PredBB == DestBB)
480 return false;
481
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000482 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
483 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
484
485 // There are a variety of optimizations that we can potentially do on these
486 // blocks: we order them from most to least preferable.
487
488 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
489 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000490 // growth. Skip debug info first.
491 BasicBlock::iterator BBI = DestBB->begin();
492 while (isa<DbgInfoIntrinsic>(BBI))
493 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000494
495 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000496 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000497 bool MadeChange = false;
498 // Ignore the default edge for now.
499 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
500 ConstantInt *DestVal = DestSI->getCaseValue(i);
501 BasicBlock *DestSucc = DestSI->getSuccessor(i);
502
503 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
504 // PredSI has an explicit case for it. If so, forward. If it is covered
505 // by the default case, we can't update PredSI.
506 unsigned PredCase = PredSI->findCaseValue(DestVal);
507 if (PredCase == 0) continue;
508
509 // If PredSI doesn't go to DestBB on this value, then it won't reach the
510 // case on this condition.
511 if (PredSI->getSuccessor(PredCase) != DestBB &&
512 DestSI->getSuccessor(i) != DestBB)
513 continue;
514
515 // Otherwise, we're safe to make the change. Make sure that the edge from
516 // DestSI to DestSucc is not critical and has no PHI nodes.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000517 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
518 DEBUG(errs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000519
520 // If the destination has PHI nodes, just split the edge for updating
521 // simplicity.
522 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
523 SplitCriticalEdge(DestSI, i, this);
524 DestSucc = DestSI->getSuccessor(i);
525 }
526 FoldSingleEntryPHINodes(DestSucc);
527 PredSI->setSuccessor(PredCase, DestSucc);
528 MadeChange = true;
529 }
530
531 if (MadeChange)
532 return true;
533 }
534
535 return false;
536}
537
538
Chris Lattner69e067f2008-11-27 05:07:53 +0000539/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
540/// load instruction, eliminate it by replacing it with a PHI node. This is an
541/// important optimization that encourages jump threading, and needs to be run
542/// interlaced with other jump threading tasks.
543bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
544 // Don't hack volatile loads.
545 if (LI->isVolatile()) return false;
546
547 // If the load is defined in a block with exactly one predecessor, it can't be
548 // partially redundant.
549 BasicBlock *LoadBB = LI->getParent();
550 if (LoadBB->getSinglePredecessor())
551 return false;
552
553 Value *LoadedPtr = LI->getOperand(0);
554
555 // If the loaded operand is defined in the LoadBB, it can't be available.
556 // FIXME: Could do PHI translation, that would be fun :)
557 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
558 if (PtrOp->getParent() == LoadBB)
559 return false;
560
561 // Scan a few instructions up from the load, to see if it is obviously live at
562 // the entry to its block.
563 BasicBlock::iterator BBIt = LI;
564
Chris Lattner52c95852008-11-27 08:10:05 +0000565 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
566 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000567 // If the value if the load is locally available within the block, just use
568 // it. This frequently occurs for reg2mem'd allocas.
569 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000570
571 // If the returned value is the load itself, replace with an undef. This can
572 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000573 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000574 LI->replaceAllUsesWith(AvailableVal);
575 LI->eraseFromParent();
576 return true;
577 }
578
579 // Otherwise, if we scanned the whole block and got to the top of the block,
580 // we know the block is locally transparent to the load. If not, something
581 // might clobber its value.
582 if (BBIt != LoadBB->begin())
583 return false;
584
585
586 SmallPtrSet<BasicBlock*, 8> PredsScanned;
587 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
588 AvailablePredsTy AvailablePreds;
589 BasicBlock *OneUnavailablePred = 0;
590
591 // If we got here, the loaded value is transparent through to the start of the
592 // block. Check to see if it is available in any of the predecessor blocks.
593 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
594 PI != PE; ++PI) {
595 BasicBlock *PredBB = *PI;
596
597 // If we already scanned this predecessor, skip it.
598 if (!PredsScanned.insert(PredBB))
599 continue;
600
601 // Scan the predecessor to see if the value is available in the pred.
602 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000603 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000604 if (!PredAvailable) {
605 OneUnavailablePred = PredBB;
606 continue;
607 }
608
609 // If so, this load is partially redundant. Remember this info so that we
610 // can create a PHI node.
611 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
612 }
613
614 // If the loaded value isn't available in any predecessor, it isn't partially
615 // redundant.
616 if (AvailablePreds.empty()) return false;
617
618 // Okay, the loaded value is available in at least one (and maybe all!)
619 // predecessors. If the value is unavailable in more than one unique
620 // predecessor, we want to insert a merge block for those common predecessors.
621 // This ensures that we only have to insert one reload, thus not increasing
622 // code size.
623 BasicBlock *UnavailablePred = 0;
624
625 // If there is exactly one predecessor where the value is unavailable, the
626 // already computed 'OneUnavailablePred' block is it. If it ends in an
627 // unconditional branch, we know that it isn't a critical edge.
628 if (PredsScanned.size() == AvailablePreds.size()+1 &&
629 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
630 UnavailablePred = OneUnavailablePred;
631 } else if (PredsScanned.size() != AvailablePreds.size()) {
632 // Otherwise, we had multiple unavailable predecessors or we had a critical
633 // edge from the one.
634 SmallVector<BasicBlock*, 8> PredsToSplit;
635 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
636
637 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
638 AvailablePredSet.insert(AvailablePreds[i].first);
639
640 // Add all the unavailable predecessors to the PredsToSplit list.
641 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
642 PI != PE; ++PI)
643 if (!AvailablePredSet.count(*PI))
644 PredsToSplit.push_back(*PI);
645
646 // Split them out to their own block.
647 UnavailablePred =
648 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
649 "thread-split", this);
650 }
651
652 // If the value isn't available in all predecessors, then there will be
653 // exactly one where it isn't available. Insert a load on that edge and add
654 // it to the AvailablePreds list.
655 if (UnavailablePred) {
656 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
657 "Can't handle critical edge here!");
658 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
659 UnavailablePred->getTerminator());
660 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
661 }
662
663 // Now we know that each predecessor of this block has a value in
664 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000665 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000666
667 // Create a PHI node at the start of the block for the PRE'd load value.
668 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
669 PN->takeName(LI);
670
671 // Insert new entries into the PHI for each predecessor. A single block may
672 // have multiple entries here.
673 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
674 ++PI) {
675 AvailablePredsTy::iterator I =
676 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
677 std::make_pair(*PI, (Value*)0));
678
679 assert(I != AvailablePreds.end() && I->first == *PI &&
680 "Didn't find entry for predecessor!");
681
682 PN->addIncoming(I->second, I->first);
683 }
684
685 //cerr << "PRE: " << *LI << *PN << "\n";
686
687 LI->replaceAllUsesWith(PN);
688 LI->eraseFromParent();
689
690 return true;
691}
692
693
Chris Lattnere33583b2009-10-11 04:18:15 +0000694/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000695/// the current block. See if there are any simplifications we can do based on
696/// inputs to the phi node.
697///
698bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000699 BasicBlock *BB = PN->getParent();
700
Chris Lattnere33583b2009-10-11 04:18:15 +0000701 // See if the phi node has any constant integer or undef values. If so, we
702 // can determine where the corresponding predecessor will branch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000703 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
704 Value *PredVal = PN->getIncomingValue(i);
Chris Lattner6b65f472009-10-11 04:40:21 +0000705
706 // Check to see if this input is a constant integer. If so, the direction
707 // of the branch is predictable.
Chris Lattnere33583b2009-10-11 04:18:15 +0000708 if (ConstantInt *CI = dyn_cast<ConstantInt>(PredVal)) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000709 // Merge any common predecessors that will act the same.
710 BasicBlock *PredBB = FactorCommonPHIPreds(PN, CI);
711
712 BasicBlock *SuccBB;
713 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
714 SuccBB = BI->getSuccessor(CI->isZero());
715 else {
716 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
717 SuccBB = SI->getSuccessor(SI->findCaseValue(CI));
718 }
719
720 // Ok, try to thread it!
721 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattnere33583b2009-10-11 04:18:15 +0000722 }
723
Chris Lattner6b65f472009-10-11 04:40:21 +0000724 // If the input is an undef, then it doesn't matter which way it will go.
725 // Pick an arbitrary dest and thread the edge.
Chris Lattnere33583b2009-10-11 04:18:15 +0000726 if (UndefValue *UV = dyn_cast<UndefValue>(PredVal)) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000727 // Merge any common predecessors that will act the same.
728 BasicBlock *PredBB = FactorCommonPHIPreds(PN, UV);
729 BasicBlock *SuccBB =
730 BB->getTerminator()->getSuccessor(GetBestDestForJumpOnUndef(BB));
731
732 // Ok, try to thread it!
733 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattnere33583b2009-10-11 04:18:15 +0000734 }
Chris Lattner6b65f472009-10-11 04:40:21 +0000735 }
Chris Lattnerf9065a92008-04-20 21:18:09 +0000736
Chris Lattner78c552e2009-10-11 07:24:57 +0000737 // If the incoming values are all variables, we don't know the destination of
738 // any predecessors. However, if any of the predecessor blocks end in an
739 // unconditional branch, we can *duplicate* the jump into that block in order
740 // to further encourage jump threading and to eliminate cases where we have
741 // branch on a phi of an icmp (branch on icmp is much better).
742
743 // We don't want to do this tranformation for switches, because we don't
744 // really want to duplicate a switch.
745 if (isa<SwitchInst>(BB->getTerminator()))
746 return false;
747
748 // Look for unconditional branch predecessors.
749 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
750 BasicBlock *PredBB = PN->getIncomingBlock(i);
751 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
752 if (PredBr->isUnconditional() &&
753 // Try to duplicate BB into PredBB.
754 DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
755 return true;
756 }
757
Chris Lattner6b65f472009-10-11 04:40:21 +0000758 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000759}
760
Chris Lattner78c552e2009-10-11 07:24:57 +0000761
Chris Lattner6bf77502008-04-22 07:05:46 +0000762/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
763/// whose condition is an AND/OR where one side is PN. If PN has constant
764/// operands that permit us to evaluate the condition for some operand, thread
765/// through the block. For example with:
766/// br (and X, phi(Y, Z, false))
767/// the predecessor corresponding to the 'false' will always jump to the false
768/// destination of the branch.
769///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000770bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
771 bool isAnd) {
772 // If this is a binary operator tree of the same AND/OR opcode, check the
773 // LHS/RHS.
774 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
Duncan Sands43e2a032008-05-27 11:50:51 +0000775 if ((isAnd && BO->getOpcode() == Instruction::And) ||
776 (!isAnd && BO->getOpcode() == Instruction::Or)) {
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000777 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
778 return true;
779 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
780 return true;
781 }
782
783 // If this isn't a PHI node, we can't handle it.
784 PHINode *PN = dyn_cast<PHINode>(V);
785 if (!PN || PN->getParent() != BB) return false;
786
Chris Lattner6bf77502008-04-22 07:05:46 +0000787 // We can only do the simplification for phi nodes of 'false' with AND or
788 // 'true' with OR. See if we have any entries in the phi for this.
789 unsigned PredNo = ~0U;
Owen Anderson1d0be152009-08-13 21:58:54 +0000790 ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()),
791 !isAnd);
Chris Lattner6bf77502008-04-22 07:05:46 +0000792 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
793 if (PN->getIncomingValue(i) == PredCst) {
794 PredNo = i;
795 break;
796 }
797 }
798
799 // If no match, bail out.
800 if (PredNo == ~0U)
801 return false;
802
Chris Lattner6bf77502008-04-22 07:05:46 +0000803 // If so, we can actually do this threading. Merge any common predecessors
804 // that will act the same.
805 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
806
807 // Next, figure out which successor we are threading to. If this was an AND,
808 // the constant must be FALSE, and we must be targeting the 'false' block.
809 // If this is an OR, the constant must be TRUE, and we must be targeting the
810 // 'true' block.
811 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
812
Mike Stumpfe095f32009-05-04 18:40:41 +0000813 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000814 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattner6bf77502008-04-22 07:05:46 +0000815}
816
Nick Lewycky9683f182009-06-19 04:56:29 +0000817/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
818/// hand sides of the compare instruction, try to determine the result. If the
819/// result can not be determined, a null pointer is returned.
820static Constant *GetResultOfComparison(CmpInst::Predicate pred,
Owen Anderson1ff50b32009-07-03 00:54:20 +0000821 Value *LHS, Value *RHS,
Owen Andersone922c022009-07-22 00:24:57 +0000822 LLVMContext &Context) {
Nick Lewycky9683f182009-06-19 04:56:29 +0000823 if (Constant *CLHS = dyn_cast<Constant>(LHS))
824 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000825 return ConstantExpr::getCompare(pred, CLHS, CRHS);
Nick Lewycky9683f182009-06-19 04:56:29 +0000826
827 if (LHS == RHS)
828 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
829 return ICmpInst::isTrueWhenEqual(pred) ?
Owen Anderson5defacc2009-07-31 17:39:07 +0000830 ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context);
Nick Lewycky9683f182009-06-19 04:56:29 +0000831
832 return 0;
833}
834
Chris Lattnera5ddb592008-04-22 21:40:39 +0000835/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
Nick Lewycky9683f182009-06-19 04:56:29 +0000836/// node and a value. If we can identify when the comparison is true between
837/// the phi inputs and the value, we can fold the compare for that edge and
838/// thread through it.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000839bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
840 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
Nick Lewycky9683f182009-06-19 04:56:29 +0000841 Value *RHS = Cmp->getOperand(1);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000842
843 // If the phi isn't in the current block, an incoming edge to this block
844 // doesn't control the destination.
845 if (PN->getParent() != BB)
846 return false;
847
848 // We can do this simplification if any comparisons fold to true or false.
849 // See if any do.
Nick Lewycky9683f182009-06-19 04:56:29 +0000850 Value *PredVal = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000851 bool TrueDirection = false;
852 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Nick Lewycky9683f182009-06-19 04:56:29 +0000853 PredVal = PN->getIncomingValue(i);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000854
Owen Anderson1ff50b32009-07-03 00:54:20 +0000855 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal,
Owen Andersone922c022009-07-22 00:24:57 +0000856 RHS, Cmp->getContext());
Nick Lewycky9683f182009-06-19 04:56:29 +0000857 if (!Res) {
858 PredVal = 0;
859 continue;
860 }
861
Chris Lattnera5ddb592008-04-22 21:40:39 +0000862 // If this folded to a constant expr, we can't do anything.
863 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
864 TrueDirection = ResC->getZExtValue();
865 break;
866 }
867 // If this folded to undef, just go the false way.
868 if (isa<UndefValue>(Res)) {
869 TrueDirection = false;
870 break;
871 }
872
873 // Otherwise, we can't fold this input.
Nick Lewycky9683f182009-06-19 04:56:29 +0000874 PredVal = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000875 }
876
877 // If no match, bail out.
Nick Lewycky9683f182009-06-19 04:56:29 +0000878 if (PredVal == 0)
Chris Lattnera5ddb592008-04-22 21:40:39 +0000879 return false;
880
Chris Lattnera5ddb592008-04-22 21:40:39 +0000881 // If so, we can actually do this threading. Merge any common predecessors
882 // that will act the same.
Nick Lewycky9683f182009-06-19 04:56:29 +0000883 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000884
885 // Next, get our successor.
886 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
887
Mike Stumpfe095f32009-05-04 18:40:41 +0000888 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000889 return ThreadEdge(BB, PredBB, SuccBB);
890}
891
Chris Lattnera5ddb592008-04-22 21:40:39 +0000892
Chris Lattner78c552e2009-10-11 07:24:57 +0000893/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
894/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
895/// NewPred using the entries from OldPred (suitably mapped).
896static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
897 BasicBlock *OldPred,
898 BasicBlock *NewPred,
899 DenseMap<Instruction*, Value*> &ValueMap) {
900 for (BasicBlock::iterator PNI = PHIBB->begin();
901 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
902 // Ok, we have a PHI node. Figure out what the incoming value was for the
903 // DestBlock.
904 Value *IV = PN->getIncomingValueForBlock(OldPred);
905
906 // Remap the value if necessary.
907 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
908 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
909 if (I != ValueMap.end())
910 IV = I->second;
911 }
912
913 PN->addIncoming(IV, NewPred);
914 }
915}
Chris Lattner6bf77502008-04-22 07:05:46 +0000916
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000917/// ThreadEdge - We have decided that it is safe and profitable to thread an
918/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
919/// change.
Mike Stumpfe095f32009-05-04 18:40:41 +0000920bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000921 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000922 // If threading to the same block as we come from, we would infinite loop.
923 if (SuccBB == BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000924 DEBUG(errs() << " Not threading across BB '" << BB->getName()
925 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000926 return false;
927 }
928
929 // If threading this would thread across a loop header, don't thread the edge.
930 // See the comments above FindLoopHeaders for justifications and caveats.
931 if (LoopHeaders.count(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000932 DEBUG(errs() << " Not threading from '" << PredBB->getName()
933 << "' across loop header BB '" << BB->getName()
934 << "' to dest BB '" << SuccBB->getName()
935 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000936 return false;
937 }
938
Chris Lattner78c552e2009-10-11 07:24:57 +0000939 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
940 if (JumpThreadCost > Threshold) {
941 DEBUG(errs() << " Not threading BB '" << BB->getName()
942 << "' - Cost is too high: " << JumpThreadCost << "\n");
943 return false;
944 }
945
Mike Stumpfe095f32009-05-04 18:40:41 +0000946 // And finally, do it!
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000947 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +0000948 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000949 << ", across block:\n "
950 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000951
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000952 // We are going to have to map operands from the original BB block to the new
953 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
954 // account for entry from PredBB.
955 DenseMap<Instruction*, Value*> ValueMapping;
956
Owen Anderson1d0be152009-08-13 21:58:54 +0000957 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
958 BB->getName()+".thread",
959 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000960 NewBB->moveAfter(PredBB);
961
962 BasicBlock::iterator BI = BB->begin();
963 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
964 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
965
966 // Clone the non-phi instructions of BB into NewBB, keeping track of the
967 // mapping and using it to remap operands in the cloned instructions.
968 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +0000969 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +0000970 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000971 NewBB->getInstList().push_back(New);
972 ValueMapping[BI] = New;
973
974 // Remap operands to patch up intra-block references.
975 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +0000976 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
977 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
978 if (I != ValueMapping.end())
979 New->setOperand(i, I->second);
980 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000981 }
982
983 // We didn't copy the terminator from BB over to NewBB, because there is now
984 // an unconditional jump to SuccBB. Insert the unconditional jump.
985 BranchInst::Create(SuccBB, NewBB);
986
987 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
988 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +0000989 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000990
Chris Lattner433a0db2009-10-10 09:05:58 +0000991 // If there were values defined in BB that are used outside the block, then we
992 // now have to update all uses of the value to use either the original value,
993 // the cloned value, or some PHI derived value. This can require arbitrary
994 // PHI insertion, of which we are prepared to do, clean these up now.
995 SSAUpdater SSAUpdate;
996 SmallVector<Use*, 16> UsesToRename;
997 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
998 // Scan all uses of this instruction to see if it is used outside of its
999 // block, and if so, record them in UsesToRename.
1000 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1001 ++UI) {
1002 Instruction *User = cast<Instruction>(*UI);
1003 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1004 if (UserPN->getIncomingBlock(UI) == BB)
1005 continue;
1006 } else if (User->getParent() == BB)
1007 continue;
1008
1009 UsesToRename.push_back(&UI.getUse());
1010 }
1011
1012 // If there are no uses outside the block, we're done with this instruction.
1013 if (UsesToRename.empty())
1014 continue;
1015
1016 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1017
1018 // We found a use of I outside of BB. Rename all uses of I that are outside
1019 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1020 // with the two values we know.
1021 SSAUpdate.Initialize(I);
1022 SSAUpdate.AddAvailableValue(BB, I);
1023 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1024
1025 while (!UsesToRename.empty())
1026 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1027 DEBUG(errs() << "\n");
1028 }
1029
1030
Chris Lattneref0c6742008-12-01 04:48:07 +00001031 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001032 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1033 // us to simplify any PHI nodes in BB.
1034 TerminatorInst *PredTerm = PredBB->getTerminator();
1035 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1036 if (PredTerm->getSuccessor(i) == BB) {
1037 BB->removePredecessor(PredBB);
1038 PredTerm->setSuccessor(i, NewBB);
1039 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001040
1041 // At this point, the IR is fully up to date and consistent. Do a quick scan
1042 // over the new instructions and zap any that are constants or dead. This
1043 // frequently happens because of phi translation.
1044 BI = NewBB->begin();
1045 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1046 Instruction *Inst = BI++;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001047 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneref0c6742008-12-01 04:48:07 +00001048 Inst->replaceAllUsesWith(C);
1049 Inst->eraseFromParent();
1050 continue;
1051 }
1052
1053 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1054 }
Mike Stumpfe095f32009-05-04 18:40:41 +00001055
1056 // Threaded an edge!
1057 ++NumThreads;
1058 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001059}
Chris Lattner78c552e2009-10-11 07:24:57 +00001060
1061/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1062/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1063/// If we can duplicate the contents of BB up into PredBB do so now, this
1064/// improves the odds that the branch will be on an analyzable instruction like
1065/// a compare.
1066bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1067 BasicBlock *PredBB) {
1068 // If BB is a loop header, then duplicating this block outside the loop would
1069 // cause us to transform this into an irreducible loop, don't do this.
1070 // See the comments above FindLoopHeaders for justifications and caveats.
1071 if (LoopHeaders.count(BB)) {
1072 DEBUG(errs() << " Not duplicating loop header '" << BB->getName()
1073 << "' into predecessor block '" << PredBB->getName()
1074 << "' - it might create an irreducible loop!\n");
1075 return false;
1076 }
1077
1078 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1079 if (DuplicationCost > Threshold) {
1080 DEBUG(errs() << " Not duplicating BB '" << BB->getName()
1081 << "' - Cost is too high: " << DuplicationCost << "\n");
1082 return false;
1083 }
1084
1085 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1086 // of PredBB.
1087 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '"
1088 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1089 << DuplicationCost << " block is:" << *BB << "\n");
1090
1091 // We are going to have to map operands from the original BB block into the
1092 // PredBB block. Evaluate PHI nodes in BB.
1093 DenseMap<Instruction*, Value*> ValueMapping;
1094
1095 BasicBlock::iterator BI = BB->begin();
1096 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1097 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1098
1099 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1100
1101 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1102 // mapping and using it to remap operands in the cloned instructions.
1103 for (; BI != BB->end(); ++BI) {
1104 Instruction *New = BI->clone();
1105 New->setName(BI->getName());
1106 PredBB->getInstList().insert(OldPredBranch, New);
1107 ValueMapping[BI] = New;
1108
1109 // Remap operands to patch up intra-block references.
1110 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1111 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1112 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1113 if (I != ValueMapping.end())
1114 New->setOperand(i, I->second);
1115 }
1116 }
1117
1118 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1119 // add entries to the PHI nodes for branch from PredBB now.
1120 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1121 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1122 ValueMapping);
1123 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1124 ValueMapping);
1125
1126 // If there were values defined in BB that are used outside the block, then we
1127 // now have to update all uses of the value to use either the original value,
1128 // the cloned value, or some PHI derived value. This can require arbitrary
1129 // PHI insertion, of which we are prepared to do, clean these up now.
1130 SSAUpdater SSAUpdate;
1131 SmallVector<Use*, 16> UsesToRename;
1132 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1133 // Scan all uses of this instruction to see if it is used outside of its
1134 // block, and if so, record them in UsesToRename.
1135 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1136 ++UI) {
1137 Instruction *User = cast<Instruction>(*UI);
1138 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1139 if (UserPN->getIncomingBlock(UI) == BB)
1140 continue;
1141 } else if (User->getParent() == BB)
1142 continue;
1143
1144 UsesToRename.push_back(&UI.getUse());
1145 }
1146
1147 // If there are no uses outside the block, we're done with this instruction.
1148 if (UsesToRename.empty())
1149 continue;
1150
1151 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1152
1153 // We found a use of I outside of BB. Rename all uses of I that are outside
1154 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1155 // with the two values we know.
1156 SSAUpdate.Initialize(I);
1157 SSAUpdate.AddAvailableValue(BB, I);
1158 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1159
1160 while (!UsesToRename.empty())
1161 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1162 DEBUG(errs() << "\n");
1163 }
1164
1165 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1166 // that we nuked.
1167 BB->removePredecessor(PredBB);
1168
1169 // Remove the unconditional branch at the end of the PredBB block.
1170 OldPredBranch->eraseFromParent();
1171
1172 ++NumDupes;
1173 return true;
1174}
1175
1176