blob: c7b00da159cee47443c2b61f6676522deb4e5ba6 [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"
Owen Anderson1ff50b32009-07-03 00:54:20 +000035#include "llvm/LLVMContext.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000036#include "llvm/Analysis/ConstantFolding.h"
Dan Gohman597c5e22009-10-13 20:12:23 +000037#include "llvm/Analysis/InlineCost.h"
Chris Lattner18f16092004-04-19 18:07:02 +000038#include "llvm/Analysis/LoopInfo.h"
Devang Patel1bc89362007-03-07 00:26:10 +000039#include "llvm/Analysis/LoopPass.h"
Devang Patelcce624a2007-06-28 00:49:00 +000040#include "llvm/Analysis/Dominators.h"
Chris Lattner18f16092004-04-19 18:07:02 +000041#include "llvm/Transforms/Utils/Cloning.h"
42#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81be2e92006-02-10 19:08:15 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000044#include "llvm/ADT/Statistic.h"
Devang Patelfb688d42007-02-26 20:22:50 +000045#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnera3522002008-12-01 06:52:57 +000046#include "llvm/ADT/STLExtras.h"
Chris Lattnere487abb2006-02-09 20:15:48 +000047#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000048#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000049#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000050#include <algorithm>
Chris Lattner2f4b8982006-02-09 19:14:52 +000051#include <set>
Chris Lattner18f16092004-04-19 18:07:02 +000052using namespace llvm;
53
Chris Lattner0e5f4992006-12-19 21:40:18 +000054STATISTIC(NumBranches, "Number of branches unswitched");
55STATISTIC(NumSwitches, "Number of switches unswitched");
56STATISTIC(NumSelects , "Number of selects unswitched");
57STATISTIC(NumTrivial , "Number of unswitches that are trivial");
58STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
59
Dan Gohmanb24f6c72009-10-13 17:50:43 +000060// The specific value of 50 here was chosen based only on intuition and a
61// few specific examples.
Dan Gohman844731a2008-05-13 00:00:25 +000062static cl::opt<unsigned>
63Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Dan Gohmanb24f6c72009-10-13 17:50:43 +000064 cl::init(50), cl::Hidden);
Chris Lattnere487abb2006-02-09 20:15:48 +000065
Dan Gohman844731a2008-05-13 00:00:25 +000066namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000067 class LoopUnswitch : public LoopPass {
Chris Lattner18f16092004-04-19 18:07:02 +000068 LoopInfo *LI; // Loop information
Devang Patel1bc89362007-03-07 00:26:10 +000069 LPPassManager *LPM;
Chris Lattnera6fc94b2006-02-18 07:57:38 +000070
Devang Patel1bc89362007-03-07 00:26:10 +000071 // LoopProcessWorklist - Used to check if second loop needs processing
72 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnera6fc94b2006-02-18 07:57:38 +000073 std::vector<Loop*> LoopProcessWorklist;
Devang Patelfb688d42007-02-26 20:22:50 +000074 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel743f7e82007-06-06 00:21:03 +000075
76 bool OptimizeForSize;
Devang Patel6f62af62007-07-30 23:07:10 +000077 bool redoLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000078
Devang Patele6962df2008-07-02 01:18:13 +000079 Loop *currentLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000080 DominanceFrontier *DF;
81 DominatorTree *DT;
Devang Patele6962df2008-07-02 01:18:13 +000082 BasicBlock *loopHeader;
83 BasicBlock *loopPreheader;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000084
Devang Patel1e41f6d2008-07-02 01:44:29 +000085 // LoopBlocks contains all of the basic blocks of the loop, including the
86 // preheader of the loop, the body of the loop, and the exit blocks of the
87 // loop, in that order.
88 std::vector<BasicBlock*> LoopBlocks;
89 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
90 std::vector<BasicBlock*> NewBlocks;
Devang Patel77a01132008-07-03 17:37:52 +000091
Chris Lattner18f16092004-04-19 18:07:02 +000092 public:
Devang Patel19974732007-05-03 01:11:54 +000093 static char ID; // Pass ID, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000094 explicit LoopUnswitch(bool Os = false) :
Dan Gohmanae73dc12008-09-04 17:05:41 +000095 LoopPass(&ID), OptimizeForSize(Os), redoLoop(false),
Devang Patele6962df2008-07-02 01:18:13 +000096 currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
97 loopPreheader(NULL) {}
Devang Patel794fd752007-05-01 21:15:47 +000098
Devang Patel1bc89362007-03-07 00:26:10 +000099 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patele6962df2008-07-02 01:18:13 +0000100 bool processCurrentLoop();
Chris Lattner18f16092004-04-19 18:07:02 +0000101
102 /// This transformation requires natural loop information & requires that
103 /// loop preheaders be inserted into the CFG...
104 ///
105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +0000107 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +0000108 AU.addRequired<LoopInfo>();
109 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +0000110 AU.addRequiredID(LCSSAID);
Devang Patel15c260a2007-07-31 08:03:26 +0000111 AU.addPreservedID(LCSSAID);
Devang Patel4be7d292008-07-03 06:48:21 +0000112 AU.addPreserved<DominatorTree>();
113 AU.addPreserved<DominanceFrontier>();
Chris Lattner18f16092004-04-19 18:07:02 +0000114 }
115
116 private:
Devang Patel15c260a2007-07-31 08:03:26 +0000117
Dan Gohman5c89b522009-09-08 15:45:00 +0000118 virtual void releaseMemory() {
119 UnswitchedVals.clear();
120 }
121
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 Patel77a01132008-07-03 17:37:52 +0000138 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000139
Devang Patele6962df2008-07-02 01:18:13 +0000140 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000141 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000142 BasicBlock *ExitBlock);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000143 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000144
145 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
146 Constant *Val, bool isEqual);
Devang Patelcce624a2007-06-28 00:49:00 +0000147
148 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
149 BasicBlock *TrueDest,
150 BasicBlock *FalseDest,
151 Instruction *InsertPt);
152
Devang Patel15c260a2007-07-31 08:03:26 +0000153 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerdb410242006-02-18 02:42:34 +0000154 void RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000155 std::vector<Instruction*> &Worklist, Loop *l);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000156 void RemoveLoopFromHierarchy(Loop *L);
Devang Patele6962df2008-07-02 01:18:13 +0000157 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
158 BasicBlock **LoopExit = 0);
159
Chris Lattner18f16092004-04-19 18:07:02 +0000160 };
Chris Lattner18f16092004-04-19 18:07:02 +0000161}
Dan Gohman844731a2008-05-13 00:00:25 +0000162char LoopUnswitch::ID = 0;
163static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattner18f16092004-04-19 18:07:02 +0000164
Daniel Dunbar394f0442008-10-22 23:32:42 +0000165Pass *llvm::createLoopUnswitchPass(bool Os) {
Devang Patel743f7e82007-06-06 00:21:03 +0000166 return new LoopUnswitch(Os);
167}
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000168
169/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
170/// invariant in the loop, or has an invariant piece, return the invariant.
171/// Otherwise, return null.
172static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
173 // Constants should be folded, not unswitched on!
Dan Gohmana1fcd772008-10-17 00:56:52 +0000174 if (isa<Constant>(Cond)) return 0;
Devang Patel558f1b82007-06-28 00:44:10 +0000175
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000176 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patel265ca5d2008-11-03 19:38:07 +0000177
Dan Gohman0df6e092009-07-14 01:37:59 +0000178 // Hoist simple values out.
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000179 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman0df6e092009-07-14 01:37:59 +0000180 return Cond;
Dan Gohman0df6e092009-07-14 01:37:59 +0000181
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
183 if (BO->getOpcode() == Instruction::And ||
184 BO->getOpcode() == Instruction::Or) {
185 // If either the left or right side is invariant, we can unswitch on this,
186 // which will cause the branch to go away in one loop and the condition to
187 // simplify in the other one.
188 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
189 return LHS;
190 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
191 return RHS;
192 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000193
194 return 0;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000195}
196
Devang Patel1bc89362007-03-07 00:26:10 +0000197bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Devang Patel1bc89362007-03-07 00:26:10 +0000198 LI = &getAnalysis<LoopInfo>();
199 LPM = &LPM_Ref;
Duncan Sands1465d612009-01-28 13:14:17 +0000200 DF = getAnalysisIfAvailable<DominanceFrontier>();
201 DT = getAnalysisIfAvailable<DominatorTree>();
Devang Patele6962df2008-07-02 01:18:13 +0000202 currentLoop = L;
Devang Pateldeafefa2008-09-04 22:43:59 +0000203 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000204 bool Changed = false;
Devang Patel6f62af62007-07-30 23:07:10 +0000205 do {
Devang Patele6962df2008-07-02 01:18:13 +0000206 assert(currentLoop->isLCSSAForm());
Devang Patel6f62af62007-07-30 23:07:10 +0000207 redoLoop = false;
Devang Patele6962df2008-07-02 01:18:13 +0000208 Changed |= processCurrentLoop();
Devang Patel6f62af62007-07-30 23:07:10 +0000209 } while(redoLoop);
210
Devang Pateldeafefa2008-09-04 22:43:59 +0000211 if (Changed) {
212 // FIXME: Reconstruct dom info, because it is not preserved properly.
213 if (DT)
214 DT->runOnFunction(*F);
215 if (DF)
216 DF->runOnFunction(*F);
217 }
Devang Patel6f62af62007-07-30 23:07:10 +0000218 return Changed;
219}
220
Devang Patele6962df2008-07-02 01:18:13 +0000221/// processCurrentLoop - Do actual work and unswitch loop if possible
222/// and profitable.
223bool LoopUnswitch::processCurrentLoop() {
Devang Patel6f62af62007-07-30 23:07:10 +0000224 bool Changed = false;
Owen Andersone922c022009-07-22 00:24:57 +0000225 LLVMContext &Context = currentLoop->getHeader()->getContext();
Devang Patel6f62af62007-07-30 23:07:10 +0000226
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000227 // Loop over all of the basic blocks in the loop. If we find an interior
228 // block that is branching on a loop-invariant condition, we can unswitch this
229 // loop.
Devang Patele6962df2008-07-02 01:18:13 +0000230 for (Loop::block_iterator I = currentLoop->block_begin(),
231 E = currentLoop->block_end();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000232 I != E; ++I) {
233 TerminatorInst *TI = (*I)->getTerminator();
234 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
235 // If this isn't branching on an invariant condition, we can't unswitch
236 // it.
237 if (BI->isConditional()) {
238 // See if this, or some part of it, is loop invariant. If so, we can
239 // unswitch on it if we desire.
Devang Patele6962df2008-07-02 01:18:13 +0000240 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
241 currentLoop, Changed);
242 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson5defacc2009-07-31 17:39:07 +0000243 ConstantInt::getTrue(Context))) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000244 ++NumBranches;
245 return true;
246 }
247 }
248 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000249 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
250 currentLoop, Changed);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000251 if (LoopCond && SI->getNumCases() > 1) {
252 // Find a value to unswitch on:
253 // FIXME: this should chose the most expensive case!
254 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel52956922007-02-26 19:31:58 +0000255 // Do not process same value again and again.
Devang Patelfb688d42007-02-26 20:22:50 +0000256 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel52956922007-02-26 19:31:58 +0000257 continue;
Devang Patel52956922007-02-26 19:31:58 +0000258
Devang Patele6962df2008-07-02 01:18:13 +0000259 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000260 ++NumSwitches;
261 return true;
262 }
263 }
264 }
265
266 // Scan the instructions to check for unswitchable values.
267 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
268 BBI != E; ++BBI)
269 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000270 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
271 currentLoop, Changed);
272 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson5defacc2009-07-31 17:39:07 +0000273 ConstantInt::getTrue(Context))) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000274 ++NumSelects;
275 return true;
276 }
277 }
278 }
Chris Lattner18f16092004-04-19 18:07:02 +0000279 return Changed;
280}
281
Chris Lattner4e132392006-02-15 22:03:36 +0000282/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
283/// 1. Exit the loop with no side effects.
284/// 2. Branch to the latch block with no side-effects.
285///
286/// If these conditions are true, we return true and set ExitBB to the block we
287/// exit through.
288///
289static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
290 BasicBlock *&ExitBB,
291 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000292 if (!Visited.insert(BB).second) {
293 // Already visited and Ok, end of recursion.
294 return true;
295 } else if (!L->contains(BB)) {
296 // Otherwise, this is a loop exit, this is fine so long as this is the
297 // first exit.
298 if (ExitBB != 0) return false;
299 ExitBB = BB;
300 return true;
301 }
302
303 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000304 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000305 // Check to see if the successor is a trivial loop exit.
306 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
307 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000308 }
Chris Lattner4e132392006-02-15 22:03:36 +0000309
310 // Okay, everything after this looks good, check to make sure that this block
311 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000312 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands7af1c782009-05-06 06:49:50 +0000313 if (I->mayHaveSideEffects())
Chris Lattner4e132392006-02-15 22:03:36 +0000314 return false;
315
316 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000317}
318
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000319/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
320/// leads to an exit from the specified loop, and has no side-effects in the
321/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000322static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
323 std::set<BasicBlock*> Visited;
324 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattner4e132392006-02-15 22:03:36 +0000325 BasicBlock *ExitBB = 0;
326 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
327 return ExitBB;
328 return 0;
329}
Chris Lattner708e1a52006-02-10 02:30:37 +0000330
Chris Lattner4c41d492006-02-10 01:24:09 +0000331/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
332/// trivial: that is, that the condition controls whether or not the loop does
333/// anything at all. If this is a trivial condition, unswitching produces no
334/// code duplications (equivalently, it produces a simpler loop and a new empty
335/// loop, which gets deleted).
336///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000337/// If this is a trivial condition, return true, otherwise return false. When
338/// returning true, this sets Cond and Val to the condition that controls the
339/// trivial condition: when Cond dynamically equals Val, the loop is known to
340/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
341/// Cond == Val.
342///
Devang Patele6962df2008-07-02 01:18:13 +0000343bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
344 BasicBlock **LoopExit) {
345 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000346 TerminatorInst *HeaderTerm = Header->getTerminator();
Owen Andersone922c022009-07-22 00:24:57 +0000347 LLVMContext &Context = Header->getContext();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000348
Chris Lattnera48654e2006-02-15 22:52:05 +0000349 BasicBlock *LoopExitBB = 0;
350 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
351 // If the header block doesn't end with a conditional branch on Cond, we
352 // can't handle it.
353 if (!BI->isConditional() || BI->getCondition() != Cond)
354 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000355
Chris Lattnera48654e2006-02-15 22:52:05 +0000356 // Check to see if a successor of the branch is guaranteed to go to the
357 // latch block or exit through a one exit block without having any
358 // side-effects. If so, determine the value of Cond that causes it to do
359 // this.
Devang Patele6962df2008-07-02 01:18:13 +0000360 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
361 BI->getSuccessor(0)))) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000362 if (Val) *Val = ConstantInt::getTrue(Context);
Devang Patele6962df2008-07-02 01:18:13 +0000363 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
364 BI->getSuccessor(1)))) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000365 if (Val) *Val = ConstantInt::getFalse(Context);
Chris Lattnera48654e2006-02-15 22:52:05 +0000366 }
367 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
368 // If this isn't a switch on Cond, we can't handle it.
369 if (SI->getCondition() != Cond) return false;
370
371 // Check to see if a successor of the switch is guaranteed to go to the
372 // latch block or exit through a one exit block without having any
373 // side-effects. If so, determine the value of Cond that causes it to do
374 // this. Note that we can't trivially unswitch on the default case.
375 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
Devang Patele6962df2008-07-02 01:18:13 +0000376 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
377 SI->getSuccessor(i)))) {
Chris Lattnera48654e2006-02-15 22:52:05 +0000378 // Okay, we found a trivial case, remember the value that is trivial.
379 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000380 break;
381 }
Chris Lattner4e132392006-02-15 22:03:36 +0000382 }
383
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000384 // If we didn't find a single unique LoopExit block, or if the loop exit block
385 // contains phi nodes, this isn't trivial.
386 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000387 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000388
Chris Lattnera48654e2006-02-15 22:52:05 +0000389 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000390
391 // We already know that nothing uses any scalar values defined inside of this
392 // loop. As such, we just have to check to see if this loop will execute any
393 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000394 // part of the loop that the code *would* execute. We already checked the
395 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000396 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
Duncan Sands7af1c782009-05-06 06:49:50 +0000397 if (I->mayHaveSideEffects())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000398 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000399 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000400}
401
Devang Patele6962df2008-07-02 01:18:13 +0000402/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerc2358092006-02-11 00:43:37 +0000403/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
404/// unswitch the loop, reprocess the pieces, then return true.
Devang Patele6962df2008-07-02 01:18:13 +0000405bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
Devang Patel10b359c2008-09-04 18:55:13 +0000406
Devang Patel027bb922008-09-04 20:36:36 +0000407 initLoopData();
Devang Patel10b359c2008-09-04 18:55:13 +0000408 Function *F = loopHeader->getParent();
409
Dan Gohmancd53f642009-10-20 20:06:09 +0000410 // If the condition is trivial, always unswitch. There is no code growth for
411 // this case.
412 if (!IsTrivialUnswitchCondition(LoopCond)) {
413 // Check to see if it would be profitable to unswitch current loop.
Devang Patel10b359c2008-09-04 18:55:13 +0000414
Dan Gohmancd53f642009-10-20 20:06:09 +0000415 // Do not do non-trivial unswitch while optimizing for size.
416 if (OptimizeForSize || F->hasFnAttr(Attribute::OptimizeForSize))
417 return false;
Devang Patel743f7e82007-06-06 00:21:03 +0000418
Dan Gohmancd53f642009-10-20 20:06:09 +0000419 // FIXME: This is overly conservative because it does not take into
420 // consideration code simplification opportunities and code that can
421 // be shared by the resultant unswitched loops.
422 CodeMetrics Metrics;
423 for (Loop::block_iterator I = currentLoop->block_begin(),
424 E = currentLoop->block_end();
425 I != E; ++I)
426 Metrics.analyzeBasicBlock(*I);
Devang Patel743f7e82007-06-06 00:21:03 +0000427
Dan Gohmancd53f642009-10-20 20:06:09 +0000428 // Limit the number of instructions to avoid causing significant code
429 // expansion, and the number of basic blocks, to avoid loops with
430 // large numbers of branches which cause loop unswitching to go crazy.
431 // This is a very ad-hoc heuristic.
432 if (Metrics.NumInsts > Threshold ||
Chris Lattnerda9c2812009-11-01 03:42:55 +0000433 Metrics.NumBlocks * 5 > Threshold ||
434 Metrics.NeverInline) {
Dan Gohmancd53f642009-10-20 20:06:09 +0000435 DEBUG(errs() << "NOT unswitching loop %"
436 << currentLoop->getHeader()->getName() << ", cost too high: "
437 << currentLoop->getBlocks().size() << "\n");
438 return false;
439 }
Chris Lattnerc2358092006-02-11 00:43:37 +0000440 }
Devang Patele6962df2008-07-02 01:18:13 +0000441
Chris Lattner6d9d13d2006-02-15 01:44:42 +0000442 Constant *CondVal;
Chris Lattnerc2358092006-02-11 00:43:37 +0000443 BasicBlock *ExitBlock;
Devang Patele6962df2008-07-02 01:18:13 +0000444 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
445 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Chris Lattnerc2358092006-02-11 00:43:37 +0000446 } else {
Devang Patele6962df2008-07-02 01:18:13 +0000447 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
Chris Lattnerc2358092006-02-11 00:43:37 +0000448 }
Devang Patel4be7d292008-07-03 06:48:21 +0000449
Chris Lattnerc2358092006-02-11 00:43:37 +0000450 return true;
451}
452
Misha Brukmanfd939082005-04-21 23:48:37 +0000453// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner18f16092004-04-19 18:07:02 +0000454// current values into those specified by ValueMap.
455//
Misha Brukmanfd939082005-04-21 23:48:37 +0000456static inline void RemapInstruction(Instruction *I,
Chris Lattner5e665f52007-02-03 00:08:31 +0000457 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattner18f16092004-04-19 18:07:02 +0000458 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
459 Value *Op = I->getOperand(op);
Chris Lattner5e665f52007-02-03 00:08:31 +0000460 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattner18f16092004-04-19 18:07:02 +0000461 if (It != ValueMap.end()) Op = It->second;
462 I->setOperand(op, Op);
463 }
464}
465
466/// CloneLoop - Recursively clone the specified loop and all of its children,
467/// mapping the blocks with the specified map.
Chris Lattner5e665f52007-02-03 00:08:31 +0000468static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000469 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000470 Loop *New = new Loop();
471
Devang Patel1bc89362007-03-07 00:26:10 +0000472 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000473
474 // Add all of the blocks in L to the new loop.
475 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
476 I != E; ++I)
477 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000478 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000479
480 // Add all of the subloops to the new loop.
481 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000482 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000483
Chris Lattner18f16092004-04-19 18:07:02 +0000484 return New;
485}
486
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000487/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
488/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
489/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000490void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
491 BasicBlock *TrueDest,
492 BasicBlock *FalseDest,
493 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000494 // Insert a conditional branch on LIC to the two preheaders. The original
495 // code is the true version and the new code is the false version.
496 Value *BranchVal = LIC;
Owen Anderson1d0be152009-08-13 21:58:54 +0000497 if (!isa<ConstantInt>(Val) ||
498 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Owen Anderson333c4002009-07-09 23:48:35 +0000499 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val, "tmp");
Owen Anderson5defacc2009-07-31 17:39:07 +0000500 else if (Val != ConstantInt::getTrue(Val->getContext()))
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000501 // We want to enter the new loop when the condition is true.
502 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000503
504 // Insert the new branch.
Dan Gohman5c89b522009-09-08 15:45:00 +0000505 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
506
507 // If either edge is critical, split it. This helps preserve LoopSimplify
508 // form for enclosing loops.
509 SplitCriticalEdge(BI, 0, this);
510 SplitCriticalEdge(BI, 1, this);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000511}
512
Chris Lattner4c41d492006-02-10 01:24:09 +0000513/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
514/// condition in it (a cond branch from its header block to its latch block,
515/// where the path through the loop that doesn't execute its body has no
516/// side-effects), unswitch it. This doesn't involve any code duplication, just
517/// moving the conditional branch outside of the loop and updating loop info.
518void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000519 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000520 BasicBlock *ExitBlock) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000521 DEBUG(errs() << "loop-unswitch: Trivial-Unswitch loop %"
522 << loopHeader->getName() << " [" << L->getBlocks().size()
523 << " blocks] in Function " << L->getHeader()->getParent()->getName()
524 << " on cond: " << *Val << " == " << *Cond << "\n");
Chris Lattner4d1ca942006-02-10 01:36:35 +0000525
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000526 // First step, split the preheader, so that we know that there is a safe place
Devang Patele6962df2008-07-02 01:18:13 +0000527 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattner4c41d492006-02-10 01:24:09 +0000528 // conditional branch on Cond.
Devang Patele6962df2008-07-02 01:18:13 +0000529 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000530
531 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000532 // to branch to: this is the exit block out of the loop that we should
533 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000534
Chris Lattner4e132392006-02-15 22:03:36 +0000535 // Split this block now, so that the loop maintains its exit block, and so
536 // that the jump from the preheader can execute the contents of the exit block
537 // without actually branching to it (the exit block should be dominated by the
538 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000539 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000540 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000541
Chris Lattner4c41d492006-02-10 01:24:09 +0000542 // Okay, now we have a position to branch from and a position to branch to,
543 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000544 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele6962df2008-07-02 01:18:13 +0000545 loopPreheader->getTerminator());
Devang Patele6962df2008-07-02 01:18:13 +0000546 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
547 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000548
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000549 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000550 redoLoop = true;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000551
Chris Lattner4c41d492006-02-10 01:24:09 +0000552 // Now that we know that the loop is never entered when this condition is a
553 // particular value, rewrite the loop with this info. We know that this will
554 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000555 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000556 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000557}
558
Chris Lattner48a80b02008-04-21 00:25:49 +0000559/// SplitExitEdges - Split all of the edges from inside the loop to their exit
560/// blocks. Update the appropriate Phi nodes as we do so.
561void LoopUnswitch::SplitExitEdges(Loop *L,
Devang Patel77a01132008-07-03 17:37:52 +0000562 const SmallVector<BasicBlock *, 8> &ExitBlocks)
563{
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000564
Chris Lattner4c41d492006-02-10 01:24:09 +0000565 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000566 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman5c89b522009-09-08 15:45:00 +0000567 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
568 pred_end(ExitBlock));
569 SplitBlockPredecessors(ExitBlock, Preds.data(), Preds.size(),
570 ".us-lcssa", this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000571 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000572}
573
Devang Patelc1e26602007-10-03 21:17:43 +0000574/// UnswitchNontrivialCondition - We determined that the loop is profitable
575/// to unswitch when LIC equal Val. Split it into loop versions and test the
576/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Patelf476e8e2007-10-03 21:16:08 +0000577void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
578 Loop *L) {
Devang Patele6962df2008-07-02 01:18:13 +0000579 Function *F = loopHeader->getParent();
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000580 DEBUG(errs() << "loop-unswitch: Unswitching loop %"
581 << loopHeader->getName() << " [" << L->getBlocks().size()
582 << " blocks] in Function " << F->getName()
583 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patelf476e8e2007-10-03 21:16:08 +0000584
Devang Patel1e41f6d2008-07-02 01:44:29 +0000585 LoopBlocks.clear();
586 NewBlocks.clear();
Devang Patelf476e8e2007-10-03 21:16:08 +0000587
588 // First step, split the preheader and exit blocks, and add these blocks to
589 // the LoopBlocks list.
Devang Patele6962df2008-07-02 01:18:13 +0000590 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patelf476e8e2007-10-03 21:16:08 +0000591 LoopBlocks.push_back(NewPreheader);
592
593 // We want the loop to come after the preheader, but before the exit blocks.
594 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
595
596 SmallVector<BasicBlock*, 8> ExitBlocks;
597 L->getUniqueExitBlocks(ExitBlocks);
598
599 // Split all of the edges from inside the loop to their exit blocks. Update
600 // the appropriate Phi nodes as we do so.
Devang Patel77a01132008-07-03 17:37:52 +0000601 SplitExitEdges(L, ExitBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000602
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000603 // The exit blocks may have been changed due to edge splitting, recompute.
604 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000605 L->getUniqueExitBlocks(ExitBlocks);
606
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000607 // Add exit blocks to the loop blocks.
608 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000609
610 // Next step, clone all of the basic blocks that make up the loop (including
611 // the loop preheader and exit blocks), keeping track of the mapping between
612 // the instructions and blocks.
Chris Lattner18f16092004-04-19 18:07:02 +0000613 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner5e665f52007-02-03 00:08:31 +0000614 DenseMap<const Value*, Value*> ValueMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000615 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner3dd4c402006-02-14 01:01:41 +0000616 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
617 NewBlocks.push_back(New);
618 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Patel15c260a2007-07-31 08:03:26 +0000619 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000620 }
621
622 // Splice the newly inserted blocks into the function right before the
623 // original preheader.
624 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
625 NewBlocks[0], F->end());
626
627 // Now we create the new Loop object for the versioned loop.
Devang Patel1bc89362007-03-07 00:26:10 +0000628 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnere8255932006-02-10 23:26:14 +0000629 Loop *ParentLoop = L->getParentLoop();
630 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000631 // Make sure to add the cloned preheader and exit blocks to the parent loop
632 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000633 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000634 }
635
636 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
637 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000638 // The new exit block should be in the same loop as the old one.
639 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000640 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000641
642 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
643 "Exit block should have been split to have one successor!");
644 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Patel77a01132008-07-03 17:37:52 +0000645
Chris Lattnere8255932006-02-10 23:26:14 +0000646 // If the successor of the exit block had PHI nodes, add an entry for
647 // NewExit.
648 PHINode *PN;
649 for (BasicBlock::iterator I = ExitSucc->begin();
650 (PN = dyn_cast<PHINode>(I)); ++I) {
651 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner5e665f52007-02-03 00:08:31 +0000652 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnere8255932006-02-10 23:26:14 +0000653 if (It != ValueMap.end()) V = It->second;
654 PN->addIncoming(V, NewExit);
655 }
Chris Lattner18f16092004-04-19 18:07:02 +0000656 }
657
658 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000659 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
660 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
661 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner18f16092004-04-19 18:07:02 +0000662 RemapInstruction(I, ValueMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000663
Chris Lattner18f16092004-04-19 18:07:02 +0000664 // Rewrite the original preheader to select between versions of the loop.
Devang Patele6962df2008-07-02 01:18:13 +0000665 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000666 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000667 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000668
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000669 // Emit the new branch that selects between the two versions of this loop.
670 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000671 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000672 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000673
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000674 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000675 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000676
677 // Now we rewrite the original code to know that the condition is true and the
678 // new code to know that the condition is false.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000679 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
680
681 // It's possible that simplifying one loop could cause the other to be
682 // deleted. If so, don't simplify it.
683 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
684 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Devang Patel77a01132008-07-03 17:37:52 +0000685
Chris Lattner18f16092004-04-19 18:07:02 +0000686}
687
Chris Lattner52221f72006-02-17 00:31:07 +0000688/// RemoveFromWorklist - Remove all instances of I from the worklist vector
689/// specified.
690static void RemoveFromWorklist(Instruction *I,
691 std::vector<Instruction*> &Worklist) {
692 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
693 Worklist.end(), I);
694 while (WI != Worklist.end()) {
695 unsigned Offset = WI-Worklist.begin();
696 Worklist.erase(WI);
697 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
698 }
699}
700
701/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
702/// program, replacing all uses with V and update the worklist.
703static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +0000704 std::vector<Instruction*> &Worklist,
705 Loop *L, LPPassManager *LPM) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000706 DEBUG(errs() << "Replace with '" << *V << "': " << *I);
Chris Lattner52221f72006-02-17 00:31:07 +0000707
708 // Add uses to the worklist, which may be dead now.
709 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
710 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
711 Worklist.push_back(Use);
712
713 // Add users to the worklist which may be simplified now.
714 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
715 UI != E; ++UI)
716 Worklist.push_back(cast<Instruction>(*UI));
Devang Patel15c260a2007-07-31 08:03:26 +0000717 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +0000718 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +0000719 I->replaceAllUsesWith(V);
720 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +0000721 ++NumSimplify;
722}
723
Chris Lattnerdb410242006-02-18 02:42:34 +0000724/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
725/// information, and remove any dead successors it has.
726///
727void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000728 std::vector<Instruction*> &Worklist,
729 Loop *L) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000730 if (pred_begin(BB) != pred_end(BB)) {
731 // This block isn't dead, since an edge to BB was just removed, see if there
732 // are any easy simplifications we can do now.
733 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
734 // If it has one pred, fold phi nodes in BB.
735 while (isa<PHINode>(BB->begin()))
736 ReplaceUsesOfWith(BB->begin(),
737 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patel15c260a2007-07-31 08:03:26 +0000738 Worklist, L, LPM);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000739
740 // If this is the header of a loop and the only pred is the latch, we now
741 // have an unreachable loop.
742 if (Loop *L = LI->getLoopFor(BB))
Devang Patele6962df2008-07-02 01:18:13 +0000743 if (loopHeader == BB && L->contains(Pred)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000744 // Remove the branch from the latch to the header block, this makes
745 // the header dead, which will make the latch dead (because the header
746 // dominates the latch).
Devang Patel15c260a2007-07-31 08:03:26 +0000747 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000748 Pred->getTerminator()->eraseFromParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000749 new UnreachableInst(BB->getContext(), Pred);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000750
751 // The loop is now broken, remove it from LI.
752 RemoveLoopFromHierarchy(L);
753
754 // Reprocess the header, which now IS dead.
Devang Patel15c260a2007-07-31 08:03:26 +0000755 RemoveBlockIfDead(BB, Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000756 return;
757 }
758
759 // If pred ends in a uncond branch, add uncond branch to worklist so that
760 // the two blocks will get merged.
761 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
762 if (BI->isUnconditional())
763 Worklist.push_back(BI);
764 }
765 return;
766 }
Chris Lattner52221f72006-02-17 00:31:07 +0000767
Chris Lattnerbdff5482009-08-23 04:37:46 +0000768 DEBUG(errs() << "Nuking dead block: " << *BB);
Chris Lattnerdb410242006-02-18 02:42:34 +0000769
770 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000771 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +0000772 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000773
774 // Anything that uses the instructions in this basic block should have their
775 // uses replaced with undefs.
Devang Patel228ebd02009-10-13 22:56:32 +0000776 // If I is not void type then replaceAllUsesWith undef.
777 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +0000778 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +0000779 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000780 }
Chris Lattnerdb410242006-02-18 02:42:34 +0000781
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000782 // If this is the edge to the header block for a loop, remove the loop and
783 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +0000784 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000785 if (BBLoop->getLoopLatch() == BB)
786 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +0000787 }
788
789 // Remove the block from the loop info, which removes it from any loops it
790 // was in.
791 LI->removeBlock(BB);
792
793
794 // Remove phi node entries in successors for this block.
795 TerminatorInst *TI = BB->getTerminator();
Chris Lattnera3522002008-12-01 06:52:57 +0000796 SmallVector<BasicBlock*, 4> Succs;
Chris Lattnerdb410242006-02-18 02:42:34 +0000797 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
798 Succs.push_back(TI->getSuccessor(i));
799 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000800 }
801
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000802 // Unique the successors, remove anything with multiple uses.
Chris Lattnera3522002008-12-01 06:52:57 +0000803 array_pod_sort(Succs.begin(), Succs.end());
Chris Lattnerdb410242006-02-18 02:42:34 +0000804 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
805
806 // Remove the basic block, including all of the instructions contained in it.
Devang Patel15c260a2007-07-31 08:03:26 +0000807 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000808 BB->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000809 // Remove successor blocks here that are not dead, so that we know we only
810 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
811 // then getting removed before we revisit them, which is badness.
812 //
813 for (unsigned i = 0; i != Succs.size(); ++i)
814 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
815 // One exception is loop headers. If this block was the preheader for a
816 // loop, then we DO want to visit the loop so the loop gets deleted.
817 // We know that if the successor is a loop header, that this loop had to
818 // be the preheader: the case where this was the latch block was handled
819 // above and headers can only have two predecessors.
820 if (!LI->isLoopHeader(Succs[i])) {
821 Succs.erase(Succs.begin()+i);
822 --i;
823 }
824 }
825
Chris Lattnerdb410242006-02-18 02:42:34 +0000826 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patel15c260a2007-07-31 08:03:26 +0000827 RemoveBlockIfDead(Succs[i], Worklist, L);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000828}
Chris Lattner52221f72006-02-17 00:31:07 +0000829
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000830/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
831/// become unwrapped, either because the backedge was deleted, or because the
832/// edge into the header was removed. If the edge into the header from the
833/// latch block was removed, the loop is unwrapped but subloops are still alive,
834/// so they just reparent loops. If the loops are actually dead, they will be
835/// removed later.
836void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel1bc89362007-03-07 00:26:10 +0000837 LPM->deleteLoopFromQueue(L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000838 RemoveLoopFromWorklist(L);
839}
840
Chris Lattnerc2358092006-02-11 00:43:37 +0000841// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
842// the value specified by Val in the specified loop, or we know it does NOT have
843// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +0000844void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +0000845 Constant *Val,
846 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000847 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +0000848
Chris Lattner18f16092004-04-19 18:07:02 +0000849 // FIXME: Support correlated properties, like:
850 // for (...)
851 // if (li1 < li2)
852 // ...
853 // if (li1 > li2)
854 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +0000855
Chris Lattner708e1a52006-02-10 02:30:37 +0000856 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
857 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +0000858 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +0000859 std::vector<Instruction*> Worklist;
Owen Andersone922c022009-07-22 00:24:57 +0000860 LLVMContext &Context = Val->getContext();
861
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000862
Chris Lattner52221f72006-02-17 00:31:07 +0000863 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
864 // in the loop with the appropriate one directly.
Owen Anderson1d0be152009-08-13 21:58:54 +0000865 if (IsEqual || (isa<ConstantInt>(Val) &&
866 Val->getType() == Type::getInt1Ty(Val->getContext()))) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000867 Value *Replacement;
868 if (IsEqual)
869 Replacement = Val;
870 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000871 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencer579dca12007-01-12 04:24:46 +0000872 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner52221f72006-02-17 00:31:07 +0000873
874 for (unsigned i = 0, e = Users.size(); i != e; ++i)
875 if (Instruction *U = cast<Instruction>(Users[i])) {
876 if (!L->contains(U->getParent()))
877 continue;
878 U->replaceUsesOfWith(LIC, Replacement);
879 Worklist.push_back(U);
880 }
881 } else {
882 // Otherwise, we don't know the precise value of LIC, but we do know that it
883 // is certainly NOT "Val". As such, simplify any uses in the loop that we
884 // can. This case occurs when we unswitch switch statements.
885 for (unsigned i = 0, e = Users.size(); i != e; ++i)
886 if (Instruction *U = cast<Instruction>(Users[i])) {
887 if (!L->contains(U->getParent()))
888 continue;
889
890 Worklist.push_back(U);
891
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000892 // If we know that LIC is not Val, use this info to simplify code.
893 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
894 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
895 if (SI->getCaseValue(i) == Val) {
896 // Found a dead case value. Don't remove PHI nodes in the
897 // successor if they become single-entry, those PHI nodes may
898 // be in the Users list.
Owen Anderson2b67f072006-06-26 07:44:36 +0000899
900 // FIXME: This is a hack. We need to keep the successor around
901 // and hooked up so as to preserve the loop structure, because
902 // trying to update it is complicated. So instead we preserve the
Dan Gohman5c89b522009-09-08 15:45:00 +0000903 // loop structure and put the block on a dead code path.
904 BasicBlock *Switch = SI->getParent();
905 SplitEdge(Switch, SI->getSuccessor(i), this);
906 // Compute the successors instead of relying on the return value
907 // of SplitEdge, since it may have split the switch successor
908 // after PHI nodes.
909 BasicBlock *NewSISucc = SI->getSuccessor(i);
910 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
911 // Create an "unreachable" destination.
912 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
913 Switch->getParent(),
914 OldSISucc);
915 new UnreachableInst(Context, Abort);
916 // Force the new case destination to branch to the "unreachable"
917 // block while maintaining a (dead) CFG edge to the old block.
918 NewSISucc->getTerminator()->eraseFromParent();
919 BranchInst::Create(Abort, OldSISucc,
920 ConstantInt::getTrue(Context), NewSISucc);
921 // Release the PHI operands for this edge.
922 for (BasicBlock::iterator II = NewSISucc->begin();
923 PHINode *PN = dyn_cast<PHINode>(II); ++II)
924 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
925 UndefValue::get(PN->getType()));
Mike Stumpc02f0d72009-09-09 17:57:16 +0000926 // Tell the domtree about the new block. We don't fully update the
927 // domtree here -- instead we force it to do a full recomputation
928 // after the pass is complete -- but we do need to inform it of
929 // new blocks.
Dan Gohman5c89b522009-09-08 15:45:00 +0000930 if (DT)
931 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000932 break;
Chris Lattnerc2358092006-02-11 00:43:37 +0000933 }
934 }
Chris Lattnerc2358092006-02-11 00:43:37 +0000935 }
Chris Lattner52221f72006-02-17 00:31:07 +0000936
937 // TODO: We could do other simplifications, for example, turning
938 // LIC == Val -> false.
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000939 }
Chris Lattner52221f72006-02-17 00:31:07 +0000940 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000941
Devang Patel15c260a2007-07-31 08:03:26 +0000942 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000943}
944
Mike Stumpc02f0d72009-09-09 17:57:16 +0000945/// SimplifyCode - Okay, now that we have simplified some instructions in the
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000946/// loop, walk over it and constant prop, dce, and fold control flow where
947/// possible. Note that this is effectively a very simple loop-structure-aware
948/// optimizer. During processing of this loop, L could very well be deleted, so
949/// it must not be used.
950///
951/// FIXME: When the loop optimizer is more mature, separate this out to a new
952/// pass.
953///
Devang Patel15c260a2007-07-31 08:03:26 +0000954void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +0000955 while (!Worklist.empty()) {
956 Instruction *I = Worklist.back();
957 Worklist.pop_back();
958
959 // Simple constant folding.
Owen Andersone922c022009-07-22 00:24:57 +0000960 if (Constant *C = ConstantFoldInstruction(I, I->getContext())) {
Devang Patel15c260a2007-07-31 08:03:26 +0000961 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +0000962 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000963 }
Chris Lattner52221f72006-02-17 00:31:07 +0000964
965 // Simple DCE.
966 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000967 DEBUG(errs() << "Remove dead instruction '" << *I);
Chris Lattner52221f72006-02-17 00:31:07 +0000968
969 // Add uses to the worklist, which may be dead now.
970 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
971 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
972 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +0000973 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +0000974 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +0000975 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +0000976 ++NumSimplify;
977 continue;
978 }
979
980 // Special case hacks that appear commonly in unswitched code.
981 switch (I->getOpcode()) {
982 case Instruction::Select:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000983 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Chris Lattner684b22d2007-08-02 16:53:43 +0000984 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
985 LPM);
Chris Lattner52221f72006-02-17 00:31:07 +0000986 continue;
987 }
988 break;
989 case Instruction::And:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000990 if (isa<ConstantInt>(I->getOperand(0)) &&
Owen Anderson1d0be152009-08-13 21:58:54 +0000991 // constant -> RHS
992 I->getOperand(0)->getType() == Type::getInt1Ty(I->getContext()))
Chris Lattner52221f72006-02-17 00:31:07 +0000993 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000994 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +0000995 if (CB->getType() == Type::getInt1Ty(I->getContext())) {
Reid Spencera5dae0c2007-03-02 23:35:28 +0000996 if (CB->isOne()) // X & 1 -> X
Devang Patel15c260a2007-07-31 08:03:26 +0000997 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000998 else // X & 0 -> 0
Devang Patel15c260a2007-07-31 08:03:26 +0000999 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001000 continue;
1001 }
Chris Lattner52221f72006-02-17 00:31:07 +00001002 break;
1003 case Instruction::Or:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001004 if (isa<ConstantInt>(I->getOperand(0)) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001005 // constant -> RHS
1006 I->getOperand(0)->getType() == Type::getInt1Ty(I->getContext()))
Chris Lattner52221f72006-02-17 00:31:07 +00001007 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001008 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00001009 if (CB->getType() == Type::getInt1Ty(I->getContext())) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001010 if (CB->isOne()) // X | 1 -> 1
Devang Patel15c260a2007-07-31 08:03:26 +00001011 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001012 else // X | 0 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001013 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001014 continue;
1015 }
Chris Lattner52221f72006-02-17 00:31:07 +00001016 break;
1017 case Instruction::Br: {
1018 BranchInst *BI = cast<BranchInst>(I);
1019 if (BI->isUnconditional()) {
1020 // If BI's parent is the only pred of the successor, fold the two blocks
1021 // together.
1022 BasicBlock *Pred = BI->getParent();
1023 BasicBlock *Succ = BI->getSuccessor(0);
1024 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1025 if (!SinglePred) continue; // Nothing to do.
1026 assert(SinglePred == Pred && "CFG broken");
1027
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001028 DEBUG(errs() << "Merging blocks: " << Pred->getName() << " <- "
1029 << Succ->getName() << "\n");
Chris Lattner52221f72006-02-17 00:31:07 +00001030
1031 // Resolve any single entry PHI nodes in Succ.
1032 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001033 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001034
1035 // Move all of the successor contents from Succ to Pred.
1036 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1037 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001038 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001039 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001040 RemoveFromWorklist(BI, Worklist);
1041
1042 // If Succ has any successors with PHI nodes, update them to have
1043 // entries coming from Pred instead of Succ.
1044 Succ->replaceAllUsesWith(Pred);
1045
1046 // Remove Succ from the loop tree.
1047 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001048 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001049 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001050 ++NumSimplify;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001051 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001052 // Conditional branch. Turn it into an unconditional branch, then
1053 // remove dead blocks.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001054 break; // FIXME: Enable.
1055
Chris Lattnerbdff5482009-08-23 04:37:46 +00001056 DEBUG(errs() << "Folded branch: " << *BI);
Reid Spencer579dca12007-01-12 04:24:46 +00001057 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1058 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnerdb410242006-02-18 02:42:34 +00001059 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greif051a9502008-04-06 20:25:17 +00001060 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patel15c260a2007-07-31 08:03:26 +00001061 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001062 BI->eraseFromParent();
Chris Lattnerdb410242006-02-18 02:42:34 +00001063 RemoveFromWorklist(BI, Worklist);
1064 ++NumSimplify;
1065
Devang Patel15c260a2007-07-31 08:03:26 +00001066 RemoveBlockIfDead(DeadSucc, Worklist, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001067 }
1068 break;
1069 }
1070 }
1071 }
Chris Lattner18f16092004-04-19 18:07:02 +00001072}