blob: 61a043596d6cab33edf3498eeff93781173763da [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 Lattnerc2e3a7a2006-02-18 07:57:38 +000039#include "llvm/ADT/PostOrderIterator.h"
Chris Lattner89762192006-02-09 20:15:48 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/CommandLine.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000042#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000043#include <iostream>
Chris Lattner2826e052006-02-09 19:14:52 +000044#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000045using namespace llvm;
46
47namespace {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +000048 Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched");
49 Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched");
50 Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched");
51 Statistic<> NumTrivial ("loop-unswitch",
52 "Number of unswitches that are trivial");
Chris Lattner6fd13622006-02-17 00:31:07 +000053 Statistic<> NumSimplify("loop-unswitch",
54 "Number of simplifications of unswitched code");
Chris Lattner89762192006-02-09 20:15:48 +000055 cl::opt<unsigned>
56 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
57 cl::init(10), cl::Hidden);
58
Chris Lattnerf48f7772004-04-19 18:07:02 +000059 class LoopUnswitch : public FunctionPass {
60 LoopInfo *LI; // Loop information
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000061
62 // LoopProcessWorklist - List of loops we need to process.
63 std::vector<Loop*> LoopProcessWorklist;
Chris Lattnerf48f7772004-04-19 18:07:02 +000064 public:
65 virtual bool runOnFunction(Function &F);
66 bool visitLoop(Loop *L);
67
68 /// This transformation requires natural loop information & requires that
69 /// loop preheaders be inserted into the CFG...
70 ///
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000073 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000074 AU.addRequired<LoopInfo>();
75 AU.addPreserved<LoopInfo>();
76 }
77
78 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000079 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
80 /// remove it.
81 void RemoveLoopFromWorklist(Loop *L) {
82 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
83 LoopProcessWorklist.end(), L);
84 if (I != LoopProcessWorklist.end())
85 LoopProcessWorklist.erase(I);
86 }
87
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000088 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +000089 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +000090 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +000091 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000092 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +000093 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +000094 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000095
96 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
97 Constant *Val, bool isEqual);
98
99 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000100 void RemoveBlockIfDead(BasicBlock *BB,
101 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000102 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000103 };
104 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
105}
106
Jeff Coheneca0d0f2005-01-06 05:47:18 +0000107FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000108
109bool LoopUnswitch::runOnFunction(Function &F) {
110 bool Changed = false;
111 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000112
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000113 // Populate the worklist of loops to process in post-order.
114 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
115 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
116 LoopProcessWorklist.push_back(*LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000117
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000118 // Process the loops in worklist order, this is a post-order visitation of
119 // the loops. We use a worklist of loops so that loops can be removed at any
120 // time if they are deleted (e.g. the backedge of a loop is removed).
121 while (!LoopProcessWorklist.empty()) {
122 Loop *L = LoopProcessWorklist.back();
123 LoopProcessWorklist.pop_back();
124 Changed |= visitLoop(L);
125 }
126
127 return Changed;
128}
129
130/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
131/// invariant in the loop, or has an invariant piece, return the invariant.
132/// Otherwise, return null.
133static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
134 // Constants should be folded, not unswitched on!
135 if (isa<Constant>(Cond)) return false;
136
137 // TODO: Handle: br (VARIANT|INVARIANT).
138 // TODO: Hoist simple expressions out of loops.
139 if (L->isLoopInvariant(Cond)) return Cond;
140
141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
142 if (BO->getOpcode() == Instruction::And ||
143 BO->getOpcode() == Instruction::Or) {
144 // If either the left or right side is invariant, we can unswitch on this,
145 // which will cause the branch to go away in one loop and the condition to
146 // simplify in the other one.
147 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
148 return LHS;
149 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
150 return RHS;
151 }
152
153 return 0;
154}
155
156bool LoopUnswitch::visitLoop(Loop *L) {
157 bool Changed = false;
158
159 // Loop over all of the basic blocks in the loop. If we find an interior
160 // block that is branching on a loop-invariant condition, we can unswitch this
161 // loop.
162 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
163 I != E; ++I) {
164 TerminatorInst *TI = (*I)->getTerminator();
165 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
166 // If this isn't branching on an invariant condition, we can't unswitch
167 // it.
168 if (BI->isConditional()) {
169 // See if this, or some part of it, is loop invariant. If so, we can
170 // unswitch on it if we desire.
171 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
172 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
173 ++NumBranches;
174 return true;
175 }
176 }
177 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
178 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
179 if (LoopCond && SI->getNumCases() > 1) {
180 // Find a value to unswitch on:
181 // FIXME: this should chose the most expensive case!
182 Constant *UnswitchVal = SI->getCaseValue(1);
183 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
184 ++NumSwitches;
185 return true;
186 }
187 }
188 }
189
190 // Scan the instructions to check for unswitchable values.
191 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
192 BBI != E; ++BBI)
193 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
194 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
195 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
196 ++NumSelects;
197 return true;
198 }
199 }
200 }
201
Chris Lattnerf48f7772004-04-19 18:07:02 +0000202 return Changed;
203}
204
Chris Lattner2826e052006-02-09 19:14:52 +0000205
Chris Lattnered7a67b2006-02-10 01:24:09 +0000206/// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
207/// the loop that are used by instructions outside of it.
Chris Lattner2826e052006-02-09 19:14:52 +0000208static bool LoopValuesUsedOutsideLoop(Loop *L) {
209 // We will be doing lots of "loop contains block" queries. Loop::contains is
210 // linear time, use a set to speed this up.
211 std::set<BasicBlock*> LoopBlocks;
212
213 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
214 BB != E; ++BB)
215 LoopBlocks.insert(*BB);
216
217 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
218 BB != E; ++BB) {
219 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
220 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
221 ++UI) {
222 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
223 if (!LoopBlocks.count(UserBB))
224 return true;
225 }
226 }
227 return false;
228}
229
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000230/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
231/// 1. Exit the loop with no side effects.
232/// 2. Branch to the latch block with no side-effects.
233///
234/// If these conditions are true, we return true and set ExitBB to the block we
235/// exit through.
236///
237static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
238 BasicBlock *&ExitBB,
239 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000240 if (!Visited.insert(BB).second) {
241 // Already visited and Ok, end of recursion.
242 return true;
243 } else if (!L->contains(BB)) {
244 // Otherwise, this is a loop exit, this is fine so long as this is the
245 // first exit.
246 if (ExitBB != 0) return false;
247 ExitBB = BB;
248 return true;
249 }
250
251 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000252 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000253 // Check to see if the successor is a trivial loop exit.
254 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
255 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000256 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000257
258 // Okay, everything after this looks good, check to make sure that this block
259 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000260 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000261 if (I->mayWriteToMemory())
262 return false;
263
264 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000265}
266
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000267/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
268/// leads to an exit from the specified loop, and has no side-effects in the
269/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000270static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
271 std::set<BasicBlock*> Visited;
272 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000273 BasicBlock *ExitBB = 0;
274 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
275 return ExitBB;
276 return 0;
277}
Chris Lattner6e263152006-02-10 02:30:37 +0000278
Chris Lattnered7a67b2006-02-10 01:24:09 +0000279/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
280/// trivial: that is, that the condition controls whether or not the loop does
281/// anything at all. If this is a trivial condition, unswitching produces no
282/// code duplications (equivalently, it produces a simpler loop and a new empty
283/// loop, which gets deleted).
284///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000285/// If this is a trivial condition, return true, otherwise return false. When
286/// returning true, this sets Cond and Val to the condition that controls the
287/// trivial condition: when Cond dynamically equals Val, the loop is known to
288/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
289/// Cond == Val.
290///
291static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000292 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000293 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000294 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000295
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000296 BasicBlock *LoopExitBB = 0;
297 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
298 // If the header block doesn't end with a conditional branch on Cond, we
299 // can't handle it.
300 if (!BI->isConditional() || BI->getCondition() != Cond)
301 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000302
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000303 // Check to see if a successor of the branch is guaranteed to go to the
304 // latch block or exit through a one exit block without having any
305 // side-effects. If so, determine the value of Cond that causes it to do
306 // this.
307 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Chris Lattnerff42e812006-02-16 01:24:41 +0000308 if (Val) *Val = ConstantBool::True;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000309 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
310 if (Val) *Val = ConstantBool::False;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000311 }
312 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
313 // If this isn't a switch on Cond, we can't handle it.
314 if (SI->getCondition() != Cond) return false;
315
316 // Check to see if a successor of the switch is guaranteed to go to the
317 // latch block or exit through a one exit block without having any
318 // side-effects. If so, determine the value of Cond that causes it to do
319 // this. Note that we can't trivially unswitch on the default case.
320 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
321 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
322 // Okay, we found a trivial case, remember the value that is trivial.
323 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000324 break;
325 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000326 }
327
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000328 if (!LoopExitBB)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000329 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000330
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000331 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000332
333 // We already know that nothing uses any scalar values defined inside of this
334 // loop. As such, we just have to check to see if this loop will execute any
335 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000336 // part of the loop that the code *would* execute. We already checked the
337 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000338 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
339 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000340 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000341 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000342}
343
344/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
345/// we choose to unswitch the specified loop on the specified value.
346///
347unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
348 // If the condition is trivial, always unswitch. There is no code growth for
349 // this case.
350 if (IsTrivialUnswitchCondition(L, LIC))
351 return 0;
352
353 unsigned Cost = 0;
354 // FIXME: this is brain dead. It should take into consideration code
355 // shrinkage.
356 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
357 I != E; ++I) {
358 BasicBlock *BB = *I;
359 // Do not include empty blocks in the cost calculation. This happen due to
360 // loop canonicalization and will be removed.
361 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
362 continue;
363
364 // Count basic blocks.
365 ++Cost;
366 }
367
368 return Cost;
369}
370
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000371/// UnswitchIfProfitable - We have found that we can unswitch L when
372/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
373/// unswitch the loop, reprocess the pieces, then return true.
374bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
375 // Check to see if it would be profitable to unswitch this loop.
376 if (getLoopUnswitchCost(L, LoopCond) > Threshold) {
377 // FIXME: this should estimate growth by the amount of code shared by the
378 // resultant unswitched loops.
379 //
380 DEBUG(std::cerr << "NOT unswitching loop %"
381 << L->getHeader()->getName() << ", cost too high: "
382 << L->getBlocks().size() << "\n");
383 return false;
384 }
385
386 // If this loop has live-out values, we can't unswitch it. We need something
387 // like loop-closed SSA form in order to know how to insert PHI nodes for
388 // these values.
389 if (LoopValuesUsedOutsideLoop(L)) {
390 DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
391 << ", a loop value is used outside loop!\n");
392 return false;
393 }
394
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);
422
423 return New;
424}
425
426
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000427BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
428 TerminatorInst *LatchTerm = BB->getTerminator();
429 unsigned SuccNum = 0;
430 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
431 assert(i != e && "Didn't find edge?");
432 if (LatchTerm->getSuccessor(i) == Succ) {
433 SuccNum = i;
434 break;
435 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000436 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000437
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000438 // If this is a critical edge, let SplitCriticalEdge do it.
439 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
440 return LatchTerm->getSuccessor(SuccNum);
441
442 // If the edge isn't critical, then BB has a single successor or Succ has a
443 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000444 BasicBlock::iterator SplitPoint;
445 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
446 // If the successor only has a single pred, split the top of the successor
447 // block.
448 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000449 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000450 } else {
451 // Otherwise, if BB has a single successor, split it at the bottom of the
452 // block.
453 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
454 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000455 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000456 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000457}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000458
Chris Lattnerf48f7772004-04-19 18:07:02 +0000459
460
Misha Brukmanb1c93172005-04-21 23:48:37 +0000461// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000462// current values into those specified by ValueMap.
463//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000464static inline void RemapInstruction(Instruction *I,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000465 std::map<const Value *, Value*> &ValueMap) {
466 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
467 Value *Op = I->getOperand(op);
468 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
469 if (It != ValueMap.end()) Op = It->second;
470 I->setOperand(op, Op);
471 }
472}
473
474/// CloneLoop - Recursively clone the specified loop and all of its children,
475/// mapping the blocks with the specified map.
476static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
477 LoopInfo *LI) {
478 Loop *New = new Loop();
479
480 if (PL)
481 PL->addChildLoop(New);
482 else
483 LI->addTopLevelLoop(New);
484
485 // Add all of the blocks in L to the new loop.
486 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
487 I != E; ++I)
488 if (LI->getLoopFor(*I) == L)
489 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
490
491 // Add all of the subloops to the new loop.
492 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
493 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000494
Chris Lattnerf48f7772004-04-19 18:07:02 +0000495 return New;
496}
497
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000498/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
499/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
500/// code immediately before InsertPt.
501static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
502 BasicBlock *TrueDest,
503 BasicBlock *FalseDest,
504 Instruction *InsertPt) {
505 // Insert a conditional branch on LIC to the two preheaders. The original
506 // code is the true version and the new code is the false version.
507 Value *BranchVal = LIC;
Chris Lattner65152d82006-02-15 19:05:52 +0000508 if (!isa<ConstantBool>(Val)) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000509 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
510 } else if (Val != ConstantBool::True) {
511 // We want to enter the new loop when the condition is true.
512 std::swap(TrueDest, FalseDest);
513 }
514
515 // Insert the new branch.
516 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
517}
518
519
Chris Lattnered7a67b2006-02-10 01:24:09 +0000520/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
521/// condition in it (a cond branch from its header block to its latch block,
522/// where the path through the loop that doesn't execute its body has no
523/// side-effects), unswitch it. This doesn't involve any code duplication, just
524/// moving the conditional branch outside of the loop and updating loop info.
525void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000526 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000527 BasicBlock *ExitBlock) {
Chris Lattner3fc31482006-02-10 01:36:35 +0000528 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
529 << L->getHeader()->getName() << " [" << L->getBlocks().size()
530 << " blocks] in Function " << L->getHeader()->getParent()->getName()
Chris Lattner8a5a3242006-02-22 06:37:14 +0000531 << " on cond: " << *Val << " == " << *Cond << "\n");
Chris Lattner3fc31482006-02-10 01:36:35 +0000532
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000533 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000534 // to insert the conditional branch. We will change 'OrigPH' to have a
535 // conditional branch on Cond.
536 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000537 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000538
539 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000540 // to branch to: this is the exit block out of the loop that we should
541 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000542
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000543 // Split this block now, so that the loop maintains its exit block, and so
544 // that the jump from the preheader can execute the contents of the exit block
545 // without actually branching to it (the exit block should be dominated by the
546 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000547 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000548 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000549
Chris Lattnered7a67b2006-02-10 01:24:09 +0000550 // Okay, now we have a position to branch from and a position to branch to,
551 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000552 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
553 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000554 OrigPH->getTerminator()->eraseFromParent();
555
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000556 // We need to reprocess this loop, it could be unswitched again.
557 LoopProcessWorklist.push_back(L);
558
Chris Lattnered7a67b2006-02-10 01:24:09 +0000559 // Now that we know that the loop is never entered when this condition is a
560 // particular value, rewrite the loop with this info. We know that this will
561 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000562 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000563 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000564}
565
Chris Lattnerf48f7772004-04-19 18:07:02 +0000566
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000567/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
568/// equal Val. Split it into loop versions and test the condition outside of
569/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000570void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
571 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000572 Function *F = L->getHeader()->getParent();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000573 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000574 << L->getHeader()->getName() << " [" << L->getBlocks().size()
575 << " blocks] in Function " << F->getName()
576 << " when '" << *Val << "' == " << *LIC << "\n");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000577
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000578 // LoopBlocks contains all of the basic blocks of the loop, including the
579 // preheader of the loop, the body of the loop, and the exit blocks of the
580 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000581 std::vector<BasicBlock*> LoopBlocks;
582
583 // First step, split the preheader and exit blocks, and add these blocks to
584 // the LoopBlocks list.
585 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000586 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000587
588 // We want the loop to come after the preheader, but before the exit blocks.
589 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
590
591 std::vector<BasicBlock*> ExitBlocks;
592 L->getExitBlocks(ExitBlocks);
593 std::sort(ExitBlocks.begin(), ExitBlocks.end());
594 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
595 ExitBlocks.end());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000596
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000597 // Split all of the edges from inside the loop to their exit blocks. This
598 // unswitching trivial: no phi nodes to update.
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000599 unsigned NumBlocks = L->getBlocks().size();
Chris Lattner8e44ff52006-02-18 00:55:32 +0000600
Chris Lattnered7a67b2006-02-10 01:24:09 +0000601 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000602 BasicBlock *ExitBlock = ExitBlocks[i];
603 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
604
605 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
606 assert(L->contains(Preds[j]) &&
607 "All preds of loop exit blocks must be the same loop!");
608 SplitEdge(Preds[j], ExitBlock);
609 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000610 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000611
612 // The exit blocks may have been changed due to edge splitting, recompute.
613 ExitBlocks.clear();
614 L->getExitBlocks(ExitBlocks);
615 std::sort(ExitBlocks.begin(), ExitBlocks.end());
616 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
617 ExitBlocks.end());
618
619 // Add exit blocks to the loop blocks.
620 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000621
622 // Next step, clone all of the basic blocks that make up the loop (including
623 // the loop preheader and exit blocks), keeping track of the mapping between
624 // the instructions and blocks.
625 std::vector<BasicBlock*> NewBlocks;
626 NewBlocks.reserve(LoopBlocks.size());
627 std::map<const Value*, Value*> ValueMap;
628 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000629 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
630 NewBlocks.push_back(New);
631 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000632 }
633
634 // Splice the newly inserted blocks into the function right before the
635 // original preheader.
636 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
637 NewBlocks[0], F->end());
638
639 // Now we create the new Loop object for the versioned loop.
640 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000641 Loop *ParentLoop = L->getParentLoop();
642 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000643 // Make sure to add the cloned preheader and exit blocks to the parent loop
644 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000645 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
646 }
647
648 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
649 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000650 // The new exit block should be in the same loop as the old one.
651 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
652 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000653
654 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
655 "Exit block should have been split to have one successor!");
656 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
657
658 // If the successor of the exit block had PHI nodes, add an entry for
659 // NewExit.
660 PHINode *PN;
661 for (BasicBlock::iterator I = ExitSucc->begin();
662 (PN = dyn_cast<PHINode>(I)); ++I) {
663 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
664 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
665 if (It != ValueMap.end()) V = It->second;
666 PN->addIncoming(V, NewExit);
667 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000668 }
669
670 // Rewrite the code to refer to itself.
671 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
672 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
673 E = NewBlocks[i]->end(); I != E; ++I)
674 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000675
Chris Lattnerf48f7772004-04-19 18:07:02 +0000676 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000677 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
678 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000679 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000680
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000681 // Emit the new branch that selects between the two versions of this loop.
682 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
683 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000684
685 LoopProcessWorklist.push_back(L);
686 LoopProcessWorklist.push_back(NewLoop);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000687
688 // Now we rewrite the original code to know that the condition is true and the
689 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000690 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
691
692 // It's possible that simplifying one loop could cause the other to be
693 // deleted. If so, don't simplify it.
694 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
695 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000696}
697
Chris Lattner6fd13622006-02-17 00:31:07 +0000698/// RemoveFromWorklist - Remove all instances of I from the worklist vector
699/// specified.
700static void RemoveFromWorklist(Instruction *I,
701 std::vector<Instruction*> &Worklist) {
702 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
703 Worklist.end(), I);
704 while (WI != Worklist.end()) {
705 unsigned Offset = WI-Worklist.begin();
706 Worklist.erase(WI);
707 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
708 }
709}
710
711/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
712/// program, replacing all uses with V and update the worklist.
713static void ReplaceUsesOfWith(Instruction *I, Value *V,
714 std::vector<Instruction*> &Worklist) {
715 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
716
717 // Add uses to the worklist, which may be dead now.
718 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
719 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
720 Worklist.push_back(Use);
721
722 // Add users to the worklist which may be simplified now.
723 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
724 UI != E; ++UI)
725 Worklist.push_back(cast<Instruction>(*UI));
726 I->replaceAllUsesWith(V);
727 I->eraseFromParent();
728 RemoveFromWorklist(I, Worklist);
729 ++NumSimplify;
730}
731
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000732/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
733/// information, and remove any dead successors it has.
734///
735void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
736 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000737 if (pred_begin(BB) != pred_end(BB)) {
738 // This block isn't dead, since an edge to BB was just removed, see if there
739 // are any easy simplifications we can do now.
740 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
741 // If it has one pred, fold phi nodes in BB.
742 while (isa<PHINode>(BB->begin()))
743 ReplaceUsesOfWith(BB->begin(),
744 cast<PHINode>(BB->begin())->getIncomingValue(0),
745 Worklist);
746
747 // If this is the header of a loop and the only pred is the latch, we now
748 // have an unreachable loop.
749 if (Loop *L = LI->getLoopFor(BB))
750 if (L->getHeader() == BB && L->contains(Pred)) {
751 // Remove the branch from the latch to the header block, this makes
752 // the header dead, which will make the latch dead (because the header
753 // dominates the latch).
754 Pred->getTerminator()->eraseFromParent();
755 new UnreachableInst(Pred);
756
757 // The loop is now broken, remove it from LI.
758 RemoveLoopFromHierarchy(L);
759
760 // Reprocess the header, which now IS dead.
761 RemoveBlockIfDead(BB, Worklist);
762 return;
763 }
764
765 // If pred ends in a uncond branch, add uncond branch to worklist so that
766 // the two blocks will get merged.
767 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
768 if (BI->isUnconditional())
769 Worklist.push_back(BI);
770 }
771 return;
772 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000773
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000774 DEBUG(std::cerr << "Nuking dead block: " << *BB);
775
776 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000777 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000778 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000779
780 // Anything that uses the instructions in this basic block should have their
781 // uses replaced with undefs.
782 if (!I->use_empty())
783 I->replaceAllUsesWith(UndefValue::get(I->getType()));
784 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000785
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000786 // If this is the edge to the header block for a loop, remove the loop and
787 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000788 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000789 if (BBLoop->getLoopLatch() == BB)
790 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000791 }
792
793 // Remove the block from the loop info, which removes it from any loops it
794 // was in.
795 LI->removeBlock(BB);
796
797
798 // Remove phi node entries in successors for this block.
799 TerminatorInst *TI = BB->getTerminator();
800 std::vector<BasicBlock*> Succs;
801 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
802 Succs.push_back(TI->getSuccessor(i));
803 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000804 }
805
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000806 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000807 std::sort(Succs.begin(), Succs.end());
808 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
809
810 // Remove the basic block, including all of the instructions contained in it.
811 BB->eraseFromParent();
812
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000813 // Remove successor blocks here that are not dead, so that we know we only
814 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
815 // then getting removed before we revisit them, which is badness.
816 //
817 for (unsigned i = 0; i != Succs.size(); ++i)
818 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
819 // One exception is loop headers. If this block was the preheader for a
820 // loop, then we DO want to visit the loop so the loop gets deleted.
821 // We know that if the successor is a loop header, that this loop had to
822 // be the preheader: the case where this was the latch block was handled
823 // above and headers can only have two predecessors.
824 if (!LI->isLoopHeader(Succs[i])) {
825 Succs.erase(Succs.begin()+i);
826 --i;
827 }
828 }
829
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000830 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
831 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000832}
Chris Lattner6fd13622006-02-17 00:31:07 +0000833
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000834/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
835/// become unwrapped, either because the backedge was deleted, or because the
836/// edge into the header was removed. If the edge into the header from the
837/// latch block was removed, the loop is unwrapped but subloops are still alive,
838/// so they just reparent loops. If the loops are actually dead, they will be
839/// removed later.
840void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
841 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
842 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
843 // they are now all in it.
844 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
845 I != E; ++I)
846 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
847 LI->changeLoopFor(*I, ParentLoop);
848
849 // Remove the loop from its parent loop.
850 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
851 ++I) {
852 assert(I != E && "Couldn't find loop");
853 if (*I == L) {
854 ParentLoop->removeChildLoop(I);
855 break;
856 }
857 }
858
859 // Move all subloops into the parent loop.
860 while (L->begin() != L->end())
861 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
862 } else {
863 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
864 // they no longer in a loop at all.
865
866 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
867 // Don't change blocks in subloops.
868 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
869 LI->removeBlock(L->getBlocks()[i]);
870 --i;
871 }
872 }
873
874 // Remove the loop from the top-level LoopInfo object.
875 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
876 assert(I != E && "Couldn't find loop");
877 if (*I == L) {
878 LI->removeLoop(I);
879 break;
880 }
881 }
882
883 // Move all of the subloops to the top-level.
884 while (L->begin() != L->end())
885 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
886 }
887
888 delete L;
889 RemoveLoopFromWorklist(L);
890}
891
892
893
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000894// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
895// the value specified by Val in the specified loop, or we know it does NOT have
896// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000897void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000898 Constant *Val,
899 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000900 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000901
Chris Lattnerf48f7772004-04-19 18:07:02 +0000902 // FIXME: Support correlated properties, like:
903 // for (...)
904 // if (li1 < li2)
905 // ...
906 // if (li1 > li2)
907 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000908
Chris Lattner6e263152006-02-10 02:30:37 +0000909 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
910 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000911 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000912 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000913
Chris Lattner6fd13622006-02-17 00:31:07 +0000914 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
915 // in the loop with the appropriate one directly.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000916 if (IsEqual || isa<ConstantBool>(Val)) {
917 Value *Replacement;
918 if (IsEqual)
919 Replacement = Val;
920 else
921 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000922
923 for (unsigned i = 0, e = Users.size(); i != e; ++i)
924 if (Instruction *U = cast<Instruction>(Users[i])) {
925 if (!L->contains(U->getParent()))
926 continue;
927 U->replaceUsesOfWith(LIC, Replacement);
928 Worklist.push_back(U);
929 }
930 } else {
931 // Otherwise, we don't know the precise value of LIC, but we do know that it
932 // is certainly NOT "Val". As such, simplify any uses in the loop that we
933 // can. This case occurs when we unswitch switch statements.
934 for (unsigned i = 0, e = Users.size(); i != e; ++i)
935 if (Instruction *U = cast<Instruction>(Users[i])) {
936 if (!L->contains(U->getParent()))
937 continue;
938
939 Worklist.push_back(U);
940
Chris Lattnerfa335f62006-02-16 19:36:22 +0000941 // If we know that LIC is not Val, use this info to simplify code.
942 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
943 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
944 if (SI->getCaseValue(i) == Val) {
945 // Found a dead case value. Don't remove PHI nodes in the
946 // successor if they become single-entry, those PHI nodes may
947 // be in the Users list.
948 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
949 SI->removeCase(i);
950 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000951 }
952 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000953 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000954
955 // TODO: We could do other simplifications, for example, turning
956 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000957 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000958 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000959
960 SimplifyCode(Worklist);
961}
962
963/// SimplifyCode - Okay, now that we have simplified some instructions in the
964/// loop, walk over it and constant prop, dce, and fold control flow where
965/// possible. Note that this is effectively a very simple loop-structure-aware
966/// optimizer. During processing of this loop, L could very well be deleted, so
967/// it must not be used.
968///
969/// FIXME: When the loop optimizer is more mature, separate this out to a new
970/// pass.
971///
972void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +0000973 while (!Worklist.empty()) {
974 Instruction *I = Worklist.back();
975 Worklist.pop_back();
976
977 // Simple constant folding.
978 if (Constant *C = ConstantFoldInstruction(I)) {
979 ReplaceUsesOfWith(I, C, Worklist);
980 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +0000981 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000982
983 // Simple DCE.
984 if (isInstructionTriviallyDead(I)) {
985 DEBUG(std::cerr << "Remove dead instruction '" << *I);
986
987 // Add uses to the worklist, which may be dead now.
988 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
989 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
990 Worklist.push_back(Use);
991 I->eraseFromParent();
992 RemoveFromWorklist(I, Worklist);
993 ++NumSimplify;
994 continue;
995 }
996
997 // Special case hacks that appear commonly in unswitched code.
998 switch (I->getOpcode()) {
999 case Instruction::Select:
1000 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1001 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1002 continue;
1003 }
1004 break;
1005 case Instruction::And:
1006 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1007 cast<BinaryOperator>(I)->swapOperands();
1008 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1009 if (CB->getValue()) // X & 1 -> X
1010 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1011 else // X & 0 -> 0
1012 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1013 continue;
1014 }
1015 break;
1016 case Instruction::Or:
1017 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1018 cast<BinaryOperator>(I)->swapOperands();
1019 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1020 if (CB->getValue()) // X | 1 -> 1
1021 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1022 else // X | 0 -> X
1023 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1024 continue;
1025 }
1026 break;
1027 case Instruction::Br: {
1028 BranchInst *BI = cast<BranchInst>(I);
1029 if (BI->isUnconditional()) {
1030 // If BI's parent is the only pred of the successor, fold the two blocks
1031 // together.
1032 BasicBlock *Pred = BI->getParent();
1033 BasicBlock *Succ = BI->getSuccessor(0);
1034 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1035 if (!SinglePred) continue; // Nothing to do.
1036 assert(SinglePred == Pred && "CFG broken");
1037
1038 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
1039 << Succ->getName() << "\n");
1040
1041 // Resolve any single entry PHI nodes in Succ.
1042 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1043 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1044
1045 // Move all of the successor contents from Succ to Pred.
1046 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1047 Succ->end());
1048 BI->eraseFromParent();
1049 RemoveFromWorklist(BI, Worklist);
1050
1051 // If Succ has any successors with PHI nodes, update them to have
1052 // entries coming from Pred instead of Succ.
1053 Succ->replaceAllUsesWith(Pred);
1054
1055 // Remove Succ from the loop tree.
1056 LI->removeBlock(Succ);
1057 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001058 ++NumSimplify;
Chris Lattner29f771b2006-02-18 01:27:45 +00001059 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001060 // Conditional branch. Turn it into an unconditional branch, then
1061 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001062 break; // FIXME: Enable.
1063
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001064 DEBUG(std::cerr << "Folded branch: " << *BI);
1065 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1066 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1067 DeadSucc->removePredecessor(BI->getParent(), true);
1068 Worklist.push_back(new BranchInst(LiveSucc, BI));
1069 BI->eraseFromParent();
1070 RemoveFromWorklist(BI, Worklist);
1071 ++NumSimplify;
1072
1073 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001074 }
1075 break;
1076 }
1077 }
1078 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001079}