1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Index Splitting Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-index-split"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Function.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolutionExpander.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/ADT/Statistic.h"
25 STATISTIC(NumIndexSplit, "Number of loops index split");
29 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
32 static char ID; // Pass ID, replacement for typeid
33 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
35 // Index split Loop L. Return true if loop is split.
36 bool runOnLoop(Loop *L, LPPassManager &LPM);
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);
49 /// Find condition inside a loop that is suitable candidate for index split.
50 void findSplitCondition();
52 /// processOneIterationLoop - Current loop L contains compare instruction
53 /// that compares induction variable, IndVar, agains loop invariant. If
54 /// entire (i.e. meaningful) loop body is dominated by this compare
55 /// instruction then loop body is executed only for one iteration. In
56 /// such case eliminate loop structure surrounding this loop body. For
57 bool processOneIterationLoop(LPPassManager &LPM);
59 // If loop header includes loop variant instruction operands then
60 // this loop may not be eliminated.
61 bool safeHeader(BasicBlock *BB);
63 // If Exit block includes loop variant instructions then this
64 // loop may not be eliminated.
65 bool safeExitBlock(BasicBlock *BB);
75 // Induction variable whose range is being split by this transformation.
78 // Induction variable's range is split at this value.
81 // Induction variable's final loop exit value.
84 // This compare instruction compares IndVar against SplitValue.
85 ICmpInst *SplitCondition;
87 // Loop exit condition.
88 ICmpInst *ExitCondition;
91 char LoopIndexSplit::ID = 0;
92 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
95 LoopPass *llvm::createLoopIndexSplitPass() {
96 return new LoopIndexSplit();
99 // Index split Loop L. Return true if loop is split.
100 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
101 bool Changed = false;
103 SplitCondition = NULL;
104 SE = &getAnalysis<ScalarEvolution>();
106 findSplitCondition();
111 if (SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
112 // If it is possible to eliminate loop then do so.
113 Changed = processOneIterationLoop(LPM);
115 Changed = splitLoop();
123 /// Find condition inside a loop that is suitable candidate for index split.
124 void LoopIndexSplit::findSplitCondition() {
126 BasicBlock *Header = L->getHeader();
128 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
129 PHINode *PN = cast<PHINode>(I);
131 if (!PN->getType()->isInteger())
134 SCEVHandle SCEV = SE->getSCEV(PN);
135 if (!isa<SCEVAddRecExpr>(SCEV))
138 // If this phi node is used in a compare instruction then it is a
139 // split condition candidate.
140 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
142 if (ICmpInst *CI = dyn_cast<ICmpInst>(*UI)) {
148 // Valid SplitCondition's one operand is phi node and the other operand
149 // is loop invariant.
150 if (SplitCondition) {
151 if (SplitCondition->getOperand(0) != PN)
152 SplitValue = SplitCondition->getOperand(0);
154 SplitValue = SplitCondition->getOperand(1);
155 SCEVHandle ValueSCEV = SE->getSCEV(SplitValue);
157 // If SplitValue is not invariant then SplitCondition is not appropriate.
158 if (!ValueSCEV->isLoopInvariant(L))
159 SplitCondition = NULL;
162 // We are looking for only one split condition.
163 if (SplitCondition) {
170 /// processOneIterationLoop - Current loop L contains compare instruction
171 /// that compares induction variable, IndVar, against loop invariant. If
172 /// entire (i.e. meaningful) loop body is dominated by this compare
173 /// instruction then loop body is executed only once. In such case eliminate
174 /// loop structure surrounding this loop body. For example,
175 /// for (int i = start; i < end; ++i) {
176 /// if ( i == somevalue) {
180 /// can be transformed into
181 /// if (somevalue >= start && somevalue < end) {
185 bool LoopIndexSplit::processOneIterationLoop(LPPassManager &LPM) {
187 BasicBlock *Header = L->getHeader();
189 // First of all, check if SplitCondition dominates entire loop body
192 // If SplitCondition is not in loop header then this loop is not suitable
193 // for this transformation.
194 if (SplitCondition->getParent() != Header)
197 // If one of the Header block's successor is not an exit block then this
198 // loop is not a suitable candidate.
199 BasicBlock *ExitBlock = NULL;
200 for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
201 if (L->isLoopExit(*SI)) {
210 // If loop header includes loop variant instruction operands then
211 // this loop may not be eliminated.
212 if (!safeHeader(Header))
215 // If Exit block includes loop variant instructions then this
216 // loop may not be eliminated.
217 if (!safeExitBlock(ExitBlock))
220 BasicBlock *Latch = L->getLoopLatch();
221 BasicBlock *Preheader = L->getLoopPreheader();
222 Instruction *Terminator = Header->getTerminator();
223 Value *StartValue = IndVar->getIncomingValueForBlock(Preheader);
227 // Replace split condition in header.
229 // SplitCondition : icmp eq i32 IndVar, SplitValue
231 // c1 = icmp uge i32 SplitValue, StartValue
232 // c2 = icmp ult i32 vSplitValue, ExitValue
234 bool SignedPredicate = ExitCondition->isSignedPredicate();
235 Instruction *C1 = new ICmpInst(SignedPredicate ?
236 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
237 SplitValue, StartValue, "lisplit", Terminator);
238 Instruction *C2 = new ICmpInst(SignedPredicate ?
239 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
240 SplitValue, ExitValue, "lisplit", Terminator);
241 Instruction *NSplitCond = BinaryOperator::create(Instruction::And,
242 C1, C2, "lisplit", Terminator);
243 SplitCondition->replaceAllUsesWith(NSplitCond);
244 SplitCondition->eraseFromParent();
246 // As a first step to break this loop, remove Latch to Header edge.
247 BasicBlock *LatchSucc = NULL;
248 Header->removePredecessor(Latch);
249 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
254 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
255 BR->setUnconditionalDest(LatchSucc);
257 // Now, clear latch block. Remove instructions that are responsible
258 // to increment induction variable.
259 Instruction *LTerminator = Latch->getTerminator();
260 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
264 if (isa<PHINode>(I) || I == LTerminator)
267 I->replaceAllUsesWith(UndefValue::get(I->getType()));
268 I->eraseFromParent();
271 LPM.deleteLoopFromQueue(L);
275 // If loop header includes loop variant instruction operands then
276 // this loop can not be eliminated. This is used by processOneIterationLoop().
277 bool LoopIndexSplit::safeHeader(BasicBlock *Header) {
279 Instruction *Terminator = Header->getTerminator();
280 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
288 // SplitCondition itself is OK.
289 if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) {
290 if (CI == SplitCondition)
294 // Terminator is also harmless.
298 // Otherwise we have a instruction that may not be safe.
305 // If Exit block includes loop variant instructions then this
306 // loop may not be eliminated. This is used by processOneIterationLoop().
307 bool LoopIndexSplit::safeExitBlock(BasicBlock *ExitBlock) {
309 Instruction *IndVarIncrement = NULL;
311 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
319 // Check if I is induction variable increment instruction.
320 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) {
321 if (BOp->getOpcode() != Instruction::Add)
324 Value *Op0 = BOp->getOperand(0);
325 Value *Op1 = BOp->getOperand(1);
327 ConstantInt *CI = NULL;
329 if ((PN = dyn_cast<PHINode>(Op0))) {
330 if ((CI = dyn_cast<ConstantInt>(Op1)))
333 if ((PN = dyn_cast<PHINode>(Op1))) {
334 if ((CI = dyn_cast<ConstantInt>(Op0)))
338 if (IndVarIncrement && PN == IndVar && CI->isOne())
341 // I is an Exit condition if next instruction is block terminator.
342 // Exit condition is OK if it compares loop invariant exit value,
343 // which is checked below.
344 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
347 if (N == ExitBlock->getTerminator()) {
353 // Otherwise we have instruction that may not be safe.
357 // Check if Exit condition is comparing induction variable against
358 // loop invariant value. If one operand is induction variable and
359 // the other operand is loop invaraint then Exit condition is safe.
361 Value *Op0 = ExitCondition->getOperand(0);
362 Value *Op1 = ExitCondition->getOperand(1);
364 Instruction *Insn0 = dyn_cast<Instruction>(Op0);
365 Instruction *Insn1 = dyn_cast<Instruction>(Op1);
367 if (Insn0 && Insn0 == IndVarIncrement)
369 else if (Insn1 && Insn1 == IndVarIncrement)
372 SCEVHandle ValueSCEV = SE->getSCEV(ExitValue);
373 if (!ValueSCEV->isLoopInvariant(L))
377 // We could not find any reason to consider ExitBlock unsafe.
381 bool LoopIndexSplit::splitLoop() {