blob: 7ad3bd626c13f7dd8aefabb1a37dc04c62fdb214 [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 Patel506310d2007-06-06 00:21:03 +000070
71 bool OptimizeForSize;
Chris Lattnerf48f7772004-04-19 18:07:02 +000072 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000073 static char ID; // Pass ID, replacement for typeid
Devang Patel506310d2007-06-06 00:21:03 +000074 LoopUnswitch(bool Os = false) :
75 LoopPass((intptr_t)&ID), OptimizeForSize(Os) {}
Devang Patel09f162c2007-05-01 21:15:47 +000076
Devang Patel901a27d2007-03-07 00:26:10 +000077 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattnerf48f7772004-04-19 18:07:02 +000078
79 /// This transformation requires natural loop information & requires that
80 /// loop preheaders be inserted into the CFG...
81 ///
82 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000084 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000085 AU.addRequired<LoopInfo>();
86 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000087 AU.addRequiredID(LCSSAID);
88 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000089 }
90
91 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000092 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
93 /// remove it.
94 void RemoveLoopFromWorklist(Loop *L) {
95 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
96 LoopProcessWorklist.end(), L);
97 if (I != LoopProcessWorklist.end())
98 LoopProcessWorklist.erase(I);
99 }
100
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000101 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000102 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +0000103 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000104 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000105 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000106 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000107 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000108
109 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
110 Constant *Val, bool isEqual);
111
112 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000113 void RemoveBlockIfDead(BasicBlock *BB,
114 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000115 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000116 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000117 char LoopUnswitch::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000118 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000119}
120
Devang Patel506310d2007-06-06 00:21:03 +0000121LoopPass *llvm::createLoopUnswitchPass(bool Os) {
122 return new LoopUnswitch(Os);
123}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000124
125/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
126/// invariant in the loop, or has an invariant piece, return the invariant.
127/// Otherwise, return null.
128static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
129 // Constants should be folded, not unswitched on!
130 if (isa<Constant>(Cond)) return false;
131
132 // TODO: Handle: br (VARIANT|INVARIANT).
133 // TODO: Hoist simple expressions out of loops.
134 if (L->isLoopInvariant(Cond)) return Cond;
135
136 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
137 if (BO->getOpcode() == Instruction::And ||
138 BO->getOpcode() == Instruction::Or) {
139 // If either the left or right side is invariant, we can unswitch on this,
140 // which will cause the branch to go away in one loop and the condition to
141 // simplify in the other one.
142 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
143 return LHS;
144 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
145 return RHS;
146 }
147
148 return 0;
149}
150
Devang Patel901a27d2007-03-07 00:26:10 +0000151bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000152 assert(L->isLCSSAForm());
Devang Patel901a27d2007-03-07 00:26:10 +0000153 LI = &getAnalysis<LoopInfo>();
154 LPM = &LPM_Ref;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000155 bool Changed = false;
156
157 // Loop over all of the basic blocks in the loop. If we find an interior
158 // block that is branching on a loop-invariant condition, we can unswitch this
159 // loop.
160 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
161 I != E; ++I) {
162 TerminatorInst *TI = (*I)->getTerminator();
163 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
164 // If this isn't branching on an invariant condition, we can't unswitch
165 // it.
166 if (BI->isConditional()) {
167 // See if this, or some part of it, is loop invariant. If so, we can
168 // unswitch on it if we desire.
169 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000170 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000171 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000172 ++NumBranches;
173 return true;
174 }
175 }
176 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
177 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
178 if (LoopCond && SI->getNumCases() > 1) {
179 // Find a value to unswitch on:
180 // FIXME: this should chose the most expensive case!
181 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000182 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000183 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000184 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000185
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000186 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
187 ++NumSwitches;
188 return true;
189 }
190 }
191 }
192
193 // Scan the instructions to check for unswitchable values.
194 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
195 BBI != E; ++BBI)
196 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
197 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000198 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000199 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000200 ++NumSelects;
201 return true;
202 }
203 }
204 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000205
206 assert(L->isLCSSAForm());
207
Chris Lattnerf48f7772004-04-19 18:07:02 +0000208 return Changed;
209}
210
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000211/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
212/// 1. Exit the loop with no side effects.
213/// 2. Branch to the latch block with no side-effects.
214///
215/// If these conditions are true, we return true and set ExitBB to the block we
216/// exit through.
217///
218static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
219 BasicBlock *&ExitBB,
220 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000221 if (!Visited.insert(BB).second) {
222 // Already visited and Ok, end of recursion.
223 return true;
224 } else if (!L->contains(BB)) {
225 // Otherwise, this is a loop exit, this is fine so long as this is the
226 // first exit.
227 if (ExitBB != 0) return false;
228 ExitBB = BB;
229 return true;
230 }
231
232 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000233 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000234 // Check to see if the successor is a trivial loop exit.
235 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
236 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000237 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000238
239 // Okay, everything after this looks good, check to make sure that this block
240 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000242 if (I->mayWriteToMemory())
243 return false;
244
245 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000246}
247
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000248/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
249/// leads to an exit from the specified loop, and has no side-effects in the
250/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000251static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
252 std::set<BasicBlock*> Visited;
253 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000254 BasicBlock *ExitBB = 0;
255 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
256 return ExitBB;
257 return 0;
258}
Chris Lattner6e263152006-02-10 02:30:37 +0000259
Chris Lattnered7a67b2006-02-10 01:24:09 +0000260/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
261/// trivial: that is, that the condition controls whether or not the loop does
262/// anything at all. If this is a trivial condition, unswitching produces no
263/// code duplications (equivalently, it produces a simpler loop and a new empty
264/// loop, which gets deleted).
265///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000266/// If this is a trivial condition, return true, otherwise return false. When
267/// returning true, this sets Cond and Val to the condition that controls the
268/// trivial condition: when Cond dynamically equals Val, the loop is known to
269/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
270/// Cond == Val.
271///
272static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000273 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000274 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000275 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000276
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000277 BasicBlock *LoopExitBB = 0;
278 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
279 // If the header block doesn't end with a conditional branch on Cond, we
280 // can't handle it.
281 if (!BI->isConditional() || BI->getCondition() != Cond)
282 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000283
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000284 // Check to see if a successor of the branch is guaranteed to go to the
285 // latch block or exit through a one exit block without having any
286 // side-effects. If so, determine the value of Cond that causes it to do
287 // this.
288 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000289 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000290 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000291 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000292 }
293 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
294 // If this isn't a switch on Cond, we can't handle it.
295 if (SI->getCondition() != Cond) return false;
296
297 // Check to see if a successor of the switch is guaranteed to go to the
298 // latch block or exit through a one exit block without having any
299 // side-effects. If so, determine the value of Cond that causes it to do
300 // this. Note that we can't trivially unswitch on the default case.
301 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
302 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
303 // Okay, we found a trivial case, remember the value that is trivial.
304 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000305 break;
306 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000307 }
308
Chris Lattnere5521db2006-02-22 23:55:00 +0000309 // If we didn't find a single unique LoopExit block, or if the loop exit block
310 // contains phi nodes, this isn't trivial.
311 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000312 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000313
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000314 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000315
316 // We already know that nothing uses any scalar values defined inside of this
317 // loop. As such, we just have to check to see if this loop will execute any
318 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000319 // part of the loop that the code *would* execute. We already checked the
320 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000321 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
322 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000323 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000324 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000325}
326
327/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
328/// we choose to unswitch the specified loop on the specified value.
329///
330unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
331 // If the condition is trivial, always unswitch. There is no code growth for
332 // this case.
333 if (IsTrivialUnswitchCondition(L, LIC))
334 return 0;
335
Owen Anderson18e816f2006-06-28 17:47:50 +0000336 // FIXME: This is really overly conservative. However, more liberal
337 // estimations have thus far resulted in excessive unswitching, which is bad
338 // both in compile time and in code size. This should be replaced once
339 // someone figures out how a good estimation.
340 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000341
Chris Lattnered7a67b2006-02-10 01:24:09 +0000342 unsigned Cost = 0;
343 // FIXME: this is brain dead. It should take into consideration code
344 // shrinkage.
345 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
346 I != E; ++I) {
347 BasicBlock *BB = *I;
348 // Do not include empty blocks in the cost calculation. This happen due to
349 // loop canonicalization and will be removed.
350 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
351 continue;
352
353 // Count basic blocks.
354 ++Cost;
355 }
356
357 return Cost;
358}
359
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000360/// UnswitchIfProfitable - We have found that we can unswitch L when
361/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
362/// unswitch the loop, reprocess the pieces, then return true.
363bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
364 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000365 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
Devang Patel506310d2007-06-06 00:21:03 +0000366
367 // Do not do non-trivial unswitch while optimizing for size.
368 if (Cost && OptimizeForSize)
369 return false;
370
Chris Lattner5821a6a2006-03-24 07:14:00 +0000371 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000372 // FIXME: this should estimate growth by the amount of code shared by the
373 // resultant unswitched loops.
374 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000375 DOUT << "NOT unswitching loop %"
376 << L->getHeader()->getName() << ", cost too high: "
377 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000378 return false;
379 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000380
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000381 // If this is a trivial condition to unswitch (which results in no code
382 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000383 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000384 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000385 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
386 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000387 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000388 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000389 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000390
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000391 return true;
392}
393
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000394/// SplitBlock - Split the specified block at the specified instruction - every
395/// thing before SplitPt stays in Old and everything starting with SplitPt moves
396/// to a new block. The two blocks are joined by an unconditional branch and
397/// the loop info is updated.
398///
399BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000400 BasicBlock::iterator SplitIt = SplitPt;
401 while (isa<PHINode>(SplitIt))
402 ++SplitIt;
403 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000404
405 // The new block lives in whichever loop the old one did.
406 if (Loop *L = LI->getLoopFor(Old))
407 L->addBasicBlockToLoop(New, *LI);
Devang Patel95572472007-05-09 08:24:12 +0000408
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000409 return New;
410}
411
412
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000413BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
414 TerminatorInst *LatchTerm = BB->getTerminator();
415 unsigned SuccNum = 0;
416 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
417 assert(i != e && "Didn't find edge?");
418 if (LatchTerm->getSuccessor(i) == Succ) {
419 SuccNum = i;
420 break;
421 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000422 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000423
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000424 // If this is a critical edge, let SplitCriticalEdge do it.
Devang Patel95572472007-05-09 08:24:12 +0000425 Loop *OrigDestBBL = LI->getLoopFor(BB->getTerminator()->getSuccessor(SuccNum));
426 if (SplitCriticalEdge(BB->getTerminator(), SuccNum)) {
427 BasicBlock *NewBB = LatchTerm->getSuccessor(SuccNum);
428
429 Loop *BBL = LI->getLoopFor(BB);
430 if (!BBL || !OrigDestBBL)
431 return NewBB;
432
433 // If edge is inside a loop then NewBB is part of same loop.
434 if (BBL == OrigDestBBL)
435 BBL->addBasicBlockToLoop(NewBB, *LI);
436 // If edge is entering loop then NewBB is part of outer loop.
437 else if (BBL->contains(OrigDestBBL->getHeader()))
438 BBL->addBasicBlockToLoop(NewBB, *LI);
439 // If edge is from an inner loop to outer loop then NewBB is part
440 // of outer loop.
441 else if (OrigDestBBL->contains(BBL->getHeader()))
442 OrigDestBBL->addBasicBlockToLoop(NewBB, *LI);
443 // Else edge is connecting two loops and NewBB is part of their parent loop
444 else if (Loop *PL = OrigDestBBL->getParentLoop())
445 PL->addBasicBlockToLoop(NewBB, *LI);
446
447 return NewBB;
448 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000449
450 // If the edge isn't critical, then BB has a single successor or Succ has a
451 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000452 BasicBlock::iterator SplitPoint;
453 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
454 // If the successor only has a single pred, split the top of the successor
455 // block.
456 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000457 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000458 } else {
459 // Otherwise, if BB has a single successor, split it at the bottom of the
460 // block.
461 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
462 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000463 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000464 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000465}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000466
Chris Lattnerf48f7772004-04-19 18:07:02 +0000467
468
Misha Brukmanb1c93172005-04-21 23:48:37 +0000469// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000470// current values into those specified by ValueMap.
471//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000472static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000473 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000474 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
475 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000476 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000477 if (It != ValueMap.end()) Op = It->second;
478 I->setOperand(op, Op);
479 }
480}
481
482/// CloneLoop - Recursively clone the specified loop and all of its children,
483/// mapping the blocks with the specified map.
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000484static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000485 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000486 Loop *New = new Loop();
487
Devang Patel901a27d2007-03-07 00:26:10 +0000488 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000489
490 // Add all of the blocks in L to the new loop.
491 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
492 I != E; ++I)
493 if (LI->getLoopFor(*I) == L)
494 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
495
496 // Add all of the subloops to the new loop.
497 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000498 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000499
Chris Lattnerf48f7772004-04-19 18:07:02 +0000500 return New;
501}
502
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000503/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
504/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
505/// code immediately before InsertPt.
506static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
507 BasicBlock *TrueDest,
508 BasicBlock *FalseDest,
509 Instruction *InsertPt) {
510 // Insert a conditional branch on LIC to the two preheaders. The original
511 // code is the true version and the new code is the false version.
512 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000513 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000514 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000515 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000516 // We want to enter the new loop when the condition is true.
517 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000518
519 // Insert the new branch.
520 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
521}
522
523
Chris Lattnered7a67b2006-02-10 01:24:09 +0000524/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
525/// condition in it (a cond branch from its header block to its latch block,
526/// where the path through the loop that doesn't execute its body has no
527/// side-effects), unswitch it. This doesn't involve any code duplication, just
528/// moving the conditional branch outside of the loop and updating loop info.
529void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000530 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000531 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000532 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
533 << L->getHeader()->getName() << " [" << L->getBlocks().size()
534 << " blocks] in Function " << L->getHeader()->getParent()->getName()
535 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000536
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000537 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000538 // to insert the conditional branch. We will change 'OrigPH' to have a
539 // conditional branch on Cond.
540 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000541 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000542
543 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000544 // to branch to: this is the exit block out of the loop that we should
545 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000546
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000547 // Split this block now, so that the loop maintains its exit block, and so
548 // that the jump from the preheader can execute the contents of the exit block
549 // without actually branching to it (the exit block should be dominated by the
550 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000551 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000552 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000553
Chris Lattnered7a67b2006-02-10 01:24:09 +0000554 // Okay, now we have a position to branch from and a position to branch to,
555 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000556 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
557 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000558 OrigPH->getTerminator()->eraseFromParent();
559
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000560 // We need to reprocess this loop, it could be unswitched again.
Devang Patel901a27d2007-03-07 00:26:10 +0000561 LPM->redoLoop(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000562
Chris Lattnered7a67b2006-02-10 01:24:09 +0000563 // Now that we know that the loop is never entered when this condition is a
564 // particular value, rewrite the loop with this info. We know that this will
565 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000566 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000567 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000568}
569
Chris Lattnerf48f7772004-04-19 18:07:02 +0000570
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000571/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
572/// equal Val. Split it into loop versions and test the condition outside of
573/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000574void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
575 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000576 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000577 DOUT << "loop-unswitch: Unswitching loop %"
578 << L->getHeader()->getName() << " [" << L->getBlocks().size()
579 << " blocks] in Function " << F->getName()
580 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000581
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000582 // LoopBlocks contains all of the basic blocks of the loop, including the
583 // preheader of the loop, the body of the loop, and the exit blocks of the
584 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000585 std::vector<BasicBlock*> LoopBlocks;
586
587 // First step, split the preheader and exit blocks, and add these blocks to
588 // the LoopBlocks list.
589 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000590 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000591
592 // We want the loop to come after the preheader, but before the exit blocks.
593 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
594
595 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000596 L->getUniqueExitBlocks(ExitBlocks);
597
Owen Andersonf52351e2006-06-26 07:44:36 +0000598 // Split all of the edges from inside the loop to their exit blocks. Update
599 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000600 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000601 BasicBlock *ExitBlock = ExitBlocks[i];
602 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
603
604 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Owen Andersonf52351e2006-06-26 07:44:36 +0000605 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
606 BasicBlock* StartBlock = Preds[j];
607 BasicBlock* EndBlock;
608 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
609 EndBlock = MiddleBlock;
610 MiddleBlock = EndBlock->getSinglePredecessor();;
611 } else {
612 EndBlock = ExitBlock;
613 }
614
615 std::set<PHINode*> InsertedPHIs;
616 PHINode* OldLCSSA = 0;
617 for (BasicBlock::iterator I = EndBlock->begin();
618 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
619 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
620 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
621 OldLCSSA->getName() + ".us-lcssa",
622 MiddleBlock->getTerminator());
623 NewLCSSA->addIncoming(OldValue, StartBlock);
624 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
625 NewLCSSA);
626 InsertedPHIs.insert(NewLCSSA);
627 }
628
Owen Anderson00b974c2006-07-19 03:51:48 +0000629 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000630 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
631 for (BasicBlock::iterator I = MiddleBlock->begin();
632 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
633 ++I) {
634 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
635 OldLCSSA->getName() + ".us-lcssa",
636 InsertPt);
637 OldLCSSA->replaceAllUsesWith(NewLCSSA);
638 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
639 }
640 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000641 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000642
643 // The exit blocks may have been changed due to edge splitting, recompute.
644 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000645 L->getUniqueExitBlocks(ExitBlocks);
646
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000647 // Add exit blocks to the loop blocks.
648 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000649
650 // Next step, clone all of the basic blocks that make up the loop (including
651 // the loop preheader and exit blocks), keeping track of the mapping between
652 // the instructions and blocks.
653 std::vector<BasicBlock*> NewBlocks;
654 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000655 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000656 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000657 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
658 NewBlocks.push_back(New);
659 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000660 }
661
662 // Splice the newly inserted blocks into the function right before the
663 // original preheader.
664 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
665 NewBlocks[0], F->end());
666
667 // Now we create the new Loop object for the versioned loop.
Devang Patel901a27d2007-03-07 00:26:10 +0000668 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000669 Loop *ParentLoop = L->getParentLoop();
670 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000671 // Make sure to add the cloned preheader and exit blocks to the parent loop
672 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000673 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
674 }
675
676 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
677 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000678 // The new exit block should be in the same loop as the old one.
679 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
680 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000681
682 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
683 "Exit block should have been split to have one successor!");
684 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
685
686 // If the successor of the exit block had PHI nodes, add an entry for
687 // NewExit.
688 PHINode *PN;
689 for (BasicBlock::iterator I = ExitSucc->begin();
690 (PN = dyn_cast<PHINode>(I)); ++I) {
691 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000692 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000693 if (It != ValueMap.end()) V = It->second;
694 PN->addIncoming(V, NewExit);
695 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000696 }
697
698 // Rewrite the code to refer to itself.
699 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
700 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
701 E = NewBlocks[i]->end(); I != E; ++I)
702 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000703
Chris Lattnerf48f7772004-04-19 18:07:02 +0000704 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000705 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
706 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000707 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000708
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000709 // Emit the new branch that selects between the two versions of this loop.
710 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
711 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000712
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000713 LoopProcessWorklist.push_back(NewLoop);
Devang Patel901a27d2007-03-07 00:26:10 +0000714 LPM->redoLoop(L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000715
716 // Now we rewrite the original code to know that the condition is true and the
717 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000718 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
719
720 // It's possible that simplifying one loop could cause the other to be
721 // deleted. If so, don't simplify it.
722 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
723 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000724}
725
Chris Lattner6fd13622006-02-17 00:31:07 +0000726/// RemoveFromWorklist - Remove all instances of I from the worklist vector
727/// specified.
728static void RemoveFromWorklist(Instruction *I,
729 std::vector<Instruction*> &Worklist) {
730 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
731 Worklist.end(), I);
732 while (WI != Worklist.end()) {
733 unsigned Offset = WI-Worklist.begin();
734 Worklist.erase(WI);
735 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
736 }
737}
738
739/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
740/// program, replacing all uses with V and update the worklist.
741static void ReplaceUsesOfWith(Instruction *I, Value *V,
742 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000743 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000744
745 // Add uses to the worklist, which may be dead now.
746 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
747 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
748 Worklist.push_back(Use);
749
750 // Add users to the worklist which may be simplified now.
751 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
752 UI != E; ++UI)
753 Worklist.push_back(cast<Instruction>(*UI));
754 I->replaceAllUsesWith(V);
755 I->eraseFromParent();
756 RemoveFromWorklist(I, Worklist);
757 ++NumSimplify;
758}
759
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000760/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
761/// information, and remove any dead successors it has.
762///
763void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
764 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000765 if (pred_begin(BB) != pred_end(BB)) {
766 // This block isn't dead, since an edge to BB was just removed, see if there
767 // are any easy simplifications we can do now.
768 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
769 // If it has one pred, fold phi nodes in BB.
770 while (isa<PHINode>(BB->begin()))
771 ReplaceUsesOfWith(BB->begin(),
772 cast<PHINode>(BB->begin())->getIncomingValue(0),
773 Worklist);
774
775 // If this is the header of a loop and the only pred is the latch, we now
776 // have an unreachable loop.
777 if (Loop *L = LI->getLoopFor(BB))
778 if (L->getHeader() == BB && L->contains(Pred)) {
779 // Remove the branch from the latch to the header block, this makes
780 // the header dead, which will make the latch dead (because the header
781 // dominates the latch).
782 Pred->getTerminator()->eraseFromParent();
783 new UnreachableInst(Pred);
784
785 // The loop is now broken, remove it from LI.
786 RemoveLoopFromHierarchy(L);
787
788 // Reprocess the header, which now IS dead.
789 RemoveBlockIfDead(BB, Worklist);
790 return;
791 }
792
793 // If pred ends in a uncond branch, add uncond branch to worklist so that
794 // the two blocks will get merged.
795 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
796 if (BI->isUnconditional())
797 Worklist.push_back(BI);
798 }
799 return;
800 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000801
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000802 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000803
804 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000805 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000806 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000807
808 // Anything that uses the instructions in this basic block should have their
809 // uses replaced with undefs.
810 if (!I->use_empty())
811 I->replaceAllUsesWith(UndefValue::get(I->getType()));
812 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000813
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000814 // If this is the edge to the header block for a loop, remove the loop and
815 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000816 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000817 if (BBLoop->getLoopLatch() == BB)
818 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000819 }
820
821 // Remove the block from the loop info, which removes it from any loops it
822 // was in.
823 LI->removeBlock(BB);
824
825
826 // Remove phi node entries in successors for this block.
827 TerminatorInst *TI = BB->getTerminator();
828 std::vector<BasicBlock*> Succs;
829 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
830 Succs.push_back(TI->getSuccessor(i));
831 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000832 }
833
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000834 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000835 std::sort(Succs.begin(), Succs.end());
836 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
837
838 // Remove the basic block, including all of the instructions contained in it.
839 BB->eraseFromParent();
840
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000841 // Remove successor blocks here that are not dead, so that we know we only
842 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
843 // then getting removed before we revisit them, which is badness.
844 //
845 for (unsigned i = 0; i != Succs.size(); ++i)
846 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
847 // One exception is loop headers. If this block was the preheader for a
848 // loop, then we DO want to visit the loop so the loop gets deleted.
849 // We know that if the successor is a loop header, that this loop had to
850 // be the preheader: the case where this was the latch block was handled
851 // above and headers can only have two predecessors.
852 if (!LI->isLoopHeader(Succs[i])) {
853 Succs.erase(Succs.begin()+i);
854 --i;
855 }
856 }
857
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000858 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
859 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000860}
Chris Lattner6fd13622006-02-17 00:31:07 +0000861
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000862/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
863/// become unwrapped, either because the backedge was deleted, or because the
864/// edge into the header was removed. If the edge into the header from the
865/// latch block was removed, the loop is unwrapped but subloops are still alive,
866/// so they just reparent loops. If the loops are actually dead, they will be
867/// removed later.
868void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000869 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000870 RemoveLoopFromWorklist(L);
871}
872
873
874
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000875// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
876// the value specified by Val in the specified loop, or we know it does NOT have
877// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000878void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000879 Constant *Val,
880 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000881 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000882
Chris Lattnerf48f7772004-04-19 18:07:02 +0000883 // FIXME: Support correlated properties, like:
884 // for (...)
885 // if (li1 < li2)
886 // ...
887 // if (li1 > li2)
888 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000889
Chris Lattner6e263152006-02-10 02:30:37 +0000890 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
891 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000892 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000893 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000894
Chris Lattner6fd13622006-02-17 00:31:07 +0000895 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
896 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000897 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000898 Value *Replacement;
899 if (IsEqual)
900 Replacement = Val;
901 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000902 Replacement = ConstantInt::get(Type::Int1Ty,
903 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000904
905 for (unsigned i = 0, e = Users.size(); i != e; ++i)
906 if (Instruction *U = cast<Instruction>(Users[i])) {
907 if (!L->contains(U->getParent()))
908 continue;
909 U->replaceUsesOfWith(LIC, Replacement);
910 Worklist.push_back(U);
911 }
912 } else {
913 // Otherwise, we don't know the precise value of LIC, but we do know that it
914 // is certainly NOT "Val". As such, simplify any uses in the loop that we
915 // can. This case occurs when we unswitch switch statements.
916 for (unsigned i = 0, e = Users.size(); i != e; ++i)
917 if (Instruction *U = cast<Instruction>(Users[i])) {
918 if (!L->contains(U->getParent()))
919 continue;
920
921 Worklist.push_back(U);
922
Chris Lattnerfa335f62006-02-16 19:36:22 +0000923 // If we know that LIC is not Val, use this info to simplify code.
924 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
925 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
926 if (SI->getCaseValue(i) == Val) {
927 // Found a dead case value. Don't remove PHI nodes in the
928 // successor if they become single-entry, those PHI nodes may
929 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000930
931 // FIXME: This is a hack. We need to keep the successor around
932 // and hooked up so as to preserve the loop structure, because
933 // trying to update it is complicated. So instead we preserve the
934 // loop structure and put the block on an dead code path.
935
936 BasicBlock* Old = SI->getParent();
937 BasicBlock* Split = SplitBlock(Old, SI);
938
939 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000940 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000941 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000942
943 Old->getTerminator()->eraseFromParent();
944
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000945
946 PHINode *PN;
947 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
948 (PN = dyn_cast<PHINode>(II)); ++II) {
949 Value *InVal = PN->removeIncomingValue(Split, false);
950 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +0000951 }
952
Chris Lattnerfa335f62006-02-16 19:36:22 +0000953 SI->removeCase(i);
954 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000955 }
956 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000957 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000958
959 // TODO: We could do other simplifications, for example, turning
960 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000961 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000962 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000963
964 SimplifyCode(Worklist);
965}
966
967/// SimplifyCode - Okay, now that we have simplified some instructions in the
968/// loop, walk over it and constant prop, dce, and fold control flow where
969/// possible. Note that this is effectively a very simple loop-structure-aware
970/// optimizer. During processing of this loop, L could very well be deleted, so
971/// it must not be used.
972///
973/// FIXME: When the loop optimizer is more mature, separate this out to a new
974/// pass.
975///
976void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +0000977 while (!Worklist.empty()) {
978 Instruction *I = Worklist.back();
979 Worklist.pop_back();
980
981 // Simple constant folding.
982 if (Constant *C = ConstantFoldInstruction(I)) {
983 ReplaceUsesOfWith(I, C, Worklist);
984 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +0000985 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000986
987 // Simple DCE.
988 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000989 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000990
991 // Add uses to the worklist, which may be dead now.
992 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
993 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
994 Worklist.push_back(Use);
995 I->eraseFromParent();
996 RemoveFromWorklist(I, Worklist);
997 ++NumSimplify;
998 continue;
999 }
1000
1001 // Special case hacks that appear commonly in unswitched code.
1002 switch (I->getOpcode()) {
1003 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001004 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001005 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001006 continue;
1007 }
1008 break;
1009 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001010 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001011 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001012 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001013 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001014 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001015 if (CB->isOne()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +00001016 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1017 else // X & 0 -> 0
1018 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1019 continue;
1020 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001021 break;
1022 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001023 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001024 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001025 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001026 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001027 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001028 if (CB->isOne()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001029 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1030 else // X | 0 -> X
1031 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1032 continue;
1033 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001034 break;
1035 case Instruction::Br: {
1036 BranchInst *BI = cast<BranchInst>(I);
1037 if (BI->isUnconditional()) {
1038 // If BI's parent is the only pred of the successor, fold the two blocks
1039 // together.
1040 BasicBlock *Pred = BI->getParent();
1041 BasicBlock *Succ = BI->getSuccessor(0);
1042 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1043 if (!SinglePred) continue; // Nothing to do.
1044 assert(SinglePred == Pred && "CFG broken");
1045
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001046 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1047 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001048
1049 // Resolve any single entry PHI nodes in Succ.
1050 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1051 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1052
1053 // Move all of the successor contents from Succ to Pred.
1054 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1055 Succ->end());
1056 BI->eraseFromParent();
1057 RemoveFromWorklist(BI, Worklist);
1058
1059 // If Succ has any successors with PHI nodes, update them to have
1060 // entries coming from Pred instead of Succ.
1061 Succ->replaceAllUsesWith(Pred);
1062
1063 // Remove Succ from the loop tree.
1064 LI->removeBlock(Succ);
1065 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001066 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001067 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001068 // Conditional branch. Turn it into an unconditional branch, then
1069 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001070 break; // FIXME: Enable.
1071
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001072 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001073 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1074 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001075 DeadSucc->removePredecessor(BI->getParent(), true);
1076 Worklist.push_back(new BranchInst(LiveSucc, BI));
1077 BI->eraseFromParent();
1078 RemoveFromWorklist(BI, Worklist);
1079 ++NumSimplify;
1080
1081 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001082 }
1083 break;
1084 }
1085 }
1086 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001087}