blob: 932bfe307877e0db6335bfde5e79bd74eafbdf19 [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"
32#include "llvm/Function.h"
33#include "llvm/Instructions.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000034#include "llvm/Analysis/LoopInfo.h"
35#include "llvm/Transforms/Utils/Cloning.h"
36#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerec6b40a2006-02-10 19:08:15 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
Chris Lattner89762192006-02-09 20:15:48 +000039#include "llvm/Support/Debug.h"
40#include "llvm/Support/CommandLine.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000041#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000042#include <iostream>
Chris Lattner2826e052006-02-09 19:14:52 +000043#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000044using namespace llvm;
45
46namespace {
47 Statistic<> NumUnswitched("loop-unswitch", "Number of loops unswitched");
Chris Lattner89762192006-02-09 20:15:48 +000048 cl::opt<unsigned>
49 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
50 cl::init(10), cl::Hidden);
51
Chris Lattnerf48f7772004-04-19 18:07:02 +000052 class LoopUnswitch : public FunctionPass {
53 LoopInfo *LI; // Loop information
Chris Lattnerf48f7772004-04-19 18:07:02 +000054 public:
55 virtual bool runOnFunction(Function &F);
56 bool visitLoop(Loop *L);
57
58 /// This transformation requires natural loop information & requires that
59 /// loop preheaders be inserted into the CFG...
60 ///
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000063 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000064 AU.addRequired<LoopInfo>();
65 AU.addPreserved<LoopInfo>();
66 }
67
68 private:
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000069 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +000070 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000071 void VersionLoop(Value *LIC, Constant *OnVal,
72 Loop *L, Loop *&Out1, Loop *&Out2);
Chris Lattnerfe4151e2006-02-10 23:16:39 +000073 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000074 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,Constant *Val,
75 bool isEqual);
Chris Lattner49354172006-02-10 02:01:22 +000076 void UnswitchTrivialCondition(Loop *L, Value *Cond, bool EntersLoopOnCond,
77 BasicBlock *ExitBlock);
Chris Lattnerf48f7772004-04-19 18:07:02 +000078 };
79 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
80}
81
Jeff Coheneca0d0f2005-01-06 05:47:18 +000082FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattnerf48f7772004-04-19 18:07:02 +000083
84bool LoopUnswitch::runOnFunction(Function &F) {
85 bool Changed = false;
86 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf48f7772004-04-19 18:07:02 +000087
88 // Transform all the top-level loops. Copy the loop list so that the child
89 // can update the loop tree if it needs to delete the loop.
90 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
91 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
92 Changed |= visitLoop(SubLoops[i]);
93
94 return Changed;
95}
96
Chris Lattner2826e052006-02-09 19:14:52 +000097
Chris Lattnered7a67b2006-02-10 01:24:09 +000098/// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
99/// the loop that are used by instructions outside of it.
Chris Lattner2826e052006-02-09 19:14:52 +0000100static bool LoopValuesUsedOutsideLoop(Loop *L) {
101 // We will be doing lots of "loop contains block" queries. Loop::contains is
102 // linear time, use a set to speed this up.
103 std::set<BasicBlock*> LoopBlocks;
104
105 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
106 BB != E; ++BB)
107 LoopBlocks.insert(*BB);
108
109 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
110 BB != E; ++BB) {
111 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
112 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
113 ++UI) {
114 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
115 if (!LoopBlocks.count(UserBB))
116 return true;
117 }
118 }
119 return false;
120}
121
Chris Lattner6e263152006-02-10 02:30:37 +0000122/// FindTrivialLoopExitBlock - We know that we have a branch from the loop
123/// header to the specified latch block. See if one of the successors of the
124/// latch block is an exit, and if so what block it is.
125static BasicBlock *FindTrivialLoopExitBlock(Loop *L, BasicBlock *Latch) {
126 BasicBlock *Header = L->getHeader();
127 BranchInst *LatchBranch = dyn_cast<BranchInst>(Latch->getTerminator());
128 if (!LatchBranch || !LatchBranch->isConditional()) return 0;
129
130 // Simple case, the latch block is a conditional branch. The target that
131 // doesn't go to the loop header is our block if it is not in the loop.
132 if (LatchBranch->getSuccessor(0) == Header) {
133 if (L->contains(LatchBranch->getSuccessor(1))) return false;
134 return LatchBranch->getSuccessor(1);
135 } else {
136 assert(LatchBranch->getSuccessor(1) == Header);
137 if (L->contains(LatchBranch->getSuccessor(0))) return false;
138 return LatchBranch->getSuccessor(0);
139 }
140}
141
142
Chris Lattnered7a67b2006-02-10 01:24:09 +0000143/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
144/// trivial: that is, that the condition controls whether or not the loop does
145/// anything at all. If this is a trivial condition, unswitching produces no
146/// code duplications (equivalently, it produces a simpler loop and a new empty
147/// loop, which gets deleted).
148///
149/// If this is a trivial condition, return ConstantBool::True if the loop body
150/// runs when the condition is true, False if the loop body executes when the
151/// condition is false. Otherwise, return null to indicate a complex condition.
Chris Lattner49354172006-02-10 02:01:22 +0000152static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond,
153 bool *CondEntersLoop = 0,
154 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000155 BasicBlock *Header = L->getHeader();
156 BranchInst *HeaderTerm = dyn_cast<BranchInst>(Header->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000157
158 // If the header block doesn't end with a conditional branch on Cond, we can't
159 // handle it.
160 if (!HeaderTerm || !HeaderTerm->isConditional() ||
161 HeaderTerm->getCondition() != Cond)
Chris Lattner49354172006-02-10 02:01:22 +0000162 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000163
164 // Check to see if the conditional branch goes to the latch block. If not,
165 // it's not trivial. This also determines the value of Cond that will execute
166 // the loop.
167 BasicBlock *Latch = L->getLoopLatch();
Chris Lattner49354172006-02-10 02:01:22 +0000168 if (HeaderTerm->getSuccessor(1) == Latch) {
169 if (CondEntersLoop) *CondEntersLoop = true;
170 } else if (HeaderTerm->getSuccessor(0) == Latch)
171 if (CondEntersLoop) *CondEntersLoop = false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000172 else
Chris Lattner49354172006-02-10 02:01:22 +0000173 return false; // Doesn't branch to latch block.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000174
175 // The latch block must end with a conditional branch where one edge goes to
176 // the header (this much we know) and one edge goes OUT of the loop.
Chris Lattner6e263152006-02-10 02:30:37 +0000177 BasicBlock *LoopExitBlock = FindTrivialLoopExitBlock(L, Latch);
178 if (!LoopExitBlock) return 0;
179 if (LoopExit) *LoopExit = LoopExitBlock;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000180
181 // We already know that nothing uses any scalar values defined inside of this
182 // loop. As such, we just have to check to see if this loop will execute any
183 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
184 // part of the loop that the code *would* execute.
185 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
186 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000187 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000188 for (BasicBlock::iterator I = Latch->begin(), E = Latch->end(); I != E; ++I)
189 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000190 return false;
191 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000192}
193
194/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
195/// we choose to unswitch the specified loop on the specified value.
196///
197unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
198 // If the condition is trivial, always unswitch. There is no code growth for
199 // this case.
200 if (IsTrivialUnswitchCondition(L, LIC))
201 return 0;
202
203 unsigned Cost = 0;
204 // FIXME: this is brain dead. It should take into consideration code
205 // shrinkage.
206 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
207 I != E; ++I) {
208 BasicBlock *BB = *I;
209 // Do not include empty blocks in the cost calculation. This happen due to
210 // loop canonicalization and will be removed.
211 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
212 continue;
213
214 // Count basic blocks.
215 ++Cost;
216 }
217
218 return Cost;
219}
220
Chris Lattner6e263152006-02-10 02:30:37 +0000221/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
222/// invariant in the loop, or has an invariant piece, return the invariant.
223/// Otherwise, return null.
224static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
225 // Constants should be folded, not unswitched on!
226 if (isa<Constant>(Cond)) return false;
227
228 // TODO: Handle: br (VARIANT|INVARIANT).
229 // TODO: Hoist simple expressions out of loops.
230 if (L->isLoopInvariant(Cond)) return Cond;
231
232 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
233 if (BO->getOpcode() == Instruction::And ||
234 BO->getOpcode() == Instruction::Or) {
235 // If either the left or right side is invariant, we can unswitch on this,
236 // which will cause the branch to go away in one loop and the condition to
237 // simplify in the other one.
238 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
239 return LHS;
240 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
241 return RHS;
242 }
243
244 return 0;
245}
246
Chris Lattnerf48f7772004-04-19 18:07:02 +0000247bool LoopUnswitch::visitLoop(Loop *L) {
248 bool Changed = false;
249
250 // Recurse through all subloops before we process this loop. Copy the loop
251 // list so that the child can update the loop tree if it needs to delete the
252 // loop.
253 std::vector<Loop*> SubLoops(L->begin(), L->end());
254 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
255 Changed |= visitLoop(SubLoops[i]);
256
257 // Loop over all of the basic blocks in the loop. If we find an interior
258 // block that is branching on a loop-invariant condition, we can unswitch this
259 // loop.
260 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
261 I != E; ++I) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000262 TerminatorInst *TI = (*I)->getTerminator();
263 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
264 // If this isn't branching on an invariant condition, we can't unswitch
265 // it.
266 if (BI->isConditional()) {
267 // See if this, or some part of it, is loop invariant. If so, we can
268 // unswitch on it if we desire.
269 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
270 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L))
271 return true;
272 }
273 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
274 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
275 if (LoopCond && SI->getNumCases() > 1) {
276 // Find a value to unswitch on:
277 // FIXME: this should chose the most expensive case!
278 Constant *UnswitchVal = SI->getCaseValue(1);
279 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L))
280 return true;
281 }
282 }
283
284 // Scan the instructions to check for unswitchable values.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000285 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
286 BBI != E; ++BBI)
287 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
288 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000289 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L))
290 return true;
Chris Lattnerf1b15162006-02-10 23:26:14 +0000291 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000292 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000293
Chris Lattnerf48f7772004-04-19 18:07:02 +0000294 return Changed;
295}
296
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000297/// UnswitchIfProfitable - We have found that we can unswitch L when
298/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
299/// unswitch the loop, reprocess the pieces, then return true.
300bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
301 // Check to see if it would be profitable to unswitch this loop.
302 if (getLoopUnswitchCost(L, LoopCond) > Threshold) {
303 // FIXME: this should estimate growth by the amount of code shared by the
304 // resultant unswitched loops.
305 //
306 DEBUG(std::cerr << "NOT unswitching loop %"
307 << L->getHeader()->getName() << ", cost too high: "
308 << L->getBlocks().size() << "\n");
309 return false;
310 }
311
312 // If this loop has live-out values, we can't unswitch it. We need something
313 // like loop-closed SSA form in order to know how to insert PHI nodes for
314 // these values.
315 if (LoopValuesUsedOutsideLoop(L)) {
316 DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
317 << ", a loop value is used outside loop!\n");
318 return false;
319 }
320
321 //std::cerr << "BEFORE:\n"; LI->dump();
322 Loop *NewLoop1 = 0, *NewLoop2 = 0;
323
324 // If this is a trivial condition to unswitch (which results in no code
325 // duplication), do it now.
326 bool EntersLoopOnCond;
327 BasicBlock *ExitBlock;
328 if (IsTrivialUnswitchCondition(L, LoopCond, &EntersLoopOnCond, &ExitBlock)){
329 UnswitchTrivialCondition(L, LoopCond, EntersLoopOnCond, ExitBlock);
330 NewLoop1 = L;
331 } else {
332 VersionLoop(LoopCond, Val, L, NewLoop1, NewLoop2);
333 }
334 ++NumUnswitched;
335
336 //std::cerr << "AFTER:\n"; LI->dump();
337
338 // Try to unswitch each of our new loops now!
339 if (NewLoop1) visitLoop(NewLoop1);
340 if (NewLoop2) visitLoop(NewLoop2);
341 return true;
342}
343
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000344BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
345 TerminatorInst *LatchTerm = BB->getTerminator();
346 unsigned SuccNum = 0;
347 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
348 assert(i != e && "Didn't find edge?");
349 if (LatchTerm->getSuccessor(i) == Succ) {
350 SuccNum = i;
351 break;
352 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000353 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000354
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000355 // If this is a critical edge, let SplitCriticalEdge do it.
356 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
357 return LatchTerm->getSuccessor(SuccNum);
358
359 // If the edge isn't critical, then BB has a single successor or Succ has a
360 // single pred. Split the block.
361 BasicBlock *BlockToSplit;
362 BasicBlock::iterator SplitPoint;
363 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
364 // If the successor only has a single pred, split the top of the successor
365 // block.
366 assert(SP == BB && "CFG broken");
367 BlockToSplit = Succ;
368 SplitPoint = Succ->begin();
369 } else {
370 // Otherwise, if BB has a single successor, split it at the bottom of the
371 // block.
372 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
373 "Should have a single succ!");
374 BlockToSplit = BB;
375 SplitPoint = BB->getTerminator();
376 }
377
378 BasicBlock *New =
379 BlockToSplit->splitBasicBlock(SplitPoint,
380 BlockToSplit->getName()+".tail");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000381 // New now lives in whichever loop that BB used to.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000382 if (Loop *L = LI->getLoopFor(BlockToSplit))
Chris Lattnerf48f7772004-04-19 18:07:02 +0000383 L->addBasicBlockToLoop(New, *LI);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000384 return New;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000385}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000386
Chris Lattnerf48f7772004-04-19 18:07:02 +0000387
388
Misha Brukmanb1c93172005-04-21 23:48:37 +0000389// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000390// current values into those specified by ValueMap.
391//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000392static inline void RemapInstruction(Instruction *I,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000393 std::map<const Value *, Value*> &ValueMap) {
394 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
395 Value *Op = I->getOperand(op);
396 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
397 if (It != ValueMap.end()) Op = It->second;
398 I->setOperand(op, Op);
399 }
400}
401
402/// CloneLoop - Recursively clone the specified loop and all of its children,
403/// mapping the blocks with the specified map.
404static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
405 LoopInfo *LI) {
406 Loop *New = new Loop();
407
408 if (PL)
409 PL->addChildLoop(New);
410 else
411 LI->addTopLevelLoop(New);
412
413 // Add all of the blocks in L to the new loop.
414 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
415 I != E; ++I)
416 if (LI->getLoopFor(*I) == L)
417 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
418
419 // Add all of the subloops to the new loop.
420 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
421 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000422
Chris Lattnerf48f7772004-04-19 18:07:02 +0000423 return New;
424}
425
Chris Lattnered7a67b2006-02-10 01:24:09 +0000426/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
427/// condition in it (a cond branch from its header block to its latch block,
428/// where the path through the loop that doesn't execute its body has no
429/// side-effects), unswitch it. This doesn't involve any code duplication, just
430/// moving the conditional branch outside of the loop and updating loop info.
431void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner49354172006-02-10 02:01:22 +0000432 bool EnterOnCond,
433 BasicBlock *ExitBlock) {
Chris Lattner3fc31482006-02-10 01:36:35 +0000434 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
435 << L->getHeader()->getName() << " [" << L->getBlocks().size()
436 << " blocks] in Function " << L->getHeader()->getParent()->getName()
437 << " on cond:" << *Cond << "\n");
438
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000439 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000440 // to insert the conditional branch. We will change 'OrigPH' to have a
441 // conditional branch on Cond.
442 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000443 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000444
445 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000446 // to branch to: this is the exit block out of the loop that we should
447 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000448
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000449 // Split this edge now, so that the loop maintains its exit block.
Chris Lattner49354172006-02-10 02:01:22 +0000450 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000451 BasicBlock *NewExit = SplitEdge(L->getLoopLatch(), ExitBlock);
452 assert(NewExit != ExitBlock && "Edge not split!");
453
Chris Lattnered7a67b2006-02-10 01:24:09 +0000454 // Okay, now we have a position to branch from and a position to branch to,
455 // insert the new conditional branch.
Chris Lattner49354172006-02-10 02:01:22 +0000456 new BranchInst(EnterOnCond ? NewPH : NewExit, EnterOnCond ? NewExit : NewPH,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000457 Cond, OrigPH->getTerminator());
458 OrigPH->getTerminator()->eraseFromParent();
459
460 // Now that we know that the loop is never entered when this condition is a
461 // particular value, rewrite the loop with this info. We know that this will
462 // at least eliminate the old branch.
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000463 RewriteLoopBodyWithConditionConstant(L, Cond, ConstantBool::get(EnterOnCond),
464 true);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000465}
466
Chris Lattnerf48f7772004-04-19 18:07:02 +0000467
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000468/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
469/// equal Val. Split it into loop versions and test the condition outside of
470/// either loop. Return the loops created as Out1/Out2.
471void LoopUnswitch::VersionLoop(Value *LIC, Constant *Val, Loop *L,
472 Loop *&Out1, Loop *&Out2) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000473 Function *F = L->getHeader()->getParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000474
Chris Lattnerf48f7772004-04-19 18:07:02 +0000475 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000476 << L->getHeader()->getName() << " [" << L->getBlocks().size()
477 << " blocks] in Function " << F->getName()
478 << " when '" << *Val << "' == " << *LIC << "\n");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000479
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000480 // LoopBlocks contains all of the basic blocks of the loop, including the
481 // preheader of the loop, the body of the loop, and the exit blocks of the
482 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000483 std::vector<BasicBlock*> LoopBlocks;
484
485 // First step, split the preheader and exit blocks, and add these blocks to
486 // the LoopBlocks list.
487 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000488 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000489
490 // We want the loop to come after the preheader, but before the exit blocks.
491 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
492
493 std::vector<BasicBlock*> ExitBlocks;
494 L->getExitBlocks(ExitBlocks);
495 std::sort(ExitBlocks.begin(), ExitBlocks.end());
496 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
497 ExitBlocks.end());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000498 // Split all of the edges from inside the loop to their exit blocks. This
499 // unswitching trivial: no phi nodes to update.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000500 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000501 BasicBlock *ExitBlock = ExitBlocks[i];
502 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
503
504 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
505 assert(L->contains(Preds[j]) &&
506 "All preds of loop exit blocks must be the same loop!");
507 SplitEdge(Preds[j], ExitBlock);
508 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000509 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000510
511 // The exit blocks may have been changed due to edge splitting, recompute.
512 ExitBlocks.clear();
513 L->getExitBlocks(ExitBlocks);
514 std::sort(ExitBlocks.begin(), ExitBlocks.end());
515 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
516 ExitBlocks.end());
517
518 // Add exit blocks to the loop blocks.
519 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000520
521 // Next step, clone all of the basic blocks that make up the loop (including
522 // the loop preheader and exit blocks), keeping track of the mapping between
523 // the instructions and blocks.
524 std::vector<BasicBlock*> NewBlocks;
525 NewBlocks.reserve(LoopBlocks.size());
526 std::map<const Value*, Value*> ValueMap;
527 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
528 NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F));
529 ValueMap[LoopBlocks[i]] = NewBlocks.back(); // Keep the BB mapping.
530 }
531
532 // Splice the newly inserted blocks into the function right before the
533 // original preheader.
534 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
535 NewBlocks[0], F->end());
536
537 // Now we create the new Loop object for the versioned loop.
538 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000539 Loop *ParentLoop = L->getParentLoop();
540 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000541 // Make sure to add the cloned preheader and exit blocks to the parent loop
542 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000543 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
544 }
545
546 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
547 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
548 if (ParentLoop)
549 ParentLoop->addBasicBlockToLoop(cast<BasicBlock>(NewExit), *LI);
550
551 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
552 "Exit block should have been split to have one successor!");
553 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
554
555 // If the successor of the exit block had PHI nodes, add an entry for
556 // NewExit.
557 PHINode *PN;
558 for (BasicBlock::iterator I = ExitSucc->begin();
559 (PN = dyn_cast<PHINode>(I)); ++I) {
560 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
561 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
562 if (It != ValueMap.end()) V = It->second;
563 PN->addIncoming(V, NewExit);
564 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000565 }
566
567 // Rewrite the code to refer to itself.
568 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
569 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
570 E = NewBlocks[i]->end(); I != E; ++I)
571 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000572
Chris Lattnerf48f7772004-04-19 18:07:02 +0000573 // Rewrite the original preheader to select between versions of the loop.
574 assert(isa<BranchInst>(OrigPreheader->getTerminator()) &&
575 cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() &&
576 OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] &&
577 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000578
579 // Insert a conditional branch on LIC to the two preheaders. The original
580 // code is the true version and the new code is the false version.
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000581 Value *BranchVal = LIC;
582 if (!isa<ConstantBool>(BranchVal)) {
583 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp",
584 OrigPreheader->getTerminator());
585 } else if (Val != ConstantBool::True) {
586 // We want to enter the new loop when the condition is true.
587 BranchVal = BinaryOperator::createNot(BranchVal, "tmp",
588 OrigPreheader->getTerminator());
589 }
590
591 // Remove the unconditional branch to LoopBlocks[0] and insert the new branch.
592 OrigPreheader->getInstList().pop_back();
593 new BranchInst(NewBlocks[0], LoopBlocks[0], BranchVal, OrigPreheader);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000594
595 // Now we rewrite the original code to know that the condition is true and the
596 // new code to know that the condition is false.
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000597 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
598 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000599 Out1 = L;
600 Out2 = NewLoop;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000601}
602
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000603// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
604// the value specified by Val in the specified loop, or we know it does NOT have
605// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000606void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000607 Constant *Val,
608 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000609 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000610
Chris Lattnerf48f7772004-04-19 18:07:02 +0000611 // FIXME: Support correlated properties, like:
612 // for (...)
613 // if (li1 < li2)
614 // ...
615 // if (li1 > li2)
616 // ...
Chris Lattnerf48f7772004-04-19 18:07:02 +0000617
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000618 // NotVal - If Val is a bool, this contains its inverse.
619 Constant *NotVal = 0;
620 if (ConstantBool *CB = dyn_cast<ConstantBool>(Val))
621 NotVal = ConstantBool::get(!CB->getValue());
622
Chris Lattner6e263152006-02-10 02:30:37 +0000623 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
624 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000625 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000626
627 // Haha, this loop could be unswitched. Get it? The unswitch pass could
628 // unswitch itself. Amazing.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000629 for (unsigned i = 0, e = Users.size(); i != e; ++i)
Chris Lattnered7a67b2006-02-10 01:24:09 +0000630 if (Instruction *U = cast<Instruction>(Users[i]))
Chris Lattnerf48f7772004-04-19 18:07:02 +0000631 if (L->contains(U->getParent()))
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000632 if (IsEqual) {
633 U->replaceUsesOfWith(LIC, Val);
634 } else if (NotVal) {
635 U->replaceUsesOfWith(LIC, NotVal);
636 } else {
637 // If we know that LIC is not Val, use this info to simplify code.
638 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
639 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
640 if (SI->getCaseValue(i) == Val) {
641 // Found a dead case value. Don't remove PHI nodes in the
642 // successor if they become single-entry, those PHI nodes may
643 // be in the Users list.
644 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
645 SI->removeCase(i);
646 break;
647 }
648 }
649 }
650
651 // TODO: We could simplify stuff like X == C.
652 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000653}