blob: 6f7a7f866a8e318bddf9a3e4ae6a10d0cced452a [file] [log] [blame]
Devang Patelfee76bd2007-08-07 00:25:56 +00001//===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Devang Patelfee76bd2007-08-07 00:25:56 +00007//
8//===----------------------------------------------------------------------===//
9//
Devang Patel38310052008-12-04 21:38:42 +000010// This file implements Loop Index Splitting Pass. This pass handles three
11// kinds of loops.
Devang Patelfee76bd2007-08-07 00:25:56 +000012//
Dan Gohmanf159ccd2009-04-29 22:01:05 +000013// [1] A loop may be eliminated if the body is executed exactly once.
14// For example,
15//
Devang Patel38310052008-12-04 21:38:42 +000016// for (i = 0; i < N; ++i) {
Dan Gohmanf159ccd2009-04-29 22:01:05 +000017// if (i == X) {
18// body;
19// }
20// }
21//
22// is transformed to
23//
24// i = X;
25// body;
26//
27// [2] A loop's iteration space may be shrunk if the loop body is executed
28// for a proper sub-range of the loop's iteration space. For example,
29//
30// for (i = 0; i < N; ++i) {
31// if (i > A && i < B) {
Devang Patel38310052008-12-04 21:38:42 +000032// ...
33// }
34// }
35//
Dan Gohmanf159ccd2009-04-29 22:01:05 +000036// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +000037//
Dan Gohmanf159ccd2009-04-29 22:01:05 +000038// [3] A loop may be split if the loop body is dominated by a branch.
39// For example,
Devang Patel38310052008-12-04 21:38:42 +000040//
41// for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
42//
43// is transformed into
Dan Gohmanf159ccd2009-04-29 22:01:05 +000044//
Devang Patel38310052008-12-04 21:38:42 +000045// AEV = BSV = SV
46// for (i = LB; i < min(UB, AEV); ++i)
47// A;
48// for (i = max(LB, BSV); i < UB; ++i);
49// B;
Dan Gohmanf159ccd2009-04-29 22:01:05 +000050//
Devang Patelfee76bd2007-08-07 00:25:56 +000051//===----------------------------------------------------------------------===//
52
53#define DEBUG_TYPE "loop-index-split"
54
Devang Patelfee76bd2007-08-07 00:25:56 +000055#include "llvm/Transforms/Scalar.h"
Devang Pateld96c60d2009-02-06 06:19:06 +000056#include "llvm/IntrinsicInst.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000057#include "llvm/Analysis/LoopPass.h"
Dan Gohman97b6e2c2009-02-17 20:50:11 +000058#include "llvm/Analysis/ScalarEvolution.h"
Devang Patel787a7132007-08-08 21:39:47 +000059#include "llvm/Analysis/Dominators.h"
Devang Patel423c8b22007-08-10 18:07:13 +000060#include "llvm/Transforms/Utils/BasicBlockUtils.h"
61#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelb23c2322009-03-30 22:24:10 +000062#include "llvm/Transforms/Utils/Local.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000063#include "llvm/Support/Compiler.h"
Devang Patel5b8ec612007-08-15 03:31:47 +000064#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000065#include "llvm/ADT/Statistic.h"
66
67using namespace llvm;
68
Devang Patel38310052008-12-04 21:38:42 +000069STATISTIC(NumIndexSplit, "Number of loop index split");
70STATISTIC(NumIndexSplitRemoved, "Number of loops eliminated by loop index split");
71STATISTIC(NumRestrictBounds, "Number of loop iteration space restricted");
Devang Patelfee76bd2007-08-07 00:25:56 +000072
73namespace {
74
75 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
76
77 public:
78 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000079 LoopIndexSplit() : LoopPass(&ID) {}
Devang Patelfee76bd2007-08-07 00:25:56 +000080
81 // Index split Loop L. Return true if loop is split.
82 bool runOnLoop(Loop *L, LPPassManager &LPM);
83
84 void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelfee76bd2007-08-07 00:25:56 +000085 AU.addPreserved<ScalarEvolution>();
86 AU.addRequiredID(LCSSAID);
87 AU.addPreservedID(LCSSAID);
Devang Patel423c8b22007-08-10 18:07:13 +000088 AU.addRequired<LoopInfo>();
Devang Patelfee76bd2007-08-07 00:25:56 +000089 AU.addPreserved<LoopInfo>();
90 AU.addRequiredID(LoopSimplifyID);
91 AU.addPreservedID(LoopSimplifyID);
Devang Patel9704fcf2007-08-08 22:25:28 +000092 AU.addRequired<DominatorTree>();
Devang Patel5b8ec612007-08-15 03:31:47 +000093 AU.addRequired<DominanceFrontier>();
Devang Patel787a7132007-08-08 21:39:47 +000094 AU.addPreserved<DominatorTree>();
95 AU.addPreserved<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +000096 }
97
98 private:
Devang Patel38310052008-12-04 21:38:42 +000099 /// processOneIterationLoop -- Eliminate loop if loop body is executed
100 /// only once. For example,
101 /// for (i = 0; i < N; ++i) {
102 /// if ( i == X) {
103 /// ...
104 /// }
105 /// }
106 ///
107 bool processOneIterationLoop();
Devang Patel71554b82007-08-08 21:02:17 +0000108
Devang Patel38310052008-12-04 21:38:42 +0000109 // -- Routines used by updateLoopIterationSpace();
Devang Patelc9d123d2007-08-09 01:39:01 +0000110
Devang Patel38310052008-12-04 21:38:42 +0000111 /// updateLoopIterationSpace -- Update loop's iteration space if loop
112 /// body is executed for certain IV range only. For example,
113 ///
114 /// for (i = 0; i < N; ++i) {
115 /// if ( i > A && i < B) {
116 /// ...
117 /// }
118 /// }
Devang Patel042b8772008-12-08 17:07:24 +0000119 /// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000120 ///
121 bool updateLoopIterationSpace();
Devang Patel71554b82007-08-08 21:02:17 +0000122
Devang Patel38310052008-12-04 21:38:42 +0000123 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
124 /// with a loop invariant value. Update loop's lower and upper bound based on
125 /// the loop invariant value.
126 bool restrictLoopBound(ICmpInst &Op);
Devang Patel4a69da92007-08-25 00:56:38 +0000127
Devang Patel38310052008-12-04 21:38:42 +0000128 // --- Routines used by splitLoop(). --- /
Devang Patel4a69da92007-08-25 00:56:38 +0000129
Devang Patel38310052008-12-04 21:38:42 +0000130 bool splitLoop();
Devang Patel4a69da92007-08-25 00:56:38 +0000131
Devang Patel38310052008-12-04 21:38:42 +0000132 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by
133 /// DeadBB. This routine is used to remove split condition's dead branch,
134 /// dominated by DeadBB. LiveBB dominates split conidition's other branch.
Devang Patela6a86632007-08-14 18:35:57 +0000135 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel38310052008-12-04 21:38:42 +0000136
137 /// moveExitCondition - Move exit condition EC into split condition block.
138 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
139 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
140 PHINode *IV, Instruction *IVAdd, Loop *LP,
141 unsigned);
142
Devang Pateld79faee2007-08-25 02:39:24 +0000143 /// updatePHINodes - CFG has been changed.
144 /// Before
145 /// - ExitBB's single predecessor was Latch
146 /// - Latch's second successor was Header
147 /// Now
148 /// - ExitBB's single predecessor was Header
149 /// - Latch's one and only successor was Header
150 ///
151 /// Update ExitBB PHINodes' to reflect this change.
152 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
153 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000154 PHINode *IV, Instruction *IVIncrement, Loop *LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000155
Devang Patel38310052008-12-04 21:38:42 +0000156 // --- Utility routines --- /
Devang Pateld79faee2007-08-25 02:39:24 +0000157
Devang Patel38310052008-12-04 21:38:42 +0000158 /// cleanBlock - A block is considered clean if all non terminal
159 /// instructions are either PHINodes or IV based values.
160 bool cleanBlock(BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000161
Devang Patel042b8772008-12-08 17:07:24 +0000162 /// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000163 /// IV based value is less than the loop invariant then return the loop
164 /// invariant. Otherwise return NULL.
165 Value * IVisLT(ICmpInst &Op);
166
Devang Patel042b8772008-12-08 17:07:24 +0000167 /// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000168 /// IV based value is less than or equal to the loop invariant then
169 /// return the loop invariant. Otherwise return NULL.
170 Value * IVisLE(ICmpInst &Op);
171
Devang Patel042b8772008-12-08 17:07:24 +0000172 /// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000173 /// IV based value is greater than the loop invariant then return the loop
174 /// invariant. Otherwise return NULL.
175 Value * IVisGT(ICmpInst &Op);
176
Devang Patel042b8772008-12-08 17:07:24 +0000177 /// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000178 /// IV based value is greater than or equal to the loop invariant then
179 /// return the loop invariant. Otherwise return NULL.
180 Value * IVisGE(ICmpInst &Op);
Devang Patelbacf5192007-08-10 00:33:50 +0000181
Devang Patelfee76bd2007-08-07 00:25:56 +0000182 private:
183
Devang Patel38310052008-12-04 21:38:42 +0000184 // Current Loop information.
Devang Patelfee76bd2007-08-07 00:25:56 +0000185 Loop *L;
Devang Patel423c8b22007-08-10 18:07:13 +0000186 LPPassManager *LPM;
187 LoopInfo *LI;
Devang Patel9704fcf2007-08-08 22:25:28 +0000188 DominatorTree *DT;
Devang Patelfc4c5f82007-08-13 22:13:24 +0000189 DominanceFrontier *DF;
Devang Patelbacf5192007-08-10 00:33:50 +0000190
Devang Patelbacf5192007-08-10 00:33:50 +0000191 PHINode *IndVar;
Devang Patelbacf5192007-08-10 00:33:50 +0000192 ICmpInst *ExitCondition;
Devang Patel38310052008-12-04 21:38:42 +0000193 ICmpInst *SplitCondition;
194 Value *IVStartValue;
195 Value *IVExitValue;
196 Instruction *IVIncrement;
197 SmallPtrSet<Value *, 4> IVBasedValues;
Devang Patelfee76bd2007-08-07 00:25:56 +0000198 };
Devang Patelfee76bd2007-08-07 00:25:56 +0000199}
200
Dan Gohman844731a2008-05-13 00:00:25 +0000201char LoopIndexSplit::ID = 0;
202static RegisterPass<LoopIndexSplit>
203X("loop-index-split", "Index Split Loops");
204
Daniel Dunbar394f0442008-10-22 23:32:42 +0000205Pass *llvm::createLoopIndexSplitPass() {
Devang Patelfee76bd2007-08-07 00:25:56 +0000206 return new LoopIndexSplit();
207}
208
209// Index split Loop L. Return true if loop is split.
Devang Patel423c8b22007-08-10 18:07:13 +0000210bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000211 L = IncomingLoop;
Devang Patel423c8b22007-08-10 18:07:13 +0000212 LPM = &LPM_Ref;
Devang Patel71554b82007-08-08 21:02:17 +0000213
Devang Patel3fe4f212007-08-15 02:14:55 +0000214 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel4e8061c2007-08-14 23:53:57 +0000215 if (!L->getSubLoops().empty())
216 return false;
217
Devang Patel9704fcf2007-08-08 22:25:28 +0000218 DT = &getAnalysis<DominatorTree>();
Devang Patel423c8b22007-08-10 18:07:13 +0000219 LI = &getAnalysis<LoopInfo>();
Devang Patel7375bb92007-08-15 03:34:53 +0000220 DF = &getAnalysis<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +0000221
Devang Patel38310052008-12-04 21:38:42 +0000222 // Initialize loop data.
223 IndVar = L->getCanonicalInductionVariable();
224 if (!IndVar) return false;
Devang Patelbacf5192007-08-10 00:33:50 +0000225
Devang Patel38310052008-12-04 21:38:42 +0000226 bool P1InLoop = L->contains(IndVar->getIncomingBlock(1));
227 IVStartValue = IndVar->getIncomingValue(!P1InLoop);
228 IVIncrement = dyn_cast<Instruction>(IndVar->getIncomingValue(P1InLoop));
229 if (!IVIncrement) return false;
Devang Patel71554b82007-08-08 21:02:17 +0000230
Devang Patel38310052008-12-04 21:38:42 +0000231 IVBasedValues.clear();
232 IVBasedValues.insert(IndVar);
233 IVBasedValues.insert(IVIncrement);
Devang Patelbacf5192007-08-10 00:33:50 +0000234 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Devang Patel38310052008-12-04 21:38:42 +0000235 I != E; ++I)
236 for(BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
237 BI != BE; ++BI) {
238 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BI))
239 if (BO != IVIncrement
240 && (BO->getOpcode() == Instruction::Add
241 || BO->getOpcode() == Instruction::Sub))
242 if (IVBasedValues.count(BO->getOperand(0))
243 && L->isLoopInvariant(BO->getOperand(1)))
244 IVBasedValues.insert(BO);
245 }
Devang Patelbacf5192007-08-10 00:33:50 +0000246
Devang Patel38310052008-12-04 21:38:42 +0000247 // Reject loop if loop exit condition is not suitable.
Dan Gohmanc8332462009-02-12 18:08:24 +0000248 BasicBlock *ExitingBlock = L->getExitingBlock();
249 if (!ExitingBlock)
Devang Patel38310052008-12-04 21:38:42 +0000250 return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000251 BranchInst *EBR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel38310052008-12-04 21:38:42 +0000252 if (!EBR) return false;
253 ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
254 if (!ExitCondition) return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000255 if (ExitingBlock != L->getLoopLatch()) return false;
Devang Patel38310052008-12-04 21:38:42 +0000256 IVExitValue = ExitCondition->getOperand(1);
257 if (!L->isLoopInvariant(IVExitValue))
258 IVExitValue = ExitCondition->getOperand(0);
259 if (!L->isLoopInvariant(IVExitValue))
260 return false;
Devang Patela5e27f82008-07-09 00:12:01 +0000261
262 // If start value is more then exit value where induction variable
263 // increments by 1 then we are potentially dealing with an infinite loop.
264 // Do not index split this loop.
Devang Patel38310052008-12-04 21:38:42 +0000265 if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
266 if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
267 if (SV->getSExtValue() > EV->getSExtValue())
268 return false;
Devang Patelc9d123d2007-08-09 01:39:01 +0000269
Devang Patel38310052008-12-04 21:38:42 +0000270 if (processOneIterationLoop())
271 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000272
Devang Patel38310052008-12-04 21:38:42 +0000273 if (updateLoopIterationSpace())
274 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000275
Devang Patel38310052008-12-04 21:38:42 +0000276 if (splitLoop())
277 return true;
Devang Pateld35ed2c2007-09-11 00:42:56 +0000278
279 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000280}
281
Devang Patel38310052008-12-04 21:38:42 +0000282// --- Helper routines ---
283// isUsedOutsideLoop - Returns true iff V is used outside the loop L.
284static bool isUsedOutsideLoop(Value *V, Loop *L) {
285 for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
286 if (!L->contains(cast<Instruction>(*UI)->getParent()))
287 return true;
288 return false;
289}
Devang Patelfee76bd2007-08-07 00:25:56 +0000290
Devang Patel38310052008-12-04 21:38:42 +0000291// Return V+1
292static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000293 Constant *One = ConstantInt::get(V->getType(), 1, Sign);
Devang Patel38310052008-12-04 21:38:42 +0000294 return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
295}
Devang Patelfee76bd2007-08-07 00:25:56 +0000296
Devang Patel38310052008-12-04 21:38:42 +0000297// Return V-1
298static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000299 Constant *One = ConstantInt::get(V->getType(), 1, Sign);
Devang Patel38310052008-12-04 21:38:42 +0000300 return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
301}
Devang Patelfee76bd2007-08-07 00:25:56 +0000302
Devang Patel38310052008-12-04 21:38:42 +0000303// Return min(V1, V1)
304static Value *getMin(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, V1, V2, "lsp", InsertPt);
309}
Devang Patelfee76bd2007-08-07 00:25:56 +0000310
Devang Patel38310052008-12-04 21:38:42 +0000311// Return max(V1, V2)
312static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
313
314 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
315 V1, V2, "lsp", InsertPt);
316 return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
317}
Devang Patel968eee22007-09-19 00:15:16 +0000318
Devang Patel38310052008-12-04 21:38:42 +0000319/// processOneIterationLoop -- Eliminate loop if loop body is executed
320/// only once. For example,
321/// for (i = 0; i < N; ++i) {
322/// if ( i == X) {
323/// ...
324/// }
325/// }
326///
327bool LoopIndexSplit::processOneIterationLoop() {
328 SplitCondition = NULL;
Devang Patel84ef08b2007-09-19 00:11:01 +0000329 BasicBlock *Latch = L->getLoopLatch();
Devang Patel38310052008-12-04 21:38:42 +0000330 BasicBlock *Header = L->getHeader();
331 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
332 if (!BR) return false;
333 if (!isa<BranchInst>(Latch->getTerminator())) return false;
334 if (BR->isUnconditional()) return false;
335 SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
336 if (!SplitCondition) return false;
337 if (SplitCondition == ExitCondition) return false;
338 if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
339 if (BR->getOperand(1) != Latch) return false;
340 if (!IVBasedValues.count(SplitCondition->getOperand(0))
341 && !IVBasedValues.count(SplitCondition->getOperand(1)))
Devang Patel84ef08b2007-09-19 00:11:01 +0000342 return false;
343
Devang Patel38310052008-12-04 21:38:42 +0000344 // If IV is used outside the loop then this loop traversal is required.
345 // FIXME: Calculate and use last IV value.
346 if (isUsedOutsideLoop(IVIncrement, L))
347 return false;
348
349 // If BR operands are not IV or not loop invariants then skip this loop.
350 Value *OPV = SplitCondition->getOperand(0);
351 Value *SplitValue = SplitCondition->getOperand(1);
Eli Friedmanf7cca7b2009-05-22 03:22:46 +0000352 if (!L->isLoopInvariant(SplitValue))
353 std::swap(OPV, SplitValue);
Devang Patel38310052008-12-04 21:38:42 +0000354 if (!L->isLoopInvariant(SplitValue))
355 return false;
356 Instruction *OPI = dyn_cast<Instruction>(OPV);
Devang Patelb23c2322009-03-30 22:24:10 +0000357 if (!OPI)
358 return false;
Devang Patel38310052008-12-04 21:38:42 +0000359 if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
360 return false;
Devang Patelb23c2322009-03-30 22:24:10 +0000361 Value *StartValue = IVStartValue;
362 Value *ExitValue = IVExitValue;;
363
364 if (OPV != IndVar) {
365 // If BR operand is IV based then use this operand to calculate
366 // effective conditions for loop body.
367 BinaryOperator *BOPV = dyn_cast<BinaryOperator>(OPV);
368 if (!BOPV)
369 return false;
370 if (BOPV->getOpcode() != Instruction::Add)
371 return false;
372 StartValue = BinaryOperator::CreateAdd(OPV, StartValue, "" , BR);
373 ExitValue = BinaryOperator::CreateAdd(OPV, ExitValue, "" , BR);
374 }
375
Devang Patel38310052008-12-04 21:38:42 +0000376 if (!cleanBlock(Header))
377 return false;
378
379 if (!cleanBlock(Latch))
380 return false;
381
382 // If the merge point for BR is not loop latch then skip this loop.
383 if (BR->getSuccessor(0) != Latch) {
384 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
385 assert (DF0 != DF->end() && "Unable to find dominance frontier");
386 if (!DF0->second.count(Latch))
387 return false;
388 }
389
390 if (BR->getSuccessor(1) != Latch) {
391 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
392 assert (DF1 != DF->end() && "Unable to find dominance frontier");
393 if (!DF1->second.count(Latch))
394 return false;
395 }
396
397 // Now, Current loop L contains compare instruction
398 // that compares induction variable, IndVar, against loop invariant. And
399 // entire (i.e. meaningful) loop body is dominated by this compare
400 // instruction. In such case eliminate
401 // loop structure surrounding this loop body. For example,
402 // for (int i = start; i < end; ++i) {
403 // if ( i == somevalue) {
404 // loop_body
405 // }
406 // }
407 // can be transformed into
408 // if (somevalue >= start && somevalue < end) {
409 // i = somevalue;
410 // loop_body
411 // }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000412
Devang Patelebc5fea2007-08-20 20:49:01 +0000413 // Replace index variable with split value in loop body. Loop body is executed
414 // only when index variable is equal to split value.
Devang Patel38310052008-12-04 21:38:42 +0000415 IndVar->replaceAllUsesWith(SplitValue);
Devang Patelfee76bd2007-08-07 00:25:56 +0000416
Devang Patelfee76bd2007-08-07 00:25:56 +0000417 // Replace split condition in header.
418 // Transform
419 // SplitCondition : icmp eq i32 IndVar, SplitValue
420 // into
421 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000422 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000423 // and i32 c1, c2
Devang Patel38310052008-12-04 21:38:42 +0000424 Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ?
Devang Patelfee76bd2007-08-07 00:25:56 +0000425 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelb23c2322009-03-30 22:24:10 +0000426 SplitValue, StartValue, "lisplit", BR);
Devang Patel38310052008-12-04 21:38:42 +0000427
428 CmpInst::Predicate C2P = ExitCondition->getPredicate();
429 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
430 if (LatchBR->getOperand(0) != Header)
431 C2P = CmpInst::getInversePredicate(C2P);
Devang Patelb23c2322009-03-30 22:24:10 +0000432 Instruction *C2 = new ICmpInst(C2P, SplitValue, ExitValue, "lisplit", BR);
Devang Patel38310052008-12-04 21:38:42 +0000433 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
434
435 SplitCondition->replaceAllUsesWith(NSplitCond);
436 SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000437
Devang Patelfc19fbd2008-10-10 22:02:57 +0000438 // Remove Latch to Header edge.
439 BasicBlock *LatchSucc = NULL;
440 Header->removePredecessor(Latch);
441 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
442 SI != E; ++SI) {
443 if (Header != *SI)
444 LatchSucc = *SI;
445 }
Devang Patelfc19fbd2008-10-10 22:02:57 +0000446
Devang Patelb23c2322009-03-30 22:24:10 +0000447 // Clean up latch block.
448 Value *LatchBRCond = LatchBR->getCondition();
449 LatchBR->setUnconditionalDest(LatchSucc);
450 RecursivelyDeleteTriviallyDeadInstructions(LatchBRCond);
Devang Patel38310052008-12-04 21:38:42 +0000451
Devang Patel423c8b22007-08-10 18:07:13 +0000452 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000453
454 // Update Dominator Info.
455 // Only CFG change done is to remove Latch to Header edge. This
456 // does not change dominator tree because Latch did not dominate
457 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000458 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000459 DominanceFrontier::iterator HeaderDF = DF->find(Header);
460 if (HeaderDF != DF->end())
461 DF->removeFromFrontier(HeaderDF, Header);
462
463 DominanceFrontier::iterator LatchDF = DF->find(Latch);
464 if (LatchDF != DF->end())
465 DF->removeFromFrontier(LatchDF, Header);
466 }
Devang Patel38310052008-12-04 21:38:42 +0000467
468 ++NumIndexSplitRemoved;
Devang Patelfee76bd2007-08-07 00:25:56 +0000469 return true;
470}
471
Devang Patel38310052008-12-04 21:38:42 +0000472/// restrictLoopBound - Op dominates loop body. Op compares an IV based value
473/// with a loop invariant value. Update loop's lower and upper bound based on
474/// the loop invariant value.
475bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
476 bool Sign = Op.isSignedPredicate();
477 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
Devang Patelfee76bd2007-08-07 00:25:56 +0000478
Devang Patel38310052008-12-04 21:38:42 +0000479 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
480 BranchInst *EBR =
481 cast<BranchInst>(ExitCondition->getParent()->getTerminator());
482 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
483 BasicBlock *T = EBR->getSuccessor(0);
484 EBR->setSuccessor(0, EBR->getSuccessor(1));
485 EBR->setSuccessor(1, T);
Devang Patelfee76bd2007-08-07 00:25:56 +0000486 }
487
Devang Patel38310052008-12-04 21:38:42 +0000488 // New upper and lower bounds.
Devang Patel453a8442007-09-25 17:31:19 +0000489 Value *NLB = NULL;
Devang Patel38310052008-12-04 21:38:42 +0000490 Value *NUB = NULL;
491 if (Value *V = IVisLT(Op)) {
492 // Restrict upper bound.
493 if (IVisLE(*ExitCondition))
494 V = getMinusOne(V, Sign, PHTerm);
495 NUB = getMin(V, IVExitValue, Sign, PHTerm);
496 } else if (Value *V = IVisLE(Op)) {
497 // Restrict upper bound.
498 if (IVisLT(*ExitCondition))
499 V = getPlusOne(V, Sign, PHTerm);
500 NUB = getMin(V, IVExitValue, Sign, PHTerm);
501 } else if (Value *V = IVisGT(Op)) {
502 // Restrict lower bound.
503 V = getPlusOne(V, Sign, PHTerm);
504 NLB = getMax(V, IVStartValue, Sign, PHTerm);
505 } else if (Value *V = IVisGE(Op))
506 // Restrict lower bound.
507 NLB = getMax(V, IVStartValue, Sign, PHTerm);
Devang Patel453a8442007-09-25 17:31:19 +0000508
Devang Patel38310052008-12-04 21:38:42 +0000509 if (!NLB && !NUB)
510 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000511
512 if (NLB) {
Devang Patel38310052008-12-04 21:38:42 +0000513 unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
Devang Patel453a8442007-09-25 17:31:19 +0000514 IndVar->setIncomingValue(i, NLB);
515 }
516
517 if (NUB) {
Devang Patel38310052008-12-04 21:38:42 +0000518 unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
519 ExitCondition->setOperand(i, NUB);
Devang Patel453a8442007-09-25 17:31:19 +0000520 }
Devang Patel38310052008-12-04 21:38:42 +0000521 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000522}
Devang Patel38310052008-12-04 21:38:42 +0000523
524/// updateLoopIterationSpace -- Update loop's iteration space if loop
525/// body is executed for certain IV range only. For example,
526///
527/// for (i = 0; i < N; ++i) {
528/// if ( i > A && i < B) {
529/// ...
530/// }
531/// }
Devang Patel042b8772008-12-08 17:07:24 +0000532/// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000533///
534bool LoopIndexSplit::updateLoopIterationSpace() {
535 SplitCondition = NULL;
536 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
537 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
538 return false;
539 BasicBlock *Latch = L->getLoopLatch();
Devang Patel5279d062007-09-17 20:39:48 +0000540 BasicBlock *Header = L->getHeader();
Devang Patel38310052008-12-04 21:38:42 +0000541 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
542 if (!BR) return false;
543 if (!isa<BranchInst>(Latch->getTerminator())) return false;
544 if (BR->isUnconditional()) return false;
545 BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
546 if (!AND) return false;
547 if (AND->getOpcode() != Instruction::And) return false;
548 ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
549 ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
550 if (!Op0 || !Op1)
551 return false;
552 IVBasedValues.insert(AND);
553 IVBasedValues.insert(Op0);
554 IVBasedValues.insert(Op1);
555 if (!cleanBlock(Header)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000556 BasicBlock *ExitingBlock = ExitCondition->getParent();
Devang Patel38310052008-12-04 21:38:42 +0000557 if (!cleanBlock(ExitingBlock)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000558
Devang Patelcf42ee42009-03-02 23:39:14 +0000559 // If the merge point for BR is not loop latch then skip this loop.
560 if (BR->getSuccessor(0) != Latch) {
561 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
562 assert (DF0 != DF->end() && "Unable to find dominance frontier");
563 if (!DF0->second.count(Latch))
564 return false;
565 }
566
567 if (BR->getSuccessor(1) != Latch) {
568 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
569 assert (DF1 != DF->end() && "Unable to find dominance frontier");
570 if (!DF1->second.count(Latch))
571 return false;
572 }
573
Devang Patel38310052008-12-04 21:38:42 +0000574 // Verify that loop exiting block has only two predecessor, where one pred
Devang Patel453a8442007-09-25 17:31:19 +0000575 // is split condition block. The other predecessor will become exiting block's
576 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
577 // more then two predecessors. This requires extra work in updating dominator
578 // information.
579 BasicBlock *ExitingBBPred = NULL;
580 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
581 PI != PE; ++PI) {
582 BasicBlock *BB = *PI;
Devang Patel38310052008-12-04 21:38:42 +0000583 if (Header == BB)
Devang Patel453a8442007-09-25 17:31:19 +0000584 continue;
585 if (ExitingBBPred)
586 return false;
587 else
588 ExitingBBPred = BB;
589 }
Devang Patel453a8442007-09-25 17:31:19 +0000590
Devang Patel38310052008-12-04 21:38:42 +0000591 if (!restrictLoopBound(*Op0))
592 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000593
Devang Patel38310052008-12-04 21:38:42 +0000594 if (!restrictLoopBound(*Op1))
595 return false;
596
597 // Update CFG.
598 if (BR->getSuccessor(0) == ExitingBlock)
599 BR->setUnconditionalDest(BR->getSuccessor(1));
Devang Patel453a8442007-09-25 17:31:19 +0000600 else
Devang Patel38310052008-12-04 21:38:42 +0000601 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel453a8442007-09-25 17:31:19 +0000602
Devang Patel38310052008-12-04 21:38:42 +0000603 AND->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000604 if (Op0->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000605 Op0->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000606 if (Op1->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000607 Op1->eraseFromParent();
Devang Patel453a8442007-09-25 17:31:19 +0000608
609 // Update domiantor info. Now, ExitingBlock has only one predecessor,
610 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
611 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
Devang Patel38310052008-12-04 21:38:42 +0000612
613 BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
614 if (L->contains(ExitBlock))
615 ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
616
617 // If ExitingBlock is a member of the loop basic blocks' DF list then
618 // replace ExitingBlock with header and exit block in the DF list
619 DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
Devang Patel453a8442007-09-25 17:31:19 +0000620 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
621 I != E; ++I) {
622 BasicBlock *BB = *I;
623 if (BB == Header || BB == ExitingBlock)
624 continue;
625 DominanceFrontier::iterator BBDF = DF->find(BB);
626 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
627 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
628 while (DomSetI != DomSetE) {
629 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
630 ++DomSetI;
631 BasicBlock *DFBB = *CurrentItr;
632 if (DFBB == ExitingBlock) {
633 BBDF->second.erase(DFBB);
Devang Patel38310052008-12-04 21:38:42 +0000634 for (DominanceFrontier::DomSetType::iterator
635 EBI = ExitingBlockDF->second.begin(),
636 EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI)
637 BBDF->second.insert(*EBI);
Devang Patel453a8442007-09-25 17:31:19 +0000638 }
639 }
640 }
Devang Patel38310052008-12-04 21:38:42 +0000641 NumRestrictBounds++;
Devang Patel1c013502007-09-25 17:43:08 +0000642 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000643}
644
Devang Patela6a86632007-08-14 18:35:57 +0000645/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
646/// This routine is used to remove split condition's dead branch, dominated by
647/// DeadBB. LiveBB dominates split conidition's other branch.
648void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
649 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +0000650
Devang Patel5b8ec612007-08-15 03:31:47 +0000651 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +0000652 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +0000653 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
654 if (DeadBBDF != DF->end()) {
655 SmallVector<BasicBlock *, 8> PredBlocks;
656
657 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
658 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
Devang Patel38310052008-12-04 21:38:42 +0000659 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI)
660 {
Devang Patel5b8ec612007-08-15 03:31:47 +0000661 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +0000662 FrontierBBs.push_back(FrontierBB);
663
Devang Patel5b8ec612007-08-15 03:31:47 +0000664 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
665 PredBlocks.clear();
666 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
667 PI != PE; ++PI) {
668 BasicBlock *P = *PI;
669 if (P == DeadBB || DT->dominates(DeadBB, P))
670 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +0000671 }
Devang Patel96bf5242007-08-17 21:59:16 +0000672
Devang Patel5b8ec612007-08-15 03:31:47 +0000673 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
674 FBI != FBE; ++FBI) {
675 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
676 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
677 PE = PredBlocks.end(); PI != PE; ++PI) {
678 BasicBlock *P = *PI;
679 PN->removeIncomingValue(P);
680 }
681 }
682 else
683 break;
Devang Patel96bf5242007-08-17 21:59:16 +0000684 }
Devang Patel98147a32007-08-12 07:02:51 +0000685 }
Devang Patel98147a32007-08-12 07:02:51 +0000686 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000687
688 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
689 SmallVector<BasicBlock *, 32> WorkList;
690 DomTreeNode *DN = DT->getNode(DeadBB);
691 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
692 E = df_end(DN); DI != E; ++DI) {
693 BasicBlock *BB = DI->getBlock();
694 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +0000695 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +0000696 }
697
698 while (!WorkList.empty()) {
699 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
Devang Patel575ec802009-03-25 23:57:48 +0000700 LPM->deleteSimpleAnalysisValue(BB, LP);
Devang Patel5b8ec612007-08-15 03:31:47 +0000701 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +0000702 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +0000703 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +0000704 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +0000705 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Owen Anderson0b2a1532009-04-14 01:04:19 +0000706 LPM->deleteSimpleAnalysisValue(I, LP);
Devang Patel5b8ec612007-08-15 03:31:47 +0000707 I->eraseFromParent();
708 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000709 DT->eraseNode(BB);
710 DF->removeBlock(BB);
711 LI->removeBlock(BB);
712 BB->eraseFromParent();
713 }
Devang Patel96bf5242007-08-17 21:59:16 +0000714
715 // Update Frontier BBs' dominator info.
716 while (!FrontierBBs.empty()) {
717 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
718 BasicBlock *NewDominator = FBB->getSinglePredecessor();
719 if (!NewDominator) {
720 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
721 NewDominator = *PI;
722 ++PI;
723 if (NewDominator != LiveBB) {
724 for(; PI != PE; ++PI) {
725 BasicBlock *P = *PI;
726 if (P == LiveBB) {
727 NewDominator = LiveBB;
728 break;
729 }
730 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
731 }
732 }
733 }
734 assert (NewDominator && "Unable to fix dominator info.");
735 DT->changeImmediateDominator(FBB, NewDominator);
736 DF->changeImmediateDominator(FBB, NewDominator, DT);
737 }
738
Devang Patel98147a32007-08-12 07:02:51 +0000739}
740
Devang Pateld79faee2007-08-25 02:39:24 +0000741// moveExitCondition - Move exit condition EC into split condition block CondBB.
742void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
Devang Patel38310052008-12-04 21:38:42 +0000743 BasicBlock *ExitBB, ICmpInst *EC,
744 ICmpInst *SC, PHINode *IV,
745 Instruction *IVAdd, Loop *LP,
746 unsigned ExitValueNum) {
Devang Pateld79faee2007-08-25 02:39:24 +0000747
748 BasicBlock *ExitingBB = EC->getParent();
749 Instruction *CurrentBR = CondBB->getTerminator();
750
751 // Move exit condition into split condition block.
752 EC->moveBefore(CurrentBR);
753 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
754
755 // Move exiting block's branch into split condition block. Update its branch
756 // destination.
757 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
758 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +0000759 BasicBlock *OrigDestBB = NULL;
760 if (ExitingBR->getSuccessor(0) == ExitBB) {
761 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +0000762 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000763 }
764 else {
765 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +0000766 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000767 }
Devang Pateld79faee2007-08-25 02:39:24 +0000768
769 // Remove split condition and current split condition branch.
770 SC->eraseFromParent();
771 CurrentBR->eraseFromParent();
772
Devang Patel23067df2008-02-13 22:06:36 +0000773 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +0000774 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +0000775
776 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +0000777 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000778
779 // Fix dominator info.
780 // ExitBB is now dominated by CondBB
781 DT->changeImmediateDominator(ExitBB, CondBB);
782 DF->changeImmediateDominator(ExitBB, CondBB, DT);
Eli Friedmanf7cca7b2009-05-22 03:22:46 +0000783
784 // Blocks outside the loop may have been in the dominance frontier of blocks
785 // inside the condition; this is now impossible because the blocks inside the
786 // condition no loger dominate the exit. Remove the relevant blocks from
787 // the dominance frontiers.
788 for (Loop::block_iterator I = LP->block_begin(), E = LP->block_end();
789 I != E; ++I) {
790 if (*I == CondBB || !DT->dominates(CondBB, *I)) continue;
791 DominanceFrontier::iterator BBDF = DF->find(*I);
Devang Pateld79faee2007-08-25 02:39:24 +0000792 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
793 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
794 while (DomSetI != DomSetE) {
795 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
796 ++DomSetI;
797 BasicBlock *DFBB = *CurrentItr;
Eli Friedmanf7cca7b2009-05-22 03:22:46 +0000798 if (!LP->contains(DFBB))
Devang Pateld79faee2007-08-25 02:39:24 +0000799 BBDF->second.erase(DFBB);
Devang Pateld79faee2007-08-25 02:39:24 +0000800 }
801 }
802}
803
804/// updatePHINodes - CFG has been changed.
805/// Before
806/// - ExitBB's single predecessor was Latch
807/// - Latch's second successor was Header
808/// Now
Devang Patel82ada542008-02-08 22:49:13 +0000809/// - ExitBB's single predecessor is Header
810/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +0000811///
812/// Update ExitBB PHINodes' to reflect this change.
813void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
814 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000815 PHINode *IV, Instruction *IVIncrement,
816 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +0000817
818 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000819 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +0000820 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000821 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +0000822 if (!PN)
823 break;
824
825 Value *V = PN->getIncomingValueForBlock(Latch);
826 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +0000827 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
828 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +0000829 Value *NewV = NULL;
830 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +0000831 UI != E; ++UI)
832 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +0000833 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +0000834 NewV = U;
835 break;
836 }
837
Devang Patel60a12902008-03-24 20:16:14 +0000838 // Add incoming value from header only if PN has any use inside the loop.
839 if (NewV)
840 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +0000841
842 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
843 // If this instruction is IVIncrement then IV is new incoming value
844 // from header otherwise this instruction must be incoming value from
845 // header because loop is in LCSSA form.
846 if (PHI == IVIncrement)
847 PN->addIncoming(IV, Header);
848 else
849 PN->addIncoming(V, Header);
850 } else
851 // Otherwise this is an incoming value from header because loop is in
852 // LCSSA form.
853 PN->addIncoming(V, Header);
854
855 // Remove incoming value from Latch.
856 PN->removeIncomingValue(Latch);
857 }
858}
Devang Patel38310052008-12-04 21:38:42 +0000859
860bool LoopIndexSplit::splitLoop() {
861 SplitCondition = NULL;
862 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
863 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
864 return false;
865 BasicBlock *Header = L->getHeader();
866 BasicBlock *Latch = L->getLoopLatch();
867 BranchInst *SBR = NULL; // Split Condition Branch
868 BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
869 // If Exiting block includes loop variant instructions then this
870 // loop may not be split safely.
871 BasicBlock *ExitingBlock = ExitCondition->getParent();
872 if (!cleanBlock(ExitingBlock)) return false;
873
874 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
875 I != E; ++I) {
876 BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
877 if (!BR || BR->isUnconditional()) continue;
878 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
879 if (!CI || CI == ExitCondition
880 || CI->getPredicate() == ICmpInst::ICMP_NE
881 || CI->getPredicate() == ICmpInst::ICMP_EQ)
882 continue;
883
884 // Unable to handle triangle loops at the moment.
885 // In triangle loop, split condition is in header and one of the
886 // the split destination is loop latch. If split condition is EQ
887 // then such loops are already handle in processOneIterationLoop().
888 if (Header == (*I)
889 && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
890 continue;
891
892 // If the block does not dominate the latch then this is not a diamond.
893 // Such loop may not benefit from index split.
894 if (!DT->dominates((*I), Latch))
895 continue;
896
897 // If split condition branches heads do not have single predecessor,
898 // SplitCondBlock, then is not possible to remove inactive branch.
899 if (!BR->getSuccessor(0)->getSinglePredecessor()
900 || !BR->getSuccessor(1)->getSinglePredecessor())
901 return false;
902
903 // If the merge point for BR is not loop latch then skip this condition.
904 if (BR->getSuccessor(0) != Latch) {
905 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
906 assert (DF0 != DF->end() && "Unable to find dominance frontier");
907 if (!DF0->second.count(Latch))
908 continue;
909 }
910
911 if (BR->getSuccessor(1) != Latch) {
912 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
913 assert (DF1 != DF->end() && "Unable to find dominance frontier");
914 if (!DF1->second.count(Latch))
915 continue;
916 }
917 SplitCondition = CI;
918 SBR = BR;
919 break;
920 }
921
922 if (!SplitCondition)
923 return false;
924
925 // If the predicate sign does not match then skip.
926 if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
927 return false;
928
929 unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
930 unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
931 Value *SplitValue = SplitCondition->getOperand(SVOpNum);
932 if (!L->isLoopInvariant(SplitValue))
933 return false;
934 if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
935 return false;
936
937 // Normalize loop conditions so that it is easier to calculate new loop
938 // bounds.
939 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
940 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
941 BasicBlock *T = EBR->getSuccessor(0);
942 EBR->setSuccessor(0, EBR->getSuccessor(1));
943 EBR->setSuccessor(1, T);
944 }
945
946 if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
947 SplitCondition->setPredicate(SplitCondition->getInversePredicate());
948 BasicBlock *T = SBR->getSuccessor(0);
949 SBR->setSuccessor(0, SBR->getSuccessor(1));
950 SBR->setSuccessor(1, T);
951 }
952
953 //[*] Calculate new loop bounds.
954 Value *AEV = SplitValue;
955 Value *BSV = SplitValue;
956 bool Sign = SplitCondition->isSignedPredicate();
957 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
958
959 if (IVisLT(*ExitCondition)) {
960 if (IVisLT(*SplitCondition)) {
961 /* Do nothing */
962 }
963 else if (IVisLE(*SplitCondition)) {
964 AEV = getPlusOne(SplitValue, Sign, PHTerm);
965 BSV = getPlusOne(SplitValue, Sign, PHTerm);
966 } else {
967 assert (0 && "Unexpected split condition!");
968 }
969 }
970 else if (IVisLE(*ExitCondition)) {
971 if (IVisLT(*SplitCondition)) {
972 AEV = getMinusOne(SplitValue, Sign, PHTerm);
973 }
974 else if (IVisLE(*SplitCondition)) {
975 BSV = getPlusOne(SplitValue, Sign, PHTerm);
976 } else {
977 assert (0 && "Unexpected split condition!");
978 }
979 } else {
980 assert (0 && "Unexpected exit condition!");
981 }
982 AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
983 BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
984
985 // [*] Clone Loop
986 DenseMap<const Value *, Value *> ValueMap;
987 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
988 Loop *ALoop = L;
989
990 // [*] ALoop's exiting edge enters BLoop's header.
991 // ALoop's original exit block becomes BLoop's exit block.
992 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
993 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
994 BranchInst *A_ExitInsn =
995 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
996 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
997 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
998 BasicBlock *B_Header = BLoop->getHeader();
999 if (ALoop->contains(B_ExitBlock)) {
1000 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1001 A_ExitInsn->setSuccessor(0, B_Header);
1002 } else
1003 A_ExitInsn->setSuccessor(1, B_Header);
1004
1005 // [*] Update ALoop's exit value using new exit value.
1006 ExitCondition->setOperand(EVOpNum, AEV);
1007
1008 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1009 // original loop's preheader. Add incoming PHINode values from
1010 // ALoop's exiting block. Update BLoop header's domiantor info.
1011
1012 // Collect inverse map of Header PHINodes.
1013 DenseMap<Value *, Value *> InverseMap;
1014 for (BasicBlock::iterator BI = ALoop->getHeader()->begin(),
1015 BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
1016 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1017 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1018 InverseMap[PNClone] = PN;
1019 } else
1020 break;
1021 }
1022
1023 BasicBlock *A_Preheader = ALoop->getLoopPreheader();
1024 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1025 BI != BE; ++BI) {
1026 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1027 // Remove incoming value from original preheader.
1028 PN->removeIncomingValue(A_Preheader);
1029
1030 // Add incoming value from A_ExitingBlock.
1031 if (PN == B_IndVar)
1032 PN->addIncoming(BSV, A_ExitingBlock);
1033 else {
1034 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1035 Value *V2 = NULL;
1036 // If loop header is also loop exiting block then
1037 // OrigPN is incoming value for B loop header.
1038 if (A_ExitingBlock == ALoop->getHeader())
1039 V2 = OrigPN;
1040 else
1041 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1042 PN->addIncoming(V2, A_ExitingBlock);
1043 }
1044 } else
1045 break;
1046 }
1047
1048 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1049 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1050
1051 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1052 // block. Remove incoming PHINode values from ALoop's exiting block.
1053 // Add new incoming values from BLoop's incoming exiting value.
1054 // Update BLoop exit block's dominator info..
1055 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1056 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1057 BI != BE; ++BI) {
1058 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1059 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1060 B_ExitingBlock);
1061 PN->removeIncomingValue(A_ExitingBlock);
1062 } else
1063 break;
1064 }
1065
1066 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1067 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1068
Dan Gohmanf159ccd2009-04-29 22:01:05 +00001069 //[*] Split ALoop's exit edge. This creates a new block which
Devang Patel38310052008-12-04 21:38:42 +00001070 // serves two purposes. First one is to hold PHINode defnitions
1071 // to ensure that ALoop's LCSSA form. Second use it to act
1072 // as a preheader for BLoop.
1073 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1074
1075 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1076 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1077 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1078 BI != BE; ++BI) {
1079 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1080 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1081 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1082 newPHI->addIncoming(V1, A_ExitingBlock);
1083 A_ExitBlock->getInstList().push_front(newPHI);
1084 PN->removeIncomingValue(A_ExitBlock);
1085 PN->addIncoming(newPHI, A_ExitBlock);
1086 } else
1087 break;
1088 }
1089
1090 //[*] Eliminate split condition's inactive branch from ALoop.
1091 BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1092 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1093 BasicBlock *A_InactiveBranch = NULL;
1094 BasicBlock *A_ActiveBranch = NULL;
1095 A_ActiveBranch = A_BR->getSuccessor(0);
1096 A_InactiveBranch = A_BR->getSuccessor(1);
1097 A_BR->setUnconditionalDest(A_ActiveBranch);
1098 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1099
1100 //[*] Eliminate split condition's inactive branch in from BLoop.
1101 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1102 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1103 BasicBlock *B_InactiveBranch = NULL;
1104 BasicBlock *B_ActiveBranch = NULL;
1105 B_ActiveBranch = B_BR->getSuccessor(1);
1106 B_InactiveBranch = B_BR->getSuccessor(0);
1107 B_BR->setUnconditionalDest(B_ActiveBranch);
1108 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1109
1110 BasicBlock *A_Header = ALoop->getHeader();
1111 if (A_ExitingBlock == A_Header)
1112 return true;
1113
1114 //[*] Move exit condition into split condition block to avoid
1115 // executing dead loop iteration.
1116 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1117 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1118 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1119
1120 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1121 cast<ICmpInst>(SplitCondition), IndVar, IVIncrement,
1122 ALoop, EVOpNum);
1123
1124 moveExitCondition(B_SplitCondBlock, B_ActiveBranch,
1125 B_ExitBlock, B_ExitCondition,
1126 B_SplitCondition, B_IndVar, B_IndVarIncrement,
1127 BLoop, EVOpNum);
1128
1129 NumIndexSplit++;
1130 return true;
1131}
1132
1133/// cleanBlock - A block is considered clean if all non terminal instructions
1134/// are either, PHINodes, IV based.
1135bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1136 Instruction *Terminator = BB->getTerminator();
1137 for(BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1138 BI != BE; ++BI) {
1139 Instruction *I = BI;
1140
1141 if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
Devang Pateld96c60d2009-02-06 06:19:06 +00001142 || I == SplitCondition || IVBasedValues.count(I)
1143 || isa<DbgInfoIntrinsic>(I))
Devang Patel38310052008-12-04 21:38:42 +00001144 continue;
1145
Duncan Sands7af1c782009-05-06 06:49:50 +00001146 if (I->mayHaveSideEffects())
Devang Patel38310052008-12-04 21:38:42 +00001147 return false;
1148
1149 // I is used only inside this block then it is OK.
1150 bool usedOutsideBB = false;
1151 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1152 UI != UE; ++UI) {
1153 Instruction *U = cast<Instruction>(UI);
1154 if (U->getParent() != BB)
1155 usedOutsideBB = true;
1156 }
1157 if (!usedOutsideBB)
1158 continue;
1159
1160 // Otherwise we have a instruction that may not allow loop spliting.
1161 return false;
1162 }
1163 return true;
1164}
1165
Devang Patel042b8772008-12-08 17:07:24 +00001166/// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001167/// IV based value is less than the loop invariant then return the loop
1168/// invariant. Otherwise return NULL.
1169Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1170 ICmpInst::Predicate P = Op.getPredicate();
1171 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1172 && IVBasedValues.count(Op.getOperand(0))
1173 && L->isLoopInvariant(Op.getOperand(1)))
1174 return Op.getOperand(1);
1175
1176 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1177 && IVBasedValues.count(Op.getOperand(1))
1178 && L->isLoopInvariant(Op.getOperand(0)))
1179 return Op.getOperand(0);
1180
1181 return NULL;
1182}
1183
Devang Patel042b8772008-12-08 17:07:24 +00001184/// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001185/// IV based value is less than or equal to the loop invariant then
1186/// return the loop invariant. Otherwise return NULL.
1187Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1188 ICmpInst::Predicate P = Op.getPredicate();
1189 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1190 && IVBasedValues.count(Op.getOperand(0))
1191 && L->isLoopInvariant(Op.getOperand(1)))
1192 return Op.getOperand(1);
1193
1194 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1195 && IVBasedValues.count(Op.getOperand(1))
1196 && L->isLoopInvariant(Op.getOperand(0)))
1197 return Op.getOperand(0);
1198
1199 return NULL;
1200}
1201
Devang Patel042b8772008-12-08 17:07:24 +00001202/// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001203/// IV based value is greater than the loop invariant then return the loop
1204/// invariant. Otherwise return NULL.
1205Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1206 ICmpInst::Predicate P = Op.getPredicate();
1207 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1208 && IVBasedValues.count(Op.getOperand(0))
1209 && L->isLoopInvariant(Op.getOperand(1)))
1210 return Op.getOperand(1);
1211
1212 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1213 && IVBasedValues.count(Op.getOperand(1))
1214 && L->isLoopInvariant(Op.getOperand(0)))
1215 return Op.getOperand(0);
1216
1217 return NULL;
1218}
1219
Devang Patel042b8772008-12-08 17:07:24 +00001220/// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001221/// IV based value is greater than or equal to the loop invariant then
1222/// return the loop invariant. Otherwise return NULL.
1223Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1224 ICmpInst::Predicate P = Op.getPredicate();
1225 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1226 && IVBasedValues.count(Op.getOperand(0))
1227 && L->isLoopInvariant(Op.getOperand(1)))
1228 return Op.getOperand(1);
1229
1230 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1231 && IVBasedValues.count(Op.getOperand(1))
1232 && L->isLoopInvariant(Op.getOperand(0)))
1233 return Op.getOperand(0);
1234
1235 return NULL;
1236}
1237