blob: 498d3785f9713f8957b120b78b0d74eeadfdbb34 [file] [log] [blame]
Chris Lattnerf48f7772004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf48f7772004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf48f7772004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
11// to have multiple loops. For example, it turns the left into the right code:
12//
13// for (...) if (lic)
14// A for (...)
15// if (lic) A; B; C
16// B else
17// C for (...)
18// A; C
19//
20// This can increase the size of the code exponentially (doubling it every time
21// a loop is unswitched) so we only unswitch if the resultant code will be
22// smaller than a threshold.
23//
24// This pass expects LICM to be run before it to hoist invariant conditions out
25// of the loop, to make the unswitching opportunity obvious.
26//
27//===----------------------------------------------------------------------===//
28
29#define DEBUG_TYPE "loop-unswitch"
30#include "llvm/Transforms/Scalar.h"
31#include "llvm/Constants.h"
Reid Spencera94d3942007-01-19 21:13:56 +000032#include "llvm/DerivedTypes.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000033#include "llvm/Function.h"
34#include "llvm/Instructions.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000035#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000036#include "llvm/Analysis/LoopInfo.h"
Devang Patel901a27d2007-03-07 00:26:10 +000037#include "llvm/Analysis/LoopPass.h"
Devang Patel3304e462007-06-28 00:49:00 +000038#include "llvm/Analysis/Dominators.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000039#include "llvm/Transforms/Utils/Cloning.h"
40#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerec6b40a2006-02-10 19:08:15 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
Devang Patel97517ff2007-02-26 20:22:50 +000043#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000044#include "llvm/ADT/PostOrderIterator.h"
Chris Lattner89762192006-02-09 20:15:48 +000045#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000046#include "llvm/Support/Compiler.h"
47#include "llvm/Support/Debug.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000048#include <algorithm>
Chris Lattner2826e052006-02-09 19:14:52 +000049#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000050using namespace llvm;
51
Chris Lattner79a42ac2006-12-19 21:40:18 +000052STATISTIC(NumBranches, "Number of branches unswitched");
53STATISTIC(NumSwitches, "Number of switches unswitched");
54STATISTIC(NumSelects , "Number of selects unswitched");
55STATISTIC(NumTrivial , "Number of unswitches that are trivial");
56STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
57
Chris Lattnerf48f7772004-04-19 18:07:02 +000058namespace {
Chris Lattner89762192006-02-09 20:15:48 +000059 cl::opt<unsigned>
60 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
61 cl::init(10), cl::Hidden);
62
Devang Patel901a27d2007-03-07 00:26:10 +000063 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +000064 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +000065 LPPassManager *LPM;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000066
Devang Patel901a27d2007-03-07 00:26:10 +000067 // LoopProcessWorklist - Used to check if second loop needs processing
68 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000069 std::vector<Loop*> LoopProcessWorklist;
Devang Patel97517ff2007-02-26 20:22:50 +000070 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel506310d2007-06-06 00:21:03 +000071
72 bool OptimizeForSize;
Chris Lattnerf48f7772004-04-19 18:07:02 +000073 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000074 static char ID; // Pass ID, replacement for typeid
Devang Patel506310d2007-06-06 00:21:03 +000075 LoopUnswitch(bool Os = false) :
76 LoopPass((intptr_t)&ID), OptimizeForSize(Os) {}
Devang Patel09f162c2007-05-01 21:15:47 +000077
Devang Patel901a27d2007-03-07 00:26:10 +000078 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattnerf48f7772004-04-19 18:07:02 +000079
80 /// This transformation requires natural loop information & requires that
81 /// loop preheaders be inserted into the CFG...
82 ///
83 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000085 AU.addPreservedID(LoopSimplifyID);
Devang Patel3304e462007-06-28 00:49:00 +000086 AU.addPreserved<DominatorTree>();
Devang Patel0975c6d2007-06-29 23:11:49 +000087 AU.addPreserved<DominanceFrontier>();
Chris Lattnerf48f7772004-04-19 18:07:02 +000088 AU.addRequired<LoopInfo>();
89 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000090 AU.addRequiredID(LCSSAID);
91 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000092 }
93
94 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000095 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
96 /// remove it.
97 void RemoveLoopFromWorklist(Loop *L) {
98 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
99 LoopProcessWorklist.end(), L);
100 if (I != LoopProcessWorklist.end())
101 LoopProcessWorklist.erase(I);
102 }
103
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000104 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000105 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +0000106 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000107 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000108 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000109 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000110 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000111
112 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
113 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000114
115 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
116 BasicBlock *TrueDest,
117 BasicBlock *FalseDest,
118 Instruction *InsertPt);
119
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000120 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000121 void RemoveBlockIfDead(BasicBlock *BB,
122 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000123 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000124 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000125 char LoopUnswitch::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000126 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000127}
128
Devang Patel506310d2007-06-06 00:21:03 +0000129LoopPass *llvm::createLoopUnswitchPass(bool Os) {
130 return new LoopUnswitch(Os);
131}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000132
133/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
134/// invariant in the loop, or has an invariant piece, return the invariant.
135/// Otherwise, return null.
136static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
137 // Constants should be folded, not unswitched on!
138 if (isa<Constant>(Cond)) return false;
Devang Patel3c723c82007-06-28 00:44:10 +0000139
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000140 // TODO: Handle: br (VARIANT|INVARIANT).
141 // TODO: Hoist simple expressions out of loops.
142 if (L->isLoopInvariant(Cond)) return Cond;
143
144 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
145 if (BO->getOpcode() == Instruction::And ||
146 BO->getOpcode() == Instruction::Or) {
147 // If either the left or right side is invariant, we can unswitch on this,
148 // which will cause the branch to go away in one loop and the condition to
149 // simplify in the other one.
150 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
151 return LHS;
152 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
153 return RHS;
154 }
155
156 return 0;
157}
158
Devang Patel901a27d2007-03-07 00:26:10 +0000159bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000160 assert(L->isLCSSAForm());
Devang Patel901a27d2007-03-07 00:26:10 +0000161 LI = &getAnalysis<LoopInfo>();
162 LPM = &LPM_Ref;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000163 bool Changed = false;
164
165 // Loop over all of the basic blocks in the loop. If we find an interior
166 // block that is branching on a loop-invariant condition, we can unswitch this
167 // loop.
168 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
169 I != E; ++I) {
170 TerminatorInst *TI = (*I)->getTerminator();
171 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
172 // If this isn't branching on an invariant condition, we can't unswitch
173 // it.
174 if (BI->isConditional()) {
175 // See if this, or some part of it, is loop invariant. If so, we can
176 // unswitch on it if we desire.
177 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000178 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000179 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000180 ++NumBranches;
181 return true;
182 }
183 }
184 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
185 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
186 if (LoopCond && SI->getNumCases() > 1) {
187 // Find a value to unswitch on:
188 // FIXME: this should chose the most expensive case!
189 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000190 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000191 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000192 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000193
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000194 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
195 ++NumSwitches;
196 return true;
197 }
198 }
199 }
200
201 // Scan the instructions to check for unswitchable values.
202 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
203 BBI != E; ++BBI)
204 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
205 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000206 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000207 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000208 ++NumSelects;
209 return true;
210 }
211 }
212 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000213
214 assert(L->isLCSSAForm());
215
Chris Lattnerf48f7772004-04-19 18:07:02 +0000216 return Changed;
217}
218
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000219/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
220/// 1. Exit the loop with no side effects.
221/// 2. Branch to the latch block with no side-effects.
222///
223/// If these conditions are true, we return true and set ExitBB to the block we
224/// exit through.
225///
226static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
227 BasicBlock *&ExitBB,
228 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000229 if (!Visited.insert(BB).second) {
230 // Already visited and Ok, end of recursion.
231 return true;
232 } else if (!L->contains(BB)) {
233 // Otherwise, this is a loop exit, this is fine so long as this is the
234 // first exit.
235 if (ExitBB != 0) return false;
236 ExitBB = BB;
237 return true;
238 }
239
240 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000241 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000242 // Check to see if the successor is a trivial loop exit.
243 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
244 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000245 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000246
247 // Okay, everything after this looks good, check to make sure that this block
248 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000249 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000250 if (I->mayWriteToMemory())
251 return false;
252
253 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000254}
255
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000256/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
257/// leads to an exit from the specified loop, and has no side-effects in the
258/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000259static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
260 std::set<BasicBlock*> Visited;
261 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000262 BasicBlock *ExitBB = 0;
263 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
264 return ExitBB;
265 return 0;
266}
Chris Lattner6e263152006-02-10 02:30:37 +0000267
Chris Lattnered7a67b2006-02-10 01:24:09 +0000268/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
269/// trivial: that is, that the condition controls whether or not the loop does
270/// anything at all. If this is a trivial condition, unswitching produces no
271/// code duplications (equivalently, it produces a simpler loop and a new empty
272/// loop, which gets deleted).
273///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000274/// If this is a trivial condition, return true, otherwise return false. When
275/// returning true, this sets Cond and Val to the condition that controls the
276/// trivial condition: when Cond dynamically equals Val, the loop is known to
277/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
278/// Cond == Val.
279///
280static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000281 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000282 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000283 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000284
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000285 BasicBlock *LoopExitBB = 0;
286 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
287 // If the header block doesn't end with a conditional branch on Cond, we
288 // can't handle it.
289 if (!BI->isConditional() || BI->getCondition() != Cond)
290 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000291
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000292 // Check to see if a successor of the branch is guaranteed to go to the
293 // latch block or exit through a one exit block without having any
294 // side-effects. If so, determine the value of Cond that causes it to do
295 // this.
296 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000297 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000298 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000299 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000300 }
301 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
302 // If this isn't a switch on Cond, we can't handle it.
303 if (SI->getCondition() != Cond) return false;
304
305 // Check to see if a successor of the switch is guaranteed to go to the
306 // latch block or exit through a one exit block without having any
307 // side-effects. If so, determine the value of Cond that causes it to do
308 // this. Note that we can't trivially unswitch on the default case.
309 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
310 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
311 // Okay, we found a trivial case, remember the value that is trivial.
312 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000313 break;
314 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000315 }
316
Chris Lattnere5521db2006-02-22 23:55:00 +0000317 // If we didn't find a single unique LoopExit block, or if the loop exit block
318 // contains phi nodes, this isn't trivial.
319 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000320 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000321
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000322 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000323
324 // We already know that nothing uses any scalar values defined inside of this
325 // loop. As such, we just have to check to see if this loop will execute any
326 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000327 // part of the loop that the code *would* execute. We already checked the
328 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000329 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
330 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000331 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000332 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000333}
334
335/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
336/// we choose to unswitch the specified loop on the specified value.
337///
338unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
339 // If the condition is trivial, always unswitch. There is no code growth for
340 // this case.
341 if (IsTrivialUnswitchCondition(L, LIC))
342 return 0;
343
Owen Anderson18e816f2006-06-28 17:47:50 +0000344 // FIXME: This is really overly conservative. However, more liberal
345 // estimations have thus far resulted in excessive unswitching, which is bad
346 // both in compile time and in code size. This should be replaced once
347 // someone figures out how a good estimation.
348 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000349
Chris Lattnered7a67b2006-02-10 01:24:09 +0000350 unsigned Cost = 0;
351 // FIXME: this is brain dead. It should take into consideration code
352 // shrinkage.
353 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
354 I != E; ++I) {
355 BasicBlock *BB = *I;
356 // Do not include empty blocks in the cost calculation. This happen due to
357 // loop canonicalization and will be removed.
358 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
359 continue;
360
361 // Count basic blocks.
362 ++Cost;
363 }
364
365 return Cost;
366}
367
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000368/// UnswitchIfProfitable - We have found that we can unswitch L when
369/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
370/// unswitch the loop, reprocess the pieces, then return true.
371bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
372 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000373 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
Devang Patel506310d2007-06-06 00:21:03 +0000374
375 // Do not do non-trivial unswitch while optimizing for size.
376 if (Cost && OptimizeForSize)
377 return false;
378
Chris Lattner5821a6a2006-03-24 07:14:00 +0000379 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000380 // FIXME: this should estimate growth by the amount of code shared by the
381 // resultant unswitched loops.
382 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000383 DOUT << "NOT unswitching loop %"
384 << L->getHeader()->getName() << ", cost too high: "
385 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000386 return false;
387 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000388
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000389 // If this is a trivial condition to unswitch (which results in no code
390 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000391 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000392 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000393 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
394 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000395 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000396 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000397 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000398
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000399 return true;
400}
401
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000402/// SplitBlock - Split the specified block at the specified instruction - every
403/// thing before SplitPt stays in Old and everything starting with SplitPt moves
404/// to a new block. The two blocks are joined by an unconditional branch and
405/// the loop info is updated.
406///
407BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000408 BasicBlock::iterator SplitIt = SplitPt;
409 while (isa<PHINode>(SplitIt))
410 ++SplitIt;
411 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000412
413 // The new block lives in whichever loop the old one did.
414 if (Loop *L = LI->getLoopFor(Old))
415 L->addBasicBlockToLoop(New, *LI);
Devang Patel95572472007-05-09 08:24:12 +0000416
Devang Patel3304e462007-06-28 00:49:00 +0000417 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
418 DT->addNewBlock(New, Old);
Devang Patel0975c6d2007-06-29 23:11:49 +0000419
420 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
421 DF->splitBlock(Old);
Devang Patel3304e462007-06-28 00:49:00 +0000422
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000423 return New;
424}
425
426
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000427BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
428 TerminatorInst *LatchTerm = BB->getTerminator();
429 unsigned SuccNum = 0;
430 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
431 assert(i != e && "Didn't find edge?");
432 if (LatchTerm->getSuccessor(i) == Succ) {
433 SuccNum = i;
434 break;
435 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000436 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000437
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000438 // If this is a critical edge, let SplitCriticalEdge do it.
Devang Patel3304e462007-06-28 00:49:00 +0000439 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
440 return LatchTerm->getSuccessor(SuccNum);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000441
442 // If the edge isn't critical, then BB has a single successor or Succ has a
443 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000444 BasicBlock::iterator SplitPoint;
445 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
446 // If the successor only has a single pred, split the top of the successor
447 // block.
448 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000449 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000450 } else {
451 // Otherwise, if BB has a single successor, split it at the bottom of the
452 // block.
453 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
454 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000455 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000456 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000457}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000458
Chris Lattnerf48f7772004-04-19 18:07:02 +0000459
460
Misha Brukmanb1c93172005-04-21 23:48:37 +0000461// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000462// current values into those specified by ValueMap.
463//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000464static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000465 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000466 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
467 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000468 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000469 if (It != ValueMap.end()) Op = It->second;
470 I->setOperand(op, Op);
471 }
472}
473
Devang Patel3304e462007-06-28 00:49:00 +0000474// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
475// If Orig is in Loop then find and use Orig dominator's cloned block as NewBB
476// dominator.
477void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig, Loop *L,
Devang Patel0975c6d2007-06-29 23:11:49 +0000478 DominatorTree *DT, DominanceFrontier *DF,
Devang Patel3304e462007-06-28 00:49:00 +0000479 DenseMap<const Value*, Value*> &VM) {
480
481 DomTreeNode *OrigNode = DT->getNode(Orig);
482 if (!OrigNode)
483 return;
484 BasicBlock *OrigIDom = OrigNode->getBlock();
485 BasicBlock *NewIDom = OrigIDom;
486 if (L->contains(OrigIDom)) {
487 if (!DT->getNode(OrigIDom))
Devang Patel0975c6d2007-06-29 23:11:49 +0000488 CloneDomInfo(NewIDom, OrigIDom, L, DT, DF, VM);
Devang Patel3304e462007-06-28 00:49:00 +0000489 NewIDom = cast<BasicBlock>(VM[OrigIDom]);
490 }
Devang Patel6ba5ad42007-06-28 02:05:46 +0000491 if (NewBB == NewIDom) {
492 DT->addNewBlock(NewBB, OrigIDom);
493 DT->changeImmediateDominator(NewBB, NewIDom);
494 } else
495 DT->addNewBlock(NewBB, NewIDom);
Devang Patel0975c6d2007-06-29 23:11:49 +0000496
497 DominanceFrontier::DomSetType NewDFSet;
498 if (DF) {
499 DominanceFrontier::iterator DFI = DF->find(Orig);
500 if ( DFI != DF->end()) {
501 DominanceFrontier::DomSetType S = DFI->second;
502 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
503 I != E; ++I) {
504 BasicBlock *BB = *I;
505 if (L->contains(BB))
506 NewDFSet.insert(cast<BasicBlock>(VM[Orig]));
507 else
508 NewDFSet.insert(BB);
509 }
510 }
511 DF->addBasicBlock(NewBB, NewDFSet);
512 }
Devang Patel3304e462007-06-28 00:49:00 +0000513}
514
Chris Lattnerf48f7772004-04-19 18:07:02 +0000515/// CloneLoop - Recursively clone the specified loop and all of its children,
516/// mapping the blocks with the specified map.
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000517static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000518 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000519 Loop *New = new Loop();
520
Devang Patel901a27d2007-03-07 00:26:10 +0000521 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000522
523 // Add all of the blocks in L to the new loop.
524 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
525 I != E; ++I)
526 if (LI->getLoopFor(*I) == L)
527 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
528
529 // Add all of the subloops to the new loop.
530 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000531 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000532
Chris Lattnerf48f7772004-04-19 18:07:02 +0000533 return New;
534}
535
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000536/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
537/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
538/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000539void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
540 BasicBlock *TrueDest,
541 BasicBlock *FalseDest,
542 Instruction *InsertPt) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000543 // Insert a conditional branch on LIC to the two preheaders. The original
544 // code is the true version and the new code is the false version.
545 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000546 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000547 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000548 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000549 // We want to enter the new loop when the condition is true.
550 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000551
552 // Insert the new branch.
Devang Patel3304e462007-06-28 00:49:00 +0000553 BranchInst *BRI = new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
554
555 // Update dominator info.
Devang Patel0975c6d2007-06-29 23:11:49 +0000556 // BranchVal is a new preheader so it dominates true and false destination
557 // loop headers.
Devang Patel3304e462007-06-28 00:49:00 +0000558 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Devang Patel3304e462007-06-28 00:49:00 +0000559 DT->changeImmediateDominator(TrueDest, BRI->getParent());
560 DT->changeImmediateDominator(FalseDest, BRI->getParent());
561 }
Devang Patel0975c6d2007-06-29 23:11:49 +0000562 // No need to update DominanceFrontier. BRI->getParent() dominated TrueDest
563 // and FalseDest anyway. Now it immediately dominates them.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000564}
565
566
Chris Lattnered7a67b2006-02-10 01:24:09 +0000567/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
568/// condition in it (a cond branch from its header block to its latch block,
569/// where the path through the loop that doesn't execute its body has no
570/// side-effects), unswitch it. This doesn't involve any code duplication, just
571/// moving the conditional branch outside of the loop and updating loop info.
572void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000573 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000574 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000575 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
576 << L->getHeader()->getName() << " [" << L->getBlocks().size()
577 << " blocks] in Function " << L->getHeader()->getParent()->getName()
578 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000579
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000580 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000581 // to insert the conditional branch. We will change 'OrigPH' to have a
582 // conditional branch on Cond.
583 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000584 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000585
586 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000587 // to branch to: this is the exit block out of the loop that we should
588 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000589
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000590 // Split this block now, so that the loop maintains its exit block, and so
591 // that the jump from the preheader can execute the contents of the exit block
592 // without actually branching to it (the exit block should be dominated by the
593 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000594 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000595 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000596
Chris Lattnered7a67b2006-02-10 01:24:09 +0000597 // Okay, now we have a position to branch from and a position to branch to,
598 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000599 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
600 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000601 OrigPH->getTerminator()->eraseFromParent();
602
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000603 // We need to reprocess this loop, it could be unswitched again.
Devang Patel901a27d2007-03-07 00:26:10 +0000604 LPM->redoLoop(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000605
Chris Lattnered7a67b2006-02-10 01:24:09 +0000606 // Now that we know that the loop is never entered when this condition is a
607 // particular value, rewrite the loop with this info. We know that this will
608 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000609 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000610 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000611}
612
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000613/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
614/// equal Val. Split it into loop versions and test the condition outside of
615/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000616void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
617 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000618 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000619 DOUT << "loop-unswitch: Unswitching loop %"
620 << L->getHeader()->getName() << " [" << L->getBlocks().size()
621 << " blocks] in Function " << F->getName()
622 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000623
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000624 // LoopBlocks contains all of the basic blocks of the loop, including the
625 // preheader of the loop, the body of the loop, and the exit blocks of the
626 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000627 std::vector<BasicBlock*> LoopBlocks;
628
629 // First step, split the preheader and exit blocks, and add these blocks to
630 // the LoopBlocks list.
631 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000632 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000633
634 // We want the loop to come after the preheader, but before the exit blocks.
635 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
636
637 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000638 L->getUniqueExitBlocks(ExitBlocks);
639
Owen Andersonf52351e2006-06-26 07:44:36 +0000640 // Split all of the edges from inside the loop to their exit blocks. Update
641 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000642 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000643 BasicBlock *ExitBlock = ExitBlocks[i];
644 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
645
646 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Owen Andersonf52351e2006-06-26 07:44:36 +0000647 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
648 BasicBlock* StartBlock = Preds[j];
649 BasicBlock* EndBlock;
650 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
651 EndBlock = MiddleBlock;
652 MiddleBlock = EndBlock->getSinglePredecessor();;
653 } else {
654 EndBlock = ExitBlock;
655 }
656
657 std::set<PHINode*> InsertedPHIs;
658 PHINode* OldLCSSA = 0;
659 for (BasicBlock::iterator I = EndBlock->begin();
660 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
661 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
662 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
663 OldLCSSA->getName() + ".us-lcssa",
664 MiddleBlock->getTerminator());
665 NewLCSSA->addIncoming(OldValue, StartBlock);
666 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
667 NewLCSSA);
668 InsertedPHIs.insert(NewLCSSA);
669 }
670
Owen Anderson00b974c2006-07-19 03:51:48 +0000671 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000672 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
673 for (BasicBlock::iterator I = MiddleBlock->begin();
674 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
675 ++I) {
676 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
677 OldLCSSA->getName() + ".us-lcssa",
678 InsertPt);
679 OldLCSSA->replaceAllUsesWith(NewLCSSA);
680 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
681 }
682 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000683 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000684
685 // The exit blocks may have been changed due to edge splitting, recompute.
686 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000687 L->getUniqueExitBlocks(ExitBlocks);
688
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000689 // Add exit blocks to the loop blocks.
690 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000691
692 // Next step, clone all of the basic blocks that make up the loop (including
693 // the loop preheader and exit blocks), keeping track of the mapping between
694 // the instructions and blocks.
695 std::vector<BasicBlock*> NewBlocks;
696 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000697 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000698 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000699 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
700 NewBlocks.push_back(New);
701 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000702 }
703
Devang Patel3304e462007-06-28 00:49:00 +0000704 // Update dominator info
Devang Patel0975c6d2007-06-29 23:11:49 +0000705 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
Devang Patel3304e462007-06-28 00:49:00 +0000706 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
707 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
708 BasicBlock *LBB = LoopBlocks[i];
709 BasicBlock *NBB = NewBlocks[i];
Devang Patel0975c6d2007-06-29 23:11:49 +0000710 CloneDomInfo(NBB, LBB, L, DT, DF, ValueMap);
Devang Patel3304e462007-06-28 00:49:00 +0000711 }
712
Chris Lattnerf48f7772004-04-19 18:07:02 +0000713 // Splice the newly inserted blocks into the function right before the
714 // original preheader.
715 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
716 NewBlocks[0], F->end());
717
718 // Now we create the new Loop object for the versioned loop.
Devang Patel901a27d2007-03-07 00:26:10 +0000719 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000720 Loop *ParentLoop = L->getParentLoop();
721 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000722 // Make sure to add the cloned preheader and exit blocks to the parent loop
723 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000724 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
725 }
726
727 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
728 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000729 // The new exit block should be in the same loop as the old one.
730 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
731 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000732
733 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
734 "Exit block should have been split to have one successor!");
735 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
736
737 // If the successor of the exit block had PHI nodes, add an entry for
738 // NewExit.
739 PHINode *PN;
740 for (BasicBlock::iterator I = ExitSucc->begin();
741 (PN = dyn_cast<PHINode>(I)); ++I) {
742 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000743 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000744 if (It != ValueMap.end()) V = It->second;
745 PN->addIncoming(V, NewExit);
746 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000747 }
748
749 // Rewrite the code to refer to itself.
750 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
751 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
752 E = NewBlocks[i]->end(); I != E; ++I)
753 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000754
Chris Lattnerf48f7772004-04-19 18:07:02 +0000755 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000756 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
757 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000758 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000759
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000760 // Emit the new branch that selects between the two versions of this loop.
761 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
762 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000763
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000764 LoopProcessWorklist.push_back(NewLoop);
Devang Patel901a27d2007-03-07 00:26:10 +0000765 LPM->redoLoop(L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000766
767 // Now we rewrite the original code to know that the condition is true and the
768 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000769 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
770
771 // It's possible that simplifying one loop could cause the other to be
772 // deleted. If so, don't simplify it.
773 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
774 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000775}
776
Chris Lattner6fd13622006-02-17 00:31:07 +0000777/// RemoveFromWorklist - Remove all instances of I from the worklist vector
778/// specified.
779static void RemoveFromWorklist(Instruction *I,
780 std::vector<Instruction*> &Worklist) {
781 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
782 Worklist.end(), I);
783 while (WI != Worklist.end()) {
784 unsigned Offset = WI-Worklist.begin();
785 Worklist.erase(WI);
786 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
787 }
788}
789
790/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
791/// program, replacing all uses with V and update the worklist.
792static void ReplaceUsesOfWith(Instruction *I, Value *V,
793 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000794 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000795
796 // Add uses to the worklist, which may be dead now.
797 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
798 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
799 Worklist.push_back(Use);
800
801 // Add users to the worklist which may be simplified now.
802 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
803 UI != E; ++UI)
804 Worklist.push_back(cast<Instruction>(*UI));
805 I->replaceAllUsesWith(V);
806 I->eraseFromParent();
807 RemoveFromWorklist(I, Worklist);
808 ++NumSimplify;
809}
810
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000811/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
812/// information, and remove any dead successors it has.
813///
814void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
815 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000816 if (pred_begin(BB) != pred_end(BB)) {
817 // This block isn't dead, since an edge to BB was just removed, see if there
818 // are any easy simplifications we can do now.
819 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
820 // If it has one pred, fold phi nodes in BB.
821 while (isa<PHINode>(BB->begin()))
822 ReplaceUsesOfWith(BB->begin(),
823 cast<PHINode>(BB->begin())->getIncomingValue(0),
824 Worklist);
825
826 // If this is the header of a loop and the only pred is the latch, we now
827 // have an unreachable loop.
828 if (Loop *L = LI->getLoopFor(BB))
829 if (L->getHeader() == BB && L->contains(Pred)) {
830 // Remove the branch from the latch to the header block, this makes
831 // the header dead, which will make the latch dead (because the header
832 // dominates the latch).
833 Pred->getTerminator()->eraseFromParent();
834 new UnreachableInst(Pred);
835
836 // The loop is now broken, remove it from LI.
837 RemoveLoopFromHierarchy(L);
838
839 // Reprocess the header, which now IS dead.
840 RemoveBlockIfDead(BB, Worklist);
841 return;
842 }
843
844 // If pred ends in a uncond branch, add uncond branch to worklist so that
845 // the two blocks will get merged.
846 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
847 if (BI->isUnconditional())
848 Worklist.push_back(BI);
849 }
850 return;
851 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000852
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000853 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000854
855 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000856 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000857 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000858
859 // Anything that uses the instructions in this basic block should have their
860 // uses replaced with undefs.
861 if (!I->use_empty())
862 I->replaceAllUsesWith(UndefValue::get(I->getType()));
863 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000864
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000865 // If this is the edge to the header block for a loop, remove the loop and
866 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000867 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000868 if (BBLoop->getLoopLatch() == BB)
869 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000870 }
871
872 // Remove the block from the loop info, which removes it from any loops it
873 // was in.
874 LI->removeBlock(BB);
875
876
877 // Remove phi node entries in successors for this block.
878 TerminatorInst *TI = BB->getTerminator();
879 std::vector<BasicBlock*> Succs;
880 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
881 Succs.push_back(TI->getSuccessor(i));
882 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000883 }
884
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000885 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000886 std::sort(Succs.begin(), Succs.end());
887 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
888
889 // Remove the basic block, including all of the instructions contained in it.
890 BB->eraseFromParent();
891
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000892 // Remove successor blocks here that are not dead, so that we know we only
893 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
894 // then getting removed before we revisit them, which is badness.
895 //
896 for (unsigned i = 0; i != Succs.size(); ++i)
897 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
898 // One exception is loop headers. If this block was the preheader for a
899 // loop, then we DO want to visit the loop so the loop gets deleted.
900 // We know that if the successor is a loop header, that this loop had to
901 // be the preheader: the case where this was the latch block was handled
902 // above and headers can only have two predecessors.
903 if (!LI->isLoopHeader(Succs[i])) {
904 Succs.erase(Succs.begin()+i);
905 --i;
906 }
907 }
908
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000909 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
910 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000911}
Chris Lattner6fd13622006-02-17 00:31:07 +0000912
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000913/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
914/// become unwrapped, either because the backedge was deleted, or because the
915/// edge into the header was removed. If the edge into the header from the
916/// latch block was removed, the loop is unwrapped but subloops are still alive,
917/// so they just reparent loops. If the loops are actually dead, they will be
918/// removed later.
919void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000920 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000921 RemoveLoopFromWorklist(L);
922}
923
924
925
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000926// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
927// the value specified by Val in the specified loop, or we know it does NOT have
928// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000929void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000930 Constant *Val,
931 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000932 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000933
Chris Lattnerf48f7772004-04-19 18:07:02 +0000934 // FIXME: Support correlated properties, like:
935 // for (...)
936 // if (li1 < li2)
937 // ...
938 // if (li1 > li2)
939 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000940
Chris Lattner6e263152006-02-10 02:30:37 +0000941 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
942 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000943 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000944 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000945
Chris Lattner6fd13622006-02-17 00:31:07 +0000946 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
947 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000948 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000949 Value *Replacement;
950 if (IsEqual)
951 Replacement = Val;
952 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000953 Replacement = ConstantInt::get(Type::Int1Ty,
954 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000955
956 for (unsigned i = 0, e = Users.size(); i != e; ++i)
957 if (Instruction *U = cast<Instruction>(Users[i])) {
958 if (!L->contains(U->getParent()))
959 continue;
960 U->replaceUsesOfWith(LIC, Replacement);
961 Worklist.push_back(U);
962 }
963 } else {
964 // Otherwise, we don't know the precise value of LIC, but we do know that it
965 // is certainly NOT "Val". As such, simplify any uses in the loop that we
966 // can. This case occurs when we unswitch switch statements.
967 for (unsigned i = 0, e = Users.size(); i != e; ++i)
968 if (Instruction *U = cast<Instruction>(Users[i])) {
969 if (!L->contains(U->getParent()))
970 continue;
971
972 Worklist.push_back(U);
973
Chris Lattnerfa335f62006-02-16 19:36:22 +0000974 // If we know that LIC is not Val, use this info to simplify code.
975 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
976 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
977 if (SI->getCaseValue(i) == Val) {
978 // Found a dead case value. Don't remove PHI nodes in the
979 // successor if they become single-entry, those PHI nodes may
980 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000981
982 // FIXME: This is a hack. We need to keep the successor around
983 // and hooked up so as to preserve the loop structure, because
984 // trying to update it is complicated. So instead we preserve the
985 // loop structure and put the block on an dead code path.
986
987 BasicBlock* Old = SI->getParent();
988 BasicBlock* Split = SplitBlock(Old, SI);
989
990 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000991 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000992 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000993
994 Old->getTerminator()->eraseFromParent();
995
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000996
997 PHINode *PN;
998 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
999 (PN = dyn_cast<PHINode>(II)); ++II) {
1000 Value *InVal = PN->removeIncomingValue(Split, false);
1001 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +00001002 }
1003
Chris Lattnerfa335f62006-02-16 19:36:22 +00001004 SI->removeCase(i);
1005 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001006 }
1007 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001008 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001009
1010 // TODO: We could do other simplifications, for example, turning
1011 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +00001012 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001013 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001014
1015 SimplifyCode(Worklist);
1016}
1017
1018/// SimplifyCode - Okay, now that we have simplified some instructions in the
1019/// loop, walk over it and constant prop, dce, and fold control flow where
1020/// possible. Note that this is effectively a very simple loop-structure-aware
1021/// optimizer. During processing of this loop, L could very well be deleted, so
1022/// it must not be used.
1023///
1024/// FIXME: When the loop optimizer is more mature, separate this out to a new
1025/// pass.
1026///
1027void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001028 while (!Worklist.empty()) {
1029 Instruction *I = Worklist.back();
1030 Worklist.pop_back();
1031
1032 // Simple constant folding.
1033 if (Constant *C = ConstantFoldInstruction(I)) {
1034 ReplaceUsesOfWith(I, C, Worklist);
1035 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001036 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001037
1038 // Simple DCE.
1039 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001040 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +00001041
1042 // Add uses to the worklist, which may be dead now.
1043 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1044 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1045 Worklist.push_back(Use);
1046 I->eraseFromParent();
1047 RemoveFromWorklist(I, Worklist);
1048 ++NumSimplify;
1049 continue;
1050 }
1051
1052 // Special case hacks that appear commonly in unswitched code.
1053 switch (I->getOpcode()) {
1054 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001055 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001056 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001057 continue;
1058 }
1059 break;
1060 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001061 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001062 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001063 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001064 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001065 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001066 if (CB->isOne()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +00001067 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1068 else // X & 0 -> 0
1069 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1070 continue;
1071 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001072 break;
1073 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001074 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001075 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001076 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001077 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001078 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001079 if (CB->isOne()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001080 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1081 else // X | 0 -> X
1082 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1083 continue;
1084 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001085 break;
1086 case Instruction::Br: {
1087 BranchInst *BI = cast<BranchInst>(I);
1088 if (BI->isUnconditional()) {
1089 // If BI's parent is the only pred of the successor, fold the two blocks
1090 // together.
1091 BasicBlock *Pred = BI->getParent();
1092 BasicBlock *Succ = BI->getSuccessor(0);
1093 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1094 if (!SinglePred) continue; // Nothing to do.
1095 assert(SinglePred == Pred && "CFG broken");
1096
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001097 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1098 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001099
1100 // Resolve any single entry PHI nodes in Succ.
1101 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1102 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1103
1104 // Move all of the successor contents from Succ to Pred.
1105 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1106 Succ->end());
1107 BI->eraseFromParent();
1108 RemoveFromWorklist(BI, Worklist);
1109
1110 // If Succ has any successors with PHI nodes, update them to have
1111 // entries coming from Pred instead of Succ.
1112 Succ->replaceAllUsesWith(Pred);
1113
1114 // Remove Succ from the loop tree.
1115 LI->removeBlock(Succ);
1116 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001117 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001118 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001119 // Conditional branch. Turn it into an unconditional branch, then
1120 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001121 break; // FIXME: Enable.
1122
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001123 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001124 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1125 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001126 DeadSucc->removePredecessor(BI->getParent(), true);
1127 Worklist.push_back(new BranchInst(LiveSucc, BI));
1128 BI->eraseFromParent();
1129 RemoveFromWorklist(BI, Worklist);
1130 ++NumSimplify;
1131
1132 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001133 }
1134 break;
1135 }
1136 }
1137 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001138}