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/Analysis/LoopPass.h"
18 #include "llvm/Analysis/ScalarEvolutionExpander.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/Statistic.h"
28 STATISTIC(NumIndexSplit, "Number of loops index split");
32 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
35 static char ID; // Pass ID, replacement for typeid
36 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
38 // Index split Loop L. Return true if loop is split.
39 bool runOnLoop(Loop *L, LPPassManager &LPM);
41 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<ScalarEvolution>();
43 AU.addPreserved<ScalarEvolution>();
44 AU.addRequiredID(LCSSAID);
45 AU.addPreservedID(LCSSAID);
46 AU.addRequired<LoopInfo>();
47 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
50 AU.addRequired<DominatorTree>();
51 AU.addRequired<DominanceFrontier>();
52 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
60 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
61 UseTrueBranchFirst(true) {}
63 // Induction variable's range is split at this value.
66 // This compare instruction compares IndVar against SplitValue.
67 ICmpInst *SplitCondition;
69 // True if after loop index split, first loop will execute split condition's
71 bool UseTrueBranchFirst;
75 SplitCondition = NULL;
76 UseTrueBranchFirst = true;
82 /// Find condition inside a loop that is suitable candidate for index split.
83 void findSplitCondition();
85 /// Find loop's exit condition.
86 void findLoopConditionals();
88 /// Return induction variable associated with value V.
89 void findIndVar(Value *V, Loop *L);
91 /// processOneIterationLoop - Current loop L contains compare instruction
92 /// that compares induction variable, IndVar, agains loop invariant. If
93 /// entire (i.e. meaningful) loop body is dominated by this compare
94 /// instruction then loop body is executed only for one iteration. In
95 /// such case eliminate loop structure surrounding this loop body. For
96 bool processOneIterationLoop(SplitInfo &SD);
98 /// If loop header includes loop variant instruction operands then
99 /// this loop may not be eliminated.
100 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
102 /// If Exiting block includes loop variant instructions then this
103 /// loop may not be eliminated.
104 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
106 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
107 /// This routine is used to remove split condition's dead branch, dominated by
108 /// DeadBB. LiveBB dominates split conidition's other branch.
109 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
111 /// safeSplitCondition - Return true if it is possible to
112 /// split loop using given split condition.
113 bool safeSplitCondition(SplitInfo &SD);
115 /// splitLoop - Split current loop L in two loops using split information
116 /// SD. Update dominator information. Maintain LCSSA form.
117 bool splitLoop(SplitInfo &SD);
121 IndVarIncrement = NULL;
122 ExitCondition = NULL;
136 DominanceFrontier *DF;
137 SmallVector<SplitInfo, 4> SplitData;
139 // Induction variable whose range is being split by this transformation.
141 Instruction *IndVarIncrement;
143 // Loop exit condition.
144 ICmpInst *ExitCondition;
146 // Induction variable's initial value.
149 // Induction variable's final loop exit value operand number in exit condition..
150 unsigned ExitValueNum;
153 char LoopIndexSplit::ID = 0;
154 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
157 LoopPass *llvm::createLoopIndexSplitPass() {
158 return new LoopIndexSplit();
161 // Index split Loop L. Return true if loop is split.
162 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
163 bool Changed = false;
167 // FIXME - Nested loops make dominator info updates tricky.
168 if (!L->getSubLoops().empty())
171 SE = &getAnalysis<ScalarEvolution>();
172 DT = &getAnalysis<DominatorTree>();
173 LI = &getAnalysis<LoopInfo>();
174 DF = &getAnalysis<DominanceFrontier>();
178 findLoopConditionals();
183 findSplitCondition();
185 if (SplitData.empty())
188 // First see if it is possible to eliminate loop itself or not.
189 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
190 E = SplitData.end(); SI != E;) {
192 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
193 Changed = processOneIterationLoop(SD);
196 // If is loop is eliminated then nothing else to do here.
199 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
201 SplitData.erase(Delete_SI);
207 if (SplitData.empty())
210 // Split most profitiable condition.
211 // FIXME : Implement cost analysis.
212 unsigned MostProfitableSDIndex = 0;
213 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
221 /// Return true if V is a induction variable or induction variable's
222 /// increment for loop L.
223 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
225 Instruction *I = dyn_cast<Instruction>(V);
229 // Check if I is a phi node from loop header or not.
230 if (PHINode *PN = dyn_cast<PHINode>(V)) {
231 if (PN->getParent() == L->getHeader()) {
237 // Check if I is a add instruction whose one operand is
238 // phi node from loop header and second operand is constant.
239 if (I->getOpcode() != Instruction::Add)
242 Value *Op0 = I->getOperand(0);
243 Value *Op1 = I->getOperand(1);
245 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
246 if (PN->getParent() == L->getHeader()
247 && isa<ConstantInt>(Op1)) {
254 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
255 if (PN->getParent() == L->getHeader()
256 && isa<ConstantInt>(Op0)) {
266 // Find loop's exit condition and associated induction variable.
267 void LoopIndexSplit::findLoopConditionals() {
269 BasicBlock *ExitingBlock = NULL;
271 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
274 if (!L->isLoopExit(BB))
284 // If exiting block is neither loop header nor loop latch then this loop is
286 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
289 // If exit block's terminator is conditional branch inst then we have found
291 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
292 if (!BR || BR->isUnconditional())
295 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
301 // Exit condition's one operand is loop invariant exit value and second
302 // operand is SCEVAddRecExpr based on induction variable.
303 Value *V0 = CI->getOperand(0);
304 Value *V1 = CI->getOperand(1);
306 SCEVHandle SH0 = SE->getSCEV(V0);
307 SCEVHandle SH1 = SE->getSCEV(V1);
309 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
313 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
319 ExitCondition = NULL;
321 BasicBlock *Preheader = L->getLoopPreheader();
322 StartValue = IndVar->getIncomingValueForBlock(Preheader);
326 /// Find condition inside a loop that is suitable candidate for index split.
327 void LoopIndexSplit::findSplitCondition() {
330 // Check all basic block's terminators.
332 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
336 // If this basic block does not terminate in a conditional branch
337 // then terminator is not a suitable split condition.
338 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
342 if (BR->isUnconditional())
345 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
346 if (!CI || CI == ExitCondition)
349 if (CI->getPredicate() == ICmpInst::ICMP_NE)
352 // If split condition predicate is GT or GE then first execute
353 // false branch of split condition.
354 if (CI->getPredicate() != ICmpInst::ICMP_ULT
355 && CI->getPredicate() != ICmpInst::ICMP_SLT
356 && CI->getPredicate() != ICmpInst::ICMP_ULE
357 && CI->getPredicate() != ICmpInst::ICMP_SLE)
358 SD.UseTrueBranchFirst = false;
360 // If one operand is loop invariant and second operand is SCEVAddRecExpr
361 // based on induction variable then CI is a candidate split condition.
362 Value *V0 = CI->getOperand(0);
363 Value *V1 = CI->getOperand(1);
365 SCEVHandle SH0 = SE->getSCEV(V0);
366 SCEVHandle SH1 = SE->getSCEV(V1);
368 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
370 SD.SplitCondition = CI;
371 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
373 SplitData.push_back(SD);
375 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
376 if (IndVarIncrement && IndVarIncrement == Insn)
377 SplitData.push_back(SD);
380 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
382 SD.SplitCondition = CI;
383 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
385 SplitData.push_back(SD);
387 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
388 if (IndVarIncrement && IndVarIncrement == Insn)
389 SplitData.push_back(SD);
395 /// processOneIterationLoop - Current loop L contains compare instruction
396 /// that compares induction variable, IndVar, against loop invariant. If
397 /// entire (i.e. meaningful) loop body is dominated by this compare
398 /// instruction then loop body is executed only once. In such case eliminate
399 /// loop structure surrounding this loop body. For example,
400 /// for (int i = start; i < end; ++i) {
401 /// if ( i == somevalue) {
405 /// can be transformed into
406 /// if (somevalue >= start && somevalue < end) {
410 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
412 BasicBlock *Header = L->getHeader();
414 // First of all, check if SplitCondition dominates entire loop body
417 // If SplitCondition is not in loop header then this loop is not suitable
418 // for this transformation.
419 if (SD.SplitCondition->getParent() != Header)
422 // If loop header includes loop variant instruction operands then
423 // this loop may not be eliminated.
424 if (!safeHeader(SD, Header))
427 // If Exiting block includes loop variant instructions then this
428 // loop may not be eliminated.
429 if (!safeExitingBlock(SD, ExitCondition->getParent()))
434 // Replace index variable with split value in loop body. Loop body is executed
435 // only when index variable is equal to split value.
436 IndVar->replaceAllUsesWith(SD.SplitValue);
438 // Remove Latch to Header edge.
439 BasicBlock *Latch = L->getLoopLatch();
440 BasicBlock *LatchSucc = NULL;
441 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
444 Header->removePredecessor(Latch);
445 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
450 BR->setUnconditionalDest(LatchSucc);
452 Instruction *Terminator = Header->getTerminator();
453 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
455 // Replace split condition in header.
457 // SplitCondition : icmp eq i32 IndVar, SplitValue
459 // c1 = icmp uge i32 SplitValue, StartValue
460 // c2 = icmp ult i32 vSplitValue, ExitValue
462 bool SignedPredicate = ExitCondition->isSignedPredicate();
463 Instruction *C1 = new ICmpInst(SignedPredicate ?
464 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
465 SD.SplitValue, StartValue, "lisplit",
467 Instruction *C2 = new ICmpInst(SignedPredicate ?
468 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
469 SD.SplitValue, ExitValue, "lisplit",
471 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
473 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
474 SD.SplitCondition->eraseFromParent();
476 // Now, clear latch block. Remove instructions that are responsible
477 // to increment induction variable.
478 Instruction *LTerminator = Latch->getTerminator();
479 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
483 if (isa<PHINode>(I) || I == LTerminator)
486 if (I == IndVarIncrement)
487 I->replaceAllUsesWith(ExitValue);
489 I->replaceAllUsesWith(UndefValue::get(I->getType()));
490 I->eraseFromParent();
493 LPM->deleteLoopFromQueue(L);
495 // Update Dominator Info.
496 // Only CFG change done is to remove Latch to Header edge. This
497 // does not change dominator tree because Latch did not dominate
500 DominanceFrontier::iterator HeaderDF = DF->find(Header);
501 if (HeaderDF != DF->end())
502 DF->removeFromFrontier(HeaderDF, Header);
504 DominanceFrontier::iterator LatchDF = DF->find(Latch);
505 if (LatchDF != DF->end())
506 DF->removeFromFrontier(LatchDF, Header);
511 // If loop header includes loop variant instruction operands then
512 // this loop can not be eliminated. This is used by processOneIterationLoop().
513 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
515 Instruction *Terminator = Header->getTerminator();
516 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
524 // SplitCondition itself is OK.
525 if (I == SD.SplitCondition)
528 // Induction variable is OK.
532 // Induction variable increment is OK.
533 if (I == IndVarIncrement)
536 // Terminator is also harmless.
540 // Otherwise we have a instruction that may not be safe.
547 // If Exiting block includes loop variant instructions then this
548 // loop may not be eliminated. This is used by processOneIterationLoop().
549 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
550 BasicBlock *ExitingBlock) {
552 for (BasicBlock::iterator BI = ExitingBlock->begin(),
553 BE = ExitingBlock->end(); BI != BE; ++BI) {
560 // Induction variable increment is OK.
561 if (IndVarIncrement && IndVarIncrement == I)
564 // Check if I is induction variable increment instruction.
565 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
567 Value *Op0 = I->getOperand(0);
568 Value *Op1 = I->getOperand(1);
570 ConstantInt *CI = NULL;
572 if ((PN = dyn_cast<PHINode>(Op0))) {
573 if ((CI = dyn_cast<ConstantInt>(Op1)))
576 if ((PN = dyn_cast<PHINode>(Op1))) {
577 if ((CI = dyn_cast<ConstantInt>(Op0)))
581 if (IndVarIncrement && PN == IndVar && CI->isOne())
585 // I is an Exit condition if next instruction is block terminator.
586 // Exit condition is OK if it compares loop invariant exit value,
587 // which is checked below.
588 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
589 if (EC == ExitCondition)
593 if (I == ExitingBlock->getTerminator())
596 // Otherwise we have instruction that may not be safe.
600 // We could not find any reason to consider ExitingBlock unsafe.
604 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
605 /// This routine is used to remove split condition's dead branch, dominated by
606 /// DeadBB. LiveBB dominates split conidition's other branch.
607 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
608 BasicBlock *LiveBB) {
610 // First update DeadBB's dominance frontier.
611 SmallVector<BasicBlock *, 8> FrontierBBs;
612 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
613 if (DeadBBDF != DF->end()) {
614 SmallVector<BasicBlock *, 8> PredBlocks;
616 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
617 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
618 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
619 BasicBlock *FrontierBB = *DeadBBSetI;
620 FrontierBBs.push_back(FrontierBB);
622 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
624 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
627 if (P == DeadBB || DT->dominates(DeadBB, P))
628 PredBlocks.push_back(P);
631 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
633 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
634 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
635 PE = PredBlocks.end(); PI != PE; ++PI) {
637 PN->removeIncomingValue(P);
646 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
647 SmallVector<BasicBlock *, 32> WorkList;
648 DomTreeNode *DN = DT->getNode(DeadBB);
649 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
650 E = df_end(DN); DI != E; ++DI) {
651 BasicBlock *BB = DI->getBlock();
652 WorkList.push_back(BB);
653 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
656 while (!WorkList.empty()) {
657 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
658 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
660 Instruction *I = BBI;
661 I->replaceAllUsesWith(UndefValue::get(I->getType()));
662 I->eraseFromParent();
664 LPM->deleteSimpleAnalysisValue(BB, LP);
668 BB->eraseFromParent();
671 // Update Frontier BBs' dominator info.
672 while (!FrontierBBs.empty()) {
673 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
674 BasicBlock *NewDominator = FBB->getSinglePredecessor();
676 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
679 if (NewDominator != LiveBB) {
680 for(; PI != PE; ++PI) {
683 NewDominator = LiveBB;
686 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
690 assert (NewDominator && "Unable to fix dominator info.");
691 DT->changeImmediateDominator(FBB, NewDominator);
692 DF->changeImmediateDominator(FBB, NewDominator, DT);
697 /// safeSplitCondition - Return true if it is possible to
698 /// split loop using given split condition.
699 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
701 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
703 // Unable to handle triange loops at the moment.
704 // In triangle loop, split condition is in header and one of the
705 // the split destination is loop latch. If split condition is EQ
706 // then such loops are already handle in processOneIterationLoop().
707 BasicBlock *Latch = L->getLoopLatch();
708 BranchInst *SplitTerminator =
709 cast<BranchInst>(SplitCondBlock->getTerminator());
710 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
711 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
712 if (L->getHeader() == SplitCondBlock
713 && (Latch == Succ0 || Latch == Succ1))
716 // If one of the split condition branch is post dominating other then loop
717 // index split is not appropriate.
718 if (DT->dominates(Succ0, Latch) || DT->dominates(Succ1, Latch))
721 // If one of the split condition branch is a predecessor of the other
722 // split condition branch head then do not split loop on this condition.
723 for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0);
727 for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1);
732 // Finally this split condition is safe only if merge point for
733 // split condition branch is loop latch. This check along with previous
734 // check, to ensure that exit condition is in either loop latch or header,
735 // filters all loops with non-empty loop body between merge point
736 // and exit condition.
737 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
738 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
739 if (Succ0DF->second.count(Latch))
742 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
743 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
744 if (Succ1DF->second.count(Latch))
750 /// splitLoop - Split current loop L in two loops using split information
751 /// SD. Update dominator information. Maintain LCSSA form.
752 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
754 if (!safeSplitCondition(SD))
757 // After loop is cloned there are two loops.
759 // First loop, referred as ALoop, executes first part of loop's iteration
760 // space split. Second loop, referred as BLoop, executes remaining
761 // part of loop's iteration space.
763 // ALoop's exit edge enters BLoop's header through a forwarding block which
764 // acts as a BLoop's preheader.
766 //[*] Calculate ALoop induction variable's new exiting value and
767 // BLoop induction variable's new starting value. Calculuate these
768 // values in original loop's preheader.
769 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
770 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
771 Value *A_ExitValue = NULL;
772 Value *B_StartValue = NULL;
773 if (isa<ConstantInt>(SD.SplitValue)) {
774 A_ExitValue = SD.SplitValue;
775 B_StartValue = SD.SplitValue;
778 BasicBlock *Preheader = L->getLoopPreheader();
779 Instruction *PHTerminator = Preheader->getTerminator();
780 bool SignedPredicate = ExitCondition->isSignedPredicate();
781 Value *C1 = new ICmpInst(SignedPredicate ?
782 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
784 ExitCondition->getOperand(ExitValueNum),
785 "lsplit.ev", PHTerminator);
786 A_ExitValue = new SelectInst(C1, SD.SplitValue,
787 ExitCondition->getOperand(ExitValueNum),
788 "lsplit.ev", PHTerminator);
790 Value *C2 = new ICmpInst(SignedPredicate ?
791 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
792 SD.SplitValue, StartValue, "lsplit.sv",
794 B_StartValue = new SelectInst(C2, StartValue, SD.SplitValue,
795 "lsplit.sv", PHTerminator);
799 DenseMap<const Value *, Value *> ValueMap;
800 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
801 BasicBlock *B_Header = BLoop->getHeader();
803 //[*] ALoop's exiting edge BLoop's header.
804 // ALoop's original exit block becomes BLoop's exit block.
805 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
806 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
807 BranchInst *A_ExitInsn =
808 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
809 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
810 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
811 if (L->contains(B_ExitBlock)) {
812 B_ExitBlock = A_ExitInsn->getSuccessor(0);
813 A_ExitInsn->setSuccessor(0, B_Header);
815 A_ExitInsn->setSuccessor(1, B_Header);
817 //[*] Update ALoop's exit value using new exit value.
818 ExitCondition->setOperand(ExitValueNum, A_ExitValue);
820 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
821 // original loop's preheader. Add incoming PHINode values from
822 // ALoop's exiting block. Update BLoop header's domiantor info.
824 // Collect inverse map of Header PHINodes.
825 DenseMap<Value *, Value *> InverseMap;
826 for (BasicBlock::iterator BI = L->getHeader()->begin(),
827 BE = L->getHeader()->end(); BI != BE; ++BI) {
828 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
829 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
830 InverseMap[PNClone] = PN;
834 BasicBlock *Preheader = L->getLoopPreheader();
835 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
837 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
838 // Remove incoming value from original preheader.
839 PN->removeIncomingValue(Preheader);
841 // Add incoming value from A_ExitingBlock.
843 PN->addIncoming(B_StartValue, A_ExitingBlock);
845 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
846 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
847 PN->addIncoming(V2, A_ExitingBlock);
852 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
853 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
855 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
856 // block. Remove incoming PHINode values from ALoop's exiting block.
857 // Add new incoming values from BLoop's incoming exiting value.
858 // Update BLoop exit block's dominator info..
859 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
860 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
862 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
863 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
865 PN->removeIncomingValue(A_ExitingBlock);
870 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
871 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
873 //[*] Split ALoop's exit edge. This creates a new block which
874 // serves two purposes. First one is to hold PHINode defnitions
875 // to ensure that ALoop's LCSSA form. Second use it to act
876 // as a preheader for BLoop.
877 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
879 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
880 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
881 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
883 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
884 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
885 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
886 newPHI->addIncoming(V1, A_ExitingBlock);
887 A_ExitBlock->getInstList().push_front(newPHI);
888 PN->removeIncomingValue(A_ExitBlock);
889 PN->addIncoming(newPHI, A_ExitBlock);
894 //[*] Eliminate split condition's inactive branch from ALoop.
895 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
896 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
897 BasicBlock *A_InactiveBranch = NULL;
898 BasicBlock *A_ActiveBranch = NULL;
899 if (SD.UseTrueBranchFirst) {
900 A_ActiveBranch = A_BR->getSuccessor(0);
901 A_InactiveBranch = A_BR->getSuccessor(1);
903 A_ActiveBranch = A_BR->getSuccessor(1);
904 A_InactiveBranch = A_BR->getSuccessor(0);
906 A_BR->setUnconditionalDest(A_BR->getSuccessor(0));
907 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
909 //[*] Eliminate split condition's inactive branch in from BLoop.
910 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
911 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
912 BasicBlock *B_InactiveBranch = NULL;
913 BasicBlock *B_ActiveBranch = NULL;
914 if (SD.UseTrueBranchFirst) {
915 B_ActiveBranch = B_BR->getSuccessor(1);
916 B_InactiveBranch = B_BR->getSuccessor(0);
918 B_ActiveBranch = B_BR->getSuccessor(0);
919 B_InactiveBranch = B_BR->getSuccessor(1);
921 B_BR->setUnconditionalDest(B_BR->getSuccessor(1));
922 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);