blob: 37adeeff337f2e00198a475715b7cd4f801fcc8a [file] [log] [blame]
Devang Patelbc5fe632007-08-07 00:25:56 +00001//===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Devang Patel and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Index Splitting Pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "loop-index-split"
15
Devang Patelbc5fe632007-08-07 00:25:56 +000016#include "llvm/Transforms/Scalar.h"
Devang Patel3719d4f2007-08-07 23:17:52 +000017#include "llvm/Function.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000018#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/ScalarEvolutionExpander.h"
20#include "llvm/Support/Compiler.h"
21#include "llvm/ADT/Statistic.h"
22
23using namespace llvm;
24
25STATISTIC(NumIndexSplit, "Number of loops index split");
26
27namespace {
28
29 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
30
31 public:
32 static char ID; // Pass ID, replacement for typeid
33 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
34
35 // Index split Loop L. Return true if loop is split.
36 bool runOnLoop(Loop *L, LPPassManager &LPM);
37
38 void getAnalysisUsage(AnalysisUsage &AU) const {
39 AU.addRequired<ScalarEvolution>();
40 AU.addPreserved<ScalarEvolution>();
41 AU.addRequiredID(LCSSAID);
42 AU.addPreservedID(LCSSAID);
43 AU.addPreserved<LoopInfo>();
44 AU.addRequiredID(LoopSimplifyID);
45 AU.addPreservedID(LoopSimplifyID);
46 }
47
48 private:
Devang Patelc8dadbf2007-08-08 21:02:17 +000049
50 class SplitInfo {
51 public:
52 SplitInfo() : IndVar(NULL), SplitValue(NULL), ExitValue(NULL),
53 SplitCondition(NULL), ExitCondition(NULL) {}
54 // Induction variable whose range is being split by this transformation.
55 PHINode *IndVar;
56
57 // Induction variable's range is split at this value.
58 Value *SplitValue;
59
60 // Induction variable's final loop exit value.
61 Value *ExitValue;
62
63 // This compare instruction compares IndVar against SplitValue.
64 ICmpInst *SplitCondition;
65
66 // Loop exit condition.
67 ICmpInst *ExitCondition;
68 };
69
70 private:
Devang Patelbc5fe632007-08-07 00:25:56 +000071 /// Find condition inside a loop that is suitable candidate for index split.
72 void findSplitCondition();
73
74 /// processOneIterationLoop - Current loop L contains compare instruction
75 /// that compares induction variable, IndVar, agains loop invariant. If
76 /// entire (i.e. meaningful) loop body is dominated by this compare
77 /// instruction then loop body is executed only for one iteration. In
78 /// such case eliminate loop structure surrounding this loop body. For
Devang Patelc8dadbf2007-08-08 21:02:17 +000079 bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
Devang Patelbc5fe632007-08-07 00:25:56 +000080
81 // If loop header includes loop variant instruction operands then
82 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000083 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000084
85 // If Exit block includes loop variant instructions then this
86 // loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000087 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000088
Devang Patelc8dadbf2007-08-08 21:02:17 +000089 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +000090
91 private:
92
93 // Current Loop.
94 Loop *L;
95 ScalarEvolution *SE;
96
Devang Patelc8dadbf2007-08-08 21:02:17 +000097 SmallVector<SplitInfo, 4> SplitData;
Devang Patelbc5fe632007-08-07 00:25:56 +000098 };
99
100 char LoopIndexSplit::ID = 0;
101 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
102}
103
104LoopPass *llvm::createLoopIndexSplitPass() {
105 return new LoopIndexSplit();
106}
107
108// Index split Loop L. Return true if loop is split.
109bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
110 bool Changed = false;
111 L = IncomingLoop;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000112
Devang Patelbc5fe632007-08-07 00:25:56 +0000113 SE = &getAnalysis<ScalarEvolution>();
114
115 findSplitCondition();
116
Devang Patelc8dadbf2007-08-08 21:02:17 +0000117 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000118 return false;
119
Devang Patelc8dadbf2007-08-08 21:02:17 +0000120 // First see if it is possible to eliminate loop itself or not.
121 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
122 E = SplitData.end(); SI != E; ++SI) {
123 SplitInfo &SD = *SI;
124 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
125 Changed = processOneIterationLoop(SD,LPM);
126 if (Changed) {
127 ++NumIndexSplit;
128 // If is loop is eliminated then nothing else to do here.
129 return Changed;
130 }
131 }
132 }
133
134 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
135 E = SplitData.end(); SI != E; ++SI) {
136 SplitInfo &SD = *SI;
137
138 // ICM_EQs are already handled above.
139 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
140 continue;
141
142 // FIXME : Collect Spliting cost for all SD. Only operate on profitable SDs.
143 Changed = splitLoop(SD);
144 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000145
146 if (Changed)
147 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000148
Devang Patelbc5fe632007-08-07 00:25:56 +0000149 return Changed;
150}
151
152/// Find condition inside a loop that is suitable candidate for index split.
153void LoopIndexSplit::findSplitCondition() {
154
Devang Patelc8dadbf2007-08-08 21:02:17 +0000155 SplitInfo SD;
156 BasicBlock *Header = L->getHeader();
Devang Patelbc5fe632007-08-07 00:25:56 +0000157
158 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
159 PHINode *PN = cast<PHINode>(I);
160
161 if (!PN->getType()->isInteger())
162 continue;
163
164 SCEVHandle SCEV = SE->getSCEV(PN);
165 if (!isa<SCEVAddRecExpr>(SCEV))
166 continue;
167
168 // If this phi node is used in a compare instruction then it is a
169 // split condition candidate.
170 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
171 UI != E; ++UI) {
172 if (ICmpInst *CI = dyn_cast<ICmpInst>(*UI)) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000173 SD.SplitCondition = CI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000174 break;
175 }
176 }
177
178 // Valid SplitCondition's one operand is phi node and the other operand
179 // is loop invariant.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000180 if (SD.SplitCondition) {
181 if (SD.SplitCondition->getOperand(0) != PN)
182 SD.SplitValue = SD.SplitCondition->getOperand(0);
Devang Patelbc5fe632007-08-07 00:25:56 +0000183 else
Devang Patelc8dadbf2007-08-08 21:02:17 +0000184 SD.SplitValue = SD.SplitCondition->getOperand(1);
185 SCEVHandle ValueSCEV = SE->getSCEV(SD.SplitValue);
Devang Patelbc5fe632007-08-07 00:25:56 +0000186
187 // If SplitValue is not invariant then SplitCondition is not appropriate.
188 if (!ValueSCEV->isLoopInvariant(L))
Devang Patelc8dadbf2007-08-08 21:02:17 +0000189 SD.SplitCondition = NULL;
Devang Patelbc5fe632007-08-07 00:25:56 +0000190 }
191
192 // We are looking for only one split condition.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000193 if (SD.SplitCondition) {
194 SD.IndVar = PN;
195 SplitData.push_back(SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000196 }
197 }
198}
199
200/// processOneIterationLoop - Current loop L contains compare instruction
201/// that compares induction variable, IndVar, against loop invariant. If
202/// entire (i.e. meaningful) loop body is dominated by this compare
203/// instruction then loop body is executed only once. In such case eliminate
204/// loop structure surrounding this loop body. For example,
205/// for (int i = start; i < end; ++i) {
206/// if ( i == somevalue) {
207/// loop_body
208/// }
209/// }
210/// can be transformed into
211/// if (somevalue >= start && somevalue < end) {
212/// i = somevalue;
213/// loop_body
214/// }
Devang Patelc8dadbf2007-08-08 21:02:17 +0000215bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000216
217 BasicBlock *Header = L->getHeader();
218
219 // First of all, check if SplitCondition dominates entire loop body
220 // or not.
221
222 // If SplitCondition is not in loop header then this loop is not suitable
223 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000224 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000225 return false;
226
227 // If one of the Header block's successor is not an exit block then this
228 // loop is not a suitable candidate.
229 BasicBlock *ExitBlock = NULL;
230 for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
231 if (L->isLoopExit(*SI)) {
232 ExitBlock = *SI;
233 break;
234 }
235 }
236
237 if (!ExitBlock)
238 return false;
239
240 // If loop header includes loop variant instruction operands then
241 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000242 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000243 return false;
244
245 // If Exit block includes loop variant instructions then this
246 // loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000247 if (!safeExitBlock(SD, ExitBlock))
Devang Patelbc5fe632007-08-07 00:25:56 +0000248 return false;
249
Devang Patel2bcb5012007-08-08 01:51:27 +0000250 // Update CFG.
251
252 // As a first step to break this loop, remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000253 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000254 BasicBlock *LatchSucc = NULL;
255 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
256 if (!BR)
257 return false;
258 Header->removePredecessor(Latch);
259 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
260 SI != E; ++SI) {
261 if (Header != *SI)
262 LatchSucc = *SI;
263 }
264 BR->setUnconditionalDest(LatchSucc);
265
Devang Patelbc5fe632007-08-07 00:25:56 +0000266 BasicBlock *Preheader = L->getLoopPreheader();
267 Instruction *Terminator = Header->getTerminator();
Devang Patelc8dadbf2007-08-08 21:02:17 +0000268 Value *StartValue = SD.IndVar->getIncomingValueForBlock(Preheader);
Devang Patelbc5fe632007-08-07 00:25:56 +0000269
Devang Patelbc5fe632007-08-07 00:25:56 +0000270 // Replace split condition in header.
271 // Transform
272 // SplitCondition : icmp eq i32 IndVar, SplitValue
273 // into
274 // c1 = icmp uge i32 SplitValue, StartValue
275 // c2 = icmp ult i32 vSplitValue, ExitValue
276 // and i32 c1, c2
Devang Patelc8dadbf2007-08-08 21:02:17 +0000277 bool SignedPredicate = SD.ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000278 Instruction *C1 = new ICmpInst(SignedPredicate ?
279 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000280 SD.SplitValue, StartValue, "lisplit",
281 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000282 Instruction *C2 = new ICmpInst(SignedPredicate ?
283 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000284 SD.SplitValue, SD.ExitValue, "lisplit",
285 Terminator);
286 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
287 Terminator);
288 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
289 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000290
Devang Patelbc5fe632007-08-07 00:25:56 +0000291 // Now, clear latch block. Remove instructions that are responsible
292 // to increment induction variable.
293 Instruction *LTerminator = Latch->getTerminator();
294 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
295 LB != LE; ) {
296 Instruction *I = LB;
297 ++LB;
298 if (isa<PHINode>(I) || I == LTerminator)
299 continue;
300
301 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000302 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000303 }
304
305 LPM.deleteLoopFromQueue(L);
306 return true;
307}
308
309// If loop header includes loop variant instruction operands then
310// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000311bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000312
313 Instruction *Terminator = Header->getTerminator();
314 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
315 BI != BE; ++BI) {
316 Instruction *I = BI;
317
Devang Patel2bcb5012007-08-08 01:51:27 +0000318 // PHI Nodes are OK. FIXME : Handle last value assignments.
Devang Patelbc5fe632007-08-07 00:25:56 +0000319 if (isa<PHINode>(I))
320 continue;
321
322 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000323 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000324 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000325
326 // Terminator is also harmless.
327 if (I == Terminator)
328 continue;
329
330 // Otherwise we have a instruction that may not be safe.
331 return false;
332 }
333
334 return true;
335}
336
337// If Exit block includes loop variant instructions then this
338// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000339bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000340
Devang Patelbc5fe632007-08-07 00:25:56 +0000341 Instruction *IndVarIncrement = NULL;
Devang Patel2bcb5012007-08-08 01:51:27 +0000342
Devang Patelbc5fe632007-08-07 00:25:56 +0000343 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
344 BI != BE; ++BI) {
345 Instruction *I = BI;
346
Devang Patel2bcb5012007-08-08 01:51:27 +0000347 // PHI Nodes are OK. FIXME : Handle last value assignments.
Devang Patelbc5fe632007-08-07 00:25:56 +0000348 if (isa<PHINode>(I))
349 continue;
350
351 // Check if I is induction variable increment instruction.
352 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) {
353 if (BOp->getOpcode() != Instruction::Add)
354 return false;
355
356 Value *Op0 = BOp->getOperand(0);
357 Value *Op1 = BOp->getOperand(1);
358 PHINode *PN = NULL;
359 ConstantInt *CI = NULL;
360
361 if ((PN = dyn_cast<PHINode>(Op0))) {
362 if ((CI = dyn_cast<ConstantInt>(Op1)))
363 IndVarIncrement = I;
364 } else
365 if ((PN = dyn_cast<PHINode>(Op1))) {
366 if ((CI = dyn_cast<ConstantInt>(Op0)))
367 IndVarIncrement = I;
368 }
369
Devang Patelc8dadbf2007-08-08 21:02:17 +0000370 if (IndVarIncrement && PN == SD.IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000371 continue;
372 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000373
Devang Patelbc5fe632007-08-07 00:25:56 +0000374 // I is an Exit condition if next instruction is block terminator.
375 // Exit condition is OK if it compares loop invariant exit value,
376 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000377 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000378 ++BI;
379 Instruction *N = BI;
380 if (N == ExitBlock->getTerminator()) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000381 SD.ExitCondition = EC;
Devang Patel2bcb5012007-08-08 01:51:27 +0000382 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000383 }
384 }
385
386 // Otherwise we have instruction that may not be safe.
387 return false;
388 }
389
390 // Check if Exit condition is comparing induction variable against
391 // loop invariant value. If one operand is induction variable and
392 // the other operand is loop invaraint then Exit condition is safe.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000393 if (SD.ExitCondition) {
394 Value *Op0 = SD.ExitCondition->getOperand(0);
395 Value *Op1 = SD.ExitCondition->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000396
397 Instruction *Insn0 = dyn_cast<Instruction>(Op0);
398 Instruction *Insn1 = dyn_cast<Instruction>(Op1);
399
400 if (Insn0 && Insn0 == IndVarIncrement)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000401 SD.ExitValue = Op1;
Devang Patelbc5fe632007-08-07 00:25:56 +0000402 else if (Insn1 && Insn1 == IndVarIncrement)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000403 SD.ExitValue = Op0;
Devang Patelbc5fe632007-08-07 00:25:56 +0000404
Devang Patelc8dadbf2007-08-08 21:02:17 +0000405 SCEVHandle ValueSCEV = SE->getSCEV(SD.ExitValue);
Devang Patelbc5fe632007-08-07 00:25:56 +0000406 if (!ValueSCEV->isLoopInvariant(L))
407 return false;
408 }
409
410 // We could not find any reason to consider ExitBlock unsafe.
411 return true;
412}
413
Devang Patelc8dadbf2007-08-08 21:02:17 +0000414bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000415 // FIXME :)
416 return false;
417}