blob: f57b7bb5194043fc6fb8ccc383720b099a0ace31 [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
Devang Patele6962df2008-07-02 01:18:13 +000074 Loop *currentLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000075 DominanceFrontier *DF;
76 DominatorTree *DT;
Devang Patele6962df2008-07-02 01:18:13 +000077 BasicBlock *loopHeader;
78 BasicBlock *loopPreheader;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000079
80 /// LoopDF - Loop's dominance frontier. This set is a collection of
81 /// loop exiting blocks' DF member blocks. However this does set does not
82 /// includes basic blocks that are inside loop.
83 SmallPtrSet<BasicBlock *, 8> LoopDF;
84
85 /// OrigLoopExitMap - This is used to map loop exiting block with
86 /// corresponding loop exit block, before updating CFG.
87 DenseMap<BasicBlock *, BasicBlock *> OrigLoopExitMap;
Devang Patel1e41f6d2008-07-02 01:44:29 +000088
89 // LoopBlocks contains all of the basic blocks of the loop, including the
90 // preheader of the loop, the body of the loop, and the exit blocks of the
91 // loop, in that order.
92 std::vector<BasicBlock*> LoopBlocks;
93 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
94 std::vector<BasicBlock*> NewBlocks;
Chris Lattner18f16092004-04-19 18:07:02 +000095 public:
Devang Patel19974732007-05-03 01:11:54 +000096 static char ID; // Pass ID, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000097 explicit LoopUnswitch(bool Os = false) :
Devang Patele6962df2008-07-02 01:18:13 +000098 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false),
99 currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
100 loopPreheader(NULL) {}
Devang Patel794fd752007-05-01 21:15:47 +0000101
Devang Patel1bc89362007-03-07 00:26:10 +0000102 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patele6962df2008-07-02 01:18:13 +0000103 bool processCurrentLoop();
Chris Lattner18f16092004-04-19 18:07:02 +0000104
105 /// This transformation requires natural loop information & requires that
106 /// loop preheaders be inserted into the CFG...
107 ///
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +0000110 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +0000111 AU.addRequired<LoopInfo>();
112 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +0000113 AU.addRequiredID(LCSSAID);
Devang Patel15c260a2007-07-31 08:03:26 +0000114 AU.addPreservedID(LCSSAID);
Devang Patelb76247b2008-07-03 05:55:03 +0000115 // FIXME: Loop Unswitch does not preserve dominator info in all cases.
116 // AU.addPreserved<DominatorTree>();
117 // AU.addPreserved<DominanceFrontier>();
Chris Lattner18f16092004-04-19 18:07:02 +0000118 }
119
120 private:
Devang Patel15c260a2007-07-31 08:03:26 +0000121
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000122 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
123 /// remove it.
124 void RemoveLoopFromWorklist(Loop *L) {
125 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
126 LoopProcessWorklist.end(), L);
127 if (I != LoopProcessWorklist.end())
128 LoopProcessWorklist.erase(I);
129 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000130
Devang Patele6962df2008-07-02 01:18:13 +0000131 void initLoopData() {
132 loopHeader = currentLoop->getHeader();
133 loopPreheader = currentLoop->getLoopPreheader();
134 }
135
Chris Lattner48a80b02008-04-21 00:25:49 +0000136 /// Split all of the edges from inside the loop to their exit blocks.
137 /// Update the appropriate Phi nodes as we do so.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000138 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000139 SmallVector<BasicBlock *, 8> &MiddleBlocks);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000140
Chris Lattner48a80b02008-04-21 00:25:49 +0000141 /// If BB's dominance frontier has a member that is not part of loop L then
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000142 /// remove it. Add NewDFMember in BB's dominance frontier.
143 void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
144 BasicBlock *NewDFMember);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000145
Devang Patele6962df2008-07-02 01:18:13 +0000146 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
147 unsigned getLoopUnswitchCost(Value *LIC);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000148 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000149 BasicBlock *ExitBlock);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000150 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000151
152 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
153 Constant *Val, bool isEqual);
Devang Patelcce624a2007-06-28 00:49:00 +0000154
155 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
156 BasicBlock *TrueDest,
157 BasicBlock *FalseDest,
158 Instruction *InsertPt);
159
Devang Patel15c260a2007-07-31 08:03:26 +0000160 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerdb410242006-02-18 02:42:34 +0000161 void RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000162 std::vector<Instruction*> &Worklist, Loop *l);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000163 void RemoveLoopFromHierarchy(Loop *L);
Devang Patele6962df2008-07-02 01:18:13 +0000164 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
165 BasicBlock **LoopExit = 0);
166
Chris Lattner18f16092004-04-19 18:07:02 +0000167 };
Chris Lattner18f16092004-04-19 18:07:02 +0000168}
Dan Gohman844731a2008-05-13 00:00:25 +0000169char LoopUnswitch::ID = 0;
170static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattner18f16092004-04-19 18:07:02 +0000171
Devang Patel743f7e82007-06-06 00:21:03 +0000172LoopPass *llvm::createLoopUnswitchPass(bool Os) {
173 return new LoopUnswitch(Os);
174}
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000175
176/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
177/// invariant in the loop, or has an invariant piece, return the invariant.
178/// Otherwise, return null.
179static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
180 // Constants should be folded, not unswitched on!
181 if (isa<Constant>(Cond)) return false;
Devang Patel558f1b82007-06-28 00:44:10 +0000182
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000183 // TODO: Handle: br (VARIANT|INVARIANT).
184 // TODO: Hoist simple expressions out of loops.
185 if (L->isLoopInvariant(Cond)) return Cond;
186
187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
188 if (BO->getOpcode() == Instruction::And ||
189 BO->getOpcode() == Instruction::Or) {
190 // If either the left or right side is invariant, we can unswitch on this,
191 // which will cause the branch to go away in one loop and the condition to
192 // simplify in the other one.
193 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
194 return LHS;
195 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
196 return RHS;
197 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000198
199 return 0;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000200}
201
Devang Patel1bc89362007-03-07 00:26:10 +0000202bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Devang Patel1bc89362007-03-07 00:26:10 +0000203 LI = &getAnalysis<LoopInfo>();
204 LPM = &LPM_Ref;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000205 DF = getAnalysisToUpdate<DominanceFrontier>();
206 DT = getAnalysisToUpdate<DominatorTree>();
Devang Patele6962df2008-07-02 01:18:13 +0000207 currentLoop = L;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000208 bool Changed = false;
Devang Patel6f62af62007-07-30 23:07:10 +0000209
210 do {
Devang Patele6962df2008-07-02 01:18:13 +0000211 assert(currentLoop->isLCSSAForm());
Devang Patel6f62af62007-07-30 23:07:10 +0000212 redoLoop = false;
Devang Patele6962df2008-07-02 01:18:13 +0000213 Changed |= processCurrentLoop();
Devang Patel6f62af62007-07-30 23:07:10 +0000214 } while(redoLoop);
215
216 return Changed;
217}
218
Devang Patele6962df2008-07-02 01:18:13 +0000219/// processCurrentLoop - Do actual work and unswitch loop if possible
220/// and profitable.
221bool LoopUnswitch::processCurrentLoop() {
Devang Patel6f62af62007-07-30 23:07:10 +0000222 bool Changed = false;
223
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000224 // Loop over all of the basic blocks in the loop. If we find an interior
225 // block that is branching on a loop-invariant condition, we can unswitch this
226 // loop.
Devang Patele6962df2008-07-02 01:18:13 +0000227 for (Loop::block_iterator I = currentLoop->block_begin(),
228 E = currentLoop->block_end();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000229 I != E; ++I) {
230 TerminatorInst *TI = (*I)->getTerminator();
231 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
232 // If this isn't branching on an invariant condition, we can't unswitch
233 // it.
234 if (BI->isConditional()) {
235 // See if this, or some part of it, is loop invariant. If so, we can
236 // unswitch on it if we desire.
Devang Patele6962df2008-07-02 01:18:13 +0000237 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
238 currentLoop, Changed);
239 if (LoopCond && UnswitchIfProfitable(LoopCond,
240 ConstantInt::getTrue())) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000241 ++NumBranches;
242 return true;
243 }
244 }
245 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000246 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
247 currentLoop, Changed);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000248 if (LoopCond && SI->getNumCases() > 1) {
249 // Find a value to unswitch on:
250 // FIXME: this should chose the most expensive case!
251 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel52956922007-02-26 19:31:58 +0000252 // Do not process same value again and again.
Devang Patelfb688d42007-02-26 20:22:50 +0000253 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel52956922007-02-26 19:31:58 +0000254 continue;
Devang Patel52956922007-02-26 19:31:58 +0000255
Devang Patele6962df2008-07-02 01:18:13 +0000256 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000257 ++NumSwitches;
258 return true;
259 }
260 }
261 }
262
263 // Scan the instructions to check for unswitchable values.
264 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
265 BBI != E; ++BBI)
266 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000267 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
268 currentLoop, Changed);
269 if (LoopCond && UnswitchIfProfitable(LoopCond,
270 ConstantInt::getTrue())) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000271 ++NumSelects;
272 return true;
273 }
274 }
275 }
Chris Lattner18f16092004-04-19 18:07:02 +0000276 return Changed;
277}
278
Chris Lattner4e132392006-02-15 22:03:36 +0000279/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
280/// 1. Exit the loop with no side effects.
281/// 2. Branch to the latch block with no side-effects.
282///
283/// If these conditions are true, we return true and set ExitBB to the block we
284/// exit through.
285///
286static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
287 BasicBlock *&ExitBB,
288 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000289 if (!Visited.insert(BB).second) {
290 // Already visited and Ok, end of recursion.
291 return true;
292 } else if (!L->contains(BB)) {
293 // Otherwise, this is a loop exit, this is fine so long as this is the
294 // first exit.
295 if (ExitBB != 0) return false;
296 ExitBB = BB;
297 return true;
298 }
299
300 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000301 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000302 // Check to see if the successor is a trivial loop exit.
303 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
304 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000305 }
Chris Lattner4e132392006-02-15 22:03:36 +0000306
307 // Okay, everything after this looks good, check to make sure that this block
308 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000309 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner4e132392006-02-15 22:03:36 +0000310 if (I->mayWriteToMemory())
311 return false;
312
313 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000314}
315
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000316/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
317/// leads to an exit from the specified loop, and has no side-effects in the
318/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000319static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
320 std::set<BasicBlock*> Visited;
321 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattner4e132392006-02-15 22:03:36 +0000322 BasicBlock *ExitBB = 0;
323 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
324 return ExitBB;
325 return 0;
326}
Chris Lattner708e1a52006-02-10 02:30:37 +0000327
Chris Lattner4c41d492006-02-10 01:24:09 +0000328/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
329/// trivial: that is, that the condition controls whether or not the loop does
330/// anything at all. If this is a trivial condition, unswitching produces no
331/// code duplications (equivalently, it produces a simpler loop and a new empty
332/// loop, which gets deleted).
333///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000334/// If this is a trivial condition, return true, otherwise return false. When
335/// returning true, this sets Cond and Val to the condition that controls the
336/// trivial condition: when Cond dynamically equals Val, the loop is known to
337/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
338/// Cond == Val.
339///
Devang Patele6962df2008-07-02 01:18:13 +0000340bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
341 BasicBlock **LoopExit) {
342 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000343 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000344
Chris Lattnera48654e2006-02-15 22:52:05 +0000345 BasicBlock *LoopExitBB = 0;
346 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
347 // If the header block doesn't end with a conditional branch on Cond, we
348 // can't handle it.
349 if (!BI->isConditional() || BI->getCondition() != Cond)
350 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000351
Chris Lattnera48654e2006-02-15 22:52:05 +0000352 // Check to see if a successor of the branch is guaranteed to go to the
353 // latch block or exit through a one exit block without having any
354 // side-effects. If so, determine the value of Cond that causes it to do
355 // this.
Devang Patele6962df2008-07-02 01:18:13 +0000356 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
357 BI->getSuccessor(0)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000358 if (Val) *Val = ConstantInt::getTrue();
Devang Patele6962df2008-07-02 01:18:13 +0000359 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
360 BI->getSuccessor(1)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000361 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnera48654e2006-02-15 22:52:05 +0000362 }
363 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
364 // If this isn't a switch on Cond, we can't handle it.
365 if (SI->getCondition() != Cond) return false;
366
367 // Check to see if a successor of the switch is guaranteed to go to the
368 // latch block or exit through a one exit block without having any
369 // side-effects. If so, determine the value of Cond that causes it to do
370 // this. Note that we can't trivially unswitch on the default case.
371 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
Devang Patele6962df2008-07-02 01:18:13 +0000372 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
373 SI->getSuccessor(i)))) {
Chris Lattnera48654e2006-02-15 22:52:05 +0000374 // Okay, we found a trivial case, remember the value that is trivial.
375 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000376 break;
377 }
Chris Lattner4e132392006-02-15 22:03:36 +0000378 }
379
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000380 // If we didn't find a single unique LoopExit block, or if the loop exit block
381 // contains phi nodes, this isn't trivial.
382 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000383 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000384
Chris Lattnera48654e2006-02-15 22:52:05 +0000385 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000386
387 // We already know that nothing uses any scalar values defined inside of this
388 // loop. As such, we just have to check to see if this loop will execute any
389 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000390 // part of the loop that the code *would* execute. We already checked the
391 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000392 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
393 if (I->mayWriteToMemory())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000394 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000395 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000396}
397
398/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
Devang Patele6962df2008-07-02 01:18:13 +0000399/// we choose to unswitch current loop on the specified value.
Chris Lattner4c41d492006-02-10 01:24:09 +0000400///
Devang Patele6962df2008-07-02 01:18:13 +0000401unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000402 // If the condition is trivial, always unswitch. There is no code growth for
403 // this case.
Devang Patele6962df2008-07-02 01:18:13 +0000404 if (IsTrivialUnswitchCondition(LIC))
Chris Lattner4c41d492006-02-10 01:24:09 +0000405 return 0;
406
Owen Anderson372994b2006-06-28 17:47:50 +0000407 // FIXME: This is really overly conservative. However, more liberal
408 // estimations have thus far resulted in excessive unswitching, which is bad
409 // both in compile time and in code size. This should be replaced once
410 // someone figures out how a good estimation.
Devang Patele6962df2008-07-02 01:18:13 +0000411 return currentLoop->getBlocks().size();
Chris Lattnerdaa2bf92006-06-28 16:38:55 +0000412
Chris Lattner4c41d492006-02-10 01:24:09 +0000413 unsigned Cost = 0;
414 // FIXME: this is brain dead. It should take into consideration code
415 // shrinkage.
Devang Patele6962df2008-07-02 01:18:13 +0000416 for (Loop::block_iterator I = currentLoop->block_begin(),
417 E = currentLoop->block_end();
Chris Lattner4c41d492006-02-10 01:24:09 +0000418 I != E; ++I) {
419 BasicBlock *BB = *I;
420 // Do not include empty blocks in the cost calculation. This happen due to
421 // loop canonicalization and will be removed.
422 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
423 continue;
424
425 // Count basic blocks.
426 ++Cost;
427 }
428
429 return Cost;
430}
431
Devang Patele6962df2008-07-02 01:18:13 +0000432/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerc2358092006-02-11 00:43:37 +0000433/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
434/// unswitch the loop, reprocess the pieces, then return true.
Devang Patele6962df2008-07-02 01:18:13 +0000435bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
436 // Check to see if it would be profitable to unswitch current loop.
437 unsigned Cost = getLoopUnswitchCost(LoopCond);
Devang Patel743f7e82007-06-06 00:21:03 +0000438
439 // Do not do non-trivial unswitch while optimizing for size.
440 if (Cost && OptimizeForSize)
441 return false;
442
Chris Lattner0f862e52006-03-24 07:14:00 +0000443 if (Cost > Threshold) {
Chris Lattnerc2358092006-02-11 00:43:37 +0000444 // FIXME: this should estimate growth by the amount of code shared by the
445 // resultant unswitched loops.
446 //
Bill Wendlingb7427032006-11-26 09:46:52 +0000447 DOUT << "NOT unswitching loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000448 << currentLoop->getHeader()->getName() << ", cost too high: "
449 << currentLoop->getBlocks().size() << "\n";
Chris Lattnerc2358092006-02-11 00:43:37 +0000450 return false;
451 }
Devang Patele6962df2008-07-02 01:18:13 +0000452
453 initLoopData();
454
Chris Lattner6d9d13d2006-02-15 01:44:42 +0000455 Constant *CondVal;
Chris Lattnerc2358092006-02-11 00:43:37 +0000456 BasicBlock *ExitBlock;
Devang Patele6962df2008-07-02 01:18:13 +0000457 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
458 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Chris Lattnerc2358092006-02-11 00:43:37 +0000459 } else {
Devang Patele6962df2008-07-02 01:18:13 +0000460 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
Chris Lattnerc2358092006-02-11 00:43:37 +0000461 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000462
Chris Lattnerc2358092006-02-11 00:43:37 +0000463 return true;
464}
465
Misha Brukmanfd939082005-04-21 23:48:37 +0000466// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner18f16092004-04-19 18:07:02 +0000467// current values into those specified by ValueMap.
468//
Misha Brukmanfd939082005-04-21 23:48:37 +0000469static inline void RemapInstruction(Instruction *I,
Chris Lattner5e665f52007-02-03 00:08:31 +0000470 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattner18f16092004-04-19 18:07:02 +0000471 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
472 Value *Op = I->getOperand(op);
Chris Lattner5e665f52007-02-03 00:08:31 +0000473 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattner18f16092004-04-19 18:07:02 +0000474 if (It != ValueMap.end()) Op = It->second;
475 I->setOperand(op, Op);
476 }
477}
478
Chris Lattner684b22d2007-08-02 16:53:43 +0000479// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
480// Info.
Devang Patel31ad7532007-07-18 23:48:20 +0000481//
482// If Orig block's immediate dominator is mapped in VM then use corresponding
483// immediate dominator from the map. Otherwise Orig block's dominator is also
484// NewBB's dominator.
485//
Devang Patel24857a32007-07-18 23:50:19 +0000486// OrigPreheader is loop pre-header before this pass started
Devang Patel31ad7532007-07-18 23:48:20 +0000487// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Patel24857a32007-07-18 23:50:19 +0000488// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Dan Gohman844731a2008-05-13 00:00:25 +0000489static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
490 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
491 BasicBlock *OrigHeader,
492 DominatorTree *DT, DominanceFrontier *DF,
493 DenseMap<const Value*, Value*> &VM) {
Devang Patelcce624a2007-06-28 00:49:00 +0000494
Devang Patel31ad7532007-07-18 23:48:20 +0000495 // If NewBB alreay has found its place in domiantor tree then no need to do
496 // anything.
497 if (DT->getNode(NewBB))
498 return;
499
500 // If Orig does not have any immediate domiantor then its clone, NewBB, does
501 // not need any immediate dominator.
Devang Patelcce624a2007-06-28 00:49:00 +0000502 DomTreeNode *OrigNode = DT->getNode(Orig);
503 if (!OrigNode)
504 return;
Devang Patel31ad7532007-07-18 23:48:20 +0000505 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
506 if (!OrigIDomNode)
507 return;
508
509 BasicBlock *OrigIDom = NULL;
510
511 // If Orig is original loop header then its immediate dominator is
512 // NewPreheader.
513 if (Orig == OrigHeader)
514 OrigIDom = NewPreheader;
515
516 // If Orig is new pre-header then its immediate dominator is
517 // original pre-header.
518 else if (Orig == NewPreheader)
519 OrigIDom = OrigPreheader;
520
Devang Patel2095c382008-07-02 01:31:19 +0000521 // Otherwise ask DT to find Orig's immediate dominator.
Devang Patel31ad7532007-07-18 23:48:20 +0000522 else
523 OrigIDom = OrigIDomNode->getBlock();
524
Devang Pateldf5cf202007-07-30 21:10:44 +0000525 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
526 BasicBlock *NewIDom = OrigIDom;
527 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
528 if (I != VM.end()) {
529 NewIDom = cast<BasicBlock>(I->second);
530
531 // If NewIDom does not have corresponding dominatore tree node then
532 // get one.
533 if (!DT->getNode(NewIDom))
Devang Patel31ad7532007-07-18 23:48:20 +0000534 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
535 OrigHeader, DT, DF, VM);
Devang Patelcce624a2007-06-28 00:49:00 +0000536 }
Devang Pateldf5cf202007-07-30 21:10:44 +0000537
538 DT->addNewBlock(NewBB, NewIDom);
539
540 // Copy cloned dominance frontiner set
Devang Patelf34a43a2007-06-29 23:11:49 +0000541 DominanceFrontier::DomSetType NewDFSet;
542 if (DF) {
543 DominanceFrontier::iterator DFI = DF->find(Orig);
544 if ( DFI != DF->end()) {
545 DominanceFrontier::DomSetType S = DFI->second;
546 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
547 I != E; ++I) {
548 BasicBlock *BB = *I;
Chuck Rose III936baaa2007-07-27 18:26:35 +0000549 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
550 if (IDM != VM.end())
551 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Devang Patelf34a43a2007-06-29 23:11:49 +0000552 else
553 NewDFSet.insert(BB);
554 }
555 }
556 DF->addBasicBlock(NewBB, NewDFSet);
557 }
Devang Patelcce624a2007-06-28 00:49:00 +0000558}
559
Chris Lattner18f16092004-04-19 18:07:02 +0000560/// CloneLoop - Recursively clone the specified loop and all of its children,
561/// mapping the blocks with the specified map.
Chris Lattner5e665f52007-02-03 00:08:31 +0000562static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000563 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000564 Loop *New = new Loop();
565
Devang Patel1bc89362007-03-07 00:26:10 +0000566 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000567
568 // Add all of the blocks in L to the new loop.
569 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
570 I != E; ++I)
571 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000572 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000573
574 // Add all of the subloops to the new loop.
575 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000576 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000577
Chris Lattner18f16092004-04-19 18:07:02 +0000578 return New;
579}
580
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000581/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
582/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
583/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000584void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
585 BasicBlock *TrueDest,
586 BasicBlock *FalseDest,
587 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000588 // Insert a conditional branch on LIC to the two preheaders. The original
589 // code is the true version and the new code is the false version.
590 Value *BranchVal = LIC;
Reid Spencerc1030572007-01-19 21:13:56 +0000591 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000592 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000593 else if (Val != ConstantInt::getTrue())
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000594 // We want to enter the new loop when the condition is true.
595 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000596
597 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000598 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000599}
600
601
Chris Lattner4c41d492006-02-10 01:24:09 +0000602/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
603/// condition in it (a cond branch from its header block to its latch block,
604/// where the path through the loop that doesn't execute its body has no
605/// side-effects), unswitch it. This doesn't involve any code duplication, just
606/// moving the conditional branch outside of the loop and updating loop info.
607void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000608 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000609 BasicBlock *ExitBlock) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000610 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000611 << loopHeader->getName() << " [" << L->getBlocks().size()
Bill Wendlingb7427032006-11-26 09:46:52 +0000612 << " blocks] in Function " << L->getHeader()->getParent()->getName()
613 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner4d1ca942006-02-10 01:36:35 +0000614
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000615 // First step, split the preheader, so that we know that there is a safe place
Devang Patele6962df2008-07-02 01:18:13 +0000616 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattner4c41d492006-02-10 01:24:09 +0000617 // conditional branch on Cond.
Devang Patele6962df2008-07-02 01:18:13 +0000618 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000619
620 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000621 // to branch to: this is the exit block out of the loop that we should
622 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000623
Chris Lattner4e132392006-02-15 22:03:36 +0000624 // Split this block now, so that the loop maintains its exit block, and so
625 // that the jump from the preheader can execute the contents of the exit block
626 // without actually branching to it (the exit block should be dominated by the
627 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000628 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000629 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000630
Chris Lattner4c41d492006-02-10 01:24:09 +0000631 // Okay, now we have a position to branch from and a position to branch to,
632 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000633 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele6962df2008-07-02 01:18:13 +0000634 loopPreheader->getTerminator());
Devang Patel2f170992008-06-02 22:52:56 +0000635 if (DT) {
Devang Patele6962df2008-07-02 01:18:13 +0000636 DT->changeImmediateDominator(NewExit, loopPreheader);
637 DT->changeImmediateDominator(NewPH, loopPreheader);
Devang Patel2f170992008-06-02 22:52:56 +0000638 }
Devang Patel64cd6582008-06-18 02:16:38 +0000639
640 if (DF) {
641 // NewExit is now part of NewPH and Loop Header's dominance
642 // frontier.
643 DominanceFrontier::iterator DFI = DF->find(NewPH);
644 if (DFI != DF->end())
645 DF->addToFrontier(DFI, NewExit);
Devang Patele6962df2008-07-02 01:18:13 +0000646 DFI = DF->find(loopHeader);
Devang Patel64cd6582008-06-18 02:16:38 +0000647 DF->addToFrontier(DFI, NewExit);
648
649 // ExitBlock does not have successors then NewExit is part of
650 // its dominance frontier.
651 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
652 DFI = DF->find(ExitBlock);
653 DF->addToFrontier(DFI, NewExit);
654 }
655 }
Devang Patele6962df2008-07-02 01:18:13 +0000656 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
657 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000658
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000659 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000660 redoLoop = true;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000661
Chris Lattner4c41d492006-02-10 01:24:09 +0000662 // Now that we know that the loop is never entered when this condition is a
663 // particular value, rewrite the loop with this info. We know that this will
664 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000665 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000666 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000667}
668
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000669/// ReplaceLoopExternalDFMember -
670/// If BB's dominance frontier has a member that is not part of loop L then
671/// remove it. Add NewDFMember in BB's dominance frontier.
672void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
673 BasicBlock *NewDFMember) {
674
675 DominanceFrontier::iterator DFI = DF->find(BB);
676 if (DFI == DF->end())
677 return;
678
679 DominanceFrontier::DomSetType &DFSet = DFI->second;
680 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
Devang Patelb5938982007-10-09 21:31:36 +0000681 DE = DFSet.end(); DI != DE;) {
682 BasicBlock *B = *DI++;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000683 if (L->contains(B))
684 continue;
David Greene60f75152007-12-17 17:40:29 +0000685
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000686 DF->removeFromFrontier(DFI, B);
687 LoopDF.insert(B);
688 }
689
690 DF->addToFrontier(DFI, NewDFMember);
691}
692
Chris Lattner48a80b02008-04-21 00:25:49 +0000693/// SplitExitEdges - Split all of the edges from inside the loop to their exit
694/// blocks. Update the appropriate Phi nodes as we do so.
695void LoopUnswitch::SplitExitEdges(Loop *L,
696 const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000697 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000698
Chris Lattner4c41d492006-02-10 01:24:09 +0000699 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000700 BasicBlock *ExitBlock = ExitBlocks[i];
701 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
702
703 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Devang Patel05c1dc62007-07-06 22:03:47 +0000704 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Devang Patel1ff61382007-08-02 15:25:57 +0000705 MiddleBlocks.push_back(MiddleBlock);
Owen Anderson2b67f072006-06-26 07:44:36 +0000706 BasicBlock* StartBlock = Preds[j];
707 BasicBlock* EndBlock;
708 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
709 EndBlock = MiddleBlock;
710 MiddleBlock = EndBlock->getSinglePredecessor();;
711 } else {
712 EndBlock = ExitBlock;
713 }
714
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000715 OrigLoopExitMap[StartBlock] = EndBlock;
716
Owen Anderson2b67f072006-06-26 07:44:36 +0000717 std::set<PHINode*> InsertedPHIs;
718 PHINode* OldLCSSA = 0;
719 for (BasicBlock::iterator I = EndBlock->begin();
720 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
721 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
Gabor Greif051a9502008-04-06 20:25:17 +0000722 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
723 OldLCSSA->getName() + ".us-lcssa",
724 MiddleBlock->getTerminator());
Owen Anderson2b67f072006-06-26 07:44:36 +0000725 NewLCSSA->addIncoming(OldValue, StartBlock);
726 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
727 NewLCSSA);
728 InsertedPHIs.insert(NewLCSSA);
729 }
730
Dan Gohman02dea8b2008-05-23 21:05:58 +0000731 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
Owen Anderson2b67f072006-06-26 07:44:36 +0000732 for (BasicBlock::iterator I = MiddleBlock->begin();
733 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
734 ++I) {
Gabor Greif051a9502008-04-06 20:25:17 +0000735 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
736 OldLCSSA->getName() + ".us-lcssa",
737 InsertPt);
Owen Anderson2b67f072006-06-26 07:44:36 +0000738 OldLCSSA->replaceAllUsesWith(NewLCSSA);
739 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
740 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000741
742 if (DF && DT) {
743 // StartBlock -- > MiddleBlock -- > EndBlock
744 // StartBlock is loop exiting block. EndBlock will become merge point
745 // of two loop exits after loop unswitch.
746
747 // If StartBlock's DF member includes a block that is not loop member
748 // then replace that DF member with EndBlock.
749
750 // If MiddleBlock's DF member includes a block that is not loop member
751 // tnen replace that DF member with EndBlock.
752
753 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
754 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
755 }
Owen Anderson2b67f072006-06-26 07:44:36 +0000756 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000757 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000758
Devang Patelf476e8e2007-10-03 21:16:08 +0000759}
760
Devang Patel501e7632008-07-02 22:58:54 +0000761/// addBBToDomFrontier - Helper function. Insert DFBB in Basic Block BB's
762/// dominance frontier using iterator DFI.
763static void addBBToDomFrontier(DominanceFrontier &DF,
764 DominanceFrontier::iterator &DFI,
765 BasicBlock *BB, BasicBlock *DFBB) {
766 if (DFI != DF.end()) {
767 DF.addToFrontier(DFI, DFBB);
768 return;
769 }
770
771 DominanceFrontier::DomSetType NSet;
772 NSet.insert(DFBB);
773 DF.addBasicBlock(BB, NSet);
774 DFI = DF.find(BB);
775}
776
Devang Patelc1e26602007-10-03 21:17:43 +0000777/// UnswitchNontrivialCondition - We determined that the loop is profitable
778/// to unswitch when LIC equal Val. Split it into loop versions and test the
779/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Patelf476e8e2007-10-03 21:16:08 +0000780void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
781 Loop *L) {
Devang Patele6962df2008-07-02 01:18:13 +0000782 Function *F = loopHeader->getParent();
Devang Patelf476e8e2007-10-03 21:16:08 +0000783 DOUT << "loop-unswitch: Unswitching loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000784 << loopHeader->getName() << " [" << L->getBlocks().size()
Devang Patelf476e8e2007-10-03 21:16:08 +0000785 << " blocks] in Function " << F->getName()
786 << " when '" << *Val << "' == " << *LIC << "\n";
787
Devang Patel1e41f6d2008-07-02 01:44:29 +0000788 LoopBlocks.clear();
789 NewBlocks.clear();
Devang Patelf476e8e2007-10-03 21:16:08 +0000790
791 // First step, split the preheader and exit blocks, and add these blocks to
792 // the LoopBlocks list.
Devang Patele6962df2008-07-02 01:18:13 +0000793 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patelf476e8e2007-10-03 21:16:08 +0000794 LoopBlocks.push_back(NewPreheader);
795
796 // We want the loop to come after the preheader, but before the exit blocks.
797 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
798
799 SmallVector<BasicBlock*, 8> ExitBlocks;
800 L->getUniqueExitBlocks(ExitBlocks);
801
802 // Split all of the edges from inside the loop to their exit blocks. Update
803 // the appropriate Phi nodes as we do so.
804 SmallVector<BasicBlock *,8> MiddleBlocks;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000805 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000806
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000807 // The exit blocks may have been changed due to edge splitting, recompute.
808 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000809 L->getUniqueExitBlocks(ExitBlocks);
810
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000811 // Add exit blocks to the loop blocks.
812 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000813
814 // Next step, clone all of the basic blocks that make up the loop (including
815 // the loop preheader and exit blocks), keeping track of the mapping between
816 // the instructions and blocks.
Chris Lattner18f16092004-04-19 18:07:02 +0000817 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner5e665f52007-02-03 00:08:31 +0000818 DenseMap<const Value*, Value*> ValueMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000819 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner3dd4c402006-02-14 01:01:41 +0000820 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
821 NewBlocks.push_back(New);
822 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Patel15c260a2007-07-31 08:03:26 +0000823 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000824 }
825
Devang Patel1ff61382007-08-02 15:25:57 +0000826 // OutSiders are basic block that are dominated by original header and
827 // at the same time they are not part of loop.
828 SmallPtrSet<BasicBlock *, 8> OutSiders;
829 if (DT) {
Devang Patele6962df2008-07-02 01:18:13 +0000830 DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
Devang Patel1ff61382007-08-02 15:25:57 +0000831 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
832 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
833 BasicBlock *B = (*DI)->getBlock();
834
835 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
836 if (VI == ValueMap.end())
837 OutSiders.insert(B);
Devang Patelcce624a2007-06-28 00:49:00 +0000838 }
Devang Patel1ff61382007-08-02 15:25:57 +0000839 }
840
Chris Lattner18f16092004-04-19 18:07:02 +0000841 // Splice the newly inserted blocks into the function right before the
842 // original preheader.
843 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
844 NewBlocks[0], F->end());
845
846 // Now we create the new Loop object for the versioned loop.
Devang Patel1bc89362007-03-07 00:26:10 +0000847 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnere8255932006-02-10 23:26:14 +0000848 Loop *ParentLoop = L->getParentLoop();
849 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000850 // Make sure to add the cloned preheader and exit blocks to the parent loop
851 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000852 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000853 }
854
855 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
856 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000857 // The new exit block should be in the same loop as the old one.
858 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000859 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000860
861 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
862 "Exit block should have been split to have one successor!");
863 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
864
865 // If the successor of the exit block had PHI nodes, add an entry for
866 // NewExit.
867 PHINode *PN;
868 for (BasicBlock::iterator I = ExitSucc->begin();
869 (PN = dyn_cast<PHINode>(I)); ++I) {
870 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner5e665f52007-02-03 00:08:31 +0000871 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnere8255932006-02-10 23:26:14 +0000872 if (It != ValueMap.end()) V = It->second;
873 PN->addIncoming(V, NewExit);
874 }
Chris Lattner18f16092004-04-19 18:07:02 +0000875 }
876
877 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000878 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
879 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
880 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner18f16092004-04-19 18:07:02 +0000881 RemapInstruction(I, ValueMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000882
Chris Lattner18f16092004-04-19 18:07:02 +0000883 // Rewrite the original preheader to select between versions of the loop.
Devang Patele6962df2008-07-02 01:18:13 +0000884 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000885 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000886 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000887
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000888 // Emit the new branch that selects between the two versions of this loop.
889 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000890 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000891 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000892
893 // Update dominator info
894 if (DF && DT) {
895
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000896 SmallVector<BasicBlock *,4> ExitingBlocks;
897 L->getExitingBlocks(ExitingBlocks);
898
Devang Patel1ff61382007-08-02 15:25:57 +0000899 // Clone dominator info for all cloned basic block.
900 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
901 BasicBlock *LBB = LoopBlocks[i];
902 BasicBlock *NBB = NewBlocks[i];
Devang Patele6962df2008-07-02 01:18:13 +0000903 CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader,
904 loopHeader, DT, DF, ValueMap);
Devang Patel1ff61382007-08-02 15:25:57 +0000905
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000906 // If LBB's dominance frontier includes DFMember
907 // such that DFMember is also a member of LoopDF then
908 // - Remove DFMember from LBB's dominance frontier
Chris Lattner48a80b02008-04-21 00:25:49 +0000909 // - Copy loop exiting blocks', that are dominated by BB,
910 // dominance frontier member in BB's dominance frontier
Devang Patel1ff61382007-08-02 15:25:57 +0000911
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000912 DominanceFrontier::iterator LBBI = DF->find(LBB);
Devang Patel1ff61382007-08-02 15:25:57 +0000913 DominanceFrontier::iterator NBBI = DF->find(NBB);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000914 if (LBBI == DF->end())
915 continue;
916
917 DominanceFrontier::DomSetType &LBSet = LBBI->second;
918 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
919 LE = LBSet.end(); LI != LE; /* NULL */) {
920 BasicBlock *B = *LI++;
Devang Patele6962df2008-07-02 01:18:13 +0000921 if (B == LBB && B == loopHeader)
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000922 continue;
923 bool removeB = false;
924 if (!LoopDF.count(B))
925 continue;
926
927 // If LBB dominates loop exits then insert loop exit block's DF
928 // into B's DF.
Chris Lattner48a80b02008-04-21 00:25:49 +0000929 for(SmallVector<BasicBlock *, 4>::iterator
930 LExitI = ExitingBlocks.begin(),
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000931 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
932 BasicBlock *E = *LExitI;
933
934 if (!DT->dominates(LBB,E))
935 continue;
936
937 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
938 OrigLoopExitMap.find(E);
939 if (DFBI == OrigLoopExitMap.end())
940 continue;
941
942 BasicBlock *DFB = DFBI->second;
943 DF->addToFrontier(LBBI, DFB);
944 DF->addToFrontier(NBBI, DFB);
945 removeB = true;
946 }
947
Chris Lattner48a80b02008-04-21 00:25:49 +0000948 // If B's replacement is inserted in DF then now is the time to remove
949 // B.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000950 if (removeB) {
951 DF->removeFromFrontier(LBBI, B);
952 if (L->contains(B))
953 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
954 else
Devang Patel1ff61382007-08-02 15:25:57 +0000955 DF->removeFromFrontier(NBBI, B);
956 }
957 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000958
Devang Patel1ff61382007-08-02 15:25:57 +0000959 }
960
961 // MiddleBlocks are dominated by original pre header. SplitEdge updated
962 // MiddleBlocks' dominance frontier appropriately.
963 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
964 BasicBlock *MBB = MiddleBlocks[i];
965 if (!MBB->getSinglePredecessor())
Devang Patele6962df2008-07-02 01:18:13 +0000966 DT->changeImmediateDominator(MBB, loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000967 }
968
969 // All Outsiders are now dominated by original pre header.
970 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
971 OE = OutSiders.end(); OI != OE; ++OI) {
972 BasicBlock *OB = *OI;
Devang Patele6962df2008-07-02 01:18:13 +0000973 DT->changeImmediateDominator(OB, loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000974 }
975
976 // New loop headers are dominated by original preheader
Devang Patele6962df2008-07-02 01:18:13 +0000977 DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
978 DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000979 }
980
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000981 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000982 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000983
984 // Now we rewrite the original code to know that the condition is true and the
985 // new code to know that the condition is false.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000986 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
987
988 // It's possible that simplifying one loop could cause the other to be
989 // deleted. If so, don't simplify it.
990 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
991 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000992}
993
Chris Lattner52221f72006-02-17 00:31:07 +0000994/// RemoveFromWorklist - Remove all instances of I from the worklist vector
995/// specified.
996static void RemoveFromWorklist(Instruction *I,
997 std::vector<Instruction*> &Worklist) {
998 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
999 Worklist.end(), I);
1000 while (WI != Worklist.end()) {
1001 unsigned Offset = WI-Worklist.begin();
1002 Worklist.erase(WI);
1003 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
1004 }
1005}
1006
1007/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
1008/// program, replacing all uses with V and update the worklist.
1009static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +00001010 std::vector<Instruction*> &Worklist,
1011 Loop *L, LPPassManager *LPM) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001012 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001013
1014 // Add uses to the worklist, which may be dead now.
1015 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1016 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1017 Worklist.push_back(Use);
1018
1019 // Add users to the worklist which may be simplified now.
1020 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1021 UI != E; ++UI)
1022 Worklist.push_back(cast<Instruction>(*UI));
Devang Patel15c260a2007-07-31 08:03:26 +00001023 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001024 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001025 I->replaceAllUsesWith(V);
1026 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001027 ++NumSimplify;
1028}
1029
Chris Lattnerdb410242006-02-18 02:42:34 +00001030/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1031/// information, and remove any dead successors it has.
1032///
1033void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +00001034 std::vector<Instruction*> &Worklist,
1035 Loop *L) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001036 if (pred_begin(BB) != pred_end(BB)) {
1037 // This block isn't dead, since an edge to BB was just removed, see if there
1038 // are any easy simplifications we can do now.
1039 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1040 // If it has one pred, fold phi nodes in BB.
1041 while (isa<PHINode>(BB->begin()))
1042 ReplaceUsesOfWith(BB->begin(),
1043 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patel15c260a2007-07-31 08:03:26 +00001044 Worklist, L, LPM);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001045
1046 // If this is the header of a loop and the only pred is the latch, we now
1047 // have an unreachable loop.
1048 if (Loop *L = LI->getLoopFor(BB))
Devang Patele6962df2008-07-02 01:18:13 +00001049 if (loopHeader == BB && L->contains(Pred)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001050 // Remove the branch from the latch to the header block, this makes
1051 // the header dead, which will make the latch dead (because the header
1052 // dominates the latch).
Devang Patel15c260a2007-07-31 08:03:26 +00001053 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001054 Pred->getTerminator()->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001055 new UnreachableInst(Pred);
1056
1057 // The loop is now broken, remove it from LI.
1058 RemoveLoopFromHierarchy(L);
1059
1060 // Reprocess the header, which now IS dead.
Devang Patel15c260a2007-07-31 08:03:26 +00001061 RemoveBlockIfDead(BB, Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001062 return;
1063 }
1064
1065 // If pred ends in a uncond branch, add uncond branch to worklist so that
1066 // the two blocks will get merged.
1067 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1068 if (BI->isUnconditional())
1069 Worklist.push_back(BI);
1070 }
1071 return;
1072 }
Chris Lattner52221f72006-02-17 00:31:07 +00001073
Bill Wendlingb7427032006-11-26 09:46:52 +00001074 DOUT << "Nuking dead block: " << *BB;
Chris Lattnerdb410242006-02-18 02:42:34 +00001075
1076 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001077 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +00001078 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001079
1080 // Anything that uses the instructions in this basic block should have their
1081 // uses replaced with undefs.
1082 if (!I->use_empty())
1083 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1084 }
Chris Lattnerdb410242006-02-18 02:42:34 +00001085
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001086 // If this is the edge to the header block for a loop, remove the loop and
1087 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +00001088 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001089 if (BBLoop->getLoopLatch() == BB)
1090 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +00001091 }
1092
1093 // Remove the block from the loop info, which removes it from any loops it
1094 // was in.
1095 LI->removeBlock(BB);
1096
1097
1098 // Remove phi node entries in successors for this block.
1099 TerminatorInst *TI = BB->getTerminator();
1100 std::vector<BasicBlock*> Succs;
1101 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1102 Succs.push_back(TI->getSuccessor(i));
1103 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001104 }
1105
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001106 // Unique the successors, remove anything with multiple uses.
Chris Lattnerdb410242006-02-18 02:42:34 +00001107 std::sort(Succs.begin(), Succs.end());
1108 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1109
1110 // Remove the basic block, including all of the instructions contained in it.
Devang Patel15c260a2007-07-31 08:03:26 +00001111 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001112 BB->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001113 // Remove successor blocks here that are not dead, so that we know we only
1114 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1115 // then getting removed before we revisit them, which is badness.
1116 //
1117 for (unsigned i = 0; i != Succs.size(); ++i)
1118 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1119 // One exception is loop headers. If this block was the preheader for a
1120 // loop, then we DO want to visit the loop so the loop gets deleted.
1121 // We know that if the successor is a loop header, that this loop had to
1122 // be the preheader: the case where this was the latch block was handled
1123 // above and headers can only have two predecessors.
1124 if (!LI->isLoopHeader(Succs[i])) {
1125 Succs.erase(Succs.begin()+i);
1126 --i;
1127 }
1128 }
1129
Chris Lattnerdb410242006-02-18 02:42:34 +00001130 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patel15c260a2007-07-31 08:03:26 +00001131 RemoveBlockIfDead(Succs[i], Worklist, L);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001132}
Chris Lattner52221f72006-02-17 00:31:07 +00001133
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001134/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1135/// become unwrapped, either because the backedge was deleted, or because the
1136/// edge into the header was removed. If the edge into the header from the
1137/// latch block was removed, the loop is unwrapped but subloops are still alive,
1138/// so they just reparent loops. If the loops are actually dead, they will be
1139/// removed later.
1140void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel1bc89362007-03-07 00:26:10 +00001141 LPM->deleteLoopFromQueue(L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001142 RemoveLoopFromWorklist(L);
1143}
1144
1145
1146
Chris Lattnerc2358092006-02-11 00:43:37 +00001147// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1148// the value specified by Val in the specified loop, or we know it does NOT have
1149// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +00001150void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +00001151 Constant *Val,
1152 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +00001153 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +00001154
Chris Lattner18f16092004-04-19 18:07:02 +00001155 // FIXME: Support correlated properties, like:
1156 // for (...)
1157 // if (li1 < li2)
1158 // ...
1159 // if (li1 > li2)
1160 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +00001161
Chris Lattner708e1a52006-02-10 02:30:37 +00001162 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1163 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +00001164 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +00001165 std::vector<Instruction*> Worklist;
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001166
Chris Lattner52221f72006-02-17 00:31:07 +00001167 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1168 // in the loop with the appropriate one directly.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001169 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001170 Value *Replacement;
1171 if (IsEqual)
1172 Replacement = Val;
1173 else
Reid Spencer579dca12007-01-12 04:24:46 +00001174 Replacement = ConstantInt::get(Type::Int1Ty,
1175 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner52221f72006-02-17 00:31:07 +00001176
1177 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1178 if (Instruction *U = cast<Instruction>(Users[i])) {
1179 if (!L->contains(U->getParent()))
1180 continue;
1181 U->replaceUsesOfWith(LIC, Replacement);
1182 Worklist.push_back(U);
1183 }
1184 } else {
1185 // Otherwise, we don't know the precise value of LIC, but we do know that it
1186 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1187 // can. This case occurs when we unswitch switch statements.
1188 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1189 if (Instruction *U = cast<Instruction>(Users[i])) {
1190 if (!L->contains(U->getParent()))
1191 continue;
1192
1193 Worklist.push_back(U);
1194
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001195 // If we know that LIC is not Val, use this info to simplify code.
1196 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1197 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1198 if (SI->getCaseValue(i) == Val) {
1199 // Found a dead case value. Don't remove PHI nodes in the
1200 // successor if they become single-entry, those PHI nodes may
1201 // be in the Users list.
Owen Anderson2b67f072006-06-26 07:44:36 +00001202
1203 // FIXME: This is a hack. We need to keep the successor around
1204 // and hooked up so as to preserve the loop structure, because
1205 // trying to update it is complicated. So instead we preserve the
1206 // loop structure and put the block on an dead code path.
1207
1208 BasicBlock* Old = SI->getParent();
Devang Patel05c1dc62007-07-06 22:03:47 +00001209 BasicBlock* Split = SplitBlock(Old, SI, this);
Owen Anderson2b67f072006-06-26 07:44:36 +00001210
1211 Instruction* OldTerm = Old->getTerminator();
Devang Patel825cb982008-07-03 00:08:13 +00001212 BranchInst::Create(Split, SI->getSuccessor(i),
Gabor Greif051a9502008-04-06 20:25:17 +00001213 ConstantInt::getTrue(), OldTerm);
Devang Patel9ee49c52007-09-20 23:45:50 +00001214
Chris Lattner48a80b02008-04-21 00:25:49 +00001215 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
Owen Anderson2b67f072006-06-26 07:44:36 +00001216 Old->getTerminator()->eraseFromParent();
1217
Owen Andersonbef85082006-06-27 22:26:09 +00001218 PHINode *PN;
Devang Patel825cb982008-07-03 00:08:13 +00001219 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
Owen Andersonbef85082006-06-27 22:26:09 +00001220 (PN = dyn_cast<PHINode>(II)); ++II) {
1221 Value *InVal = PN->removeIncomingValue(Split, false);
1222 PN->addIncoming(InVal, Old);
Owen Anderson2b67f072006-06-26 07:44:36 +00001223 }
1224
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001225 SI->removeCase(i);
1226 break;
Chris Lattnerc2358092006-02-11 00:43:37 +00001227 }
1228 }
Chris Lattnerc2358092006-02-11 00:43:37 +00001229 }
Chris Lattner52221f72006-02-17 00:31:07 +00001230
1231 // TODO: We could do other simplifications, for example, turning
1232 // LIC == Val -> false.
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001233 }
Chris Lattner52221f72006-02-17 00:31:07 +00001234 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001235
Devang Patel15c260a2007-07-31 08:03:26 +00001236 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001237}
1238
1239/// SimplifyCode - Okay, now that we have simplified some instructions in the
1240/// loop, walk over it and constant prop, dce, and fold control flow where
1241/// possible. Note that this is effectively a very simple loop-structure-aware
1242/// optimizer. During processing of this loop, L could very well be deleted, so
1243/// it must not be used.
1244///
1245/// FIXME: When the loop optimizer is more mature, separate this out to a new
1246/// pass.
1247///
Devang Patel15c260a2007-07-31 08:03:26 +00001248void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +00001249 while (!Worklist.empty()) {
1250 Instruction *I = Worklist.back();
1251 Worklist.pop_back();
1252
1253 // Simple constant folding.
1254 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Patel15c260a2007-07-31 08:03:26 +00001255 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001256 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001257 }
Chris Lattner52221f72006-02-17 00:31:07 +00001258
1259 // Simple DCE.
1260 if (isInstructionTriviallyDead(I)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001261 DOUT << "Remove dead instruction '" << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001262
1263 // Add uses to the worklist, which may be dead now.
1264 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1265 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1266 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +00001267 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001268 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001269 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001270 ++NumSimplify;
1271 continue;
1272 }
1273
1274 // Special case hacks that appear commonly in unswitched code.
1275 switch (I->getOpcode()) {
1276 case Instruction::Select:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001277 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Chris Lattner684b22d2007-08-02 16:53:43 +00001278 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1279 LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001280 continue;
1281 }
1282 break;
1283 case Instruction::And:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001284 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001285 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001286 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001287 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001288 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001289 if (CB->isOne()) // X & 1 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001290 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001291 else // X & 0 -> 0
Devang Patel15c260a2007-07-31 08:03:26 +00001292 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001293 continue;
1294 }
Chris Lattner52221f72006-02-17 00:31:07 +00001295 break;
1296 case Instruction::Or:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001297 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001298 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001299 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001300 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001301 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001302 if (CB->isOne()) // X | 1 -> 1
Devang Patel15c260a2007-07-31 08:03:26 +00001303 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001304 else // X | 0 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001305 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001306 continue;
1307 }
Chris Lattner52221f72006-02-17 00:31:07 +00001308 break;
1309 case Instruction::Br: {
1310 BranchInst *BI = cast<BranchInst>(I);
1311 if (BI->isUnconditional()) {
1312 // If BI's parent is the only pred of the successor, fold the two blocks
1313 // together.
1314 BasicBlock *Pred = BI->getParent();
1315 BasicBlock *Succ = BI->getSuccessor(0);
1316 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1317 if (!SinglePred) continue; // Nothing to do.
1318 assert(SinglePred == Pred && "CFG broken");
1319
Bill Wendlingb7427032006-11-26 09:46:52 +00001320 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1321 << Succ->getName() << "\n";
Chris Lattner52221f72006-02-17 00:31:07 +00001322
1323 // Resolve any single entry PHI nodes in Succ.
1324 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001325 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001326
1327 // Move all of the successor contents from Succ to Pred.
1328 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1329 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001330 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001331 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001332 RemoveFromWorklist(BI, Worklist);
1333
1334 // If Succ has any successors with PHI nodes, update them to have
1335 // entries coming from Pred instead of Succ.
1336 Succ->replaceAllUsesWith(Pred);
1337
1338 // Remove Succ from the loop tree.
1339 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001340 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001341 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001342 ++NumSimplify;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001343 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001344 // Conditional branch. Turn it into an unconditional branch, then
1345 // remove dead blocks.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001346 break; // FIXME: Enable.
1347
Bill Wendlingb7427032006-11-26 09:46:52 +00001348 DOUT << "Folded branch: " << *BI;
Reid Spencer579dca12007-01-12 04:24:46 +00001349 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1350 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnerdb410242006-02-18 02:42:34 +00001351 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greif051a9502008-04-06 20:25:17 +00001352 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patel15c260a2007-07-31 08:03:26 +00001353 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001354 BI->eraseFromParent();
Chris Lattnerdb410242006-02-18 02:42:34 +00001355 RemoveFromWorklist(BI, Worklist);
1356 ++NumSimplify;
1357
Devang Patel15c260a2007-07-31 08:03:26 +00001358 RemoveBlockIfDead(DeadSucc, Worklist, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001359 }
1360 break;
1361 }
1362 }
1363 }
Chris Lattner18f16092004-04-19 18:07:02 +00001364}