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);
52 SplitInfo() : IndVar(NULL), SplitValue(NULL), ExitValue(NULL),
53 SplitCondition(NULL), ExitCondition(NULL) {}
54 // Induction variable whose range is being split by this transformation.
57 // Induction variable's range is split at this value.
60 // Induction variable's final loop exit value.
63 // This compare instruction compares IndVar against SplitValue.
64 ICmpInst *SplitCondition;
66 // Loop exit condition.
67 ICmpInst *ExitCondition;
74 SplitCondition = NULL;
80 /// Find condition inside a loop that is suitable candidate for index split.
81 void findSplitCondition();
83 /// processOneIterationLoop - Current loop L contains compare instruction
84 /// that compares induction variable, IndVar, agains loop invariant. If
85 /// entire (i.e. meaningful) loop body is dominated by this compare
86 /// instruction then loop body is executed only for one iteration. In
87 /// such case eliminate loop structure surrounding this loop body. For
88 bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
90 // If loop header includes loop variant instruction operands then
91 // this loop may not be eliminated.
92 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
94 // If Exit block includes loop variant instructions then this
95 // loop may not be eliminated.
96 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
98 bool splitLoop(SplitInfo &SD);
106 SmallVector<SplitInfo, 4> SplitData;
109 char LoopIndexSplit::ID = 0;
110 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
113 LoopPass *llvm::createLoopIndexSplitPass() {
114 return new LoopIndexSplit();
117 // Index split Loop L. Return true if loop is split.
118 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
119 bool Changed = false;
122 SE = &getAnalysis<ScalarEvolution>();
124 findSplitCondition();
126 if (SplitData.empty())
129 // First see if it is possible to eliminate loop itself or not.
130 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
131 E = SplitData.end(); SI != E; ++SI) {
133 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
134 Changed = processOneIterationLoop(SD,LPM);
137 // If is loop is eliminated then nothing else to do here.
143 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
144 E = SplitData.end(); SI != E; ++SI) {
147 // ICM_EQs are already handled above.
148 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
151 // FIXME : Collect Spliting cost for all SD. Only operate on profitable SDs.
152 Changed = splitLoop(SD);
161 /// Find condition inside a loop that is suitable candidate for index split.
162 void LoopIndexSplit::findSplitCondition() {
165 BasicBlock *Header = L->getHeader();
167 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
168 PHINode *PN = cast<PHINode>(I);
170 if (!PN->getType()->isInteger())
173 SCEVHandle SCEV = SE->getSCEV(PN);
174 if (!isa<SCEVAddRecExpr>(SCEV))
177 // If this phi node is used in a compare instruction then it is a
178 // split condition candidate.
179 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
181 if (ICmpInst *CI = dyn_cast<ICmpInst>(*UI)) {
182 SD.SplitCondition = CI;
187 // Valid SplitCondition's one operand is phi node and the other operand
188 // is loop invariant.
189 if (SD.SplitCondition) {
190 if (SD.SplitCondition->getOperand(0) != PN)
191 SD.SplitValue = SD.SplitCondition->getOperand(0);
193 SD.SplitValue = SD.SplitCondition->getOperand(1);
194 SCEVHandle ValueSCEV = SE->getSCEV(SD.SplitValue);
196 // If SplitValue is not invariant then SplitCondition is not appropriate.
197 if (!ValueSCEV->isLoopInvariant(L))
198 SD.SplitCondition = NULL;
201 // We are looking for only one split condition.
202 if (SD.SplitCondition) {
204 SplitData.push_back(SD);
205 // Before reusing SD for next split condition clear its content.
211 /// processOneIterationLoop - Current loop L contains compare instruction
212 /// that compares induction variable, IndVar, against loop invariant. If
213 /// entire (i.e. meaningful) loop body is dominated by this compare
214 /// instruction then loop body is executed only once. In such case eliminate
215 /// loop structure surrounding this loop body. For example,
216 /// for (int i = start; i < end; ++i) {
217 /// if ( i == somevalue) {
221 /// can be transformed into
222 /// if (somevalue >= start && somevalue < end) {
226 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
228 BasicBlock *Header = L->getHeader();
230 // First of all, check if SplitCondition dominates entire loop body
233 // If SplitCondition is not in loop header then this loop is not suitable
234 // for this transformation.
235 if (SD.SplitCondition->getParent() != Header)
238 // If one of the Header block's successor is not an exit block then this
239 // loop is not a suitable candidate.
240 BasicBlock *ExitBlock = NULL;
241 for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
242 if (L->isLoopExit(*SI)) {
251 // If loop header includes loop variant instruction operands then
252 // this loop may not be eliminated.
253 if (!safeHeader(SD, Header))
256 // If Exit block includes loop variant instructions then this
257 // loop may not be eliminated.
258 if (!safeExitBlock(SD, ExitBlock))
263 // As a first step to break this loop, remove Latch to Header edge.
264 BasicBlock *Latch = L->getLoopLatch();
265 BasicBlock *LatchSucc = NULL;
266 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
269 Header->removePredecessor(Latch);
270 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
275 BR->setUnconditionalDest(LatchSucc);
277 BasicBlock *Preheader = L->getLoopPreheader();
278 Instruction *Terminator = Header->getTerminator();
279 Value *StartValue = SD.IndVar->getIncomingValueForBlock(Preheader);
281 // Replace split condition in header.
283 // SplitCondition : icmp eq i32 IndVar, SplitValue
285 // c1 = icmp uge i32 SplitValue, StartValue
286 // c2 = icmp ult i32 vSplitValue, ExitValue
288 bool SignedPredicate = SD.ExitCondition->isSignedPredicate();
289 Instruction *C1 = new ICmpInst(SignedPredicate ?
290 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
291 SD.SplitValue, StartValue, "lisplit",
293 Instruction *C2 = new ICmpInst(SignedPredicate ?
294 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
295 SD.SplitValue, SD.ExitValue, "lisplit",
297 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
299 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
300 SD.SplitCondition->eraseFromParent();
302 // Now, clear latch block. Remove instructions that are responsible
303 // to increment induction variable.
304 Instruction *LTerminator = Latch->getTerminator();
305 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
309 if (isa<PHINode>(I) || I == LTerminator)
312 I->replaceAllUsesWith(UndefValue::get(I->getType()));
313 I->eraseFromParent();
316 LPM.deleteLoopFromQueue(L);
320 // If loop header includes loop variant instruction operands then
321 // this loop can not be eliminated. This is used by processOneIterationLoop().
322 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
324 Instruction *Terminator = Header->getTerminator();
325 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
329 // PHI Nodes are OK. FIXME : Handle last value assignments.
333 // SplitCondition itself is OK.
334 if (I == SD.SplitCondition)
337 // Terminator is also harmless.
341 // Otherwise we have a instruction that may not be safe.
348 // If Exit block includes loop variant instructions then this
349 // loop may not be eliminated. This is used by processOneIterationLoop().
350 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
352 Instruction *IndVarIncrement = NULL;
354 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
358 // PHI Nodes are OK. FIXME : Handle last value assignments.
362 // Check if I is induction variable increment instruction.
363 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) {
364 if (BOp->getOpcode() != Instruction::Add)
367 Value *Op0 = BOp->getOperand(0);
368 Value *Op1 = BOp->getOperand(1);
370 ConstantInt *CI = NULL;
372 if ((PN = dyn_cast<PHINode>(Op0))) {
373 if ((CI = dyn_cast<ConstantInt>(Op1)))
376 if ((PN = dyn_cast<PHINode>(Op1))) {
377 if ((CI = dyn_cast<ConstantInt>(Op0)))
381 if (IndVarIncrement && PN == SD.IndVar && CI->isOne())
385 // I is an Exit condition if next instruction is block terminator.
386 // Exit condition is OK if it compares loop invariant exit value,
387 // which is checked below.
388 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
391 if (N == ExitBlock->getTerminator()) {
392 SD.ExitCondition = EC;
397 // Otherwise we have instruction that may not be safe.
401 // Check if Exit condition is comparing induction variable against
402 // loop invariant value. If one operand is induction variable and
403 // the other operand is loop invaraint then Exit condition is safe.
404 if (SD.ExitCondition) {
405 Value *Op0 = SD.ExitCondition->getOperand(0);
406 Value *Op1 = SD.ExitCondition->getOperand(1);
408 Instruction *Insn0 = dyn_cast<Instruction>(Op0);
409 Instruction *Insn1 = dyn_cast<Instruction>(Op1);
411 if (Insn0 && Insn0 == IndVarIncrement)
413 else if (Insn1 && Insn1 == IndVarIncrement)
416 SCEVHandle ValueSCEV = SE->getSCEV(SD.ExitValue);
417 if (!ValueSCEV->isLoopInvariant(L))
421 // We could not find any reason to consider ExitBlock unsafe.
425 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {