blob: 35b73beade5e8ae805912fa7d70c5a3246294389 [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 Lattneref0c6742008-12-01 04:48:07 +000020#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000021#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000022#include "llvm/Transforms/Utils/Local.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000023#include "llvm/Target/TargetData.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Compiler.h"
Chris Lattner177480b2008-04-20 21:13:06 +000026#include "llvm/Support/Debug.h"
Chris Lattner69e067f2008-11-27 05:07:53 +000027#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000028using namespace llvm;
29
Chris Lattnerbd3401f2008-04-20 22:39:42 +000030STATISTIC(NumThreads, "Number of jumps threaded");
31STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner8383a7b2008-04-20 20:35:01 +000032
Chris Lattner177480b2008-04-20 21:13:06 +000033static cl::opt<unsigned>
34Threshold("jump-threading-threshold",
35 cl::desc("Max block size to duplicate for jump threading"),
36 cl::init(6), cl::Hidden);
37
Chris Lattner8383a7b2008-04-20 20:35:01 +000038namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000039 /// This pass performs 'jump threading', which looks at blocks that have
40 /// multiple predecessors and multiple successors. If one or more of the
41 /// predecessors of the block can be proven to always jump to one of the
42 /// successors, we forward the edge from the predecessor to the successor by
43 /// duplicating the contents of this block.
44 ///
45 /// An example of when this can occur is code like this:
46 ///
47 /// if () { ...
48 /// X = 4;
49 /// }
50 /// if (X < 3) {
51 ///
52 /// In this case, the unconditional branch at the end of the first if can be
53 /// revectored to the false side of the second if.
54 ///
Chris Lattner8383a7b2008-04-20 20:35:01 +000055 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000056 TargetData *TD;
Chris Lattner8383a7b2008-04-20 20:35:01 +000057 public:
58 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000059 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000060
Chris Lattneref0c6742008-12-01 04:48:07 +000061 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequired<TargetData>();
63 }
64
Chris Lattner8383a7b2008-04-20 20:35:01 +000065 bool runOnFunction(Function &F);
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000066 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +000067 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000068 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
69
Chris Lattnerd38c14e2008-04-22 06:36:15 +000070 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerae65b3c2008-04-22 20:46:09 +000071 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattnera5ddb592008-04-22 21:40:39 +000072 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner69e067f2008-11-27 05:07:53 +000073
74 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000075 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000076}
77
Dan Gohman844731a2008-05-13 00:00:25 +000078char JumpThreading::ID = 0;
79static RegisterPass<JumpThreading>
80X("jump-threading", "Jump Threading");
81
Chris Lattner8383a7b2008-04-20 20:35:01 +000082// Public interface to the Jump Threading pass
83FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
84
85/// runOnFunction - Top level algorithm.
86///
87bool JumpThreading::runOnFunction(Function &F) {
Chris Lattner177480b2008-04-20 21:13:06 +000088 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattneref0c6742008-12-01 04:48:07 +000089 TD = &getAnalysis<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +000090
91 bool AnotherIteration = true, EverChanged = false;
92 while (AnotherIteration) {
93 AnotherIteration = false;
94 bool Changed = false;
95 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000096 while (ProcessBlock(I))
Chris Lattnerbd3401f2008-04-20 22:39:42 +000097 Changed = true;
98 AnotherIteration = Changed;
99 EverChanged |= Changed;
100 }
101 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000102}
Chris Lattner177480b2008-04-20 21:13:06 +0000103
Chris Lattner6bf77502008-04-22 07:05:46 +0000104/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
105/// value for the PHI, factor them together so we get one block to thread for
106/// the whole group.
107/// This is important for things like "phi i1 [true, true, false, true, x]"
108/// where we only need to clone the block for the true blocks once.
109///
110BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
111 SmallVector<BasicBlock*, 16> CommonPreds;
112 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
113 if (PN->getIncomingValue(i) == CstVal)
114 CommonPreds.push_back(PN->getIncomingBlock(i));
115
116 if (CommonPreds.size() == 1)
117 return CommonPreds[0];
118
119 DOUT << " Factoring out " << CommonPreds.size()
120 << " common predecessors.\n";
121 return SplitBlockPredecessors(PN->getParent(),
122 &CommonPreds[0], CommonPreds.size(),
123 ".thr_comm", this);
124}
125
126
Chris Lattner177480b2008-04-20 21:13:06 +0000127/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
128/// thread across it.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000129static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
Chris Lattner177480b2008-04-20 21:13:06 +0000130 /// Ignore PHI nodes, these will be flattened when duplication happens.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000131 BasicBlock::const_iterator I = BB->getFirstNonPHI();
Chris Lattner177480b2008-04-20 21:13:06 +0000132
133 // Sum up the cost of each instruction until we get to the terminator. Don't
134 // include the terminator because the copy won't include it.
135 unsigned Size = 0;
136 for (; !isa<TerminatorInst>(I); ++I) {
137 // Debugger intrinsics don't incur code size.
138 if (isa<DbgInfoIntrinsic>(I)) continue;
139
140 // If this is a pointer->pointer bitcast, it is free.
141 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
142 continue;
143
144 // All other instructions count for at least one unit.
145 ++Size;
146
147 // Calls are more expensive. If they are non-intrinsic calls, we model them
148 // as having cost of 4. If they are a non-vector intrinsic, we model them
149 // as having cost of 2 total, and if they are a vector intrinsic, we model
150 // them as having cost 1.
151 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
152 if (!isa<IntrinsicInst>(CI))
153 Size += 3;
154 else if (isa<VectorType>(CI->getType()))
155 Size += 1;
156 }
157 }
158
159 // Threading through a switch statement is particularly profitable. If this
160 // block ends in a switch, decrease its cost to make it more likely to happen.
161 if (isa<SwitchInst>(I))
162 Size = Size > 6 ? Size-6 : 0;
163
164 return Size;
165}
166
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000167/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000168/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000169bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000170 // If this block has a single predecessor, and if that pred has a single
171 // successor, merge the blocks. This encourages recursive jump threading
172 // because now the condition in this block can be threaded through
173 // predecessors of our predecessor block.
174 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
Chris Lattnerf5102a02008-11-28 19:54:49 +0000175 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
176 SinglePred != BB) {
Chris Lattner3d86d242008-11-27 19:25:19 +0000177 // Remember if SinglePred was the entry block of the function. If so, we
178 // will need to move BB back to the entry position.
179 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000180 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000181
182 if (isEntry && BB != &BB->getParent()->getEntryBlock())
183 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000184 return true;
185 }
186
Matthijs Kooijman6e7b3222008-05-20 07:26:45 +0000187 // See if this block ends with a branch or switch. If so, see if the
Chris Lattner177480b2008-04-20 21:13:06 +0000188 // condition is a phi node. If so, and if an entry of the phi node is a
189 // constant, we can thread the block.
190 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000191 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
192 // Can't thread an unconditional jump.
193 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000194 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000195 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000196 Condition = SI->getCondition();
197 else
198 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000199
200 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000201 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000202 // other blocks.
203 if (isa<ConstantInt>(Condition)) {
204 DOUT << " In block '" << BB->getNameStart()
205 << "' folding terminator: " << *BB->getTerminator();
206 ++NumFolds;
207 ConstantFoldTerminator(BB);
208 return true;
209 }
210
211 // If there is only a single predecessor of this block, nothing to fold.
212 if (BB->getSinglePredecessor())
213 return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000214
215 // See if this is a phi node in the current block.
216 PHINode *PN = dyn_cast<PHINode>(Condition);
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000217 if (PN && PN->getParent() == BB)
218 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000219
Chris Lattner6bf77502008-04-22 07:05:46 +0000220 // If this is a conditional branch whose condition is and/or of a phi, try to
221 // simplify it.
222 if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
223 if ((CondI->getOpcode() == Instruction::And ||
224 CondI->getOpcode() == Instruction::Or) &&
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000225 isa<BranchInst>(BB->getTerminator()) &&
226 ProcessBranchOnLogical(CondI, BB,
227 CondI->getOpcode() == Instruction::And))
228 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000229 }
230
Chris Lattnera5ddb592008-04-22 21:40:39 +0000231 // If we have "br (phi != 42)" and the phi node has any constant values as
232 // operands, we can thread through this block.
233 if (CmpInst *CondCmp = dyn_cast<CmpInst>(Condition))
234 if (isa<PHINode>(CondCmp->getOperand(0)) &&
235 isa<Constant>(CondCmp->getOperand(1)) &&
236 ProcessBranchOnCompare(CondCmp, BB))
237 return true;
Chris Lattner69e067f2008-11-27 05:07:53 +0000238
239 // Check for some cases that are worth simplifying. Right now we want to look
240 // for loads that are used by a switch or by the condition for the branch. If
241 // we see one, check to see if it's partially redundant. If so, insert a PHI
242 // which can then be used to thread the values.
243 //
244 // This is particularly important because reg2mem inserts loads and stores all
245 // over the place, and this blocks jump threading if we don't zap them.
246 Value *SimplifyValue = Condition;
247 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
248 if (isa<Constant>(CondCmp->getOperand(1)))
249 SimplifyValue = CondCmp->getOperand(0);
250
251 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
252 if (SimplifyPartiallyRedundantLoad(LI))
253 return true;
254
255 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
256 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000257
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000258 return false;
259}
260
Chris Lattner69e067f2008-11-27 05:07:53 +0000261/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
262/// load instruction, eliminate it by replacing it with a PHI node. This is an
263/// important optimization that encourages jump threading, and needs to be run
264/// interlaced with other jump threading tasks.
265bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
266 // Don't hack volatile loads.
267 if (LI->isVolatile()) return false;
268
269 // If the load is defined in a block with exactly one predecessor, it can't be
270 // partially redundant.
271 BasicBlock *LoadBB = LI->getParent();
272 if (LoadBB->getSinglePredecessor())
273 return false;
274
275 Value *LoadedPtr = LI->getOperand(0);
276
277 // If the loaded operand is defined in the LoadBB, it can't be available.
278 // FIXME: Could do PHI translation, that would be fun :)
279 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
280 if (PtrOp->getParent() == LoadBB)
281 return false;
282
283 // Scan a few instructions up from the load, to see if it is obviously live at
284 // the entry to its block.
285 BasicBlock::iterator BBIt = LI;
286
Chris Lattner52c95852008-11-27 08:10:05 +0000287 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
288 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000289 // If the value if the load is locally available within the block, just use
290 // it. This frequently occurs for reg2mem'd allocas.
291 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
292 LI->replaceAllUsesWith(AvailableVal);
293 LI->eraseFromParent();
294 return true;
295 }
296
297 // Otherwise, if we scanned the whole block and got to the top of the block,
298 // we know the block is locally transparent to the load. If not, something
299 // might clobber its value.
300 if (BBIt != LoadBB->begin())
301 return false;
302
303
304 SmallPtrSet<BasicBlock*, 8> PredsScanned;
305 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
306 AvailablePredsTy AvailablePreds;
307 BasicBlock *OneUnavailablePred = 0;
308
309 // If we got here, the loaded value is transparent through to the start of the
310 // block. Check to see if it is available in any of the predecessor blocks.
311 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
312 PI != PE; ++PI) {
313 BasicBlock *PredBB = *PI;
314
315 // If we already scanned this predecessor, skip it.
316 if (!PredsScanned.insert(PredBB))
317 continue;
318
319 // Scan the predecessor to see if the value is available in the pred.
320 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000321 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000322 if (!PredAvailable) {
323 OneUnavailablePred = PredBB;
324 continue;
325 }
326
327 // If so, this load is partially redundant. Remember this info so that we
328 // can create a PHI node.
329 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
330 }
331
332 // If the loaded value isn't available in any predecessor, it isn't partially
333 // redundant.
334 if (AvailablePreds.empty()) return false;
335
336 // Okay, the loaded value is available in at least one (and maybe all!)
337 // predecessors. If the value is unavailable in more than one unique
338 // predecessor, we want to insert a merge block for those common predecessors.
339 // This ensures that we only have to insert one reload, thus not increasing
340 // code size.
341 BasicBlock *UnavailablePred = 0;
342
343 // If there is exactly one predecessor where the value is unavailable, the
344 // already computed 'OneUnavailablePred' block is it. If it ends in an
345 // unconditional branch, we know that it isn't a critical edge.
346 if (PredsScanned.size() == AvailablePreds.size()+1 &&
347 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
348 UnavailablePred = OneUnavailablePred;
349 } else if (PredsScanned.size() != AvailablePreds.size()) {
350 // Otherwise, we had multiple unavailable predecessors or we had a critical
351 // edge from the one.
352 SmallVector<BasicBlock*, 8> PredsToSplit;
353 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
354
355 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
356 AvailablePredSet.insert(AvailablePreds[i].first);
357
358 // Add all the unavailable predecessors to the PredsToSplit list.
359 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
360 PI != PE; ++PI)
361 if (!AvailablePredSet.count(*PI))
362 PredsToSplit.push_back(*PI);
363
364 // Split them out to their own block.
365 UnavailablePred =
366 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
367 "thread-split", this);
368 }
369
370 // If the value isn't available in all predecessors, then there will be
371 // exactly one where it isn't available. Insert a load on that edge and add
372 // it to the AvailablePreds list.
373 if (UnavailablePred) {
374 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
375 "Can't handle critical edge here!");
376 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
377 UnavailablePred->getTerminator());
378 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
379 }
380
381 // Now we know that each predecessor of this block has a value in
382 // AvailablePreds, sort them for efficient access as we're walking the preds.
383 std::sort(AvailablePreds.begin(), AvailablePreds.end());
384
385 // Create a PHI node at the start of the block for the PRE'd load value.
386 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
387 PN->takeName(LI);
388
389 // Insert new entries into the PHI for each predecessor. A single block may
390 // have multiple entries here.
391 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
392 ++PI) {
393 AvailablePredsTy::iterator I =
394 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
395 std::make_pair(*PI, (Value*)0));
396
397 assert(I != AvailablePreds.end() && I->first == *PI &&
398 "Didn't find entry for predecessor!");
399
400 PN->addIncoming(I->second, I->first);
401 }
402
403 //cerr << "PRE: " << *LI << *PN << "\n";
404
405 LI->replaceAllUsesWith(PN);
406 LI->eraseFromParent();
407
408 return true;
409}
410
411
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000412/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
413/// the current block. See if there are any simplifications we can do based on
414/// inputs to the phi node.
415///
416bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattnerf9065a92008-04-20 21:18:09 +0000417 // See if the phi node has any constant values. If so, we can determine where
418 // the corresponding predecessor will branch.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000419 ConstantInt *PredCst = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000420 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
421 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
Chris Lattnerf9065a92008-04-20 21:18:09 +0000422 break;
Chris Lattnerf9065a92008-04-20 21:18:09 +0000423
424 // If no incoming value has a constant, we don't know the destination of any
425 // predecessors.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000426 if (PredCst == 0)
Chris Lattnerf9065a92008-04-20 21:18:09 +0000427 return false;
428
Chris Lattner177480b2008-04-20 21:13:06 +0000429 // See if the cost of duplicating this block is low enough.
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000430 BasicBlock *BB = PN->getParent();
Chris Lattner177480b2008-04-20 21:13:06 +0000431 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
432 if (JumpThreadCost > Threshold) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000433 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattnerf9065a92008-04-20 21:18:09 +0000434 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner177480b2008-04-20 21:13:06 +0000435 return false;
436 }
Chris Lattner177480b2008-04-20 21:13:06 +0000437
Chris Lattner6bf77502008-04-22 07:05:46 +0000438 // If so, we can actually do this threading. Merge any common predecessors
439 // that will act the same.
440 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
441
442 // Next, figure out which successor we are threading to.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000443 BasicBlock *SuccBB;
444 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
445 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
446 else {
447 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
448 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
449 }
450
Chris Lattnereede65c2008-04-25 04:12:29 +0000451 // If threading to the same block as we come from, we would infinite loop.
452 if (SuccBB == BB) {
453 DOUT << " Not threading BB '" << BB->getNameStart()
454 << "' - would thread to self!\n";
455 return false;
456 }
457
Chris Lattner6bf77502008-04-22 07:05:46 +0000458 // And finally, do it!
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000459 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
460 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
461 << ", across block:\n "
Chris Lattner6bf77502008-04-22 07:05:46 +0000462 << *BB << "\n";
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000463
464 ThreadEdge(BB, PredBB, SuccBB);
465 ++NumThreads;
466 return true;
467}
468
Chris Lattner6bf77502008-04-22 07:05:46 +0000469/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
470/// whose condition is an AND/OR where one side is PN. If PN has constant
471/// operands that permit us to evaluate the condition for some operand, thread
472/// through the block. For example with:
473/// br (and X, phi(Y, Z, false))
474/// the predecessor corresponding to the 'false' will always jump to the false
475/// destination of the branch.
476///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000477bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
478 bool isAnd) {
479 // If this is a binary operator tree of the same AND/OR opcode, check the
480 // LHS/RHS.
481 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
Duncan Sands43e2a032008-05-27 11:50:51 +0000482 if ((isAnd && BO->getOpcode() == Instruction::And) ||
483 (!isAnd && BO->getOpcode() == Instruction::Or)) {
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000484 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
485 return true;
486 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
487 return true;
488 }
489
490 // If this isn't a PHI node, we can't handle it.
491 PHINode *PN = dyn_cast<PHINode>(V);
492 if (!PN || PN->getParent() != BB) return false;
493
Chris Lattner6bf77502008-04-22 07:05:46 +0000494 // We can only do the simplification for phi nodes of 'false' with AND or
495 // 'true' with OR. See if we have any entries in the phi for this.
496 unsigned PredNo = ~0U;
497 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
498 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
499 if (PN->getIncomingValue(i) == PredCst) {
500 PredNo = i;
501 break;
502 }
503 }
504
505 // If no match, bail out.
506 if (PredNo == ~0U)
507 return false;
508
509 // See if the cost of duplicating this block is low enough.
Chris Lattner6bf77502008-04-22 07:05:46 +0000510 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
511 if (JumpThreadCost > Threshold) {
512 DOUT << " Not threading BB '" << BB->getNameStart()
513 << "' - Cost is too high: " << JumpThreadCost << "\n";
514 return false;
515 }
516
517 // If so, we can actually do this threading. Merge any common predecessors
518 // that will act the same.
519 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
520
521 // Next, figure out which successor we are threading to. If this was an AND,
522 // the constant must be FALSE, and we must be targeting the 'false' block.
523 // If this is an OR, the constant must be TRUE, and we must be targeting the
524 // 'true' block.
525 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
526
Chris Lattnereede65c2008-04-25 04:12:29 +0000527 // If threading to the same block as we come from, we would infinite loop.
528 if (SuccBB == BB) {
529 DOUT << " Not threading BB '" << BB->getNameStart()
530 << "' - would thread to self!\n";
531 return false;
532 }
533
Chris Lattner6bf77502008-04-22 07:05:46 +0000534 // And finally, do it!
535 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
536 << "' to '" << SuccBB->getNameStart() << "' with cost: "
537 << JumpThreadCost << ", across block:\n "
538 << *BB << "\n";
539
540 ThreadEdge(BB, PredBB, SuccBB);
541 ++NumThreads;
542 return true;
543}
544
Chris Lattnera5ddb592008-04-22 21:40:39 +0000545/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
546/// node and a constant. If the PHI node contains any constants as inputs, we
547/// can fold the compare for that edge and thread through it.
548bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
549 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
550 Constant *RHS = cast<Constant>(Cmp->getOperand(1));
551
552 // If the phi isn't in the current block, an incoming edge to this block
553 // doesn't control the destination.
554 if (PN->getParent() != BB)
555 return false;
556
557 // We can do this simplification if any comparisons fold to true or false.
558 // See if any do.
559 Constant *PredCst = 0;
560 bool TrueDirection = false;
561 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
562 PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
563 if (PredCst == 0) continue;
564
565 Constant *Res;
566 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
567 Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
568 else
569 Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
570 PredCst, RHS);
571 // If this folded to a constant expr, we can't do anything.
572 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
573 TrueDirection = ResC->getZExtValue();
574 break;
575 }
576 // If this folded to undef, just go the false way.
577 if (isa<UndefValue>(Res)) {
578 TrueDirection = false;
579 break;
580 }
581
582 // Otherwise, we can't fold this input.
583 PredCst = 0;
584 }
585
586 // If no match, bail out.
587 if (PredCst == 0)
588 return false;
589
590 // See if the cost of duplicating this block is low enough.
591 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
592 if (JumpThreadCost > Threshold) {
593 DOUT << " Not threading BB '" << BB->getNameStart()
594 << "' - Cost is too high: " << JumpThreadCost << "\n";
595 return false;
596 }
597
598 // If so, we can actually do this threading. Merge any common predecessors
599 // that will act the same.
600 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
601
602 // Next, get our successor.
603 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
604
Chris Lattnereede65c2008-04-25 04:12:29 +0000605 // If threading to the same block as we come from, we would infinite loop.
606 if (SuccBB == BB) {
607 DOUT << " Not threading BB '" << BB->getNameStart()
608 << "' - would thread to self!\n";
609 return false;
610 }
611
612
Chris Lattnera5ddb592008-04-22 21:40:39 +0000613 // And finally, do it!
614 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
615 << "' to '" << SuccBB->getNameStart() << "' with cost: "
616 << JumpThreadCost << ", across block:\n "
617 << *BB << "\n";
618
619 ThreadEdge(BB, PredBB, SuccBB);
620 ++NumThreads;
621 return true;
622}
623
Chris Lattner6bf77502008-04-22 07:05:46 +0000624
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000625/// ThreadEdge - We have decided that it is safe and profitable to thread an
626/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
627/// change.
628void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
629 BasicBlock *SuccBB) {
630
631 // Jump Threading can not update SSA properties correctly if the values
632 // defined in the duplicated block are used outside of the block itself. For
633 // this reason, we spill all values that are used outside of BB to the stack.
Chris Lattner8554cc22008-05-05 20:21:22 +0000634 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
635 if (!I->isUsedOutsideOfBlock(BB))
636 continue;
637
638 // We found a use of I outside of BB. Create a new stack slot to
639 // break this inter-block usage pattern.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000640 DemoteRegToStack(*I);
Chris Lattner8554cc22008-05-05 20:21:22 +0000641 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000642
643 // We are going to have to map operands from the original BB block to the new
644 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
645 // account for entry from PredBB.
646 DenseMap<Instruction*, Value*> ValueMapping;
647
648 BasicBlock *NewBB =
649 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
650 NewBB->moveAfter(PredBB);
651
652 BasicBlock::iterator BI = BB->begin();
653 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
654 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
655
656 // Clone the non-phi instructions of BB into NewBB, keeping track of the
657 // mapping and using it to remap operands in the cloned instructions.
658 for (; !isa<TerminatorInst>(BI); ++BI) {
659 Instruction *New = BI->clone();
660 New->setName(BI->getNameStart());
661 NewBB->getInstList().push_back(New);
662 ValueMapping[BI] = New;
663
664 // Remap operands to patch up intra-block references.
665 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
666 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
667 if (Value *Remapped = ValueMapping[Inst])
668 New->setOperand(i, Remapped);
669 }
670
671 // We didn't copy the terminator from BB over to NewBB, because there is now
672 // an unconditional jump to SuccBB. Insert the unconditional jump.
673 BranchInst::Create(SuccBB, NewBB);
674
675 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
676 // PHI nodes for NewBB now.
677 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
678 PHINode *PN = cast<PHINode>(PNI);
679 // Ok, we have a PHI node. Figure out what the incoming value was for the
680 // DestBlock.
681 Value *IV = PN->getIncomingValueForBlock(BB);
682
683 // Remap the value if necessary.
684 if (Instruction *Inst = dyn_cast<Instruction>(IV))
685 if (Value *MappedIV = ValueMapping[Inst])
686 IV = MappedIV;
687 PN->addIncoming(IV, NewBB);
688 }
689
Chris Lattneref0c6742008-12-01 04:48:07 +0000690 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000691 // NewBB instead of BB. This eliminates predecessors from BB, which requires
692 // us to simplify any PHI nodes in BB.
693 TerminatorInst *PredTerm = PredBB->getTerminator();
694 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
695 if (PredTerm->getSuccessor(i) == BB) {
696 BB->removePredecessor(PredBB);
697 PredTerm->setSuccessor(i, NewBB);
698 }
Chris Lattneref0c6742008-12-01 04:48:07 +0000699
700 // At this point, the IR is fully up to date and consistent. Do a quick scan
701 // over the new instructions and zap any that are constants or dead. This
702 // frequently happens because of phi translation.
703 BI = NewBB->begin();
704 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
705 Instruction *Inst = BI++;
706 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
707 Inst->replaceAllUsesWith(C);
708 Inst->eraseFromParent();
709 continue;
710 }
711
712 RecursivelyDeleteTriviallyDeadInstructions(Inst);
713 }
Chris Lattner177480b2008-04-20 21:13:06 +0000714}