blob: 76878274ee86de0d9905f1baff2373e6aea0a2db [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"
Devang Patel95fd7172007-08-08 21:39:47 +000020#include "llvm/Analysis/Dominators.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000021#include "llvm/Support/Compiler.h"
22#include "llvm/ADT/Statistic.h"
23
24using namespace llvm;
25
26STATISTIC(NumIndexSplit, "Number of loops index split");
27
28namespace {
29
30 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
31
32 public:
33 static char ID; // Pass ID, replacement for typeid
34 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
35
36 // Index split Loop L. Return true if loop is split.
37 bool runOnLoop(Loop *L, LPPassManager &LPM);
38
39 void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<ScalarEvolution>();
41 AU.addPreserved<ScalarEvolution>();
42 AU.addRequiredID(LCSSAID);
43 AU.addPreservedID(LCSSAID);
44 AU.addPreserved<LoopInfo>();
45 AU.addRequiredID(LoopSimplifyID);
46 AU.addPreservedID(LoopSimplifyID);
Devang Patel95fd7172007-08-08 21:39:47 +000047 AU.addPreserved<DominatorTree>();
48 AU.addPreserved<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +000049 }
50
51 private:
Devang Patelc8dadbf2007-08-08 21:02:17 +000052
53 class SplitInfo {
54 public:
55 SplitInfo() : IndVar(NULL), SplitValue(NULL), ExitValue(NULL),
56 SplitCondition(NULL), ExitCondition(NULL) {}
57 // Induction variable whose range is being split by this transformation.
58 PHINode *IndVar;
59
60 // Induction variable's range is split at this value.
61 Value *SplitValue;
62
63 // Induction variable's final loop exit value.
64 Value *ExitValue;
65
66 // This compare instruction compares IndVar against SplitValue.
67 ICmpInst *SplitCondition;
68
69 // Loop exit condition.
70 ICmpInst *ExitCondition;
Devang Patel31696332007-08-08 21:18:27 +000071
72 // Clear split info.
73 void clear() {
74 IndVar = NULL;
75 SplitValue = NULL;
76 ExitValue = NULL;
77 SplitCondition = NULL;
78 ExitCondition = NULL;
79 }
Devang Patelc8dadbf2007-08-08 21:02:17 +000080 };
81
82 private:
Devang Patelbc5fe632007-08-07 00:25:56 +000083 /// Find condition inside a loop that is suitable candidate for index split.
84 void findSplitCondition();
85
86 /// processOneIterationLoop - Current loop L contains compare instruction
87 /// that compares induction variable, IndVar, agains loop invariant. If
88 /// entire (i.e. meaningful) loop body is dominated by this compare
89 /// instruction then loop body is executed only for one iteration. In
90 /// such case eliminate loop structure surrounding this loop body. For
Devang Patelc8dadbf2007-08-08 21:02:17 +000091 bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
Devang Patelbc5fe632007-08-07 00:25:56 +000092
93 // If loop header includes loop variant instruction operands then
94 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000095 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000096
97 // If Exit block includes loop variant instructions then this
98 // loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000099 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000100
Devang Patelc8dadbf2007-08-08 21:02:17 +0000101 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000102
103 private:
104
105 // Current Loop.
106 Loop *L;
107 ScalarEvolution *SE;
108
Devang Patelc8dadbf2007-08-08 21:02:17 +0000109 SmallVector<SplitInfo, 4> SplitData;
Devang Patelbc5fe632007-08-07 00:25:56 +0000110 };
111
112 char LoopIndexSplit::ID = 0;
113 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
114}
115
116LoopPass *llvm::createLoopIndexSplitPass() {
117 return new LoopIndexSplit();
118}
119
120// Index split Loop L. Return true if loop is split.
121bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
122 bool Changed = false;
123 L = IncomingLoop;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000124
Devang Patelbc5fe632007-08-07 00:25:56 +0000125 SE = &getAnalysis<ScalarEvolution>();
126
127 findSplitCondition();
128
Devang Patelc8dadbf2007-08-08 21:02:17 +0000129 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000130 return false;
131
Devang Patelc8dadbf2007-08-08 21:02:17 +0000132 // First see if it is possible to eliminate loop itself or not.
133 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
134 E = SplitData.end(); SI != E; ++SI) {
135 SplitInfo &SD = *SI;
136 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
137 Changed = processOneIterationLoop(SD,LPM);
138 if (Changed) {
139 ++NumIndexSplit;
140 // If is loop is eliminated then nothing else to do here.
141 return Changed;
142 }
143 }
144 }
145
146 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
147 E = SplitData.end(); SI != E; ++SI) {
148 SplitInfo &SD = *SI;
149
150 // ICM_EQs are already handled above.
151 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
152 continue;
153
154 // FIXME : Collect Spliting cost for all SD. Only operate on profitable SDs.
155 Changed = splitLoop(SD);
156 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000157
158 if (Changed)
159 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000160
Devang Patelbc5fe632007-08-07 00:25:56 +0000161 return Changed;
162}
163
164/// Find condition inside a loop that is suitable candidate for index split.
165void LoopIndexSplit::findSplitCondition() {
166
Devang Patelc8dadbf2007-08-08 21:02:17 +0000167 SplitInfo SD;
168 BasicBlock *Header = L->getHeader();
Devang Patelbc5fe632007-08-07 00:25:56 +0000169
170 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
171 PHINode *PN = cast<PHINode>(I);
172
173 if (!PN->getType()->isInteger())
174 continue;
175
176 SCEVHandle SCEV = SE->getSCEV(PN);
177 if (!isa<SCEVAddRecExpr>(SCEV))
178 continue;
179
180 // If this phi node is used in a compare instruction then it is a
181 // split condition candidate.
182 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
183 UI != E; ++UI) {
184 if (ICmpInst *CI = dyn_cast<ICmpInst>(*UI)) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000185 SD.SplitCondition = CI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000186 break;
187 }
188 }
189
190 // Valid SplitCondition's one operand is phi node and the other operand
191 // is loop invariant.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000192 if (SD.SplitCondition) {
193 if (SD.SplitCondition->getOperand(0) != PN)
194 SD.SplitValue = SD.SplitCondition->getOperand(0);
Devang Patelbc5fe632007-08-07 00:25:56 +0000195 else
Devang Patelc8dadbf2007-08-08 21:02:17 +0000196 SD.SplitValue = SD.SplitCondition->getOperand(1);
197 SCEVHandle ValueSCEV = SE->getSCEV(SD.SplitValue);
Devang Patelbc5fe632007-08-07 00:25:56 +0000198
199 // If SplitValue is not invariant then SplitCondition is not appropriate.
200 if (!ValueSCEV->isLoopInvariant(L))
Devang Patelc8dadbf2007-08-08 21:02:17 +0000201 SD.SplitCondition = NULL;
Devang Patelbc5fe632007-08-07 00:25:56 +0000202 }
203
204 // We are looking for only one split condition.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000205 if (SD.SplitCondition) {
206 SD.IndVar = PN;
207 SplitData.push_back(SD);
Devang Patel31696332007-08-08 21:18:27 +0000208 // Before reusing SD for next split condition clear its content.
209 SD.clear();
Devang Patelbc5fe632007-08-07 00:25:56 +0000210 }
211 }
212}
213
214/// processOneIterationLoop - Current loop L contains compare instruction
215/// that compares induction variable, IndVar, against loop invariant. If
216/// entire (i.e. meaningful) loop body is dominated by this compare
217/// instruction then loop body is executed only once. In such case eliminate
218/// loop structure surrounding this loop body. For example,
219/// for (int i = start; i < end; ++i) {
220/// if ( i == somevalue) {
221/// loop_body
222/// }
223/// }
224/// can be transformed into
225/// if (somevalue >= start && somevalue < end) {
226/// i = somevalue;
227/// loop_body
228/// }
Devang Patelc8dadbf2007-08-08 21:02:17 +0000229bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000230
231 BasicBlock *Header = L->getHeader();
232
233 // First of all, check if SplitCondition dominates entire loop body
234 // or not.
235
236 // If SplitCondition is not in loop header then this loop is not suitable
237 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000238 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000239 return false;
240
241 // If one of the Header block's successor is not an exit block then this
242 // loop is not a suitable candidate.
243 BasicBlock *ExitBlock = NULL;
244 for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
245 if (L->isLoopExit(*SI)) {
246 ExitBlock = *SI;
247 break;
248 }
249 }
250
251 if (!ExitBlock)
252 return false;
253
254 // If loop header includes loop variant instruction operands then
255 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000256 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000257 return false;
258
259 // If Exit block includes loop variant instructions then this
260 // loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000261 if (!safeExitBlock(SD, ExitBlock))
Devang Patelbc5fe632007-08-07 00:25:56 +0000262 return false;
263
Devang Patel2bcb5012007-08-08 01:51:27 +0000264 // Update CFG.
265
266 // As a first step to break this loop, remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000267 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000268 BasicBlock *LatchSucc = NULL;
269 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
270 if (!BR)
271 return false;
272 Header->removePredecessor(Latch);
273 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
274 SI != E; ++SI) {
275 if (Header != *SI)
276 LatchSucc = *SI;
277 }
278 BR->setUnconditionalDest(LatchSucc);
279
Devang Patelbc5fe632007-08-07 00:25:56 +0000280 BasicBlock *Preheader = L->getLoopPreheader();
281 Instruction *Terminator = Header->getTerminator();
Devang Patelc8dadbf2007-08-08 21:02:17 +0000282 Value *StartValue = SD.IndVar->getIncomingValueForBlock(Preheader);
Devang Patelbc5fe632007-08-07 00:25:56 +0000283
Devang Patelbc5fe632007-08-07 00:25:56 +0000284 // Replace split condition in header.
285 // Transform
286 // SplitCondition : icmp eq i32 IndVar, SplitValue
287 // into
288 // c1 = icmp uge i32 SplitValue, StartValue
289 // c2 = icmp ult i32 vSplitValue, ExitValue
290 // and i32 c1, c2
Devang Patelc8dadbf2007-08-08 21:02:17 +0000291 bool SignedPredicate = SD.ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000292 Instruction *C1 = new ICmpInst(SignedPredicate ?
293 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000294 SD.SplitValue, StartValue, "lisplit",
295 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000296 Instruction *C2 = new ICmpInst(SignedPredicate ?
297 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000298 SD.SplitValue, SD.ExitValue, "lisplit",
299 Terminator);
300 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
301 Terminator);
302 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
303 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000304
Devang Patelbc5fe632007-08-07 00:25:56 +0000305 // Now, clear latch block. Remove instructions that are responsible
306 // to increment induction variable.
307 Instruction *LTerminator = Latch->getTerminator();
308 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
309 LB != LE; ) {
310 Instruction *I = LB;
311 ++LB;
312 if (isa<PHINode>(I) || I == LTerminator)
313 continue;
314
315 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000316 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000317 }
318
319 LPM.deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000320
321 // Update Dominator Info.
322 // Only CFG change done is to remove Latch to Header edge. This
323 // does not change dominator tree because Latch did not dominate
324 // Header.
325 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
326 DominanceFrontier::iterator HeaderDF = DF->find(Header);
327 if (HeaderDF != DF->end())
328 DF->removeFromFrontier(HeaderDF, Header);
329
330 DominanceFrontier::iterator LatchDF = DF->find(Latch);
331 if (LatchDF != DF->end())
332 DF->removeFromFrontier(LatchDF, Header);
333 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000334 return true;
335}
336
337// If loop header includes loop variant instruction operands then
338// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000339bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000340
341 Instruction *Terminator = Header->getTerminator();
342 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
343 BI != BE; ++BI) {
344 Instruction *I = BI;
345
Devang Patel2bcb5012007-08-08 01:51:27 +0000346 // PHI Nodes are OK. FIXME : Handle last value assignments.
Devang Patelbc5fe632007-08-07 00:25:56 +0000347 if (isa<PHINode>(I))
348 continue;
349
350 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000351 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000352 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000353
354 // Terminator is also harmless.
355 if (I == Terminator)
356 continue;
357
358 // Otherwise we have a instruction that may not be safe.
359 return false;
360 }
361
362 return true;
363}
364
365// If Exit block includes loop variant instructions then this
366// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000367bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000368
Devang Patelbc5fe632007-08-07 00:25:56 +0000369 Instruction *IndVarIncrement = NULL;
Devang Patel2bcb5012007-08-08 01:51:27 +0000370
Devang Patelbc5fe632007-08-07 00:25:56 +0000371 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
372 BI != BE; ++BI) {
373 Instruction *I = BI;
374
Devang Patel2bcb5012007-08-08 01:51:27 +0000375 // PHI Nodes are OK. FIXME : Handle last value assignments.
Devang Patelbc5fe632007-08-07 00:25:56 +0000376 if (isa<PHINode>(I))
377 continue;
378
379 // Check if I is induction variable increment instruction.
380 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) {
381 if (BOp->getOpcode() != Instruction::Add)
382 return false;
383
384 Value *Op0 = BOp->getOperand(0);
385 Value *Op1 = BOp->getOperand(1);
386 PHINode *PN = NULL;
387 ConstantInt *CI = NULL;
388
389 if ((PN = dyn_cast<PHINode>(Op0))) {
390 if ((CI = dyn_cast<ConstantInt>(Op1)))
391 IndVarIncrement = I;
392 } else
393 if ((PN = dyn_cast<PHINode>(Op1))) {
394 if ((CI = dyn_cast<ConstantInt>(Op0)))
395 IndVarIncrement = I;
396 }
397
Devang Patelc8dadbf2007-08-08 21:02:17 +0000398 if (IndVarIncrement && PN == SD.IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000399 continue;
400 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000401
Devang Patelbc5fe632007-08-07 00:25:56 +0000402 // I is an Exit condition if next instruction is block terminator.
403 // Exit condition is OK if it compares loop invariant exit value,
404 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000405 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000406 ++BI;
407 Instruction *N = BI;
408 if (N == ExitBlock->getTerminator()) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000409 SD.ExitCondition = EC;
Devang Patel2bcb5012007-08-08 01:51:27 +0000410 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000411 }
412 }
413
414 // Otherwise we have instruction that may not be safe.
415 return false;
416 }
417
418 // Check if Exit condition is comparing induction variable against
419 // loop invariant value. If one operand is induction variable and
420 // the other operand is loop invaraint then Exit condition is safe.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000421 if (SD.ExitCondition) {
422 Value *Op0 = SD.ExitCondition->getOperand(0);
423 Value *Op1 = SD.ExitCondition->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000424
425 Instruction *Insn0 = dyn_cast<Instruction>(Op0);
426 Instruction *Insn1 = dyn_cast<Instruction>(Op1);
427
428 if (Insn0 && Insn0 == IndVarIncrement)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000429 SD.ExitValue = Op1;
Devang Patelbc5fe632007-08-07 00:25:56 +0000430 else if (Insn1 && Insn1 == IndVarIncrement)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000431 SD.ExitValue = Op0;
Devang Patelbc5fe632007-08-07 00:25:56 +0000432
Devang Patelc8dadbf2007-08-08 21:02:17 +0000433 SCEVHandle ValueSCEV = SE->getSCEV(SD.ExitValue);
Devang Patelbc5fe632007-08-07 00:25:56 +0000434 if (!ValueSCEV->isLoopInvariant(L))
435 return false;
436 }
437
438 // We could not find any reason to consider ExitBlock unsafe.
439 return true;
440}
441
Devang Patelc8dadbf2007-08-08 21:02:17 +0000442bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000443 // FIXME :)
444 return false;
445}