blob: 955622e0256c2274efb090c3a29dc113b950680a [file] [log] [blame]
Chris Lattner18f16092004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner18f16092004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner18f16092004-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 Spencerc1030572007-01-19 21:13:56 +000032#include "llvm/DerivedTypes.h"
Chris Lattner18f16092004-04-19 18:07:02 +000033#include "llvm/Function.h"
34#include "llvm/Instructions.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner18f16092004-04-19 18:07:02 +000036#include "llvm/Analysis/LoopInfo.h"
Devang Patel1bc89362007-03-07 00:26:10 +000037#include "llvm/Analysis/LoopPass.h"
Devang Patelcce624a2007-06-28 00:49:00 +000038#include "llvm/Analysis/Dominators.h"
Chris Lattner18f16092004-04-19 18:07:02 +000039#include "llvm/Transforms/Utils/Cloning.h"
40#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81be2e92006-02-10 19:08:15 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
Devang Patelfb688d42007-02-26 20:22:50 +000043#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere487abb2006-02-09 20:15:48 +000044#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000045#include "llvm/Support/Compiler.h"
46#include "llvm/Support/Debug.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000047#include <algorithm>
Chris Lattner2f4b8982006-02-09 19:14:52 +000048#include <set>
Chris Lattner18f16092004-04-19 18:07:02 +000049using namespace llvm;
50
Chris Lattner0e5f4992006-12-19 21:40:18 +000051STATISTIC(NumBranches, "Number of branches unswitched");
52STATISTIC(NumSwitches, "Number of switches unswitched");
53STATISTIC(NumSelects , "Number of selects unswitched");
54STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
56
Dan Gohman844731a2008-05-13 00:00:25 +000057static cl::opt<unsigned>
58Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
59 cl::init(10), cl::Hidden);
Chris Lattnere487abb2006-02-09 20:15:48 +000060
Dan Gohman844731a2008-05-13 00:00:25 +000061namespace {
Devang Patel1bc89362007-03-07 00:26:10 +000062 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
Chris Lattner18f16092004-04-19 18:07:02 +000063 LoopInfo *LI; // Loop information
Devang Patel1bc89362007-03-07 00:26:10 +000064 LPPassManager *LPM;
Chris Lattnera6fc94b2006-02-18 07:57:38 +000065
Devang Patel1bc89362007-03-07 00:26:10 +000066 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnera6fc94b2006-02-18 07:57:38 +000068 std::vector<Loop*> LoopProcessWorklist;
Devang Patelfb688d42007-02-26 20:22:50 +000069 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel743f7e82007-06-06 00:21:03 +000070
71 bool OptimizeForSize;
Devang Patel6f62af62007-07-30 23:07:10 +000072 bool redoLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000073
74 DominanceFrontier *DF;
75 DominatorTree *DT;
76
77 /// LoopDF - Loop's dominance frontier. This set is a collection of
78 /// loop exiting blocks' DF member blocks. However this does set does not
79 /// includes basic blocks that are inside loop.
80 SmallPtrSet<BasicBlock *, 8> LoopDF;
81
82 /// OrigLoopExitMap - This is used to map loop exiting block with
83 /// corresponding loop exit block, before updating CFG.
84 DenseMap<BasicBlock *, BasicBlock *> OrigLoopExitMap;
Chris Lattner18f16092004-04-19 18:07:02 +000085 public:
Devang Patel19974732007-05-03 01:11:54 +000086 static char ID; // Pass ID, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000087 explicit LoopUnswitch(bool Os = false) :
Devang Patel6f62af62007-07-30 23:07:10 +000088 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false) {}
Devang Patel794fd752007-05-01 21:15:47 +000089
Devang Patel1bc89362007-03-07 00:26:10 +000090 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patel6f62af62007-07-30 23:07:10 +000091 bool processLoop(Loop *L);
Chris Lattner18f16092004-04-19 18:07:02 +000092
93 /// This transformation requires natural loop information & requires that
94 /// loop preheaders be inserted into the CFG...
95 ///
96 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +000098 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +000099 AU.addRequired<LoopInfo>();
100 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +0000101 AU.addRequiredID(LCSSAID);
Devang Patel15c260a2007-07-31 08:03:26 +0000102 AU.addPreservedID(LCSSAID);
103 AU.addPreserved<DominatorTree>();
104 AU.addPreserved<DominanceFrontier>();
Chris Lattner18f16092004-04-19 18:07:02 +0000105 }
106
107 private:
Devang Patel15c260a2007-07-31 08:03:26 +0000108
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000109 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
110 /// remove it.
111 void RemoveLoopFromWorklist(Loop *L) {
112 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
113 LoopProcessWorklist.end(), L);
114 if (I != LoopProcessWorklist.end())
115 LoopProcessWorklist.erase(I);
116 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000117
Chris Lattner48a80b02008-04-21 00:25:49 +0000118 /// Split all of the edges from inside the loop to their exit blocks.
119 /// Update the appropriate Phi nodes as we do so.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000120 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000121 SmallVector<BasicBlock *, 8> &MiddleBlocks);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000122
Chris Lattner48a80b02008-04-21 00:25:49 +0000123 /// If BB's dominance frontier has a member that is not part of loop L then
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000124 /// remove it. Add NewDFMember in BB's dominance frontier.
125 void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
126 BasicBlock *NewDFMember);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000127
Chris Lattnerc2358092006-02-11 00:43:37 +0000128 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattner4c41d492006-02-10 01:24:09 +0000129 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000130 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000131 BasicBlock *ExitBlock);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000132 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000133
134 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
135 Constant *Val, bool isEqual);
Devang Patelcce624a2007-06-28 00:49:00 +0000136
137 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
138 BasicBlock *TrueDest,
139 BasicBlock *FalseDest,
140 Instruction *InsertPt);
141
Devang Patel15c260a2007-07-31 08:03:26 +0000142 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerdb410242006-02-18 02:42:34 +0000143 void RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000144 std::vector<Instruction*> &Worklist, Loop *l);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000145 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattner18f16092004-04-19 18:07:02 +0000146 };
Chris Lattner18f16092004-04-19 18:07:02 +0000147}
Dan Gohman844731a2008-05-13 00:00:25 +0000148char LoopUnswitch::ID = 0;
149static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattner18f16092004-04-19 18:07:02 +0000150
Devang Patel743f7e82007-06-06 00:21:03 +0000151LoopPass *llvm::createLoopUnswitchPass(bool Os) {
152 return new LoopUnswitch(Os);
153}
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000154
155/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
156/// invariant in the loop, or has an invariant piece, return the invariant.
157/// Otherwise, return null.
158static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
159 // Constants should be folded, not unswitched on!
160 if (isa<Constant>(Cond)) return false;
Devang Patel558f1b82007-06-28 00:44:10 +0000161
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000162 // TODO: Handle: br (VARIANT|INVARIANT).
163 // TODO: Hoist simple expressions out of loops.
164 if (L->isLoopInvariant(Cond)) return Cond;
165
166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
167 if (BO->getOpcode() == Instruction::And ||
168 BO->getOpcode() == Instruction::Or) {
169 // If either the left or right side is invariant, we can unswitch on this,
170 // which will cause the branch to go away in one loop and the condition to
171 // simplify in the other one.
172 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
173 return LHS;
174 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
175 return RHS;
176 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000177
178 return 0;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000179}
180
Devang Patel1bc89362007-03-07 00:26:10 +0000181bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Devang Patel1bc89362007-03-07 00:26:10 +0000182 LI = &getAnalysis<LoopInfo>();
183 LPM = &LPM_Ref;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000184 DF = getAnalysisToUpdate<DominanceFrontier>();
185 DT = getAnalysisToUpdate<DominatorTree>();
186
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000187 bool Changed = false;
Devang Patel6f62af62007-07-30 23:07:10 +0000188
189 do {
190 redoLoop = false;
191 Changed |= processLoop(L);
192 } while(redoLoop);
193
194 return Changed;
195}
196
197/// processLoop - Do actual work and unswitch loop if possible and profitable.
198bool LoopUnswitch::processLoop(Loop *L) {
199 assert(L->isLCSSAForm());
200 bool Changed = false;
201
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000202 // Loop over all of the basic blocks in the loop. If we find an interior
203 // block that is branching on a loop-invariant condition, we can unswitch this
204 // loop.
205 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
206 I != E; ++I) {
207 TerminatorInst *TI = (*I)->getTerminator();
208 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
209 // If this isn't branching on an invariant condition, we can't unswitch
210 // it.
211 if (BI->isConditional()) {
212 // See if this, or some part of it, is loop invariant. If so, we can
213 // unswitch on it if we desire.
214 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000215 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner47811b72006-09-28 23:35:22 +0000216 L)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000217 ++NumBranches;
218 return true;
219 }
220 }
221 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
222 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
223 if (LoopCond && SI->getNumCases() > 1) {
224 // Find a value to unswitch on:
225 // FIXME: this should chose the most expensive case!
226 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel52956922007-02-26 19:31:58 +0000227 // Do not process same value again and again.
Devang Patelfb688d42007-02-26 20:22:50 +0000228 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel52956922007-02-26 19:31:58 +0000229 continue;
Devang Patel52956922007-02-26 19:31:58 +0000230
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000231 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
232 ++NumSwitches;
233 return true;
234 }
235 }
236 }
237
238 // Scan the instructions to check for unswitchable values.
239 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
240 BBI != E; ++BBI)
241 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
242 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000243 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner47811b72006-09-28 23:35:22 +0000244 L)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000245 ++NumSelects;
246 return true;
247 }
248 }
249 }
Owen Anderson6edf3992006-06-12 21:49:21 +0000250
251 assert(L->isLCSSAForm());
252
Chris Lattner18f16092004-04-19 18:07:02 +0000253 return Changed;
254}
255
Chris Lattner4e132392006-02-15 22:03:36 +0000256/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
257/// 1. Exit the loop with no side effects.
258/// 2. Branch to the latch block with no side-effects.
259///
260/// If these conditions are true, we return true and set ExitBB to the block we
261/// exit through.
262///
263static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
264 BasicBlock *&ExitBB,
265 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000266 if (!Visited.insert(BB).second) {
267 // Already visited and Ok, end of recursion.
268 return true;
269 } else if (!L->contains(BB)) {
270 // Otherwise, this is a loop exit, this is fine so long as this is the
271 // first exit.
272 if (ExitBB != 0) return false;
273 ExitBB = BB;
274 return true;
275 }
276
277 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000278 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000279 // Check to see if the successor is a trivial loop exit.
280 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
281 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000282 }
Chris Lattner4e132392006-02-15 22:03:36 +0000283
284 // Okay, everything after this looks good, check to make sure that this block
285 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000286 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner4e132392006-02-15 22:03:36 +0000287 if (I->mayWriteToMemory())
288 return false;
289
290 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000291}
292
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000293/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
294/// leads to an exit from the specified loop, and has no side-effects in the
295/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000296static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
297 std::set<BasicBlock*> Visited;
298 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattner4e132392006-02-15 22:03:36 +0000299 BasicBlock *ExitBB = 0;
300 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
301 return ExitBB;
302 return 0;
303}
Chris Lattner708e1a52006-02-10 02:30:37 +0000304
Chris Lattner4c41d492006-02-10 01:24:09 +0000305/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
306/// trivial: that is, that the condition controls whether or not the loop does
307/// anything at all. If this is a trivial condition, unswitching produces no
308/// code duplications (equivalently, it produces a simpler loop and a new empty
309/// loop, which gets deleted).
310///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000311/// If this is a trivial condition, return true, otherwise return false. When
312/// returning true, this sets Cond and Val to the condition that controls the
313/// trivial condition: when Cond dynamically equals Val, the loop is known to
314/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
315/// Cond == Val.
316///
317static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000318 BasicBlock **LoopExit = 0) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000319 BasicBlock *Header = L->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000320 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000321
Chris Lattnera48654e2006-02-15 22:52:05 +0000322 BasicBlock *LoopExitBB = 0;
323 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
324 // If the header block doesn't end with a conditional branch on Cond, we
325 // can't handle it.
326 if (!BI->isConditional() || BI->getCondition() != Cond)
327 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000328
Chris Lattnera48654e2006-02-15 22:52:05 +0000329 // Check to see if a successor of the branch is guaranteed to go to the
330 // latch block or exit through a one exit block without having any
331 // side-effects. If so, determine the value of Cond that causes it to do
332 // this.
333 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000334 if (Val) *Val = ConstantInt::getTrue();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000335 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000336 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnera48654e2006-02-15 22:52:05 +0000337 }
338 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
339 // If this isn't a switch on Cond, we can't handle it.
340 if (SI->getCondition() != Cond) return false;
341
342 // Check to see if a successor of the switch is guaranteed to go to the
343 // latch block or exit through a one exit block without having any
344 // side-effects. If so, determine the value of Cond that causes it to do
345 // this. Note that we can't trivially unswitch on the default case.
346 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
347 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
348 // Okay, we found a trivial case, remember the value that is trivial.
349 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000350 break;
351 }
Chris Lattner4e132392006-02-15 22:03:36 +0000352 }
353
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000354 // If we didn't find a single unique LoopExit block, or if the loop exit block
355 // contains phi nodes, this isn't trivial.
356 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000357 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000358
Chris Lattnera48654e2006-02-15 22:52:05 +0000359 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000360
361 // We already know that nothing uses any scalar values defined inside of this
362 // loop. As such, we just have to check to see if this loop will execute any
363 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000364 // part of the loop that the code *would* execute. We already checked the
365 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000366 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
367 if (I->mayWriteToMemory())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000368 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000369 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000370}
371
372/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
373/// we choose to unswitch the specified loop on the specified value.
374///
375unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
376 // If the condition is trivial, always unswitch. There is no code growth for
377 // this case.
378 if (IsTrivialUnswitchCondition(L, LIC))
379 return 0;
380
Owen Anderson372994b2006-06-28 17:47:50 +0000381 // FIXME: This is really overly conservative. However, more liberal
382 // estimations have thus far resulted in excessive unswitching, which is bad
383 // both in compile time and in code size. This should be replaced once
384 // someone figures out how a good estimation.
385 return L->getBlocks().size();
Chris Lattnerdaa2bf92006-06-28 16:38:55 +0000386
Chris Lattner4c41d492006-02-10 01:24:09 +0000387 unsigned Cost = 0;
388 // FIXME: this is brain dead. It should take into consideration code
389 // shrinkage.
390 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
391 I != E; ++I) {
392 BasicBlock *BB = *I;
393 // Do not include empty blocks in the cost calculation. This happen due to
394 // loop canonicalization and will be removed.
395 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
396 continue;
397
398 // Count basic blocks.
399 ++Cost;
400 }
401
402 return Cost;
403}
404
Chris Lattnerc2358092006-02-11 00:43:37 +0000405/// UnswitchIfProfitable - We have found that we can unswitch L when
406/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
407/// unswitch the loop, reprocess the pieces, then return true.
408bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
409 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner0f862e52006-03-24 07:14:00 +0000410 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
Devang Patel743f7e82007-06-06 00:21:03 +0000411
412 // Do not do non-trivial unswitch while optimizing for size.
413 if (Cost && OptimizeForSize)
414 return false;
415
Chris Lattner0f862e52006-03-24 07:14:00 +0000416 if (Cost > Threshold) {
Chris Lattnerc2358092006-02-11 00:43:37 +0000417 // FIXME: this should estimate growth by the amount of code shared by the
418 // resultant unswitched loops.
419 //
Bill Wendlingb7427032006-11-26 09:46:52 +0000420 DOUT << "NOT unswitching loop %"
421 << L->getHeader()->getName() << ", cost too high: "
422 << L->getBlocks().size() << "\n";
Chris Lattnerc2358092006-02-11 00:43:37 +0000423 return false;
424 }
Owen Anderson2b67f072006-06-26 07:44:36 +0000425
Chris Lattnerc2358092006-02-11 00:43:37 +0000426 // If this is a trivial condition to unswitch (which results in no code
427 // duplication), do it now.
Chris Lattner6d9d13d2006-02-15 01:44:42 +0000428 Constant *CondVal;
Chris Lattnerc2358092006-02-11 00:43:37 +0000429 BasicBlock *ExitBlock;
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000430 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
431 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerc2358092006-02-11 00:43:37 +0000432 } else {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000433 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerc2358092006-02-11 00:43:37 +0000434 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000435
Chris Lattnerc2358092006-02-11 00:43:37 +0000436 return true;
437}
438
Misha Brukmanfd939082005-04-21 23:48:37 +0000439// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner18f16092004-04-19 18:07:02 +0000440// current values into those specified by ValueMap.
441//
Misha Brukmanfd939082005-04-21 23:48:37 +0000442static inline void RemapInstruction(Instruction *I,
Chris Lattner5e665f52007-02-03 00:08:31 +0000443 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattner18f16092004-04-19 18:07:02 +0000444 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
445 Value *Op = I->getOperand(op);
Chris Lattner5e665f52007-02-03 00:08:31 +0000446 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattner18f16092004-04-19 18:07:02 +0000447 if (It != ValueMap.end()) Op = It->second;
448 I->setOperand(op, Op);
449 }
450}
451
Chris Lattner684b22d2007-08-02 16:53:43 +0000452// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
453// Info.
Devang Patel31ad7532007-07-18 23:48:20 +0000454//
455// If Orig block's immediate dominator is mapped in VM then use corresponding
456// immediate dominator from the map. Otherwise Orig block's dominator is also
457// NewBB's dominator.
458//
Devang Patel24857a32007-07-18 23:50:19 +0000459// OrigPreheader is loop pre-header before this pass started
Devang Patel31ad7532007-07-18 23:48:20 +0000460// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Patel24857a32007-07-18 23:50:19 +0000461// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Dan Gohman844731a2008-05-13 00:00:25 +0000462static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
463 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
464 BasicBlock *OrigHeader,
465 DominatorTree *DT, DominanceFrontier *DF,
466 DenseMap<const Value*, Value*> &VM) {
Devang Patelcce624a2007-06-28 00:49:00 +0000467
Devang Patel31ad7532007-07-18 23:48:20 +0000468 // If NewBB alreay has found its place in domiantor tree then no need to do
469 // anything.
470 if (DT->getNode(NewBB))
471 return;
472
473 // If Orig does not have any immediate domiantor then its clone, NewBB, does
474 // not need any immediate dominator.
Devang Patelcce624a2007-06-28 00:49:00 +0000475 DomTreeNode *OrigNode = DT->getNode(Orig);
476 if (!OrigNode)
477 return;
Devang Patel31ad7532007-07-18 23:48:20 +0000478 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
479 if (!OrigIDomNode)
480 return;
481
482 BasicBlock *OrigIDom = NULL;
483
484 // If Orig is original loop header then its immediate dominator is
485 // NewPreheader.
486 if (Orig == OrigHeader)
487 OrigIDom = NewPreheader;
488
489 // If Orig is new pre-header then its immediate dominator is
490 // original pre-header.
491 else if (Orig == NewPreheader)
492 OrigIDom = OrigPreheader;
493
494 // Other as DT to find Orig's immediate dominator.
495 else
496 OrigIDom = OrigIDomNode->getBlock();
497
Devang Pateldf5cf202007-07-30 21:10:44 +0000498 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
499 BasicBlock *NewIDom = OrigIDom;
500 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
501 if (I != VM.end()) {
502 NewIDom = cast<BasicBlock>(I->second);
503
504 // If NewIDom does not have corresponding dominatore tree node then
505 // get one.
506 if (!DT->getNode(NewIDom))
Devang Patel31ad7532007-07-18 23:48:20 +0000507 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
508 OrigHeader, DT, DF, VM);
Devang Patelcce624a2007-06-28 00:49:00 +0000509 }
Devang Pateldf5cf202007-07-30 21:10:44 +0000510
511 DT->addNewBlock(NewBB, NewIDom);
512
513 // Copy cloned dominance frontiner set
Devang Patelf34a43a2007-06-29 23:11:49 +0000514 DominanceFrontier::DomSetType NewDFSet;
515 if (DF) {
516 DominanceFrontier::iterator DFI = DF->find(Orig);
517 if ( DFI != DF->end()) {
518 DominanceFrontier::DomSetType S = DFI->second;
519 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
520 I != E; ++I) {
521 BasicBlock *BB = *I;
Chuck Rose III936baaa2007-07-27 18:26:35 +0000522 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
523 if (IDM != VM.end())
524 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Devang Patelf34a43a2007-06-29 23:11:49 +0000525 else
526 NewDFSet.insert(BB);
527 }
528 }
529 DF->addBasicBlock(NewBB, NewDFSet);
530 }
Devang Patelcce624a2007-06-28 00:49:00 +0000531}
532
Chris Lattner18f16092004-04-19 18:07:02 +0000533/// CloneLoop - Recursively clone the specified loop and all of its children,
534/// mapping the blocks with the specified map.
Chris Lattner5e665f52007-02-03 00:08:31 +0000535static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000536 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000537 Loop *New = new Loop();
538
Devang Patel1bc89362007-03-07 00:26:10 +0000539 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000540
541 // Add all of the blocks in L to the new loop.
542 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
543 I != E; ++I)
544 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000545 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000546
547 // Add all of the subloops to the new loop.
548 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000549 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000550
Chris Lattner18f16092004-04-19 18:07:02 +0000551 return New;
552}
553
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000554/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
555/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
556/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000557void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
558 BasicBlock *TrueDest,
559 BasicBlock *FalseDest,
560 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000561 // Insert a conditional branch on LIC to the two preheaders. The original
562 // code is the true version and the new code is the false version.
563 Value *BranchVal = LIC;
Reid Spencerc1030572007-01-19 21:13:56 +0000564 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000565 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000566 else if (Val != ConstantInt::getTrue())
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000567 // We want to enter the new loop when the condition is true.
568 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000569
570 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000571 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000572}
573
574
Chris Lattner4c41d492006-02-10 01:24:09 +0000575/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
576/// condition in it (a cond branch from its header block to its latch block,
577/// where the path through the loop that doesn't execute its body has no
578/// side-effects), unswitch it. This doesn't involve any code duplication, just
579/// moving the conditional branch outside of the loop and updating loop info.
580void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000581 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000582 BasicBlock *ExitBlock) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000583 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
584 << L->getHeader()->getName() << " [" << L->getBlocks().size()
585 << " blocks] in Function " << L->getHeader()->getParent()->getName()
586 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner4d1ca942006-02-10 01:36:35 +0000587
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000588 // First step, split the preheader, so that we know that there is a safe place
Chris Lattner4c41d492006-02-10 01:24:09 +0000589 // to insert the conditional branch. We will change 'OrigPH' to have a
590 // conditional branch on Cond.
591 BasicBlock *OrigPH = L->getLoopPreheader();
Devang Patel05c1dc62007-07-06 22:03:47 +0000592 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000593
594 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000595 // to branch to: this is the exit block out of the loop that we should
596 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000597
Chris Lattner4e132392006-02-15 22:03:36 +0000598 // Split this block now, so that the loop maintains its exit block, and so
599 // that the jump from the preheader can execute the contents of the exit block
600 // without actually branching to it (the exit block should be dominated by the
601 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000602 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000603 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000604
Chris Lattner4c41d492006-02-10 01:24:09 +0000605 // Okay, now we have a position to branch from and a position to branch to,
606 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000607 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
608 OrigPH->getTerminator());
Devang Patel2f170992008-06-02 22:52:56 +0000609 if (DT) {
610 DT->changeImmediateDominator(NewExit, OrigPH);
611 DT->changeImmediateDominator(NewPH, OrigPH);
612 }
Devang Patel64cd6582008-06-18 02:16:38 +0000613
614 if (DF) {
615 // NewExit is now part of NewPH and Loop Header's dominance
616 // frontier.
617 DominanceFrontier::iterator DFI = DF->find(NewPH);
618 if (DFI != DF->end())
619 DF->addToFrontier(DFI, NewExit);
620 DFI = DF->find(L->getHeader());
621 DF->addToFrontier(DFI, NewExit);
622
623 // ExitBlock does not have successors then NewExit is part of
624 // its dominance frontier.
625 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
626 DFI = DF->find(ExitBlock);
627 DF->addToFrontier(DFI, NewExit);
628 }
629 }
Devang Patel15c260a2007-07-31 08:03:26 +0000630 LPM->deleteSimpleAnalysisValue(OrigPH->getTerminator(), L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000631 OrigPH->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000632
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000633 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000634 redoLoop = true;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000635
Chris Lattner4c41d492006-02-10 01:24:09 +0000636 // Now that we know that the loop is never entered when this condition is a
637 // particular value, rewrite the loop with this info. We know that this will
638 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000639 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000640 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000641}
642
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000643/// ReplaceLoopExternalDFMember -
644/// If BB's dominance frontier has a member that is not part of loop L then
645/// remove it. Add NewDFMember in BB's dominance frontier.
646void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
647 BasicBlock *NewDFMember) {
648
649 DominanceFrontier::iterator DFI = DF->find(BB);
650 if (DFI == DF->end())
651 return;
652
653 DominanceFrontier::DomSetType &DFSet = DFI->second;
654 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
Devang Patelb5938982007-10-09 21:31:36 +0000655 DE = DFSet.end(); DI != DE;) {
656 BasicBlock *B = *DI++;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000657 if (L->contains(B))
658 continue;
David Greene60f75152007-12-17 17:40:29 +0000659
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000660 DF->removeFromFrontier(DFI, B);
661 LoopDF.insert(B);
662 }
663
664 DF->addToFrontier(DFI, NewDFMember);
665}
666
Chris Lattner48a80b02008-04-21 00:25:49 +0000667/// SplitExitEdges - Split all of the edges from inside the loop to their exit
668/// blocks. Update the appropriate Phi nodes as we do so.
669void LoopUnswitch::SplitExitEdges(Loop *L,
670 const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000671 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000672
Chris Lattner4c41d492006-02-10 01:24:09 +0000673 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000674 BasicBlock *ExitBlock = ExitBlocks[i];
675 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
676
677 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Devang Patel05c1dc62007-07-06 22:03:47 +0000678 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Devang Patel1ff61382007-08-02 15:25:57 +0000679 MiddleBlocks.push_back(MiddleBlock);
Owen Anderson2b67f072006-06-26 07:44:36 +0000680 BasicBlock* StartBlock = Preds[j];
681 BasicBlock* EndBlock;
682 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
683 EndBlock = MiddleBlock;
684 MiddleBlock = EndBlock->getSinglePredecessor();;
685 } else {
686 EndBlock = ExitBlock;
687 }
688
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000689 OrigLoopExitMap[StartBlock] = EndBlock;
690
Owen Anderson2b67f072006-06-26 07:44:36 +0000691 std::set<PHINode*> InsertedPHIs;
692 PHINode* OldLCSSA = 0;
693 for (BasicBlock::iterator I = EndBlock->begin();
694 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
695 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
Gabor Greif051a9502008-04-06 20:25:17 +0000696 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
697 OldLCSSA->getName() + ".us-lcssa",
698 MiddleBlock->getTerminator());
Owen Anderson2b67f072006-06-26 07:44:36 +0000699 NewLCSSA->addIncoming(OldValue, StartBlock);
700 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
701 NewLCSSA);
702 InsertedPHIs.insert(NewLCSSA);
703 }
704
Dan Gohman02dea8b2008-05-23 21:05:58 +0000705 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
Owen Anderson2b67f072006-06-26 07:44:36 +0000706 for (BasicBlock::iterator I = MiddleBlock->begin();
707 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
708 ++I) {
Gabor Greif051a9502008-04-06 20:25:17 +0000709 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
710 OldLCSSA->getName() + ".us-lcssa",
711 InsertPt);
Owen Anderson2b67f072006-06-26 07:44:36 +0000712 OldLCSSA->replaceAllUsesWith(NewLCSSA);
713 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
714 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000715
716 if (DF && DT) {
717 // StartBlock -- > MiddleBlock -- > EndBlock
718 // StartBlock is loop exiting block. EndBlock will become merge point
719 // of two loop exits after loop unswitch.
720
721 // If StartBlock's DF member includes a block that is not loop member
722 // then replace that DF member with EndBlock.
723
724 // If MiddleBlock's DF member includes a block that is not loop member
725 // tnen replace that DF member with EndBlock.
726
727 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
728 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
729 }
Owen Anderson2b67f072006-06-26 07:44:36 +0000730 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000731 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000732
Devang Patelf476e8e2007-10-03 21:16:08 +0000733}
734
Devang Patelc1e26602007-10-03 21:17:43 +0000735/// UnswitchNontrivialCondition - We determined that the loop is profitable
736/// to unswitch when LIC equal Val. Split it into loop versions and test the
737/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Patelf476e8e2007-10-03 21:16:08 +0000738void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
739 Loop *L) {
740 Function *F = L->getHeader()->getParent();
741 DOUT << "loop-unswitch: Unswitching loop %"
742 << L->getHeader()->getName() << " [" << L->getBlocks().size()
743 << " blocks] in Function " << F->getName()
744 << " when '" << *Val << "' == " << *LIC << "\n";
745
746 // LoopBlocks contains all of the basic blocks of the loop, including the
747 // preheader of the loop, the body of the loop, and the exit blocks of the
748 // loop, in that order.
749 std::vector<BasicBlock*> LoopBlocks;
750
751 // First step, split the preheader and exit blocks, and add these blocks to
752 // the LoopBlocks list.
753 BasicBlock *OrigHeader = L->getHeader();
754 BasicBlock *OrigPreheader = L->getLoopPreheader();
755 BasicBlock *NewPreheader = SplitEdge(OrigPreheader, L->getHeader(), this);
756 LoopBlocks.push_back(NewPreheader);
757
758 // We want the loop to come after the preheader, but before the exit blocks.
759 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
760
761 SmallVector<BasicBlock*, 8> ExitBlocks;
762 L->getUniqueExitBlocks(ExitBlocks);
763
764 // Split all of the edges from inside the loop to their exit blocks. Update
765 // the appropriate Phi nodes as we do so.
766 SmallVector<BasicBlock *,8> MiddleBlocks;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000767 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000768
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000769 // The exit blocks may have been changed due to edge splitting, recompute.
770 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000771 L->getUniqueExitBlocks(ExitBlocks);
772
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000773 // Add exit blocks to the loop blocks.
774 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000775
776 // Next step, clone all of the basic blocks that make up the loop (including
777 // the loop preheader and exit blocks), keeping track of the mapping between
778 // the instructions and blocks.
779 std::vector<BasicBlock*> NewBlocks;
780 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner5e665f52007-02-03 00:08:31 +0000781 DenseMap<const Value*, Value*> ValueMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000782 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner3dd4c402006-02-14 01:01:41 +0000783 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
784 NewBlocks.push_back(New);
785 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Patel15c260a2007-07-31 08:03:26 +0000786 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000787 }
788
Devang Patel1ff61382007-08-02 15:25:57 +0000789 // OutSiders are basic block that are dominated by original header and
790 // at the same time they are not part of loop.
791 SmallPtrSet<BasicBlock *, 8> OutSiders;
792 if (DT) {
793 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
794 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
795 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
796 BasicBlock *B = (*DI)->getBlock();
797
798 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
799 if (VI == ValueMap.end())
800 OutSiders.insert(B);
Devang Patelcce624a2007-06-28 00:49:00 +0000801 }
Devang Patel1ff61382007-08-02 15:25:57 +0000802 }
803
Chris Lattner18f16092004-04-19 18:07:02 +0000804 // Splice the newly inserted blocks into the function right before the
805 // original preheader.
806 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
807 NewBlocks[0], F->end());
808
809 // Now we create the new Loop object for the versioned loop.
Devang Patel1bc89362007-03-07 00:26:10 +0000810 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnere8255932006-02-10 23:26:14 +0000811 Loop *ParentLoop = L->getParentLoop();
812 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000813 // Make sure to add the cloned preheader and exit blocks to the parent loop
814 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000815 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000816 }
817
818 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
819 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000820 // The new exit block should be in the same loop as the old one.
821 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000822 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000823
824 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
825 "Exit block should have been split to have one successor!");
826 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
827
828 // If the successor of the exit block had PHI nodes, add an entry for
829 // NewExit.
830 PHINode *PN;
831 for (BasicBlock::iterator I = ExitSucc->begin();
832 (PN = dyn_cast<PHINode>(I)); ++I) {
833 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner5e665f52007-02-03 00:08:31 +0000834 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnere8255932006-02-10 23:26:14 +0000835 if (It != ValueMap.end()) V = It->second;
836 PN->addIncoming(V, NewExit);
837 }
Chris Lattner18f16092004-04-19 18:07:02 +0000838 }
839
840 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000841 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
842 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
843 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner18f16092004-04-19 18:07:02 +0000844 RemapInstruction(I, ValueMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000845
Chris Lattner18f16092004-04-19 18:07:02 +0000846 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000847 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
848 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000849 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000850
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000851 // Emit the new branch that selects between the two versions of this loop.
852 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000853 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000854 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000855
856 // Update dominator info
857 if (DF && DT) {
858
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000859 SmallVector<BasicBlock *,4> ExitingBlocks;
860 L->getExitingBlocks(ExitingBlocks);
861
Devang Patel1ff61382007-08-02 15:25:57 +0000862 // Clone dominator info for all cloned basic block.
863 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
864 BasicBlock *LBB = LoopBlocks[i];
865 BasicBlock *NBB = NewBlocks[i];
866 CloneDomInfo(NBB, LBB, NewPreheader, OrigPreheader,
867 OrigHeader, DT, DF, ValueMap);
868
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000869 // If LBB's dominance frontier includes DFMember
870 // such that DFMember is also a member of LoopDF then
871 // - Remove DFMember from LBB's dominance frontier
Chris Lattner48a80b02008-04-21 00:25:49 +0000872 // - Copy loop exiting blocks', that are dominated by BB,
873 // dominance frontier member in BB's dominance frontier
Devang Patel1ff61382007-08-02 15:25:57 +0000874
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000875 DominanceFrontier::iterator LBBI = DF->find(LBB);
Devang Patel1ff61382007-08-02 15:25:57 +0000876 DominanceFrontier::iterator NBBI = DF->find(NBB);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000877 if (LBBI == DF->end())
878 continue;
879
880 DominanceFrontier::DomSetType &LBSet = LBBI->second;
881 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
882 LE = LBSet.end(); LI != LE; /* NULL */) {
883 BasicBlock *B = *LI++;
884 if (B == LBB && B == L->getHeader())
885 continue;
886 bool removeB = false;
887 if (!LoopDF.count(B))
888 continue;
889
890 // If LBB dominates loop exits then insert loop exit block's DF
891 // into B's DF.
Chris Lattner48a80b02008-04-21 00:25:49 +0000892 for(SmallVector<BasicBlock *, 4>::iterator
893 LExitI = ExitingBlocks.begin(),
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000894 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
895 BasicBlock *E = *LExitI;
896
897 if (!DT->dominates(LBB,E))
898 continue;
899
900 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
901 OrigLoopExitMap.find(E);
902 if (DFBI == OrigLoopExitMap.end())
903 continue;
904
905 BasicBlock *DFB = DFBI->second;
906 DF->addToFrontier(LBBI, DFB);
907 DF->addToFrontier(NBBI, DFB);
908 removeB = true;
909 }
910
Chris Lattner48a80b02008-04-21 00:25:49 +0000911 // If B's replacement is inserted in DF then now is the time to remove
912 // B.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000913 if (removeB) {
914 DF->removeFromFrontier(LBBI, B);
915 if (L->contains(B))
916 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
917 else
Devang Patel1ff61382007-08-02 15:25:57 +0000918 DF->removeFromFrontier(NBBI, B);
919 }
920 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000921
Devang Patel1ff61382007-08-02 15:25:57 +0000922 }
923
924 // MiddleBlocks are dominated by original pre header. SplitEdge updated
925 // MiddleBlocks' dominance frontier appropriately.
926 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
927 BasicBlock *MBB = MiddleBlocks[i];
928 if (!MBB->getSinglePredecessor())
929 DT->changeImmediateDominator(MBB, OrigPreheader);
930 }
931
932 // All Outsiders are now dominated by original pre header.
933 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
934 OE = OutSiders.end(); OI != OE; ++OI) {
935 BasicBlock *OB = *OI;
936 DT->changeImmediateDominator(OB, OrigPreheader);
937 }
938
939 // New loop headers are dominated by original preheader
940 DT->changeImmediateDominator(NewBlocks[0], OrigPreheader);
941 DT->changeImmediateDominator(LoopBlocks[0], OrigPreheader);
942 }
943
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000944 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000945 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000946
947 // Now we rewrite the original code to know that the condition is true and the
948 // new code to know that the condition is false.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000949 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
950
951 // It's possible that simplifying one loop could cause the other to be
952 // deleted. If so, don't simplify it.
953 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
954 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000955}
956
Chris Lattner52221f72006-02-17 00:31:07 +0000957/// RemoveFromWorklist - Remove all instances of I from the worklist vector
958/// specified.
959static void RemoveFromWorklist(Instruction *I,
960 std::vector<Instruction*> &Worklist) {
961 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
962 Worklist.end(), I);
963 while (WI != Worklist.end()) {
964 unsigned Offset = WI-Worklist.begin();
965 Worklist.erase(WI);
966 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
967 }
968}
969
970/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
971/// program, replacing all uses with V and update the worklist.
972static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +0000973 std::vector<Instruction*> &Worklist,
974 Loop *L, LPPassManager *LPM) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000975 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner52221f72006-02-17 00:31:07 +0000976
977 // Add uses to the worklist, which may be dead now.
978 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
979 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
980 Worklist.push_back(Use);
981
982 // Add users to the worklist which may be simplified now.
983 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
984 UI != E; ++UI)
985 Worklist.push_back(cast<Instruction>(*UI));
Devang Patel15c260a2007-07-31 08:03:26 +0000986 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +0000987 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +0000988 I->replaceAllUsesWith(V);
989 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +0000990 ++NumSimplify;
991}
992
Chris Lattnerdb410242006-02-18 02:42:34 +0000993/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
994/// information, and remove any dead successors it has.
995///
996void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000997 std::vector<Instruction*> &Worklist,
998 Loop *L) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000999 if (pred_begin(BB) != pred_end(BB)) {
1000 // This block isn't dead, since an edge to BB was just removed, see if there
1001 // are any easy simplifications we can do now.
1002 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1003 // If it has one pred, fold phi nodes in BB.
1004 while (isa<PHINode>(BB->begin()))
1005 ReplaceUsesOfWith(BB->begin(),
1006 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patel15c260a2007-07-31 08:03:26 +00001007 Worklist, L, LPM);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001008
1009 // If this is the header of a loop and the only pred is the latch, we now
1010 // have an unreachable loop.
1011 if (Loop *L = LI->getLoopFor(BB))
1012 if (L->getHeader() == BB && L->contains(Pred)) {
1013 // Remove the branch from the latch to the header block, this makes
1014 // the header dead, which will make the latch dead (because the header
1015 // dominates the latch).
Devang Patel15c260a2007-07-31 08:03:26 +00001016 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001017 Pred->getTerminator()->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001018 new UnreachableInst(Pred);
1019
1020 // The loop is now broken, remove it from LI.
1021 RemoveLoopFromHierarchy(L);
1022
1023 // Reprocess the header, which now IS dead.
Devang Patel15c260a2007-07-31 08:03:26 +00001024 RemoveBlockIfDead(BB, Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001025 return;
1026 }
1027
1028 // If pred ends in a uncond branch, add uncond branch to worklist so that
1029 // the two blocks will get merged.
1030 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1031 if (BI->isUnconditional())
1032 Worklist.push_back(BI);
1033 }
1034 return;
1035 }
Chris Lattner52221f72006-02-17 00:31:07 +00001036
Bill Wendlingb7427032006-11-26 09:46:52 +00001037 DOUT << "Nuking dead block: " << *BB;
Chris Lattnerdb410242006-02-18 02:42:34 +00001038
1039 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001040 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +00001041 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001042
1043 // Anything that uses the instructions in this basic block should have their
1044 // uses replaced with undefs.
1045 if (!I->use_empty())
1046 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1047 }
Chris Lattnerdb410242006-02-18 02:42:34 +00001048
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001049 // If this is the edge to the header block for a loop, remove the loop and
1050 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +00001051 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001052 if (BBLoop->getLoopLatch() == BB)
1053 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +00001054 }
1055
1056 // Remove the block from the loop info, which removes it from any loops it
1057 // was in.
1058 LI->removeBlock(BB);
1059
1060
1061 // Remove phi node entries in successors for this block.
1062 TerminatorInst *TI = BB->getTerminator();
1063 std::vector<BasicBlock*> Succs;
1064 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1065 Succs.push_back(TI->getSuccessor(i));
1066 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001067 }
1068
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001069 // Unique the successors, remove anything with multiple uses.
Chris Lattnerdb410242006-02-18 02:42:34 +00001070 std::sort(Succs.begin(), Succs.end());
1071 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1072
1073 // Remove the basic block, including all of the instructions contained in it.
Devang Patel15c260a2007-07-31 08:03:26 +00001074 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001075 BB->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001076 // Remove successor blocks here that are not dead, so that we know we only
1077 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1078 // then getting removed before we revisit them, which is badness.
1079 //
1080 for (unsigned i = 0; i != Succs.size(); ++i)
1081 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1082 // One exception is loop headers. If this block was the preheader for a
1083 // loop, then we DO want to visit the loop so the loop gets deleted.
1084 // We know that if the successor is a loop header, that this loop had to
1085 // be the preheader: the case where this was the latch block was handled
1086 // above and headers can only have two predecessors.
1087 if (!LI->isLoopHeader(Succs[i])) {
1088 Succs.erase(Succs.begin()+i);
1089 --i;
1090 }
1091 }
1092
Chris Lattnerdb410242006-02-18 02:42:34 +00001093 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patel15c260a2007-07-31 08:03:26 +00001094 RemoveBlockIfDead(Succs[i], Worklist, L);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001095}
Chris Lattner52221f72006-02-17 00:31:07 +00001096
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001097/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1098/// become unwrapped, either because the backedge was deleted, or because the
1099/// edge into the header was removed. If the edge into the header from the
1100/// latch block was removed, the loop is unwrapped but subloops are still alive,
1101/// so they just reparent loops. If the loops are actually dead, they will be
1102/// removed later.
1103void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel1bc89362007-03-07 00:26:10 +00001104 LPM->deleteLoopFromQueue(L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001105 RemoveLoopFromWorklist(L);
1106}
1107
1108
1109
Chris Lattnerc2358092006-02-11 00:43:37 +00001110// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1111// the value specified by Val in the specified loop, or we know it does NOT have
1112// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +00001113void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +00001114 Constant *Val,
1115 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +00001116 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +00001117
Chris Lattner18f16092004-04-19 18:07:02 +00001118 // FIXME: Support correlated properties, like:
1119 // for (...)
1120 // if (li1 < li2)
1121 // ...
1122 // if (li1 > li2)
1123 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +00001124
Chris Lattner708e1a52006-02-10 02:30:37 +00001125 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1126 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +00001127 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +00001128 std::vector<Instruction*> Worklist;
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001129
Chris Lattner52221f72006-02-17 00:31:07 +00001130 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1131 // in the loop with the appropriate one directly.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001132 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001133 Value *Replacement;
1134 if (IsEqual)
1135 Replacement = Val;
1136 else
Reid Spencer579dca12007-01-12 04:24:46 +00001137 Replacement = ConstantInt::get(Type::Int1Ty,
1138 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner52221f72006-02-17 00:31:07 +00001139
1140 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1141 if (Instruction *U = cast<Instruction>(Users[i])) {
1142 if (!L->contains(U->getParent()))
1143 continue;
1144 U->replaceUsesOfWith(LIC, Replacement);
1145 Worklist.push_back(U);
1146 }
1147 } else {
1148 // Otherwise, we don't know the precise value of LIC, but we do know that it
1149 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1150 // can. This case occurs when we unswitch switch statements.
1151 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1152 if (Instruction *U = cast<Instruction>(Users[i])) {
1153 if (!L->contains(U->getParent()))
1154 continue;
1155
1156 Worklist.push_back(U);
1157
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001158 // If we know that LIC is not Val, use this info to simplify code.
1159 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1160 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1161 if (SI->getCaseValue(i) == Val) {
1162 // Found a dead case value. Don't remove PHI nodes in the
1163 // successor if they become single-entry, those PHI nodes may
1164 // be in the Users list.
Owen Anderson2b67f072006-06-26 07:44:36 +00001165
1166 // FIXME: This is a hack. We need to keep the successor around
1167 // and hooked up so as to preserve the loop structure, because
1168 // trying to update it is complicated. So instead we preserve the
1169 // loop structure and put the block on an dead code path.
1170
1171 BasicBlock* Old = SI->getParent();
Devang Patel05c1dc62007-07-06 22:03:47 +00001172 BasicBlock* Split = SplitBlock(Old, SI, this);
Owen Anderson2b67f072006-06-26 07:44:36 +00001173
1174 Instruction* OldTerm = Old->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001175 BranchInst::Create(Split, SI->getSuccessor(i),
1176 ConstantInt::getTrue(), OldTerm);
Devang Patel9ee49c52007-09-20 23:45:50 +00001177
Chris Lattner48a80b02008-04-21 00:25:49 +00001178 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
Owen Anderson2b67f072006-06-26 07:44:36 +00001179 Old->getTerminator()->eraseFromParent();
1180
Owen Andersonbef85082006-06-27 22:26:09 +00001181 PHINode *PN;
1182 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1183 (PN = dyn_cast<PHINode>(II)); ++II) {
1184 Value *InVal = PN->removeIncomingValue(Split, false);
1185 PN->addIncoming(InVal, Old);
Owen Anderson2b67f072006-06-26 07:44:36 +00001186 }
1187
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001188 SI->removeCase(i);
1189 break;
Chris Lattnerc2358092006-02-11 00:43:37 +00001190 }
1191 }
Chris Lattnerc2358092006-02-11 00:43:37 +00001192 }
Chris Lattner52221f72006-02-17 00:31:07 +00001193
1194 // TODO: We could do other simplifications, for example, turning
1195 // LIC == Val -> false.
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001196 }
Chris Lattner52221f72006-02-17 00:31:07 +00001197 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001198
Devang Patel15c260a2007-07-31 08:03:26 +00001199 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001200}
1201
1202/// SimplifyCode - Okay, now that we have simplified some instructions in the
1203/// loop, walk over it and constant prop, dce, and fold control flow where
1204/// possible. Note that this is effectively a very simple loop-structure-aware
1205/// optimizer. During processing of this loop, L could very well be deleted, so
1206/// it must not be used.
1207///
1208/// FIXME: When the loop optimizer is more mature, separate this out to a new
1209/// pass.
1210///
Devang Patel15c260a2007-07-31 08:03:26 +00001211void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +00001212 while (!Worklist.empty()) {
1213 Instruction *I = Worklist.back();
1214 Worklist.pop_back();
1215
1216 // Simple constant folding.
1217 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Patel15c260a2007-07-31 08:03:26 +00001218 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001219 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001220 }
Chris Lattner52221f72006-02-17 00:31:07 +00001221
1222 // Simple DCE.
1223 if (isInstructionTriviallyDead(I)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001224 DOUT << "Remove dead instruction '" << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001225
1226 // Add uses to the worklist, which may be dead now.
1227 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1228 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1229 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +00001230 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001231 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001232 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001233 ++NumSimplify;
1234 continue;
1235 }
1236
1237 // Special case hacks that appear commonly in unswitched code.
1238 switch (I->getOpcode()) {
1239 case Instruction::Select:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001240 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Chris Lattner684b22d2007-08-02 16:53:43 +00001241 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1242 LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001243 continue;
1244 }
1245 break;
1246 case Instruction::And:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001247 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001248 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001249 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001250 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001251 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001252 if (CB->isOne()) // X & 1 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001253 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001254 else // X & 0 -> 0
Devang Patel15c260a2007-07-31 08:03:26 +00001255 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001256 continue;
1257 }
Chris Lattner52221f72006-02-17 00:31:07 +00001258 break;
1259 case Instruction::Or:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001260 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001261 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001262 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001263 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001264 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001265 if (CB->isOne()) // X | 1 -> 1
Devang Patel15c260a2007-07-31 08:03:26 +00001266 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001267 else // X | 0 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001268 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001269 continue;
1270 }
Chris Lattner52221f72006-02-17 00:31:07 +00001271 break;
1272 case Instruction::Br: {
1273 BranchInst *BI = cast<BranchInst>(I);
1274 if (BI->isUnconditional()) {
1275 // If BI's parent is the only pred of the successor, fold the two blocks
1276 // together.
1277 BasicBlock *Pred = BI->getParent();
1278 BasicBlock *Succ = BI->getSuccessor(0);
1279 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1280 if (!SinglePred) continue; // Nothing to do.
1281 assert(SinglePred == Pred && "CFG broken");
1282
Bill Wendlingb7427032006-11-26 09:46:52 +00001283 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1284 << Succ->getName() << "\n";
Chris Lattner52221f72006-02-17 00:31:07 +00001285
1286 // Resolve any single entry PHI nodes in Succ.
1287 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001288 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001289
1290 // Move all of the successor contents from Succ to Pred.
1291 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1292 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001293 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001294 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001295 RemoveFromWorklist(BI, Worklist);
1296
1297 // If Succ has any successors with PHI nodes, update them to have
1298 // entries coming from Pred instead of Succ.
1299 Succ->replaceAllUsesWith(Pred);
1300
1301 // Remove Succ from the loop tree.
1302 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001303 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001304 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001305 ++NumSimplify;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001306 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001307 // Conditional branch. Turn it into an unconditional branch, then
1308 // remove dead blocks.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001309 break; // FIXME: Enable.
1310
Bill Wendlingb7427032006-11-26 09:46:52 +00001311 DOUT << "Folded branch: " << *BI;
Reid Spencer579dca12007-01-12 04:24:46 +00001312 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1313 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnerdb410242006-02-18 02:42:34 +00001314 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greif051a9502008-04-06 20:25:17 +00001315 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patel15c260a2007-07-31 08:03:26 +00001316 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001317 BI->eraseFromParent();
Chris Lattnerdb410242006-02-18 02:42:34 +00001318 RemoveFromWorklist(BI, Worklist);
1319 ++NumSimplify;
1320
Devang Patel15c260a2007-07-31 08:03:26 +00001321 RemoveBlockIfDead(DeadSucc, Worklist, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001322 }
1323 break;
1324 }
1325 }
1326 }
Chris Lattner18f16092004-04-19 18:07:02 +00001327}