blob: f625c13d453b53a7996bd6d614c4bfce3b7d7c36 [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.
239 SmallVector<BasicBlock *, 2> EBs;
240 L->getExitingBlocks(EBs);
241 if (EBs.size() != 1)
242 return false;
243 BranchInst *EBR = dyn_cast<BranchInst>(EBs[0]->getTerminator());
244 if (!EBR) return false;
245 ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
246 if (!ExitCondition) return false;
247 if (EBs[0] != L->getLoopLatch()) return false;
248 IVExitValue = ExitCondition->getOperand(1);
249 if (!L->isLoopInvariant(IVExitValue))
250 IVExitValue = ExitCondition->getOperand(0);
251 if (!L->isLoopInvariant(IVExitValue))
252 return false;
Devang Patela5e27f82008-07-09 00:12:01 +0000253
254 // If start value is more then exit value where induction variable
255 // increments by 1 then we are potentially dealing with an infinite loop.
256 // Do not index split this loop.
Devang Patel38310052008-12-04 21:38:42 +0000257 if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
258 if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
259 if (SV->getSExtValue() > EV->getSExtValue())
260 return false;
Devang Patelc9d123d2007-08-09 01:39:01 +0000261
Devang Patel38310052008-12-04 21:38:42 +0000262 if (processOneIterationLoop())
263 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000264
Devang Patel38310052008-12-04 21:38:42 +0000265 if (updateLoopIterationSpace())
266 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000267
Devang Patel38310052008-12-04 21:38:42 +0000268 if (splitLoop())
269 return true;
Devang Pateld35ed2c2007-09-11 00:42:56 +0000270
271 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000272}
273
Devang Patel38310052008-12-04 21:38:42 +0000274// --- Helper routines ---
275// isUsedOutsideLoop - Returns true iff V is used outside the loop L.
276static bool isUsedOutsideLoop(Value *V, Loop *L) {
277 for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
278 if (!L->contains(cast<Instruction>(*UI)->getParent()))
279 return true;
280 return false;
281}
Devang Patelfee76bd2007-08-07 00:25:56 +0000282
Devang Patel38310052008-12-04 21:38:42 +0000283// Return V+1
284static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
285 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
286 return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
287}
Devang Patelfee76bd2007-08-07 00:25:56 +0000288
Devang Patel38310052008-12-04 21:38:42 +0000289// Return V-1
290static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
291 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
292 return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
293}
Devang Patelfee76bd2007-08-07 00:25:56 +0000294
Devang Patel38310052008-12-04 21:38:42 +0000295// Return min(V1, V1)
296static Value *getMin(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
297
298 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
299 V1, V2, "lsp", InsertPt);
300 return SelectInst::Create(C, V1, V2, "lsp", InsertPt);
301}
Devang Patelfee76bd2007-08-07 00:25:56 +0000302
Devang Patel38310052008-12-04 21:38:42 +0000303// Return max(V1, V2)
304static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
305
306 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
307 V1, V2, "lsp", InsertPt);
308 return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
309}
Devang Patel968eee22007-09-19 00:15:16 +0000310
Devang Patel38310052008-12-04 21:38:42 +0000311/// processOneIterationLoop -- Eliminate loop if loop body is executed
312/// only once. For example,
313/// for (i = 0; i < N; ++i) {
314/// if ( i == X) {
315/// ...
316/// }
317/// }
318///
319bool LoopIndexSplit::processOneIterationLoop() {
320 SplitCondition = NULL;
Devang Patel84ef08b2007-09-19 00:11:01 +0000321 BasicBlock *Latch = L->getLoopLatch();
Devang Patel38310052008-12-04 21:38:42 +0000322 BasicBlock *Header = L->getHeader();
323 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
324 if (!BR) return false;
325 if (!isa<BranchInst>(Latch->getTerminator())) return false;
326 if (BR->isUnconditional()) return false;
327 SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
328 if (!SplitCondition) return false;
329 if (SplitCondition == ExitCondition) return false;
330 if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
331 if (BR->getOperand(1) != Latch) return false;
332 if (!IVBasedValues.count(SplitCondition->getOperand(0))
333 && !IVBasedValues.count(SplitCondition->getOperand(1)))
Devang Patel84ef08b2007-09-19 00:11:01 +0000334 return false;
335
Devang Patel38310052008-12-04 21:38:42 +0000336 // If IV is used outside the loop then this loop traversal is required.
337 // FIXME: Calculate and use last IV value.
338 if (isUsedOutsideLoop(IVIncrement, L))
339 return false;
340
341 // If BR operands are not IV or not loop invariants then skip this loop.
342 Value *OPV = SplitCondition->getOperand(0);
343 Value *SplitValue = SplitCondition->getOperand(1);
344 if (!L->isLoopInvariant(SplitValue)) {
345 Value *T = SplitValue;
346 SplitValue = OPV;
347 OPV = T;
348 }
349 if (!L->isLoopInvariant(SplitValue))
350 return false;
351 Instruction *OPI = dyn_cast<Instruction>(OPV);
352 if (!OPI) return false;
353 if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
354 return false;
355
356 if (!cleanBlock(Header))
357 return false;
358
359 if (!cleanBlock(Latch))
360 return false;
361
362 // If the merge point for BR is not loop latch then skip this loop.
363 if (BR->getSuccessor(0) != Latch) {
364 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
365 assert (DF0 != DF->end() && "Unable to find dominance frontier");
366 if (!DF0->second.count(Latch))
367 return false;
368 }
369
370 if (BR->getSuccessor(1) != Latch) {
371 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
372 assert (DF1 != DF->end() && "Unable to find dominance frontier");
373 if (!DF1->second.count(Latch))
374 return false;
375 }
376
377 // Now, Current loop L contains compare instruction
378 // that compares induction variable, IndVar, against loop invariant. And
379 // entire (i.e. meaningful) loop body is dominated by this compare
380 // instruction. In such case eliminate
381 // loop structure surrounding this loop body. For example,
382 // for (int i = start; i < end; ++i) {
383 // if ( i == somevalue) {
384 // loop_body
385 // }
386 // }
387 // can be transformed into
388 // if (somevalue >= start && somevalue < end) {
389 // i = somevalue;
390 // loop_body
391 // }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000392
Devang Patelebc5fea2007-08-20 20:49:01 +0000393 // Replace index variable with split value in loop body. Loop body is executed
394 // only when index variable is equal to split value.
Devang Patel38310052008-12-04 21:38:42 +0000395 IndVar->replaceAllUsesWith(SplitValue);
Devang Patelfee76bd2007-08-07 00:25:56 +0000396
Devang Patelfee76bd2007-08-07 00:25:56 +0000397 // Replace split condition in header.
398 // Transform
399 // SplitCondition : icmp eq i32 IndVar, SplitValue
400 // into
401 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000402 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000403 // and i32 c1, c2
Devang Patel38310052008-12-04 21:38:42 +0000404 Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ?
Devang Patelfee76bd2007-08-07 00:25:56 +0000405 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patel38310052008-12-04 21:38:42 +0000406 SplitValue, IVStartValue, "lisplit", BR);
407
408 CmpInst::Predicate C2P = ExitCondition->getPredicate();
409 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
410 if (LatchBR->getOperand(0) != Header)
411 C2P = CmpInst::getInversePredicate(C2P);
412 Instruction *C2 = new ICmpInst(C2P, SplitValue, IVExitValue, "lisplit", BR);
413 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
414
415 SplitCondition->replaceAllUsesWith(NSplitCond);
416 SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000417
Devang Patelfc19fbd2008-10-10 22:02:57 +0000418 // Remove Latch to Header edge.
419 BasicBlock *LatchSucc = NULL;
420 Header->removePredecessor(Latch);
421 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
422 SI != E; ++SI) {
423 if (Header != *SI)
424 LatchSucc = *SI;
425 }
Devang Patel38310052008-12-04 21:38:42 +0000426 LatchBR->setUnconditionalDest(LatchSucc);
Devang Patelfc19fbd2008-10-10 22:02:57 +0000427
Devang Patel38310052008-12-04 21:38:42 +0000428 // Remove IVIncrement
429 IVIncrement->replaceAllUsesWith(UndefValue::get(IVIncrement->getType()));
430 IVIncrement->eraseFromParent();
431
Devang Patel423c8b22007-08-10 18:07:13 +0000432 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000433
434 // Update Dominator Info.
435 // Only CFG change done is to remove Latch to Header edge. This
436 // does not change dominator tree because Latch did not dominate
437 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000438 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000439 DominanceFrontier::iterator HeaderDF = DF->find(Header);
440 if (HeaderDF != DF->end())
441 DF->removeFromFrontier(HeaderDF, Header);
442
443 DominanceFrontier::iterator LatchDF = DF->find(Latch);
444 if (LatchDF != DF->end())
445 DF->removeFromFrontier(LatchDF, Header);
446 }
Devang Patel38310052008-12-04 21:38:42 +0000447
448 ++NumIndexSplitRemoved;
Devang Patelfee76bd2007-08-07 00:25:56 +0000449 return true;
450}
451
Devang Patel38310052008-12-04 21:38:42 +0000452/// restrictLoopBound - Op dominates loop body. Op compares an IV based value
453/// with a loop invariant value. Update loop's lower and upper bound based on
454/// the loop invariant value.
455bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
456 bool Sign = Op.isSignedPredicate();
457 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
Devang Patelfee76bd2007-08-07 00:25:56 +0000458
Devang Patel38310052008-12-04 21:38:42 +0000459 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
460 BranchInst *EBR =
461 cast<BranchInst>(ExitCondition->getParent()->getTerminator());
462 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
463 BasicBlock *T = EBR->getSuccessor(0);
464 EBR->setSuccessor(0, EBR->getSuccessor(1));
465 EBR->setSuccessor(1, T);
Devang Patelfee76bd2007-08-07 00:25:56 +0000466 }
467
Devang Patel38310052008-12-04 21:38:42 +0000468 // New upper and lower bounds.
Devang Patel453a8442007-09-25 17:31:19 +0000469 Value *NLB = NULL;
Devang Patel38310052008-12-04 21:38:42 +0000470 Value *NUB = NULL;
471 if (Value *V = IVisLT(Op)) {
472 // Restrict upper bound.
473 if (IVisLE(*ExitCondition))
474 V = getMinusOne(V, Sign, PHTerm);
475 NUB = getMin(V, IVExitValue, Sign, PHTerm);
476 } else if (Value *V = IVisLE(Op)) {
477 // Restrict upper bound.
478 if (IVisLT(*ExitCondition))
479 V = getPlusOne(V, Sign, PHTerm);
480 NUB = getMin(V, IVExitValue, Sign, PHTerm);
481 } else if (Value *V = IVisGT(Op)) {
482 // Restrict lower bound.
483 V = getPlusOne(V, Sign, PHTerm);
484 NLB = getMax(V, IVStartValue, Sign, PHTerm);
485 } else if (Value *V = IVisGE(Op))
486 // Restrict lower bound.
487 NLB = getMax(V, IVStartValue, Sign, PHTerm);
Devang Patel453a8442007-09-25 17:31:19 +0000488
Devang Patel38310052008-12-04 21:38:42 +0000489 if (!NLB && !NUB)
490 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000491
492 if (NLB) {
Devang Patel38310052008-12-04 21:38:42 +0000493 unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
Devang Patel453a8442007-09-25 17:31:19 +0000494 IndVar->setIncomingValue(i, NLB);
495 }
496
497 if (NUB) {
Devang Patel38310052008-12-04 21:38:42 +0000498 unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
499 ExitCondition->setOperand(i, NUB);
Devang Patel453a8442007-09-25 17:31:19 +0000500 }
Devang Patel38310052008-12-04 21:38:42 +0000501 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000502}
Devang Patel38310052008-12-04 21:38:42 +0000503
504/// updateLoopIterationSpace -- Update loop's iteration space if loop
505/// body is executed for certain IV range only. For example,
506///
507/// for (i = 0; i < N; ++i) {
508/// if ( i > A && i < B) {
509/// ...
510/// }
511/// }
Devang Patel042b8772008-12-08 17:07:24 +0000512/// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000513///
514bool LoopIndexSplit::updateLoopIterationSpace() {
515 SplitCondition = NULL;
516 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
517 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
518 return false;
519 BasicBlock *Latch = L->getLoopLatch();
Devang Patel5279d062007-09-17 20:39:48 +0000520 BasicBlock *Header = L->getHeader();
Devang Patel38310052008-12-04 21:38:42 +0000521 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
522 if (!BR) return false;
523 if (!isa<BranchInst>(Latch->getTerminator())) return false;
524 if (BR->isUnconditional()) return false;
525 BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
526 if (!AND) return false;
527 if (AND->getOpcode() != Instruction::And) return false;
528 ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
529 ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
530 if (!Op0 || !Op1)
531 return false;
532 IVBasedValues.insert(AND);
533 IVBasedValues.insert(Op0);
534 IVBasedValues.insert(Op1);
535 if (!cleanBlock(Header)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000536 BasicBlock *ExitingBlock = ExitCondition->getParent();
Devang Patel38310052008-12-04 21:38:42 +0000537 if (!cleanBlock(ExitingBlock)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000538
Devang Patel38310052008-12-04 21:38:42 +0000539 // Verify that loop exiting block has only two predecessor, where one pred
Devang Patel453a8442007-09-25 17:31:19 +0000540 // is split condition block. The other predecessor will become exiting block's
541 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
542 // more then two predecessors. This requires extra work in updating dominator
543 // information.
544 BasicBlock *ExitingBBPred = NULL;
545 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
546 PI != PE; ++PI) {
547 BasicBlock *BB = *PI;
Devang Patel38310052008-12-04 21:38:42 +0000548 if (Header == BB)
Devang Patel453a8442007-09-25 17:31:19 +0000549 continue;
550 if (ExitingBBPred)
551 return false;
552 else
553 ExitingBBPred = BB;
554 }
Devang Patel453a8442007-09-25 17:31:19 +0000555
Devang Patel38310052008-12-04 21:38:42 +0000556 if (!restrictLoopBound(*Op0))
557 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000558
Devang Patel38310052008-12-04 21:38:42 +0000559 if (!restrictLoopBound(*Op1))
560 return false;
561
562 // Update CFG.
563 if (BR->getSuccessor(0) == ExitingBlock)
564 BR->setUnconditionalDest(BR->getSuccessor(1));
Devang Patel453a8442007-09-25 17:31:19 +0000565 else
Devang Patel38310052008-12-04 21:38:42 +0000566 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel453a8442007-09-25 17:31:19 +0000567
Devang Patel38310052008-12-04 21:38:42 +0000568 AND->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000569 if (Op0->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000570 Op0->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000571 if (Op1->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000572 Op1->eraseFromParent();
Devang Patel453a8442007-09-25 17:31:19 +0000573
574 // Update domiantor info. Now, ExitingBlock has only one predecessor,
575 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
576 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
Devang Patel38310052008-12-04 21:38:42 +0000577
578 BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
579 if (L->contains(ExitBlock))
580 ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
581
582 // If ExitingBlock is a member of the loop basic blocks' DF list then
583 // replace ExitingBlock with header and exit block in the DF list
584 DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
Devang Patel453a8442007-09-25 17:31:19 +0000585 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
586 I != E; ++I) {
587 BasicBlock *BB = *I;
588 if (BB == Header || BB == ExitingBlock)
589 continue;
590 DominanceFrontier::iterator BBDF = DF->find(BB);
591 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
592 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
593 while (DomSetI != DomSetE) {
594 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
595 ++DomSetI;
596 BasicBlock *DFBB = *CurrentItr;
597 if (DFBB == ExitingBlock) {
598 BBDF->second.erase(DFBB);
Devang Patel38310052008-12-04 21:38:42 +0000599 for (DominanceFrontier::DomSetType::iterator
600 EBI = ExitingBlockDF->second.begin(),
601 EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI)
602 BBDF->second.insert(*EBI);
Devang Patel453a8442007-09-25 17:31:19 +0000603 }
604 }
605 }
Devang Patel38310052008-12-04 21:38:42 +0000606 NumRestrictBounds++;
Devang Patel1c013502007-09-25 17:43:08 +0000607 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000608}
609
Devang Patela6a86632007-08-14 18:35:57 +0000610/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
611/// This routine is used to remove split condition's dead branch, dominated by
612/// DeadBB. LiveBB dominates split conidition's other branch.
613void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
614 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +0000615
Devang Patel5b8ec612007-08-15 03:31:47 +0000616 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +0000617 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +0000618 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
619 if (DeadBBDF != DF->end()) {
620 SmallVector<BasicBlock *, 8> PredBlocks;
621
622 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
623 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
Devang Patel38310052008-12-04 21:38:42 +0000624 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI)
625 {
Devang Patel5b8ec612007-08-15 03:31:47 +0000626 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +0000627 FrontierBBs.push_back(FrontierBB);
628
Devang Patel5b8ec612007-08-15 03:31:47 +0000629 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
630 PredBlocks.clear();
631 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
632 PI != PE; ++PI) {
633 BasicBlock *P = *PI;
634 if (P == DeadBB || DT->dominates(DeadBB, P))
635 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +0000636 }
Devang Patel96bf5242007-08-17 21:59:16 +0000637
Devang Patel5b8ec612007-08-15 03:31:47 +0000638 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
639 FBI != FBE; ++FBI) {
640 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
641 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
642 PE = PredBlocks.end(); PI != PE; ++PI) {
643 BasicBlock *P = *PI;
644 PN->removeIncomingValue(P);
645 }
646 }
647 else
648 break;
Devang Patel96bf5242007-08-17 21:59:16 +0000649 }
Devang Patel98147a32007-08-12 07:02:51 +0000650 }
Devang Patel98147a32007-08-12 07:02:51 +0000651 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000652
653 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
654 SmallVector<BasicBlock *, 32> WorkList;
655 DomTreeNode *DN = DT->getNode(DeadBB);
656 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
657 E = df_end(DN); DI != E; ++DI) {
658 BasicBlock *BB = DI->getBlock();
659 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +0000660 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +0000661 }
662
663 while (!WorkList.empty()) {
664 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
665 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +0000666 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +0000667 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +0000668 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +0000669 I->replaceAllUsesWith(UndefValue::get(I->getType()));
670 I->eraseFromParent();
671 }
672 LPM->deleteSimpleAnalysisValue(BB, LP);
673 DT->eraseNode(BB);
674 DF->removeBlock(BB);
675 LI->removeBlock(BB);
676 BB->eraseFromParent();
677 }
Devang Patel96bf5242007-08-17 21:59:16 +0000678
679 // Update Frontier BBs' dominator info.
680 while (!FrontierBBs.empty()) {
681 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
682 BasicBlock *NewDominator = FBB->getSinglePredecessor();
683 if (!NewDominator) {
684 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
685 NewDominator = *PI;
686 ++PI;
687 if (NewDominator != LiveBB) {
688 for(; PI != PE; ++PI) {
689 BasicBlock *P = *PI;
690 if (P == LiveBB) {
691 NewDominator = LiveBB;
692 break;
693 }
694 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
695 }
696 }
697 }
698 assert (NewDominator && "Unable to fix dominator info.");
699 DT->changeImmediateDominator(FBB, NewDominator);
700 DF->changeImmediateDominator(FBB, NewDominator, DT);
701 }
702
Devang Patel98147a32007-08-12 07:02:51 +0000703}
704
Devang Pateld79faee2007-08-25 02:39:24 +0000705// moveExitCondition - Move exit condition EC into split condition block CondBB.
706void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
Devang Patel38310052008-12-04 21:38:42 +0000707 BasicBlock *ExitBB, ICmpInst *EC,
708 ICmpInst *SC, PHINode *IV,
709 Instruction *IVAdd, Loop *LP,
710 unsigned ExitValueNum) {
Devang Pateld79faee2007-08-25 02:39:24 +0000711
712 BasicBlock *ExitingBB = EC->getParent();
713 Instruction *CurrentBR = CondBB->getTerminator();
714
715 // Move exit condition into split condition block.
716 EC->moveBefore(CurrentBR);
717 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
718
719 // Move exiting block's branch into split condition block. Update its branch
720 // destination.
721 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
722 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +0000723 BasicBlock *OrigDestBB = NULL;
724 if (ExitingBR->getSuccessor(0) == ExitBB) {
725 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +0000726 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000727 }
728 else {
729 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +0000730 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000731 }
Devang Pateld79faee2007-08-25 02:39:24 +0000732
733 // Remove split condition and current split condition branch.
734 SC->eraseFromParent();
735 CurrentBR->eraseFromParent();
736
Devang Patel23067df2008-02-13 22:06:36 +0000737 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +0000738 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +0000739
740 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +0000741 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000742
743 // Fix dominator info.
744 // ExitBB is now dominated by CondBB
745 DT->changeImmediateDominator(ExitBB, CondBB);
746 DF->changeImmediateDominator(ExitBB, CondBB, DT);
747
748 // Basicblocks dominated by ActiveBB may have ExitingBB or
749 // a basic block outside the loop in their DF list. If so,
750 // replace it with CondBB.
751 DomTreeNode *Node = DT->getNode(ActiveBB);
752 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
753 DI != DE; ++DI) {
754 BasicBlock *BB = DI->getBlock();
755 DominanceFrontier::iterator BBDF = DF->find(BB);
756 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
757 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
758 while (DomSetI != DomSetE) {
759 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
760 ++DomSetI;
761 BasicBlock *DFBB = *CurrentItr;
762 if (DFBB == ExitingBB || !L->contains(DFBB)) {
763 BBDF->second.erase(DFBB);
764 BBDF->second.insert(CondBB);
765 }
766 }
767 }
768}
769
770/// updatePHINodes - CFG has been changed.
771/// Before
772/// - ExitBB's single predecessor was Latch
773/// - Latch's second successor was Header
774/// Now
Devang Patel82ada542008-02-08 22:49:13 +0000775/// - ExitBB's single predecessor is Header
776/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +0000777///
778/// Update ExitBB PHINodes' to reflect this change.
779void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
780 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000781 PHINode *IV, Instruction *IVIncrement,
782 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +0000783
784 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000785 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +0000786 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000787 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +0000788 if (!PN)
789 break;
790
791 Value *V = PN->getIncomingValueForBlock(Latch);
792 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +0000793 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
794 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +0000795 Value *NewV = NULL;
796 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +0000797 UI != E; ++UI)
798 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +0000799 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +0000800 NewV = U;
801 break;
802 }
803
Devang Patel60a12902008-03-24 20:16:14 +0000804 // Add incoming value from header only if PN has any use inside the loop.
805 if (NewV)
806 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +0000807
808 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
809 // If this instruction is IVIncrement then IV is new incoming value
810 // from header otherwise this instruction must be incoming value from
811 // header because loop is in LCSSA form.
812 if (PHI == IVIncrement)
813 PN->addIncoming(IV, Header);
814 else
815 PN->addIncoming(V, Header);
816 } else
817 // Otherwise this is an incoming value from header because loop is in
818 // LCSSA form.
819 PN->addIncoming(V, Header);
820
821 // Remove incoming value from Latch.
822 PN->removeIncomingValue(Latch);
823 }
824}
Devang Patel38310052008-12-04 21:38:42 +0000825
826bool LoopIndexSplit::splitLoop() {
827 SplitCondition = NULL;
828 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
829 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
830 return false;
831 BasicBlock *Header = L->getHeader();
832 BasicBlock *Latch = L->getLoopLatch();
833 BranchInst *SBR = NULL; // Split Condition Branch
834 BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
835 // If Exiting block includes loop variant instructions then this
836 // loop may not be split safely.
837 BasicBlock *ExitingBlock = ExitCondition->getParent();
838 if (!cleanBlock(ExitingBlock)) return false;
839
840 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
841 I != E; ++I) {
842 BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
843 if (!BR || BR->isUnconditional()) continue;
844 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
845 if (!CI || CI == ExitCondition
846 || CI->getPredicate() == ICmpInst::ICMP_NE
847 || CI->getPredicate() == ICmpInst::ICMP_EQ)
848 continue;
849
850 // Unable to handle triangle loops at the moment.
851 // In triangle loop, split condition is in header and one of the
852 // the split destination is loop latch. If split condition is EQ
853 // then such loops are already handle in processOneIterationLoop().
854 if (Header == (*I)
855 && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
856 continue;
857
858 // If the block does not dominate the latch then this is not a diamond.
859 // Such loop may not benefit from index split.
860 if (!DT->dominates((*I), Latch))
861 continue;
862
863 // If split condition branches heads do not have single predecessor,
864 // SplitCondBlock, then is not possible to remove inactive branch.
865 if (!BR->getSuccessor(0)->getSinglePredecessor()
866 || !BR->getSuccessor(1)->getSinglePredecessor())
867 return false;
868
869 // If the merge point for BR is not loop latch then skip this condition.
870 if (BR->getSuccessor(0) != Latch) {
871 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
872 assert (DF0 != DF->end() && "Unable to find dominance frontier");
873 if (!DF0->second.count(Latch))
874 continue;
875 }
876
877 if (BR->getSuccessor(1) != Latch) {
878 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
879 assert (DF1 != DF->end() && "Unable to find dominance frontier");
880 if (!DF1->second.count(Latch))
881 continue;
882 }
883 SplitCondition = CI;
884 SBR = BR;
885 break;
886 }
887
888 if (!SplitCondition)
889 return false;
890
891 // If the predicate sign does not match then skip.
892 if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
893 return false;
894
895 unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
896 unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
897 Value *SplitValue = SplitCondition->getOperand(SVOpNum);
898 if (!L->isLoopInvariant(SplitValue))
899 return false;
900 if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
901 return false;
902
903 // Normalize loop conditions so that it is easier to calculate new loop
904 // bounds.
905 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
906 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
907 BasicBlock *T = EBR->getSuccessor(0);
908 EBR->setSuccessor(0, EBR->getSuccessor(1));
909 EBR->setSuccessor(1, T);
910 }
911
912 if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
913 SplitCondition->setPredicate(SplitCondition->getInversePredicate());
914 BasicBlock *T = SBR->getSuccessor(0);
915 SBR->setSuccessor(0, SBR->getSuccessor(1));
916 SBR->setSuccessor(1, T);
917 }
918
919 //[*] Calculate new loop bounds.
920 Value *AEV = SplitValue;
921 Value *BSV = SplitValue;
922 bool Sign = SplitCondition->isSignedPredicate();
923 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
924
925 if (IVisLT(*ExitCondition)) {
926 if (IVisLT(*SplitCondition)) {
927 /* Do nothing */
928 }
929 else if (IVisLE(*SplitCondition)) {
930 AEV = getPlusOne(SplitValue, Sign, PHTerm);
931 BSV = getPlusOne(SplitValue, Sign, PHTerm);
932 } else {
933 assert (0 && "Unexpected split condition!");
934 }
935 }
936 else if (IVisLE(*ExitCondition)) {
937 if (IVisLT(*SplitCondition)) {
938 AEV = getMinusOne(SplitValue, Sign, PHTerm);
939 }
940 else if (IVisLE(*SplitCondition)) {
941 BSV = getPlusOne(SplitValue, Sign, PHTerm);
942 } else {
943 assert (0 && "Unexpected split condition!");
944 }
945 } else {
946 assert (0 && "Unexpected exit condition!");
947 }
948 AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
949 BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
950
951 // [*] Clone Loop
952 DenseMap<const Value *, Value *> ValueMap;
953 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
954 Loop *ALoop = L;
955
956 // [*] ALoop's exiting edge enters BLoop's header.
957 // ALoop's original exit block becomes BLoop's exit block.
958 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
959 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
960 BranchInst *A_ExitInsn =
961 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
962 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
963 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
964 BasicBlock *B_Header = BLoop->getHeader();
965 if (ALoop->contains(B_ExitBlock)) {
966 B_ExitBlock = A_ExitInsn->getSuccessor(0);
967 A_ExitInsn->setSuccessor(0, B_Header);
968 } else
969 A_ExitInsn->setSuccessor(1, B_Header);
970
971 // [*] Update ALoop's exit value using new exit value.
972 ExitCondition->setOperand(EVOpNum, AEV);
973
974 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
975 // original loop's preheader. Add incoming PHINode values from
976 // ALoop's exiting block. Update BLoop header's domiantor info.
977
978 // Collect inverse map of Header PHINodes.
979 DenseMap<Value *, Value *> InverseMap;
980 for (BasicBlock::iterator BI = ALoop->getHeader()->begin(),
981 BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
982 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
983 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
984 InverseMap[PNClone] = PN;
985 } else
986 break;
987 }
988
989 BasicBlock *A_Preheader = ALoop->getLoopPreheader();
990 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
991 BI != BE; ++BI) {
992 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
993 // Remove incoming value from original preheader.
994 PN->removeIncomingValue(A_Preheader);
995
996 // Add incoming value from A_ExitingBlock.
997 if (PN == B_IndVar)
998 PN->addIncoming(BSV, A_ExitingBlock);
999 else {
1000 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1001 Value *V2 = NULL;
1002 // If loop header is also loop exiting block then
1003 // OrigPN is incoming value for B loop header.
1004 if (A_ExitingBlock == ALoop->getHeader())
1005 V2 = OrigPN;
1006 else
1007 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1008 PN->addIncoming(V2, A_ExitingBlock);
1009 }
1010 } else
1011 break;
1012 }
1013
1014 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1015 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1016
1017 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1018 // block. Remove incoming PHINode values from ALoop's exiting block.
1019 // Add new incoming values from BLoop's incoming exiting value.
1020 // Update BLoop exit block's dominator info..
1021 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1022 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1023 BI != BE; ++BI) {
1024 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1025 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1026 B_ExitingBlock);
1027 PN->removeIncomingValue(A_ExitingBlock);
1028 } else
1029 break;
1030 }
1031
1032 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1033 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1034
1035 //[*] Split ALoop's exit edge. This creates a new block which
1036 // serves two purposes. First one is to hold PHINode defnitions
1037 // to ensure that ALoop's LCSSA form. Second use it to act
1038 // as a preheader for BLoop.
1039 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1040
1041 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1042 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1043 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1044 BI != BE; ++BI) {
1045 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1046 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1047 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1048 newPHI->addIncoming(V1, A_ExitingBlock);
1049 A_ExitBlock->getInstList().push_front(newPHI);
1050 PN->removeIncomingValue(A_ExitBlock);
1051 PN->addIncoming(newPHI, A_ExitBlock);
1052 } else
1053 break;
1054 }
1055
1056 //[*] Eliminate split condition's inactive branch from ALoop.
1057 BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1058 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1059 BasicBlock *A_InactiveBranch = NULL;
1060 BasicBlock *A_ActiveBranch = NULL;
1061 A_ActiveBranch = A_BR->getSuccessor(0);
1062 A_InactiveBranch = A_BR->getSuccessor(1);
1063 A_BR->setUnconditionalDest(A_ActiveBranch);
1064 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1065
1066 //[*] Eliminate split condition's inactive branch in from BLoop.
1067 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1068 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1069 BasicBlock *B_InactiveBranch = NULL;
1070 BasicBlock *B_ActiveBranch = NULL;
1071 B_ActiveBranch = B_BR->getSuccessor(1);
1072 B_InactiveBranch = B_BR->getSuccessor(0);
1073 B_BR->setUnconditionalDest(B_ActiveBranch);
1074 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1075
1076 BasicBlock *A_Header = ALoop->getHeader();
1077 if (A_ExitingBlock == A_Header)
1078 return true;
1079
1080 //[*] Move exit condition into split condition block to avoid
1081 // executing dead loop iteration.
1082 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1083 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1084 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1085
1086 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1087 cast<ICmpInst>(SplitCondition), IndVar, IVIncrement,
1088 ALoop, EVOpNum);
1089
1090 moveExitCondition(B_SplitCondBlock, B_ActiveBranch,
1091 B_ExitBlock, B_ExitCondition,
1092 B_SplitCondition, B_IndVar, B_IndVarIncrement,
1093 BLoop, EVOpNum);
1094
1095 NumIndexSplit++;
1096 return true;
1097}
1098
1099/// cleanBlock - A block is considered clean if all non terminal instructions
1100/// are either, PHINodes, IV based.
1101bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1102 Instruction *Terminator = BB->getTerminator();
1103 for(BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1104 BI != BE; ++BI) {
1105 Instruction *I = BI;
1106
1107 if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
Devang Pateld96c60d2009-02-06 06:19:06 +00001108 || I == SplitCondition || IVBasedValues.count(I)
1109 || isa<DbgInfoIntrinsic>(I))
Devang Patel38310052008-12-04 21:38:42 +00001110 continue;
1111
1112 if (I->mayWriteToMemory())
1113 return false;
1114
1115 // I is used only inside this block then it is OK.
1116 bool usedOutsideBB = false;
1117 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1118 UI != UE; ++UI) {
1119 Instruction *U = cast<Instruction>(UI);
1120 if (U->getParent() != BB)
1121 usedOutsideBB = true;
1122 }
1123 if (!usedOutsideBB)
1124 continue;
1125
1126 // Otherwise we have a instruction that may not allow loop spliting.
1127 return false;
1128 }
1129 return true;
1130}
1131
Devang Patel042b8772008-12-08 17:07:24 +00001132/// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001133/// IV based value is less than the loop invariant then return the loop
1134/// invariant. Otherwise return NULL.
1135Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1136 ICmpInst::Predicate P = Op.getPredicate();
1137 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1138 && IVBasedValues.count(Op.getOperand(0))
1139 && L->isLoopInvariant(Op.getOperand(1)))
1140 return Op.getOperand(1);
1141
1142 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1143 && IVBasedValues.count(Op.getOperand(1))
1144 && L->isLoopInvariant(Op.getOperand(0)))
1145 return Op.getOperand(0);
1146
1147 return NULL;
1148}
1149
Devang Patel042b8772008-12-08 17:07:24 +00001150/// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001151/// IV based value is less than or equal to the loop invariant then
1152/// return the loop invariant. Otherwise return NULL.
1153Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1154 ICmpInst::Predicate P = Op.getPredicate();
1155 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1156 && IVBasedValues.count(Op.getOperand(0))
1157 && L->isLoopInvariant(Op.getOperand(1)))
1158 return Op.getOperand(1);
1159
1160 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1161 && IVBasedValues.count(Op.getOperand(1))
1162 && L->isLoopInvariant(Op.getOperand(0)))
1163 return Op.getOperand(0);
1164
1165 return NULL;
1166}
1167
Devang Patel042b8772008-12-08 17:07:24 +00001168/// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001169/// IV based value is greater than the loop invariant then return the loop
1170/// invariant. Otherwise return NULL.
1171Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1172 ICmpInst::Predicate P = Op.getPredicate();
1173 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1174 && IVBasedValues.count(Op.getOperand(0))
1175 && L->isLoopInvariant(Op.getOperand(1)))
1176 return Op.getOperand(1);
1177
1178 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1179 && IVBasedValues.count(Op.getOperand(1))
1180 && L->isLoopInvariant(Op.getOperand(0)))
1181 return Op.getOperand(0);
1182
1183 return NULL;
1184}
1185
Devang Patel042b8772008-12-08 17:07:24 +00001186/// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001187/// IV based value is greater than or equal to the loop invariant then
1188/// return the loop invariant. Otherwise return NULL.
1189Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1190 ICmpInst::Predicate P = Op.getPredicate();
1191 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1192 && IVBasedValues.count(Op.getOperand(0))
1193 && L->isLoopInvariant(Op.getOperand(1)))
1194 return Op.getOperand(1);
1195
1196 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1197 && IVBasedValues.count(Op.getOperand(1))
1198 && L->isLoopInvariant(Op.getOperand(0)))
1199 return Op.getOperand(0);
1200
1201 return NULL;
1202}
1203