blob: 77dfb908fa774ea78b2e9c7587fe140b09c62d49 [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"
Chris Lattnerf48f7772004-04-19 18:07:02 +000038#include "llvm/Transforms/Utils/Cloning.h"
39#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerec6b40a2006-02-10 19:08:15 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
Devang Patel97517ff2007-02-26 20:22:50 +000042#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000043#include "llvm/ADT/PostOrderIterator.h"
Chris Lattner89762192006-02-09 20:15:48 +000044#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000045#include "llvm/Support/Compiler.h"
46#include "llvm/Support/Debug.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000047#include <algorithm>
Chris Lattner2826e052006-02-09 19:14:52 +000048#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000049using namespace llvm;
50
Chris Lattner79a42ac2006-12-19 21:40:18 +000051STATISTIC(NumBranches, "Number of branches unswitched");
52STATISTIC(NumSwitches, "Number of switches unswitched");
53STATISTIC(NumSelects , "Number of selects unswitched");
54STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
56
Chris Lattnerf48f7772004-04-19 18:07:02 +000057namespace {
Chris Lattner89762192006-02-09 20:15:48 +000058 cl::opt<unsigned>
59 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
60 cl::init(10), cl::Hidden);
61
Devang Patel901a27d2007-03-07 00:26:10 +000062 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +000063 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +000064 LPPassManager *LPM;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000065
Devang Patel901a27d2007-03-07 00:26:10 +000066 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000068 std::vector<Loop*> LoopProcessWorklist;
Devang Patel97517ff2007-02-26 20:22:50 +000069 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel967b84c2007-02-26 19:31:58 +000070
Chris Lattnerf48f7772004-04-19 18:07:02 +000071 public:
Devang Patel901a27d2007-03-07 00:26:10 +000072 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattnerf48f7772004-04-19 18:07:02 +000073
74 /// This transformation requires natural loop information & requires that
75 /// loop preheaders be inserted into the CFG...
76 ///
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000079 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000080 AU.addRequired<LoopInfo>();
81 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000082 AU.addRequiredID(LCSSAID);
83 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000084 }
85
86 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000087 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
88 /// remove it.
89 void RemoveLoopFromWorklist(Loop *L) {
90 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
91 LoopProcessWorklist.end(), L);
92 if (I != LoopProcessWorklist.end())
93 LoopProcessWorklist.erase(I);
94 }
95
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000096 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +000097 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +000098 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +000099 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000100 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000101 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000102 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000103
104 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
105 Constant *Val, bool isEqual);
106
107 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000108 void RemoveBlockIfDead(BasicBlock *BB,
109 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000110 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000111 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000112 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000113}
114
Devang Patel901a27d2007-03-07 00:26:10 +0000115LoopPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000116
117/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
118/// invariant in the loop, or has an invariant piece, return the invariant.
119/// Otherwise, return null.
120static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
121 // Constants should be folded, not unswitched on!
122 if (isa<Constant>(Cond)) return false;
123
124 // TODO: Handle: br (VARIANT|INVARIANT).
125 // TODO: Hoist simple expressions out of loops.
126 if (L->isLoopInvariant(Cond)) return Cond;
127
128 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
129 if (BO->getOpcode() == Instruction::And ||
130 BO->getOpcode() == Instruction::Or) {
131 // If either the left or right side is invariant, we can unswitch on this,
132 // which will cause the branch to go away in one loop and the condition to
133 // simplify in the other one.
134 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
135 return LHS;
136 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
137 return RHS;
138 }
139
140 return 0;
141}
142
Devang Patel901a27d2007-03-07 00:26:10 +0000143bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000144 assert(L->isLCSSAForm());
Devang Patel901a27d2007-03-07 00:26:10 +0000145 LI = &getAnalysis<LoopInfo>();
146 LPM = &LPM_Ref;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000147 bool Changed = false;
148
149 // Loop over all of the basic blocks in the loop. If we find an interior
150 // block that is branching on a loop-invariant condition, we can unswitch this
151 // loop.
152 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
153 I != E; ++I) {
154 TerminatorInst *TI = (*I)->getTerminator();
155 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
156 // If this isn't branching on an invariant condition, we can't unswitch
157 // it.
158 if (BI->isConditional()) {
159 // See if this, or some part of it, is loop invariant. If so, we can
160 // unswitch on it if we desire.
161 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000162 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000163 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000164 ++NumBranches;
165 return true;
166 }
167 }
168 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
169 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
170 if (LoopCond && SI->getNumCases() > 1) {
171 // Find a value to unswitch on:
172 // FIXME: this should chose the most expensive case!
173 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000174 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000175 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000176 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000177
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000178 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
179 ++NumSwitches;
180 return true;
181 }
182 }
183 }
184
185 // Scan the instructions to check for unswitchable values.
186 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
187 BBI != E; ++BBI)
188 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
189 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000190 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000191 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000192 ++NumSelects;
193 return true;
194 }
195 }
196 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000197
198 assert(L->isLCSSAForm());
199
Chris Lattnerf48f7772004-04-19 18:07:02 +0000200 return Changed;
201}
202
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000203/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
204/// 1. Exit the loop with no side effects.
205/// 2. Branch to the latch block with no side-effects.
206///
207/// If these conditions are true, we return true and set ExitBB to the block we
208/// exit through.
209///
210static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
211 BasicBlock *&ExitBB,
212 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000213 if (!Visited.insert(BB).second) {
214 // Already visited and Ok, end of recursion.
215 return true;
216 } else if (!L->contains(BB)) {
217 // Otherwise, this is a loop exit, this is fine so long as this is the
218 // first exit.
219 if (ExitBB != 0) return false;
220 ExitBB = BB;
221 return true;
222 }
223
224 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000225 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000226 // Check to see if the successor is a trivial loop exit.
227 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
228 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000229 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000230
231 // Okay, everything after this looks good, check to make sure that this block
232 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000233 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000234 if (I->mayWriteToMemory())
235 return false;
236
237 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000238}
239
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000240/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
241/// leads to an exit from the specified loop, and has no side-effects in the
242/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000243static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
244 std::set<BasicBlock*> Visited;
245 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000246 BasicBlock *ExitBB = 0;
247 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
248 return ExitBB;
249 return 0;
250}
Chris Lattner6e263152006-02-10 02:30:37 +0000251
Chris Lattnered7a67b2006-02-10 01:24:09 +0000252/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
253/// trivial: that is, that the condition controls whether or not the loop does
254/// anything at all. If this is a trivial condition, unswitching produces no
255/// code duplications (equivalently, it produces a simpler loop and a new empty
256/// loop, which gets deleted).
257///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000258/// If this is a trivial condition, return true, otherwise return false. When
259/// returning true, this sets Cond and Val to the condition that controls the
260/// trivial condition: when Cond dynamically equals Val, the loop is known to
261/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
262/// Cond == Val.
263///
264static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000265 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000266 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000267 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000268
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000269 BasicBlock *LoopExitBB = 0;
270 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
271 // If the header block doesn't end with a conditional branch on Cond, we
272 // can't handle it.
273 if (!BI->isConditional() || BI->getCondition() != Cond)
274 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000275
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000276 // Check to see if a successor of the branch is guaranteed to go to the
277 // latch block or exit through a one exit block without having any
278 // side-effects. If so, determine the value of Cond that causes it to do
279 // this.
280 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000281 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000282 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000283 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000284 }
285 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
286 // If this isn't a switch on Cond, we can't handle it.
287 if (SI->getCondition() != Cond) return false;
288
289 // Check to see if a successor of the switch is guaranteed to go to the
290 // latch block or exit through a one exit block without having any
291 // side-effects. If so, determine the value of Cond that causes it to do
292 // this. Note that we can't trivially unswitch on the default case.
293 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
294 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
295 // Okay, we found a trivial case, remember the value that is trivial.
296 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000297 break;
298 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000299 }
300
Chris Lattnere5521db2006-02-22 23:55:00 +0000301 // If we didn't find a single unique LoopExit block, or if the loop exit block
302 // contains phi nodes, this isn't trivial.
303 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000304 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000305
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000306 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000307
308 // We already know that nothing uses any scalar values defined inside of this
309 // loop. As such, we just have to check to see if this loop will execute any
310 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000311 // part of the loop that the code *would* execute. We already checked the
312 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000313 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
314 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000315 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000316 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000317}
318
319/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
320/// we choose to unswitch the specified loop on the specified value.
321///
322unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
323 // If the condition is trivial, always unswitch. There is no code growth for
324 // this case.
325 if (IsTrivialUnswitchCondition(L, LIC))
326 return 0;
327
Owen Anderson18e816f2006-06-28 17:47:50 +0000328 // FIXME: This is really overly conservative. However, more liberal
329 // estimations have thus far resulted in excessive unswitching, which is bad
330 // both in compile time and in code size. This should be replaced once
331 // someone figures out how a good estimation.
332 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000333
Chris Lattnered7a67b2006-02-10 01:24:09 +0000334 unsigned Cost = 0;
335 // FIXME: this is brain dead. It should take into consideration code
336 // shrinkage.
337 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
338 I != E; ++I) {
339 BasicBlock *BB = *I;
340 // Do not include empty blocks in the cost calculation. This happen due to
341 // loop canonicalization and will be removed.
342 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
343 continue;
344
345 // Count basic blocks.
346 ++Cost;
347 }
348
349 return Cost;
350}
351
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000352/// UnswitchIfProfitable - We have found that we can unswitch L when
353/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
354/// unswitch the loop, reprocess the pieces, then return true.
355bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
356 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000357 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
358 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000359 // FIXME: this should estimate growth by the amount of code shared by the
360 // resultant unswitched loops.
361 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000362 DOUT << "NOT unswitching loop %"
363 << L->getHeader()->getName() << ", cost too high: "
364 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000365 return false;
366 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000367
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000368 // If this is a trivial condition to unswitch (which results in no code
369 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000370 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000371 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000372 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
373 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000374 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000375 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000376 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000377
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000378 return true;
379}
380
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000381/// SplitBlock - Split the specified block at the specified instruction - every
382/// thing before SplitPt stays in Old and everything starting with SplitPt moves
383/// to a new block. The two blocks are joined by an unconditional branch and
384/// the loop info is updated.
385///
386BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000387 BasicBlock::iterator SplitIt = SplitPt;
388 while (isa<PHINode>(SplitIt))
389 ++SplitIt;
390 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000391
392 // The new block lives in whichever loop the old one did.
393 if (Loop *L = LI->getLoopFor(Old))
394 L->addBasicBlockToLoop(New, *LI);
395
396 return New;
397}
398
399
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000400BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
401 TerminatorInst *LatchTerm = BB->getTerminator();
402 unsigned SuccNum = 0;
403 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
404 assert(i != e && "Didn't find edge?");
405 if (LatchTerm->getSuccessor(i) == Succ) {
406 SuccNum = i;
407 break;
408 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000409 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000410
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000411 // If this is a critical edge, let SplitCriticalEdge do it.
412 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
413 return LatchTerm->getSuccessor(SuccNum);
414
415 // If the edge isn't critical, then BB has a single successor or Succ has a
416 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000417 BasicBlock::iterator SplitPoint;
418 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
419 // If the successor only has a single pred, split the top of the successor
420 // block.
421 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000422 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000423 } else {
424 // Otherwise, if BB has a single successor, split it at the bottom of the
425 // block.
426 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
427 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000428 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000429 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000430}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000431
Chris Lattnerf48f7772004-04-19 18:07:02 +0000432
433
Misha Brukmanb1c93172005-04-21 23:48:37 +0000434// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000435// current values into those specified by ValueMap.
436//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000437static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000438 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000439 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
440 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000441 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000442 if (It != ValueMap.end()) Op = It->second;
443 I->setOperand(op, Op);
444 }
445}
446
447/// CloneLoop - Recursively clone the specified loop and all of its children,
448/// mapping the blocks with the specified map.
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000449static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000450 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000451 Loop *New = new Loop();
452
Devang Patel901a27d2007-03-07 00:26:10 +0000453 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000454
455 // Add all of the blocks in L to the new loop.
456 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
457 I != E; ++I)
458 if (LI->getLoopFor(*I) == L)
459 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
460
461 // Add all of the subloops to the new loop.
462 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000463 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000464
Chris Lattnerf48f7772004-04-19 18:07:02 +0000465 return New;
466}
467
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000468/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
469/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
470/// code immediately before InsertPt.
471static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
472 BasicBlock *TrueDest,
473 BasicBlock *FalseDest,
474 Instruction *InsertPt) {
475 // Insert a conditional branch on LIC to the two preheaders. The original
476 // code is the true version and the new code is the false version.
477 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000478 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000479 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000480 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000481 // We want to enter the new loop when the condition is true.
482 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000483
484 // Insert the new branch.
485 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
486}
487
488
Chris Lattnered7a67b2006-02-10 01:24:09 +0000489/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
490/// condition in it (a cond branch from its header block to its latch block,
491/// where the path through the loop that doesn't execute its body has no
492/// side-effects), unswitch it. This doesn't involve any code duplication, just
493/// moving the conditional branch outside of the loop and updating loop info.
494void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000495 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000496 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000497 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
498 << L->getHeader()->getName() << " [" << L->getBlocks().size()
499 << " blocks] in Function " << L->getHeader()->getParent()->getName()
500 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000501
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000502 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000503 // to insert the conditional branch. We will change 'OrigPH' to have a
504 // conditional branch on Cond.
505 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000506 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000507
508 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000509 // to branch to: this is the exit block out of the loop that we should
510 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000511
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000512 // Split this block now, so that the loop maintains its exit block, and so
513 // that the jump from the preheader can execute the contents of the exit block
514 // without actually branching to it (the exit block should be dominated by the
515 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000516 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000517 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000518
Chris Lattnered7a67b2006-02-10 01:24:09 +0000519 // Okay, now we have a position to branch from and a position to branch to,
520 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000521 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
522 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000523 OrigPH->getTerminator()->eraseFromParent();
524
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000525 // We need to reprocess this loop, it could be unswitched again.
Devang Patel901a27d2007-03-07 00:26:10 +0000526 LPM->redoLoop(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000527
Chris Lattnered7a67b2006-02-10 01:24:09 +0000528 // Now that we know that the loop is never entered when this condition is a
529 // particular value, rewrite the loop with this info. We know that this will
530 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000531 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000532 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000533}
534
Chris Lattnerf48f7772004-04-19 18:07:02 +0000535
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000536/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
537/// equal Val. Split it into loop versions and test the condition outside of
538/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000539void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
540 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000541 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000542 DOUT << "loop-unswitch: Unswitching loop %"
543 << L->getHeader()->getName() << " [" << L->getBlocks().size()
544 << " blocks] in Function " << F->getName()
545 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000546
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000547 // LoopBlocks contains all of the basic blocks of the loop, including the
548 // preheader of the loop, the body of the loop, and the exit blocks of the
549 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000550 std::vector<BasicBlock*> LoopBlocks;
551
552 // First step, split the preheader and exit blocks, and add these blocks to
553 // the LoopBlocks list.
554 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000555 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000556
557 // We want the loop to come after the preheader, but before the exit blocks.
558 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
559
560 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000561 L->getUniqueExitBlocks(ExitBlocks);
562
Owen Andersonf52351e2006-06-26 07:44:36 +0000563 // Split all of the edges from inside the loop to their exit blocks. Update
564 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000565 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000566 BasicBlock *ExitBlock = ExitBlocks[i];
567 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
568
569 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
570 assert(L->contains(Preds[j]) &&
571 "All preds of loop exit blocks must be the same loop!");
Owen Andersonf52351e2006-06-26 07:44:36 +0000572 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
573 BasicBlock* StartBlock = Preds[j];
574 BasicBlock* EndBlock;
575 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
576 EndBlock = MiddleBlock;
577 MiddleBlock = EndBlock->getSinglePredecessor();;
578 } else {
579 EndBlock = ExitBlock;
580 }
581
582 std::set<PHINode*> InsertedPHIs;
583 PHINode* OldLCSSA = 0;
584 for (BasicBlock::iterator I = EndBlock->begin();
585 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
586 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
587 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
588 OldLCSSA->getName() + ".us-lcssa",
589 MiddleBlock->getTerminator());
590 NewLCSSA->addIncoming(OldValue, StartBlock);
591 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
592 NewLCSSA);
593 InsertedPHIs.insert(NewLCSSA);
594 }
595
Owen Anderson00b974c2006-07-19 03:51:48 +0000596 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000597 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
598 for (BasicBlock::iterator I = MiddleBlock->begin();
599 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
600 ++I) {
601 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
602 OldLCSSA->getName() + ".us-lcssa",
603 InsertPt);
604 OldLCSSA->replaceAllUsesWith(NewLCSSA);
605 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
606 }
607 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000608 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000609
610 // The exit blocks may have been changed due to edge splitting, recompute.
611 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000612 L->getUniqueExitBlocks(ExitBlocks);
613
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000614 // Add exit blocks to the loop blocks.
615 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000616
617 // Next step, clone all of the basic blocks that make up the loop (including
618 // the loop preheader and exit blocks), keeping track of the mapping between
619 // the instructions and blocks.
620 std::vector<BasicBlock*> NewBlocks;
621 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000622 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000623 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000624 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
625 NewBlocks.push_back(New);
626 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000627 }
628
629 // Splice the newly inserted blocks into the function right before the
630 // original preheader.
631 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
632 NewBlocks[0], F->end());
633
634 // Now we create the new Loop object for the versioned loop.
Devang Patel901a27d2007-03-07 00:26:10 +0000635 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000636 Loop *ParentLoop = L->getParentLoop();
637 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000638 // Make sure to add the cloned preheader and exit blocks to the parent loop
639 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000640 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
641 }
642
643 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
644 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000645 // The new exit block should be in the same loop as the old one.
646 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
647 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000648
649 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
650 "Exit block should have been split to have one successor!");
651 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
652
653 // If the successor of the exit block had PHI nodes, add an entry for
654 // NewExit.
655 PHINode *PN;
656 for (BasicBlock::iterator I = ExitSucc->begin();
657 (PN = dyn_cast<PHINode>(I)); ++I) {
658 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000659 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000660 if (It != ValueMap.end()) V = It->second;
661 PN->addIncoming(V, NewExit);
662 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000663 }
664
665 // Rewrite the code to refer to itself.
666 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
667 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
668 E = NewBlocks[i]->end(); I != E; ++I)
669 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000670
Chris Lattnerf48f7772004-04-19 18:07:02 +0000671 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000672 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
673 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000674 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000675
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000676 // Emit the new branch that selects between the two versions of this loop.
677 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
678 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000679
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000680 LoopProcessWorklist.push_back(NewLoop);
Devang Patel901a27d2007-03-07 00:26:10 +0000681 LPM->redoLoop(L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000682
683 // Now we rewrite the original code to know that the condition is true and the
684 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000685 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
686
687 // It's possible that simplifying one loop could cause the other to be
688 // deleted. If so, don't simplify it.
689 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
690 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000691}
692
Chris Lattner6fd13622006-02-17 00:31:07 +0000693/// RemoveFromWorklist - Remove all instances of I from the worklist vector
694/// specified.
695static void RemoveFromWorklist(Instruction *I,
696 std::vector<Instruction*> &Worklist) {
697 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
698 Worklist.end(), I);
699 while (WI != Worklist.end()) {
700 unsigned Offset = WI-Worklist.begin();
701 Worklist.erase(WI);
702 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
703 }
704}
705
706/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
707/// program, replacing all uses with V and update the worklist.
708static void ReplaceUsesOfWith(Instruction *I, Value *V,
709 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000710 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000711
712 // Add uses to the worklist, which may be dead now.
713 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
714 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
715 Worklist.push_back(Use);
716
717 // Add users to the worklist which may be simplified now.
718 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
719 UI != E; ++UI)
720 Worklist.push_back(cast<Instruction>(*UI));
721 I->replaceAllUsesWith(V);
722 I->eraseFromParent();
723 RemoveFromWorklist(I, Worklist);
724 ++NumSimplify;
725}
726
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000727/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
728/// information, and remove any dead successors it has.
729///
730void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
731 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000732 if (pred_begin(BB) != pred_end(BB)) {
733 // This block isn't dead, since an edge to BB was just removed, see if there
734 // are any easy simplifications we can do now.
735 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
736 // If it has one pred, fold phi nodes in BB.
737 while (isa<PHINode>(BB->begin()))
738 ReplaceUsesOfWith(BB->begin(),
739 cast<PHINode>(BB->begin())->getIncomingValue(0),
740 Worklist);
741
742 // If this is the header of a loop and the only pred is the latch, we now
743 // have an unreachable loop.
744 if (Loop *L = LI->getLoopFor(BB))
745 if (L->getHeader() == BB && L->contains(Pred)) {
746 // Remove the branch from the latch to the header block, this makes
747 // the header dead, which will make the latch dead (because the header
748 // dominates the latch).
749 Pred->getTerminator()->eraseFromParent();
750 new UnreachableInst(Pred);
751
752 // The loop is now broken, remove it from LI.
753 RemoveLoopFromHierarchy(L);
754
755 // Reprocess the header, which now IS dead.
756 RemoveBlockIfDead(BB, Worklist);
757 return;
758 }
759
760 // If pred ends in a uncond branch, add uncond branch to worklist so that
761 // the two blocks will get merged.
762 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
763 if (BI->isUnconditional())
764 Worklist.push_back(BI);
765 }
766 return;
767 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000768
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000769 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000770
771 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000772 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000773 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000774
775 // Anything that uses the instructions in this basic block should have their
776 // uses replaced with undefs.
777 if (!I->use_empty())
778 I->replaceAllUsesWith(UndefValue::get(I->getType()));
779 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000780
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000781 // If this is the edge to the header block for a loop, remove the loop and
782 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000783 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000784 if (BBLoop->getLoopLatch() == BB)
785 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000786 }
787
788 // Remove the block from the loop info, which removes it from any loops it
789 // was in.
790 LI->removeBlock(BB);
791
792
793 // Remove phi node entries in successors for this block.
794 TerminatorInst *TI = BB->getTerminator();
795 std::vector<BasicBlock*> Succs;
796 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
797 Succs.push_back(TI->getSuccessor(i));
798 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000799 }
800
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000801 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000802 std::sort(Succs.begin(), Succs.end());
803 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
804
805 // Remove the basic block, including all of the instructions contained in it.
806 BB->eraseFromParent();
807
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000808 // Remove successor blocks here that are not dead, so that we know we only
809 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
810 // then getting removed before we revisit them, which is badness.
811 //
812 for (unsigned i = 0; i != Succs.size(); ++i)
813 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
814 // One exception is loop headers. If this block was the preheader for a
815 // loop, then we DO want to visit the loop so the loop gets deleted.
816 // We know that if the successor is a loop header, that this loop had to
817 // be the preheader: the case where this was the latch block was handled
818 // above and headers can only have two predecessors.
819 if (!LI->isLoopHeader(Succs[i])) {
820 Succs.erase(Succs.begin()+i);
821 --i;
822 }
823 }
824
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000825 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
826 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000827}
Chris Lattner6fd13622006-02-17 00:31:07 +0000828
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000829/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
830/// become unwrapped, either because the backedge was deleted, or because the
831/// edge into the header was removed. If the edge into the header from the
832/// latch block was removed, the loop is unwrapped but subloops are still alive,
833/// so they just reparent loops. If the loops are actually dead, they will be
834/// removed later.
835void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000836 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000837 RemoveLoopFromWorklist(L);
838}
839
840
841
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000842// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
843// the value specified by Val in the specified loop, or we know it does NOT have
844// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000845void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000846 Constant *Val,
847 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000848 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000849
Chris Lattnerf48f7772004-04-19 18:07:02 +0000850 // FIXME: Support correlated properties, like:
851 // for (...)
852 // if (li1 < li2)
853 // ...
854 // if (li1 > li2)
855 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000856
Chris Lattner6e263152006-02-10 02:30:37 +0000857 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
858 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000859 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000860 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000861
Chris Lattner6fd13622006-02-17 00:31:07 +0000862 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
863 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000864 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000865 Value *Replacement;
866 if (IsEqual)
867 Replacement = Val;
868 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000869 Replacement = ConstantInt::get(Type::Int1Ty,
870 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000871
872 for (unsigned i = 0, e = Users.size(); i != e; ++i)
873 if (Instruction *U = cast<Instruction>(Users[i])) {
874 if (!L->contains(U->getParent()))
875 continue;
876 U->replaceUsesOfWith(LIC, Replacement);
877 Worklist.push_back(U);
878 }
879 } else {
880 // Otherwise, we don't know the precise value of LIC, but we do know that it
881 // is certainly NOT "Val". As such, simplify any uses in the loop that we
882 // can. This case occurs when we unswitch switch statements.
883 for (unsigned i = 0, e = Users.size(); i != e; ++i)
884 if (Instruction *U = cast<Instruction>(Users[i])) {
885 if (!L->contains(U->getParent()))
886 continue;
887
888 Worklist.push_back(U);
889
Chris Lattnerfa335f62006-02-16 19:36:22 +0000890 // If we know that LIC is not Val, use this info to simplify code.
891 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
892 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
893 if (SI->getCaseValue(i) == Val) {
894 // Found a dead case value. Don't remove PHI nodes in the
895 // successor if they become single-entry, those PHI nodes may
896 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000897
898 // FIXME: This is a hack. We need to keep the successor around
899 // and hooked up so as to preserve the loop structure, because
900 // trying to update it is complicated. So instead we preserve the
901 // loop structure and put the block on an dead code path.
902
903 BasicBlock* Old = SI->getParent();
904 BasicBlock* Split = SplitBlock(Old, SI);
905
906 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000907 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000908 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000909
910 Old->getTerminator()->eraseFromParent();
911
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000912
913 PHINode *PN;
914 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
915 (PN = dyn_cast<PHINode>(II)); ++II) {
916 Value *InVal = PN->removeIncomingValue(Split, false);
917 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +0000918 }
919
Chris Lattnerfa335f62006-02-16 19:36:22 +0000920 SI->removeCase(i);
921 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000922 }
923 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000924 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000925
926 // TODO: We could do other simplifications, for example, turning
927 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000928 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000929 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000930
931 SimplifyCode(Worklist);
932}
933
934/// SimplifyCode - Okay, now that we have simplified some instructions in the
935/// loop, walk over it and constant prop, dce, and fold control flow where
936/// possible. Note that this is effectively a very simple loop-structure-aware
937/// optimizer. During processing of this loop, L could very well be deleted, so
938/// it must not be used.
939///
940/// FIXME: When the loop optimizer is more mature, separate this out to a new
941/// pass.
942///
943void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +0000944 while (!Worklist.empty()) {
945 Instruction *I = Worklist.back();
946 Worklist.pop_back();
947
948 // Simple constant folding.
949 if (Constant *C = ConstantFoldInstruction(I)) {
950 ReplaceUsesOfWith(I, C, Worklist);
951 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +0000952 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000953
954 // Simple DCE.
955 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000956 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000957
958 // Add uses to the worklist, which may be dead now.
959 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
960 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
961 Worklist.push_back(Use);
962 I->eraseFromParent();
963 RemoveFromWorklist(I, Worklist);
964 ++NumSimplify;
965 continue;
966 }
967
968 // Special case hacks that appear commonly in unswitched code.
969 switch (I->getOpcode()) {
970 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000971 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +0000972 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +0000973 continue;
974 }
975 break;
976 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000977 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +0000978 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +0000979 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000980 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +0000981 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +0000982 if (CB->isOne()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +0000983 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
984 else // X & 0 -> 0
985 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
986 continue;
987 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000988 break;
989 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000990 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +0000991 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +0000992 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000993 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +0000994 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +0000995 if (CB->isOne()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +0000996 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
997 else // X | 0 -> X
998 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
999 continue;
1000 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001001 break;
1002 case Instruction::Br: {
1003 BranchInst *BI = cast<BranchInst>(I);
1004 if (BI->isUnconditional()) {
1005 // If BI's parent is the only pred of the successor, fold the two blocks
1006 // together.
1007 BasicBlock *Pred = BI->getParent();
1008 BasicBlock *Succ = BI->getSuccessor(0);
1009 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1010 if (!SinglePred) continue; // Nothing to do.
1011 assert(SinglePred == Pred && "CFG broken");
1012
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001013 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1014 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001015
1016 // Resolve any single entry PHI nodes in Succ.
1017 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1018 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1019
1020 // Move all of the successor contents from Succ to Pred.
1021 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1022 Succ->end());
1023 BI->eraseFromParent();
1024 RemoveFromWorklist(BI, Worklist);
1025
1026 // If Succ has any successors with PHI nodes, update them to have
1027 // entries coming from Pred instead of Succ.
1028 Succ->replaceAllUsesWith(Pred);
1029
1030 // Remove Succ from the loop tree.
1031 LI->removeBlock(Succ);
1032 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001033 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001034 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001035 // Conditional branch. Turn it into an unconditional branch, then
1036 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001037 break; // FIXME: Enable.
1038
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001039 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001040 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1041 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001042 DeadSucc->removePredecessor(BI->getParent(), true);
1043 Worklist.push_back(new BranchInst(LiveSucc, BI));
1044 BI->eraseFromParent();
1045 RemoveFromWorklist(BI, Worklist);
1046 ++NumSimplify;
1047
1048 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001049 }
1050 break;
1051 }
1052 }
1053 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001054}