blob: eb4a873a464d91e42b1b3c860a65bf9b5b8b2cb5 [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 Lattner2cc67512008-04-21 02:57:57 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Compiler.h"
Chris Lattner177480b2008-04-20 21:13:06 +000024#include "llvm/Support/Debug.h"
Chris Lattner69e067f2008-11-27 05:07:53 +000025#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000026using namespace llvm;
27
Chris Lattnerbd3401f2008-04-20 22:39:42 +000028STATISTIC(NumThreads, "Number of jumps threaded");
29STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner8383a7b2008-04-20 20:35:01 +000030
Chris Lattner177480b2008-04-20 21:13:06 +000031static cl::opt<unsigned>
32Threshold("jump-threading-threshold",
33 cl::desc("Max block size to duplicate for jump threading"),
34 cl::init(6), cl::Hidden);
35
Chris Lattner8383a7b2008-04-20 20:35:01 +000036namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000037 /// This pass performs 'jump threading', which looks at blocks that have
38 /// multiple predecessors and multiple successors. If one or more of the
39 /// predecessors of the block can be proven to always jump to one of the
40 /// successors, we forward the edge from the predecessor to the successor by
41 /// duplicating the contents of this block.
42 ///
43 /// An example of when this can occur is code like this:
44 ///
45 /// if () { ...
46 /// X = 4;
47 /// }
48 /// if (X < 3) {
49 ///
50 /// In this case, the unconditional branch at the end of the first if can be
51 /// revectored to the false side of the second if.
52 ///
Chris Lattner8383a7b2008-04-20 20:35:01 +000053 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
54 public:
55 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000056 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000057
58 bool runOnFunction(Function &F);
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000059 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +000060 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000061 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
62
Chris Lattnerd38c14e2008-04-22 06:36:15 +000063 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerae65b3c2008-04-22 20:46:09 +000064 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattnera5ddb592008-04-22 21:40:39 +000065 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner69e067f2008-11-27 05:07:53 +000066
67 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000068 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000069}
70
Dan Gohman844731a2008-05-13 00:00:25 +000071char JumpThreading::ID = 0;
72static RegisterPass<JumpThreading>
73X("jump-threading", "Jump Threading");
74
Chris Lattner8383a7b2008-04-20 20:35:01 +000075// Public interface to the Jump Threading pass
76FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
77
78/// runOnFunction - Top level algorithm.
79///
80bool JumpThreading::runOnFunction(Function &F) {
Chris Lattner177480b2008-04-20 21:13:06 +000081 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattnerbd3401f2008-04-20 22:39:42 +000082
83 bool AnotherIteration = true, EverChanged = false;
84 while (AnotherIteration) {
85 AnotherIteration = false;
86 bool Changed = false;
87 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000088 while (ProcessBlock(I))
Chris Lattnerbd3401f2008-04-20 22:39:42 +000089 Changed = true;
90 AnotherIteration = Changed;
91 EverChanged |= Changed;
92 }
93 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +000094}
Chris Lattner177480b2008-04-20 21:13:06 +000095
Chris Lattner6bf77502008-04-22 07:05:46 +000096/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
97/// value for the PHI, factor them together so we get one block to thread for
98/// the whole group.
99/// This is important for things like "phi i1 [true, true, false, true, x]"
100/// where we only need to clone the block for the true blocks once.
101///
102BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
103 SmallVector<BasicBlock*, 16> CommonPreds;
104 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
105 if (PN->getIncomingValue(i) == CstVal)
106 CommonPreds.push_back(PN->getIncomingBlock(i));
107
108 if (CommonPreds.size() == 1)
109 return CommonPreds[0];
110
111 DOUT << " Factoring out " << CommonPreds.size()
112 << " common predecessors.\n";
113 return SplitBlockPredecessors(PN->getParent(),
114 &CommonPreds[0], CommonPreds.size(),
115 ".thr_comm", this);
116}
117
118
Chris Lattner177480b2008-04-20 21:13:06 +0000119/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
120/// thread across it.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000121static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
Chris Lattner177480b2008-04-20 21:13:06 +0000122 /// Ignore PHI nodes, these will be flattened when duplication happens.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000123 BasicBlock::const_iterator I = BB->getFirstNonPHI();
Chris Lattner177480b2008-04-20 21:13:06 +0000124
125 // Sum up the cost of each instruction until we get to the terminator. Don't
126 // include the terminator because the copy won't include it.
127 unsigned Size = 0;
128 for (; !isa<TerminatorInst>(I); ++I) {
129 // Debugger intrinsics don't incur code size.
130 if (isa<DbgInfoIntrinsic>(I)) continue;
131
132 // If this is a pointer->pointer bitcast, it is free.
133 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
134 continue;
135
136 // All other instructions count for at least one unit.
137 ++Size;
138
139 // Calls are more expensive. If they are non-intrinsic calls, we model them
140 // as having cost of 4. If they are a non-vector intrinsic, we model them
141 // as having cost of 2 total, and if they are a vector intrinsic, we model
142 // them as having cost 1.
143 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
144 if (!isa<IntrinsicInst>(CI))
145 Size += 3;
146 else if (isa<VectorType>(CI->getType()))
147 Size += 1;
148 }
149 }
150
151 // Threading through a switch statement is particularly profitable. If this
152 // block ends in a switch, decrease its cost to make it more likely to happen.
153 if (isa<SwitchInst>(I))
154 Size = Size > 6 ? Size-6 : 0;
155
156 return Size;
157}
158
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000159/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000160/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000161bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000162 // If this block has a single predecessor, and if that pred has a single
163 // successor, merge the blocks. This encourages recursive jump threading
164 // because now the condition in this block can be threaded through
165 // predecessors of our predecessor block.
166 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
167 if (SinglePred->getTerminator()->getNumSuccessors() == 1) {
168 MergeBasicBlockIntoOnlyPred(BB);
169 return true;
170 }
171
Matthijs Kooijman6e7b3222008-05-20 07:26:45 +0000172 // See if this block ends with a branch or switch. If so, see if the
Chris Lattner177480b2008-04-20 21:13:06 +0000173 // condition is a phi node. If so, and if an entry of the phi node is a
174 // constant, we can thread the block.
175 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000176 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
177 // Can't thread an unconditional jump.
178 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000179 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000180 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000181 Condition = SI->getCondition();
182 else
183 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000184
185 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000186 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000187 // other blocks.
188 if (isa<ConstantInt>(Condition)) {
189 DOUT << " In block '" << BB->getNameStart()
190 << "' folding terminator: " << *BB->getTerminator();
191 ++NumFolds;
192 ConstantFoldTerminator(BB);
193 return true;
194 }
195
196 // If there is only a single predecessor of this block, nothing to fold.
197 if (BB->getSinglePredecessor())
198 return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000199
200 // See if this is a phi node in the current block.
201 PHINode *PN = dyn_cast<PHINode>(Condition);
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000202 if (PN && PN->getParent() == BB)
203 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000204
Chris Lattner6bf77502008-04-22 07:05:46 +0000205 // If this is a conditional branch whose condition is and/or of a phi, try to
206 // simplify it.
207 if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
208 if ((CondI->getOpcode() == Instruction::And ||
209 CondI->getOpcode() == Instruction::Or) &&
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000210 isa<BranchInst>(BB->getTerminator()) &&
211 ProcessBranchOnLogical(CondI, BB,
212 CondI->getOpcode() == Instruction::And))
213 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000214 }
215
Chris Lattnera5ddb592008-04-22 21:40:39 +0000216 // If we have "br (phi != 42)" and the phi node has any constant values as
217 // operands, we can thread through this block.
218 if (CmpInst *CondCmp = dyn_cast<CmpInst>(Condition))
219 if (isa<PHINode>(CondCmp->getOperand(0)) &&
220 isa<Constant>(CondCmp->getOperand(1)) &&
221 ProcessBranchOnCompare(CondCmp, BB))
222 return true;
Chris Lattner69e067f2008-11-27 05:07:53 +0000223
224 // Check for some cases that are worth simplifying. Right now we want to look
225 // for loads that are used by a switch or by the condition for the branch. If
226 // we see one, check to see if it's partially redundant. If so, insert a PHI
227 // which can then be used to thread the values.
228 //
229 // This is particularly important because reg2mem inserts loads and stores all
230 // over the place, and this blocks jump threading if we don't zap them.
231 Value *SimplifyValue = Condition;
232 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
233 if (isa<Constant>(CondCmp->getOperand(1)))
234 SimplifyValue = CondCmp->getOperand(0);
235
236 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
237 if (SimplifyPartiallyRedundantLoad(LI))
238 return true;
239
240 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
241 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000242
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000243 return false;
244}
245
Chris Lattner69e067f2008-11-27 05:07:53 +0000246
247/// FindAvailableLoadedValue - Scan backwards from ScanFrom checking to see if
248/// we have the value at the memory address *Ptr locally available within a
249/// small number of instructions. If the value is available, return it.
250///
251/// If not, return the iterator for the last validated instruction that the
252/// value would be live through. If we scanned the entire block, ScanFrom would
253/// be left at begin().
254///
255/// FIXME: Move this to transform utils and use from
256/// InstCombiner::visitLoadInst. It would also be nice to optionally take AA so
257/// that GVN could do this.
258static Value *FindAvailableLoadedValue(Value *Ptr,
259 BasicBlock *ScanBB,
260 BasicBlock::iterator &ScanFrom) {
261
262 unsigned NumToScan = 6;
263 while (ScanFrom != ScanBB->begin()) {
264 // Don't scan huge blocks.
265 if (--NumToScan == 0) return 0;
266
267 Instruction *Inst = --ScanFrom;
268
269 // If this is a load of Ptr, the loaded value is available.
270 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
271 if (LI->getOperand(0) == Ptr)
272 return LI;
273
274 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
275 // If this is a store through Ptr, the value is available!
276 if (SI->getOperand(1) == Ptr)
277 return SI->getOperand(0);
278
279 // If Ptr is an alloca and this is a store to a different alloca, ignore
280 // the store. This is a trivial form of alias analysis that is important
281 // for reg2mem'd code.
282 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
283 (isa<AllocaInst>(SI->getOperand(1)) ||
284 isa<GlobalVariable>(SI->getOperand(1))))
285 continue;
286
287 // Otherwise the store that may or may not alias the pointer, bail out.
288 ++ScanFrom;
289 return 0;
290 }
291
292
293 // If this is some other instruction that may clobber Ptr, bail out.
294 if (Inst->mayWriteToMemory()) {
295 // May modify the pointer, bail out.
296 ++ScanFrom;
297 return 0;
298 }
299 }
300
301 // Got to the start of the block, we didn't find it, but are done for this
302 // block.
303 return 0;
304}
305
306
307/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
308/// load instruction, eliminate it by replacing it with a PHI node. This is an
309/// important optimization that encourages jump threading, and needs to be run
310/// interlaced with other jump threading tasks.
311bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
312 // Don't hack volatile loads.
313 if (LI->isVolatile()) return false;
314
315 // If the load is defined in a block with exactly one predecessor, it can't be
316 // partially redundant.
317 BasicBlock *LoadBB = LI->getParent();
318 if (LoadBB->getSinglePredecessor())
319 return false;
320
321 Value *LoadedPtr = LI->getOperand(0);
322
323 // If the loaded operand is defined in the LoadBB, it can't be available.
324 // FIXME: Could do PHI translation, that would be fun :)
325 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
326 if (PtrOp->getParent() == LoadBB)
327 return false;
328
329 // Scan a few instructions up from the load, to see if it is obviously live at
330 // the entry to its block.
331 BasicBlock::iterator BBIt = LI;
332
333 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt)) {
334 // If the value if the load is locally available within the block, just use
335 // it. This frequently occurs for reg2mem'd allocas.
336 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
337 LI->replaceAllUsesWith(AvailableVal);
338 LI->eraseFromParent();
339 return true;
340 }
341
342 // Otherwise, if we scanned the whole block and got to the top of the block,
343 // we know the block is locally transparent to the load. If not, something
344 // might clobber its value.
345 if (BBIt != LoadBB->begin())
346 return false;
347
348
349 SmallPtrSet<BasicBlock*, 8> PredsScanned;
350 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
351 AvailablePredsTy AvailablePreds;
352 BasicBlock *OneUnavailablePred = 0;
353
354 // If we got here, the loaded value is transparent through to the start of the
355 // block. Check to see if it is available in any of the predecessor blocks.
356 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
357 PI != PE; ++PI) {
358 BasicBlock *PredBB = *PI;
359
360 // If we already scanned this predecessor, skip it.
361 if (!PredsScanned.insert(PredBB))
362 continue;
363
364 // Scan the predecessor to see if the value is available in the pred.
365 BBIt = PredBB->end();
366 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt);
367 if (!PredAvailable) {
368 OneUnavailablePred = PredBB;
369 continue;
370 }
371
372 // If so, this load is partially redundant. Remember this info so that we
373 // can create a PHI node.
374 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
375 }
376
377 // If the loaded value isn't available in any predecessor, it isn't partially
378 // redundant.
379 if (AvailablePreds.empty()) return false;
380
381 // Okay, the loaded value is available in at least one (and maybe all!)
382 // predecessors. If the value is unavailable in more than one unique
383 // predecessor, we want to insert a merge block for those common predecessors.
384 // This ensures that we only have to insert one reload, thus not increasing
385 // code size.
386 BasicBlock *UnavailablePred = 0;
387
388 // If there is exactly one predecessor where the value is unavailable, the
389 // already computed 'OneUnavailablePred' block is it. If it ends in an
390 // unconditional branch, we know that it isn't a critical edge.
391 if (PredsScanned.size() == AvailablePreds.size()+1 &&
392 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
393 UnavailablePred = OneUnavailablePred;
394 } else if (PredsScanned.size() != AvailablePreds.size()) {
395 // Otherwise, we had multiple unavailable predecessors or we had a critical
396 // edge from the one.
397 SmallVector<BasicBlock*, 8> PredsToSplit;
398 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
399
400 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
401 AvailablePredSet.insert(AvailablePreds[i].first);
402
403 // Add all the unavailable predecessors to the PredsToSplit list.
404 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
405 PI != PE; ++PI)
406 if (!AvailablePredSet.count(*PI))
407 PredsToSplit.push_back(*PI);
408
409 // Split them out to their own block.
410 UnavailablePred =
411 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
412 "thread-split", this);
413 }
414
415 // If the value isn't available in all predecessors, then there will be
416 // exactly one where it isn't available. Insert a load on that edge and add
417 // it to the AvailablePreds list.
418 if (UnavailablePred) {
419 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
420 "Can't handle critical edge here!");
421 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
422 UnavailablePred->getTerminator());
423 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
424 }
425
426 // Now we know that each predecessor of this block has a value in
427 // AvailablePreds, sort them for efficient access as we're walking the preds.
428 std::sort(AvailablePreds.begin(), AvailablePreds.end());
429
430 // Create a PHI node at the start of the block for the PRE'd load value.
431 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
432 PN->takeName(LI);
433
434 // Insert new entries into the PHI for each predecessor. A single block may
435 // have multiple entries here.
436 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
437 ++PI) {
438 AvailablePredsTy::iterator I =
439 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
440 std::make_pair(*PI, (Value*)0));
441
442 assert(I != AvailablePreds.end() && I->first == *PI &&
443 "Didn't find entry for predecessor!");
444
445 PN->addIncoming(I->second, I->first);
446 }
447
448 //cerr << "PRE: " << *LI << *PN << "\n";
449
450 LI->replaceAllUsesWith(PN);
451 LI->eraseFromParent();
452
453 return true;
454}
455
456
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000457/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
458/// the current block. See if there are any simplifications we can do based on
459/// inputs to the phi node.
460///
461bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattnerf9065a92008-04-20 21:18:09 +0000462 // See if the phi node has any constant values. If so, we can determine where
463 // the corresponding predecessor will branch.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000464 ConstantInt *PredCst = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000465 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
466 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
Chris Lattnerf9065a92008-04-20 21:18:09 +0000467 break;
Chris Lattnerf9065a92008-04-20 21:18:09 +0000468
469 // If no incoming value has a constant, we don't know the destination of any
470 // predecessors.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000471 if (PredCst == 0)
Chris Lattnerf9065a92008-04-20 21:18:09 +0000472 return false;
473
Chris Lattner177480b2008-04-20 21:13:06 +0000474 // See if the cost of duplicating this block is low enough.
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000475 BasicBlock *BB = PN->getParent();
Chris Lattner177480b2008-04-20 21:13:06 +0000476 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
477 if (JumpThreadCost > Threshold) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000478 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattnerf9065a92008-04-20 21:18:09 +0000479 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner177480b2008-04-20 21:13:06 +0000480 return false;
481 }
Chris Lattner177480b2008-04-20 21:13:06 +0000482
Chris Lattner6bf77502008-04-22 07:05:46 +0000483 // If so, we can actually do this threading. Merge any common predecessors
484 // that will act the same.
485 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
486
487 // Next, figure out which successor we are threading to.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000488 BasicBlock *SuccBB;
489 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
490 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
491 else {
492 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
493 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
494 }
495
Chris Lattnereede65c2008-04-25 04:12:29 +0000496 // If threading to the same block as we come from, we would infinite loop.
497 if (SuccBB == BB) {
498 DOUT << " Not threading BB '" << BB->getNameStart()
499 << "' - would thread to self!\n";
500 return false;
501 }
502
Chris Lattner6bf77502008-04-22 07:05:46 +0000503 // And finally, do it!
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000504 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
505 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
506 << ", across block:\n "
Chris Lattner6bf77502008-04-22 07:05:46 +0000507 << *BB << "\n";
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000508
509 ThreadEdge(BB, PredBB, SuccBB);
510 ++NumThreads;
511 return true;
512}
513
Chris Lattner6bf77502008-04-22 07:05:46 +0000514/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
515/// whose condition is an AND/OR where one side is PN. If PN has constant
516/// operands that permit us to evaluate the condition for some operand, thread
517/// through the block. For example with:
518/// br (and X, phi(Y, Z, false))
519/// the predecessor corresponding to the 'false' will always jump to the false
520/// destination of the branch.
521///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000522bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
523 bool isAnd) {
524 // If this is a binary operator tree of the same AND/OR opcode, check the
525 // LHS/RHS.
526 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
Duncan Sands43e2a032008-05-27 11:50:51 +0000527 if ((isAnd && BO->getOpcode() == Instruction::And) ||
528 (!isAnd && BO->getOpcode() == Instruction::Or)) {
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000529 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
530 return true;
531 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
532 return true;
533 }
534
535 // If this isn't a PHI node, we can't handle it.
536 PHINode *PN = dyn_cast<PHINode>(V);
537 if (!PN || PN->getParent() != BB) return false;
538
Chris Lattner6bf77502008-04-22 07:05:46 +0000539 // We can only do the simplification for phi nodes of 'false' with AND or
540 // 'true' with OR. See if we have any entries in the phi for this.
541 unsigned PredNo = ~0U;
542 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
543 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
544 if (PN->getIncomingValue(i) == PredCst) {
545 PredNo = i;
546 break;
547 }
548 }
549
550 // If no match, bail out.
551 if (PredNo == ~0U)
552 return false;
553
554 // See if the cost of duplicating this block is low enough.
Chris Lattner6bf77502008-04-22 07:05:46 +0000555 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
556 if (JumpThreadCost > Threshold) {
557 DOUT << " Not threading BB '" << BB->getNameStart()
558 << "' - Cost is too high: " << JumpThreadCost << "\n";
559 return false;
560 }
561
562 // If so, we can actually do this threading. Merge any common predecessors
563 // that will act the same.
564 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
565
566 // Next, figure out which successor we are threading to. If this was an AND,
567 // the constant must be FALSE, and we must be targeting the 'false' block.
568 // If this is an OR, the constant must be TRUE, and we must be targeting the
569 // 'true' block.
570 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
571
Chris Lattnereede65c2008-04-25 04:12:29 +0000572 // If threading to the same block as we come from, we would infinite loop.
573 if (SuccBB == BB) {
574 DOUT << " Not threading BB '" << BB->getNameStart()
575 << "' - would thread to self!\n";
576 return false;
577 }
578
Chris Lattner6bf77502008-04-22 07:05:46 +0000579 // And finally, do it!
580 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
581 << "' to '" << SuccBB->getNameStart() << "' with cost: "
582 << JumpThreadCost << ", across block:\n "
583 << *BB << "\n";
584
585 ThreadEdge(BB, PredBB, SuccBB);
586 ++NumThreads;
587 return true;
588}
589
Chris Lattnera5ddb592008-04-22 21:40:39 +0000590/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
591/// node and a constant. If the PHI node contains any constants as inputs, we
592/// can fold the compare for that edge and thread through it.
593bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
594 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
595 Constant *RHS = cast<Constant>(Cmp->getOperand(1));
596
597 // If the phi isn't in the current block, an incoming edge to this block
598 // doesn't control the destination.
599 if (PN->getParent() != BB)
600 return false;
601
602 // We can do this simplification if any comparisons fold to true or false.
603 // See if any do.
604 Constant *PredCst = 0;
605 bool TrueDirection = false;
606 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
607 PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
608 if (PredCst == 0) continue;
609
610 Constant *Res;
611 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
612 Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
613 else
614 Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
615 PredCst, RHS);
616 // If this folded to a constant expr, we can't do anything.
617 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
618 TrueDirection = ResC->getZExtValue();
619 break;
620 }
621 // If this folded to undef, just go the false way.
622 if (isa<UndefValue>(Res)) {
623 TrueDirection = false;
624 break;
625 }
626
627 // Otherwise, we can't fold this input.
628 PredCst = 0;
629 }
630
631 // If no match, bail out.
632 if (PredCst == 0)
633 return false;
634
635 // See if the cost of duplicating this block is low enough.
636 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
637 if (JumpThreadCost > Threshold) {
638 DOUT << " Not threading BB '" << BB->getNameStart()
639 << "' - Cost is too high: " << JumpThreadCost << "\n";
640 return false;
641 }
642
643 // If so, we can actually do this threading. Merge any common predecessors
644 // that will act the same.
645 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
646
647 // Next, get our successor.
648 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
649
Chris Lattnereede65c2008-04-25 04:12:29 +0000650 // If threading to the same block as we come from, we would infinite loop.
651 if (SuccBB == BB) {
652 DOUT << " Not threading BB '" << BB->getNameStart()
653 << "' - would thread to self!\n";
654 return false;
655 }
656
657
Chris Lattnera5ddb592008-04-22 21:40:39 +0000658 // And finally, do it!
659 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
660 << "' to '" << SuccBB->getNameStart() << "' with cost: "
661 << JumpThreadCost << ", across block:\n "
662 << *BB << "\n";
663
664 ThreadEdge(BB, PredBB, SuccBB);
665 ++NumThreads;
666 return true;
667}
668
Chris Lattner6bf77502008-04-22 07:05:46 +0000669
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000670/// ThreadEdge - We have decided that it is safe and profitable to thread an
671/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
672/// change.
673void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
674 BasicBlock *SuccBB) {
675
676 // Jump Threading can not update SSA properties correctly if the values
677 // defined in the duplicated block are used outside of the block itself. For
678 // this reason, we spill all values that are used outside of BB to the stack.
Chris Lattner8554cc22008-05-05 20:21:22 +0000679 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
680 if (!I->isUsedOutsideOfBlock(BB))
681 continue;
682
683 // We found a use of I outside of BB. Create a new stack slot to
684 // break this inter-block usage pattern.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000685 DemoteRegToStack(*I);
Chris Lattner8554cc22008-05-05 20:21:22 +0000686 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000687
688 // We are going to have to map operands from the original BB block to the new
689 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
690 // account for entry from PredBB.
691 DenseMap<Instruction*, Value*> ValueMapping;
692
693 BasicBlock *NewBB =
694 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
695 NewBB->moveAfter(PredBB);
696
697 BasicBlock::iterator BI = BB->begin();
698 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
699 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
700
701 // Clone the non-phi instructions of BB into NewBB, keeping track of the
702 // mapping and using it to remap operands in the cloned instructions.
703 for (; !isa<TerminatorInst>(BI); ++BI) {
704 Instruction *New = BI->clone();
705 New->setName(BI->getNameStart());
706 NewBB->getInstList().push_back(New);
707 ValueMapping[BI] = New;
708
709 // Remap operands to patch up intra-block references.
710 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
711 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
712 if (Value *Remapped = ValueMapping[Inst])
713 New->setOperand(i, Remapped);
714 }
715
716 // We didn't copy the terminator from BB over to NewBB, because there is now
717 // an unconditional jump to SuccBB. Insert the unconditional jump.
718 BranchInst::Create(SuccBB, NewBB);
719
720 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
721 // PHI nodes for NewBB now.
722 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
723 PHINode *PN = cast<PHINode>(PNI);
724 // Ok, we have a PHI node. Figure out what the incoming value was for the
725 // DestBlock.
726 Value *IV = PN->getIncomingValueForBlock(BB);
727
728 // Remap the value if necessary.
729 if (Instruction *Inst = dyn_cast<Instruction>(IV))
730 if (Value *MappedIV = ValueMapping[Inst])
731 IV = MappedIV;
732 PN->addIncoming(IV, NewBB);
733 }
734
735 // Finally, NewBB is good to go. Update the terminator of PredBB to jump to
736 // NewBB instead of BB. This eliminates predecessors from BB, which requires
737 // us to simplify any PHI nodes in BB.
738 TerminatorInst *PredTerm = PredBB->getTerminator();
739 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
740 if (PredTerm->getSuccessor(i) == BB) {
741 BB->removePredecessor(PredBB);
742 PredTerm->setSuccessor(i, NewBB);
743 }
Chris Lattner177480b2008-04-20 21:13:06 +0000744}