blob: 02dac92aa1306dc4bd19d0d2fa894fe465c0d64a [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.
Devang Patel4be7d292008-07-03 06:48:21 +0000116 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 do {
Devang Patele6962df2008-07-02 01:18:13 +0000210 assert(currentLoop->isLCSSAForm());
Devang Patel6f62af62007-07-30 23:07:10 +0000211 redoLoop = false;
Devang Patele6962df2008-07-02 01:18:13 +0000212 Changed |= processCurrentLoop();
Devang Patel6f62af62007-07-30 23:07:10 +0000213 } while(redoLoop);
214
215 return Changed;
216}
217
Devang Patele6962df2008-07-02 01:18:13 +0000218/// processCurrentLoop - Do actual work and unswitch loop if possible
219/// and profitable.
220bool LoopUnswitch::processCurrentLoop() {
Devang Patel6f62af62007-07-30 23:07:10 +0000221 bool Changed = false;
222
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000223 // Loop over all of the basic blocks in the loop. If we find an interior
224 // block that is branching on a loop-invariant condition, we can unswitch this
225 // loop.
Devang Patele6962df2008-07-02 01:18:13 +0000226 for (Loop::block_iterator I = currentLoop->block_begin(),
227 E = currentLoop->block_end();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000228 I != E; ++I) {
229 TerminatorInst *TI = (*I)->getTerminator();
230 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
231 // If this isn't branching on an invariant condition, we can't unswitch
232 // it.
233 if (BI->isConditional()) {
234 // See if this, or some part of it, is loop invariant. If so, we can
235 // unswitch on it if we desire.
Devang Patele6962df2008-07-02 01:18:13 +0000236 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
237 currentLoop, Changed);
238 if (LoopCond && UnswitchIfProfitable(LoopCond,
239 ConstantInt::getTrue())) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000240 ++NumBranches;
241 return true;
242 }
243 }
244 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000245 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
246 currentLoop, Changed);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000247 if (LoopCond && SI->getNumCases() > 1) {
248 // Find a value to unswitch on:
249 // FIXME: this should chose the most expensive case!
250 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel52956922007-02-26 19:31:58 +0000251 // Do not process same value again and again.
Devang Patelfb688d42007-02-26 20:22:50 +0000252 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel52956922007-02-26 19:31:58 +0000253 continue;
Devang Patel52956922007-02-26 19:31:58 +0000254
Devang Patele6962df2008-07-02 01:18:13 +0000255 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000256 ++NumSwitches;
257 return true;
258 }
259 }
260 }
261
262 // Scan the instructions to check for unswitchable values.
263 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
264 BBI != E; ++BBI)
265 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000266 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
267 currentLoop, Changed);
268 if (LoopCond && UnswitchIfProfitable(LoopCond,
269 ConstantInt::getTrue())) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000270 ++NumSelects;
271 return true;
272 }
273 }
274 }
Chris Lattner18f16092004-04-19 18:07:02 +0000275 return Changed;
276}
277
Chris Lattner4e132392006-02-15 22:03:36 +0000278/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
279/// 1. Exit the loop with no side effects.
280/// 2. Branch to the latch block with no side-effects.
281///
282/// If these conditions are true, we return true and set ExitBB to the block we
283/// exit through.
284///
285static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
286 BasicBlock *&ExitBB,
287 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000288 if (!Visited.insert(BB).second) {
289 // Already visited and Ok, end of recursion.
290 return true;
291 } else if (!L->contains(BB)) {
292 // Otherwise, this is a loop exit, this is fine so long as this is the
293 // first exit.
294 if (ExitBB != 0) return false;
295 ExitBB = BB;
296 return true;
297 }
298
299 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000300 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000301 // Check to see if the successor is a trivial loop exit.
302 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
303 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000304 }
Chris Lattner4e132392006-02-15 22:03:36 +0000305
306 // Okay, everything after this looks good, check to make sure that this block
307 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000308 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner4e132392006-02-15 22:03:36 +0000309 if (I->mayWriteToMemory())
310 return false;
311
312 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000313}
314
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000315/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
316/// leads to an exit from the specified loop, and has no side-effects in the
317/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000318static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
319 std::set<BasicBlock*> Visited;
320 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattner4e132392006-02-15 22:03:36 +0000321 BasicBlock *ExitBB = 0;
322 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
323 return ExitBB;
324 return 0;
325}
Chris Lattner708e1a52006-02-10 02:30:37 +0000326
Chris Lattner4c41d492006-02-10 01:24:09 +0000327/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
328/// trivial: that is, that the condition controls whether or not the loop does
329/// anything at all. If this is a trivial condition, unswitching produces no
330/// code duplications (equivalently, it produces a simpler loop and a new empty
331/// loop, which gets deleted).
332///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000333/// If this is a trivial condition, return true, otherwise return false. When
334/// returning true, this sets Cond and Val to the condition that controls the
335/// trivial condition: when Cond dynamically equals Val, the loop is known to
336/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
337/// Cond == Val.
338///
Devang Patele6962df2008-07-02 01:18:13 +0000339bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
340 BasicBlock **LoopExit) {
341 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000342 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000343
Chris Lattnera48654e2006-02-15 22:52:05 +0000344 BasicBlock *LoopExitBB = 0;
345 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
346 // If the header block doesn't end with a conditional branch on Cond, we
347 // can't handle it.
348 if (!BI->isConditional() || BI->getCondition() != Cond)
349 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000350
Chris Lattnera48654e2006-02-15 22:52:05 +0000351 // Check to see if a successor of the branch is guaranteed to go to the
352 // latch block or exit through a one exit block without having any
353 // side-effects. If so, determine the value of Cond that causes it to do
354 // this.
Devang Patele6962df2008-07-02 01:18:13 +0000355 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
356 BI->getSuccessor(0)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000357 if (Val) *Val = ConstantInt::getTrue();
Devang Patele6962df2008-07-02 01:18:13 +0000358 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
359 BI->getSuccessor(1)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000360 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnera48654e2006-02-15 22:52:05 +0000361 }
362 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
363 // If this isn't a switch on Cond, we can't handle it.
364 if (SI->getCondition() != Cond) return false;
365
366 // Check to see if a successor of the switch is guaranteed to go to the
367 // latch block or exit through a one exit block without having any
368 // side-effects. If so, determine the value of Cond that causes it to do
369 // this. Note that we can't trivially unswitch on the default case.
370 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
Devang Patele6962df2008-07-02 01:18:13 +0000371 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
372 SI->getSuccessor(i)))) {
Chris Lattnera48654e2006-02-15 22:52:05 +0000373 // Okay, we found a trivial case, remember the value that is trivial.
374 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000375 break;
376 }
Chris Lattner4e132392006-02-15 22:03:36 +0000377 }
378
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000379 // If we didn't find a single unique LoopExit block, or if the loop exit block
380 // contains phi nodes, this isn't trivial.
381 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000382 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000383
Chris Lattnera48654e2006-02-15 22:52:05 +0000384 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000385
386 // We already know that nothing uses any scalar values defined inside of this
387 // loop. As such, we just have to check to see if this loop will execute any
388 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000389 // part of the loop that the code *would* execute. We already checked the
390 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000391 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
392 if (I->mayWriteToMemory())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000393 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000394 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000395}
396
397/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
Devang Patele6962df2008-07-02 01:18:13 +0000398/// we choose to unswitch current loop on the specified value.
Chris Lattner4c41d492006-02-10 01:24:09 +0000399///
Devang Patele6962df2008-07-02 01:18:13 +0000400unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000401 // If the condition is trivial, always unswitch. There is no code growth for
402 // this case.
Devang Patele6962df2008-07-02 01:18:13 +0000403 if (IsTrivialUnswitchCondition(LIC))
Chris Lattner4c41d492006-02-10 01:24:09 +0000404 return 0;
405
Owen Anderson372994b2006-06-28 17:47:50 +0000406 // FIXME: This is really overly conservative. However, more liberal
407 // estimations have thus far resulted in excessive unswitching, which is bad
408 // both in compile time and in code size. This should be replaced once
409 // someone figures out how a good estimation.
Devang Patele6962df2008-07-02 01:18:13 +0000410 return currentLoop->getBlocks().size();
Chris Lattnerdaa2bf92006-06-28 16:38:55 +0000411
Chris Lattner4c41d492006-02-10 01:24:09 +0000412 unsigned Cost = 0;
413 // FIXME: this is brain dead. It should take into consideration code
414 // shrinkage.
Devang Patele6962df2008-07-02 01:18:13 +0000415 for (Loop::block_iterator I = currentLoop->block_begin(),
416 E = currentLoop->block_end();
Chris Lattner4c41d492006-02-10 01:24:09 +0000417 I != E; ++I) {
418 BasicBlock *BB = *I;
419 // Do not include empty blocks in the cost calculation. This happen due to
420 // loop canonicalization and will be removed.
421 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
422 continue;
423
424 // Count basic blocks.
425 ++Cost;
426 }
427
428 return Cost;
429}
430
Devang Patele6962df2008-07-02 01:18:13 +0000431/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerc2358092006-02-11 00:43:37 +0000432/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
433/// unswitch the loop, reprocess the pieces, then return true.
Devang Patele6962df2008-07-02 01:18:13 +0000434bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
435 // Check to see if it would be profitable to unswitch current loop.
436 unsigned Cost = getLoopUnswitchCost(LoopCond);
Devang Patel743f7e82007-06-06 00:21:03 +0000437
438 // Do not do non-trivial unswitch while optimizing for size.
439 if (Cost && OptimizeForSize)
440 return false;
441
Chris Lattner0f862e52006-03-24 07:14:00 +0000442 if (Cost > Threshold) {
Chris Lattnerc2358092006-02-11 00:43:37 +0000443 // FIXME: this should estimate growth by the amount of code shared by the
444 // resultant unswitched loops.
445 //
Bill Wendlingb7427032006-11-26 09:46:52 +0000446 DOUT << "NOT unswitching loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000447 << currentLoop->getHeader()->getName() << ", cost too high: "
448 << currentLoop->getBlocks().size() << "\n";
Chris Lattnerc2358092006-02-11 00:43:37 +0000449 return false;
450 }
Devang Patele6962df2008-07-02 01:18:13 +0000451
452 initLoopData();
453
Chris Lattner6d9d13d2006-02-15 01:44:42 +0000454 Constant *CondVal;
Chris Lattnerc2358092006-02-11 00:43:37 +0000455 BasicBlock *ExitBlock;
Devang Patele6962df2008-07-02 01:18:13 +0000456 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
457 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Chris Lattnerc2358092006-02-11 00:43:37 +0000458 } else {
Devang Patele6962df2008-07-02 01:18:13 +0000459 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
Chris Lattnerc2358092006-02-11 00:43:37 +0000460 }
Devang Patel4be7d292008-07-03 06:48:21 +0000461
462 // FIXME: Reconstruct dom info, because it is not preserved properly.
463 Function *F = loopHeader->getParent();
464 if (DT)
465 DT->runOnFunction(*F);
466 if (DF)
467 DF->runOnFunction(*F);
Chris Lattnerc2358092006-02-11 00:43:37 +0000468 return true;
469}
470
Misha Brukmanfd939082005-04-21 23:48:37 +0000471// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner18f16092004-04-19 18:07:02 +0000472// current values into those specified by ValueMap.
473//
Misha Brukmanfd939082005-04-21 23:48:37 +0000474static inline void RemapInstruction(Instruction *I,
Chris Lattner5e665f52007-02-03 00:08:31 +0000475 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattner18f16092004-04-19 18:07:02 +0000476 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
477 Value *Op = I->getOperand(op);
Chris Lattner5e665f52007-02-03 00:08:31 +0000478 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattner18f16092004-04-19 18:07:02 +0000479 if (It != ValueMap.end()) Op = It->second;
480 I->setOperand(op, Op);
481 }
482}
483
Chris Lattner684b22d2007-08-02 16:53:43 +0000484// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
485// Info.
Devang Patel31ad7532007-07-18 23:48:20 +0000486//
487// If Orig block's immediate dominator is mapped in VM then use corresponding
488// immediate dominator from the map. Otherwise Orig block's dominator is also
489// NewBB's dominator.
490//
Devang Patel24857a32007-07-18 23:50:19 +0000491// OrigPreheader is loop pre-header before this pass started
Devang Patel31ad7532007-07-18 23:48:20 +0000492// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Patel24857a32007-07-18 23:50:19 +0000493// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Dan Gohman844731a2008-05-13 00:00:25 +0000494static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
495 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
496 BasicBlock *OrigHeader,
497 DominatorTree *DT, DominanceFrontier *DF,
498 DenseMap<const Value*, Value*> &VM) {
Devang Patelcce624a2007-06-28 00:49:00 +0000499
Devang Patel31ad7532007-07-18 23:48:20 +0000500 // If NewBB alreay has found its place in domiantor tree then no need to do
501 // anything.
502 if (DT->getNode(NewBB))
503 return;
504
505 // If Orig does not have any immediate domiantor then its clone, NewBB, does
506 // not need any immediate dominator.
Devang Patelcce624a2007-06-28 00:49:00 +0000507 DomTreeNode *OrigNode = DT->getNode(Orig);
508 if (!OrigNode)
509 return;
Devang Patel31ad7532007-07-18 23:48:20 +0000510 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
511 if (!OrigIDomNode)
512 return;
513
514 BasicBlock *OrigIDom = NULL;
515
516 // If Orig is original loop header then its immediate dominator is
517 // NewPreheader.
518 if (Orig == OrigHeader)
519 OrigIDom = NewPreheader;
520
521 // If Orig is new pre-header then its immediate dominator is
522 // original pre-header.
523 else if (Orig == NewPreheader)
524 OrigIDom = OrigPreheader;
525
Devang Patel2095c382008-07-02 01:31:19 +0000526 // Otherwise ask DT to find Orig's immediate dominator.
Devang Patel31ad7532007-07-18 23:48:20 +0000527 else
528 OrigIDom = OrigIDomNode->getBlock();
529
Devang Pateldf5cf202007-07-30 21:10:44 +0000530 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
531 BasicBlock *NewIDom = OrigIDom;
532 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
533 if (I != VM.end()) {
534 NewIDom = cast<BasicBlock>(I->second);
535
536 // If NewIDom does not have corresponding dominatore tree node then
537 // get one.
538 if (!DT->getNode(NewIDom))
Devang Patel31ad7532007-07-18 23:48:20 +0000539 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
540 OrigHeader, DT, DF, VM);
Devang Patelcce624a2007-06-28 00:49:00 +0000541 }
Devang Pateldf5cf202007-07-30 21:10:44 +0000542
543 DT->addNewBlock(NewBB, NewIDom);
544
545 // Copy cloned dominance frontiner set
Devang Patelf34a43a2007-06-29 23:11:49 +0000546 DominanceFrontier::DomSetType NewDFSet;
547 if (DF) {
548 DominanceFrontier::iterator DFI = DF->find(Orig);
549 if ( DFI != DF->end()) {
550 DominanceFrontier::DomSetType S = DFI->second;
551 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
552 I != E; ++I) {
553 BasicBlock *BB = *I;
Chuck Rose III936baaa2007-07-27 18:26:35 +0000554 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
555 if (IDM != VM.end())
556 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Devang Patelf34a43a2007-06-29 23:11:49 +0000557 else
558 NewDFSet.insert(BB);
559 }
560 }
561 DF->addBasicBlock(NewBB, NewDFSet);
562 }
Devang Patelcce624a2007-06-28 00:49:00 +0000563}
564
Chris Lattner18f16092004-04-19 18:07:02 +0000565/// CloneLoop - Recursively clone the specified loop and all of its children,
566/// mapping the blocks with the specified map.
Chris Lattner5e665f52007-02-03 00:08:31 +0000567static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000568 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000569 Loop *New = new Loop();
570
Devang Patel1bc89362007-03-07 00:26:10 +0000571 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000572
573 // Add all of the blocks in L to the new loop.
574 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
575 I != E; ++I)
576 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000577 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000578
579 // Add all of the subloops to the new loop.
580 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000581 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000582
Chris Lattner18f16092004-04-19 18:07:02 +0000583 return New;
584}
585
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000586/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
587/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
588/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000589void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
590 BasicBlock *TrueDest,
591 BasicBlock *FalseDest,
592 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000593 // Insert a conditional branch on LIC to the two preheaders. The original
594 // code is the true version and the new code is the false version.
595 Value *BranchVal = LIC;
Reid Spencerc1030572007-01-19 21:13:56 +0000596 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000597 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000598 else if (Val != ConstantInt::getTrue())
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000599 // We want to enter the new loop when the condition is true.
600 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000601
602 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000603 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000604}
605
606
Chris Lattner4c41d492006-02-10 01:24:09 +0000607/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
608/// condition in it (a cond branch from its header block to its latch block,
609/// where the path through the loop that doesn't execute its body has no
610/// side-effects), unswitch it. This doesn't involve any code duplication, just
611/// moving the conditional branch outside of the loop and updating loop info.
612void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000613 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000614 BasicBlock *ExitBlock) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000615 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000616 << loopHeader->getName() << " [" << L->getBlocks().size()
Bill Wendlingb7427032006-11-26 09:46:52 +0000617 << " blocks] in Function " << L->getHeader()->getParent()->getName()
618 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner4d1ca942006-02-10 01:36:35 +0000619
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000620 // First step, split the preheader, so that we know that there is a safe place
Devang Patele6962df2008-07-02 01:18:13 +0000621 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattner4c41d492006-02-10 01:24:09 +0000622 // conditional branch on Cond.
Devang Patele6962df2008-07-02 01:18:13 +0000623 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000624
625 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000626 // to branch to: this is the exit block out of the loop that we should
627 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000628
Chris Lattner4e132392006-02-15 22:03:36 +0000629 // Split this block now, so that the loop maintains its exit block, and so
630 // that the jump from the preheader can execute the contents of the exit block
631 // without actually branching to it (the exit block should be dominated by the
632 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000633 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000634 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000635
Chris Lattner4c41d492006-02-10 01:24:09 +0000636 // Okay, now we have a position to branch from and a position to branch to,
637 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000638 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele6962df2008-07-02 01:18:13 +0000639 loopPreheader->getTerminator());
Devang Patel2f170992008-06-02 22:52:56 +0000640 if (DT) {
Devang Patele6962df2008-07-02 01:18:13 +0000641 DT->changeImmediateDominator(NewExit, loopPreheader);
642 DT->changeImmediateDominator(NewPH, loopPreheader);
Devang Patel2f170992008-06-02 22:52:56 +0000643 }
Devang Patel64cd6582008-06-18 02:16:38 +0000644
645 if (DF) {
646 // NewExit is now part of NewPH and Loop Header's dominance
647 // frontier.
648 DominanceFrontier::iterator DFI = DF->find(NewPH);
649 if (DFI != DF->end())
650 DF->addToFrontier(DFI, NewExit);
Devang Patele6962df2008-07-02 01:18:13 +0000651 DFI = DF->find(loopHeader);
Devang Patel64cd6582008-06-18 02:16:38 +0000652 DF->addToFrontier(DFI, NewExit);
653
654 // ExitBlock does not have successors then NewExit is part of
655 // its dominance frontier.
656 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
657 DFI = DF->find(ExitBlock);
658 DF->addToFrontier(DFI, NewExit);
659 }
660 }
Devang Patele6962df2008-07-02 01:18:13 +0000661 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
662 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000663
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000664 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000665 redoLoop = true;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000666
Chris Lattner4c41d492006-02-10 01:24:09 +0000667 // Now that we know that the loop is never entered when this condition is a
668 // particular value, rewrite the loop with this info. We know that this will
669 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000670 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000671 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000672}
673
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000674/// ReplaceLoopExternalDFMember -
675/// If BB's dominance frontier has a member that is not part of loop L then
676/// remove it. Add NewDFMember in BB's dominance frontier.
677void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
678 BasicBlock *NewDFMember) {
679
680 DominanceFrontier::iterator DFI = DF->find(BB);
681 if (DFI == DF->end())
682 return;
683
684 DominanceFrontier::DomSetType &DFSet = DFI->second;
685 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
Devang Patelb5938982007-10-09 21:31:36 +0000686 DE = DFSet.end(); DI != DE;) {
687 BasicBlock *B = *DI++;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000688 if (L->contains(B))
689 continue;
David Greene60f75152007-12-17 17:40:29 +0000690
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000691 DF->removeFromFrontier(DFI, B);
692 LoopDF.insert(B);
693 }
694
695 DF->addToFrontier(DFI, NewDFMember);
696}
697
Chris Lattner48a80b02008-04-21 00:25:49 +0000698/// SplitExitEdges - Split all of the edges from inside the loop to their exit
699/// blocks. Update the appropriate Phi nodes as we do so.
700void LoopUnswitch::SplitExitEdges(Loop *L,
701 const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000702 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000703
Chris Lattner4c41d492006-02-10 01:24:09 +0000704 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000705 BasicBlock *ExitBlock = ExitBlocks[i];
706 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
707
708 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Devang Patel05c1dc62007-07-06 22:03:47 +0000709 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Devang Patel1ff61382007-08-02 15:25:57 +0000710 MiddleBlocks.push_back(MiddleBlock);
Owen Anderson2b67f072006-06-26 07:44:36 +0000711 BasicBlock* StartBlock = Preds[j];
712 BasicBlock* EndBlock;
713 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
714 EndBlock = MiddleBlock;
715 MiddleBlock = EndBlock->getSinglePredecessor();;
716 } else {
717 EndBlock = ExitBlock;
718 }
719
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000720 OrigLoopExitMap[StartBlock] = EndBlock;
721
Owen Anderson2b67f072006-06-26 07:44:36 +0000722 std::set<PHINode*> InsertedPHIs;
723 PHINode* OldLCSSA = 0;
724 for (BasicBlock::iterator I = EndBlock->begin();
725 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
726 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
Gabor Greif051a9502008-04-06 20:25:17 +0000727 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
728 OldLCSSA->getName() + ".us-lcssa",
729 MiddleBlock->getTerminator());
Owen Anderson2b67f072006-06-26 07:44:36 +0000730 NewLCSSA->addIncoming(OldValue, StartBlock);
731 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
732 NewLCSSA);
733 InsertedPHIs.insert(NewLCSSA);
734 }
735
Dan Gohman02dea8b2008-05-23 21:05:58 +0000736 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
Owen Anderson2b67f072006-06-26 07:44:36 +0000737 for (BasicBlock::iterator I = MiddleBlock->begin();
738 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
739 ++I) {
Gabor Greif051a9502008-04-06 20:25:17 +0000740 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
741 OldLCSSA->getName() + ".us-lcssa",
742 InsertPt);
Owen Anderson2b67f072006-06-26 07:44:36 +0000743 OldLCSSA->replaceAllUsesWith(NewLCSSA);
744 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
745 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000746
747 if (DF && DT) {
748 // StartBlock -- > MiddleBlock -- > EndBlock
749 // StartBlock is loop exiting block. EndBlock will become merge point
750 // of two loop exits after loop unswitch.
751
752 // If StartBlock's DF member includes a block that is not loop member
753 // then replace that DF member with EndBlock.
754
755 // If MiddleBlock's DF member includes a block that is not loop member
756 // tnen replace that DF member with EndBlock.
757
758 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
759 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
760 }
Owen Anderson2b67f072006-06-26 07:44:36 +0000761 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000762 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000763
Devang Patelf476e8e2007-10-03 21:16:08 +0000764}
765
Devang Patel501e7632008-07-02 22:58:54 +0000766/// addBBToDomFrontier - Helper function. Insert DFBB in Basic Block BB's
767/// dominance frontier using iterator DFI.
768static void addBBToDomFrontier(DominanceFrontier &DF,
769 DominanceFrontier::iterator &DFI,
770 BasicBlock *BB, BasicBlock *DFBB) {
771 if (DFI != DF.end()) {
772 DF.addToFrontier(DFI, DFBB);
773 return;
774 }
775
776 DominanceFrontier::DomSetType NSet;
777 NSet.insert(DFBB);
778 DF.addBasicBlock(BB, NSet);
779 DFI = DF.find(BB);
780}
781
Devang Patelc1e26602007-10-03 21:17:43 +0000782/// UnswitchNontrivialCondition - We determined that the loop is profitable
783/// to unswitch when LIC equal Val. Split it into loop versions and test the
784/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Patelf476e8e2007-10-03 21:16:08 +0000785void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
786 Loop *L) {
Devang Patele6962df2008-07-02 01:18:13 +0000787 Function *F = loopHeader->getParent();
Devang Patelf476e8e2007-10-03 21:16:08 +0000788 DOUT << "loop-unswitch: Unswitching loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000789 << loopHeader->getName() << " [" << L->getBlocks().size()
Devang Patelf476e8e2007-10-03 21:16:08 +0000790 << " blocks] in Function " << F->getName()
791 << " when '" << *Val << "' == " << *LIC << "\n";
792
Devang Patel1e41f6d2008-07-02 01:44:29 +0000793 LoopBlocks.clear();
794 NewBlocks.clear();
Devang Patelf476e8e2007-10-03 21:16:08 +0000795
796 // First step, split the preheader and exit blocks, and add these blocks to
797 // the LoopBlocks list.
Devang Patele6962df2008-07-02 01:18:13 +0000798 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patelf476e8e2007-10-03 21:16:08 +0000799 LoopBlocks.push_back(NewPreheader);
800
801 // We want the loop to come after the preheader, but before the exit blocks.
802 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
803
804 SmallVector<BasicBlock*, 8> ExitBlocks;
805 L->getUniqueExitBlocks(ExitBlocks);
806
807 // Split all of the edges from inside the loop to their exit blocks. Update
808 // the appropriate Phi nodes as we do so.
809 SmallVector<BasicBlock *,8> MiddleBlocks;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000810 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000811
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000812 // The exit blocks may have been changed due to edge splitting, recompute.
813 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000814 L->getUniqueExitBlocks(ExitBlocks);
815
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000816 // Add exit blocks to the loop blocks.
817 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000818
819 // Next step, clone all of the basic blocks that make up the loop (including
820 // the loop preheader and exit blocks), keeping track of the mapping between
821 // the instructions and blocks.
Chris Lattner18f16092004-04-19 18:07:02 +0000822 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner5e665f52007-02-03 00:08:31 +0000823 DenseMap<const Value*, Value*> ValueMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000824 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner3dd4c402006-02-14 01:01:41 +0000825 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
826 NewBlocks.push_back(New);
827 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Patel15c260a2007-07-31 08:03:26 +0000828 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000829 }
830
Devang Patel1ff61382007-08-02 15:25:57 +0000831 // OutSiders are basic block that are dominated by original header and
832 // at the same time they are not part of loop.
833 SmallPtrSet<BasicBlock *, 8> OutSiders;
834 if (DT) {
Devang Patele6962df2008-07-02 01:18:13 +0000835 DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
Devang Patel1ff61382007-08-02 15:25:57 +0000836 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
837 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
838 BasicBlock *B = (*DI)->getBlock();
839
840 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
841 if (VI == ValueMap.end())
842 OutSiders.insert(B);
Devang Patelcce624a2007-06-28 00:49:00 +0000843 }
Devang Patel1ff61382007-08-02 15:25:57 +0000844 }
845
Chris Lattner18f16092004-04-19 18:07:02 +0000846 // Splice the newly inserted blocks into the function right before the
847 // original preheader.
848 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
849 NewBlocks[0], F->end());
850
851 // Now we create the new Loop object for the versioned loop.
Devang Patel1bc89362007-03-07 00:26:10 +0000852 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnere8255932006-02-10 23:26:14 +0000853 Loop *ParentLoop = L->getParentLoop();
854 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000855 // Make sure to add the cloned preheader and exit blocks to the parent loop
856 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000857 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000858 }
859
860 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
861 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000862 // The new exit block should be in the same loop as the old one.
863 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000864 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000865
866 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
867 "Exit block should have been split to have one successor!");
868 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
869
870 // If the successor of the exit block had PHI nodes, add an entry for
871 // NewExit.
872 PHINode *PN;
873 for (BasicBlock::iterator I = ExitSucc->begin();
874 (PN = dyn_cast<PHINode>(I)); ++I) {
875 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner5e665f52007-02-03 00:08:31 +0000876 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnere8255932006-02-10 23:26:14 +0000877 if (It != ValueMap.end()) V = It->second;
878 PN->addIncoming(V, NewExit);
879 }
Chris Lattner18f16092004-04-19 18:07:02 +0000880 }
881
882 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000883 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
884 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
885 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner18f16092004-04-19 18:07:02 +0000886 RemapInstruction(I, ValueMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000887
Chris Lattner18f16092004-04-19 18:07:02 +0000888 // Rewrite the original preheader to select between versions of the loop.
Devang Patele6962df2008-07-02 01:18:13 +0000889 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000890 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000891 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000892
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000893 // Emit the new branch that selects between the two versions of this loop.
894 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000895 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000896 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000897
898 // Update dominator info
899 if (DF && DT) {
900
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000901 SmallVector<BasicBlock *,4> ExitingBlocks;
902 L->getExitingBlocks(ExitingBlocks);
903
Devang Patel1ff61382007-08-02 15:25:57 +0000904 // Clone dominator info for all cloned basic block.
905 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
906 BasicBlock *LBB = LoopBlocks[i];
907 BasicBlock *NBB = NewBlocks[i];
Devang Patele6962df2008-07-02 01:18:13 +0000908 CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader,
909 loopHeader, DT, DF, ValueMap);
Devang Patel1ff61382007-08-02 15:25:57 +0000910
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000911 // If LBB's dominance frontier includes DFMember
912 // such that DFMember is also a member of LoopDF then
913 // - Remove DFMember from LBB's dominance frontier
Chris Lattner48a80b02008-04-21 00:25:49 +0000914 // - Copy loop exiting blocks', that are dominated by BB,
915 // dominance frontier member in BB's dominance frontier
Devang Patel1ff61382007-08-02 15:25:57 +0000916
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000917 DominanceFrontier::iterator LBBI = DF->find(LBB);
Devang Patel1ff61382007-08-02 15:25:57 +0000918 DominanceFrontier::iterator NBBI = DF->find(NBB);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000919 if (LBBI == DF->end())
920 continue;
921
922 DominanceFrontier::DomSetType &LBSet = LBBI->second;
923 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
924 LE = LBSet.end(); LI != LE; /* NULL */) {
925 BasicBlock *B = *LI++;
Devang Patele6962df2008-07-02 01:18:13 +0000926 if (B == LBB && B == loopHeader)
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000927 continue;
928 bool removeB = false;
929 if (!LoopDF.count(B))
930 continue;
931
932 // If LBB dominates loop exits then insert loop exit block's DF
933 // into B's DF.
Chris Lattner48a80b02008-04-21 00:25:49 +0000934 for(SmallVector<BasicBlock *, 4>::iterator
935 LExitI = ExitingBlocks.begin(),
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000936 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
937 BasicBlock *E = *LExitI;
938
939 if (!DT->dominates(LBB,E))
940 continue;
941
942 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
943 OrigLoopExitMap.find(E);
944 if (DFBI == OrigLoopExitMap.end())
945 continue;
946
947 BasicBlock *DFB = DFBI->second;
948 DF->addToFrontier(LBBI, DFB);
949 DF->addToFrontier(NBBI, DFB);
950 removeB = true;
951 }
952
Chris Lattner48a80b02008-04-21 00:25:49 +0000953 // If B's replacement is inserted in DF then now is the time to remove
954 // B.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000955 if (removeB) {
956 DF->removeFromFrontier(LBBI, B);
957 if (L->contains(B))
958 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
959 else
Devang Patel1ff61382007-08-02 15:25:57 +0000960 DF->removeFromFrontier(NBBI, B);
961 }
962 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000963
Devang Patel1ff61382007-08-02 15:25:57 +0000964 }
965
966 // MiddleBlocks are dominated by original pre header. SplitEdge updated
967 // MiddleBlocks' dominance frontier appropriately.
968 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
969 BasicBlock *MBB = MiddleBlocks[i];
970 if (!MBB->getSinglePredecessor())
Devang Patele6962df2008-07-02 01:18:13 +0000971 DT->changeImmediateDominator(MBB, loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000972 }
973
974 // All Outsiders are now dominated by original pre header.
975 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
976 OE = OutSiders.end(); OI != OE; ++OI) {
977 BasicBlock *OB = *OI;
Devang Patele6962df2008-07-02 01:18:13 +0000978 DT->changeImmediateDominator(OB, loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000979 }
980
981 // New loop headers are dominated by original preheader
Devang Patele6962df2008-07-02 01:18:13 +0000982 DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
983 DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000984 }
985
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000986 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000987 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000988
989 // Now we rewrite the original code to know that the condition is true and the
990 // new code to know that the condition is false.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000991 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
992
993 // It's possible that simplifying one loop could cause the other to be
994 // deleted. If so, don't simplify it.
995 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
996 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000997}
998
Chris Lattner52221f72006-02-17 00:31:07 +0000999/// RemoveFromWorklist - Remove all instances of I from the worklist vector
1000/// specified.
1001static void RemoveFromWorklist(Instruction *I,
1002 std::vector<Instruction*> &Worklist) {
1003 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
1004 Worklist.end(), I);
1005 while (WI != Worklist.end()) {
1006 unsigned Offset = WI-Worklist.begin();
1007 Worklist.erase(WI);
1008 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
1009 }
1010}
1011
1012/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
1013/// program, replacing all uses with V and update the worklist.
1014static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +00001015 std::vector<Instruction*> &Worklist,
1016 Loop *L, LPPassManager *LPM) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001017 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001018
1019 // Add uses to the worklist, which may be dead now.
1020 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1021 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1022 Worklist.push_back(Use);
1023
1024 // Add users to the worklist which may be simplified now.
1025 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1026 UI != E; ++UI)
1027 Worklist.push_back(cast<Instruction>(*UI));
Devang Patel15c260a2007-07-31 08:03:26 +00001028 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001029 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001030 I->replaceAllUsesWith(V);
1031 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001032 ++NumSimplify;
1033}
1034
Chris Lattnerdb410242006-02-18 02:42:34 +00001035/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1036/// information, and remove any dead successors it has.
1037///
1038void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +00001039 std::vector<Instruction*> &Worklist,
1040 Loop *L) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001041 if (pred_begin(BB) != pred_end(BB)) {
1042 // This block isn't dead, since an edge to BB was just removed, see if there
1043 // are any easy simplifications we can do now.
1044 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1045 // If it has one pred, fold phi nodes in BB.
1046 while (isa<PHINode>(BB->begin()))
1047 ReplaceUsesOfWith(BB->begin(),
1048 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patel15c260a2007-07-31 08:03:26 +00001049 Worklist, L, LPM);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001050
1051 // If this is the header of a loop and the only pred is the latch, we now
1052 // have an unreachable loop.
1053 if (Loop *L = LI->getLoopFor(BB))
Devang Patele6962df2008-07-02 01:18:13 +00001054 if (loopHeader == BB && L->contains(Pred)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001055 // Remove the branch from the latch to the header block, this makes
1056 // the header dead, which will make the latch dead (because the header
1057 // dominates the latch).
Devang Patel15c260a2007-07-31 08:03:26 +00001058 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001059 Pred->getTerminator()->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001060 new UnreachableInst(Pred);
1061
1062 // The loop is now broken, remove it from LI.
1063 RemoveLoopFromHierarchy(L);
1064
1065 // Reprocess the header, which now IS dead.
Devang Patel15c260a2007-07-31 08:03:26 +00001066 RemoveBlockIfDead(BB, Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001067 return;
1068 }
1069
1070 // If pred ends in a uncond branch, add uncond branch to worklist so that
1071 // the two blocks will get merged.
1072 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1073 if (BI->isUnconditional())
1074 Worklist.push_back(BI);
1075 }
1076 return;
1077 }
Chris Lattner52221f72006-02-17 00:31:07 +00001078
Bill Wendlingb7427032006-11-26 09:46:52 +00001079 DOUT << "Nuking dead block: " << *BB;
Chris Lattnerdb410242006-02-18 02:42:34 +00001080
1081 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001082 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +00001083 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001084
1085 // Anything that uses the instructions in this basic block should have their
1086 // uses replaced with undefs.
1087 if (!I->use_empty())
1088 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1089 }
Chris Lattnerdb410242006-02-18 02:42:34 +00001090
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001091 // If this is the edge to the header block for a loop, remove the loop and
1092 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +00001093 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001094 if (BBLoop->getLoopLatch() == BB)
1095 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +00001096 }
1097
1098 // Remove the block from the loop info, which removes it from any loops it
1099 // was in.
1100 LI->removeBlock(BB);
1101
1102
1103 // Remove phi node entries in successors for this block.
1104 TerminatorInst *TI = BB->getTerminator();
1105 std::vector<BasicBlock*> Succs;
1106 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1107 Succs.push_back(TI->getSuccessor(i));
1108 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001109 }
1110
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001111 // Unique the successors, remove anything with multiple uses.
Chris Lattnerdb410242006-02-18 02:42:34 +00001112 std::sort(Succs.begin(), Succs.end());
1113 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1114
1115 // Remove the basic block, including all of the instructions contained in it.
Devang Patel15c260a2007-07-31 08:03:26 +00001116 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001117 BB->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001118 // Remove successor blocks here that are not dead, so that we know we only
1119 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1120 // then getting removed before we revisit them, which is badness.
1121 //
1122 for (unsigned i = 0; i != Succs.size(); ++i)
1123 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1124 // One exception is loop headers. If this block was the preheader for a
1125 // loop, then we DO want to visit the loop so the loop gets deleted.
1126 // We know that if the successor is a loop header, that this loop had to
1127 // be the preheader: the case where this was the latch block was handled
1128 // above and headers can only have two predecessors.
1129 if (!LI->isLoopHeader(Succs[i])) {
1130 Succs.erase(Succs.begin()+i);
1131 --i;
1132 }
1133 }
1134
Chris Lattnerdb410242006-02-18 02:42:34 +00001135 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patel15c260a2007-07-31 08:03:26 +00001136 RemoveBlockIfDead(Succs[i], Worklist, L);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001137}
Chris Lattner52221f72006-02-17 00:31:07 +00001138
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001139/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1140/// become unwrapped, either because the backedge was deleted, or because the
1141/// edge into the header was removed. If the edge into the header from the
1142/// latch block was removed, the loop is unwrapped but subloops are still alive,
1143/// so they just reparent loops. If the loops are actually dead, they will be
1144/// removed later.
1145void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel1bc89362007-03-07 00:26:10 +00001146 LPM->deleteLoopFromQueue(L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001147 RemoveLoopFromWorklist(L);
1148}
1149
1150
1151
Chris Lattnerc2358092006-02-11 00:43:37 +00001152// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1153// the value specified by Val in the specified loop, or we know it does NOT have
1154// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +00001155void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +00001156 Constant *Val,
1157 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +00001158 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +00001159
Chris Lattner18f16092004-04-19 18:07:02 +00001160 // FIXME: Support correlated properties, like:
1161 // for (...)
1162 // if (li1 < li2)
1163 // ...
1164 // if (li1 > li2)
1165 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +00001166
Chris Lattner708e1a52006-02-10 02:30:37 +00001167 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1168 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +00001169 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +00001170 std::vector<Instruction*> Worklist;
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001171
Chris Lattner52221f72006-02-17 00:31:07 +00001172 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1173 // in the loop with the appropriate one directly.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001174 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001175 Value *Replacement;
1176 if (IsEqual)
1177 Replacement = Val;
1178 else
Reid Spencer579dca12007-01-12 04:24:46 +00001179 Replacement = ConstantInt::get(Type::Int1Ty,
1180 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner52221f72006-02-17 00:31:07 +00001181
1182 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1183 if (Instruction *U = cast<Instruction>(Users[i])) {
1184 if (!L->contains(U->getParent()))
1185 continue;
1186 U->replaceUsesOfWith(LIC, Replacement);
1187 Worklist.push_back(U);
1188 }
1189 } else {
1190 // Otherwise, we don't know the precise value of LIC, but we do know that it
1191 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1192 // can. This case occurs when we unswitch switch statements.
1193 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1194 if (Instruction *U = cast<Instruction>(Users[i])) {
1195 if (!L->contains(U->getParent()))
1196 continue;
1197
1198 Worklist.push_back(U);
1199
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001200 // If we know that LIC is not Val, use this info to simplify code.
1201 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1202 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1203 if (SI->getCaseValue(i) == Val) {
1204 // Found a dead case value. Don't remove PHI nodes in the
1205 // successor if they become single-entry, those PHI nodes may
1206 // be in the Users list.
Owen Anderson2b67f072006-06-26 07:44:36 +00001207
1208 // FIXME: This is a hack. We need to keep the successor around
1209 // and hooked up so as to preserve the loop structure, because
1210 // trying to update it is complicated. So instead we preserve the
1211 // loop structure and put the block on an dead code path.
1212
1213 BasicBlock* Old = SI->getParent();
Devang Patel05c1dc62007-07-06 22:03:47 +00001214 BasicBlock* Split = SplitBlock(Old, SI, this);
Owen Anderson2b67f072006-06-26 07:44:36 +00001215
1216 Instruction* OldTerm = Old->getTerminator();
Devang Patel825cb982008-07-03 00:08:13 +00001217 BranchInst::Create(Split, SI->getSuccessor(i),
Gabor Greif051a9502008-04-06 20:25:17 +00001218 ConstantInt::getTrue(), OldTerm);
Devang Patel9ee49c52007-09-20 23:45:50 +00001219
Chris Lattner48a80b02008-04-21 00:25:49 +00001220 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
Owen Anderson2b67f072006-06-26 07:44:36 +00001221 Old->getTerminator()->eraseFromParent();
1222
Owen Andersonbef85082006-06-27 22:26:09 +00001223 PHINode *PN;
Devang Patel825cb982008-07-03 00:08:13 +00001224 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
Owen Andersonbef85082006-06-27 22:26:09 +00001225 (PN = dyn_cast<PHINode>(II)); ++II) {
1226 Value *InVal = PN->removeIncomingValue(Split, false);
1227 PN->addIncoming(InVal, Old);
Owen Anderson2b67f072006-06-26 07:44:36 +00001228 }
1229
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001230 SI->removeCase(i);
1231 break;
Chris Lattnerc2358092006-02-11 00:43:37 +00001232 }
1233 }
Chris Lattnerc2358092006-02-11 00:43:37 +00001234 }
Chris Lattner52221f72006-02-17 00:31:07 +00001235
1236 // TODO: We could do other simplifications, for example, turning
1237 // LIC == Val -> false.
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001238 }
Chris Lattner52221f72006-02-17 00:31:07 +00001239 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001240
Devang Patel15c260a2007-07-31 08:03:26 +00001241 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001242}
1243
1244/// SimplifyCode - Okay, now that we have simplified some instructions in the
1245/// loop, walk over it and constant prop, dce, and fold control flow where
1246/// possible. Note that this is effectively a very simple loop-structure-aware
1247/// optimizer. During processing of this loop, L could very well be deleted, so
1248/// it must not be used.
1249///
1250/// FIXME: When the loop optimizer is more mature, separate this out to a new
1251/// pass.
1252///
Devang Patel15c260a2007-07-31 08:03:26 +00001253void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +00001254 while (!Worklist.empty()) {
1255 Instruction *I = Worklist.back();
1256 Worklist.pop_back();
1257
1258 // Simple constant folding.
1259 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Patel15c260a2007-07-31 08:03:26 +00001260 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001261 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001262 }
Chris Lattner52221f72006-02-17 00:31:07 +00001263
1264 // Simple DCE.
1265 if (isInstructionTriviallyDead(I)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001266 DOUT << "Remove dead instruction '" << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001267
1268 // Add uses to the worklist, which may be dead now.
1269 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1270 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1271 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +00001272 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001273 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001274 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001275 ++NumSimplify;
1276 continue;
1277 }
1278
1279 // Special case hacks that appear commonly in unswitched code.
1280 switch (I->getOpcode()) {
1281 case Instruction::Select:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001282 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Chris Lattner684b22d2007-08-02 16:53:43 +00001283 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1284 LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001285 continue;
1286 }
1287 break;
1288 case Instruction::And:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001289 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001290 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001291 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001292 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001293 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001294 if (CB->isOne()) // X & 1 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001295 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001296 else // X & 0 -> 0
Devang Patel15c260a2007-07-31 08:03:26 +00001297 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001298 continue;
1299 }
Chris Lattner52221f72006-02-17 00:31:07 +00001300 break;
1301 case Instruction::Or:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001302 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001303 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001304 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001305 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001306 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001307 if (CB->isOne()) // X | 1 -> 1
Devang Patel15c260a2007-07-31 08:03:26 +00001308 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001309 else // X | 0 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001310 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001311 continue;
1312 }
Chris Lattner52221f72006-02-17 00:31:07 +00001313 break;
1314 case Instruction::Br: {
1315 BranchInst *BI = cast<BranchInst>(I);
1316 if (BI->isUnconditional()) {
1317 // If BI's parent is the only pred of the successor, fold the two blocks
1318 // together.
1319 BasicBlock *Pred = BI->getParent();
1320 BasicBlock *Succ = BI->getSuccessor(0);
1321 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1322 if (!SinglePred) continue; // Nothing to do.
1323 assert(SinglePred == Pred && "CFG broken");
1324
Bill Wendlingb7427032006-11-26 09:46:52 +00001325 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1326 << Succ->getName() << "\n";
Chris Lattner52221f72006-02-17 00:31:07 +00001327
1328 // Resolve any single entry PHI nodes in Succ.
1329 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001330 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001331
1332 // Move all of the successor contents from Succ to Pred.
1333 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1334 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001335 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001336 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001337 RemoveFromWorklist(BI, Worklist);
1338
1339 // If Succ has any successors with PHI nodes, update them to have
1340 // entries coming from Pred instead of Succ.
1341 Succ->replaceAllUsesWith(Pred);
1342
1343 // Remove Succ from the loop tree.
1344 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001345 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001346 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001347 ++NumSimplify;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001348 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001349 // Conditional branch. Turn it into an unconditional branch, then
1350 // remove dead blocks.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001351 break; // FIXME: Enable.
1352
Bill Wendlingb7427032006-11-26 09:46:52 +00001353 DOUT << "Folded branch: " << *BI;
Reid Spencer579dca12007-01-12 04:24:46 +00001354 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1355 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnerdb410242006-02-18 02:42:34 +00001356 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greif051a9502008-04-06 20:25:17 +00001357 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patel15c260a2007-07-31 08:03:26 +00001358 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001359 BI->eraseFromParent();
Chris Lattnerdb410242006-02-18 02:42:34 +00001360 RemoveFromWorklist(BI, Worklist);
1361 ++NumSimplify;
1362
Devang Patel15c260a2007-07-31 08:03:26 +00001363 RemoveBlockIfDead(DeadSucc, Worklist, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001364 }
1365 break;
1366 }
1367 }
1368 }
Chris Lattner18f16092004-04-19 18:07:02 +00001369}