blob: 2bcb10849edef2a955cf14381764c239da824463 [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//
Devang Patel38310052008-12-04 21:38:42 +000013// [1] Loop is eliminated when loop body is executed only once. For example,
14// for (i = 0; i < N; ++i) {
15// if ( i == X) {
16// ...
17// }
18// }
19//
20// [2] Loop's iteration space is shrunk if loop body is executed for certain
21// range only. For example,
22//
23// for (i = 0; i < N; ++i) {
24// if ( i > A && i < B) {
25// ...
26// }
27// }
28// is trnasformed to iterators from A to B, if A > 0 and B < N.
29//
30// [3] Loop is split if the loop body is dominated by an branch. For example,
31//
32// for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
33//
34// is transformed into
35// AEV = BSV = SV
36// for (i = LB; i < min(UB, AEV); ++i)
37// A;
38// for (i = max(LB, BSV); i < UB; ++i);
39// B;
Devang Patelfee76bd2007-08-07 00:25:56 +000040//===----------------------------------------------------------------------===//
41
42#define DEBUG_TYPE "loop-index-split"
43
Devang Patelfee76bd2007-08-07 00:25:56 +000044#include "llvm/Transforms/Scalar.h"
Devang Pateld96c60d2009-02-06 06:19:06 +000045#include "llvm/IntrinsicInst.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000046#include "llvm/Analysis/LoopPass.h"
47#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel787a7132007-08-08 21:39:47 +000048#include "llvm/Analysis/Dominators.h"
Devang Patel423c8b22007-08-10 18:07:13 +000049#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000051#include "llvm/Support/Compiler.h"
Devang Patel5b8ec612007-08-15 03:31:47 +000052#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000053#include "llvm/ADT/Statistic.h"
54
55using namespace llvm;
56
Devang Patel38310052008-12-04 21:38:42 +000057STATISTIC(NumIndexSplit, "Number of loop index split");
58STATISTIC(NumIndexSplitRemoved, "Number of loops eliminated by loop index split");
59STATISTIC(NumRestrictBounds, "Number of loop iteration space restricted");
Devang Patelfee76bd2007-08-07 00:25:56 +000060
61namespace {
62
63 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
64
65 public:
66 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000067 LoopIndexSplit() : LoopPass(&ID) {}
Devang Patelfee76bd2007-08-07 00:25:56 +000068
69 // Index split Loop L. Return true if loop is split.
70 bool runOnLoop(Loop *L, LPPassManager &LPM);
71
72 void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequired<ScalarEvolution>();
74 AU.addPreserved<ScalarEvolution>();
75 AU.addRequiredID(LCSSAID);
76 AU.addPreservedID(LCSSAID);
Devang Patel423c8b22007-08-10 18:07:13 +000077 AU.addRequired<LoopInfo>();
Devang Patelfee76bd2007-08-07 00:25:56 +000078 AU.addPreserved<LoopInfo>();
79 AU.addRequiredID(LoopSimplifyID);
80 AU.addPreservedID(LoopSimplifyID);
Devang Patel9704fcf2007-08-08 22:25:28 +000081 AU.addRequired<DominatorTree>();
Devang Patel5b8ec612007-08-15 03:31:47 +000082 AU.addRequired<DominanceFrontier>();
Devang Patel787a7132007-08-08 21:39:47 +000083 AU.addPreserved<DominatorTree>();
84 AU.addPreserved<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +000085 }
86
87 private:
Devang Patel38310052008-12-04 21:38:42 +000088 /// processOneIterationLoop -- Eliminate loop if loop body is executed
89 /// only once. For example,
90 /// for (i = 0; i < N; ++i) {
91 /// if ( i == X) {
92 /// ...
93 /// }
94 /// }
95 ///
96 bool processOneIterationLoop();
Devang Patel71554b82007-08-08 21:02:17 +000097
Devang Patel38310052008-12-04 21:38:42 +000098 // -- Routines used by updateLoopIterationSpace();
Devang Patelc9d123d2007-08-09 01:39:01 +000099
Devang Patel38310052008-12-04 21:38:42 +0000100 /// updateLoopIterationSpace -- Update loop's iteration space if loop
101 /// body is executed for certain IV range only. For example,
102 ///
103 /// for (i = 0; i < N; ++i) {
104 /// if ( i > A && i < B) {
105 /// ...
106 /// }
107 /// }
Devang Patel042b8772008-12-08 17:07:24 +0000108 /// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000109 ///
110 bool updateLoopIterationSpace();
Devang Patel71554b82007-08-08 21:02:17 +0000111
Devang Patel38310052008-12-04 21:38:42 +0000112 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
113 /// with a loop invariant value. Update loop's lower and upper bound based on
114 /// the loop invariant value.
115 bool restrictLoopBound(ICmpInst &Op);
Devang Patel4a69da92007-08-25 00:56:38 +0000116
Devang Patel38310052008-12-04 21:38:42 +0000117 // --- Routines used by splitLoop(). --- /
Devang Patel4a69da92007-08-25 00:56:38 +0000118
Devang Patel38310052008-12-04 21:38:42 +0000119 bool splitLoop();
Devang Patel4a69da92007-08-25 00:56:38 +0000120
Devang Patel38310052008-12-04 21:38:42 +0000121 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by
122 /// DeadBB. This routine is used to remove split condition's dead branch,
123 /// dominated by DeadBB. LiveBB dominates split conidition's other branch.
Devang Patela6a86632007-08-14 18:35:57 +0000124 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel38310052008-12-04 21:38:42 +0000125
126 /// moveExitCondition - Move exit condition EC into split condition block.
127 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
128 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
129 PHINode *IV, Instruction *IVAdd, Loop *LP,
130 unsigned);
131
Devang Pateld79faee2007-08-25 02:39:24 +0000132 /// updatePHINodes - CFG has been changed.
133 /// Before
134 /// - ExitBB's single predecessor was Latch
135 /// - Latch's second successor was Header
136 /// Now
137 /// - ExitBB's single predecessor was Header
138 /// - Latch's one and only successor was Header
139 ///
140 /// Update ExitBB PHINodes' to reflect this change.
141 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
142 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000143 PHINode *IV, Instruction *IVIncrement, Loop *LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000144
Devang Patel38310052008-12-04 21:38:42 +0000145 // --- Utility routines --- /
Devang Pateld79faee2007-08-25 02:39:24 +0000146
Devang Patel38310052008-12-04 21:38:42 +0000147 /// cleanBlock - A block is considered clean if all non terminal
148 /// instructions are either PHINodes or IV based values.
149 bool cleanBlock(BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000150
Devang Patel042b8772008-12-08 17:07:24 +0000151 /// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000152 /// IV based value is less than the loop invariant then return the loop
153 /// invariant. Otherwise return NULL.
154 Value * IVisLT(ICmpInst &Op);
155
Devang Patel042b8772008-12-08 17:07:24 +0000156 /// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000157 /// IV based value is less than or equal to the loop invariant then
158 /// return the loop invariant. Otherwise return NULL.
159 Value * IVisLE(ICmpInst &Op);
160
Devang Patel042b8772008-12-08 17:07:24 +0000161 /// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000162 /// IV based value is greater than the loop invariant then return the loop
163 /// invariant. Otherwise return NULL.
164 Value * IVisGT(ICmpInst &Op);
165
Devang Patel042b8772008-12-08 17:07:24 +0000166 /// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000167 /// IV based value is greater than or equal to the loop invariant then
168 /// return the loop invariant. Otherwise return NULL.
169 Value * IVisGE(ICmpInst &Op);
Devang Patelbacf5192007-08-10 00:33:50 +0000170
Devang Patelfee76bd2007-08-07 00:25:56 +0000171 private:
172
Devang Patel38310052008-12-04 21:38:42 +0000173 // Current Loop information.
Devang Patelfee76bd2007-08-07 00:25:56 +0000174 Loop *L;
Devang Patel423c8b22007-08-10 18:07:13 +0000175 LPPassManager *LPM;
176 LoopInfo *LI;
Devang Patelfee76bd2007-08-07 00:25:56 +0000177 ScalarEvolution *SE;
Devang Patel9704fcf2007-08-08 22:25:28 +0000178 DominatorTree *DT;
Devang Patelfc4c5f82007-08-13 22:13:24 +0000179 DominanceFrontier *DF;
Devang Patelbacf5192007-08-10 00:33:50 +0000180
Devang Patelbacf5192007-08-10 00:33:50 +0000181 PHINode *IndVar;
Devang Patelbacf5192007-08-10 00:33:50 +0000182 ICmpInst *ExitCondition;
Devang Patel38310052008-12-04 21:38:42 +0000183 ICmpInst *SplitCondition;
184 Value *IVStartValue;
185 Value *IVExitValue;
186 Instruction *IVIncrement;
187 SmallPtrSet<Value *, 4> IVBasedValues;
Devang Patelfee76bd2007-08-07 00:25:56 +0000188 };
Devang Patelfee76bd2007-08-07 00:25:56 +0000189}
190
Dan Gohman844731a2008-05-13 00:00:25 +0000191char LoopIndexSplit::ID = 0;
192static RegisterPass<LoopIndexSplit>
193X("loop-index-split", "Index Split Loops");
194
Daniel Dunbar394f0442008-10-22 23:32:42 +0000195Pass *llvm::createLoopIndexSplitPass() {
Devang Patelfee76bd2007-08-07 00:25:56 +0000196 return new LoopIndexSplit();
197}
198
199// Index split Loop L. Return true if loop is split.
Devang Patel423c8b22007-08-10 18:07:13 +0000200bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000201 L = IncomingLoop;
Devang Patel423c8b22007-08-10 18:07:13 +0000202 LPM = &LPM_Ref;
Devang Patel71554b82007-08-08 21:02:17 +0000203
Devang Patel3fe4f212007-08-15 02:14:55 +0000204 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel4e8061c2007-08-14 23:53:57 +0000205 if (!L->getSubLoops().empty())
206 return false;
207
Devang Patelfee76bd2007-08-07 00:25:56 +0000208 SE = &getAnalysis<ScalarEvolution>();
Devang Patel9704fcf2007-08-08 22:25:28 +0000209 DT = &getAnalysis<DominatorTree>();
Devang Patel423c8b22007-08-10 18:07:13 +0000210 LI = &getAnalysis<LoopInfo>();
Devang Patel7375bb92007-08-15 03:34:53 +0000211 DF = &getAnalysis<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +0000212
Devang Patel38310052008-12-04 21:38:42 +0000213 // Initialize loop data.
214 IndVar = L->getCanonicalInductionVariable();
215 if (!IndVar) return false;
Devang Patelbacf5192007-08-10 00:33:50 +0000216
Devang Patel38310052008-12-04 21:38:42 +0000217 bool P1InLoop = L->contains(IndVar->getIncomingBlock(1));
218 IVStartValue = IndVar->getIncomingValue(!P1InLoop);
219 IVIncrement = dyn_cast<Instruction>(IndVar->getIncomingValue(P1InLoop));
220 if (!IVIncrement) return false;
Devang Patel71554b82007-08-08 21:02:17 +0000221
Devang Patel38310052008-12-04 21:38:42 +0000222 IVBasedValues.clear();
223 IVBasedValues.insert(IndVar);
224 IVBasedValues.insert(IVIncrement);
Devang Patelbacf5192007-08-10 00:33:50 +0000225 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Devang Patel38310052008-12-04 21:38:42 +0000226 I != E; ++I)
227 for(BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
228 BI != BE; ++BI) {
229 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BI))
230 if (BO != IVIncrement
231 && (BO->getOpcode() == Instruction::Add
232 || BO->getOpcode() == Instruction::Sub))
233 if (IVBasedValues.count(BO->getOperand(0))
234 && L->isLoopInvariant(BO->getOperand(1)))
235 IVBasedValues.insert(BO);
236 }
Devang Patelbacf5192007-08-10 00:33:50 +0000237
Devang Patel38310052008-12-04 21:38:42 +0000238 // Reject loop if loop exit condition is not suitable.
Dan Gohmanc8332462009-02-12 18:08:24 +0000239 BasicBlock *ExitingBlock = L->getExitingBlock();
240 if (!ExitingBlock)
Devang Patel38310052008-12-04 21:38:42 +0000241 return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000242 BranchInst *EBR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel38310052008-12-04 21:38:42 +0000243 if (!EBR) return false;
244 ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
245 if (!ExitCondition) return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000246 if (ExitingBlock != L->getLoopLatch()) return false;
Devang Patel38310052008-12-04 21:38:42 +0000247 IVExitValue = ExitCondition->getOperand(1);
248 if (!L->isLoopInvariant(IVExitValue))
249 IVExitValue = ExitCondition->getOperand(0);
250 if (!L->isLoopInvariant(IVExitValue))
251 return false;
Devang Patela5e27f82008-07-09 00:12:01 +0000252
253 // If start value is more then exit value where induction variable
254 // increments by 1 then we are potentially dealing with an infinite loop.
255 // Do not index split this loop.
Devang Patel38310052008-12-04 21:38:42 +0000256 if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
257 if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
258 if (SV->getSExtValue() > EV->getSExtValue())
259 return false;
Devang Patelc9d123d2007-08-09 01:39:01 +0000260
Devang Patel38310052008-12-04 21:38:42 +0000261 if (processOneIterationLoop())
262 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000263
Devang Patel38310052008-12-04 21:38:42 +0000264 if (updateLoopIterationSpace())
265 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000266
Devang Patel38310052008-12-04 21:38:42 +0000267 if (splitLoop())
268 return true;
Devang Pateld35ed2c2007-09-11 00:42:56 +0000269
270 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000271}
272
Devang Patel38310052008-12-04 21:38:42 +0000273// --- Helper routines ---
274// isUsedOutsideLoop - Returns true iff V is used outside the loop L.
275static bool isUsedOutsideLoop(Value *V, Loop *L) {
276 for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
277 if (!L->contains(cast<Instruction>(*UI)->getParent()))
278 return true;
279 return false;
280}
Devang Patelfee76bd2007-08-07 00:25:56 +0000281
Devang Patel38310052008-12-04 21:38:42 +0000282// Return V+1
283static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
284 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
285 return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
286}
Devang Patelfee76bd2007-08-07 00:25:56 +0000287
Devang Patel38310052008-12-04 21:38:42 +0000288// Return V-1
289static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
290 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
291 return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
292}
Devang Patelfee76bd2007-08-07 00:25:56 +0000293
Devang Patel38310052008-12-04 21:38:42 +0000294// Return min(V1, V1)
295static Value *getMin(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
296
297 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
298 V1, V2, "lsp", InsertPt);
299 return SelectInst::Create(C, V1, V2, "lsp", InsertPt);
300}
Devang Patelfee76bd2007-08-07 00:25:56 +0000301
Devang Patel38310052008-12-04 21:38:42 +0000302// Return max(V1, V2)
303static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
304
305 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
306 V1, V2, "lsp", InsertPt);
307 return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
308}
Devang Patel968eee22007-09-19 00:15:16 +0000309
Devang Patel38310052008-12-04 21:38:42 +0000310/// processOneIterationLoop -- Eliminate loop if loop body is executed
311/// only once. For example,
312/// for (i = 0; i < N; ++i) {
313/// if ( i == X) {
314/// ...
315/// }
316/// }
317///
318bool LoopIndexSplit::processOneIterationLoop() {
319 SplitCondition = NULL;
Devang Patel84ef08b2007-09-19 00:11:01 +0000320 BasicBlock *Latch = L->getLoopLatch();
Devang Patel38310052008-12-04 21:38:42 +0000321 BasicBlock *Header = L->getHeader();
322 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
323 if (!BR) return false;
324 if (!isa<BranchInst>(Latch->getTerminator())) return false;
325 if (BR->isUnconditional()) return false;
326 SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
327 if (!SplitCondition) return false;
328 if (SplitCondition == ExitCondition) return false;
329 if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
330 if (BR->getOperand(1) != Latch) return false;
331 if (!IVBasedValues.count(SplitCondition->getOperand(0))
332 && !IVBasedValues.count(SplitCondition->getOperand(1)))
Devang Patel84ef08b2007-09-19 00:11:01 +0000333 return false;
334
Devang Patel38310052008-12-04 21:38:42 +0000335 // If IV is used outside the loop then this loop traversal is required.
336 // FIXME: Calculate and use last IV value.
337 if (isUsedOutsideLoop(IVIncrement, L))
338 return false;
339
340 // If BR operands are not IV or not loop invariants then skip this loop.
341 Value *OPV = SplitCondition->getOperand(0);
342 Value *SplitValue = SplitCondition->getOperand(1);
343 if (!L->isLoopInvariant(SplitValue)) {
344 Value *T = SplitValue;
345 SplitValue = OPV;
346 OPV = T;
347 }
348 if (!L->isLoopInvariant(SplitValue))
349 return false;
350 Instruction *OPI = dyn_cast<Instruction>(OPV);
351 if (!OPI) return false;
352 if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
353 return false;
354
355 if (!cleanBlock(Header))
356 return false;
357
358 if (!cleanBlock(Latch))
359 return false;
360
361 // If the merge point for BR is not loop latch then skip this loop.
362 if (BR->getSuccessor(0) != Latch) {
363 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
364 assert (DF0 != DF->end() && "Unable to find dominance frontier");
365 if (!DF0->second.count(Latch))
366 return false;
367 }
368
369 if (BR->getSuccessor(1) != Latch) {
370 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
371 assert (DF1 != DF->end() && "Unable to find dominance frontier");
372 if (!DF1->second.count(Latch))
373 return false;
374 }
375
376 // Now, Current loop L contains compare instruction
377 // that compares induction variable, IndVar, against loop invariant. And
378 // entire (i.e. meaningful) loop body is dominated by this compare
379 // instruction. In such case eliminate
380 // loop structure surrounding this loop body. For example,
381 // for (int i = start; i < end; ++i) {
382 // if ( i == somevalue) {
383 // loop_body
384 // }
385 // }
386 // can be transformed into
387 // if (somevalue >= start && somevalue < end) {
388 // i = somevalue;
389 // loop_body
390 // }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000391
Devang Patelebc5fea2007-08-20 20:49:01 +0000392 // Replace index variable with split value in loop body. Loop body is executed
393 // only when index variable is equal to split value.
Devang Patel38310052008-12-04 21:38:42 +0000394 IndVar->replaceAllUsesWith(SplitValue);
Devang Patelfee76bd2007-08-07 00:25:56 +0000395
Devang Patelfee76bd2007-08-07 00:25:56 +0000396 // Replace split condition in header.
397 // Transform
398 // SplitCondition : icmp eq i32 IndVar, SplitValue
399 // into
400 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000401 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000402 // and i32 c1, c2
Devang Patel38310052008-12-04 21:38:42 +0000403 Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ?
Devang Patelfee76bd2007-08-07 00:25:56 +0000404 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patel38310052008-12-04 21:38:42 +0000405 SplitValue, IVStartValue, "lisplit", BR);
406
407 CmpInst::Predicate C2P = ExitCondition->getPredicate();
408 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
409 if (LatchBR->getOperand(0) != Header)
410 C2P = CmpInst::getInversePredicate(C2P);
411 Instruction *C2 = new ICmpInst(C2P, SplitValue, IVExitValue, "lisplit", BR);
412 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
413
414 SplitCondition->replaceAllUsesWith(NSplitCond);
415 SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000416
Devang Patelfc19fbd2008-10-10 22:02:57 +0000417 // Remove Latch to Header edge.
418 BasicBlock *LatchSucc = NULL;
419 Header->removePredecessor(Latch);
420 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
421 SI != E; ++SI) {
422 if (Header != *SI)
423 LatchSucc = *SI;
424 }
Devang Patel38310052008-12-04 21:38:42 +0000425 LatchBR->setUnconditionalDest(LatchSucc);
Devang Patelfc19fbd2008-10-10 22:02:57 +0000426
Devang Patel38310052008-12-04 21:38:42 +0000427 // Remove IVIncrement
428 IVIncrement->replaceAllUsesWith(UndefValue::get(IVIncrement->getType()));
429 IVIncrement->eraseFromParent();
430
Devang Patel423c8b22007-08-10 18:07:13 +0000431 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000432
433 // Update Dominator Info.
434 // Only CFG change done is to remove Latch to Header edge. This
435 // does not change dominator tree because Latch did not dominate
436 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000437 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000438 DominanceFrontier::iterator HeaderDF = DF->find(Header);
439 if (HeaderDF != DF->end())
440 DF->removeFromFrontier(HeaderDF, Header);
441
442 DominanceFrontier::iterator LatchDF = DF->find(Latch);
443 if (LatchDF != DF->end())
444 DF->removeFromFrontier(LatchDF, Header);
445 }
Devang Patel38310052008-12-04 21:38:42 +0000446
447 ++NumIndexSplitRemoved;
Devang Patelfee76bd2007-08-07 00:25:56 +0000448 return true;
449}
450
Devang Patel38310052008-12-04 21:38:42 +0000451/// restrictLoopBound - Op dominates loop body. Op compares an IV based value
452/// with a loop invariant value. Update loop's lower and upper bound based on
453/// the loop invariant value.
454bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
455 bool Sign = Op.isSignedPredicate();
456 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
Devang Patelfee76bd2007-08-07 00:25:56 +0000457
Devang Patel38310052008-12-04 21:38:42 +0000458 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
459 BranchInst *EBR =
460 cast<BranchInst>(ExitCondition->getParent()->getTerminator());
461 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
462 BasicBlock *T = EBR->getSuccessor(0);
463 EBR->setSuccessor(0, EBR->getSuccessor(1));
464 EBR->setSuccessor(1, T);
Devang Patelfee76bd2007-08-07 00:25:56 +0000465 }
466
Devang Patel38310052008-12-04 21:38:42 +0000467 // New upper and lower bounds.
Devang Patel453a8442007-09-25 17:31:19 +0000468 Value *NLB = NULL;
Devang Patel38310052008-12-04 21:38:42 +0000469 Value *NUB = NULL;
470 if (Value *V = IVisLT(Op)) {
471 // Restrict upper bound.
472 if (IVisLE(*ExitCondition))
473 V = getMinusOne(V, Sign, PHTerm);
474 NUB = getMin(V, IVExitValue, Sign, PHTerm);
475 } else if (Value *V = IVisLE(Op)) {
476 // Restrict upper bound.
477 if (IVisLT(*ExitCondition))
478 V = getPlusOne(V, Sign, PHTerm);
479 NUB = getMin(V, IVExitValue, Sign, PHTerm);
480 } else if (Value *V = IVisGT(Op)) {
481 // Restrict lower bound.
482 V = getPlusOne(V, Sign, PHTerm);
483 NLB = getMax(V, IVStartValue, Sign, PHTerm);
484 } else if (Value *V = IVisGE(Op))
485 // Restrict lower bound.
486 NLB = getMax(V, IVStartValue, Sign, PHTerm);
Devang Patel453a8442007-09-25 17:31:19 +0000487
Devang Patel38310052008-12-04 21:38:42 +0000488 if (!NLB && !NUB)
489 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000490
491 if (NLB) {
Devang Patel38310052008-12-04 21:38:42 +0000492 unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
Devang Patel453a8442007-09-25 17:31:19 +0000493 IndVar->setIncomingValue(i, NLB);
494 }
495
496 if (NUB) {
Devang Patel38310052008-12-04 21:38:42 +0000497 unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
498 ExitCondition->setOperand(i, NUB);
Devang Patel453a8442007-09-25 17:31:19 +0000499 }
Devang Patel38310052008-12-04 21:38:42 +0000500 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000501}
Devang Patel38310052008-12-04 21:38:42 +0000502
503/// updateLoopIterationSpace -- Update loop's iteration space if loop
504/// body is executed for certain IV range only. For example,
505///
506/// for (i = 0; i < N; ++i) {
507/// if ( i > A && i < B) {
508/// ...
509/// }
510/// }
Devang Patel042b8772008-12-08 17:07:24 +0000511/// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000512///
513bool LoopIndexSplit::updateLoopIterationSpace() {
514 SplitCondition = NULL;
515 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
516 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
517 return false;
518 BasicBlock *Latch = L->getLoopLatch();
Devang Patel5279d062007-09-17 20:39:48 +0000519 BasicBlock *Header = L->getHeader();
Devang Patel38310052008-12-04 21:38:42 +0000520 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
521 if (!BR) return false;
522 if (!isa<BranchInst>(Latch->getTerminator())) return false;
523 if (BR->isUnconditional()) return false;
524 BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
525 if (!AND) return false;
526 if (AND->getOpcode() != Instruction::And) return false;
527 ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
528 ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
529 if (!Op0 || !Op1)
530 return false;
531 IVBasedValues.insert(AND);
532 IVBasedValues.insert(Op0);
533 IVBasedValues.insert(Op1);
534 if (!cleanBlock(Header)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000535 BasicBlock *ExitingBlock = ExitCondition->getParent();
Devang Patel38310052008-12-04 21:38:42 +0000536 if (!cleanBlock(ExitingBlock)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000537
Devang Patel38310052008-12-04 21:38:42 +0000538 // Verify that loop exiting block has only two predecessor, where one pred
Devang Patel453a8442007-09-25 17:31:19 +0000539 // is split condition block. The other predecessor will become exiting block's
540 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
541 // more then two predecessors. This requires extra work in updating dominator
542 // information.
543 BasicBlock *ExitingBBPred = NULL;
544 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
545 PI != PE; ++PI) {
546 BasicBlock *BB = *PI;
Devang Patel38310052008-12-04 21:38:42 +0000547 if (Header == BB)
Devang Patel453a8442007-09-25 17:31:19 +0000548 continue;
549 if (ExitingBBPred)
550 return false;
551 else
552 ExitingBBPred = BB;
553 }
Devang Patel453a8442007-09-25 17:31:19 +0000554
Devang Patel38310052008-12-04 21:38:42 +0000555 if (!restrictLoopBound(*Op0))
556 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000557
Devang Patel38310052008-12-04 21:38:42 +0000558 if (!restrictLoopBound(*Op1))
559 return false;
560
561 // Update CFG.
562 if (BR->getSuccessor(0) == ExitingBlock)
563 BR->setUnconditionalDest(BR->getSuccessor(1));
Devang Patel453a8442007-09-25 17:31:19 +0000564 else
Devang Patel38310052008-12-04 21:38:42 +0000565 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel453a8442007-09-25 17:31:19 +0000566
Devang Patel38310052008-12-04 21:38:42 +0000567 AND->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000568 if (Op0->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000569 Op0->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000570 if (Op1->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000571 Op1->eraseFromParent();
Devang Patel453a8442007-09-25 17:31:19 +0000572
573 // Update domiantor info. Now, ExitingBlock has only one predecessor,
574 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
575 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
Devang Patel38310052008-12-04 21:38:42 +0000576
577 BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
578 if (L->contains(ExitBlock))
579 ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
580
581 // If ExitingBlock is a member of the loop basic blocks' DF list then
582 // replace ExitingBlock with header and exit block in the DF list
583 DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
Devang Patel453a8442007-09-25 17:31:19 +0000584 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
585 I != E; ++I) {
586 BasicBlock *BB = *I;
587 if (BB == Header || BB == ExitingBlock)
588 continue;
589 DominanceFrontier::iterator BBDF = DF->find(BB);
590 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
591 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
592 while (DomSetI != DomSetE) {
593 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
594 ++DomSetI;
595 BasicBlock *DFBB = *CurrentItr;
596 if (DFBB == ExitingBlock) {
597 BBDF->second.erase(DFBB);
Devang Patel38310052008-12-04 21:38:42 +0000598 for (DominanceFrontier::DomSetType::iterator
599 EBI = ExitingBlockDF->second.begin(),
600 EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI)
601 BBDF->second.insert(*EBI);
Devang Patel453a8442007-09-25 17:31:19 +0000602 }
603 }
604 }
Devang Patel38310052008-12-04 21:38:42 +0000605 NumRestrictBounds++;
Devang Patel1c013502007-09-25 17:43:08 +0000606 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000607}
608
Devang Patela6a86632007-08-14 18:35:57 +0000609/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
610/// This routine is used to remove split condition's dead branch, dominated by
611/// DeadBB. LiveBB dominates split conidition's other branch.
612void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
613 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +0000614
Devang Patel5b8ec612007-08-15 03:31:47 +0000615 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +0000616 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +0000617 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
618 if (DeadBBDF != DF->end()) {
619 SmallVector<BasicBlock *, 8> PredBlocks;
620
621 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
622 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
Devang Patel38310052008-12-04 21:38:42 +0000623 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI)
624 {
Devang Patel5b8ec612007-08-15 03:31:47 +0000625 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +0000626 FrontierBBs.push_back(FrontierBB);
627
Devang Patel5b8ec612007-08-15 03:31:47 +0000628 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
629 PredBlocks.clear();
630 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
631 PI != PE; ++PI) {
632 BasicBlock *P = *PI;
633 if (P == DeadBB || DT->dominates(DeadBB, P))
634 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +0000635 }
Devang Patel96bf5242007-08-17 21:59:16 +0000636
Devang Patel5b8ec612007-08-15 03:31:47 +0000637 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
638 FBI != FBE; ++FBI) {
639 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
640 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
641 PE = PredBlocks.end(); PI != PE; ++PI) {
642 BasicBlock *P = *PI;
643 PN->removeIncomingValue(P);
644 }
645 }
646 else
647 break;
Devang Patel96bf5242007-08-17 21:59:16 +0000648 }
Devang Patel98147a32007-08-12 07:02:51 +0000649 }
Devang Patel98147a32007-08-12 07:02:51 +0000650 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000651
652 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
653 SmallVector<BasicBlock *, 32> WorkList;
654 DomTreeNode *DN = DT->getNode(DeadBB);
655 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
656 E = df_end(DN); DI != E; ++DI) {
657 BasicBlock *BB = DI->getBlock();
658 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +0000659 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +0000660 }
661
662 while (!WorkList.empty()) {
663 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
664 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +0000665 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +0000666 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +0000667 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +0000668 I->replaceAllUsesWith(UndefValue::get(I->getType()));
669 I->eraseFromParent();
670 }
671 LPM->deleteSimpleAnalysisValue(BB, LP);
672 DT->eraseNode(BB);
673 DF->removeBlock(BB);
674 LI->removeBlock(BB);
675 BB->eraseFromParent();
676 }
Devang Patel96bf5242007-08-17 21:59:16 +0000677
678 // Update Frontier BBs' dominator info.
679 while (!FrontierBBs.empty()) {
680 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
681 BasicBlock *NewDominator = FBB->getSinglePredecessor();
682 if (!NewDominator) {
683 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
684 NewDominator = *PI;
685 ++PI;
686 if (NewDominator != LiveBB) {
687 for(; PI != PE; ++PI) {
688 BasicBlock *P = *PI;
689 if (P == LiveBB) {
690 NewDominator = LiveBB;
691 break;
692 }
693 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
694 }
695 }
696 }
697 assert (NewDominator && "Unable to fix dominator info.");
698 DT->changeImmediateDominator(FBB, NewDominator);
699 DF->changeImmediateDominator(FBB, NewDominator, DT);
700 }
701
Devang Patel98147a32007-08-12 07:02:51 +0000702}
703
Devang Pateld79faee2007-08-25 02:39:24 +0000704// moveExitCondition - Move exit condition EC into split condition block CondBB.
705void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
Devang Patel38310052008-12-04 21:38:42 +0000706 BasicBlock *ExitBB, ICmpInst *EC,
707 ICmpInst *SC, PHINode *IV,
708 Instruction *IVAdd, Loop *LP,
709 unsigned ExitValueNum) {
Devang Pateld79faee2007-08-25 02:39:24 +0000710
711 BasicBlock *ExitingBB = EC->getParent();
712 Instruction *CurrentBR = CondBB->getTerminator();
713
714 // Move exit condition into split condition block.
715 EC->moveBefore(CurrentBR);
716 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
717
718 // Move exiting block's branch into split condition block. Update its branch
719 // destination.
720 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
721 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +0000722 BasicBlock *OrigDestBB = NULL;
723 if (ExitingBR->getSuccessor(0) == ExitBB) {
724 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +0000725 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000726 }
727 else {
728 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +0000729 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000730 }
Devang Pateld79faee2007-08-25 02:39:24 +0000731
732 // Remove split condition and current split condition branch.
733 SC->eraseFromParent();
734 CurrentBR->eraseFromParent();
735
Devang Patel23067df2008-02-13 22:06:36 +0000736 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +0000737 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +0000738
739 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +0000740 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000741
742 // Fix dominator info.
743 // ExitBB is now dominated by CondBB
744 DT->changeImmediateDominator(ExitBB, CondBB);
745 DF->changeImmediateDominator(ExitBB, CondBB, DT);
746
747 // Basicblocks dominated by ActiveBB may have ExitingBB or
748 // a basic block outside the loop in their DF list. If so,
749 // replace it with CondBB.
750 DomTreeNode *Node = DT->getNode(ActiveBB);
751 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
752 DI != DE; ++DI) {
753 BasicBlock *BB = DI->getBlock();
754 DominanceFrontier::iterator BBDF = DF->find(BB);
755 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
756 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
757 while (DomSetI != DomSetE) {
758 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
759 ++DomSetI;
760 BasicBlock *DFBB = *CurrentItr;
761 if (DFBB == ExitingBB || !L->contains(DFBB)) {
762 BBDF->second.erase(DFBB);
763 BBDF->second.insert(CondBB);
764 }
765 }
766 }
767}
768
769/// updatePHINodes - CFG has been changed.
770/// Before
771/// - ExitBB's single predecessor was Latch
772/// - Latch's second successor was Header
773/// Now
Devang Patel82ada542008-02-08 22:49:13 +0000774/// - ExitBB's single predecessor is Header
775/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +0000776///
777/// Update ExitBB PHINodes' to reflect this change.
778void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
779 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000780 PHINode *IV, Instruction *IVIncrement,
781 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +0000782
783 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000784 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +0000785 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000786 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +0000787 if (!PN)
788 break;
789
790 Value *V = PN->getIncomingValueForBlock(Latch);
791 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +0000792 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
793 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +0000794 Value *NewV = NULL;
795 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +0000796 UI != E; ++UI)
797 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +0000798 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +0000799 NewV = U;
800 break;
801 }
802
Devang Patel60a12902008-03-24 20:16:14 +0000803 // Add incoming value from header only if PN has any use inside the loop.
804 if (NewV)
805 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +0000806
807 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
808 // If this instruction is IVIncrement then IV is new incoming value
809 // from header otherwise this instruction must be incoming value from
810 // header because loop is in LCSSA form.
811 if (PHI == IVIncrement)
812 PN->addIncoming(IV, Header);
813 else
814 PN->addIncoming(V, Header);
815 } else
816 // Otherwise this is an incoming value from header because loop is in
817 // LCSSA form.
818 PN->addIncoming(V, Header);
819
820 // Remove incoming value from Latch.
821 PN->removeIncomingValue(Latch);
822 }
823}
Devang Patel38310052008-12-04 21:38:42 +0000824
825bool LoopIndexSplit::splitLoop() {
826 SplitCondition = NULL;
827 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
828 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
829 return false;
830 BasicBlock *Header = L->getHeader();
831 BasicBlock *Latch = L->getLoopLatch();
832 BranchInst *SBR = NULL; // Split Condition Branch
833 BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
834 // If Exiting block includes loop variant instructions then this
835 // loop may not be split safely.
836 BasicBlock *ExitingBlock = ExitCondition->getParent();
837 if (!cleanBlock(ExitingBlock)) return false;
838
839 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
840 I != E; ++I) {
841 BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
842 if (!BR || BR->isUnconditional()) continue;
843 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
844 if (!CI || CI == ExitCondition
845 || CI->getPredicate() == ICmpInst::ICMP_NE
846 || CI->getPredicate() == ICmpInst::ICMP_EQ)
847 continue;
848
849 // Unable to handle triangle loops at the moment.
850 // In triangle loop, split condition is in header and one of the
851 // the split destination is loop latch. If split condition is EQ
852 // then such loops are already handle in processOneIterationLoop().
853 if (Header == (*I)
854 && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
855 continue;
856
857 // If the block does not dominate the latch then this is not a diamond.
858 // Such loop may not benefit from index split.
859 if (!DT->dominates((*I), Latch))
860 continue;
861
862 // If split condition branches heads do not have single predecessor,
863 // SplitCondBlock, then is not possible to remove inactive branch.
864 if (!BR->getSuccessor(0)->getSinglePredecessor()
865 || !BR->getSuccessor(1)->getSinglePredecessor())
866 return false;
867
868 // If the merge point for BR is not loop latch then skip this condition.
869 if (BR->getSuccessor(0) != Latch) {
870 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
871 assert (DF0 != DF->end() && "Unable to find dominance frontier");
872 if (!DF0->second.count(Latch))
873 continue;
874 }
875
876 if (BR->getSuccessor(1) != Latch) {
877 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
878 assert (DF1 != DF->end() && "Unable to find dominance frontier");
879 if (!DF1->second.count(Latch))
880 continue;
881 }
882 SplitCondition = CI;
883 SBR = BR;
884 break;
885 }
886
887 if (!SplitCondition)
888 return false;
889
890 // If the predicate sign does not match then skip.
891 if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
892 return false;
893
894 unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
895 unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
896 Value *SplitValue = SplitCondition->getOperand(SVOpNum);
897 if (!L->isLoopInvariant(SplitValue))
898 return false;
899 if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
900 return false;
901
902 // Normalize loop conditions so that it is easier to calculate new loop
903 // bounds.
904 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
905 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
906 BasicBlock *T = EBR->getSuccessor(0);
907 EBR->setSuccessor(0, EBR->getSuccessor(1));
908 EBR->setSuccessor(1, T);
909 }
910
911 if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
912 SplitCondition->setPredicate(SplitCondition->getInversePredicate());
913 BasicBlock *T = SBR->getSuccessor(0);
914 SBR->setSuccessor(0, SBR->getSuccessor(1));
915 SBR->setSuccessor(1, T);
916 }
917
918 //[*] Calculate new loop bounds.
919 Value *AEV = SplitValue;
920 Value *BSV = SplitValue;
921 bool Sign = SplitCondition->isSignedPredicate();
922 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
923
924 if (IVisLT(*ExitCondition)) {
925 if (IVisLT(*SplitCondition)) {
926 /* Do nothing */
927 }
928 else if (IVisLE(*SplitCondition)) {
929 AEV = getPlusOne(SplitValue, Sign, PHTerm);
930 BSV = getPlusOne(SplitValue, Sign, PHTerm);
931 } else {
932 assert (0 && "Unexpected split condition!");
933 }
934 }
935 else if (IVisLE(*ExitCondition)) {
936 if (IVisLT(*SplitCondition)) {
937 AEV = getMinusOne(SplitValue, Sign, PHTerm);
938 }
939 else if (IVisLE(*SplitCondition)) {
940 BSV = getPlusOne(SplitValue, Sign, PHTerm);
941 } else {
942 assert (0 && "Unexpected split condition!");
943 }
944 } else {
945 assert (0 && "Unexpected exit condition!");
946 }
947 AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
948 BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
949
950 // [*] Clone Loop
951 DenseMap<const Value *, Value *> ValueMap;
952 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
953 Loop *ALoop = L;
954
955 // [*] ALoop's exiting edge enters BLoop's header.
956 // ALoop's original exit block becomes BLoop's exit block.
957 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
958 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
959 BranchInst *A_ExitInsn =
960 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
961 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
962 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
963 BasicBlock *B_Header = BLoop->getHeader();
964 if (ALoop->contains(B_ExitBlock)) {
965 B_ExitBlock = A_ExitInsn->getSuccessor(0);
966 A_ExitInsn->setSuccessor(0, B_Header);
967 } else
968 A_ExitInsn->setSuccessor(1, B_Header);
969
970 // [*] Update ALoop's exit value using new exit value.
971 ExitCondition->setOperand(EVOpNum, AEV);
972
973 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
974 // original loop's preheader. Add incoming PHINode values from
975 // ALoop's exiting block. Update BLoop header's domiantor info.
976
977 // Collect inverse map of Header PHINodes.
978 DenseMap<Value *, Value *> InverseMap;
979 for (BasicBlock::iterator BI = ALoop->getHeader()->begin(),
980 BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
981 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
982 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
983 InverseMap[PNClone] = PN;
984 } else
985 break;
986 }
987
988 BasicBlock *A_Preheader = ALoop->getLoopPreheader();
989 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
990 BI != BE; ++BI) {
991 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
992 // Remove incoming value from original preheader.
993 PN->removeIncomingValue(A_Preheader);
994
995 // Add incoming value from A_ExitingBlock.
996 if (PN == B_IndVar)
997 PN->addIncoming(BSV, A_ExitingBlock);
998 else {
999 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1000 Value *V2 = NULL;
1001 // If loop header is also loop exiting block then
1002 // OrigPN is incoming value for B loop header.
1003 if (A_ExitingBlock == ALoop->getHeader())
1004 V2 = OrigPN;
1005 else
1006 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1007 PN->addIncoming(V2, A_ExitingBlock);
1008 }
1009 } else
1010 break;
1011 }
1012
1013 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1014 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1015
1016 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1017 // block. Remove incoming PHINode values from ALoop's exiting block.
1018 // Add new incoming values from BLoop's incoming exiting value.
1019 // Update BLoop exit block's dominator info..
1020 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1021 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1022 BI != BE; ++BI) {
1023 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1024 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1025 B_ExitingBlock);
1026 PN->removeIncomingValue(A_ExitingBlock);
1027 } else
1028 break;
1029 }
1030
1031 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1032 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1033
1034 //[*] Split ALoop's exit edge. This creates a new block which
1035 // serves two purposes. First one is to hold PHINode defnitions
1036 // to ensure that ALoop's LCSSA form. Second use it to act
1037 // as a preheader for BLoop.
1038 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1039
1040 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1041 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1042 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1043 BI != BE; ++BI) {
1044 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1045 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1046 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1047 newPHI->addIncoming(V1, A_ExitingBlock);
1048 A_ExitBlock->getInstList().push_front(newPHI);
1049 PN->removeIncomingValue(A_ExitBlock);
1050 PN->addIncoming(newPHI, A_ExitBlock);
1051 } else
1052 break;
1053 }
1054
1055 //[*] Eliminate split condition's inactive branch from ALoop.
1056 BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1057 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1058 BasicBlock *A_InactiveBranch = NULL;
1059 BasicBlock *A_ActiveBranch = NULL;
1060 A_ActiveBranch = A_BR->getSuccessor(0);
1061 A_InactiveBranch = A_BR->getSuccessor(1);
1062 A_BR->setUnconditionalDest(A_ActiveBranch);
1063 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1064
1065 //[*] Eliminate split condition's inactive branch in from BLoop.
1066 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1067 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1068 BasicBlock *B_InactiveBranch = NULL;
1069 BasicBlock *B_ActiveBranch = NULL;
1070 B_ActiveBranch = B_BR->getSuccessor(1);
1071 B_InactiveBranch = B_BR->getSuccessor(0);
1072 B_BR->setUnconditionalDest(B_ActiveBranch);
1073 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1074
1075 BasicBlock *A_Header = ALoop->getHeader();
1076 if (A_ExitingBlock == A_Header)
1077 return true;
1078
1079 //[*] Move exit condition into split condition block to avoid
1080 // executing dead loop iteration.
1081 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1082 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1083 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1084
1085 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1086 cast<ICmpInst>(SplitCondition), IndVar, IVIncrement,
1087 ALoop, EVOpNum);
1088
1089 moveExitCondition(B_SplitCondBlock, B_ActiveBranch,
1090 B_ExitBlock, B_ExitCondition,
1091 B_SplitCondition, B_IndVar, B_IndVarIncrement,
1092 BLoop, EVOpNum);
1093
1094 NumIndexSplit++;
1095 return true;
1096}
1097
1098/// cleanBlock - A block is considered clean if all non terminal instructions
1099/// are either, PHINodes, IV based.
1100bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1101 Instruction *Terminator = BB->getTerminator();
1102 for(BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1103 BI != BE; ++BI) {
1104 Instruction *I = BI;
1105
1106 if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
Devang Pateld96c60d2009-02-06 06:19:06 +00001107 || I == SplitCondition || IVBasedValues.count(I)
1108 || isa<DbgInfoIntrinsic>(I))
Devang Patel38310052008-12-04 21:38:42 +00001109 continue;
1110
1111 if (I->mayWriteToMemory())
1112 return false;
1113
1114 // I is used only inside this block then it is OK.
1115 bool usedOutsideBB = false;
1116 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1117 UI != UE; ++UI) {
1118 Instruction *U = cast<Instruction>(UI);
1119 if (U->getParent() != BB)
1120 usedOutsideBB = true;
1121 }
1122 if (!usedOutsideBB)
1123 continue;
1124
1125 // Otherwise we have a instruction that may not allow loop spliting.
1126 return false;
1127 }
1128 return true;
1129}
1130
Devang Patel042b8772008-12-08 17:07:24 +00001131/// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001132/// IV based value is less than the loop invariant then return the loop
1133/// invariant. Otherwise return NULL.
1134Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1135 ICmpInst::Predicate P = Op.getPredicate();
1136 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1137 && IVBasedValues.count(Op.getOperand(0))
1138 && L->isLoopInvariant(Op.getOperand(1)))
1139 return Op.getOperand(1);
1140
1141 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1142 && IVBasedValues.count(Op.getOperand(1))
1143 && L->isLoopInvariant(Op.getOperand(0)))
1144 return Op.getOperand(0);
1145
1146 return NULL;
1147}
1148
Devang Patel042b8772008-12-08 17:07:24 +00001149/// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001150/// IV based value is less than or equal to the loop invariant then
1151/// return the loop invariant. Otherwise return NULL.
1152Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1153 ICmpInst::Predicate P = Op.getPredicate();
1154 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1155 && IVBasedValues.count(Op.getOperand(0))
1156 && L->isLoopInvariant(Op.getOperand(1)))
1157 return Op.getOperand(1);
1158
1159 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1160 && IVBasedValues.count(Op.getOperand(1))
1161 && L->isLoopInvariant(Op.getOperand(0)))
1162 return Op.getOperand(0);
1163
1164 return NULL;
1165}
1166
Devang Patel042b8772008-12-08 17:07:24 +00001167/// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001168/// IV based value is greater than the loop invariant then return the loop
1169/// invariant. Otherwise return NULL.
1170Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1171 ICmpInst::Predicate P = Op.getPredicate();
1172 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1173 && IVBasedValues.count(Op.getOperand(0))
1174 && L->isLoopInvariant(Op.getOperand(1)))
1175 return Op.getOperand(1);
1176
1177 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1178 && IVBasedValues.count(Op.getOperand(1))
1179 && L->isLoopInvariant(Op.getOperand(0)))
1180 return Op.getOperand(0);
1181
1182 return NULL;
1183}
1184
Devang Patel042b8772008-12-08 17:07:24 +00001185/// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001186/// IV based value is greater than or equal to the loop invariant then
1187/// return the loop invariant. Otherwise return NULL.
1188Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1189 ICmpInst::Predicate P = Op.getPredicate();
1190 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1191 && IVBasedValues.count(Op.getOperand(0))
1192 && L->isLoopInvariant(Op.getOperand(1)))
1193 return Op.getOperand(1);
1194
1195 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1196 && IVBasedValues.count(Op.getOperand(1))
1197 && L->isLoopInvariant(Op.getOperand(0)))
1198 return Op.getOperand(0);
1199
1200 return NULL;
1201}
1202