blob: c5acdd4e5399093e11a529d483a74341f5e64468 [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"
Chris Lattner8383a7b2008-04-20 20:35:01 +000017#include "llvm/Pass.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000018#include "llvm/ADT/DenseMap.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000019#include "llvm/ADT/Statistic.h"
Chris Lattnera3522002008-12-01 06:52:57 +000020#include "llvm/ADT/STLExtras.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000021#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000023#include "llvm/Transforms/Utils/Local.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000024#include "llvm/Target/TargetData.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Compiler.h"
Chris Lattner177480b2008-04-20 21:13:06 +000027#include "llvm/Support/Debug.h"
Chris Lattner69e067f2008-11-27 05:07:53 +000028#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000029using namespace llvm;
30
Chris Lattnerbd3401f2008-04-20 22:39:42 +000031STATISTIC(NumThreads, "Number of jumps threaded");
32STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner8383a7b2008-04-20 20:35:01 +000033
Chris Lattner177480b2008-04-20 21:13:06 +000034static cl::opt<unsigned>
35Threshold("jump-threading-threshold",
36 cl::desc("Max block size to duplicate for jump threading"),
37 cl::init(6), cl::Hidden);
38
Chris Lattner8383a7b2008-04-20 20:35:01 +000039namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000040 /// This pass performs 'jump threading', which looks at blocks that have
41 /// multiple predecessors and multiple successors. If one or more of the
42 /// predecessors of the block can be proven to always jump to one of the
43 /// successors, we forward the edge from the predecessor to the successor by
44 /// duplicating the contents of this block.
45 ///
46 /// An example of when this can occur is code like this:
47 ///
48 /// if () { ...
49 /// X = 4;
50 /// }
51 /// if (X < 3) {
52 ///
53 /// In this case, the unconditional branch at the end of the first if can be
54 /// revectored to the false side of the second if.
55 ///
Chris Lattner8383a7b2008-04-20 20:35:01 +000056 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000057 TargetData *TD;
Chris Lattner8383a7b2008-04-20 20:35:01 +000058 public:
59 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000060 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000061
Chris Lattneref0c6742008-12-01 04:48:07 +000062 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addRequired<TargetData>();
64 }
65
Chris Lattner8383a7b2008-04-20 20:35:01 +000066 bool runOnFunction(Function &F);
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000067 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +000068 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000069 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
Chris Lattner421fa9e2008-12-03 07:48:08 +000070 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000071
Chris Lattnerd38c14e2008-04-22 06:36:15 +000072 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerae65b3c2008-04-22 20:46:09 +000073 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattnera5ddb592008-04-22 21:40:39 +000074 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner69e067f2008-11-27 05:07:53 +000075
76 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000077 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000078}
79
Dan Gohman844731a2008-05-13 00:00:25 +000080char JumpThreading::ID = 0;
81static RegisterPass<JumpThreading>
82X("jump-threading", "Jump Threading");
83
Chris Lattner8383a7b2008-04-20 20:35:01 +000084// Public interface to the Jump Threading pass
85FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
86
87/// runOnFunction - Top level algorithm.
88///
89bool JumpThreading::runOnFunction(Function &F) {
Chris Lattner177480b2008-04-20 21:13:06 +000090 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattneref0c6742008-12-01 04:48:07 +000091 TD = &getAnalysis<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +000092
93 bool AnotherIteration = true, EverChanged = false;
94 while (AnotherIteration) {
95 AnotherIteration = false;
96 bool Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +000097 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
98 BasicBlock *BB = I;
99 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000100 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000101
102 ++I;
103
104 // If the block is trivially dead, zap it. This eliminates the successor
105 // edges which simplifies the CFG.
106 if (pred_begin(BB) == pred_end(BB) &&
107 BB != &BB->getParent()->getEntryBlock()) {
108 DOUT << " JT: Deleting dead block '" << BB->getNameStart()
109 << "' with terminator: " << *BB->getTerminator();
110 DeleteDeadBlock(BB);
111 Changed = true;
112 }
113 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000114 AnotherIteration = Changed;
115 EverChanged |= Changed;
116 }
117 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000118}
Chris Lattner177480b2008-04-20 21:13:06 +0000119
Chris Lattner6bf77502008-04-22 07:05:46 +0000120/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
121/// value for the PHI, factor them together so we get one block to thread for
122/// the whole group.
123/// This is important for things like "phi i1 [true, true, false, true, x]"
124/// where we only need to clone the block for the true blocks once.
125///
126BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
127 SmallVector<BasicBlock*, 16> CommonPreds;
128 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
129 if (PN->getIncomingValue(i) == CstVal)
130 CommonPreds.push_back(PN->getIncomingBlock(i));
131
132 if (CommonPreds.size() == 1)
133 return CommonPreds[0];
134
135 DOUT << " Factoring out " << CommonPreds.size()
136 << " common predecessors.\n";
137 return SplitBlockPredecessors(PN->getParent(),
138 &CommonPreds[0], CommonPreds.size(),
139 ".thr_comm", this);
140}
141
142
Chris Lattner177480b2008-04-20 21:13:06 +0000143/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
144/// thread across it.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000145static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
Chris Lattner177480b2008-04-20 21:13:06 +0000146 /// Ignore PHI nodes, these will be flattened when duplication happens.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000147 BasicBlock::const_iterator I = BB->getFirstNonPHI();
Chris Lattner177480b2008-04-20 21:13:06 +0000148
149 // Sum up the cost of each instruction until we get to the terminator. Don't
150 // include the terminator because the copy won't include it.
151 unsigned Size = 0;
152 for (; !isa<TerminatorInst>(I); ++I) {
153 // Debugger intrinsics don't incur code size.
154 if (isa<DbgInfoIntrinsic>(I)) continue;
155
156 // If this is a pointer->pointer bitcast, it is free.
157 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
158 continue;
159
160 // All other instructions count for at least one unit.
161 ++Size;
162
163 // Calls are more expensive. If they are non-intrinsic calls, we model them
164 // as having cost of 4. If they are a non-vector intrinsic, we model them
165 // as having cost of 2 total, and if they are a vector intrinsic, we model
166 // them as having cost 1.
167 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
168 if (!isa<IntrinsicInst>(CI))
169 Size += 3;
170 else if (isa<VectorType>(CI->getType()))
171 Size += 1;
172 }
173 }
174
175 // Threading through a switch statement is particularly profitable. If this
176 // block ends in a switch, decrease its cost to make it more likely to happen.
177 if (isa<SwitchInst>(I))
178 Size = Size > 6 ? Size-6 : 0;
179
180 return Size;
181}
182
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000183/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000184/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000185bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000186 // If this block has a single predecessor, and if that pred has a single
187 // successor, merge the blocks. This encourages recursive jump threading
188 // because now the condition in this block can be threaded through
189 // predecessors of our predecessor block.
190 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
Chris Lattnerf5102a02008-11-28 19:54:49 +0000191 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
192 SinglePred != BB) {
Chris Lattner3d86d242008-11-27 19:25:19 +0000193 // Remember if SinglePred was the entry block of the function. If so, we
194 // will need to move BB back to the entry position.
195 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000196 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000197
198 if (isEntry && BB != &BB->getParent()->getEntryBlock())
199 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000200 return true;
201 }
202
Matthijs Kooijman6e7b3222008-05-20 07:26:45 +0000203 // See if this block ends with a branch or switch. If so, see if the
Chris Lattner177480b2008-04-20 21:13:06 +0000204 // condition is a phi node. If so, and if an entry of the phi node is a
205 // constant, we can thread the block.
206 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000207 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
208 // Can't thread an unconditional jump.
209 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000210 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000211 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000212 Condition = SI->getCondition();
213 else
214 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000215
216 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000217 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000218 // other blocks.
219 if (isa<ConstantInt>(Condition)) {
220 DOUT << " In block '" << BB->getNameStart()
221 << "' folding terminator: " << *BB->getTerminator();
222 ++NumFolds;
223 ConstantFoldTerminator(BB);
224 return true;
225 }
226
Chris Lattner421fa9e2008-12-03 07:48:08 +0000227 // If the terminator is branching on an undef, we can pick any of the
228 // successors to branch to. Since this is arbitrary, we pick the successor
229 // with the fewest predecessors. This should reduce the in-degree of the
230 // others.
231 if (isa<UndefValue>(Condition)) {
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 // Fold the branch/switch.
245 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
246 if (i == MinSucc) continue;
247 BBTerm->getSuccessor(i)->removePredecessor(BB);
248 }
249
250 DOUT << " In block '" << BB->getNameStart()
251 << "' folding undef terminator: " << *BBTerm;
252 BranchInst::Create(BBTerm->getSuccessor(MinSucc), BBTerm);
253 BBTerm->eraseFromParent();
254 return true;
255 }
256
257 Instruction *CondInst = dyn_cast<Instruction>(Condition);
258
259 // If the condition is an instruction defined in another block, see if a
260 // predecessor has the same condition:
261 // br COND, BBX, BBY
262 // BBX:
263 // br COND, BBZ, BBW
264 if (!Condition->hasOneUse() && // Multiple uses.
265 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
266 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
267 if (isa<BranchInst>(BB->getTerminator())) {
268 for (; PI != E; ++PI)
269 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
270 if (PBI->isConditional() && PBI->getCondition() == Condition &&
271 ProcessBranchOnDuplicateCond(*PI, BB))
272 return true;
273 }
274 }
275
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000276 // If there is only a single predecessor of this block, nothing to fold.
277 if (BB->getSinglePredecessor())
278 return false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000279
280 // All the rest of our checks depend on the condition being an instruction.
281 if (CondInst == 0)
282 return false;
283
Chris Lattner177480b2008-04-20 21:13:06 +0000284 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000285 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
286 if (PN->getParent() == BB)
287 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000288
Chris Lattner6bf77502008-04-22 07:05:46 +0000289 // If this is a conditional branch whose condition is and/or of a phi, try to
290 // simplify it.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000291 if ((CondInst->getOpcode() == Instruction::And ||
292 CondInst->getOpcode() == Instruction::Or) &&
293 isa<BranchInst>(BB->getTerminator()) &&
294 ProcessBranchOnLogical(CondInst, BB,
295 CondInst->getOpcode() == Instruction::And))
296 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000297
Chris Lattnera5ddb592008-04-22 21:40:39 +0000298 // If we have "br (phi != 42)" and the phi node has any constant values as
299 // operands, we can thread through this block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000300 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst))
Chris Lattnera5ddb592008-04-22 21:40:39 +0000301 if (isa<PHINode>(CondCmp->getOperand(0)) &&
302 isa<Constant>(CondCmp->getOperand(1)) &&
303 ProcessBranchOnCompare(CondCmp, BB))
304 return true;
Chris Lattner69e067f2008-11-27 05:07:53 +0000305
306 // Check for some cases that are worth simplifying. Right now we want to look
307 // for loads that are used by a switch or by the condition for the branch. If
308 // we see one, check to see if it's partially redundant. If so, insert a PHI
309 // which can then be used to thread the values.
310 //
311 // This is particularly important because reg2mem inserts loads and stores all
312 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000313 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000314 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
315 if (isa<Constant>(CondCmp->getOperand(1)))
316 SimplifyValue = CondCmp->getOperand(0);
317
318 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
319 if (SimplifyPartiallyRedundantLoad(LI))
320 return true;
321
322 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
323 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000324
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000325 return false;
326}
327
Chris Lattner421fa9e2008-12-03 07:48:08 +0000328/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
329/// block that jump on exactly the same condition. This means that we almost
330/// always know the direction of the edge in the DESTBB:
331/// PREDBB:
332/// br COND, DESTBB, BBY
333/// DESTBB:
334/// br COND, BBZ, BBW
335///
336/// If DESTBB has multiple predecessors, we can't just constant fold the branch
337/// in DESTBB, we have to thread over it.
338bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
339 BasicBlock *BB) {
340 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
341
342 // If both successors of PredBB go to DESTBB, we don't know anything. We can
343 // fold the branch to an unconditional one, which allows other recursive
344 // simplifications.
345 bool BranchDir;
346 if (PredBI->getSuccessor(1) != BB)
347 BranchDir = true;
348 else if (PredBI->getSuccessor(0) != BB)
349 BranchDir = false;
350 else {
351 DOUT << " In block '" << PredBB->getNameStart()
352 << "' folding terminator: " << *PredBB->getTerminator();
353 ++NumFolds;
354 ConstantFoldTerminator(PredBB);
355 return true;
356 }
357
358 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
359
360 // If the dest block has one predecessor, just fix the branch condition to a
361 // constant and fold it.
362 if (BB->getSinglePredecessor()) {
363 DOUT << " In block '" << BB->getNameStart()
364 << "' folding condition to '" << BranchDir << "': "
365 << *BB->getTerminator();
366 ++NumFolds;
367 DestBI->setCondition(ConstantInt::get(Type::Int1Ty, BranchDir));
368 ConstantFoldTerminator(BB);
369 return true;
370 }
371
372 // Otherwise we need to thread from PredBB to DestBB's successor which
373 // involves code duplication. Check to see if it is worth it.
374 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
375 if (JumpThreadCost > Threshold) {
376 DOUT << " Not threading BB '" << BB->getNameStart()
377 << "' - Cost is too high: " << JumpThreadCost << "\n";
378 return false;
379 }
380
381 // Next, figure out which successor we are threading to.
382 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
383
384 // If threading to the same block as we come from, we would infinite loop.
385 if (SuccBB == BB) {
386 DOUT << " Not threading BB '" << BB->getNameStart()
387 << "' - would thread to self!\n";
388 return false;
389 }
390
391 // And finally, do it!
392 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
393 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
394 << ", across block:\n "
395 << *BB << "\n";
396
397 ThreadEdge(BB, PredBB, SuccBB);
398 ++NumThreads;
399 return true;
400}
401
Chris Lattner69e067f2008-11-27 05:07:53 +0000402/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
403/// load instruction, eliminate it by replacing it with a PHI node. This is an
404/// important optimization that encourages jump threading, and needs to be run
405/// interlaced with other jump threading tasks.
406bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
407 // Don't hack volatile loads.
408 if (LI->isVolatile()) return false;
409
410 // If the load is defined in a block with exactly one predecessor, it can't be
411 // partially redundant.
412 BasicBlock *LoadBB = LI->getParent();
413 if (LoadBB->getSinglePredecessor())
414 return false;
415
416 Value *LoadedPtr = LI->getOperand(0);
417
418 // If the loaded operand is defined in the LoadBB, it can't be available.
419 // FIXME: Could do PHI translation, that would be fun :)
420 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
421 if (PtrOp->getParent() == LoadBB)
422 return false;
423
424 // Scan a few instructions up from the load, to see if it is obviously live at
425 // the entry to its block.
426 BasicBlock::iterator BBIt = LI;
427
Chris Lattner52c95852008-11-27 08:10:05 +0000428 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
429 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000430 // If the value if the load is locally available within the block, just use
431 // it. This frequently occurs for reg2mem'd allocas.
432 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
433 LI->replaceAllUsesWith(AvailableVal);
434 LI->eraseFromParent();
435 return true;
436 }
437
438 // Otherwise, if we scanned the whole block and got to the top of the block,
439 // we know the block is locally transparent to the load. If not, something
440 // might clobber its value.
441 if (BBIt != LoadBB->begin())
442 return false;
443
444
445 SmallPtrSet<BasicBlock*, 8> PredsScanned;
446 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
447 AvailablePredsTy AvailablePreds;
448 BasicBlock *OneUnavailablePred = 0;
449
450 // If we got here, the loaded value is transparent through to the start of the
451 // block. Check to see if it is available in any of the predecessor blocks.
452 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
453 PI != PE; ++PI) {
454 BasicBlock *PredBB = *PI;
455
456 // If we already scanned this predecessor, skip it.
457 if (!PredsScanned.insert(PredBB))
458 continue;
459
460 // Scan the predecessor to see if the value is available in the pred.
461 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000462 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000463 if (!PredAvailable) {
464 OneUnavailablePred = PredBB;
465 continue;
466 }
467
468 // If so, this load is partially redundant. Remember this info so that we
469 // can create a PHI node.
470 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
471 }
472
473 // If the loaded value isn't available in any predecessor, it isn't partially
474 // redundant.
475 if (AvailablePreds.empty()) return false;
476
477 // Okay, the loaded value is available in at least one (and maybe all!)
478 // predecessors. If the value is unavailable in more than one unique
479 // predecessor, we want to insert a merge block for those common predecessors.
480 // This ensures that we only have to insert one reload, thus not increasing
481 // code size.
482 BasicBlock *UnavailablePred = 0;
483
484 // If there is exactly one predecessor where the value is unavailable, the
485 // already computed 'OneUnavailablePred' block is it. If it ends in an
486 // unconditional branch, we know that it isn't a critical edge.
487 if (PredsScanned.size() == AvailablePreds.size()+1 &&
488 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
489 UnavailablePred = OneUnavailablePred;
490 } else if (PredsScanned.size() != AvailablePreds.size()) {
491 // Otherwise, we had multiple unavailable predecessors or we had a critical
492 // edge from the one.
493 SmallVector<BasicBlock*, 8> PredsToSplit;
494 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
495
496 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
497 AvailablePredSet.insert(AvailablePreds[i].first);
498
499 // Add all the unavailable predecessors to the PredsToSplit list.
500 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
501 PI != PE; ++PI)
502 if (!AvailablePredSet.count(*PI))
503 PredsToSplit.push_back(*PI);
504
505 // Split them out to their own block.
506 UnavailablePred =
507 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
508 "thread-split", this);
509 }
510
511 // If the value isn't available in all predecessors, then there will be
512 // exactly one where it isn't available. Insert a load on that edge and add
513 // it to the AvailablePreds list.
514 if (UnavailablePred) {
515 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
516 "Can't handle critical edge here!");
517 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
518 UnavailablePred->getTerminator());
519 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
520 }
521
522 // Now we know that each predecessor of this block has a value in
523 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000524 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000525
526 // Create a PHI node at the start of the block for the PRE'd load value.
527 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
528 PN->takeName(LI);
529
530 // Insert new entries into the PHI for each predecessor. A single block may
531 // have multiple entries here.
532 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
533 ++PI) {
534 AvailablePredsTy::iterator I =
535 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
536 std::make_pair(*PI, (Value*)0));
537
538 assert(I != AvailablePreds.end() && I->first == *PI &&
539 "Didn't find entry for predecessor!");
540
541 PN->addIncoming(I->second, I->first);
542 }
543
544 //cerr << "PRE: " << *LI << *PN << "\n";
545
546 LI->replaceAllUsesWith(PN);
547 LI->eraseFromParent();
548
549 return true;
550}
551
552
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000553/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
554/// the current block. See if there are any simplifications we can do based on
555/// inputs to the phi node.
556///
557bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattnerf9065a92008-04-20 21:18:09 +0000558 // See if the phi node has any constant values. If so, we can determine where
559 // the corresponding predecessor will branch.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000560 ConstantInt *PredCst = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000561 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
562 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
Chris Lattnerf9065a92008-04-20 21:18:09 +0000563 break;
Chris Lattnerf9065a92008-04-20 21:18:09 +0000564
565 // If no incoming value has a constant, we don't know the destination of any
566 // predecessors.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000567 if (PredCst == 0)
Chris Lattnerf9065a92008-04-20 21:18:09 +0000568 return false;
569
Chris Lattner177480b2008-04-20 21:13:06 +0000570 // See if the cost of duplicating this block is low enough.
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000571 BasicBlock *BB = PN->getParent();
Chris Lattner177480b2008-04-20 21:13:06 +0000572 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
573 if (JumpThreadCost > Threshold) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000574 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattnerf9065a92008-04-20 21:18:09 +0000575 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner177480b2008-04-20 21:13:06 +0000576 return false;
577 }
Chris Lattner177480b2008-04-20 21:13:06 +0000578
Chris Lattner6bf77502008-04-22 07:05:46 +0000579 // If so, we can actually do this threading. Merge any common predecessors
580 // that will act the same.
581 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
582
583 // Next, figure out which successor we are threading to.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000584 BasicBlock *SuccBB;
585 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
586 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
587 else {
588 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
589 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
590 }
591
Chris Lattnereede65c2008-04-25 04:12:29 +0000592 // If threading to the same block as we come from, we would infinite loop.
593 if (SuccBB == BB) {
594 DOUT << " Not threading BB '" << BB->getNameStart()
595 << "' - would thread to self!\n";
596 return false;
597 }
598
Chris Lattner6bf77502008-04-22 07:05:46 +0000599 // And finally, do it!
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000600 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
601 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
602 << ", across block:\n "
Chris Lattner6bf77502008-04-22 07:05:46 +0000603 << *BB << "\n";
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000604
605 ThreadEdge(BB, PredBB, SuccBB);
606 ++NumThreads;
607 return true;
608}
609
Chris Lattner6bf77502008-04-22 07:05:46 +0000610/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
611/// whose condition is an AND/OR where one side is PN. If PN has constant
612/// operands that permit us to evaluate the condition for some operand, thread
613/// through the block. For example with:
614/// br (and X, phi(Y, Z, false))
615/// the predecessor corresponding to the 'false' will always jump to the false
616/// destination of the branch.
617///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000618bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
619 bool isAnd) {
620 // If this is a binary operator tree of the same AND/OR opcode, check the
621 // LHS/RHS.
622 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
Duncan Sands43e2a032008-05-27 11:50:51 +0000623 if ((isAnd && BO->getOpcode() == Instruction::And) ||
624 (!isAnd && BO->getOpcode() == Instruction::Or)) {
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000625 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
626 return true;
627 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
628 return true;
629 }
630
631 // If this isn't a PHI node, we can't handle it.
632 PHINode *PN = dyn_cast<PHINode>(V);
633 if (!PN || PN->getParent() != BB) return false;
634
Chris Lattner6bf77502008-04-22 07:05:46 +0000635 // We can only do the simplification for phi nodes of 'false' with AND or
636 // 'true' with OR. See if we have any entries in the phi for this.
637 unsigned PredNo = ~0U;
638 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
639 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
640 if (PN->getIncomingValue(i) == PredCst) {
641 PredNo = i;
642 break;
643 }
644 }
645
646 // If no match, bail out.
647 if (PredNo == ~0U)
648 return false;
649
650 // See if the cost of duplicating this block is low enough.
Chris Lattner6bf77502008-04-22 07:05:46 +0000651 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
652 if (JumpThreadCost > Threshold) {
653 DOUT << " Not threading BB '" << BB->getNameStart()
654 << "' - Cost is too high: " << JumpThreadCost << "\n";
655 return false;
656 }
657
658 // If so, we can actually do this threading. Merge any common predecessors
659 // that will act the same.
660 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
661
662 // Next, figure out which successor we are threading to. If this was an AND,
663 // the constant must be FALSE, and we must be targeting the 'false' block.
664 // If this is an OR, the constant must be TRUE, and we must be targeting the
665 // 'true' block.
666 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
667
Chris Lattnereede65c2008-04-25 04:12:29 +0000668 // If threading to the same block as we come from, we would infinite loop.
669 if (SuccBB == BB) {
670 DOUT << " Not threading BB '" << BB->getNameStart()
671 << "' - would thread to self!\n";
672 return false;
673 }
674
Chris Lattner6bf77502008-04-22 07:05:46 +0000675 // And finally, do it!
676 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
677 << "' to '" << SuccBB->getNameStart() << "' with cost: "
678 << JumpThreadCost << ", across block:\n "
679 << *BB << "\n";
680
681 ThreadEdge(BB, PredBB, SuccBB);
682 ++NumThreads;
683 return true;
684}
685
Chris Lattnera5ddb592008-04-22 21:40:39 +0000686/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
687/// node and a constant. If the PHI node contains any constants as inputs, we
688/// can fold the compare for that edge and thread through it.
689bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
690 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
691 Constant *RHS = cast<Constant>(Cmp->getOperand(1));
692
693 // If the phi isn't in the current block, an incoming edge to this block
694 // doesn't control the destination.
695 if (PN->getParent() != BB)
696 return false;
697
698 // We can do this simplification if any comparisons fold to true or false.
699 // See if any do.
700 Constant *PredCst = 0;
701 bool TrueDirection = false;
702 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
703 PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
704 if (PredCst == 0) continue;
705
706 Constant *Res;
707 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
708 Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
709 else
710 Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
711 PredCst, RHS);
712 // If this folded to a constant expr, we can't do anything.
713 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
714 TrueDirection = ResC->getZExtValue();
715 break;
716 }
717 // If this folded to undef, just go the false way.
718 if (isa<UndefValue>(Res)) {
719 TrueDirection = false;
720 break;
721 }
722
723 // Otherwise, we can't fold this input.
724 PredCst = 0;
725 }
726
727 // If no match, bail out.
728 if (PredCst == 0)
729 return false;
730
731 // See if the cost of duplicating this block is low enough.
732 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
733 if (JumpThreadCost > Threshold) {
734 DOUT << " Not threading BB '" << BB->getNameStart()
735 << "' - Cost is too high: " << JumpThreadCost << "\n";
736 return false;
737 }
738
739 // If so, we can actually do this threading. Merge any common predecessors
740 // that will act the same.
741 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
742
743 // Next, get our successor.
744 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
745
Chris Lattnereede65c2008-04-25 04:12:29 +0000746 // If threading to the same block as we come from, we would infinite loop.
747 if (SuccBB == BB) {
748 DOUT << " Not threading BB '" << BB->getNameStart()
749 << "' - would thread to self!\n";
750 return false;
751 }
752
753
Chris Lattnera5ddb592008-04-22 21:40:39 +0000754 // And finally, do it!
755 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
756 << "' to '" << SuccBB->getNameStart() << "' with cost: "
757 << JumpThreadCost << ", across block:\n "
758 << *BB << "\n";
759
760 ThreadEdge(BB, PredBB, SuccBB);
761 ++NumThreads;
762 return true;
763}
764
Chris Lattner6bf77502008-04-22 07:05:46 +0000765
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000766/// ThreadEdge - We have decided that it is safe and profitable to thread an
767/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
768/// change.
769void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
770 BasicBlock *SuccBB) {
771
772 // Jump Threading can not update SSA properties correctly if the values
773 // defined in the duplicated block are used outside of the block itself. For
774 // this reason, we spill all values that are used outside of BB to the stack.
Chris Lattner8554cc22008-05-05 20:21:22 +0000775 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
776 if (!I->isUsedOutsideOfBlock(BB))
777 continue;
778
779 // We found a use of I outside of BB. Create a new stack slot to
780 // break this inter-block usage pattern.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000781 DemoteRegToStack(*I);
Chris Lattner8554cc22008-05-05 20:21:22 +0000782 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000783
784 // We are going to have to map operands from the original BB block to the new
785 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
786 // account for entry from PredBB.
787 DenseMap<Instruction*, Value*> ValueMapping;
788
789 BasicBlock *NewBB =
790 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
791 NewBB->moveAfter(PredBB);
792
793 BasicBlock::iterator BI = BB->begin();
794 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
795 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
796
797 // Clone the non-phi instructions of BB into NewBB, keeping track of the
798 // mapping and using it to remap operands in the cloned instructions.
799 for (; !isa<TerminatorInst>(BI); ++BI) {
800 Instruction *New = BI->clone();
801 New->setName(BI->getNameStart());
802 NewBB->getInstList().push_back(New);
803 ValueMapping[BI] = New;
804
805 // Remap operands to patch up intra-block references.
806 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
807 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
808 if (Value *Remapped = ValueMapping[Inst])
809 New->setOperand(i, Remapped);
810 }
811
812 // We didn't copy the terminator from BB over to NewBB, because there is now
813 // an unconditional jump to SuccBB. Insert the unconditional jump.
814 BranchInst::Create(SuccBB, NewBB);
815
816 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
817 // PHI nodes for NewBB now.
818 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
819 PHINode *PN = cast<PHINode>(PNI);
820 // Ok, we have a PHI node. Figure out what the incoming value was for the
821 // DestBlock.
822 Value *IV = PN->getIncomingValueForBlock(BB);
823
824 // Remap the value if necessary.
825 if (Instruction *Inst = dyn_cast<Instruction>(IV))
826 if (Value *MappedIV = ValueMapping[Inst])
827 IV = MappedIV;
828 PN->addIncoming(IV, NewBB);
829 }
830
Chris Lattneref0c6742008-12-01 04:48:07 +0000831 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000832 // NewBB instead of BB. This eliminates predecessors from BB, which requires
833 // us to simplify any PHI nodes in BB.
834 TerminatorInst *PredTerm = PredBB->getTerminator();
835 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
836 if (PredTerm->getSuccessor(i) == BB) {
837 BB->removePredecessor(PredBB);
838 PredTerm->setSuccessor(i, NewBB);
839 }
Chris Lattneref0c6742008-12-01 04:48:07 +0000840
841 // At this point, the IR is fully up to date and consistent. Do a quick scan
842 // over the new instructions and zap any that are constants or dead. This
843 // frequently happens because of phi translation.
844 BI = NewBB->begin();
845 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
846 Instruction *Inst = BI++;
847 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
848 Inst->replaceAllUsesWith(C);
849 Inst->eraseFromParent();
850 continue;
851 }
852
853 RecursivelyDeleteTriviallyDeadInstructions(Inst);
854 }
Chris Lattner177480b2008-04-20 21:13:06 +0000855}