1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Index Splitting Pass. This pass handles three
13 // [1] Loop is eliminated when loop body is executed only once. For example,
14 // for (i = 0; i < N; ++i) {
20 // [2] Loop's iteration space is shrunk if loop body is executed for certain
21 // range only. For example,
23 // for (i = 0; i < N; ++i) {
24 // if ( i > A && i < B) {
28 // is trnasformed to iterators from A to B, if A > 0 and B < N.
30 // [3] Loop is split if the loop body is dominated by an branch. For example,
32 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
34 // is transformed into
36 // for (i = LB; i < min(UB, AEV); ++i)
38 // for (i = max(LB, BSV); i < UB; ++i);
40 //===----------------------------------------------------------------------===//
42 #define DEBUG_TYPE "loop-index-split"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/IntrinsicInst.h"
46 #include "llvm/Analysis/LoopPass.h"
47 #include "llvm/Analysis/ScalarEvolution.h"
48 #include "llvm/Analysis/Dominators.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/Cloning.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/DepthFirstIterator.h"
53 #include "llvm/ADT/Statistic.h"
57 STATISTIC(NumIndexSplit, "Number of loop index split");
58 STATISTIC(NumIndexSplitRemoved, "Number of loops eliminated by loop index split");
59 STATISTIC(NumRestrictBounds, "Number of loop iteration space restricted");
63 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
66 static char ID; // Pass ID, replacement for typeid
67 LoopIndexSplit() : LoopPass(&ID) {}
69 // Index split Loop L. Return true if loop is split.
70 bool runOnLoop(Loop *L, LPPassManager &LPM);
72 void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addPreserved<ScalarEvolution>();
74 AU.addRequiredID(LCSSAID);
75 AU.addPreservedID(LCSSAID);
76 AU.addRequired<LoopInfo>();
77 AU.addPreserved<LoopInfo>();
78 AU.addRequiredID(LoopSimplifyID);
79 AU.addPreservedID(LoopSimplifyID);
80 AU.addRequired<DominatorTree>();
81 AU.addRequired<DominanceFrontier>();
82 AU.addPreserved<DominatorTree>();
83 AU.addPreserved<DominanceFrontier>();
87 /// processOneIterationLoop -- Eliminate loop if loop body is executed
88 /// only once. For example,
89 /// for (i = 0; i < N; ++i) {
95 bool processOneIterationLoop();
97 // -- Routines used by updateLoopIterationSpace();
99 /// updateLoopIterationSpace -- Update loop's iteration space if loop
100 /// body is executed for certain IV range only. For example,
102 /// for (i = 0; i < N; ++i) {
103 /// if ( i > A && i < B) {
107 /// is transformed to iterators from A to B, if A > 0 and B < N.
109 bool updateLoopIterationSpace();
111 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
112 /// with a loop invariant value. Update loop's lower and upper bound based on
113 /// the loop invariant value.
114 bool restrictLoopBound(ICmpInst &Op);
116 // --- Routines used by splitLoop(). --- /
120 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by
121 /// DeadBB. This routine is used to remove split condition's dead branch,
122 /// dominated by DeadBB. LiveBB dominates split conidition's other branch.
123 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
125 /// moveExitCondition - Move exit condition EC into split condition block.
126 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
127 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
128 PHINode *IV, Instruction *IVAdd, Loop *LP,
131 /// updatePHINodes - CFG has been changed.
133 /// - ExitBB's single predecessor was Latch
134 /// - Latch's second successor was Header
136 /// - ExitBB's single predecessor was Header
137 /// - Latch's one and only successor was Header
139 /// Update ExitBB PHINodes' to reflect this change.
140 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
142 PHINode *IV, Instruction *IVIncrement, Loop *LP);
144 // --- Utility routines --- /
146 /// cleanBlock - A block is considered clean if all non terminal
147 /// instructions are either PHINodes or IV based values.
148 bool cleanBlock(BasicBlock *BB);
150 /// IVisLT - If Op is comparing IV based value with an loop invariant and
151 /// IV based value is less than the loop invariant then return the loop
152 /// invariant. Otherwise return NULL.
153 Value * IVisLT(ICmpInst &Op);
155 /// IVisLE - If Op is comparing IV based value with an loop invariant and
156 /// IV based value is less than or equal to the loop invariant then
157 /// return the loop invariant. Otherwise return NULL.
158 Value * IVisLE(ICmpInst &Op);
160 /// IVisGT - If Op is comparing IV based value with an loop invariant and
161 /// IV based value is greater than the loop invariant then return the loop
162 /// invariant. Otherwise return NULL.
163 Value * IVisGT(ICmpInst &Op);
165 /// IVisGE - If Op is comparing IV based value with an loop invariant and
166 /// IV based value is greater than or equal to the loop invariant then
167 /// return the loop invariant. Otherwise return NULL.
168 Value * IVisGE(ICmpInst &Op);
172 // Current Loop information.
177 DominanceFrontier *DF;
180 ICmpInst *ExitCondition;
181 ICmpInst *SplitCondition;
184 Instruction *IVIncrement;
185 SmallPtrSet<Value *, 4> IVBasedValues;
189 char LoopIndexSplit::ID = 0;
190 static RegisterPass<LoopIndexSplit>
191 X("loop-index-split", "Index Split Loops");
193 Pass *llvm::createLoopIndexSplitPass() {
194 return new LoopIndexSplit();
197 // Index split Loop L. Return true if loop is split.
198 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
202 // FIXME - Nested loops make dominator info updates tricky.
203 if (!L->getSubLoops().empty())
206 DT = &getAnalysis<DominatorTree>();
207 LI = &getAnalysis<LoopInfo>();
208 DF = &getAnalysis<DominanceFrontier>();
210 // Initialize loop data.
211 IndVar = L->getCanonicalInductionVariable();
212 if (!IndVar) return false;
214 bool P1InLoop = L->contains(IndVar->getIncomingBlock(1));
215 IVStartValue = IndVar->getIncomingValue(!P1InLoop);
216 IVIncrement = dyn_cast<Instruction>(IndVar->getIncomingValue(P1InLoop));
217 if (!IVIncrement) return false;
219 IVBasedValues.clear();
220 IVBasedValues.insert(IndVar);
221 IVBasedValues.insert(IVIncrement);
222 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
224 for(BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BI))
227 if (BO != IVIncrement
228 && (BO->getOpcode() == Instruction::Add
229 || BO->getOpcode() == Instruction::Sub))
230 if (IVBasedValues.count(BO->getOperand(0))
231 && L->isLoopInvariant(BO->getOperand(1)))
232 IVBasedValues.insert(BO);
235 // Reject loop if loop exit condition is not suitable.
236 BasicBlock *ExitingBlock = L->getExitingBlock();
239 BranchInst *EBR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
240 if (!EBR) return false;
241 ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
242 if (!ExitCondition) return false;
243 if (ExitingBlock != L->getLoopLatch()) return false;
244 IVExitValue = ExitCondition->getOperand(1);
245 if (!L->isLoopInvariant(IVExitValue))
246 IVExitValue = ExitCondition->getOperand(0);
247 if (!L->isLoopInvariant(IVExitValue))
250 // If start value is more then exit value where induction variable
251 // increments by 1 then we are potentially dealing with an infinite loop.
252 // Do not index split this loop.
253 if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
254 if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
255 if (SV->getSExtValue() > EV->getSExtValue())
258 if (processOneIterationLoop())
261 if (updateLoopIterationSpace())
270 // --- Helper routines ---
271 // isUsedOutsideLoop - Returns true iff V is used outside the loop L.
272 static bool isUsedOutsideLoop(Value *V, Loop *L) {
273 for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
274 if (!L->contains(cast<Instruction>(*UI)->getParent()))
280 static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
281 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
282 return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
286 static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
287 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
288 return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
291 // Return min(V1, V1)
292 static Value *getMin(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
294 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
295 V1, V2, "lsp", InsertPt);
296 return SelectInst::Create(C, V1, V2, "lsp", InsertPt);
299 // Return max(V1, V2)
300 static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
302 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
303 V1, V2, "lsp", InsertPt);
304 return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
307 /// processOneIterationLoop -- Eliminate loop if loop body is executed
308 /// only once. For example,
309 /// for (i = 0; i < N; ++i) {
315 bool LoopIndexSplit::processOneIterationLoop() {
316 SplitCondition = NULL;
317 BasicBlock *Latch = L->getLoopLatch();
318 BasicBlock *Header = L->getHeader();
319 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
320 if (!BR) return false;
321 if (!isa<BranchInst>(Latch->getTerminator())) return false;
322 if (BR->isUnconditional()) return false;
323 SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
324 if (!SplitCondition) return false;
325 if (SplitCondition == ExitCondition) return false;
326 if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
327 if (BR->getOperand(1) != Latch) return false;
328 if (!IVBasedValues.count(SplitCondition->getOperand(0))
329 && !IVBasedValues.count(SplitCondition->getOperand(1)))
332 // If IV is used outside the loop then this loop traversal is required.
333 // FIXME: Calculate and use last IV value.
334 if (isUsedOutsideLoop(IVIncrement, L))
337 // If BR operands are not IV or not loop invariants then skip this loop.
338 Value *OPV = SplitCondition->getOperand(0);
339 Value *SplitValue = SplitCondition->getOperand(1);
340 if (!L->isLoopInvariant(SplitValue)) {
341 Value *T = SplitValue;
345 if (!L->isLoopInvariant(SplitValue))
347 Instruction *OPI = dyn_cast<Instruction>(OPV);
348 if (!OPI) return false;
349 if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
352 if (!cleanBlock(Header))
355 if (!cleanBlock(Latch))
358 // If the merge point for BR is not loop latch then skip this loop.
359 if (BR->getSuccessor(0) != Latch) {
360 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
361 assert (DF0 != DF->end() && "Unable to find dominance frontier");
362 if (!DF0->second.count(Latch))
366 if (BR->getSuccessor(1) != Latch) {
367 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
368 assert (DF1 != DF->end() && "Unable to find dominance frontier");
369 if (!DF1->second.count(Latch))
373 // Now, Current loop L contains compare instruction
374 // that compares induction variable, IndVar, against loop invariant. And
375 // entire (i.e. meaningful) loop body is dominated by this compare
376 // instruction. In such case eliminate
377 // loop structure surrounding this loop body. For example,
378 // for (int i = start; i < end; ++i) {
379 // if ( i == somevalue) {
383 // can be transformed into
384 // if (somevalue >= start && somevalue < end) {
389 // Replace index variable with split value in loop body. Loop body is executed
390 // only when index variable is equal to split value.
391 IndVar->replaceAllUsesWith(SplitValue);
393 // Replace split condition in header.
395 // SplitCondition : icmp eq i32 IndVar, SplitValue
397 // c1 = icmp uge i32 SplitValue, StartValue
398 // c2 = icmp ult i32 SplitValue, ExitValue
400 Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ?
401 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
402 SplitValue, IVStartValue, "lisplit", BR);
404 CmpInst::Predicate C2P = ExitCondition->getPredicate();
405 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
406 if (LatchBR->getOperand(0) != Header)
407 C2P = CmpInst::getInversePredicate(C2P);
408 Instruction *C2 = new ICmpInst(C2P, SplitValue, IVExitValue, "lisplit", BR);
409 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
411 SplitCondition->replaceAllUsesWith(NSplitCond);
412 SplitCondition->eraseFromParent();
414 // Remove Latch to Header edge.
415 BasicBlock *LatchSucc = NULL;
416 Header->removePredecessor(Latch);
417 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
422 LatchBR->setUnconditionalDest(LatchSucc);
424 // Remove IVIncrement
425 IVIncrement->replaceAllUsesWith(UndefValue::get(IVIncrement->getType()));
426 IVIncrement->eraseFromParent();
428 LPM->deleteLoopFromQueue(L);
430 // Update Dominator Info.
431 // Only CFG change done is to remove Latch to Header edge. This
432 // does not change dominator tree because Latch did not dominate
435 DominanceFrontier::iterator HeaderDF = DF->find(Header);
436 if (HeaderDF != DF->end())
437 DF->removeFromFrontier(HeaderDF, Header);
439 DominanceFrontier::iterator LatchDF = DF->find(Latch);
440 if (LatchDF != DF->end())
441 DF->removeFromFrontier(LatchDF, Header);
444 ++NumIndexSplitRemoved;
448 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
449 /// with a loop invariant value. Update loop's lower and upper bound based on
450 /// the loop invariant value.
451 bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
452 bool Sign = Op.isSignedPredicate();
453 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
455 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
457 cast<BranchInst>(ExitCondition->getParent()->getTerminator());
458 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
459 BasicBlock *T = EBR->getSuccessor(0);
460 EBR->setSuccessor(0, EBR->getSuccessor(1));
461 EBR->setSuccessor(1, T);
464 // New upper and lower bounds.
467 if (Value *V = IVisLT(Op)) {
468 // Restrict upper bound.
469 if (IVisLE(*ExitCondition))
470 V = getMinusOne(V, Sign, PHTerm);
471 NUB = getMin(V, IVExitValue, Sign, PHTerm);
472 } else if (Value *V = IVisLE(Op)) {
473 // Restrict upper bound.
474 if (IVisLT(*ExitCondition))
475 V = getPlusOne(V, Sign, PHTerm);
476 NUB = getMin(V, IVExitValue, Sign, PHTerm);
477 } else if (Value *V = IVisGT(Op)) {
478 // Restrict lower bound.
479 V = getPlusOne(V, Sign, PHTerm);
480 NLB = getMax(V, IVStartValue, Sign, PHTerm);
481 } else if (Value *V = IVisGE(Op))
482 // Restrict lower bound.
483 NLB = getMax(V, IVStartValue, Sign, PHTerm);
489 unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
490 IndVar->setIncomingValue(i, NLB);
494 unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
495 ExitCondition->setOperand(i, NUB);
500 /// updateLoopIterationSpace -- Update loop's iteration space if loop
501 /// body is executed for certain IV range only. For example,
503 /// for (i = 0; i < N; ++i) {
504 /// if ( i > A && i < B) {
508 /// is transformed to iterators from A to B, if A > 0 and B < N.
510 bool LoopIndexSplit::updateLoopIterationSpace() {
511 SplitCondition = NULL;
512 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
513 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
515 BasicBlock *Latch = L->getLoopLatch();
516 BasicBlock *Header = L->getHeader();
517 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
518 if (!BR) return false;
519 if (!isa<BranchInst>(Latch->getTerminator())) return false;
520 if (BR->isUnconditional()) return false;
521 BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
522 if (!AND) return false;
523 if (AND->getOpcode() != Instruction::And) return false;
524 ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
525 ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
528 IVBasedValues.insert(AND);
529 IVBasedValues.insert(Op0);
530 IVBasedValues.insert(Op1);
531 if (!cleanBlock(Header)) return false;
532 BasicBlock *ExitingBlock = ExitCondition->getParent();
533 if (!cleanBlock(ExitingBlock)) return false;
535 // Verify that loop exiting block has only two predecessor, where one pred
536 // is split condition block. The other predecessor will become exiting block's
537 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
538 // more then two predecessors. This requires extra work in updating dominator
540 BasicBlock *ExitingBBPred = NULL;
541 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
543 BasicBlock *BB = *PI;
552 if (!restrictLoopBound(*Op0))
555 if (!restrictLoopBound(*Op1))
559 if (BR->getSuccessor(0) == ExitingBlock)
560 BR->setUnconditionalDest(BR->getSuccessor(1));
562 BR->setUnconditionalDest(BR->getSuccessor(0));
564 AND->eraseFromParent();
565 if (Op0->use_empty())
566 Op0->eraseFromParent();
567 if (Op1->use_empty())
568 Op1->eraseFromParent();
570 // Update domiantor info. Now, ExitingBlock has only one predecessor,
571 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
572 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
574 BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
575 if (L->contains(ExitBlock))
576 ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
578 // If ExitingBlock is a member of the loop basic blocks' DF list then
579 // replace ExitingBlock with header and exit block in the DF list
580 DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
581 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
584 if (BB == Header || BB == ExitingBlock)
586 DominanceFrontier::iterator BBDF = DF->find(BB);
587 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
588 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
589 while (DomSetI != DomSetE) {
590 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
592 BasicBlock *DFBB = *CurrentItr;
593 if (DFBB == ExitingBlock) {
594 BBDF->second.erase(DFBB);
595 for (DominanceFrontier::DomSetType::iterator
596 EBI = ExitingBlockDF->second.begin(),
597 EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI)
598 BBDF->second.insert(*EBI);
606 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
607 /// This routine is used to remove split condition's dead branch, dominated by
608 /// DeadBB. LiveBB dominates split conidition's other branch.
609 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
610 BasicBlock *LiveBB) {
612 // First update DeadBB's dominance frontier.
613 SmallVector<BasicBlock *, 8> FrontierBBs;
614 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
615 if (DeadBBDF != DF->end()) {
616 SmallVector<BasicBlock *, 8> PredBlocks;
618 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
619 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
620 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI)
622 BasicBlock *FrontierBB = *DeadBBSetI;
623 FrontierBBs.push_back(FrontierBB);
625 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
627 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
630 if (P == DeadBB || DT->dominates(DeadBB, P))
631 PredBlocks.push_back(P);
634 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
636 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
637 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
638 PE = PredBlocks.end(); PI != PE; ++PI) {
640 PN->removeIncomingValue(P);
649 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
650 SmallVector<BasicBlock *, 32> WorkList;
651 DomTreeNode *DN = DT->getNode(DeadBB);
652 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
653 E = df_end(DN); DI != E; ++DI) {
654 BasicBlock *BB = DI->getBlock();
655 WorkList.push_back(BB);
656 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
659 while (!WorkList.empty()) {
660 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
661 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
663 Instruction *I = BBI;
665 I->replaceAllUsesWith(UndefValue::get(I->getType()));
666 I->eraseFromParent();
668 LPM->deleteSimpleAnalysisValue(BB, LP);
672 BB->eraseFromParent();
675 // Update Frontier BBs' dominator info.
676 while (!FrontierBBs.empty()) {
677 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
678 BasicBlock *NewDominator = FBB->getSinglePredecessor();
680 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
683 if (NewDominator != LiveBB) {
684 for(; PI != PE; ++PI) {
687 NewDominator = LiveBB;
690 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
694 assert (NewDominator && "Unable to fix dominator info.");
695 DT->changeImmediateDominator(FBB, NewDominator);
696 DF->changeImmediateDominator(FBB, NewDominator, DT);
701 // moveExitCondition - Move exit condition EC into split condition block CondBB.
702 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
703 BasicBlock *ExitBB, ICmpInst *EC,
704 ICmpInst *SC, PHINode *IV,
705 Instruction *IVAdd, Loop *LP,
706 unsigned ExitValueNum) {
708 BasicBlock *ExitingBB = EC->getParent();
709 Instruction *CurrentBR = CondBB->getTerminator();
711 // Move exit condition into split condition block.
712 EC->moveBefore(CurrentBR);
713 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
715 // Move exiting block's branch into split condition block. Update its branch
717 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
718 ExitingBR->moveBefore(CurrentBR);
719 BasicBlock *OrigDestBB = NULL;
720 if (ExitingBR->getSuccessor(0) == ExitBB) {
721 OrigDestBB = ExitingBR->getSuccessor(1);
722 ExitingBR->setSuccessor(1, ActiveBB);
725 OrigDestBB = ExitingBR->getSuccessor(0);
726 ExitingBR->setSuccessor(0, ActiveBB);
729 // Remove split condition and current split condition branch.
730 SC->eraseFromParent();
731 CurrentBR->eraseFromParent();
733 // Connect exiting block to original destination.
734 BranchInst::Create(OrigDestBB, ExitingBB);
737 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
739 // Fix dominator info.
740 // ExitBB is now dominated by CondBB
741 DT->changeImmediateDominator(ExitBB, CondBB);
742 DF->changeImmediateDominator(ExitBB, CondBB, DT);
744 // Basicblocks dominated by ActiveBB may have ExitingBB or
745 // a basic block outside the loop in their DF list. If so,
746 // replace it with CondBB.
747 DomTreeNode *Node = DT->getNode(ActiveBB);
748 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
750 BasicBlock *BB = DI->getBlock();
751 DominanceFrontier::iterator BBDF = DF->find(BB);
752 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
753 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
754 while (DomSetI != DomSetE) {
755 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
757 BasicBlock *DFBB = *CurrentItr;
758 if (DFBB == ExitingBB || !L->contains(DFBB)) {
759 BBDF->second.erase(DFBB);
760 BBDF->second.insert(CondBB);
766 /// updatePHINodes - CFG has been changed.
768 /// - ExitBB's single predecessor was Latch
769 /// - Latch's second successor was Header
771 /// - ExitBB's single predecessor is Header
772 /// - Latch's one and only successor is Header
774 /// Update ExitBB PHINodes' to reflect this change.
775 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
777 PHINode *IV, Instruction *IVIncrement,
780 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
782 PHINode *PN = dyn_cast<PHINode>(BI);
787 Value *V = PN->getIncomingValueForBlock(Latch);
788 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
789 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
790 // in Header which is new incoming value for PN.
792 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
794 if (PHINode *U = dyn_cast<PHINode>(*UI))
795 if (LP->contains(U->getParent())) {
800 // Add incoming value from header only if PN has any use inside the loop.
802 PN->addIncoming(NewV, Header);
804 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
805 // If this instruction is IVIncrement then IV is new incoming value
806 // from header otherwise this instruction must be incoming value from
807 // header because loop is in LCSSA form.
808 if (PHI == IVIncrement)
809 PN->addIncoming(IV, Header);
811 PN->addIncoming(V, Header);
813 // Otherwise this is an incoming value from header because loop is in
815 PN->addIncoming(V, Header);
817 // Remove incoming value from Latch.
818 PN->removeIncomingValue(Latch);
822 bool LoopIndexSplit::splitLoop() {
823 SplitCondition = NULL;
824 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
825 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
827 BasicBlock *Header = L->getHeader();
828 BasicBlock *Latch = L->getLoopLatch();
829 BranchInst *SBR = NULL; // Split Condition Branch
830 BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
831 // If Exiting block includes loop variant instructions then this
832 // loop may not be split safely.
833 BasicBlock *ExitingBlock = ExitCondition->getParent();
834 if (!cleanBlock(ExitingBlock)) return false;
836 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
838 BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
839 if (!BR || BR->isUnconditional()) continue;
840 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
841 if (!CI || CI == ExitCondition
842 || CI->getPredicate() == ICmpInst::ICMP_NE
843 || CI->getPredicate() == ICmpInst::ICMP_EQ)
846 // Unable to handle triangle loops at the moment.
847 // In triangle loop, split condition is in header and one of the
848 // the split destination is loop latch. If split condition is EQ
849 // then such loops are already handle in processOneIterationLoop().
851 && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
854 // If the block does not dominate the latch then this is not a diamond.
855 // Such loop may not benefit from index split.
856 if (!DT->dominates((*I), Latch))
859 // If split condition branches heads do not have single predecessor,
860 // SplitCondBlock, then is not possible to remove inactive branch.
861 if (!BR->getSuccessor(0)->getSinglePredecessor()
862 || !BR->getSuccessor(1)->getSinglePredecessor())
865 // If the merge point for BR is not loop latch then skip this condition.
866 if (BR->getSuccessor(0) != Latch) {
867 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
868 assert (DF0 != DF->end() && "Unable to find dominance frontier");
869 if (!DF0->second.count(Latch))
873 if (BR->getSuccessor(1) != Latch) {
874 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
875 assert (DF1 != DF->end() && "Unable to find dominance frontier");
876 if (!DF1->second.count(Latch))
887 // If the predicate sign does not match then skip.
888 if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
891 unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
892 unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
893 Value *SplitValue = SplitCondition->getOperand(SVOpNum);
894 if (!L->isLoopInvariant(SplitValue))
896 if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
899 // Normalize loop conditions so that it is easier to calculate new loop
901 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
902 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
903 BasicBlock *T = EBR->getSuccessor(0);
904 EBR->setSuccessor(0, EBR->getSuccessor(1));
905 EBR->setSuccessor(1, T);
908 if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
909 SplitCondition->setPredicate(SplitCondition->getInversePredicate());
910 BasicBlock *T = SBR->getSuccessor(0);
911 SBR->setSuccessor(0, SBR->getSuccessor(1));
912 SBR->setSuccessor(1, T);
915 //[*] Calculate new loop bounds.
916 Value *AEV = SplitValue;
917 Value *BSV = SplitValue;
918 bool Sign = SplitCondition->isSignedPredicate();
919 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
921 if (IVisLT(*ExitCondition)) {
922 if (IVisLT(*SplitCondition)) {
925 else if (IVisLE(*SplitCondition)) {
926 AEV = getPlusOne(SplitValue, Sign, PHTerm);
927 BSV = getPlusOne(SplitValue, Sign, PHTerm);
929 assert (0 && "Unexpected split condition!");
932 else if (IVisLE(*ExitCondition)) {
933 if (IVisLT(*SplitCondition)) {
934 AEV = getMinusOne(SplitValue, Sign, PHTerm);
936 else if (IVisLE(*SplitCondition)) {
937 BSV = getPlusOne(SplitValue, Sign, PHTerm);
939 assert (0 && "Unexpected split condition!");
942 assert (0 && "Unexpected exit condition!");
944 AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
945 BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
948 DenseMap<const Value *, Value *> ValueMap;
949 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
952 // [*] ALoop's exiting edge enters BLoop's header.
953 // ALoop's original exit block becomes BLoop's exit block.
954 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
955 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
956 BranchInst *A_ExitInsn =
957 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
958 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
959 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
960 BasicBlock *B_Header = BLoop->getHeader();
961 if (ALoop->contains(B_ExitBlock)) {
962 B_ExitBlock = A_ExitInsn->getSuccessor(0);
963 A_ExitInsn->setSuccessor(0, B_Header);
965 A_ExitInsn->setSuccessor(1, B_Header);
967 // [*] Update ALoop's exit value using new exit value.
968 ExitCondition->setOperand(EVOpNum, AEV);
970 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
971 // original loop's preheader. Add incoming PHINode values from
972 // ALoop's exiting block. Update BLoop header's domiantor info.
974 // Collect inverse map of Header PHINodes.
975 DenseMap<Value *, Value *> InverseMap;
976 for (BasicBlock::iterator BI = ALoop->getHeader()->begin(),
977 BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
978 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
979 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
980 InverseMap[PNClone] = PN;
985 BasicBlock *A_Preheader = ALoop->getLoopPreheader();
986 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
988 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
989 // Remove incoming value from original preheader.
990 PN->removeIncomingValue(A_Preheader);
992 // Add incoming value from A_ExitingBlock.
994 PN->addIncoming(BSV, A_ExitingBlock);
996 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
998 // If loop header is also loop exiting block then
999 // OrigPN is incoming value for B loop header.
1000 if (A_ExitingBlock == ALoop->getHeader())
1003 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1004 PN->addIncoming(V2, A_ExitingBlock);
1010 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1011 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1013 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1014 // block. Remove incoming PHINode values from ALoop's exiting block.
1015 // Add new incoming values from BLoop's incoming exiting value.
1016 // Update BLoop exit block's dominator info..
1017 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1018 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1020 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1021 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1023 PN->removeIncomingValue(A_ExitingBlock);
1028 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1029 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1031 //[*] Split ALoop's exit edge. This creates a new block which
1032 // serves two purposes. First one is to hold PHINode defnitions
1033 // to ensure that ALoop's LCSSA form. Second use it to act
1034 // as a preheader for BLoop.
1035 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1037 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1038 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1039 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1041 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1042 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1043 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1044 newPHI->addIncoming(V1, A_ExitingBlock);
1045 A_ExitBlock->getInstList().push_front(newPHI);
1046 PN->removeIncomingValue(A_ExitBlock);
1047 PN->addIncoming(newPHI, A_ExitBlock);
1052 //[*] Eliminate split condition's inactive branch from ALoop.
1053 BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1054 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1055 BasicBlock *A_InactiveBranch = NULL;
1056 BasicBlock *A_ActiveBranch = NULL;
1057 A_ActiveBranch = A_BR->getSuccessor(0);
1058 A_InactiveBranch = A_BR->getSuccessor(1);
1059 A_BR->setUnconditionalDest(A_ActiveBranch);
1060 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1062 //[*] Eliminate split condition's inactive branch in from BLoop.
1063 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1064 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1065 BasicBlock *B_InactiveBranch = NULL;
1066 BasicBlock *B_ActiveBranch = NULL;
1067 B_ActiveBranch = B_BR->getSuccessor(1);
1068 B_InactiveBranch = B_BR->getSuccessor(0);
1069 B_BR->setUnconditionalDest(B_ActiveBranch);
1070 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1072 BasicBlock *A_Header = ALoop->getHeader();
1073 if (A_ExitingBlock == A_Header)
1076 //[*] Move exit condition into split condition block to avoid
1077 // executing dead loop iteration.
1078 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1079 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1080 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1082 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1083 cast<ICmpInst>(SplitCondition), IndVar, IVIncrement,
1086 moveExitCondition(B_SplitCondBlock, B_ActiveBranch,
1087 B_ExitBlock, B_ExitCondition,
1088 B_SplitCondition, B_IndVar, B_IndVarIncrement,
1095 /// cleanBlock - A block is considered clean if all non terminal instructions
1096 /// are either, PHINodes, IV based.
1097 bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1098 Instruction *Terminator = BB->getTerminator();
1099 for(BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1101 Instruction *I = BI;
1103 if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
1104 || I == SplitCondition || IVBasedValues.count(I)
1105 || isa<DbgInfoIntrinsic>(I))
1108 if (I->mayWriteToMemory())
1111 // I is used only inside this block then it is OK.
1112 bool usedOutsideBB = false;
1113 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1115 Instruction *U = cast<Instruction>(UI);
1116 if (U->getParent() != BB)
1117 usedOutsideBB = true;
1122 // Otherwise we have a instruction that may not allow loop spliting.
1128 /// IVisLT - If Op is comparing IV based value with an loop invariant and
1129 /// IV based value is less than the loop invariant then return the loop
1130 /// invariant. Otherwise return NULL.
1131 Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1132 ICmpInst::Predicate P = Op.getPredicate();
1133 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1134 && IVBasedValues.count(Op.getOperand(0))
1135 && L->isLoopInvariant(Op.getOperand(1)))
1136 return Op.getOperand(1);
1138 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1139 && IVBasedValues.count(Op.getOperand(1))
1140 && L->isLoopInvariant(Op.getOperand(0)))
1141 return Op.getOperand(0);
1146 /// IVisLE - If Op is comparing IV based value with an loop invariant and
1147 /// IV based value is less than or equal to the loop invariant then
1148 /// return the loop invariant. Otherwise return NULL.
1149 Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1150 ICmpInst::Predicate P = Op.getPredicate();
1151 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1152 && IVBasedValues.count(Op.getOperand(0))
1153 && L->isLoopInvariant(Op.getOperand(1)))
1154 return Op.getOperand(1);
1156 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1157 && IVBasedValues.count(Op.getOperand(1))
1158 && L->isLoopInvariant(Op.getOperand(0)))
1159 return Op.getOperand(0);
1164 /// IVisGT - If Op is comparing IV based value with an loop invariant and
1165 /// IV based value is greater than the loop invariant then return the loop
1166 /// invariant. Otherwise return NULL.
1167 Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1168 ICmpInst::Predicate P = Op.getPredicate();
1169 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1170 && IVBasedValues.count(Op.getOperand(0))
1171 && L->isLoopInvariant(Op.getOperand(1)))
1172 return Op.getOperand(1);
1174 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1175 && IVBasedValues.count(Op.getOperand(1))
1176 && L->isLoopInvariant(Op.getOperand(0)))
1177 return Op.getOperand(0);
1182 /// IVisGE - If Op is comparing IV based value with an loop invariant and
1183 /// IV based value is greater than or equal to the loop invariant then
1184 /// return the loop invariant. Otherwise return NULL.
1185 Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1186 ICmpInst::Predicate P = Op.getPredicate();
1187 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1188 && IVBasedValues.count(Op.getOperand(0))
1189 && L->isLoopInvariant(Op.getOperand(1)))
1190 return Op.getOperand(1);
1192 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1193 && IVBasedValues.count(Op.getOperand(1))
1194 && L->isLoopInvariant(Op.getOperand(0)))
1195 return Op.getOperand(0);