blob: 8adeea25d78e52b2dba2dd13ed0d39b0f151db23 [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 Lattnerf48f7772004-04-19 18:07:02 +000035#include "llvm/Analysis/LoopInfo.h"
36#include "llvm/Transforms/Utils/Cloning.h"
37#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerec6b40a2006-02-10 19:08:15 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000040#include "llvm/ADT/PostOrderIterator.h"
Chris Lattner89762192006-02-09 20:15:48 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/CommandLine.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000043#include <algorithm>
Chris Lattner2826e052006-02-09 19:14:52 +000044#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000045using namespace llvm;
46
Chris Lattner79a42ac2006-12-19 21:40:18 +000047STATISTIC(NumBranches, "Number of branches unswitched");
48STATISTIC(NumSwitches, "Number of switches unswitched");
49STATISTIC(NumSelects , "Number of selects unswitched");
50STATISTIC(NumTrivial , "Number of unswitches that are trivial");
51STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
52
Chris Lattnerf48f7772004-04-19 18:07:02 +000053namespace {
Chris Lattner89762192006-02-09 20:15:48 +000054 cl::opt<unsigned>
55 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
56 cl::init(10), cl::Hidden);
57
Chris Lattnerf48f7772004-04-19 18:07:02 +000058 class LoopUnswitch : public FunctionPass {
59 LoopInfo *LI; // Loop information
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000060
61 // LoopProcessWorklist - List of loops we need to process.
62 std::vector<Loop*> LoopProcessWorklist;
Chris Lattnerf48f7772004-04-19 18:07:02 +000063 public:
64 virtual bool runOnFunction(Function &F);
65 bool visitLoop(Loop *L);
66
67 /// This transformation requires natural loop information & requires that
68 /// loop preheaders be inserted into the CFG...
69 ///
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000072 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000073 AU.addRequired<LoopInfo>();
74 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000075 AU.addRequiredID(LCSSAID);
76 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000077 }
78
79 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000080 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
81 /// remove it.
82 void RemoveLoopFromWorklist(Loop *L) {
83 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
84 LoopProcessWorklist.end(), L);
85 if (I != LoopProcessWorklist.end())
86 LoopProcessWorklist.erase(I);
87 }
88
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000089 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +000090 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +000091 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +000092 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000093 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +000094 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +000095 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000096
97 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
98 Constant *Val, bool isEqual);
99
100 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000101 void RemoveBlockIfDead(BasicBlock *BB,
102 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000103 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000104 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000105 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000106}
107
Jeff Coheneca0d0f2005-01-06 05:47:18 +0000108FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000109
110bool LoopUnswitch::runOnFunction(Function &F) {
111 bool Changed = false;
112 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000113
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000114 // Populate the worklist of loops to process in post-order.
115 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
116 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
117 LoopProcessWorklist.push_back(*LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000118
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000119 // Process the loops in worklist order, this is a post-order visitation of
120 // the loops. We use a worklist of loops so that loops can be removed at any
121 // time if they are deleted (e.g. the backedge of a loop is removed).
122 while (!LoopProcessWorklist.empty()) {
123 Loop *L = LoopProcessWorklist.back();
124 LoopProcessWorklist.pop_back();
125 Changed |= visitLoop(L);
126 }
127
128 return Changed;
129}
130
131/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
132/// invariant in the loop, or has an invariant piece, return the invariant.
133/// Otherwise, return null.
134static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
135 // Constants should be folded, not unswitched on!
136 if (isa<Constant>(Cond)) return false;
137
138 // TODO: Handle: br (VARIANT|INVARIANT).
139 // TODO: Hoist simple expressions out of loops.
140 if (L->isLoopInvariant(Cond)) return Cond;
141
142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
143 if (BO->getOpcode() == Instruction::And ||
144 BO->getOpcode() == Instruction::Or) {
145 // If either the left or right side is invariant, we can unswitch on this,
146 // which will cause the branch to go away in one loop and the condition to
147 // simplify in the other one.
148 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
149 return LHS;
150 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
151 return RHS;
152 }
153
154 return 0;
155}
156
157bool LoopUnswitch::visitLoop(Loop *L) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000158 assert(L->isLCSSAForm());
159
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000160 bool Changed = false;
161
162 // Loop over all of the basic blocks in the loop. If we find an interior
163 // block that is branching on a loop-invariant condition, we can unswitch this
164 // loop.
165 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
166 I != E; ++I) {
167 TerminatorInst *TI = (*I)->getTerminator();
168 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
169 // If this isn't branching on an invariant condition, we can't unswitch
170 // it.
171 if (BI->isConditional()) {
172 // See if this, or some part of it, is loop invariant. If so, we can
173 // unswitch on it if we desire.
174 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000175 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000176 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000177 ++NumBranches;
178 return true;
179 }
180 }
181 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
182 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
183 if (LoopCond && SI->getNumCases() > 1) {
184 // Find a value to unswitch on:
185 // FIXME: this should chose the most expensive case!
186 Constant *UnswitchVal = SI->getCaseValue(1);
187 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
188 ++NumSwitches;
189 return true;
190 }
191 }
192 }
193
194 // Scan the instructions to check for unswitchable values.
195 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
196 BBI != E; ++BBI)
197 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
198 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000199 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000200 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000201 ++NumSelects;
202 return true;
203 }
204 }
205 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000206
207 assert(L->isLCSSAForm());
208
Chris Lattnerf48f7772004-04-19 18:07:02 +0000209 return Changed;
210}
211
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000212/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
213/// 1. Exit the loop with no side effects.
214/// 2. Branch to the latch block with no side-effects.
215///
216/// If these conditions are true, we return true and set ExitBB to the block we
217/// exit through.
218///
219static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
220 BasicBlock *&ExitBB,
221 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000222 if (!Visited.insert(BB).second) {
223 // Already visited and Ok, end of recursion.
224 return true;
225 } else if (!L->contains(BB)) {
226 // Otherwise, this is a loop exit, this is fine so long as this is the
227 // first exit.
228 if (ExitBB != 0) return false;
229 ExitBB = BB;
230 return true;
231 }
232
233 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000234 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000235 // Check to see if the successor is a trivial loop exit.
236 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
237 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000238 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000239
240 // Okay, everything after this looks good, check to make sure that this block
241 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000243 if (I->mayWriteToMemory())
244 return false;
245
246 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000247}
248
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000249/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
250/// leads to an exit from the specified loop, and has no side-effects in the
251/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000252static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
253 std::set<BasicBlock*> Visited;
254 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000255 BasicBlock *ExitBB = 0;
256 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
257 return ExitBB;
258 return 0;
259}
Chris Lattner6e263152006-02-10 02:30:37 +0000260
Chris Lattnered7a67b2006-02-10 01:24:09 +0000261/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
262/// trivial: that is, that the condition controls whether or not the loop does
263/// anything at all. If this is a trivial condition, unswitching produces no
264/// code duplications (equivalently, it produces a simpler loop and a new empty
265/// loop, which gets deleted).
266///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000267/// If this is a trivial condition, return true, otherwise return false. When
268/// returning true, this sets Cond and Val to the condition that controls the
269/// trivial condition: when Cond dynamically equals Val, the loop is known to
270/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
271/// Cond == Val.
272///
273static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000274 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000275 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000276 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000277
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000278 BasicBlock *LoopExitBB = 0;
279 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
280 // If the header block doesn't end with a conditional branch on Cond, we
281 // can't handle it.
282 if (!BI->isConditional() || BI->getCondition() != Cond)
283 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000284
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000285 // Check to see if a successor of the branch is guaranteed to go to the
286 // latch block or exit through a one exit block without having any
287 // side-effects. If so, determine the value of Cond that causes it to do
288 // this.
289 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000290 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000291 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000292 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000293 }
294 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
295 // If this isn't a switch on Cond, we can't handle it.
296 if (SI->getCondition() != Cond) return false;
297
298 // Check to see if a successor of the switch is guaranteed to go to the
299 // latch block or exit through a one exit block without having any
300 // side-effects. If so, determine the value of Cond that causes it to do
301 // this. Note that we can't trivially unswitch on the default case.
302 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
303 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
304 // Okay, we found a trivial case, remember the value that is trivial.
305 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000306 break;
307 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000308 }
309
Chris Lattnere5521db2006-02-22 23:55:00 +0000310 // If we didn't find a single unique LoopExit block, or if the loop exit block
311 // contains phi nodes, this isn't trivial.
312 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000313 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000314
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000315 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000316
317 // We already know that nothing uses any scalar values defined inside of this
318 // loop. As such, we just have to check to see if this loop will execute any
319 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000320 // part of the loop that the code *would* execute. We already checked the
321 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000322 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
323 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000324 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000325 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000326}
327
328/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
329/// we choose to unswitch the specified loop on the specified value.
330///
331unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
332 // If the condition is trivial, always unswitch. There is no code growth for
333 // this case.
334 if (IsTrivialUnswitchCondition(L, LIC))
335 return 0;
336
Owen Anderson18e816f2006-06-28 17:47:50 +0000337 // FIXME: This is really overly conservative. However, more liberal
338 // estimations have thus far resulted in excessive unswitching, which is bad
339 // both in compile time and in code size. This should be replaced once
340 // someone figures out how a good estimation.
341 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000342
Chris Lattnered7a67b2006-02-10 01:24:09 +0000343 unsigned Cost = 0;
344 // FIXME: this is brain dead. It should take into consideration code
345 // shrinkage.
346 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
347 I != E; ++I) {
348 BasicBlock *BB = *I;
349 // Do not include empty blocks in the cost calculation. This happen due to
350 // loop canonicalization and will be removed.
351 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
352 continue;
353
354 // Count basic blocks.
355 ++Cost;
356 }
357
358 return Cost;
359}
360
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000361/// UnswitchIfProfitable - We have found that we can unswitch L when
362/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
363/// unswitch the loop, reprocess the pieces, then return true.
364bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
365 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000366 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
367 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000368 // FIXME: this should estimate growth by the amount of code shared by the
369 // resultant unswitched loops.
370 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000371 DOUT << "NOT unswitching loop %"
372 << L->getHeader()->getName() << ", cost too high: "
373 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000374 return false;
375 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000376
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000377 // If this is a trivial condition to unswitch (which results in no code
378 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000379 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000380 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000381 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
382 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000383 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000384 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000385 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000386
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000387 return true;
388}
389
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000390/// SplitBlock - Split the specified block at the specified instruction - every
391/// thing before SplitPt stays in Old and everything starting with SplitPt moves
392/// to a new block. The two blocks are joined by an unconditional branch and
393/// the loop info is updated.
394///
395BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000396 BasicBlock::iterator SplitIt = SplitPt;
397 while (isa<PHINode>(SplitIt))
398 ++SplitIt;
399 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000400
401 // The new block lives in whichever loop the old one did.
402 if (Loop *L = LI->getLoopFor(Old))
403 L->addBasicBlockToLoop(New, *LI);
404
405 return New;
406}
407
408
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000409BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
410 TerminatorInst *LatchTerm = BB->getTerminator();
411 unsigned SuccNum = 0;
412 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
413 assert(i != e && "Didn't find edge?");
414 if (LatchTerm->getSuccessor(i) == Succ) {
415 SuccNum = i;
416 break;
417 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000418 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000419
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000420 // If this is a critical edge, let SplitCriticalEdge do it.
421 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
422 return LatchTerm->getSuccessor(SuccNum);
423
424 // If the edge isn't critical, then BB has a single successor or Succ has a
425 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000426 BasicBlock::iterator SplitPoint;
427 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
428 // If the successor only has a single pred, split the top of the successor
429 // block.
430 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000431 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000432 } else {
433 // Otherwise, if BB has a single successor, split it at the bottom of the
434 // block.
435 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
436 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000437 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000438 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000439}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000440
Chris Lattnerf48f7772004-04-19 18:07:02 +0000441
442
Misha Brukmanb1c93172005-04-21 23:48:37 +0000443// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000444// current values into those specified by ValueMap.
445//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000446static inline void RemapInstruction(Instruction *I,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000447 std::map<const Value *, Value*> &ValueMap) {
448 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
449 Value *Op = I->getOperand(op);
450 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
451 if (It != ValueMap.end()) Op = It->second;
452 I->setOperand(op, Op);
453 }
454}
455
456/// CloneLoop - Recursively clone the specified loop and all of its children,
457/// mapping the blocks with the specified map.
458static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
459 LoopInfo *LI) {
460 Loop *New = new Loop();
461
462 if (PL)
463 PL->addChildLoop(New);
464 else
465 LI->addTopLevelLoop(New);
466
467 // Add all of the blocks in L to the new loop.
468 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
469 I != E; ++I)
470 if (LI->getLoopFor(*I) == L)
471 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
472
473 // Add all of the subloops to the new loop.
474 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
475 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000476
Chris Lattnerf48f7772004-04-19 18:07:02 +0000477 return New;
478}
479
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000480/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
481/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
482/// code immediately before InsertPt.
483static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
484 BasicBlock *TrueDest,
485 BasicBlock *FalseDest,
486 Instruction *InsertPt) {
487 // Insert a conditional branch on LIC to the two preheaders. The original
488 // code is the true version and the new code is the false version.
489 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000490 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000491 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000492 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000493 // We want to enter the new loop when the condition is true.
494 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000495
496 // Insert the new branch.
497 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
498}
499
500
Chris Lattnered7a67b2006-02-10 01:24:09 +0000501/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
502/// condition in it (a cond branch from its header block to its latch block,
503/// where the path through the loop that doesn't execute its body has no
504/// side-effects), unswitch it. This doesn't involve any code duplication, just
505/// moving the conditional branch outside of the loop and updating loop info.
506void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000507 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000508 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000509 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
510 << L->getHeader()->getName() << " [" << L->getBlocks().size()
511 << " blocks] in Function " << L->getHeader()->getParent()->getName()
512 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000513
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000514 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000515 // to insert the conditional branch. We will change 'OrigPH' to have a
516 // conditional branch on Cond.
517 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000518 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000519
520 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000521 // to branch to: this is the exit block out of the loop that we should
522 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000523
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000524 // Split this block now, so that the loop maintains its exit block, and so
525 // that the jump from the preheader can execute the contents of the exit block
526 // without actually branching to it (the exit block should be dominated by the
527 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000528 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000529 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000530
Chris Lattnered7a67b2006-02-10 01:24:09 +0000531 // Okay, now we have a position to branch from and a position to branch to,
532 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000533 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
534 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000535 OrigPH->getTerminator()->eraseFromParent();
536
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000537 // We need to reprocess this loop, it could be unswitched again.
538 LoopProcessWorklist.push_back(L);
539
Chris Lattnered7a67b2006-02-10 01:24:09 +0000540 // Now that we know that the loop is never entered when this condition is a
541 // particular value, rewrite the loop with this info. We know that this will
542 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000543 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000544 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000545}
546
Chris Lattnerf48f7772004-04-19 18:07:02 +0000547
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000548/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
549/// equal Val. Split it into loop versions and test the condition outside of
550/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000551void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
552 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000553 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000554 DOUT << "loop-unswitch: Unswitching loop %"
555 << L->getHeader()->getName() << " [" << L->getBlocks().size()
556 << " blocks] in Function " << F->getName()
557 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000558
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000559 // LoopBlocks contains all of the basic blocks of the loop, including the
560 // preheader of the loop, the body of the loop, and the exit blocks of the
561 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000562 std::vector<BasicBlock*> LoopBlocks;
563
564 // First step, split the preheader and exit blocks, and add these blocks to
565 // the LoopBlocks list.
566 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000567 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000568
569 // We want the loop to come after the preheader, but before the exit blocks.
570 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
571
572 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000573 L->getUniqueExitBlocks(ExitBlocks);
574
Owen Andersonf52351e2006-06-26 07:44:36 +0000575 // Split all of the edges from inside the loop to their exit blocks. Update
576 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000577 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000578 BasicBlock *ExitBlock = ExitBlocks[i];
579 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
580
581 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
582 assert(L->contains(Preds[j]) &&
583 "All preds of loop exit blocks must be the same loop!");
Owen Andersonf52351e2006-06-26 07:44:36 +0000584 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
585 BasicBlock* StartBlock = Preds[j];
586 BasicBlock* EndBlock;
587 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
588 EndBlock = MiddleBlock;
589 MiddleBlock = EndBlock->getSinglePredecessor();;
590 } else {
591 EndBlock = ExitBlock;
592 }
593
594 std::set<PHINode*> InsertedPHIs;
595 PHINode* OldLCSSA = 0;
596 for (BasicBlock::iterator I = EndBlock->begin();
597 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
598 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
599 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
600 OldLCSSA->getName() + ".us-lcssa",
601 MiddleBlock->getTerminator());
602 NewLCSSA->addIncoming(OldValue, StartBlock);
603 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
604 NewLCSSA);
605 InsertedPHIs.insert(NewLCSSA);
606 }
607
Owen Anderson00b974c2006-07-19 03:51:48 +0000608 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000609 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
610 for (BasicBlock::iterator I = MiddleBlock->begin();
611 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
612 ++I) {
613 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
614 OldLCSSA->getName() + ".us-lcssa",
615 InsertPt);
616 OldLCSSA->replaceAllUsesWith(NewLCSSA);
617 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
618 }
619 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000620 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000621
622 // The exit blocks may have been changed due to edge splitting, recompute.
623 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000624 L->getUniqueExitBlocks(ExitBlocks);
625
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000626 // Add exit blocks to the loop blocks.
627 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000628
629 // Next step, clone all of the basic blocks that make up the loop (including
630 // the loop preheader and exit blocks), keeping track of the mapping between
631 // the instructions and blocks.
632 std::vector<BasicBlock*> NewBlocks;
633 NewBlocks.reserve(LoopBlocks.size());
634 std::map<const Value*, Value*> ValueMap;
635 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000636 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
637 NewBlocks.push_back(New);
638 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000639 }
640
641 // Splice the newly inserted blocks into the function right before the
642 // original preheader.
643 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
644 NewBlocks[0], F->end());
645
646 // Now we create the new Loop object for the versioned loop.
647 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000648 Loop *ParentLoop = L->getParentLoop();
649 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000650 // Make sure to add the cloned preheader and exit blocks to the parent loop
651 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000652 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
653 }
654
655 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
656 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000657 // The new exit block should be in the same loop as the old one.
658 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
659 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000660
661 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
662 "Exit block should have been split to have one successor!");
663 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
664
665 // If the successor of the exit block had PHI nodes, add an entry for
666 // NewExit.
667 PHINode *PN;
668 for (BasicBlock::iterator I = ExitSucc->begin();
669 (PN = dyn_cast<PHINode>(I)); ++I) {
670 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
671 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
672 if (It != ValueMap.end()) V = It->second;
673 PN->addIncoming(V, NewExit);
674 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000675 }
676
677 // Rewrite the code to refer to itself.
678 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
679 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
680 E = NewBlocks[i]->end(); I != E; ++I)
681 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000682
Chris Lattnerf48f7772004-04-19 18:07:02 +0000683 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000684 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
685 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000686 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000687
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000688 // Emit the new branch that selects between the two versions of this loop.
689 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
690 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000691
692 LoopProcessWorklist.push_back(L);
693 LoopProcessWorklist.push_back(NewLoop);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000694
695 // Now we rewrite the original code to know that the condition is true and the
696 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000697 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
698
699 // It's possible that simplifying one loop could cause the other to be
700 // deleted. If so, don't simplify it.
701 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
702 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000703}
704
Chris Lattner6fd13622006-02-17 00:31:07 +0000705/// RemoveFromWorklist - Remove all instances of I from the worklist vector
706/// specified.
707static void RemoveFromWorklist(Instruction *I,
708 std::vector<Instruction*> &Worklist) {
709 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
710 Worklist.end(), I);
711 while (WI != Worklist.end()) {
712 unsigned Offset = WI-Worklist.begin();
713 Worklist.erase(WI);
714 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
715 }
716}
717
718/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
719/// program, replacing all uses with V and update the worklist.
720static void ReplaceUsesOfWith(Instruction *I, Value *V,
721 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000722 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000723
724 // Add uses to the worklist, which may be dead now.
725 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
726 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
727 Worklist.push_back(Use);
728
729 // Add users to the worklist which may be simplified now.
730 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
731 UI != E; ++UI)
732 Worklist.push_back(cast<Instruction>(*UI));
733 I->replaceAllUsesWith(V);
734 I->eraseFromParent();
735 RemoveFromWorklist(I, Worklist);
736 ++NumSimplify;
737}
738
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000739/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
740/// information, and remove any dead successors it has.
741///
742void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
743 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000744 if (pred_begin(BB) != pred_end(BB)) {
745 // This block isn't dead, since an edge to BB was just removed, see if there
746 // are any easy simplifications we can do now.
747 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
748 // If it has one pred, fold phi nodes in BB.
749 while (isa<PHINode>(BB->begin()))
750 ReplaceUsesOfWith(BB->begin(),
751 cast<PHINode>(BB->begin())->getIncomingValue(0),
752 Worklist);
753
754 // If this is the header of a loop and the only pred is the latch, we now
755 // have an unreachable loop.
756 if (Loop *L = LI->getLoopFor(BB))
757 if (L->getHeader() == BB && L->contains(Pred)) {
758 // Remove the branch from the latch to the header block, this makes
759 // the header dead, which will make the latch dead (because the header
760 // dominates the latch).
761 Pred->getTerminator()->eraseFromParent();
762 new UnreachableInst(Pred);
763
764 // The loop is now broken, remove it from LI.
765 RemoveLoopFromHierarchy(L);
766
767 // Reprocess the header, which now IS dead.
768 RemoveBlockIfDead(BB, Worklist);
769 return;
770 }
771
772 // If pred ends in a uncond branch, add uncond branch to worklist so that
773 // the two blocks will get merged.
774 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
775 if (BI->isUnconditional())
776 Worklist.push_back(BI);
777 }
778 return;
779 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000780
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000781 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000782
783 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000784 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000785 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000786
787 // Anything that uses the instructions in this basic block should have their
788 // uses replaced with undefs.
789 if (!I->use_empty())
790 I->replaceAllUsesWith(UndefValue::get(I->getType()));
791 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000792
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000793 // If this is the edge to the header block for a loop, remove the loop and
794 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000795 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000796 if (BBLoop->getLoopLatch() == BB)
797 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000798 }
799
800 // Remove the block from the loop info, which removes it from any loops it
801 // was in.
802 LI->removeBlock(BB);
803
804
805 // Remove phi node entries in successors for this block.
806 TerminatorInst *TI = BB->getTerminator();
807 std::vector<BasicBlock*> Succs;
808 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
809 Succs.push_back(TI->getSuccessor(i));
810 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000811 }
812
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000813 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000814 std::sort(Succs.begin(), Succs.end());
815 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
816
817 // Remove the basic block, including all of the instructions contained in it.
818 BB->eraseFromParent();
819
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000820 // Remove successor blocks here that are not dead, so that we know we only
821 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
822 // then getting removed before we revisit them, which is badness.
823 //
824 for (unsigned i = 0; i != Succs.size(); ++i)
825 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
826 // One exception is loop headers. If this block was the preheader for a
827 // loop, then we DO want to visit the loop so the loop gets deleted.
828 // We know that if the successor is a loop header, that this loop had to
829 // be the preheader: the case where this was the latch block was handled
830 // above and headers can only have two predecessors.
831 if (!LI->isLoopHeader(Succs[i])) {
832 Succs.erase(Succs.begin()+i);
833 --i;
834 }
835 }
836
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000837 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
838 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000839}
Chris Lattner6fd13622006-02-17 00:31:07 +0000840
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000841/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
842/// become unwrapped, either because the backedge was deleted, or because the
843/// edge into the header was removed. If the edge into the header from the
844/// latch block was removed, the loop is unwrapped but subloops are still alive,
845/// so they just reparent loops. If the loops are actually dead, they will be
846/// removed later.
847void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
848 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
849 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
850 // they are now all in it.
851 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
852 I != E; ++I)
853 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
854 LI->changeLoopFor(*I, ParentLoop);
855
856 // Remove the loop from its parent loop.
857 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
858 ++I) {
859 assert(I != E && "Couldn't find loop");
860 if (*I == L) {
861 ParentLoop->removeChildLoop(I);
862 break;
863 }
864 }
865
866 // Move all subloops into the parent loop.
867 while (L->begin() != L->end())
868 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
869 } else {
870 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
871 // they no longer in a loop at all.
872
873 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
874 // Don't change blocks in subloops.
875 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
876 LI->removeBlock(L->getBlocks()[i]);
877 --i;
878 }
879 }
880
881 // Remove the loop from the top-level LoopInfo object.
882 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
883 assert(I != E && "Couldn't find loop");
884 if (*I == L) {
885 LI->removeLoop(I);
886 break;
887 }
888 }
889
890 // Move all of the subloops to the top-level.
891 while (L->begin() != L->end())
892 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
893 }
894
895 delete L;
896 RemoveLoopFromWorklist(L);
897}
898
899
900
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000901// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
902// the value specified by Val in the specified loop, or we know it does NOT have
903// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000904void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000905 Constant *Val,
906 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000907 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000908
Chris Lattnerf48f7772004-04-19 18:07:02 +0000909 // FIXME: Support correlated properties, like:
910 // for (...)
911 // if (li1 < li2)
912 // ...
913 // if (li1 > li2)
914 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000915
Chris Lattner6e263152006-02-10 02:30:37 +0000916 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
917 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000918 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000919 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000920
Chris Lattner6fd13622006-02-17 00:31:07 +0000921 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
922 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000923 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000924 Value *Replacement;
925 if (IsEqual)
926 Replacement = Val;
927 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000928 Replacement = ConstantInt::get(Type::Int1Ty,
929 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000930
931 for (unsigned i = 0, e = Users.size(); i != e; ++i)
932 if (Instruction *U = cast<Instruction>(Users[i])) {
933 if (!L->contains(U->getParent()))
934 continue;
935 U->replaceUsesOfWith(LIC, Replacement);
936 Worklist.push_back(U);
937 }
938 } else {
939 // Otherwise, we don't know the precise value of LIC, but we do know that it
940 // is certainly NOT "Val". As such, simplify any uses in the loop that we
941 // can. This case occurs when we unswitch switch statements.
942 for (unsigned i = 0, e = Users.size(); i != e; ++i)
943 if (Instruction *U = cast<Instruction>(Users[i])) {
944 if (!L->contains(U->getParent()))
945 continue;
946
947 Worklist.push_back(U);
948
Chris Lattnerfa335f62006-02-16 19:36:22 +0000949 // If we know that LIC is not Val, use this info to simplify code.
950 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
951 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
952 if (SI->getCaseValue(i) == Val) {
953 // Found a dead case value. Don't remove PHI nodes in the
954 // successor if they become single-entry, those PHI nodes may
955 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000956
957 // FIXME: This is a hack. We need to keep the successor around
958 // and hooked up so as to preserve the loop structure, because
959 // trying to update it is complicated. So instead we preserve the
960 // loop structure and put the block on an dead code path.
961
962 BasicBlock* Old = SI->getParent();
963 BasicBlock* Split = SplitBlock(Old, SI);
964
965 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000966 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000967 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000968
969 Old->getTerminator()->eraseFromParent();
970
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000971
972 PHINode *PN;
973 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
974 (PN = dyn_cast<PHINode>(II)); ++II) {
975 Value *InVal = PN->removeIncomingValue(Split, false);
976 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +0000977 }
978
Chris Lattnerfa335f62006-02-16 19:36:22 +0000979 SI->removeCase(i);
980 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000981 }
982 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000983 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000984
985 // TODO: We could do other simplifications, for example, turning
986 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000987 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000988 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000989
990 SimplifyCode(Worklist);
991}
992
993/// SimplifyCode - Okay, now that we have simplified some instructions in the
994/// loop, walk over it and constant prop, dce, and fold control flow where
995/// possible. Note that this is effectively a very simple loop-structure-aware
996/// optimizer. During processing of this loop, L could very well be deleted, so
997/// it must not be used.
998///
999/// FIXME: When the loop optimizer is more mature, separate this out to a new
1000/// pass.
1001///
1002void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001003 while (!Worklist.empty()) {
1004 Instruction *I = Worklist.back();
1005 Worklist.pop_back();
1006
1007 // Simple constant folding.
1008 if (Constant *C = ConstantFoldInstruction(I)) {
1009 ReplaceUsesOfWith(I, C, Worklist);
1010 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001011 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001012
1013 // Simple DCE.
1014 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001015 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +00001016
1017 // Add uses to the worklist, which may be dead now.
1018 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1019 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1020 Worklist.push_back(Use);
1021 I->eraseFromParent();
1022 RemoveFromWorklist(I, Worklist);
1023 ++NumSimplify;
1024 continue;
1025 }
1026
1027 // Special case hacks that appear commonly in unswitched code.
1028 switch (I->getOpcode()) {
1029 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001030 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001031 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001032 continue;
1033 }
1034 break;
1035 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001036 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001037 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001038 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001039 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001040 if (CB->getType() == Type::Int1Ty) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001041 if (CB->getZExtValue()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +00001042 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1043 else // X & 0 -> 0
1044 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1045 continue;
1046 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001047 break;
1048 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001049 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001050 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001051 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001052 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001053 if (CB->getType() == Type::Int1Ty) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001054 if (CB->getZExtValue()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001055 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1056 else // X | 0 -> X
1057 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1058 continue;
1059 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001060 break;
1061 case Instruction::Br: {
1062 BranchInst *BI = cast<BranchInst>(I);
1063 if (BI->isUnconditional()) {
1064 // If BI's parent is the only pred of the successor, fold the two blocks
1065 // together.
1066 BasicBlock *Pred = BI->getParent();
1067 BasicBlock *Succ = BI->getSuccessor(0);
1068 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1069 if (!SinglePred) continue; // Nothing to do.
1070 assert(SinglePred == Pred && "CFG broken");
1071
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001072 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1073 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001074
1075 // Resolve any single entry PHI nodes in Succ.
1076 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1077 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1078
1079 // Move all of the successor contents from Succ to Pred.
1080 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1081 Succ->end());
1082 BI->eraseFromParent();
1083 RemoveFromWorklist(BI, Worklist);
1084
1085 // If Succ has any successors with PHI nodes, update them to have
1086 // entries coming from Pred instead of Succ.
1087 Succ->replaceAllUsesWith(Pred);
1088
1089 // Remove Succ from the loop tree.
1090 LI->removeBlock(Succ);
1091 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001092 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001093 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001094 // Conditional branch. Turn it into an unconditional branch, then
1095 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001096 break; // FIXME: Enable.
1097
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001098 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001099 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1100 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001101 DeadSucc->removePredecessor(BI->getParent(), true);
1102 Worklist.push_back(new BranchInst(LiveSucc, BI));
1103 BI->eraseFromParent();
1104 RemoveFromWorklist(BI, Worklist);
1105 ++NumSimplify;
1106
1107 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001108 }
1109 break;
1110 }
1111 }
1112 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001113}