blob: ff0ec6d2ac61dce37b1de16b38755dd4de14cccf [file] [log] [blame]
Devang Patelfee76bd2007-08-07 00:25:56 +00001//===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2//
3// 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.
Devang Patelfee76bd2007-08-07 00:25:56 +00007//
8//===----------------------------------------------------------------------===//
9//
Devang Patel38310052008-12-04 21:38:42 +000010// This file implements Loop Index Splitting Pass. This pass handles three
11// kinds of loops.
Devang Patelfee76bd2007-08-07 00:25:56 +000012//
Dan Gohmanf159ccd2009-04-29 22:01:05 +000013// [1] A loop may be eliminated if the body is executed exactly once.
14// For example,
15//
Devang Patel38310052008-12-04 21:38:42 +000016// for (i = 0; i < N; ++i) {
Dan Gohmanf159ccd2009-04-29 22:01:05 +000017// if (i == X) {
18// body;
19// }
20// }
21//
22// is transformed to
23//
24// i = X;
25// body;
26//
27// [2] A loop's iteration space may be shrunk if the loop body is executed
28// for a proper sub-range of the loop's iteration space. For example,
29//
30// for (i = 0; i < N; ++i) {
31// if (i > A && i < B) {
Devang Patel38310052008-12-04 21:38:42 +000032// ...
33// }
34// }
35//
Dan Gohmanf159ccd2009-04-29 22:01:05 +000036// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +000037//
Dan Gohmanf159ccd2009-04-29 22:01:05 +000038// [3] A loop may be split if the loop body is dominated by a branch.
39// For example,
Devang Patel38310052008-12-04 21:38:42 +000040//
41// for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
42//
43// is transformed into
Dan Gohmanf159ccd2009-04-29 22:01:05 +000044//
Devang Patel38310052008-12-04 21:38:42 +000045// AEV = BSV = SV
46// for (i = LB; i < min(UB, AEV); ++i)
47// A;
48// for (i = max(LB, BSV); i < UB; ++i);
49// B;
Dan Gohmanf159ccd2009-04-29 22:01:05 +000050//
Devang Patelfee76bd2007-08-07 00:25:56 +000051//===----------------------------------------------------------------------===//
52
53#define DEBUG_TYPE "loop-index-split"
54
Devang Patelfee76bd2007-08-07 00:25:56 +000055#include "llvm/Transforms/Scalar.h"
Devang Pateld96c60d2009-02-06 06:19:06 +000056#include "llvm/IntrinsicInst.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000057#include "llvm/Analysis/LoopPass.h"
Dan Gohman97b6e2c2009-02-17 20:50:11 +000058#include "llvm/Analysis/ScalarEvolution.h"
Devang Patel787a7132007-08-08 21:39:47 +000059#include "llvm/Analysis/Dominators.h"
Devang Patel423c8b22007-08-10 18:07:13 +000060#include "llvm/Transforms/Utils/BasicBlockUtils.h"
61#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelb23c2322009-03-30 22:24:10 +000062#include "llvm/Transforms/Utils/Local.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000063#include "llvm/Support/Compiler.h"
Devang Patel5b8ec612007-08-15 03:31:47 +000064#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000065#include "llvm/ADT/Statistic.h"
66
67using namespace llvm;
68
Devang Patel38310052008-12-04 21:38:42 +000069STATISTIC(NumIndexSplit, "Number of loop index split");
70STATISTIC(NumIndexSplitRemoved, "Number of loops eliminated by loop index split");
71STATISTIC(NumRestrictBounds, "Number of loop iteration space restricted");
Devang Patelfee76bd2007-08-07 00:25:56 +000072
73namespace {
74
75 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
76
77 public:
78 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000079 LoopIndexSplit() : LoopPass(&ID) {}
Devang Patelfee76bd2007-08-07 00:25:56 +000080
81 // Index split Loop L. Return true if loop is split.
82 bool runOnLoop(Loop *L, LPPassManager &LPM);
83
84 void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelfee76bd2007-08-07 00:25:56 +000085 AU.addPreserved<ScalarEvolution>();
86 AU.addRequiredID(LCSSAID);
87 AU.addPreservedID(LCSSAID);
Devang Patel423c8b22007-08-10 18:07:13 +000088 AU.addRequired<LoopInfo>();
Devang Patelfee76bd2007-08-07 00:25:56 +000089 AU.addPreserved<LoopInfo>();
90 AU.addRequiredID(LoopSimplifyID);
91 AU.addPreservedID(LoopSimplifyID);
Devang Patel9704fcf2007-08-08 22:25:28 +000092 AU.addRequired<DominatorTree>();
Devang Patel5b8ec612007-08-15 03:31:47 +000093 AU.addRequired<DominanceFrontier>();
Devang Patel787a7132007-08-08 21:39:47 +000094 AU.addPreserved<DominatorTree>();
95 AU.addPreserved<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +000096 }
97
98 private:
Devang Patel38310052008-12-04 21:38:42 +000099 /// processOneIterationLoop -- Eliminate loop if loop body is executed
100 /// only once. For example,
101 /// for (i = 0; i < N; ++i) {
102 /// if ( i == X) {
103 /// ...
104 /// }
105 /// }
106 ///
107 bool processOneIterationLoop();
Devang Patel71554b82007-08-08 21:02:17 +0000108
Devang Patel38310052008-12-04 21:38:42 +0000109 // -- Routines used by updateLoopIterationSpace();
Devang Patelc9d123d2007-08-09 01:39:01 +0000110
Devang Patel38310052008-12-04 21:38:42 +0000111 /// updateLoopIterationSpace -- Update loop's iteration space if loop
112 /// body is executed for certain IV range only. For example,
113 ///
114 /// for (i = 0; i < N; ++i) {
115 /// if ( i > A && i < B) {
116 /// ...
117 /// }
118 /// }
Devang Patel042b8772008-12-08 17:07:24 +0000119 /// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000120 ///
121 bool updateLoopIterationSpace();
Devang Patel71554b82007-08-08 21:02:17 +0000122
Devang Patel38310052008-12-04 21:38:42 +0000123 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
124 /// with a loop invariant value. Update loop's lower and upper bound based on
125 /// the loop invariant value.
126 bool restrictLoopBound(ICmpInst &Op);
Devang Patel4a69da92007-08-25 00:56:38 +0000127
Devang Patel38310052008-12-04 21:38:42 +0000128 // --- Routines used by splitLoop(). --- /
Devang Patel4a69da92007-08-25 00:56:38 +0000129
Devang Patel38310052008-12-04 21:38:42 +0000130 bool splitLoop();
Devang Patel4a69da92007-08-25 00:56:38 +0000131
Devang Patel38310052008-12-04 21:38:42 +0000132 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by
133 /// DeadBB. This routine is used to remove split condition's dead branch,
134 /// dominated by DeadBB. LiveBB dominates split conidition's other branch.
Devang Patela6a86632007-08-14 18:35:57 +0000135 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel38310052008-12-04 21:38:42 +0000136
137 /// moveExitCondition - Move exit condition EC into split condition block.
138 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
139 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
140 PHINode *IV, Instruction *IVAdd, Loop *LP,
141 unsigned);
142
Devang Pateld79faee2007-08-25 02:39:24 +0000143 /// updatePHINodes - CFG has been changed.
144 /// Before
145 /// - ExitBB's single predecessor was Latch
146 /// - Latch's second successor was Header
147 /// Now
148 /// - ExitBB's single predecessor was Header
149 /// - Latch's one and only successor was Header
150 ///
151 /// Update ExitBB PHINodes' to reflect this change.
152 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
153 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000154 PHINode *IV, Instruction *IVIncrement, Loop *LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000155
Devang Patel38310052008-12-04 21:38:42 +0000156 // --- Utility routines --- /
Devang Pateld79faee2007-08-25 02:39:24 +0000157
Devang Patel38310052008-12-04 21:38:42 +0000158 /// cleanBlock - A block is considered clean if all non terminal
159 /// instructions are either PHINodes or IV based values.
160 bool cleanBlock(BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000161
Devang Patel042b8772008-12-08 17:07:24 +0000162 /// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000163 /// IV based value is less than the loop invariant then return the loop
164 /// invariant. Otherwise return NULL.
165 Value * IVisLT(ICmpInst &Op);
166
Devang Patel042b8772008-12-08 17:07:24 +0000167 /// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000168 /// IV based value is less than or equal to the loop invariant then
169 /// return the loop invariant. Otherwise return NULL.
170 Value * IVisLE(ICmpInst &Op);
171
Devang Patel042b8772008-12-08 17:07:24 +0000172 /// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000173 /// IV based value is greater than the loop invariant then return the loop
174 /// invariant. Otherwise return NULL.
175 Value * IVisGT(ICmpInst &Op);
176
Devang Patel042b8772008-12-08 17:07:24 +0000177 /// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000178 /// IV based value is greater than or equal to the loop invariant then
179 /// return the loop invariant. Otherwise return NULL.
180 Value * IVisGE(ICmpInst &Op);
Devang Patelbacf5192007-08-10 00:33:50 +0000181
Devang Patelfee76bd2007-08-07 00:25:56 +0000182 private:
183
Devang Patel38310052008-12-04 21:38:42 +0000184 // Current Loop information.
Devang Patelfee76bd2007-08-07 00:25:56 +0000185 Loop *L;
Devang Patel423c8b22007-08-10 18:07:13 +0000186 LPPassManager *LPM;
187 LoopInfo *LI;
Devang Patel9704fcf2007-08-08 22:25:28 +0000188 DominatorTree *DT;
Devang Patelfc4c5f82007-08-13 22:13:24 +0000189 DominanceFrontier *DF;
Devang Patelbacf5192007-08-10 00:33:50 +0000190
Devang Patelbacf5192007-08-10 00:33:50 +0000191 PHINode *IndVar;
Devang Patelbacf5192007-08-10 00:33:50 +0000192 ICmpInst *ExitCondition;
Devang Patel38310052008-12-04 21:38:42 +0000193 ICmpInst *SplitCondition;
194 Value *IVStartValue;
195 Value *IVExitValue;
196 Instruction *IVIncrement;
197 SmallPtrSet<Value *, 4> IVBasedValues;
Devang Patelfee76bd2007-08-07 00:25:56 +0000198 };
Devang Patelfee76bd2007-08-07 00:25:56 +0000199}
200
Dan Gohman844731a2008-05-13 00:00:25 +0000201char LoopIndexSplit::ID = 0;
202static RegisterPass<LoopIndexSplit>
203X("loop-index-split", "Index Split Loops");
204
Daniel Dunbar394f0442008-10-22 23:32:42 +0000205Pass *llvm::createLoopIndexSplitPass() {
Devang Patelfee76bd2007-08-07 00:25:56 +0000206 return new LoopIndexSplit();
207}
208
209// Index split Loop L. Return true if loop is split.
Devang Patel423c8b22007-08-10 18:07:13 +0000210bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000211 L = IncomingLoop;
Devang Patel423c8b22007-08-10 18:07:13 +0000212 LPM = &LPM_Ref;
Devang Patel71554b82007-08-08 21:02:17 +0000213
Devang Patel3fe4f212007-08-15 02:14:55 +0000214 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel4e8061c2007-08-14 23:53:57 +0000215 if (!L->getSubLoops().empty())
216 return false;
217
Devang Patel9704fcf2007-08-08 22:25:28 +0000218 DT = &getAnalysis<DominatorTree>();
Devang Patel423c8b22007-08-10 18:07:13 +0000219 LI = &getAnalysis<LoopInfo>();
Devang Patel7375bb92007-08-15 03:34:53 +0000220 DF = &getAnalysis<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +0000221
Devang Patel38310052008-12-04 21:38:42 +0000222 // Initialize loop data.
223 IndVar = L->getCanonicalInductionVariable();
224 if (!IndVar) return false;
Devang Patelbacf5192007-08-10 00:33:50 +0000225
Devang Patel38310052008-12-04 21:38:42 +0000226 bool P1InLoop = L->contains(IndVar->getIncomingBlock(1));
227 IVStartValue = IndVar->getIncomingValue(!P1InLoop);
228 IVIncrement = dyn_cast<Instruction>(IndVar->getIncomingValue(P1InLoop));
229 if (!IVIncrement) return false;
Devang Patel71554b82007-08-08 21:02:17 +0000230
Devang Patel38310052008-12-04 21:38:42 +0000231 IVBasedValues.clear();
232 IVBasedValues.insert(IndVar);
233 IVBasedValues.insert(IVIncrement);
Devang Patelbacf5192007-08-10 00:33:50 +0000234 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Devang Patel38310052008-12-04 21:38:42 +0000235 I != E; ++I)
236 for(BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
237 BI != BE; ++BI) {
238 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BI))
239 if (BO != IVIncrement
240 && (BO->getOpcode() == Instruction::Add
241 || BO->getOpcode() == Instruction::Sub))
242 if (IVBasedValues.count(BO->getOperand(0))
243 && L->isLoopInvariant(BO->getOperand(1)))
244 IVBasedValues.insert(BO);
245 }
Devang Patelbacf5192007-08-10 00:33:50 +0000246
Devang Patel38310052008-12-04 21:38:42 +0000247 // Reject loop if loop exit condition is not suitable.
Dan Gohmanc8332462009-02-12 18:08:24 +0000248 BasicBlock *ExitingBlock = L->getExitingBlock();
249 if (!ExitingBlock)
Devang Patel38310052008-12-04 21:38:42 +0000250 return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000251 BranchInst *EBR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel38310052008-12-04 21:38:42 +0000252 if (!EBR) return false;
253 ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
254 if (!ExitCondition) return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000255 if (ExitingBlock != L->getLoopLatch()) return false;
Devang Patel38310052008-12-04 21:38:42 +0000256 IVExitValue = ExitCondition->getOperand(1);
257 if (!L->isLoopInvariant(IVExitValue))
258 IVExitValue = ExitCondition->getOperand(0);
259 if (!L->isLoopInvariant(IVExitValue))
260 return false;
Dan Gohmanf7ca1612009-06-27 22:58:27 +0000261 if (!IVBasedValues.count(
262 ExitCondition->getOperand(IVExitValue == ExitCondition->getOperand(0))))
263 return false;
Devang Patela5e27f82008-07-09 00:12:01 +0000264
265 // If start value is more then exit value where induction variable
266 // increments by 1 then we are potentially dealing with an infinite loop.
267 // Do not index split this loop.
Devang Patel38310052008-12-04 21:38:42 +0000268 if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
269 if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
270 if (SV->getSExtValue() > EV->getSExtValue())
271 return false;
Devang Patelc9d123d2007-08-09 01:39:01 +0000272
Devang Patel38310052008-12-04 21:38:42 +0000273 if (processOneIterationLoop())
274 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000275
Devang Patel38310052008-12-04 21:38:42 +0000276 if (updateLoopIterationSpace())
277 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000278
Devang Patel38310052008-12-04 21:38:42 +0000279 if (splitLoop())
280 return true;
Devang Pateld35ed2c2007-09-11 00:42:56 +0000281
282 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000283}
284
Devang Patel38310052008-12-04 21:38:42 +0000285// --- Helper routines ---
286// isUsedOutsideLoop - Returns true iff V is used outside the loop L.
287static bool isUsedOutsideLoop(Value *V, Loop *L) {
288 for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
289 if (!L->contains(cast<Instruction>(*UI)->getParent()))
290 return true;
291 return false;
292}
Devang Patelfee76bd2007-08-07 00:25:56 +0000293
Devang Patel38310052008-12-04 21:38:42 +0000294// Return V+1
295static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000296 Constant *One = ConstantInt::get(V->getType(), 1, Sign);
Devang Patel38310052008-12-04 21:38:42 +0000297 return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
298}
Devang Patelfee76bd2007-08-07 00:25:56 +0000299
Devang Patel38310052008-12-04 21:38:42 +0000300// Return V-1
301static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000302 Constant *One = ConstantInt::get(V->getType(), 1, Sign);
Devang Patel38310052008-12-04 21:38:42 +0000303 return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
304}
Devang Patelfee76bd2007-08-07 00:25:56 +0000305
Devang Patel38310052008-12-04 21:38:42 +0000306// Return min(V1, V1)
307static Value *getMin(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
308
309 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
310 V1, V2, "lsp", InsertPt);
311 return SelectInst::Create(C, V1, V2, "lsp", InsertPt);
312}
Devang Patelfee76bd2007-08-07 00:25:56 +0000313
Devang Patel38310052008-12-04 21:38:42 +0000314// Return max(V1, V2)
315static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
316
317 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
318 V1, V2, "lsp", InsertPt);
319 return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
320}
Devang Patel968eee22007-09-19 00:15:16 +0000321
Devang Patel38310052008-12-04 21:38:42 +0000322/// processOneIterationLoop -- Eliminate loop if loop body is executed
323/// only once. For example,
324/// for (i = 0; i < N; ++i) {
325/// if ( i == X) {
326/// ...
327/// }
328/// }
329///
330bool LoopIndexSplit::processOneIterationLoop() {
331 SplitCondition = NULL;
Devang Patel84ef08b2007-09-19 00:11:01 +0000332 BasicBlock *Latch = L->getLoopLatch();
Devang Patel38310052008-12-04 21:38:42 +0000333 BasicBlock *Header = L->getHeader();
334 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
335 if (!BR) return false;
336 if (!isa<BranchInst>(Latch->getTerminator())) return false;
337 if (BR->isUnconditional()) return false;
338 SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
339 if (!SplitCondition) return false;
340 if (SplitCondition == ExitCondition) return false;
341 if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
342 if (BR->getOperand(1) != Latch) return false;
343 if (!IVBasedValues.count(SplitCondition->getOperand(0))
344 && !IVBasedValues.count(SplitCondition->getOperand(1)))
Devang Patel84ef08b2007-09-19 00:11:01 +0000345 return false;
346
Devang Patel38310052008-12-04 21:38:42 +0000347 // If IV is used outside the loop then this loop traversal is required.
348 // FIXME: Calculate and use last IV value.
349 if (isUsedOutsideLoop(IVIncrement, L))
350 return false;
351
352 // If BR operands are not IV or not loop invariants then skip this loop.
353 Value *OPV = SplitCondition->getOperand(0);
354 Value *SplitValue = SplitCondition->getOperand(1);
Eli Friedmanf7cca7b2009-05-22 03:22:46 +0000355 if (!L->isLoopInvariant(SplitValue))
356 std::swap(OPV, SplitValue);
Devang Patel38310052008-12-04 21:38:42 +0000357 if (!L->isLoopInvariant(SplitValue))
358 return false;
359 Instruction *OPI = dyn_cast<Instruction>(OPV);
Devang Patelb23c2322009-03-30 22:24:10 +0000360 if (!OPI)
361 return false;
Devang Patel38310052008-12-04 21:38:42 +0000362 if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
363 return false;
Devang Patelb23c2322009-03-30 22:24:10 +0000364 Value *StartValue = IVStartValue;
365 Value *ExitValue = IVExitValue;;
366
367 if (OPV != IndVar) {
368 // If BR operand is IV based then use this operand to calculate
369 // effective conditions for loop body.
370 BinaryOperator *BOPV = dyn_cast<BinaryOperator>(OPV);
371 if (!BOPV)
372 return false;
373 if (BOPV->getOpcode() != Instruction::Add)
374 return false;
375 StartValue = BinaryOperator::CreateAdd(OPV, StartValue, "" , BR);
376 ExitValue = BinaryOperator::CreateAdd(OPV, ExitValue, "" , BR);
377 }
378
Devang Patel38310052008-12-04 21:38:42 +0000379 if (!cleanBlock(Header))
380 return false;
381
382 if (!cleanBlock(Latch))
383 return false;
384
385 // If the merge point for BR is not loop latch then skip this loop.
386 if (BR->getSuccessor(0) != Latch) {
387 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
388 assert (DF0 != DF->end() && "Unable to find dominance frontier");
389 if (!DF0->second.count(Latch))
390 return false;
391 }
392
393 if (BR->getSuccessor(1) != Latch) {
394 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
395 assert (DF1 != DF->end() && "Unable to find dominance frontier");
396 if (!DF1->second.count(Latch))
397 return false;
398 }
399
400 // Now, Current loop L contains compare instruction
401 // that compares induction variable, IndVar, against loop invariant. And
402 // entire (i.e. meaningful) loop body is dominated by this compare
403 // instruction. In such case eliminate
404 // loop structure surrounding this loop body. For example,
405 // for (int i = start; i < end; ++i) {
406 // if ( i == somevalue) {
407 // loop_body
408 // }
409 // }
410 // can be transformed into
411 // if (somevalue >= start && somevalue < end) {
412 // i = somevalue;
413 // loop_body
414 // }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000415
Devang Patelebc5fea2007-08-20 20:49:01 +0000416 // Replace index variable with split value in loop body. Loop body is executed
417 // only when index variable is equal to split value.
Devang Patel38310052008-12-04 21:38:42 +0000418 IndVar->replaceAllUsesWith(SplitValue);
Devang Patelfee76bd2007-08-07 00:25:56 +0000419
Devang Patelfee76bd2007-08-07 00:25:56 +0000420 // Replace split condition in header.
421 // Transform
422 // SplitCondition : icmp eq i32 IndVar, SplitValue
423 // into
424 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000425 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000426 // and i32 c1, c2
Devang Patel38310052008-12-04 21:38:42 +0000427 Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ?
Devang Patelfee76bd2007-08-07 00:25:56 +0000428 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelb23c2322009-03-30 22:24:10 +0000429 SplitValue, StartValue, "lisplit", BR);
Devang Patel38310052008-12-04 21:38:42 +0000430
431 CmpInst::Predicate C2P = ExitCondition->getPredicate();
432 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
433 if (LatchBR->getOperand(0) != Header)
434 C2P = CmpInst::getInversePredicate(C2P);
Devang Patelb23c2322009-03-30 22:24:10 +0000435 Instruction *C2 = new ICmpInst(C2P, SplitValue, ExitValue, "lisplit", BR);
Devang Patel38310052008-12-04 21:38:42 +0000436 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
437
438 SplitCondition->replaceAllUsesWith(NSplitCond);
439 SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000440
Devang Patelfc19fbd2008-10-10 22:02:57 +0000441 // Remove Latch to Header edge.
442 BasicBlock *LatchSucc = NULL;
443 Header->removePredecessor(Latch);
444 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
445 SI != E; ++SI) {
446 if (Header != *SI)
447 LatchSucc = *SI;
448 }
Devang Patelfc19fbd2008-10-10 22:02:57 +0000449
Devang Patelb23c2322009-03-30 22:24:10 +0000450 // Clean up latch block.
451 Value *LatchBRCond = LatchBR->getCondition();
452 LatchBR->setUnconditionalDest(LatchSucc);
453 RecursivelyDeleteTriviallyDeadInstructions(LatchBRCond);
Devang Patel38310052008-12-04 21:38:42 +0000454
Devang Patel423c8b22007-08-10 18:07:13 +0000455 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000456
457 // Update Dominator Info.
458 // Only CFG change done is to remove Latch to Header edge. This
459 // does not change dominator tree because Latch did not dominate
460 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000461 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000462 DominanceFrontier::iterator HeaderDF = DF->find(Header);
463 if (HeaderDF != DF->end())
464 DF->removeFromFrontier(HeaderDF, Header);
465
466 DominanceFrontier::iterator LatchDF = DF->find(Latch);
467 if (LatchDF != DF->end())
468 DF->removeFromFrontier(LatchDF, Header);
469 }
Devang Patel38310052008-12-04 21:38:42 +0000470
471 ++NumIndexSplitRemoved;
Devang Patelfee76bd2007-08-07 00:25:56 +0000472 return true;
473}
474
Devang Patel38310052008-12-04 21:38:42 +0000475/// restrictLoopBound - Op dominates loop body. Op compares an IV based value
476/// with a loop invariant value. Update loop's lower and upper bound based on
477/// the loop invariant value.
478bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
479 bool Sign = Op.isSignedPredicate();
480 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
Devang Patelfee76bd2007-08-07 00:25:56 +0000481
Devang Patel38310052008-12-04 21:38:42 +0000482 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
483 BranchInst *EBR =
484 cast<BranchInst>(ExitCondition->getParent()->getTerminator());
485 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
486 BasicBlock *T = EBR->getSuccessor(0);
487 EBR->setSuccessor(0, EBR->getSuccessor(1));
488 EBR->setSuccessor(1, T);
Devang Patelfee76bd2007-08-07 00:25:56 +0000489 }
490
Devang Patel38310052008-12-04 21:38:42 +0000491 // New upper and lower bounds.
Devang Patel453a8442007-09-25 17:31:19 +0000492 Value *NLB = NULL;
Devang Patel38310052008-12-04 21:38:42 +0000493 Value *NUB = NULL;
494 if (Value *V = IVisLT(Op)) {
495 // Restrict upper bound.
496 if (IVisLE(*ExitCondition))
497 V = getMinusOne(V, Sign, PHTerm);
498 NUB = getMin(V, IVExitValue, Sign, PHTerm);
499 } else if (Value *V = IVisLE(Op)) {
500 // Restrict upper bound.
501 if (IVisLT(*ExitCondition))
502 V = getPlusOne(V, Sign, PHTerm);
503 NUB = getMin(V, IVExitValue, Sign, PHTerm);
504 } else if (Value *V = IVisGT(Op)) {
505 // Restrict lower bound.
506 V = getPlusOne(V, Sign, PHTerm);
507 NLB = getMax(V, IVStartValue, Sign, PHTerm);
508 } else if (Value *V = IVisGE(Op))
509 // Restrict lower bound.
510 NLB = getMax(V, IVStartValue, Sign, PHTerm);
Devang Patel453a8442007-09-25 17:31:19 +0000511
Devang Patel38310052008-12-04 21:38:42 +0000512 if (!NLB && !NUB)
513 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000514
515 if (NLB) {
Devang Patel38310052008-12-04 21:38:42 +0000516 unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
Devang Patel453a8442007-09-25 17:31:19 +0000517 IndVar->setIncomingValue(i, NLB);
518 }
519
520 if (NUB) {
Devang Patel38310052008-12-04 21:38:42 +0000521 unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
522 ExitCondition->setOperand(i, NUB);
Devang Patel453a8442007-09-25 17:31:19 +0000523 }
Devang Patel38310052008-12-04 21:38:42 +0000524 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000525}
Devang Patel38310052008-12-04 21:38:42 +0000526
527/// updateLoopIterationSpace -- Update loop's iteration space if loop
528/// body is executed for certain IV range only. For example,
529///
530/// for (i = 0; i < N; ++i) {
531/// if ( i > A && i < B) {
532/// ...
533/// }
534/// }
Devang Patel042b8772008-12-08 17:07:24 +0000535/// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000536///
537bool LoopIndexSplit::updateLoopIterationSpace() {
538 SplitCondition = NULL;
539 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
540 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
541 return false;
542 BasicBlock *Latch = L->getLoopLatch();
Devang Patel5279d062007-09-17 20:39:48 +0000543 BasicBlock *Header = L->getHeader();
Devang Patel38310052008-12-04 21:38:42 +0000544 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
545 if (!BR) return false;
546 if (!isa<BranchInst>(Latch->getTerminator())) return false;
547 if (BR->isUnconditional()) return false;
548 BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
549 if (!AND) return false;
550 if (AND->getOpcode() != Instruction::And) return false;
551 ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
552 ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
553 if (!Op0 || !Op1)
554 return false;
555 IVBasedValues.insert(AND);
556 IVBasedValues.insert(Op0);
557 IVBasedValues.insert(Op1);
558 if (!cleanBlock(Header)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000559 BasicBlock *ExitingBlock = ExitCondition->getParent();
Devang Patel38310052008-12-04 21:38:42 +0000560 if (!cleanBlock(ExitingBlock)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000561
Devang Patelcf42ee42009-03-02 23:39:14 +0000562 // If the merge point for BR is not loop latch then skip this loop.
563 if (BR->getSuccessor(0) != Latch) {
564 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
565 assert (DF0 != DF->end() && "Unable to find dominance frontier");
566 if (!DF0->second.count(Latch))
567 return false;
568 }
569
570 if (BR->getSuccessor(1) != Latch) {
571 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
572 assert (DF1 != DF->end() && "Unable to find dominance frontier");
573 if (!DF1->second.count(Latch))
574 return false;
575 }
576
Devang Patel38310052008-12-04 21:38:42 +0000577 // Verify that loop exiting block has only two predecessor, where one pred
Devang Patel453a8442007-09-25 17:31:19 +0000578 // is split condition block. The other predecessor will become exiting block's
579 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
580 // more then two predecessors. This requires extra work in updating dominator
581 // information.
582 BasicBlock *ExitingBBPred = NULL;
583 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
584 PI != PE; ++PI) {
585 BasicBlock *BB = *PI;
Devang Patel38310052008-12-04 21:38:42 +0000586 if (Header == BB)
Devang Patel453a8442007-09-25 17:31:19 +0000587 continue;
588 if (ExitingBBPred)
589 return false;
590 else
591 ExitingBBPred = BB;
592 }
Devang Patel453a8442007-09-25 17:31:19 +0000593
Devang Patel38310052008-12-04 21:38:42 +0000594 if (!restrictLoopBound(*Op0))
595 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000596
Devang Patel38310052008-12-04 21:38:42 +0000597 if (!restrictLoopBound(*Op1))
598 return false;
599
600 // Update CFG.
601 if (BR->getSuccessor(0) == ExitingBlock)
602 BR->setUnconditionalDest(BR->getSuccessor(1));
Devang Patel453a8442007-09-25 17:31:19 +0000603 else
Devang Patel38310052008-12-04 21:38:42 +0000604 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel453a8442007-09-25 17:31:19 +0000605
Devang Patel38310052008-12-04 21:38:42 +0000606 AND->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000607 if (Op0->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000608 Op0->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000609 if (Op1->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000610 Op1->eraseFromParent();
Devang Patel453a8442007-09-25 17:31:19 +0000611
612 // Update domiantor info. Now, ExitingBlock has only one predecessor,
613 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
614 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
Devang Patel38310052008-12-04 21:38:42 +0000615
616 BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
617 if (L->contains(ExitBlock))
618 ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
619
620 // If ExitingBlock is a member of the loop basic blocks' DF list then
621 // replace ExitingBlock with header and exit block in the DF list
622 DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
Devang Patel453a8442007-09-25 17:31:19 +0000623 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
624 I != E; ++I) {
625 BasicBlock *BB = *I;
626 if (BB == Header || BB == ExitingBlock)
627 continue;
628 DominanceFrontier::iterator BBDF = DF->find(BB);
629 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
630 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
631 while (DomSetI != DomSetE) {
632 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
633 ++DomSetI;
634 BasicBlock *DFBB = *CurrentItr;
635 if (DFBB == ExitingBlock) {
636 BBDF->second.erase(DFBB);
Devang Patel38310052008-12-04 21:38:42 +0000637 for (DominanceFrontier::DomSetType::iterator
638 EBI = ExitingBlockDF->second.begin(),
639 EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI)
640 BBDF->second.insert(*EBI);
Devang Patel453a8442007-09-25 17:31:19 +0000641 }
642 }
643 }
Devang Patel38310052008-12-04 21:38:42 +0000644 NumRestrictBounds++;
Devang Patel1c013502007-09-25 17:43:08 +0000645 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000646}
647
Devang Patela6a86632007-08-14 18:35:57 +0000648/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
649/// This routine is used to remove split condition's dead branch, dominated by
650/// DeadBB. LiveBB dominates split conidition's other branch.
651void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
652 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +0000653
Devang Patel5b8ec612007-08-15 03:31:47 +0000654 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +0000655 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +0000656 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
657 if (DeadBBDF != DF->end()) {
658 SmallVector<BasicBlock *, 8> PredBlocks;
659
660 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
661 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
Devang Patel38310052008-12-04 21:38:42 +0000662 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI)
663 {
Devang Patel5b8ec612007-08-15 03:31:47 +0000664 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +0000665 FrontierBBs.push_back(FrontierBB);
666
Devang Patel5b8ec612007-08-15 03:31:47 +0000667 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
668 PredBlocks.clear();
669 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
670 PI != PE; ++PI) {
671 BasicBlock *P = *PI;
672 if (P == DeadBB || DT->dominates(DeadBB, P))
673 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +0000674 }
Devang Patel96bf5242007-08-17 21:59:16 +0000675
Devang Patel5b8ec612007-08-15 03:31:47 +0000676 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
677 FBI != FBE; ++FBI) {
678 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
679 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
680 PE = PredBlocks.end(); PI != PE; ++PI) {
681 BasicBlock *P = *PI;
682 PN->removeIncomingValue(P);
683 }
684 }
685 else
686 break;
Devang Patel96bf5242007-08-17 21:59:16 +0000687 }
Devang Patel98147a32007-08-12 07:02:51 +0000688 }
Devang Patel98147a32007-08-12 07:02:51 +0000689 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000690
691 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
692 SmallVector<BasicBlock *, 32> WorkList;
693 DomTreeNode *DN = DT->getNode(DeadBB);
694 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
695 E = df_end(DN); DI != E; ++DI) {
696 BasicBlock *BB = DI->getBlock();
697 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +0000698 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +0000699 }
700
701 while (!WorkList.empty()) {
702 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
Devang Patel575ec802009-03-25 23:57:48 +0000703 LPM->deleteSimpleAnalysisValue(BB, LP);
Devang Patel5b8ec612007-08-15 03:31:47 +0000704 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +0000705 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +0000706 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +0000707 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +0000708 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Owen Anderson0b2a1532009-04-14 01:04:19 +0000709 LPM->deleteSimpleAnalysisValue(I, LP);
Devang Patel5b8ec612007-08-15 03:31:47 +0000710 I->eraseFromParent();
711 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000712 DT->eraseNode(BB);
713 DF->removeBlock(BB);
714 LI->removeBlock(BB);
715 BB->eraseFromParent();
716 }
Devang Patel96bf5242007-08-17 21:59:16 +0000717
718 // Update Frontier BBs' dominator info.
719 while (!FrontierBBs.empty()) {
720 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
721 BasicBlock *NewDominator = FBB->getSinglePredecessor();
722 if (!NewDominator) {
723 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
724 NewDominator = *PI;
725 ++PI;
726 if (NewDominator != LiveBB) {
727 for(; PI != PE; ++PI) {
728 BasicBlock *P = *PI;
729 if (P == LiveBB) {
730 NewDominator = LiveBB;
731 break;
732 }
733 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
734 }
735 }
736 }
737 assert (NewDominator && "Unable to fix dominator info.");
738 DT->changeImmediateDominator(FBB, NewDominator);
739 DF->changeImmediateDominator(FBB, NewDominator, DT);
740 }
741
Devang Patel98147a32007-08-12 07:02:51 +0000742}
743
Devang Pateld79faee2007-08-25 02:39:24 +0000744// moveExitCondition - Move exit condition EC into split condition block CondBB.
745void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
Devang Patel38310052008-12-04 21:38:42 +0000746 BasicBlock *ExitBB, ICmpInst *EC,
747 ICmpInst *SC, PHINode *IV,
748 Instruction *IVAdd, Loop *LP,
749 unsigned ExitValueNum) {
Devang Pateld79faee2007-08-25 02:39:24 +0000750
751 BasicBlock *ExitingBB = EC->getParent();
752 Instruction *CurrentBR = CondBB->getTerminator();
753
754 // Move exit condition into split condition block.
755 EC->moveBefore(CurrentBR);
756 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
757
758 // Move exiting block's branch into split condition block. Update its branch
759 // destination.
760 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
761 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +0000762 BasicBlock *OrigDestBB = NULL;
763 if (ExitingBR->getSuccessor(0) == ExitBB) {
764 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +0000765 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000766 }
767 else {
768 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +0000769 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000770 }
Devang Pateld79faee2007-08-25 02:39:24 +0000771
772 // Remove split condition and current split condition branch.
773 SC->eraseFromParent();
774 CurrentBR->eraseFromParent();
775
Devang Patel23067df2008-02-13 22:06:36 +0000776 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +0000777 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +0000778
779 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +0000780 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000781
782 // Fix dominator info.
783 // ExitBB is now dominated by CondBB
784 DT->changeImmediateDominator(ExitBB, CondBB);
785 DF->changeImmediateDominator(ExitBB, CondBB, DT);
Eli Friedmanf7cca7b2009-05-22 03:22:46 +0000786
787 // Blocks outside the loop may have been in the dominance frontier of blocks
788 // inside the condition; this is now impossible because the blocks inside the
789 // condition no loger dominate the exit. Remove the relevant blocks from
790 // the dominance frontiers.
791 for (Loop::block_iterator I = LP->block_begin(), E = LP->block_end();
792 I != E; ++I) {
793 if (*I == CondBB || !DT->dominates(CondBB, *I)) continue;
794 DominanceFrontier::iterator BBDF = DF->find(*I);
Devang Pateld79faee2007-08-25 02:39:24 +0000795 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
796 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
797 while (DomSetI != DomSetE) {
798 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
799 ++DomSetI;
800 BasicBlock *DFBB = *CurrentItr;
Eli Friedmanf7cca7b2009-05-22 03:22:46 +0000801 if (!LP->contains(DFBB))
Devang Pateld79faee2007-08-25 02:39:24 +0000802 BBDF->second.erase(DFBB);
Devang Pateld79faee2007-08-25 02:39:24 +0000803 }
804 }
805}
806
807/// updatePHINodes - CFG has been changed.
808/// Before
809/// - ExitBB's single predecessor was Latch
810/// - Latch's second successor was Header
811/// Now
Devang Patel82ada542008-02-08 22:49:13 +0000812/// - ExitBB's single predecessor is Header
813/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +0000814///
815/// Update ExitBB PHINodes' to reflect this change.
816void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
817 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000818 PHINode *IV, Instruction *IVIncrement,
819 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +0000820
821 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000822 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +0000823 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000824 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +0000825 if (!PN)
826 break;
827
828 Value *V = PN->getIncomingValueForBlock(Latch);
829 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +0000830 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
831 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +0000832 Value *NewV = NULL;
833 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +0000834 UI != E; ++UI)
835 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +0000836 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +0000837 NewV = U;
838 break;
839 }
840
Devang Patel60a12902008-03-24 20:16:14 +0000841 // Add incoming value from header only if PN has any use inside the loop.
842 if (NewV)
843 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +0000844
845 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
846 // If this instruction is IVIncrement then IV is new incoming value
847 // from header otherwise this instruction must be incoming value from
848 // header because loop is in LCSSA form.
849 if (PHI == IVIncrement)
850 PN->addIncoming(IV, Header);
851 else
852 PN->addIncoming(V, Header);
853 } else
854 // Otherwise this is an incoming value from header because loop is in
855 // LCSSA form.
856 PN->addIncoming(V, Header);
857
858 // Remove incoming value from Latch.
859 PN->removeIncomingValue(Latch);
860 }
861}
Devang Patel38310052008-12-04 21:38:42 +0000862
863bool LoopIndexSplit::splitLoop() {
864 SplitCondition = NULL;
865 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
866 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
867 return false;
868 BasicBlock *Header = L->getHeader();
869 BasicBlock *Latch = L->getLoopLatch();
870 BranchInst *SBR = NULL; // Split Condition Branch
871 BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
872 // If Exiting block includes loop variant instructions then this
873 // loop may not be split safely.
874 BasicBlock *ExitingBlock = ExitCondition->getParent();
875 if (!cleanBlock(ExitingBlock)) return false;
876
877 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
878 I != E; ++I) {
879 BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
880 if (!BR || BR->isUnconditional()) continue;
881 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
882 if (!CI || CI == ExitCondition
883 || CI->getPredicate() == ICmpInst::ICMP_NE
884 || CI->getPredicate() == ICmpInst::ICMP_EQ)
885 continue;
886
887 // Unable to handle triangle loops at the moment.
888 // In triangle loop, split condition is in header and one of the
889 // the split destination is loop latch. If split condition is EQ
890 // then such loops are already handle in processOneIterationLoop().
891 if (Header == (*I)
892 && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
893 continue;
894
895 // If the block does not dominate the latch then this is not a diamond.
896 // Such loop may not benefit from index split.
897 if (!DT->dominates((*I), Latch))
898 continue;
899
900 // If split condition branches heads do not have single predecessor,
901 // SplitCondBlock, then is not possible to remove inactive branch.
902 if (!BR->getSuccessor(0)->getSinglePredecessor()
903 || !BR->getSuccessor(1)->getSinglePredecessor())
904 return false;
905
906 // If the merge point for BR is not loop latch then skip this condition.
907 if (BR->getSuccessor(0) != Latch) {
908 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
909 assert (DF0 != DF->end() && "Unable to find dominance frontier");
910 if (!DF0->second.count(Latch))
911 continue;
912 }
913
914 if (BR->getSuccessor(1) != Latch) {
915 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
916 assert (DF1 != DF->end() && "Unable to find dominance frontier");
917 if (!DF1->second.count(Latch))
918 continue;
919 }
920 SplitCondition = CI;
921 SBR = BR;
922 break;
923 }
924
925 if (!SplitCondition)
926 return false;
927
928 // If the predicate sign does not match then skip.
929 if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
930 return false;
931
932 unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
933 unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
934 Value *SplitValue = SplitCondition->getOperand(SVOpNum);
935 if (!L->isLoopInvariant(SplitValue))
936 return false;
937 if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
938 return false;
939
940 // Normalize loop conditions so that it is easier to calculate new loop
941 // bounds.
942 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
943 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
944 BasicBlock *T = EBR->getSuccessor(0);
945 EBR->setSuccessor(0, EBR->getSuccessor(1));
946 EBR->setSuccessor(1, T);
947 }
948
949 if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
950 SplitCondition->setPredicate(SplitCondition->getInversePredicate());
951 BasicBlock *T = SBR->getSuccessor(0);
952 SBR->setSuccessor(0, SBR->getSuccessor(1));
953 SBR->setSuccessor(1, T);
954 }
955
956 //[*] Calculate new loop bounds.
957 Value *AEV = SplitValue;
958 Value *BSV = SplitValue;
959 bool Sign = SplitCondition->isSignedPredicate();
960 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
961
962 if (IVisLT(*ExitCondition)) {
963 if (IVisLT(*SplitCondition)) {
964 /* Do nothing */
965 }
966 else if (IVisLE(*SplitCondition)) {
967 AEV = getPlusOne(SplitValue, Sign, PHTerm);
968 BSV = getPlusOne(SplitValue, Sign, PHTerm);
969 } else {
970 assert (0 && "Unexpected split condition!");
971 }
972 }
973 else if (IVisLE(*ExitCondition)) {
974 if (IVisLT(*SplitCondition)) {
975 AEV = getMinusOne(SplitValue, Sign, PHTerm);
976 }
977 else if (IVisLE(*SplitCondition)) {
978 BSV = getPlusOne(SplitValue, Sign, PHTerm);
979 } else {
980 assert (0 && "Unexpected split condition!");
981 }
982 } else {
983 assert (0 && "Unexpected exit condition!");
984 }
985 AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
986 BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
987
988 // [*] Clone Loop
989 DenseMap<const Value *, Value *> ValueMap;
990 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
991 Loop *ALoop = L;
992
993 // [*] ALoop's exiting edge enters BLoop's header.
994 // ALoop's original exit block becomes BLoop's exit block.
995 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
996 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
997 BranchInst *A_ExitInsn =
998 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
999 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1000 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1001 BasicBlock *B_Header = BLoop->getHeader();
1002 if (ALoop->contains(B_ExitBlock)) {
1003 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1004 A_ExitInsn->setSuccessor(0, B_Header);
1005 } else
1006 A_ExitInsn->setSuccessor(1, B_Header);
1007
1008 // [*] Update ALoop's exit value using new exit value.
1009 ExitCondition->setOperand(EVOpNum, AEV);
1010
1011 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1012 // original loop's preheader. Add incoming PHINode values from
1013 // ALoop's exiting block. Update BLoop header's domiantor info.
1014
1015 // Collect inverse map of Header PHINodes.
1016 DenseMap<Value *, Value *> InverseMap;
1017 for (BasicBlock::iterator BI = ALoop->getHeader()->begin(),
1018 BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
1019 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1020 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1021 InverseMap[PNClone] = PN;
1022 } else
1023 break;
1024 }
1025
1026 BasicBlock *A_Preheader = ALoop->getLoopPreheader();
1027 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1028 BI != BE; ++BI) {
1029 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1030 // Remove incoming value from original preheader.
1031 PN->removeIncomingValue(A_Preheader);
1032
1033 // Add incoming value from A_ExitingBlock.
1034 if (PN == B_IndVar)
1035 PN->addIncoming(BSV, A_ExitingBlock);
1036 else {
1037 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1038 Value *V2 = NULL;
1039 // If loop header is also loop exiting block then
1040 // OrigPN is incoming value for B loop header.
1041 if (A_ExitingBlock == ALoop->getHeader())
1042 V2 = OrigPN;
1043 else
1044 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1045 PN->addIncoming(V2, A_ExitingBlock);
1046 }
1047 } else
1048 break;
1049 }
1050
1051 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1052 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1053
1054 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1055 // block. Remove incoming PHINode values from ALoop's exiting block.
1056 // Add new incoming values from BLoop's incoming exiting value.
1057 // Update BLoop exit block's dominator info..
1058 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1059 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1060 BI != BE; ++BI) {
1061 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1062 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1063 B_ExitingBlock);
1064 PN->removeIncomingValue(A_ExitingBlock);
1065 } else
1066 break;
1067 }
1068
1069 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1070 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1071
Dan Gohmanf159ccd2009-04-29 22:01:05 +00001072 //[*] Split ALoop's exit edge. This creates a new block which
Devang Patel38310052008-12-04 21:38:42 +00001073 // serves two purposes. First one is to hold PHINode defnitions
1074 // to ensure that ALoop's LCSSA form. Second use it to act
1075 // as a preheader for BLoop.
1076 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1077
1078 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1079 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1080 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1081 BI != BE; ++BI) {
1082 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1083 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1084 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1085 newPHI->addIncoming(V1, A_ExitingBlock);
1086 A_ExitBlock->getInstList().push_front(newPHI);
1087 PN->removeIncomingValue(A_ExitBlock);
1088 PN->addIncoming(newPHI, A_ExitBlock);
1089 } else
1090 break;
1091 }
1092
1093 //[*] Eliminate split condition's inactive branch from ALoop.
1094 BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1095 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1096 BasicBlock *A_InactiveBranch = NULL;
1097 BasicBlock *A_ActiveBranch = NULL;
1098 A_ActiveBranch = A_BR->getSuccessor(0);
1099 A_InactiveBranch = A_BR->getSuccessor(1);
1100 A_BR->setUnconditionalDest(A_ActiveBranch);
1101 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1102
1103 //[*] Eliminate split condition's inactive branch in from BLoop.
1104 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1105 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1106 BasicBlock *B_InactiveBranch = NULL;
1107 BasicBlock *B_ActiveBranch = NULL;
1108 B_ActiveBranch = B_BR->getSuccessor(1);
1109 B_InactiveBranch = B_BR->getSuccessor(0);
1110 B_BR->setUnconditionalDest(B_ActiveBranch);
1111 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1112
1113 BasicBlock *A_Header = ALoop->getHeader();
1114 if (A_ExitingBlock == A_Header)
1115 return true;
1116
1117 //[*] Move exit condition into split condition block to avoid
1118 // executing dead loop iteration.
1119 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1120 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1121 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1122
1123 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1124 cast<ICmpInst>(SplitCondition), IndVar, IVIncrement,
1125 ALoop, EVOpNum);
1126
1127 moveExitCondition(B_SplitCondBlock, B_ActiveBranch,
1128 B_ExitBlock, B_ExitCondition,
1129 B_SplitCondition, B_IndVar, B_IndVarIncrement,
1130 BLoop, EVOpNum);
1131
1132 NumIndexSplit++;
1133 return true;
1134}
1135
1136/// cleanBlock - A block is considered clean if all non terminal instructions
1137/// are either, PHINodes, IV based.
1138bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1139 Instruction *Terminator = BB->getTerminator();
1140 for(BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1141 BI != BE; ++BI) {
1142 Instruction *I = BI;
1143
1144 if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
Devang Pateld96c60d2009-02-06 06:19:06 +00001145 || I == SplitCondition || IVBasedValues.count(I)
1146 || isa<DbgInfoIntrinsic>(I))
Devang Patel38310052008-12-04 21:38:42 +00001147 continue;
1148
Duncan Sands7af1c782009-05-06 06:49:50 +00001149 if (I->mayHaveSideEffects())
Devang Patel38310052008-12-04 21:38:42 +00001150 return false;
1151
1152 // I is used only inside this block then it is OK.
1153 bool usedOutsideBB = false;
1154 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1155 UI != UE; ++UI) {
1156 Instruction *U = cast<Instruction>(UI);
1157 if (U->getParent() != BB)
1158 usedOutsideBB = true;
1159 }
1160 if (!usedOutsideBB)
1161 continue;
1162
1163 // Otherwise we have a instruction that may not allow loop spliting.
1164 return false;
1165 }
1166 return true;
1167}
1168
Devang Patel042b8772008-12-08 17:07:24 +00001169/// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001170/// IV based value is less than the loop invariant then return the loop
1171/// invariant. Otherwise return NULL.
1172Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1173 ICmpInst::Predicate P = Op.getPredicate();
1174 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1175 && IVBasedValues.count(Op.getOperand(0))
1176 && L->isLoopInvariant(Op.getOperand(1)))
1177 return Op.getOperand(1);
1178
1179 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1180 && IVBasedValues.count(Op.getOperand(1))
1181 && L->isLoopInvariant(Op.getOperand(0)))
1182 return Op.getOperand(0);
1183
1184 return NULL;
1185}
1186
Devang Patel042b8772008-12-08 17:07:24 +00001187/// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001188/// IV based value is less than or equal to the loop invariant then
1189/// return the loop invariant. Otherwise return NULL.
1190Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1191 ICmpInst::Predicate P = Op.getPredicate();
1192 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1193 && IVBasedValues.count(Op.getOperand(0))
1194 && L->isLoopInvariant(Op.getOperand(1)))
1195 return Op.getOperand(1);
1196
1197 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1198 && IVBasedValues.count(Op.getOperand(1))
1199 && L->isLoopInvariant(Op.getOperand(0)))
1200 return Op.getOperand(0);
1201
1202 return NULL;
1203}
1204
Devang Patel042b8772008-12-08 17:07:24 +00001205/// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001206/// IV based value is greater than the loop invariant then return the loop
1207/// invariant. Otherwise return NULL.
1208Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1209 ICmpInst::Predicate P = Op.getPredicate();
1210 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1211 && IVBasedValues.count(Op.getOperand(0))
1212 && L->isLoopInvariant(Op.getOperand(1)))
1213 return Op.getOperand(1);
1214
1215 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1216 && IVBasedValues.count(Op.getOperand(1))
1217 && L->isLoopInvariant(Op.getOperand(0)))
1218 return Op.getOperand(0);
1219
1220 return NULL;
1221}
1222
Devang Patel042b8772008-12-08 17:07:24 +00001223/// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001224/// IV based value is greater than or equal to the loop invariant then
1225/// return the loop invariant. Otherwise return NULL.
1226Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1227 ICmpInst::Predicate P = Op.getPredicate();
1228 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1229 && IVBasedValues.count(Op.getOperand(0))
1230 && L->isLoopInvariant(Op.getOperand(1)))
1231 return Op.getOperand(1);
1232
1233 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1234 && IVBasedValues.count(Op.getOperand(1))
1235 && L->isLoopInvariant(Op.getOperand(0)))
1236 return Op.getOperand(0);
1237
1238 return NULL;
1239}
1240