blob: ed84ec1b965403419e39c19580da7b91dd80e321 [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 Lattneref0c6742008-12-01 04:48:07 +000018#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000019#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000021#include "llvm/Target/TargetData.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000022#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Compiler.h"
Chris Lattner177480b2008-04-20 21:13:06 +000029#include "llvm/Support/Debug.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000030#include "llvm/Support/ValueHandle.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000031using namespace llvm;
32
Chris Lattnerbd3401f2008-04-20 22:39:42 +000033STATISTIC(NumThreads, "Number of jumps threaded");
34STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner8383a7b2008-04-20 20:35:01 +000035
Chris Lattner177480b2008-04-20 21:13:06 +000036static cl::opt<unsigned>
37Threshold("jump-threading-threshold",
38 cl::desc("Max block size to duplicate for jump threading"),
39 cl::init(6), cl::Hidden);
40
Chris Lattner8383a7b2008-04-20 20:35:01 +000041namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000042 /// This pass performs 'jump threading', which looks at blocks that have
43 /// multiple predecessors and multiple successors. If one or more of the
44 /// predecessors of the block can be proven to always jump to one of the
45 /// successors, we forward the edge from the predecessor to the successor by
46 /// duplicating the contents of this block.
47 ///
48 /// An example of when this can occur is code like this:
49 ///
50 /// if () { ...
51 /// X = 4;
52 /// }
53 /// if (X < 3) {
54 ///
55 /// In this case, the unconditional branch at the end of the first if can be
56 /// revectored to the false side of the second if.
57 ///
Chris Lattner8383a7b2008-04-20 20:35:01 +000058 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000059 TargetData *TD;
Mike Stumpfe095f32009-05-04 18:40:41 +000060#ifdef NDEBUG
61 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
62#else
63 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
64#endif
Chris Lattner8383a7b2008-04-20 20:35:01 +000065 public:
66 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000067 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000068
Chris Lattneref0c6742008-12-01 04:48:07 +000069 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<TargetData>();
71 }
72
Chris Lattner8383a7b2008-04-20 20:35:01 +000073 bool runOnFunction(Function &F);
Mike Stumpfe095f32009-05-04 18:40:41 +000074 void FindLoopHeaders(Function &F);
75
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000076 bool ProcessBlock(BasicBlock *BB);
Mike Stumpfe095f32009-05-04 18:40:41 +000077 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB,
78 unsigned JumpThreadCost);
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) {
Chris Lattner177480b2008-04-20 21:13:06 +0000101 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattneref0c6742008-12-01 04:48:07 +0000102 TD = &getAnalysis<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()) {
Chris Lattner421fa9e2008-12-03 07:48:08 +0000121 DOUT << " JT: Deleting dead block '" << BB->getNameStart()
122 << "' with terminator: " << *BB->getTerminator();
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
Mike Stumpfe095f32009-05-04 18:40:41 +0000136/// FindLoopHeaders - We do not want jump threading to turn proper loop
137/// structures into irreducible loops. Doing this breaks up the loop nesting
138/// hierarchy and pessimizes later transformations. To prevent this from
139/// happening, we first have to find the loop headers. Here we approximate this
140/// by finding targets of backedges in the CFG.
141///
142/// Note that there definitely are cases when we want to allow threading of
143/// edges across a loop header. For example, threading a jump from outside the
144/// loop (the preheader) to an exit block of the loop is definitely profitable.
145/// It is also almost always profitable to thread backedges from within the loop
146/// to exit blocks, and is often profitable to thread backedges to other blocks
147/// within the loop (forming a nested loop). This simple analysis is not rich
148/// enough to track all of these properties and keep it up-to-date as the CFG
149/// mutates, so we don't allow any of these transformations.
150///
151void JumpThreading::FindLoopHeaders(Function &F) {
152 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
153 FindFunctionBackedges(F, Edges);
154
155 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
156 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
157}
158
159
Chris Lattner6bf77502008-04-22 07:05:46 +0000160/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
161/// value for the PHI, factor them together so we get one block to thread for
162/// the whole group.
163/// This is important for things like "phi i1 [true, true, false, true, x]"
164/// where we only need to clone the block for the true blocks once.
165///
Nick Lewycky9683f182009-06-19 04:56:29 +0000166BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
Chris Lattner6bf77502008-04-22 07:05:46 +0000167 SmallVector<BasicBlock*, 16> CommonPreds;
168 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Nick Lewycky9683f182009-06-19 04:56:29 +0000169 if (PN->getIncomingValue(i) == Val)
Chris Lattner6bf77502008-04-22 07:05:46 +0000170 CommonPreds.push_back(PN->getIncomingBlock(i));
171
172 if (CommonPreds.size() == 1)
173 return CommonPreds[0];
174
175 DOUT << " Factoring out " << CommonPreds.size()
176 << " common predecessors.\n";
177 return SplitBlockPredecessors(PN->getParent(),
178 &CommonPreds[0], CommonPreds.size(),
179 ".thr_comm", this);
180}
181
182
Chris Lattner177480b2008-04-20 21:13:06 +0000183/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
184/// thread across it.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000185static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
Chris Lattner177480b2008-04-20 21:13:06 +0000186 /// Ignore PHI nodes, these will be flattened when duplication happens.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000187 BasicBlock::const_iterator I = BB->getFirstNonPHI();
Chris Lattner177480b2008-04-20 21:13:06 +0000188
189 // Sum up the cost of each instruction until we get to the terminator. Don't
190 // include the terminator because the copy won't include it.
191 unsigned Size = 0;
192 for (; !isa<TerminatorInst>(I); ++I) {
193 // Debugger intrinsics don't incur code size.
194 if (isa<DbgInfoIntrinsic>(I)) continue;
195
196 // If this is a pointer->pointer bitcast, it is free.
197 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
198 continue;
199
200 // All other instructions count for at least one unit.
201 ++Size;
202
203 // Calls are more expensive. If they are non-intrinsic calls, we model them
204 // as having cost of 4. If they are a non-vector intrinsic, we model them
205 // as having cost of 2 total, and if they are a vector intrinsic, we model
206 // them as having cost 1.
207 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
208 if (!isa<IntrinsicInst>(CI))
209 Size += 3;
210 else if (isa<VectorType>(CI->getType()))
211 Size += 1;
212 }
213 }
214
215 // Threading through a switch statement is particularly profitable. If this
216 // block ends in a switch, decrease its cost to make it more likely to happen.
217 if (isa<SwitchInst>(I))
218 Size = Size > 6 ? Size-6 : 0;
219
220 return Size;
221}
222
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000223/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000224/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000225bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000226 // If this block has a single predecessor, and if that pred has a single
227 // successor, merge the blocks. This encourages recursive jump threading
228 // because now the condition in this block can be threaded through
229 // predecessors of our predecessor block.
230 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
Chris Lattnerf5102a02008-11-28 19:54:49 +0000231 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
232 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000233 // If SinglePred was a loop header, BB becomes one.
234 if (LoopHeaders.erase(SinglePred))
235 LoopHeaders.insert(BB);
236
Chris Lattner3d86d242008-11-27 19:25:19 +0000237 // Remember if SinglePred was the entry block of the function. If so, we
238 // will need to move BB back to the entry position.
239 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000240 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000241
242 if (isEntry && BB != &BB->getParent()->getEntryBlock())
243 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000244 return true;
245 }
246
Matthijs Kooijman6e7b3222008-05-20 07:26:45 +0000247 // See if this block ends with a branch or switch. If so, see if the
Chris Lattner177480b2008-04-20 21:13:06 +0000248 // condition is a phi node. If so, and if an entry of the phi node is a
249 // constant, we can thread the block.
250 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000251 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
252 // Can't thread an unconditional jump.
253 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000254 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000255 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000256 Condition = SI->getCondition();
257 else
258 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000259
260 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000261 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000262 // other blocks.
263 if (isa<ConstantInt>(Condition)) {
264 DOUT << " In block '" << BB->getNameStart()
265 << "' folding terminator: " << *BB->getTerminator();
266 ++NumFolds;
267 ConstantFoldTerminator(BB);
268 return true;
269 }
270
Chris Lattner421fa9e2008-12-03 07:48:08 +0000271 // If the terminator is branching on an undef, we can pick any of the
272 // successors to branch to. Since this is arbitrary, we pick the successor
273 // with the fewest predecessors. This should reduce the in-degree of the
274 // others.
275 if (isa<UndefValue>(Condition)) {
276 TerminatorInst *BBTerm = BB->getTerminator();
277 unsigned MinSucc = 0;
278 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
279 // Compute the successor with the minimum number of predecessors.
280 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
281 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
282 TestBB = BBTerm->getSuccessor(i);
283 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
284 if (NumPreds < MinNumPreds)
285 MinSucc = i;
286 }
287
288 // Fold the branch/switch.
289 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
290 if (i == MinSucc) continue;
291 BBTerm->getSuccessor(i)->removePredecessor(BB);
292 }
293
294 DOUT << " In block '" << BB->getNameStart()
295 << "' folding undef terminator: " << *BBTerm;
296 BranchInst::Create(BBTerm->getSuccessor(MinSucc), BBTerm);
297 BBTerm->eraseFromParent();
298 return true;
299 }
300
301 Instruction *CondInst = dyn_cast<Instruction>(Condition);
302
303 // If the condition is an instruction defined in another block, see if a
304 // predecessor has the same condition:
305 // br COND, BBX, BBY
306 // BBX:
307 // br COND, BBZ, BBW
308 if (!Condition->hasOneUse() && // Multiple uses.
309 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
310 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
311 if (isa<BranchInst>(BB->getTerminator())) {
312 for (; PI != E; ++PI)
313 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
314 if (PBI->isConditional() && PBI->getCondition() == Condition &&
315 ProcessBranchOnDuplicateCond(*PI, BB))
316 return true;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000317 } else {
318 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
319 for (; PI != E; ++PI)
320 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
321 if (PSI->getCondition() == Condition &&
322 ProcessSwitchOnDuplicateCond(*PI, BB))
323 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000324 }
325 }
326
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000327 // If there is only a single predecessor of this block, nothing to fold.
328 if (BB->getSinglePredecessor())
329 return false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000330
331 // All the rest of our checks depend on the condition being an instruction.
332 if (CondInst == 0)
333 return false;
334
Chris Lattner177480b2008-04-20 21:13:06 +0000335 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000336 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
337 if (PN->getParent() == BB)
338 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000339
Chris Lattner6bf77502008-04-22 07:05:46 +0000340 // If this is a conditional branch whose condition is and/or of a phi, try to
341 // simplify it.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000342 if ((CondInst->getOpcode() == Instruction::And ||
343 CondInst->getOpcode() == Instruction::Or) &&
344 isa<BranchInst>(BB->getTerminator()) &&
345 ProcessBranchOnLogical(CondInst, BB,
346 CondInst->getOpcode() == Instruction::And))
347 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000348
Nick Lewycky9683f182009-06-19 04:56:29 +0000349 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
350 if (isa<PHINode>(CondCmp->getOperand(0))) {
351 // If we have "br (phi != 42)" and the phi node has any constant values
352 // as operands, we can thread through this block.
353 //
354 // If we have "br (cmp phi, x)" and the phi node contains x such that the
355 // comparison uniquely identifies the branch target, we can thread
356 // through this block.
357
358 if (ProcessBranchOnCompare(CondCmp, BB))
359 return true;
360 }
361 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000362
363 // Check for some cases that are worth simplifying. Right now we want to look
364 // for loads that are used by a switch or by the condition for the branch. If
365 // we see one, check to see if it's partially redundant. If so, insert a PHI
366 // which can then be used to thread the values.
367 //
368 // This is particularly important because reg2mem inserts loads and stores all
369 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000370 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000371 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
372 if (isa<Constant>(CondCmp->getOperand(1)))
373 SimplifyValue = CondCmp->getOperand(0);
374
375 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
376 if (SimplifyPartiallyRedundantLoad(LI))
377 return true;
378
379 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
380 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000381
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000382 return false;
383}
384
Chris Lattner421fa9e2008-12-03 07:48:08 +0000385/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
386/// block that jump on exactly the same condition. This means that we almost
387/// always know the direction of the edge in the DESTBB:
388/// PREDBB:
389/// br COND, DESTBB, BBY
390/// DESTBB:
391/// br COND, BBZ, BBW
392///
393/// If DESTBB has multiple predecessors, we can't just constant fold the branch
394/// in DESTBB, we have to thread over it.
395bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
396 BasicBlock *BB) {
397 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
398
399 // If both successors of PredBB go to DESTBB, we don't know anything. We can
400 // fold the branch to an unconditional one, which allows other recursive
401 // simplifications.
402 bool BranchDir;
403 if (PredBI->getSuccessor(1) != BB)
404 BranchDir = true;
405 else if (PredBI->getSuccessor(0) != BB)
406 BranchDir = false;
407 else {
408 DOUT << " In block '" << PredBB->getNameStart()
409 << "' folding terminator: " << *PredBB->getTerminator();
410 ++NumFolds;
411 ConstantFoldTerminator(PredBB);
412 return true;
413 }
414
415 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
416
417 // If the dest block has one predecessor, just fix the branch condition to a
418 // constant and fold it.
419 if (BB->getSinglePredecessor()) {
420 DOUT << " In block '" << BB->getNameStart()
421 << "' folding condition to '" << BranchDir << "': "
422 << *BB->getTerminator();
423 ++NumFolds;
424 DestBI->setCondition(ConstantInt::get(Type::Int1Ty, BranchDir));
425 ConstantFoldTerminator(BB);
426 return true;
427 }
428
429 // Otherwise we need to thread from PredBB to DestBB's successor which
430 // involves code duplication. Check to see if it is worth it.
431 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
432 if (JumpThreadCost > Threshold) {
433 DOUT << " Not threading BB '" << BB->getNameStart()
434 << "' - Cost is too high: " << JumpThreadCost << "\n";
435 return false;
436 }
437
438 // Next, figure out which successor we are threading to.
439 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
440
Mike Stumpfe095f32009-05-04 18:40:41 +0000441 // Ok, try to thread it!
442 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000443}
444
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000445/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
446/// block that switch on exactly the same condition. This means that we almost
447/// always know the direction of the edge in the DESTBB:
448/// PREDBB:
449/// switch COND [... DESTBB, BBY ... ]
450/// DESTBB:
451/// switch COND [... BBZ, BBW ]
452///
453/// Optimizing switches like this is very important, because simplifycfg builds
454/// switches out of repeated 'if' conditions.
455bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
456 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000457 // Can't thread edge to self.
458 if (PredBB == DestBB)
459 return false;
460
461
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000462 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
463 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
464
465 // There are a variety of optimizations that we can potentially do on these
466 // blocks: we order them from most to least preferable.
467
468 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
469 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000470 // growth. Skip debug info first.
471 BasicBlock::iterator BBI = DestBB->begin();
472 while (isa<DbgInfoIntrinsic>(BBI))
473 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000474
475 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000476 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000477 bool MadeChange = false;
478 // Ignore the default edge for now.
479 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
480 ConstantInt *DestVal = DestSI->getCaseValue(i);
481 BasicBlock *DestSucc = DestSI->getSuccessor(i);
482
483 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
484 // PredSI has an explicit case for it. If so, forward. If it is covered
485 // by the default case, we can't update PredSI.
486 unsigned PredCase = PredSI->findCaseValue(DestVal);
487 if (PredCase == 0) continue;
488
489 // If PredSI doesn't go to DestBB on this value, then it won't reach the
490 // case on this condition.
491 if (PredSI->getSuccessor(PredCase) != DestBB &&
492 DestSI->getSuccessor(i) != DestBB)
493 continue;
494
495 // Otherwise, we're safe to make the change. Make sure that the edge from
496 // DestSI to DestSucc is not critical and has no PHI nodes.
497 DOUT << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI;
498 DOUT << "THROUGH: " << *DestSI;
499
500 // If the destination has PHI nodes, just split the edge for updating
501 // simplicity.
502 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
503 SplitCriticalEdge(DestSI, i, this);
504 DestSucc = DestSI->getSuccessor(i);
505 }
506 FoldSingleEntryPHINodes(DestSucc);
507 PredSI->setSuccessor(PredCase, DestSucc);
508 MadeChange = true;
509 }
510
511 if (MadeChange)
512 return true;
513 }
514
515 return false;
516}
517
518
Chris Lattner69e067f2008-11-27 05:07:53 +0000519/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
520/// load instruction, eliminate it by replacing it with a PHI node. This is an
521/// important optimization that encourages jump threading, and needs to be run
522/// interlaced with other jump threading tasks.
523bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
524 // Don't hack volatile loads.
525 if (LI->isVolatile()) return false;
526
527 // If the load is defined in a block with exactly one predecessor, it can't be
528 // partially redundant.
529 BasicBlock *LoadBB = LI->getParent();
530 if (LoadBB->getSinglePredecessor())
531 return false;
532
533 Value *LoadedPtr = LI->getOperand(0);
534
535 // If the loaded operand is defined in the LoadBB, it can't be available.
536 // FIXME: Could do PHI translation, that would be fun :)
537 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
538 if (PtrOp->getParent() == LoadBB)
539 return false;
540
541 // Scan a few instructions up from the load, to see if it is obviously live at
542 // the entry to its block.
543 BasicBlock::iterator BBIt = LI;
544
Chris Lattner52c95852008-11-27 08:10:05 +0000545 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
546 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000547 // If the value if the load is locally available within the block, just use
548 // it. This frequently occurs for reg2mem'd allocas.
549 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000550
551 // If the returned value is the load itself, replace with an undef. This can
552 // only happen in dead loops.
553 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000554 LI->replaceAllUsesWith(AvailableVal);
555 LI->eraseFromParent();
556 return true;
557 }
558
559 // Otherwise, if we scanned the whole block and got to the top of the block,
560 // we know the block is locally transparent to the load. If not, something
561 // might clobber its value.
562 if (BBIt != LoadBB->begin())
563 return false;
564
565
566 SmallPtrSet<BasicBlock*, 8> PredsScanned;
567 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
568 AvailablePredsTy AvailablePreds;
569 BasicBlock *OneUnavailablePred = 0;
570
571 // If we got here, the loaded value is transparent through to the start of the
572 // block. Check to see if it is available in any of the predecessor blocks.
573 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
574 PI != PE; ++PI) {
575 BasicBlock *PredBB = *PI;
576
577 // If we already scanned this predecessor, skip it.
578 if (!PredsScanned.insert(PredBB))
579 continue;
580
581 // Scan the predecessor to see if the value is available in the pred.
582 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000583 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000584 if (!PredAvailable) {
585 OneUnavailablePred = PredBB;
586 continue;
587 }
588
589 // If so, this load is partially redundant. Remember this info so that we
590 // can create a PHI node.
591 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
592 }
593
594 // If the loaded value isn't available in any predecessor, it isn't partially
595 // redundant.
596 if (AvailablePreds.empty()) return false;
597
598 // Okay, the loaded value is available in at least one (and maybe all!)
599 // predecessors. If the value is unavailable in more than one unique
600 // predecessor, we want to insert a merge block for those common predecessors.
601 // This ensures that we only have to insert one reload, thus not increasing
602 // code size.
603 BasicBlock *UnavailablePred = 0;
604
605 // If there is exactly one predecessor where the value is unavailable, the
606 // already computed 'OneUnavailablePred' block is it. If it ends in an
607 // unconditional branch, we know that it isn't a critical edge.
608 if (PredsScanned.size() == AvailablePreds.size()+1 &&
609 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
610 UnavailablePred = OneUnavailablePred;
611 } else if (PredsScanned.size() != AvailablePreds.size()) {
612 // Otherwise, we had multiple unavailable predecessors or we had a critical
613 // edge from the one.
614 SmallVector<BasicBlock*, 8> PredsToSplit;
615 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
616
617 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
618 AvailablePredSet.insert(AvailablePreds[i].first);
619
620 // Add all the unavailable predecessors to the PredsToSplit list.
621 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
622 PI != PE; ++PI)
623 if (!AvailablePredSet.count(*PI))
624 PredsToSplit.push_back(*PI);
625
626 // Split them out to their own block.
627 UnavailablePred =
628 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
629 "thread-split", this);
630 }
631
632 // If the value isn't available in all predecessors, then there will be
633 // exactly one where it isn't available. Insert a load on that edge and add
634 // it to the AvailablePreds list.
635 if (UnavailablePred) {
636 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
637 "Can't handle critical edge here!");
638 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
639 UnavailablePred->getTerminator());
640 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
641 }
642
643 // Now we know that each predecessor of this block has a value in
644 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000645 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000646
647 // Create a PHI node at the start of the block for the PRE'd load value.
648 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
649 PN->takeName(LI);
650
651 // Insert new entries into the PHI for each predecessor. A single block may
652 // have multiple entries here.
653 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
654 ++PI) {
655 AvailablePredsTy::iterator I =
656 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
657 std::make_pair(*PI, (Value*)0));
658
659 assert(I != AvailablePreds.end() && I->first == *PI &&
660 "Didn't find entry for predecessor!");
661
662 PN->addIncoming(I->second, I->first);
663 }
664
665 //cerr << "PRE: " << *LI << *PN << "\n";
666
667 LI->replaceAllUsesWith(PN);
668 LI->eraseFromParent();
669
670 return true;
671}
672
673
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000674/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
675/// the current block. See if there are any simplifications we can do based on
676/// inputs to the phi node.
677///
678bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattnerf9065a92008-04-20 21:18:09 +0000679 // See if the phi node has any constant values. If so, we can determine where
680 // the corresponding predecessor will branch.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000681 ConstantInt *PredCst = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000682 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
683 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
Chris Lattnerf9065a92008-04-20 21:18:09 +0000684 break;
Chris Lattnerf9065a92008-04-20 21:18:09 +0000685
686 // If no incoming value has a constant, we don't know the destination of any
687 // predecessors.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000688 if (PredCst == 0)
Chris Lattnerf9065a92008-04-20 21:18:09 +0000689 return false;
690
Chris Lattner177480b2008-04-20 21:13:06 +0000691 // See if the cost of duplicating this block is low enough.
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000692 BasicBlock *BB = PN->getParent();
Chris Lattner177480b2008-04-20 21:13:06 +0000693 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
694 if (JumpThreadCost > Threshold) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000695 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattnerf9065a92008-04-20 21:18:09 +0000696 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner177480b2008-04-20 21:13:06 +0000697 return false;
698 }
Chris Lattner177480b2008-04-20 21:13:06 +0000699
Chris Lattner6bf77502008-04-22 07:05:46 +0000700 // If so, we can actually do this threading. Merge any common predecessors
701 // that will act the same.
702 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
703
704 // Next, figure out which successor we are threading to.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000705 BasicBlock *SuccBB;
706 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
707 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
708 else {
709 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
710 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
711 }
712
Mike Stumpfe095f32009-05-04 18:40:41 +0000713 // Ok, try to thread it!
714 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000715}
716
Chris Lattner6bf77502008-04-22 07:05:46 +0000717/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
718/// whose condition is an AND/OR where one side is PN. If PN has constant
719/// operands that permit us to evaluate the condition for some operand, thread
720/// through the block. For example with:
721/// br (and X, phi(Y, Z, false))
722/// the predecessor corresponding to the 'false' will always jump to the false
723/// destination of the branch.
724///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000725bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
726 bool isAnd) {
727 // If this is a binary operator tree of the same AND/OR opcode, check the
728 // LHS/RHS.
729 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
Duncan Sands43e2a032008-05-27 11:50:51 +0000730 if ((isAnd && BO->getOpcode() == Instruction::And) ||
731 (!isAnd && BO->getOpcode() == Instruction::Or)) {
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000732 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
733 return true;
734 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
735 return true;
736 }
737
738 // If this isn't a PHI node, we can't handle it.
739 PHINode *PN = dyn_cast<PHINode>(V);
740 if (!PN || PN->getParent() != BB) return false;
741
Chris Lattner6bf77502008-04-22 07:05:46 +0000742 // We can only do the simplification for phi nodes of 'false' with AND or
743 // 'true' with OR. See if we have any entries in the phi for this.
744 unsigned PredNo = ~0U;
745 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
746 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
747 if (PN->getIncomingValue(i) == PredCst) {
748 PredNo = i;
749 break;
750 }
751 }
752
753 // If no match, bail out.
754 if (PredNo == ~0U)
755 return false;
756
757 // See if the cost of duplicating this block is low enough.
Chris Lattner6bf77502008-04-22 07:05:46 +0000758 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
759 if (JumpThreadCost > Threshold) {
760 DOUT << " Not threading BB '" << BB->getNameStart()
761 << "' - Cost is too high: " << JumpThreadCost << "\n";
762 return false;
763 }
764
765 // If so, we can actually do this threading. Merge any common predecessors
766 // that will act the same.
767 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
768
769 // Next, figure out which successor we are threading to. If this was an AND,
770 // the constant must be FALSE, and we must be targeting the 'false' block.
771 // If this is an OR, the constant must be TRUE, and we must be targeting the
772 // 'true' block.
773 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
774
Mike Stumpfe095f32009-05-04 18:40:41 +0000775 // Ok, try to thread it!
776 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
Chris Lattner6bf77502008-04-22 07:05:46 +0000777}
778
Nick Lewycky9683f182009-06-19 04:56:29 +0000779/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
780/// hand sides of the compare instruction, try to determine the result. If the
781/// result can not be determined, a null pointer is returned.
782static Constant *GetResultOfComparison(CmpInst::Predicate pred,
783 Value *LHS, Value *RHS) {
784 if (Constant *CLHS = dyn_cast<Constant>(LHS))
785 if (Constant *CRHS = dyn_cast<Constant>(RHS))
786 return ConstantExpr::getCompare(pred, CLHS, CRHS);
787
788 if (LHS == RHS)
789 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
790 return ICmpInst::isTrueWhenEqual(pred) ?
791 ConstantInt::getTrue() : ConstantInt::getFalse();
792
793 return 0;
794}
795
Chris Lattnera5ddb592008-04-22 21:40:39 +0000796/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
Nick Lewycky9683f182009-06-19 04:56:29 +0000797/// node and a value. If we can identify when the comparison is true between
798/// the phi inputs and the value, we can fold the compare for that edge and
799/// thread through it.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000800bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
801 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
Nick Lewycky9683f182009-06-19 04:56:29 +0000802 Value *RHS = Cmp->getOperand(1);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000803
804 // If the phi isn't in the current block, an incoming edge to this block
805 // doesn't control the destination.
806 if (PN->getParent() != BB)
807 return false;
808
809 // We can do this simplification if any comparisons fold to true or false.
810 // See if any do.
Nick Lewycky9683f182009-06-19 04:56:29 +0000811 Value *PredVal = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000812 bool TrueDirection = false;
813 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Nick Lewycky9683f182009-06-19 04:56:29 +0000814 PredVal = PN->getIncomingValue(i);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000815
Nick Lewycky9683f182009-06-19 04:56:29 +0000816 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal, RHS);
817 if (!Res) {
818 PredVal = 0;
819 continue;
820 }
821
Chris Lattnera5ddb592008-04-22 21:40:39 +0000822 // If this folded to a constant expr, we can't do anything.
823 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
824 TrueDirection = ResC->getZExtValue();
825 break;
826 }
827 // If this folded to undef, just go the false way.
828 if (isa<UndefValue>(Res)) {
829 TrueDirection = false;
830 break;
831 }
832
833 // Otherwise, we can't fold this input.
Nick Lewycky9683f182009-06-19 04:56:29 +0000834 PredVal = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000835 }
836
837 // If no match, bail out.
Nick Lewycky9683f182009-06-19 04:56:29 +0000838 if (PredVal == 0)
Chris Lattnera5ddb592008-04-22 21:40:39 +0000839 return false;
840
841 // See if the cost of duplicating this block is low enough.
842 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
843 if (JumpThreadCost > Threshold) {
844 DOUT << " Not threading BB '" << BB->getNameStart()
845 << "' - Cost is too high: " << JumpThreadCost << "\n";
846 return false;
847 }
848
849 // If so, we can actually do this threading. Merge any common predecessors
850 // that will act the same.
Nick Lewycky9683f182009-06-19 04:56:29 +0000851 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000852
853 // Next, get our successor.
854 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
855
Mike Stumpfe095f32009-05-04 18:40:41 +0000856 // Ok, try to thread it!
857 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000858}
859
Chris Lattner6bf77502008-04-22 07:05:46 +0000860
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000861/// ThreadEdge - We have decided that it is safe and profitable to thread an
862/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
863/// change.
Mike Stumpfe095f32009-05-04 18:40:41 +0000864bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
865 BasicBlock *SuccBB, unsigned JumpThreadCost) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000866
Mike Stumpfe095f32009-05-04 18:40:41 +0000867 // If threading to the same block as we come from, we would infinite loop.
868 if (SuccBB == BB) {
869 DOUT << " Not threading across BB '" << BB->getNameStart()
870 << "' - would thread to self!\n";
871 return false;
872 }
873
874 // If threading this would thread across a loop header, don't thread the edge.
875 // See the comments above FindLoopHeaders for justifications and caveats.
876 if (LoopHeaders.count(BB)) {
877 DOUT << " Not threading from '" << PredBB->getNameStart()
878 << "' across loop header BB '" << BB->getNameStart()
879 << "' to dest BB '" << SuccBB->getNameStart()
880 << "' - it might create an irreducible loop!\n";
881 return false;
882 }
883
884 // And finally, do it!
885 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
886 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
887 << ", across block:\n "
888 << *BB << "\n";
889
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000890 // Jump Threading can not update SSA properties correctly if the values
891 // defined in the duplicated block are used outside of the block itself. For
892 // this reason, we spill all values that are used outside of BB to the stack.
Chris Lattner8554cc22008-05-05 20:21:22 +0000893 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
894 if (!I->isUsedOutsideOfBlock(BB))
895 continue;
896
897 // We found a use of I outside of BB. Create a new stack slot to
898 // break this inter-block usage pattern.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000899 DemoteRegToStack(*I);
Chris Lattner8554cc22008-05-05 20:21:22 +0000900 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000901
902 // We are going to have to map operands from the original BB block to the new
903 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
904 // account for entry from PredBB.
905 DenseMap<Instruction*, Value*> ValueMapping;
906
907 BasicBlock *NewBB =
908 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
909 NewBB->moveAfter(PredBB);
910
911 BasicBlock::iterator BI = BB->begin();
912 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
913 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
914
915 // Clone the non-phi instructions of BB into NewBB, keeping track of the
916 // mapping and using it to remap operands in the cloned instructions.
917 for (; !isa<TerminatorInst>(BI); ++BI) {
918 Instruction *New = BI->clone();
919 New->setName(BI->getNameStart());
920 NewBB->getInstList().push_back(New);
921 ValueMapping[BI] = New;
922
923 // Remap operands to patch up intra-block references.
924 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
925 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
926 if (Value *Remapped = ValueMapping[Inst])
927 New->setOperand(i, Remapped);
928 }
929
930 // We didn't copy the terminator from BB over to NewBB, because there is now
931 // an unconditional jump to SuccBB. Insert the unconditional jump.
932 BranchInst::Create(SuccBB, NewBB);
933
934 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
935 // PHI nodes for NewBB now.
936 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
937 PHINode *PN = cast<PHINode>(PNI);
938 // Ok, we have a PHI node. Figure out what the incoming value was for the
939 // DestBlock.
940 Value *IV = PN->getIncomingValueForBlock(BB);
941
942 // Remap the value if necessary.
943 if (Instruction *Inst = dyn_cast<Instruction>(IV))
944 if (Value *MappedIV = ValueMapping[Inst])
945 IV = MappedIV;
946 PN->addIncoming(IV, NewBB);
947 }
948
Chris Lattneref0c6742008-12-01 04:48:07 +0000949 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000950 // NewBB instead of BB. This eliminates predecessors from BB, which requires
951 // us to simplify any PHI nodes in BB.
952 TerminatorInst *PredTerm = PredBB->getTerminator();
953 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
954 if (PredTerm->getSuccessor(i) == BB) {
955 BB->removePredecessor(PredBB);
956 PredTerm->setSuccessor(i, NewBB);
957 }
Chris Lattneref0c6742008-12-01 04:48:07 +0000958
959 // At this point, the IR is fully up to date and consistent. Do a quick scan
960 // over the new instructions and zap any that are constants or dead. This
961 // frequently happens because of phi translation.
962 BI = NewBB->begin();
963 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
964 Instruction *Inst = BI++;
965 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
966 Inst->replaceAllUsesWith(C);
967 Inst->eraseFromParent();
968 continue;
969 }
970
971 RecursivelyDeleteTriviallyDeadInstructions(Inst);
972 }
Mike Stumpfe095f32009-05-04 18:40:41 +0000973
974 // Threaded an edge!
975 ++NumThreads;
976 return true;
Chris Lattner177480b2008-04-20 21:13:06 +0000977}