blob: 6b4d6376f286a7628a757f55bf2957be44a8cb08 [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;
Devang Patel7d165e12007-07-30 23:07:10 +000073 bool redoLoop;
Chris Lattnerf48f7772004-04-19 18:07:02 +000074 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000075 static char ID; // Pass ID, replacement for typeid
Dan Gohman34d442f2007-08-01 15:32:29 +000076 explicit LoopUnswitch(bool Os = false) :
Devang Patel7d165e12007-07-30 23:07:10 +000077 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false) {}
Devang Patel09f162c2007-05-01 21:15:47 +000078
Devang Patel901a27d2007-03-07 00:26:10 +000079 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patel7d165e12007-07-30 23:07:10 +000080 bool processLoop(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +000081
82 /// This transformation requires natural loop information & requires that
83 /// loop preheaders be inserted into the CFG...
84 ///
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000087 AU.addPreservedID(LoopSimplifyID);
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);
Devang Pateld4911982007-07-31 08:03:26 +000091 AU.addPreservedID(LCSSAID);
92 AU.addPreserved<DominatorTree>();
93 AU.addPreserved<DominanceFrontier>();
Chris Lattnerf48f7772004-04-19 18:07:02 +000094 }
95
96 private:
Devang Pateld4911982007-07-31 08:03:26 +000097
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000098 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
99 /// remove it.
100 void RemoveLoopFromWorklist(Loop *L) {
101 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
102 LoopProcessWorklist.end(), L);
103 if (I != LoopProcessWorklist.end())
104 LoopProcessWorklist.erase(I);
105 }
106
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000107 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000108 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +0000109 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000110 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000111 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000112
113 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
114 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000115
116 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
117 BasicBlock *TrueDest,
118 BasicBlock *FalseDest,
119 Instruction *InsertPt);
120
Devang Pateld4911982007-07-31 08:03:26 +0000121 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000122 void RemoveBlockIfDead(BasicBlock *BB,
Devang Pateld4911982007-07-31 08:03:26 +0000123 std::vector<Instruction*> &Worklist, Loop *l);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000124 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000125 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000126 char LoopUnswitch::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000127 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000128}
129
Devang Patel506310d2007-06-06 00:21:03 +0000130LoopPass *llvm::createLoopUnswitchPass(bool Os) {
131 return new LoopUnswitch(Os);
132}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000133
134/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
135/// invariant in the loop, or has an invariant piece, return the invariant.
136/// Otherwise, return null.
137static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
138 // Constants should be folded, not unswitched on!
139 if (isa<Constant>(Cond)) return false;
Devang Patel3c723c82007-06-28 00:44:10 +0000140
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000141 // TODO: Handle: br (VARIANT|INVARIANT).
142 // TODO: Hoist simple expressions out of loops.
143 if (L->isLoopInvariant(Cond)) return Cond;
144
145 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
146 if (BO->getOpcode() == Instruction::And ||
147 BO->getOpcode() == Instruction::Or) {
148 // If either the left or right side is invariant, we can unswitch on this,
149 // which will cause the branch to go away in one loop and the condition to
150 // simplify in the other one.
151 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
152 return LHS;
153 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
154 return RHS;
155 }
156
157 return 0;
158}
159
Devang Patel901a27d2007-03-07 00:26:10 +0000160bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
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;
Devang Patel7d165e12007-07-30 23:07:10 +0000164
165 do {
166 redoLoop = false;
167 Changed |= processLoop(L);
168 } while(redoLoop);
169
170 return Changed;
171}
172
173/// processLoop - Do actual work and unswitch loop if possible and profitable.
174bool LoopUnswitch::processLoop(Loop *L) {
175 assert(L->isLCSSAForm());
176 bool Changed = false;
177
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000178 // Loop over all of the basic blocks in the loop. If we find an interior
179 // block that is branching on a loop-invariant condition, we can unswitch this
180 // loop.
181 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
182 I != E; ++I) {
183 TerminatorInst *TI = (*I)->getTerminator();
184 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
185 // If this isn't branching on an invariant condition, we can't unswitch
186 // it.
187 if (BI->isConditional()) {
188 // See if this, or some part of it, is loop invariant. If so, we can
189 // unswitch on it if we desire.
190 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000191 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000192 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000193 ++NumBranches;
194 return true;
195 }
196 }
197 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
198 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
199 if (LoopCond && SI->getNumCases() > 1) {
200 // Find a value to unswitch on:
201 // FIXME: this should chose the most expensive case!
202 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000203 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000204 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000205 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000206
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000207 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
208 ++NumSwitches;
209 return true;
210 }
211 }
212 }
213
214 // Scan the instructions to check for unswitchable values.
215 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
216 BBI != E; ++BBI)
217 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
218 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000219 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000220 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000221 ++NumSelects;
222 return true;
223 }
224 }
225 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000226
227 assert(L->isLCSSAForm());
228
Chris Lattnerf48f7772004-04-19 18:07:02 +0000229 return Changed;
230}
231
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000232/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
233/// 1. Exit the loop with no side effects.
234/// 2. Branch to the latch block with no side-effects.
235///
236/// If these conditions are true, we return true and set ExitBB to the block we
237/// exit through.
238///
239static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
240 BasicBlock *&ExitBB,
241 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000242 if (!Visited.insert(BB).second) {
243 // Already visited and Ok, end of recursion.
244 return true;
245 } else if (!L->contains(BB)) {
246 // Otherwise, this is a loop exit, this is fine so long as this is the
247 // first exit.
248 if (ExitBB != 0) return false;
249 ExitBB = BB;
250 return true;
251 }
252
253 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000254 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000255 // Check to see if the successor is a trivial loop exit.
256 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
257 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000258 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000259
260 // Okay, everything after this looks good, check to make sure that this block
261 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000262 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000263 if (I->mayWriteToMemory())
264 return false;
265
266 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000267}
268
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000269/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
270/// leads to an exit from the specified loop, and has no side-effects in the
271/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000272static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
273 std::set<BasicBlock*> Visited;
274 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000275 BasicBlock *ExitBB = 0;
276 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
277 return ExitBB;
278 return 0;
279}
Chris Lattner6e263152006-02-10 02:30:37 +0000280
Chris Lattnered7a67b2006-02-10 01:24:09 +0000281/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
282/// trivial: that is, that the condition controls whether or not the loop does
283/// anything at all. If this is a trivial condition, unswitching produces no
284/// code duplications (equivalently, it produces a simpler loop and a new empty
285/// loop, which gets deleted).
286///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000287/// If this is a trivial condition, return true, otherwise return false. When
288/// returning true, this sets Cond and Val to the condition that controls the
289/// trivial condition: when Cond dynamically equals Val, the loop is known to
290/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
291/// Cond == Val.
292///
293static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000294 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000295 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000296 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000297
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000298 BasicBlock *LoopExitBB = 0;
299 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
300 // If the header block doesn't end with a conditional branch on Cond, we
301 // can't handle it.
302 if (!BI->isConditional() || BI->getCondition() != Cond)
303 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000304
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000305 // Check to see if a successor of the branch 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.
309 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000310 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000311 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000312 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000313 }
314 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
315 // If this isn't a switch on Cond, we can't handle it.
316 if (SI->getCondition() != Cond) return false;
317
318 // Check to see if a successor of the switch is guaranteed to go to the
319 // latch block or exit through a one exit block without having any
320 // side-effects. If so, determine the value of Cond that causes it to do
321 // this. Note that we can't trivially unswitch on the default case.
322 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
323 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
324 // Okay, we found a trivial case, remember the value that is trivial.
325 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000326 break;
327 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000328 }
329
Chris Lattnere5521db2006-02-22 23:55:00 +0000330 // If we didn't find a single unique LoopExit block, or if the loop exit block
331 // contains phi nodes, this isn't trivial.
332 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000333 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000334
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000335 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000336
337 // We already know that nothing uses any scalar values defined inside of this
338 // loop. As such, we just have to check to see if this loop will execute any
339 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000340 // part of the loop that the code *would* execute. We already checked the
341 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000342 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
343 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000344 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000345 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000346}
347
348/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
349/// we choose to unswitch the specified loop on the specified value.
350///
351unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
352 // If the condition is trivial, always unswitch. There is no code growth for
353 // this case.
354 if (IsTrivialUnswitchCondition(L, LIC))
355 return 0;
356
Owen Anderson18e816f2006-06-28 17:47:50 +0000357 // FIXME: This is really overly conservative. However, more liberal
358 // estimations have thus far resulted in excessive unswitching, which is bad
359 // both in compile time and in code size. This should be replaced once
360 // someone figures out how a good estimation.
361 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000362
Chris Lattnered7a67b2006-02-10 01:24:09 +0000363 unsigned Cost = 0;
364 // FIXME: this is brain dead. It should take into consideration code
365 // shrinkage.
366 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
367 I != E; ++I) {
368 BasicBlock *BB = *I;
369 // Do not include empty blocks in the cost calculation. This happen due to
370 // loop canonicalization and will be removed.
371 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
372 continue;
373
374 // Count basic blocks.
375 ++Cost;
376 }
377
378 return Cost;
379}
380
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000381/// UnswitchIfProfitable - We have found that we can unswitch L when
382/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
383/// unswitch the loop, reprocess the pieces, then return true.
384bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
385 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000386 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
Devang Patel506310d2007-06-06 00:21:03 +0000387
388 // Do not do non-trivial unswitch while optimizing for size.
389 if (Cost && OptimizeForSize)
390 return false;
391
Chris Lattner5821a6a2006-03-24 07:14:00 +0000392 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000393 // FIXME: this should estimate growth by the amount of code shared by the
394 // resultant unswitched loops.
395 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000396 DOUT << "NOT unswitching loop %"
397 << L->getHeader()->getName() << ", cost too high: "
398 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000399 return false;
400 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000401
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000402 // If this is a trivial condition to unswitch (which results in no code
403 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000404 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000405 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000406 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
407 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000408 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000409 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000410 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000411
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000412 return true;
413}
414
Misha Brukmanb1c93172005-04-21 23:48:37 +0000415// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000416// current values into those specified by ValueMap.
417//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000418static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000419 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000420 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
421 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000422 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000423 if (It != ValueMap.end()) Op = It->second;
424 I->setOperand(op, Op);
425 }
426}
427
Devang Patel3304e462007-06-28 00:49:00 +0000428// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000429//
430// If Orig block's immediate dominator is mapped in VM then use corresponding
431// immediate dominator from the map. Otherwise Orig block's dominator is also
432// NewBB's dominator.
433//
Devang Patel8a1d1ac2007-07-18 23:50:19 +0000434// OrigPreheader is loop pre-header before this pass started
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000435// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Patel8a1d1ac2007-07-18 23:50:19 +0000436// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000437void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
438 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
439 BasicBlock *OrigHeader,
Devang Patel0975c6d2007-06-29 23:11:49 +0000440 DominatorTree *DT, DominanceFrontier *DF,
Devang Patel3304e462007-06-28 00:49:00 +0000441 DenseMap<const Value*, Value*> &VM) {
442
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000443 // If NewBB alreay has found its place in domiantor tree then no need to do
444 // anything.
445 if (DT->getNode(NewBB))
446 return;
447
448 // If Orig does not have any immediate domiantor then its clone, NewBB, does
449 // not need any immediate dominator.
Devang Patel3304e462007-06-28 00:49:00 +0000450 DomTreeNode *OrigNode = DT->getNode(Orig);
451 if (!OrigNode)
452 return;
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000453 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
454 if (!OrigIDomNode)
455 return;
456
457 BasicBlock *OrigIDom = NULL;
458
459 // If Orig is original loop header then its immediate dominator is
460 // NewPreheader.
461 if (Orig == OrigHeader)
462 OrigIDom = NewPreheader;
463
464 // If Orig is new pre-header then its immediate dominator is
465 // original pre-header.
466 else if (Orig == NewPreheader)
467 OrigIDom = OrigPreheader;
468
469 // Other as DT to find Orig's immediate dominator.
470 else
471 OrigIDom = OrigIDomNode->getBlock();
472
Devang Patel14fae502007-07-30 21:10:44 +0000473 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
474 BasicBlock *NewIDom = OrigIDom;
475 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
476 if (I != VM.end()) {
477 NewIDom = cast<BasicBlock>(I->second);
478
479 // If NewIDom does not have corresponding dominatore tree node then
480 // get one.
481 if (!DT->getNode(NewIDom))
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000482 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
483 OrigHeader, DT, DF, VM);
Devang Patel3304e462007-06-28 00:49:00 +0000484 }
Devang Patel14fae502007-07-30 21:10:44 +0000485
486 DT->addNewBlock(NewBB, NewIDom);
487
488 // Copy cloned dominance frontiner set
Devang Patel0975c6d2007-06-29 23:11:49 +0000489 DominanceFrontier::DomSetType NewDFSet;
490 if (DF) {
491 DominanceFrontier::iterator DFI = DF->find(Orig);
492 if ( DFI != DF->end()) {
493 DominanceFrontier::DomSetType S = DFI->second;
494 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
495 I != E; ++I) {
496 BasicBlock *BB = *I;
Chuck Rose III1a39a2d12007-07-27 18:26:35 +0000497 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
498 if (IDM != VM.end())
499 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Devang Patel0975c6d2007-06-29 23:11:49 +0000500 else
501 NewDFSet.insert(BB);
502 }
503 }
504 DF->addBasicBlock(NewBB, NewDFSet);
505 }
Devang Patel3304e462007-06-28 00:49:00 +0000506}
507
Chris Lattnerf48f7772004-04-19 18:07:02 +0000508/// CloneLoop - Recursively clone the specified loop and all of its children,
509/// mapping the blocks with the specified map.
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000510static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000511 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000512 Loop *New = new Loop();
513
Devang Patel901a27d2007-03-07 00:26:10 +0000514 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000515
516 // Add all of the blocks in L to the new loop.
517 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
518 I != E; ++I)
519 if (LI->getLoopFor(*I) == L)
520 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
521
522 // Add all of the subloops to the new loop.
523 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000524 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000525
Chris Lattnerf48f7772004-04-19 18:07:02 +0000526 return New;
527}
528
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000529/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
530/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
531/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000532void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
533 BasicBlock *TrueDest,
534 BasicBlock *FalseDest,
535 Instruction *InsertPt) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000536 // Insert a conditional branch on LIC to the two preheaders. The original
537 // code is the true version and the new code is the false version.
538 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000539 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000540 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000541 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000542 // We want to enter the new loop when the condition is true.
543 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000544
545 // Insert the new branch.
Devang Patela8823282007-08-02 15:25:57 +0000546 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
Devang Patel3304e462007-06-28 00:49:00 +0000547
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000548}
549
550
Chris Lattnered7a67b2006-02-10 01:24:09 +0000551/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
552/// condition in it (a cond branch from its header block to its latch block,
553/// where the path through the loop that doesn't execute its body has no
554/// side-effects), unswitch it. This doesn't involve any code duplication, just
555/// moving the conditional branch outside of the loop and updating loop info.
556void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000557 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000558 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000559 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
560 << L->getHeader()->getName() << " [" << L->getBlocks().size()
561 << " blocks] in Function " << L->getHeader()->getParent()->getName()
562 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000563
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000564 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000565 // to insert the conditional branch. We will change 'OrigPH' to have a
566 // conditional branch on Cond.
567 BasicBlock *OrigPH = L->getLoopPreheader();
Devang Patel12358b42007-07-06 22:03:47 +0000568 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000569
570 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000571 // to branch to: this is the exit block out of the loop that we should
572 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000573
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000574 // Split this block now, so that the loop maintains its exit block, and so
575 // that the jump from the preheader can execute the contents of the exit block
576 // without actually branching to it (the exit block should be dominated by the
577 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000578 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel12358b42007-07-06 22:03:47 +0000579 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000580
Chris Lattnered7a67b2006-02-10 01:24:09 +0000581 // Okay, now we have a position to branch from and a position to branch to,
582 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000583 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
584 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000585 OrigPH->getTerminator()->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +0000586 LPM->deleteSimpleAnalysisValue(OrigPH->getTerminator(), L);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000587
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000588 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000589 redoLoop = true;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000590
Chris Lattnered7a67b2006-02-10 01:24:09 +0000591 // Now that we know that the loop is never entered when this condition is a
592 // particular value, rewrite the loop with this info. We know that this will
593 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000594 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000595 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000596}
597
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000598/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
599/// equal Val. Split it into loop versions and test the condition outside of
600/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000601void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
602 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000603 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000604 DOUT << "loop-unswitch: Unswitching loop %"
605 << L->getHeader()->getName() << " [" << L->getBlocks().size()
606 << " blocks] in Function " << F->getName()
607 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000608
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000609 // LoopBlocks contains all of the basic blocks of the loop, including the
610 // preheader of the loop, the body of the loop, and the exit blocks of the
611 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000612 std::vector<BasicBlock*> LoopBlocks;
613
614 // First step, split the preheader and exit blocks, and add these blocks to
615 // the LoopBlocks list.
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000616 BasicBlock *OrigHeader = L->getHeader();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000617 BasicBlock *OrigPreheader = L->getLoopPreheader();
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000618 BasicBlock *NewPreheader = SplitEdge(OrigPreheader, L->getHeader(), this);
619 LoopBlocks.push_back(NewPreheader);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000620
621 // We want the loop to come after the preheader, but before the exit blocks.
622 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
623
624 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000625 L->getUniqueExitBlocks(ExitBlocks);
626
Owen Andersonf52351e2006-06-26 07:44:36 +0000627 // Split all of the edges from inside the loop to their exit blocks. Update
628 // the appropriate Phi nodes as we do so.
Devang Patela8823282007-08-02 15:25:57 +0000629 SmallVector<BasicBlock *,8> MiddleBlocks;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000630 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000631 BasicBlock *ExitBlock = ExitBlocks[i];
632 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
633
634 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Devang Patel12358b42007-07-06 22:03:47 +0000635 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Devang Patela8823282007-08-02 15:25:57 +0000636 MiddleBlocks.push_back(MiddleBlock);
Owen Andersonf52351e2006-06-26 07:44:36 +0000637 BasicBlock* StartBlock = Preds[j];
638 BasicBlock* EndBlock;
639 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
640 EndBlock = MiddleBlock;
641 MiddleBlock = EndBlock->getSinglePredecessor();;
642 } else {
643 EndBlock = ExitBlock;
644 }
645
646 std::set<PHINode*> InsertedPHIs;
647 PHINode* OldLCSSA = 0;
648 for (BasicBlock::iterator I = EndBlock->begin();
649 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
650 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
651 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
652 OldLCSSA->getName() + ".us-lcssa",
653 MiddleBlock->getTerminator());
654 NewLCSSA->addIncoming(OldValue, StartBlock);
655 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
656 NewLCSSA);
657 InsertedPHIs.insert(NewLCSSA);
658 }
659
Owen Anderson00b974c2006-07-19 03:51:48 +0000660 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000661 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
662 for (BasicBlock::iterator I = MiddleBlock->begin();
663 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
664 ++I) {
665 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
666 OldLCSSA->getName() + ".us-lcssa",
667 InsertPt);
668 OldLCSSA->replaceAllUsesWith(NewLCSSA);
669 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
670 }
671 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000672 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000673
674 // The exit blocks may have been changed due to edge splitting, recompute.
675 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000676 L->getUniqueExitBlocks(ExitBlocks);
677
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000678 // Add exit blocks to the loop blocks.
679 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000680
Devang Patela8823282007-08-02 15:25:57 +0000681 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
682 DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
683
Chris Lattnerf48f7772004-04-19 18:07:02 +0000684 // Next step, clone all of the basic blocks that make up the loop (including
685 // the loop preheader and exit blocks), keeping track of the mapping between
686 // the instructions and blocks.
687 std::vector<BasicBlock*> NewBlocks;
688 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000689 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000690 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000691 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
692 NewBlocks.push_back(New);
693 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Pateld4911982007-07-31 08:03:26 +0000694 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000695 }
696
Devang Patela8823282007-08-02 15:25:57 +0000697 // OutSiders are basic block that are dominated by original header and
698 // at the same time they are not part of loop.
699 SmallPtrSet<BasicBlock *, 8> OutSiders;
700 if (DT) {
701 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
702 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
703 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
704 BasicBlock *B = (*DI)->getBlock();
705
706 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
707 if (VI == ValueMap.end())
708 OutSiders.insert(B);
Devang Patel3304e462007-06-28 00:49:00 +0000709 }
Devang Patela8823282007-08-02 15:25:57 +0000710 }
711
Chris Lattnerf48f7772004-04-19 18:07:02 +0000712 // Splice the newly inserted blocks into the function right before the
713 // original preheader.
714 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
715 NewBlocks[0], F->end());
716
717 // Now we create the new Loop object for the versioned loop.
Devang Patel901a27d2007-03-07 00:26:10 +0000718 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000719 Loop *ParentLoop = L->getParentLoop();
720 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000721 // Make sure to add the cloned preheader and exit blocks to the parent loop
722 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000723 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
724 }
725
726 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
727 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000728 // The new exit block should be in the same loop as the old one.
729 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
730 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000731
732 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
733 "Exit block should have been split to have one successor!");
734 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
735
736 // If the successor of the exit block had PHI nodes, add an entry for
737 // NewExit.
738 PHINode *PN;
739 for (BasicBlock::iterator I = ExitSucc->begin();
740 (PN = dyn_cast<PHINode>(I)); ++I) {
741 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000742 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000743 if (It != ValueMap.end()) V = It->second;
744 PN->addIncoming(V, NewExit);
745 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000746 }
747
748 // Rewrite the code to refer to itself.
749 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
750 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
751 E = NewBlocks[i]->end(); I != E; ++I)
752 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000753
Chris Lattnerf48f7772004-04-19 18:07:02 +0000754 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000755 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
756 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000757 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000758
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000759 // Emit the new branch that selects between the two versions of this loop.
760 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
761 OldBR->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +0000762 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patela8823282007-08-02 15:25:57 +0000763
764 // Update dominator info
765 if (DF && DT) {
766
767 // Clone dominator info for all cloned basic block.
768 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
769 BasicBlock *LBB = LoopBlocks[i];
770 BasicBlock *NBB = NewBlocks[i];
771 CloneDomInfo(NBB, LBB, NewPreheader, OrigPreheader,
772 OrigHeader, DT, DF, ValueMap);
773
774 // Remove any OutSiders from LBB and NBB's dominance frontier.
775 DominanceFrontier::iterator LBBI = DF->find(LBB);
776 if (LBBI != DF->end()) {
777 DominanceFrontier::DomSetType &LBSet = LBBI->second;
778 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
779 LE = LBSet.end(); LI != LE; ++LI) {
780 BasicBlock *B = *LI;
781 if (OutSiders.count(B))
782 DF->removeFromFrontier(LBBI, B);
783 }
784 }
785
786 // Remove any OutSiders from LBB and NBB's dominance frontier.
787 DominanceFrontier::iterator NBBI = DF->find(NBB);
788 if (NBBI != DF->end()) {
789 DominanceFrontier::DomSetType NBSet = NBBI->second;
790 for (DominanceFrontier::DomSetType::iterator NI = NBSet.begin(),
791 NE = NBSet.end(); NI != NE; ++NI) {
792 BasicBlock *B = *NI;
793 if (OutSiders.count(B))
794 DF->removeFromFrontier(NBBI, B);
795 }
796 }
797 }
798
799 // MiddleBlocks are dominated by original pre header. SplitEdge updated
800 // MiddleBlocks' dominance frontier appropriately.
801 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
802 BasicBlock *MBB = MiddleBlocks[i];
803 if (!MBB->getSinglePredecessor())
804 DT->changeImmediateDominator(MBB, OrigPreheader);
805 }
806
807 // All Outsiders are now dominated by original pre header.
808 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
809 OE = OutSiders.end(); OI != OE; ++OI) {
810 BasicBlock *OB = *OI;
811 DT->changeImmediateDominator(OB, OrigPreheader);
812 }
813
814 // New loop headers are dominated by original preheader
815 DT->changeImmediateDominator(NewBlocks[0], OrigPreheader);
816 DT->changeImmediateDominator(LoopBlocks[0], OrigPreheader);
817 }
818
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000819 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +0000820 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000821
822 // Now we rewrite the original code to know that the condition is true and the
823 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000824 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
825
826 // It's possible that simplifying one loop could cause the other to be
827 // deleted. If so, don't simplify it.
828 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
829 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000830}
831
Chris Lattner6fd13622006-02-17 00:31:07 +0000832/// RemoveFromWorklist - Remove all instances of I from the worklist vector
833/// specified.
834static void RemoveFromWorklist(Instruction *I,
835 std::vector<Instruction*> &Worklist) {
836 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
837 Worklist.end(), I);
838 while (WI != Worklist.end()) {
839 unsigned Offset = WI-Worklist.begin();
840 Worklist.erase(WI);
841 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
842 }
843}
844
845/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
846/// program, replacing all uses with V and update the worklist.
847static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +0000848 std::vector<Instruction*> &Worklist,
849 Loop *L, LPPassManager *LPM) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000850 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000851
852 // Add uses to the worklist, which may be dead now.
853 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
854 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
855 Worklist.push_back(Use);
856
857 // Add users to the worklist which may be simplified now.
858 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
859 UI != E; ++UI)
860 Worklist.push_back(cast<Instruction>(*UI));
861 I->replaceAllUsesWith(V);
862 I->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +0000863 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +0000864 RemoveFromWorklist(I, Worklist);
865 ++NumSimplify;
866}
867
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000868/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
869/// information, and remove any dead successors it has.
870///
871void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Pateld4911982007-07-31 08:03:26 +0000872 std::vector<Instruction*> &Worklist,
873 Loop *L) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000874 if (pred_begin(BB) != pred_end(BB)) {
875 // This block isn't dead, since an edge to BB was just removed, see if there
876 // are any easy simplifications we can do now.
877 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
878 // If it has one pred, fold phi nodes in BB.
879 while (isa<PHINode>(BB->begin()))
880 ReplaceUsesOfWith(BB->begin(),
881 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Pateld4911982007-07-31 08:03:26 +0000882 Worklist, L, LPM);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000883
884 // If this is the header of a loop and the only pred is the latch, we now
885 // have an unreachable loop.
886 if (Loop *L = LI->getLoopFor(BB))
887 if (L->getHeader() == BB && L->contains(Pred)) {
888 // Remove the branch from the latch to the header block, this makes
889 // the header dead, which will make the latch dead (because the header
890 // dominates the latch).
891 Pred->getTerminator()->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +0000892 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000893 new UnreachableInst(Pred);
894
895 // The loop is now broken, remove it from LI.
896 RemoveLoopFromHierarchy(L);
897
898 // Reprocess the header, which now IS dead.
Devang Pateld4911982007-07-31 08:03:26 +0000899 RemoveBlockIfDead(BB, Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000900 return;
901 }
902
903 // If pred ends in a uncond branch, add uncond branch to worklist so that
904 // the two blocks will get merged.
905 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
906 if (BI->isUnconditional())
907 Worklist.push_back(BI);
908 }
909 return;
910 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000911
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000912 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000913
914 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000915 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000916 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000917
918 // Anything that uses the instructions in this basic block should have their
919 // uses replaced with undefs.
920 if (!I->use_empty())
921 I->replaceAllUsesWith(UndefValue::get(I->getType()));
922 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000923
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000924 // If this is the edge to the header block for a loop, remove the loop and
925 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000926 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000927 if (BBLoop->getLoopLatch() == BB)
928 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000929 }
930
931 // Remove the block from the loop info, which removes it from any loops it
932 // was in.
933 LI->removeBlock(BB);
934
935
936 // Remove phi node entries in successors for this block.
937 TerminatorInst *TI = BB->getTerminator();
938 std::vector<BasicBlock*> Succs;
939 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
940 Succs.push_back(TI->getSuccessor(i));
941 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000942 }
943
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000944 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000945 std::sort(Succs.begin(), Succs.end());
946 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
947
948 // Remove the basic block, including all of the instructions contained in it.
949 BB->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +0000950 LPM->deleteSimpleAnalysisValue(BB, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000951 // Remove successor blocks here that are not dead, so that we know we only
952 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
953 // then getting removed before we revisit them, which is badness.
954 //
955 for (unsigned i = 0; i != Succs.size(); ++i)
956 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
957 // One exception is loop headers. If this block was the preheader for a
958 // loop, then we DO want to visit the loop so the loop gets deleted.
959 // We know that if the successor is a loop header, that this loop had to
960 // be the preheader: the case where this was the latch block was handled
961 // above and headers can only have two predecessors.
962 if (!LI->isLoopHeader(Succs[i])) {
963 Succs.erase(Succs.begin()+i);
964 --i;
965 }
966 }
967
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000968 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Pateld4911982007-07-31 08:03:26 +0000969 RemoveBlockIfDead(Succs[i], Worklist, L);
Chris Lattner29f771b2006-02-18 01:27:45 +0000970}
Chris Lattner6fd13622006-02-17 00:31:07 +0000971
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000972/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
973/// become unwrapped, either because the backedge was deleted, or because the
974/// edge into the header was removed. If the edge into the header from the
975/// latch block was removed, the loop is unwrapped but subloops are still alive,
976/// so they just reparent loops. If the loops are actually dead, they will be
977/// removed later.
978void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000979 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000980 RemoveLoopFromWorklist(L);
981}
982
983
984
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000985// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
986// the value specified by Val in the specified loop, or we know it does NOT have
987// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000988void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000989 Constant *Val,
990 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000991 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000992
Chris Lattnerf48f7772004-04-19 18:07:02 +0000993 // FIXME: Support correlated properties, like:
994 // for (...)
995 // if (li1 < li2)
996 // ...
997 // if (li1 > li2)
998 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000999
Chris Lattner6e263152006-02-10 02:30:37 +00001000 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1001 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001002 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +00001003 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001004
Chris Lattner6fd13622006-02-17 00:31:07 +00001005 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1006 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +00001007 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +00001008 Value *Replacement;
1009 if (IsEqual)
1010 Replacement = Val;
1011 else
Reid Spencercddc9df2007-01-12 04:24:46 +00001012 Replacement = ConstantInt::get(Type::Int1Ty,
1013 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +00001014
1015 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1016 if (Instruction *U = cast<Instruction>(Users[i])) {
1017 if (!L->contains(U->getParent()))
1018 continue;
1019 U->replaceUsesOfWith(LIC, Replacement);
1020 Worklist.push_back(U);
1021 }
1022 } else {
1023 // Otherwise, we don't know the precise value of LIC, but we do know that it
1024 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1025 // can. This case occurs when we unswitch switch statements.
1026 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1027 if (Instruction *U = cast<Instruction>(Users[i])) {
1028 if (!L->contains(U->getParent()))
1029 continue;
1030
1031 Worklist.push_back(U);
1032
Chris Lattnerfa335f62006-02-16 19:36:22 +00001033 // If we know that LIC is not Val, use this info to simplify code.
1034 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1035 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1036 if (SI->getCaseValue(i) == Val) {
1037 // Found a dead case value. Don't remove PHI nodes in the
1038 // successor if they become single-entry, those PHI nodes may
1039 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +00001040
1041 // FIXME: This is a hack. We need to keep the successor around
1042 // and hooked up so as to preserve the loop structure, because
1043 // trying to update it is complicated. So instead we preserve the
1044 // loop structure and put the block on an dead code path.
1045
1046 BasicBlock* Old = SI->getParent();
Devang Patel12358b42007-07-06 22:03:47 +00001047 BasicBlock* Split = SplitBlock(Old, SI, this);
Owen Andersonf52351e2006-06-26 07:44:36 +00001048
1049 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +00001050 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +00001051 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +00001052
1053 Old->getTerminator()->eraseFromParent();
1054
Owen Andersonbb3ae5e2006-06-27 22:26:09 +00001055
1056 PHINode *PN;
1057 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1058 (PN = dyn_cast<PHINode>(II)); ++II) {
1059 Value *InVal = PN->removeIncomingValue(Split, false);
1060 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +00001061 }
1062
Chris Lattnerfa335f62006-02-16 19:36:22 +00001063 SI->removeCase(i);
1064 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001065 }
1066 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001067 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001068
1069 // TODO: We could do other simplifications, for example, turning
1070 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +00001071 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001072 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001073
Devang Pateld4911982007-07-31 08:03:26 +00001074 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001075}
1076
1077/// SimplifyCode - Okay, now that we have simplified some instructions in the
1078/// loop, walk over it and constant prop, dce, and fold control flow where
1079/// possible. Note that this is effectively a very simple loop-structure-aware
1080/// optimizer. During processing of this loop, L could very well be deleted, so
1081/// it must not be used.
1082///
1083/// FIXME: When the loop optimizer is more mature, separate this out to a new
1084/// pass.
1085///
Devang Pateld4911982007-07-31 08:03:26 +00001086void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001087 while (!Worklist.empty()) {
1088 Instruction *I = Worklist.back();
1089 Worklist.pop_back();
1090
1091 // Simple constant folding.
1092 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Pateld4911982007-07-31 08:03:26 +00001093 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Chris Lattner6fd13622006-02-17 00:31:07 +00001094 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001095 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001096
1097 // Simple DCE.
1098 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001099 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +00001100
1101 // Add uses to the worklist, which may be dead now.
1102 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1103 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1104 Worklist.push_back(Use);
1105 I->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +00001106 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001107 RemoveFromWorklist(I, Worklist);
1108 ++NumSimplify;
1109 continue;
1110 }
1111
1112 // Special case hacks that appear commonly in unswitched code.
1113 switch (I->getOpcode()) {
1114 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001115 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Devang Pateld4911982007-07-31 08:03:26 +00001116 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L, LPM);
Chris Lattner6fd13622006-02-17 00:31:07 +00001117 continue;
1118 }
1119 break;
1120 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001121 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001122 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001123 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001124 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001125 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001126 if (CB->isOne()) // X & 1 -> X
Devang Pateld4911982007-07-31 08:03:26 +00001127 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001128 else // X & 0 -> 0
Devang Pateld4911982007-07-31 08:03:26 +00001129 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001130 continue;
1131 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001132 break;
1133 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001134 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001135 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001136 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001137 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001138 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001139 if (CB->isOne()) // X | 1 -> 1
Devang Pateld4911982007-07-31 08:03:26 +00001140 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001141 else // X | 0 -> X
Devang Pateld4911982007-07-31 08:03:26 +00001142 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001143 continue;
1144 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001145 break;
1146 case Instruction::Br: {
1147 BranchInst *BI = cast<BranchInst>(I);
1148 if (BI->isUnconditional()) {
1149 // If BI's parent is the only pred of the successor, fold the two blocks
1150 // together.
1151 BasicBlock *Pred = BI->getParent();
1152 BasicBlock *Succ = BI->getSuccessor(0);
1153 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1154 if (!SinglePred) continue; // Nothing to do.
1155 assert(SinglePred == Pred && "CFG broken");
1156
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001157 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1158 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001159
1160 // Resolve any single entry PHI nodes in Succ.
1161 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001162 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Chris Lattner6fd13622006-02-17 00:31:07 +00001163
1164 // Move all of the successor contents from Succ to Pred.
1165 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1166 Succ->end());
1167 BI->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +00001168 LPM->deleteSimpleAnalysisValue(BI, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001169 RemoveFromWorklist(BI, Worklist);
1170
1171 // If Succ has any successors with PHI nodes, update them to have
1172 // entries coming from Pred instead of Succ.
1173 Succ->replaceAllUsesWith(Pred);
1174
1175 // Remove Succ from the loop tree.
1176 LI->removeBlock(Succ);
1177 Succ->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +00001178 LPM->deleteSimpleAnalysisValue(Succ, L);
Chris Lattner29f771b2006-02-18 01:27:45 +00001179 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001180 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001181 // Conditional branch. Turn it into an unconditional branch, then
1182 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001183 break; // FIXME: Enable.
1184
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001185 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001186 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1187 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001188 DeadSucc->removePredecessor(BI->getParent(), true);
1189 Worklist.push_back(new BranchInst(LiveSucc, BI));
1190 BI->eraseFromParent();
Devang Pateld4911982007-07-31 08:03:26 +00001191 LPM->deleteSimpleAnalysisValue(BI, L);
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001192 RemoveFromWorklist(BI, Worklist);
1193 ++NumSimplify;
1194
Devang Pateld4911982007-07-31 08:03:26 +00001195 RemoveBlockIfDead(DeadSucc, Worklist, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001196 }
1197 break;
1198 }
1199 }
1200 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001201}