blob: 142299dc9973490a09aafdae17d6a0ec0be39566 [file] [log] [blame]
Chris Lattnerf48f7772004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf48f7772004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf48f7772004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
11// to have multiple loops. For example, it turns the left into the right code:
12//
13// for (...) if (lic)
14// A for (...)
15// if (lic) A; B; C
16// B else
17// C for (...)
18// A; C
19//
20// This can increase the size of the code exponentially (doubling it every time
21// a loop is unswitched) so we only unswitch if the resultant code will be
22// smaller than a threshold.
23//
24// This pass expects LICM to be run before it to hoist invariant conditions out
25// of the loop, to make the unswitching opportunity obvious.
26//
27//===----------------------------------------------------------------------===//
28
29#define DEBUG_TYPE "loop-unswitch"
30#include "llvm/Transforms/Scalar.h"
31#include "llvm/Constants.h"
Reid Spencera94d3942007-01-19 21:13:56 +000032#include "llvm/DerivedTypes.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000033#include "llvm/Function.h"
34#include "llvm/Instructions.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000035#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000036#include "llvm/Analysis/LoopInfo.h"
Devang Patel901a27d2007-03-07 00:26:10 +000037#include "llvm/Analysis/LoopPass.h"
Devang Patel3304e462007-06-28 00:49:00 +000038#include "llvm/Analysis/Dominators.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000039#include "llvm/Transforms/Utils/Cloning.h"
40#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerec6b40a2006-02-10 19:08:15 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
Devang Patel97517ff2007-02-26 20:22:50 +000043#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000044#include "llvm/ADT/PostOrderIterator.h"
Chris Lattner89762192006-02-09 20:15:48 +000045#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000046#include "llvm/Support/Compiler.h"
47#include "llvm/Support/Debug.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000048#include <algorithm>
Chris Lattner2826e052006-02-09 19:14:52 +000049#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000050using namespace llvm;
51
Chris Lattner79a42ac2006-12-19 21:40:18 +000052STATISTIC(NumBranches, "Number of branches unswitched");
53STATISTIC(NumSwitches, "Number of switches unswitched");
54STATISTIC(NumSelects , "Number of selects unswitched");
55STATISTIC(NumTrivial , "Number of unswitches that are trivial");
56STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
57
Chris Lattnerf48f7772004-04-19 18:07:02 +000058namespace {
Chris Lattner89762192006-02-09 20:15:48 +000059 cl::opt<unsigned>
60 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
61 cl::init(10), cl::Hidden);
62
Devang Patel901a27d2007-03-07 00:26:10 +000063 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +000064 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +000065 LPPassManager *LPM;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000066
Devang Patel901a27d2007-03-07 00:26:10 +000067 // LoopProcessWorklist - Used to check if second loop needs processing
68 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000069 std::vector<Loop*> LoopProcessWorklist;
Devang Patel97517ff2007-02-26 20:22:50 +000070 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel506310d2007-06-06 00:21:03 +000071
72 bool OptimizeForSize;
Chris Lattnerf48f7772004-04-19 18:07:02 +000073 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000074 static char ID; // Pass ID, replacement for typeid
Devang Patel506310d2007-06-06 00:21:03 +000075 LoopUnswitch(bool Os = false) :
76 LoopPass((intptr_t)&ID), OptimizeForSize(Os) {}
Devang Patel09f162c2007-05-01 21:15:47 +000077
Devang Patel901a27d2007-03-07 00:26:10 +000078 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattnerf48f7772004-04-19 18:07:02 +000079
80 /// This transformation requires natural loop information & requires that
81 /// loop preheaders be inserted into the CFG...
82 ///
83 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000085 AU.addPreservedID(LoopSimplifyID);
Devang Patel3304e462007-06-28 00:49:00 +000086 AU.addPreserved<DominatorTree>();
Chris Lattnerf48f7772004-04-19 18:07:02 +000087 AU.addRequired<LoopInfo>();
88 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000089 AU.addRequiredID(LCSSAID);
90 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000091 }
92
93 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000094 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
95 /// remove it.
96 void RemoveLoopFromWorklist(Loop *L) {
97 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
98 LoopProcessWorklist.end(), L);
99 if (I != LoopProcessWorklist.end())
100 LoopProcessWorklist.erase(I);
101 }
102
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000103 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000104 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +0000105 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000106 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000107 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000108 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000109 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000110
111 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
112 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000113
114 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
115 BasicBlock *TrueDest,
116 BasicBlock *FalseDest,
117 Instruction *InsertPt);
118
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000119 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000120 void RemoveBlockIfDead(BasicBlock *BB,
121 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000122 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000123 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000124 char LoopUnswitch::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000125 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000126}
127
Devang Patel506310d2007-06-06 00:21:03 +0000128LoopPass *llvm::createLoopUnswitchPass(bool Os) {
129 return new LoopUnswitch(Os);
130}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000131
132/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
133/// invariant in the loop, or has an invariant piece, return the invariant.
134/// Otherwise, return null.
135static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
136 // Constants should be folded, not unswitched on!
137 if (isa<Constant>(Cond)) return false;
Devang Patel3c723c82007-06-28 00:44:10 +0000138
139 // If cond is not in loop then it is not suitable.
140 if (Instruction *I = dyn_cast<Instruction>(Cond))
141 if (!L->contains(I->getParent()))
142 return 0;
143 if (isa<Argument>(Cond))
144 return 0;
Devang Patel3304e462007-06-28 00:49:00 +0000145
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000146 // TODO: Handle: br (VARIANT|INVARIANT).
147 // TODO: Hoist simple expressions out of loops.
148 if (L->isLoopInvariant(Cond)) return Cond;
149
150 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
151 if (BO->getOpcode() == Instruction::And ||
152 BO->getOpcode() == Instruction::Or) {
153 // If either the left or right side is invariant, we can unswitch on this,
154 // which will cause the branch to go away in one loop and the condition to
155 // simplify in the other one.
156 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
157 return LHS;
158 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
159 return RHS;
160 }
161
162 return 0;
163}
164
Devang Patel901a27d2007-03-07 00:26:10 +0000165bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000166 assert(L->isLCSSAForm());
Devang Patel901a27d2007-03-07 00:26:10 +0000167 LI = &getAnalysis<LoopInfo>();
168 LPM = &LPM_Ref;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000169 bool Changed = false;
170
171 // Loop over all of the basic blocks in the loop. If we find an interior
172 // block that is branching on a loop-invariant condition, we can unswitch this
173 // loop.
174 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
175 I != E; ++I) {
176 TerminatorInst *TI = (*I)->getTerminator();
177 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
178 // If this isn't branching on an invariant condition, we can't unswitch
179 // it.
180 if (BI->isConditional()) {
181 // See if this, or some part of it, is loop invariant. If so, we can
182 // unswitch on it if we desire.
183 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000184 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000185 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000186 ++NumBranches;
187 return true;
188 }
189 }
190 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
191 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
192 if (LoopCond && SI->getNumCases() > 1) {
193 // Find a value to unswitch on:
194 // FIXME: this should chose the most expensive case!
195 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000196 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000197 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000198 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000199
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000200 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
201 ++NumSwitches;
202 return true;
203 }
204 }
205 }
206
207 // Scan the instructions to check for unswitchable values.
208 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
209 BBI != E; ++BBI)
210 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
211 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000212 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000213 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000214 ++NumSelects;
215 return true;
216 }
217 }
218 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000219
220 assert(L->isLCSSAForm());
221
Chris Lattnerf48f7772004-04-19 18:07:02 +0000222 return Changed;
223}
224
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000225/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
226/// 1. Exit the loop with no side effects.
227/// 2. Branch to the latch block with no side-effects.
228///
229/// If these conditions are true, we return true and set ExitBB to the block we
230/// exit through.
231///
232static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
233 BasicBlock *&ExitBB,
234 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000235 if (!Visited.insert(BB).second) {
236 // Already visited and Ok, end of recursion.
237 return true;
238 } else if (!L->contains(BB)) {
239 // Otherwise, this is a loop exit, this is fine so long as this is the
240 // first exit.
241 if (ExitBB != 0) return false;
242 ExitBB = BB;
243 return true;
244 }
245
246 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000247 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000248 // Check to see if the successor is a trivial loop exit.
249 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
250 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000251 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000252
253 // Okay, everything after this looks good, check to make sure that this block
254 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000255 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000256 if (I->mayWriteToMemory())
257 return false;
258
259 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000260}
261
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000262/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
263/// leads to an exit from the specified loop, and has no side-effects in the
264/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000265static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
266 std::set<BasicBlock*> Visited;
267 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000268 BasicBlock *ExitBB = 0;
269 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
270 return ExitBB;
271 return 0;
272}
Chris Lattner6e263152006-02-10 02:30:37 +0000273
Chris Lattnered7a67b2006-02-10 01:24:09 +0000274/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
275/// trivial: that is, that the condition controls whether or not the loop does
276/// anything at all. If this is a trivial condition, unswitching produces no
277/// code duplications (equivalently, it produces a simpler loop and a new empty
278/// loop, which gets deleted).
279///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000280/// If this is a trivial condition, return true, otherwise return false. When
281/// returning true, this sets Cond and Val to the condition that controls the
282/// trivial condition: when Cond dynamically equals Val, the loop is known to
283/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
284/// Cond == Val.
285///
286static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000287 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000288 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000289 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000290
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000291 BasicBlock *LoopExitBB = 0;
292 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
293 // If the header block doesn't end with a conditional branch on Cond, we
294 // can't handle it.
295 if (!BI->isConditional() || BI->getCondition() != Cond)
296 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000297
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000298 // Check to see if a successor of the branch is guaranteed to go to the
299 // latch block or exit through a one exit block without having any
300 // side-effects. If so, determine the value of Cond that causes it to do
301 // this.
302 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000303 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000304 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000305 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000306 }
307 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
308 // If this isn't a switch on Cond, we can't handle it.
309 if (SI->getCondition() != Cond) return false;
310
311 // Check to see if a successor of the switch is guaranteed to go to the
312 // latch block or exit through a one exit block without having any
313 // side-effects. If so, determine the value of Cond that causes it to do
314 // this. Note that we can't trivially unswitch on the default case.
315 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
316 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
317 // Okay, we found a trivial case, remember the value that is trivial.
318 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000319 break;
320 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000321 }
322
Chris Lattnere5521db2006-02-22 23:55:00 +0000323 // If we didn't find a single unique LoopExit block, or if the loop exit block
324 // contains phi nodes, this isn't trivial.
325 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000326 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000327
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000328 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000329
330 // We already know that nothing uses any scalar values defined inside of this
331 // loop. As such, we just have to check to see if this loop will execute any
332 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000333 // part of the loop that the code *would* execute. We already checked the
334 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000335 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
336 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000337 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000338 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000339}
340
341/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
342/// we choose to unswitch the specified loop on the specified value.
343///
344unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
345 // If the condition is trivial, always unswitch. There is no code growth for
346 // this case.
347 if (IsTrivialUnswitchCondition(L, LIC))
348 return 0;
349
Owen Anderson18e816f2006-06-28 17:47:50 +0000350 // FIXME: This is really overly conservative. However, more liberal
351 // estimations have thus far resulted in excessive unswitching, which is bad
352 // both in compile time and in code size. This should be replaced once
353 // someone figures out how a good estimation.
354 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000355
Chris Lattnered7a67b2006-02-10 01:24:09 +0000356 unsigned Cost = 0;
357 // FIXME: this is brain dead. It should take into consideration code
358 // shrinkage.
359 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
360 I != E; ++I) {
361 BasicBlock *BB = *I;
362 // Do not include empty blocks in the cost calculation. This happen due to
363 // loop canonicalization and will be removed.
364 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
365 continue;
366
367 // Count basic blocks.
368 ++Cost;
369 }
370
371 return Cost;
372}
373
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000374/// UnswitchIfProfitable - We have found that we can unswitch L when
375/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
376/// unswitch the loop, reprocess the pieces, then return true.
377bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
378 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000379 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
Devang Patel506310d2007-06-06 00:21:03 +0000380
381 // Do not do non-trivial unswitch while optimizing for size.
382 if (Cost && OptimizeForSize)
383 return false;
384
Chris Lattner5821a6a2006-03-24 07:14:00 +0000385 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000386 // FIXME: this should estimate growth by the amount of code shared by the
387 // resultant unswitched loops.
388 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000389 DOUT << "NOT unswitching loop %"
390 << L->getHeader()->getName() << ", cost too high: "
391 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000392 return false;
393 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000394
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000395 // If this is a trivial condition to unswitch (which results in no code
396 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000397 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000398 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000399 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
400 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000401 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000402 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000403 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000404
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000405 return true;
406}
407
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000408/// SplitBlock - Split the specified block at the specified instruction - every
409/// thing before SplitPt stays in Old and everything starting with SplitPt moves
410/// to a new block. The two blocks are joined by an unconditional branch and
411/// the loop info is updated.
412///
413BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000414 BasicBlock::iterator SplitIt = SplitPt;
415 while (isa<PHINode>(SplitIt))
416 ++SplitIt;
417 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000418
419 // The new block lives in whichever loop the old one did.
420 if (Loop *L = LI->getLoopFor(Old))
421 L->addBasicBlockToLoop(New, *LI);
Devang Patel95572472007-05-09 08:24:12 +0000422
Devang Patel3304e462007-06-28 00:49:00 +0000423 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
424 DT->addNewBlock(New, Old);
425
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000426 return New;
427}
428
429
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000430BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
431 TerminatorInst *LatchTerm = BB->getTerminator();
432 unsigned SuccNum = 0;
433 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
434 assert(i != e && "Didn't find edge?");
435 if (LatchTerm->getSuccessor(i) == Succ) {
436 SuccNum = i;
437 break;
438 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000439 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000440
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000441 // If this is a critical edge, let SplitCriticalEdge do it.
Devang Patel3304e462007-06-28 00:49:00 +0000442 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
443 return LatchTerm->getSuccessor(SuccNum);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000444
445 // If the edge isn't critical, then BB has a single successor or Succ has a
446 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000447 BasicBlock::iterator SplitPoint;
448 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
449 // If the successor only has a single pred, split the top of the successor
450 // block.
451 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000452 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000453 } else {
454 // Otherwise, if BB has a single successor, split it at the bottom of the
455 // block.
456 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
457 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000458 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000459 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000460}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000461
Chris Lattnerf48f7772004-04-19 18:07:02 +0000462
463
Misha Brukmanb1c93172005-04-21 23:48:37 +0000464// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000465// current values into those specified by ValueMap.
466//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000467static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000468 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000469 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
470 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000471 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000472 if (It != ValueMap.end()) Op = It->second;
473 I->setOperand(op, Op);
474 }
475}
476
Devang Patel3304e462007-06-28 00:49:00 +0000477// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
478// If Orig is in Loop then find and use Orig dominator's cloned block as NewBB
479// dominator.
480void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig, Loop *L,
481 DominatorTree *DT,
482 DenseMap<const Value*, Value*> &VM) {
483
484 DomTreeNode *OrigNode = DT->getNode(Orig);
485 if (!OrigNode)
486 return;
487 BasicBlock *OrigIDom = OrigNode->getBlock();
488 BasicBlock *NewIDom = OrigIDom;
489 if (L->contains(OrigIDom)) {
490 if (!DT->getNode(OrigIDom))
491 CloneDomInfo(NewIDom, OrigIDom, L, DT, VM);
492 NewIDom = cast<BasicBlock>(VM[OrigIDom]);
493 }
494 DT->addNewBlock(NewBB, OrigIDom);
495}
496
Chris Lattnerf48f7772004-04-19 18:07:02 +0000497/// CloneLoop - Recursively clone the specified loop and all of its children,
498/// mapping the blocks with the specified map.
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000499static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000500 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000501 Loop *New = new Loop();
502
Devang Patel901a27d2007-03-07 00:26:10 +0000503 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000504
505 // Add all of the blocks in L to the new loop.
506 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
507 I != E; ++I)
508 if (LI->getLoopFor(*I) == L)
509 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
510
511 // Add all of the subloops to the new loop.
512 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000513 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000514
Chris Lattnerf48f7772004-04-19 18:07:02 +0000515 return New;
516}
517
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000518/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
519/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
520/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000521void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
522 BasicBlock *TrueDest,
523 BasicBlock *FalseDest,
524 Instruction *InsertPt) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000525 // Insert a conditional branch on LIC to the two preheaders. The original
526 // code is the true version and the new code is the false version.
527 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000528 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000529 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000530 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000531 // We want to enter the new loop when the condition is true.
532 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000533
534 // Insert the new branch.
Devang Patel3304e462007-06-28 00:49:00 +0000535 BranchInst *BRI = new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
536
537 // Update dominator info.
538 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
539 // BranchVal is a new preheader so it dominates true and false destination
540 // loop headers.
541 DT->changeImmediateDominator(TrueDest, BRI->getParent());
542 DT->changeImmediateDominator(FalseDest, BRI->getParent());
543 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000544}
545
546
Chris Lattnered7a67b2006-02-10 01:24:09 +0000547/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
548/// condition in it (a cond branch from its header block to its latch block,
549/// where the path through the loop that doesn't execute its body has no
550/// side-effects), unswitch it. This doesn't involve any code duplication, just
551/// moving the conditional branch outside of the loop and updating loop info.
552void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000553 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000554 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000555 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
556 << L->getHeader()->getName() << " [" << L->getBlocks().size()
557 << " blocks] in Function " << L->getHeader()->getParent()->getName()
558 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000559
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000560 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000561 // to insert the conditional branch. We will change 'OrigPH' to have a
562 // conditional branch on Cond.
563 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000564 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000565
566 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000567 // to branch to: this is the exit block out of the loop that we should
568 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000569
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000570 // Split this block now, so that the loop maintains its exit block, and so
571 // that the jump from the preheader can execute the contents of the exit block
572 // without actually branching to it (the exit block should be dominated by the
573 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000574 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000575 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000576
Chris Lattnered7a67b2006-02-10 01:24:09 +0000577 // Okay, now we have a position to branch from and a position to branch to,
578 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000579 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
580 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000581 OrigPH->getTerminator()->eraseFromParent();
582
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000583 // We need to reprocess this loop, it could be unswitched again.
Devang Patel901a27d2007-03-07 00:26:10 +0000584 LPM->redoLoop(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000585
Chris Lattnered7a67b2006-02-10 01:24:09 +0000586 // Now that we know that the loop is never entered when this condition is a
587 // particular value, rewrite the loop with this info. We know that this will
588 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000589 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000590 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000591}
592
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000593/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
594/// equal Val. Split it into loop versions and test the condition outside of
595/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000596void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
597 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000598 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000599 DOUT << "loop-unswitch: Unswitching loop %"
600 << L->getHeader()->getName() << " [" << L->getBlocks().size()
601 << " blocks] in Function " << F->getName()
602 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000603
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000604 // LoopBlocks contains all of the basic blocks of the loop, including the
605 // preheader of the loop, the body of the loop, and the exit blocks of the
606 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000607 std::vector<BasicBlock*> LoopBlocks;
608
609 // First step, split the preheader and exit blocks, and add these blocks to
610 // the LoopBlocks list.
611 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000612 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000613
614 // We want the loop to come after the preheader, but before the exit blocks.
615 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
616
617 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000618 L->getUniqueExitBlocks(ExitBlocks);
619
Owen Andersonf52351e2006-06-26 07:44:36 +0000620 // Split all of the edges from inside the loop to their exit blocks. Update
621 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000622 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000623 BasicBlock *ExitBlock = ExitBlocks[i];
624 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
625
626 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Owen Andersonf52351e2006-06-26 07:44:36 +0000627 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
628 BasicBlock* StartBlock = Preds[j];
629 BasicBlock* EndBlock;
630 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
631 EndBlock = MiddleBlock;
632 MiddleBlock = EndBlock->getSinglePredecessor();;
633 } else {
634 EndBlock = ExitBlock;
635 }
636
637 std::set<PHINode*> InsertedPHIs;
638 PHINode* OldLCSSA = 0;
639 for (BasicBlock::iterator I = EndBlock->begin();
640 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
641 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
642 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
643 OldLCSSA->getName() + ".us-lcssa",
644 MiddleBlock->getTerminator());
645 NewLCSSA->addIncoming(OldValue, StartBlock);
646 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
647 NewLCSSA);
648 InsertedPHIs.insert(NewLCSSA);
649 }
650
Owen Anderson00b974c2006-07-19 03:51:48 +0000651 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000652 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
653 for (BasicBlock::iterator I = MiddleBlock->begin();
654 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
655 ++I) {
656 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
657 OldLCSSA->getName() + ".us-lcssa",
658 InsertPt);
659 OldLCSSA->replaceAllUsesWith(NewLCSSA);
660 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
661 }
662 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000663 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000664
665 // The exit blocks may have been changed due to edge splitting, recompute.
666 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000667 L->getUniqueExitBlocks(ExitBlocks);
668
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000669 // Add exit blocks to the loop blocks.
670 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000671
672 // Next step, clone all of the basic blocks that make up the loop (including
673 // the loop preheader and exit blocks), keeping track of the mapping between
674 // the instructions and blocks.
675 std::vector<BasicBlock*> NewBlocks;
676 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000677 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000678 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000679 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
680 NewBlocks.push_back(New);
681 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000682 }
683
Devang Patel3304e462007-06-28 00:49:00 +0000684 // Update dominator info
685 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
686 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
687 BasicBlock *LBB = LoopBlocks[i];
688 BasicBlock *NBB = NewBlocks[i];
689 CloneDomInfo(NBB, LBB, L, DT, ValueMap);
690 }
691
Chris Lattnerf48f7772004-04-19 18:07:02 +0000692 // Splice the newly inserted blocks into the function right before the
693 // original preheader.
694 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
695 NewBlocks[0], F->end());
696
697 // Now we create the new Loop object for the versioned loop.
Devang Patel901a27d2007-03-07 00:26:10 +0000698 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000699 Loop *ParentLoop = L->getParentLoop();
700 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000701 // Make sure to add the cloned preheader and exit blocks to the parent loop
702 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000703 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
704 }
705
706 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
707 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000708 // The new exit block should be in the same loop as the old one.
709 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
710 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000711
712 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
713 "Exit block should have been split to have one successor!");
714 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
715
716 // If the successor of the exit block had PHI nodes, add an entry for
717 // NewExit.
718 PHINode *PN;
719 for (BasicBlock::iterator I = ExitSucc->begin();
720 (PN = dyn_cast<PHINode>(I)); ++I) {
721 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000722 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000723 if (It != ValueMap.end()) V = It->second;
724 PN->addIncoming(V, NewExit);
725 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000726 }
727
728 // Rewrite the code to refer to itself.
729 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
730 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
731 E = NewBlocks[i]->end(); I != E; ++I)
732 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000733
Chris Lattnerf48f7772004-04-19 18:07:02 +0000734 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000735 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
736 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000737 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000738
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000739 // Emit the new branch that selects between the two versions of this loop.
740 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
741 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000742
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000743 LoopProcessWorklist.push_back(NewLoop);
Devang Patel901a27d2007-03-07 00:26:10 +0000744 LPM->redoLoop(L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000745
746 // Now we rewrite the original code to know that the condition is true and the
747 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000748 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
749
750 // It's possible that simplifying one loop could cause the other to be
751 // deleted. If so, don't simplify it.
752 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
753 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000754}
755
Chris Lattner6fd13622006-02-17 00:31:07 +0000756/// RemoveFromWorklist - Remove all instances of I from the worklist vector
757/// specified.
758static void RemoveFromWorklist(Instruction *I,
759 std::vector<Instruction*> &Worklist) {
760 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
761 Worklist.end(), I);
762 while (WI != Worklist.end()) {
763 unsigned Offset = WI-Worklist.begin();
764 Worklist.erase(WI);
765 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
766 }
767}
768
769/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
770/// program, replacing all uses with V and update the worklist.
771static void ReplaceUsesOfWith(Instruction *I, Value *V,
772 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000773 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000774
775 // Add uses to the worklist, which may be dead now.
776 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
777 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
778 Worklist.push_back(Use);
779
780 // Add users to the worklist which may be simplified now.
781 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
782 UI != E; ++UI)
783 Worklist.push_back(cast<Instruction>(*UI));
784 I->replaceAllUsesWith(V);
785 I->eraseFromParent();
786 RemoveFromWorklist(I, Worklist);
787 ++NumSimplify;
788}
789
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000790/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
791/// information, and remove any dead successors it has.
792///
793void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
794 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000795 if (pred_begin(BB) != pred_end(BB)) {
796 // This block isn't dead, since an edge to BB was just removed, see if there
797 // are any easy simplifications we can do now.
798 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
799 // If it has one pred, fold phi nodes in BB.
800 while (isa<PHINode>(BB->begin()))
801 ReplaceUsesOfWith(BB->begin(),
802 cast<PHINode>(BB->begin())->getIncomingValue(0),
803 Worklist);
804
805 // If this is the header of a loop and the only pred is the latch, we now
806 // have an unreachable loop.
807 if (Loop *L = LI->getLoopFor(BB))
808 if (L->getHeader() == BB && L->contains(Pred)) {
809 // Remove the branch from the latch to the header block, this makes
810 // the header dead, which will make the latch dead (because the header
811 // dominates the latch).
812 Pred->getTerminator()->eraseFromParent();
813 new UnreachableInst(Pred);
814
815 // The loop is now broken, remove it from LI.
816 RemoveLoopFromHierarchy(L);
817
818 // Reprocess the header, which now IS dead.
819 RemoveBlockIfDead(BB, Worklist);
820 return;
821 }
822
823 // If pred ends in a uncond branch, add uncond branch to worklist so that
824 // the two blocks will get merged.
825 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
826 if (BI->isUnconditional())
827 Worklist.push_back(BI);
828 }
829 return;
830 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000831
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000832 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000833
834 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000835 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000836 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000837
838 // Anything that uses the instructions in this basic block should have their
839 // uses replaced with undefs.
840 if (!I->use_empty())
841 I->replaceAllUsesWith(UndefValue::get(I->getType()));
842 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000843
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000844 // If this is the edge to the header block for a loop, remove the loop and
845 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000846 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000847 if (BBLoop->getLoopLatch() == BB)
848 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000849 }
850
851 // Remove the block from the loop info, which removes it from any loops it
852 // was in.
853 LI->removeBlock(BB);
854
855
856 // Remove phi node entries in successors for this block.
857 TerminatorInst *TI = BB->getTerminator();
858 std::vector<BasicBlock*> Succs;
859 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
860 Succs.push_back(TI->getSuccessor(i));
861 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000862 }
863
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000864 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000865 std::sort(Succs.begin(), Succs.end());
866 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
867
868 // Remove the basic block, including all of the instructions contained in it.
869 BB->eraseFromParent();
870
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000871 // Remove successor blocks here that are not dead, so that we know we only
872 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
873 // then getting removed before we revisit them, which is badness.
874 //
875 for (unsigned i = 0; i != Succs.size(); ++i)
876 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
877 // One exception is loop headers. If this block was the preheader for a
878 // loop, then we DO want to visit the loop so the loop gets deleted.
879 // We know that if the successor is a loop header, that this loop had to
880 // be the preheader: the case where this was the latch block was handled
881 // above and headers can only have two predecessors.
882 if (!LI->isLoopHeader(Succs[i])) {
883 Succs.erase(Succs.begin()+i);
884 --i;
885 }
886 }
887
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000888 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
889 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000890}
Chris Lattner6fd13622006-02-17 00:31:07 +0000891
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000892/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
893/// become unwrapped, either because the backedge was deleted, or because the
894/// edge into the header was removed. If the edge into the header from the
895/// latch block was removed, the loop is unwrapped but subloops are still alive,
896/// so they just reparent loops. If the loops are actually dead, they will be
897/// removed later.
898void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000899 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000900 RemoveLoopFromWorklist(L);
901}
902
903
904
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000905// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
906// the value specified by Val in the specified loop, or we know it does NOT have
907// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000908void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000909 Constant *Val,
910 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000911 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000912
Chris Lattnerf48f7772004-04-19 18:07:02 +0000913 // FIXME: Support correlated properties, like:
914 // for (...)
915 // if (li1 < li2)
916 // ...
917 // if (li1 > li2)
918 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000919
Chris Lattner6e263152006-02-10 02:30:37 +0000920 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
921 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000922 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000923 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000924
Chris Lattner6fd13622006-02-17 00:31:07 +0000925 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
926 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000927 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000928 Value *Replacement;
929 if (IsEqual)
930 Replacement = Val;
931 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000932 Replacement = ConstantInt::get(Type::Int1Ty,
933 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000934
935 for (unsigned i = 0, e = Users.size(); i != e; ++i)
936 if (Instruction *U = cast<Instruction>(Users[i])) {
937 if (!L->contains(U->getParent()))
938 continue;
939 U->replaceUsesOfWith(LIC, Replacement);
940 Worklist.push_back(U);
941 }
942 } else {
943 // Otherwise, we don't know the precise value of LIC, but we do know that it
944 // is certainly NOT "Val". As such, simplify any uses in the loop that we
945 // can. This case occurs when we unswitch switch statements.
946 for (unsigned i = 0, e = Users.size(); i != e; ++i)
947 if (Instruction *U = cast<Instruction>(Users[i])) {
948 if (!L->contains(U->getParent()))
949 continue;
950
951 Worklist.push_back(U);
952
Chris Lattnerfa335f62006-02-16 19:36:22 +0000953 // If we know that LIC is not Val, use this info to simplify code.
954 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
955 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
956 if (SI->getCaseValue(i) == Val) {
957 // Found a dead case value. Don't remove PHI nodes in the
958 // successor if they become single-entry, those PHI nodes may
959 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000960
961 // FIXME: This is a hack. We need to keep the successor around
962 // and hooked up so as to preserve the loop structure, because
963 // trying to update it is complicated. So instead we preserve the
964 // loop structure and put the block on an dead code path.
965
966 BasicBlock* Old = SI->getParent();
967 BasicBlock* Split = SplitBlock(Old, SI);
968
969 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000970 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000971 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000972
973 Old->getTerminator()->eraseFromParent();
974
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000975
976 PHINode *PN;
977 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
978 (PN = dyn_cast<PHINode>(II)); ++II) {
979 Value *InVal = PN->removeIncomingValue(Split, false);
980 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +0000981 }
982
Chris Lattnerfa335f62006-02-16 19:36:22 +0000983 SI->removeCase(i);
984 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000985 }
986 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000987 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000988
989 // TODO: We could do other simplifications, for example, turning
990 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000991 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000992 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000993
994 SimplifyCode(Worklist);
995}
996
997/// SimplifyCode - Okay, now that we have simplified some instructions in the
998/// loop, walk over it and constant prop, dce, and fold control flow where
999/// possible. Note that this is effectively a very simple loop-structure-aware
1000/// optimizer. During processing of this loop, L could very well be deleted, so
1001/// it must not be used.
1002///
1003/// FIXME: When the loop optimizer is more mature, separate this out to a new
1004/// pass.
1005///
1006void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001007 while (!Worklist.empty()) {
1008 Instruction *I = Worklist.back();
1009 Worklist.pop_back();
1010
1011 // Simple constant folding.
1012 if (Constant *C = ConstantFoldInstruction(I)) {
1013 ReplaceUsesOfWith(I, C, Worklist);
1014 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001015 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001016
1017 // Simple DCE.
1018 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001019 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +00001020
1021 // Add uses to the worklist, which may be dead now.
1022 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1023 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1024 Worklist.push_back(Use);
1025 I->eraseFromParent();
1026 RemoveFromWorklist(I, Worklist);
1027 ++NumSimplify;
1028 continue;
1029 }
1030
1031 // Special case hacks that appear commonly in unswitched code.
1032 switch (I->getOpcode()) {
1033 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001034 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001035 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001036 continue;
1037 }
1038 break;
1039 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001040 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001041 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001042 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001043 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001044 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001045 if (CB->isOne()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +00001046 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1047 else // X & 0 -> 0
1048 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1049 continue;
1050 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001051 break;
1052 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001053 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001054 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001055 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001056 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001057 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001058 if (CB->isOne()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001059 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1060 else // X | 0 -> X
1061 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1062 continue;
1063 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001064 break;
1065 case Instruction::Br: {
1066 BranchInst *BI = cast<BranchInst>(I);
1067 if (BI->isUnconditional()) {
1068 // If BI's parent is the only pred of the successor, fold the two blocks
1069 // together.
1070 BasicBlock *Pred = BI->getParent();
1071 BasicBlock *Succ = BI->getSuccessor(0);
1072 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1073 if (!SinglePred) continue; // Nothing to do.
1074 assert(SinglePred == Pred && "CFG broken");
1075
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001076 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1077 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001078
1079 // Resolve any single entry PHI nodes in Succ.
1080 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1081 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1082
1083 // Move all of the successor contents from Succ to Pred.
1084 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1085 Succ->end());
1086 BI->eraseFromParent();
1087 RemoveFromWorklist(BI, Worklist);
1088
1089 // If Succ has any successors with PHI nodes, update them to have
1090 // entries coming from Pred instead of Succ.
1091 Succ->replaceAllUsesWith(Pred);
1092
1093 // Remove Succ from the loop tree.
1094 LI->removeBlock(Succ);
1095 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001096 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001097 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001098 // Conditional branch. Turn it into an unconditional branch, then
1099 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001100 break; // FIXME: Enable.
1101
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001102 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001103 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1104 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001105 DeadSucc->removePredecessor(BI->getParent(), true);
1106 Worklist.push_back(new BranchInst(LiveSucc, BI));
1107 BI->eraseFromParent();
1108 RemoveFromWorklist(BI, Worklist);
1109 ++NumSimplify;
1110
1111 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001112 }
1113 break;
1114 }
1115 }
1116 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001117}