92a6058b5a64b569b53372dea9de749a84f0e34c
[oota-llvm.git] / lib / Transforms / Scalar / LoopIndexSplit.cpp
1 //===- 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
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"
25
26 using namespace llvm;
27
28 STATISTIC(NumIndexSplit, "Number of loops index split");
29
30 namespace {
31
32   class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33
34   public:
35     static char ID; // Pass ID, replacement for typeid
36     LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
37
38     // Index split Loop L. Return true if loop is split.
39     bool runOnLoop(Loop *L, LPPassManager &LPM);
40
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>();
54     }
55
56   private:
57
58     class SplitInfo {
59     public:
60       SplitInfo() : SplitValue(NULL), SplitCondition(NULL), 
61                     UseTrueBranchFirst(true), A_ExitValue(NULL), 
62                     B_StartValue(NULL) {}
63
64       // Induction variable's range is split at this value.
65       Value *SplitValue;
66       
67       // This instruction compares IndVar against SplitValue.
68       Instruction *SplitCondition;
69
70       // True if after loop index split, first loop will execute split condition's
71       // true branch.
72       bool UseTrueBranchFirst;
73
74       // Exit value for first loop after loop split.
75       Value *A_ExitValue;
76
77       // Start value for second loop after loop split.
78       Value *B_StartValue;
79
80       // Clear split info.
81       void clear() {
82         SplitValue = NULL;
83         SplitCondition = NULL;
84         UseTrueBranchFirst = true;
85         A_ExitValue = NULL;
86         B_StartValue = NULL;
87       }
88
89     };
90     
91   private:
92
93     // safeIcmpInst - CI is considered safe instruction if one of the operand
94     // is SCEVAddRecExpr based on induction variable and other operand is
95     // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
96     // and return true;
97     bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
98
99     /// Find condition inside a loop that is suitable candidate for index split.
100     void findSplitCondition();
101
102     /// Find loop's exit condition.
103     void findLoopConditionals();
104
105     /// Return induction variable associated with value V.
106     void findIndVar(Value *V, Loop *L);
107
108     /// processOneIterationLoop - Current loop L contains compare instruction
109     /// that compares induction variable, IndVar, agains loop invariant. If
110     /// entire (i.e. meaningful) loop body is dominated by this compare
111     /// instruction then loop body is executed only for one iteration. In
112     /// such case eliminate loop structure surrounding this loop body. For
113     bool processOneIterationLoop(SplitInfo &SD);
114
115     void updateLoopBounds(ICmpInst *CI);
116     /// updateLoopIterationSpace - Current loop body is covered by an AND
117     /// instruction whose operands compares induction variables with loop
118     /// invariants. If possible, hoist this check outside the loop by
119     /// updating appropriate start and end values for induction variable.
120     bool updateLoopIterationSpace(SplitInfo &SD);
121
122     /// If loop header includes loop variant instruction operands then
123     /// this loop may not be eliminated.
124     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
125
126     /// If Exiting block includes loop variant instructions then this
127     /// loop may not be eliminated.
128     bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
129
130     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
131     /// This routine is used to remove split condition's dead branch, dominated by
132     /// DeadBB. LiveBB dominates split conidition's other branch.
133     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
134
135     /// safeSplitCondition - Return true if it is possible to
136     /// split loop using given split condition.
137     bool safeSplitCondition(SplitInfo &SD);
138
139     /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
140     /// based on split value. 
141     void calculateLoopBounds(SplitInfo &SD);
142
143     /// updatePHINodes - CFG has been changed. 
144     /// Before 
145     ///   - ExitBB's single predecessor was Latch
146     ///   - Latch's second successor was Header
147     /// Now
148     ///   - ExitBB's single predecessor was Header
149     ///   - Latch's one and only successor was Header
150     ///
151     /// Update ExitBB PHINodes' to reflect this change.
152     void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
153                         BasicBlock *Header,
154                         PHINode *IV, Instruction *IVIncrement);
155
156     /// moveExitCondition - Move exit condition EC into split condition block CondBB.
157     void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
158                            BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
159                            PHINode *IV, Instruction *IVAdd, Loop *LP);
160
161     /// splitLoop - Split current loop L in two loops using split information
162     /// SD. Update dominator information. Maintain LCSSA form.
163     bool splitLoop(SplitInfo &SD);
164
165     void initialize() {
166       IndVar = NULL; 
167       IndVarIncrement = NULL;
168       ExitCondition = NULL;
169       StartValue = NULL;
170       ExitValueNum = 0;
171       SplitData.clear();
172     }
173
174   private:
175
176     // Current Loop.
177     Loop *L;
178     LPPassManager *LPM;
179     LoopInfo *LI;
180     ScalarEvolution *SE;
181     DominatorTree *DT;
182     DominanceFrontier *DF;
183     SmallVector<SplitInfo, 4> SplitData;
184
185     // Induction variable whose range is being split by this transformation.
186     PHINode *IndVar;
187     Instruction *IndVarIncrement;
188       
189     // Loop exit condition.
190     ICmpInst *ExitCondition;
191
192     // Induction variable's initial value.
193     Value *StartValue;
194
195     // Induction variable's final loop exit value operand number in exit condition..
196     unsigned ExitValueNum;
197   };
198
199   char LoopIndexSplit::ID = 0;
200   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
201 }
202
203 LoopPass *llvm::createLoopIndexSplitPass() {
204   return new LoopIndexSplit();
205 }
206
207 // Index split Loop L. Return true if loop is split.
208 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
209   bool Changed = false;
210   L = IncomingLoop;
211   LPM = &LPM_Ref;
212
213   // FIXME - Nested loops make dominator info updates tricky. 
214   if (!L->getSubLoops().empty())
215     return false;
216
217   SE = &getAnalysis<ScalarEvolution>();
218   DT = &getAnalysis<DominatorTree>();
219   LI = &getAnalysis<LoopInfo>();
220   DF = &getAnalysis<DominanceFrontier>();
221
222   initialize();
223
224   findLoopConditionals();
225
226   if (!ExitCondition)
227     return false;
228
229   findSplitCondition();
230
231   if (SplitData.empty())
232     return false;
233
234   // First see if it is possible to eliminate loop itself or not.
235   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
236          E = SplitData.end(); SI != E;) {
237     SplitInfo &SD = *SI;
238     ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
239     if (SD.SplitCondition->getOpcode() == Instruction::And) {
240       Changed = updateLoopIterationSpace(SD);
241       if (Changed) {
242         ++NumIndexSplit;
243         // If is loop is eliminated then nothing else to do here.
244         return Changed;
245       } else {
246         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
247         ++SI;
248         SplitData.erase(Delete_SI);
249       }
250     }
251     else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
252       Changed = processOneIterationLoop(SD);
253       if (Changed) {
254         ++NumIndexSplit;
255         // If is loop is eliminated then nothing else to do here.
256         return Changed;
257       } else {
258         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
259         ++SI;
260         SplitData.erase(Delete_SI);
261       }
262     } else
263       ++SI;
264   }
265
266   if (SplitData.empty())
267     return false;
268
269   // Split most profitiable condition.
270   // FIXME : Implement cost analysis.
271   unsigned MostProfitableSDIndex = 0;
272   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
273
274   if (Changed)
275     ++NumIndexSplit;
276   
277   return Changed;
278 }
279
280 /// Return true if V is a induction variable or induction variable's
281 /// increment for loop L.
282 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
283   
284   Instruction *I = dyn_cast<Instruction>(V);
285   if (!I)
286     return;
287
288   // Check if I is a phi node from loop header or not.
289   if (PHINode *PN = dyn_cast<PHINode>(V)) {
290     if (PN->getParent() == L->getHeader()) {
291       IndVar = PN;
292       return;
293     }
294   }
295  
296   // Check if I is a add instruction whose one operand is
297   // phi node from loop header and second operand is constant.
298   if (I->getOpcode() != Instruction::Add)
299     return;
300   
301   Value *Op0 = I->getOperand(0);
302   Value *Op1 = I->getOperand(1);
303   
304   if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
305     if (PN->getParent() == L->getHeader()
306         && isa<ConstantInt>(Op1)) {
307       IndVar = PN;
308       IndVarIncrement = I;
309       return;
310     }
311   }
312   
313   if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
314     if (PN->getParent() == L->getHeader()
315         && isa<ConstantInt>(Op0)) {
316       IndVar = PN;
317       IndVarIncrement = I;
318       return;
319     }
320   }
321   
322   return;
323 }
324
325 // Find loop's exit condition and associated induction variable.
326 void LoopIndexSplit::findLoopConditionals() {
327
328   BasicBlock *ExitingBlock = NULL;
329
330   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
331        I != E; ++I) {
332     BasicBlock *BB = *I;
333     if (!L->isLoopExit(BB))
334       continue;
335     if (ExitingBlock)
336       return;
337     ExitingBlock = BB;
338   }
339
340   if (!ExitingBlock)
341     return;
342
343   // If exiting block is neither loop header nor loop latch then this loop is
344   // not suitable. 
345   if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
346     return;
347
348   // If exit block's terminator is conditional branch inst then we have found
349   // exit condition.
350   BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
351   if (!BR || BR->isUnconditional())
352     return;
353   
354   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
355   if (!CI)
356     return;
357
358   // FIXME 
359   if (CI->getPredicate() == ICmpInst::ICMP_SGT
360       || CI->getPredicate() == ICmpInst::ICMP_UGT
361       || CI->getPredicate() == ICmpInst::ICMP_SGE
362       || CI->getPredicate() == ICmpInst::ICMP_UGE
363       || CI->getPredicate() == ICmpInst::ICMP_EQ
364       || CI->getPredicate() == ICmpInst::ICMP_NE)
365     return;
366
367   ExitCondition = CI;
368
369   // Exit condition's one operand is loop invariant exit value and second 
370   // operand is SCEVAddRecExpr based on induction variable.
371   Value *V0 = CI->getOperand(0);
372   Value *V1 = CI->getOperand(1);
373   
374   SCEVHandle SH0 = SE->getSCEV(V0);
375   SCEVHandle SH1 = SE->getSCEV(V1);
376   
377   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
378     ExitValueNum = 0;
379     findIndVar(V1, L);
380   }
381   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
382     ExitValueNum =  1;
383     findIndVar(V0, L);
384   }
385
386   if (!IndVar) 
387     ExitCondition = NULL;
388   else if (IndVar) {
389     BasicBlock *Preheader = L->getLoopPreheader();
390     StartValue = IndVar->getIncomingValueForBlock(Preheader);
391   }
392 }
393
394 /// Find condition inside a loop that is suitable candidate for index split.
395 void LoopIndexSplit::findSplitCondition() {
396
397   SplitInfo SD;
398   // Check all basic block's terminators.
399   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
400        I != E; ++I) {
401     SD.clear();
402     BasicBlock *BB = *I;
403
404     // If this basic block does not terminate in a conditional branch
405     // then terminator is not a suitable split condition.
406     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
407     if (!BR)
408       continue;
409     
410     if (BR->isUnconditional())
411       continue;
412
413     if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
414       if (AndI->getOpcode() == Instruction::And) {
415         ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
416         ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
417
418         if (!Op0 || !Op1)
419           continue;
420
421         if (!safeICmpInst(Op0, SD))
422           continue;
423         SD.clear();
424         if (!safeICmpInst(Op1, SD))
425           continue;
426         SD.clear();
427         SD.SplitCondition = AndI;
428         SplitData.push_back(SD);
429         continue;
430       }
431     }
432     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
433     if (!CI || CI == ExitCondition)
434       continue;
435
436     if (CI->getPredicate() == ICmpInst::ICMP_NE)
437       continue;
438
439     // If split condition predicate is GT or GE then first execute
440     // false branch of split condition.
441     if (CI->getPredicate() == ICmpInst::ICMP_UGT
442         || CI->getPredicate() == ICmpInst::ICMP_SGT
443         || CI->getPredicate() == ICmpInst::ICMP_UGE
444         || CI->getPredicate() == ICmpInst::ICMP_SGE)
445       SD.UseTrueBranchFirst = false;
446
447     // If one operand is loop invariant and second operand is SCEVAddRecExpr
448     // based on induction variable then CI is a candidate split condition.
449     if (safeICmpInst(CI, SD))
450       SplitData.push_back(SD);
451   }
452 }
453
454 // safeIcmpInst - CI is considered safe instruction if one of the operand
455 // is SCEVAddRecExpr based on induction variable and other operand is
456 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
457 // and return true;
458 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
459
460   Value *V0 = CI->getOperand(0);
461   Value *V1 = CI->getOperand(1);
462   
463   SCEVHandle SH0 = SE->getSCEV(V0);
464   SCEVHandle SH1 = SE->getSCEV(V1);
465   
466   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
467     SD.SplitValue = V0;
468     SD.SplitCondition = CI;
469     if (PHINode *PN = dyn_cast<PHINode>(V1)) {
470       if (PN == IndVar)
471         return true;
472     }
473     else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
474       if (IndVarIncrement && IndVarIncrement == Insn)
475         return true;
476     }
477   }
478   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
479     SD.SplitValue =  V1;
480     SD.SplitCondition = CI;
481     if (PHINode *PN = dyn_cast<PHINode>(V0)) {
482       if (PN == IndVar)
483         return true;
484     }
485     else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
486       if (IndVarIncrement && IndVarIncrement == Insn)
487         return true;
488     }
489   }
490
491   return false;
492 }
493
494 /// processOneIterationLoop - Current loop L contains compare instruction
495 /// that compares induction variable, IndVar, against loop invariant. If
496 /// entire (i.e. meaningful) loop body is dominated by this compare
497 /// instruction then loop body is executed only once. In such case eliminate 
498 /// loop structure surrounding this loop body. For example,
499 ///     for (int i = start; i < end; ++i) {
500 ///         if ( i == somevalue) {
501 ///           loop_body
502 ///         }
503 ///     }
504 /// can be transformed into
505 ///     if (somevalue >= start && somevalue < end) {
506 ///        i = somevalue;
507 ///        loop_body
508 ///     }
509 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
510
511   BasicBlock *Header = L->getHeader();
512
513   // First of all, check if SplitCondition dominates entire loop body
514   // or not.
515   
516   // If SplitCondition is not in loop header then this loop is not suitable
517   // for this transformation.
518   if (SD.SplitCondition->getParent() != Header)
519     return false;
520   
521   // If loop header includes loop variant instruction operands then
522   // this loop may not be eliminated.
523   if (!safeHeader(SD, Header)) 
524     return false;
525
526   // If Exiting block includes loop variant instructions then this
527   // loop may not be eliminated.
528   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
529     return false;
530
531   // If split condition is not safe then do not process this loop.
532   // For example,
533   // for(int i = 0; i < N; i++) {
534   //    if ( i == XYZ) {
535   //      A;
536   //    else
537   //      B;
538   //    }
539   //   C;
540   //   D;
541   // }
542   if (!safeSplitCondition(SD))
543     return false;
544
545   BasicBlock *Latch = L->getLoopLatch();
546   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
547   if (!BR)
548     return false;
549
550   // Update CFG.
551
552   // Replace index variable with split value in loop body. Loop body is executed
553   // only when index variable is equal to split value.
554   IndVar->replaceAllUsesWith(SD.SplitValue);
555
556   // Remove Latch to Header edge.
557   BasicBlock *LatchSucc = NULL;
558   Header->removePredecessor(Latch);
559   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
560        SI != E; ++SI) {
561     if (Header != *SI)
562       LatchSucc = *SI;
563   }
564   BR->setUnconditionalDest(LatchSucc);
565
566   Instruction *Terminator = Header->getTerminator();
567   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
568
569   // Replace split condition in header.
570   // Transform 
571   //      SplitCondition : icmp eq i32 IndVar, SplitValue
572   // into
573   //      c1 = icmp uge i32 SplitValue, StartValue
574   //      c2 = icmp ult i32 SplitValue, ExitValue
575   //      and i32 c1, c2 
576   bool SignedPredicate = ExitCondition->isSignedPredicate();
577   Instruction *C1 = new ICmpInst(SignedPredicate ? 
578                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
579                                  SD.SplitValue, StartValue, "lisplit", 
580                                  Terminator);
581   Instruction *C2 = new ICmpInst(SignedPredicate ? 
582                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
583                                  SD.SplitValue, ExitValue, "lisplit", 
584                                  Terminator);
585   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
586                                                       Terminator);
587   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
588   SD.SplitCondition->eraseFromParent();
589
590   // Now, clear latch block. Remove instructions that are responsible
591   // to increment induction variable. 
592   Instruction *LTerminator = Latch->getTerminator();
593   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
594        LB != LE; ) {
595     Instruction *I = LB;
596     ++LB;
597     if (isa<PHINode>(I) || I == LTerminator)
598       continue;
599
600     if (I == IndVarIncrement) 
601       I->replaceAllUsesWith(ExitValue);
602     else
603       I->replaceAllUsesWith(UndefValue::get(I->getType()));
604     I->eraseFromParent();
605   }
606
607   LPM->deleteLoopFromQueue(L);
608
609   // Update Dominator Info.
610   // Only CFG change done is to remove Latch to Header edge. This
611   // does not change dominator tree because Latch did not dominate
612   // Header.
613   if (DF) {
614     DominanceFrontier::iterator HeaderDF = DF->find(Header);
615     if (HeaderDF != DF->end()) 
616       DF->removeFromFrontier(HeaderDF, Header);
617
618     DominanceFrontier::iterator LatchDF = DF->find(Latch);
619     if (LatchDF != DF->end()) 
620       DF->removeFromFrontier(LatchDF, Header);
621   }
622   return true;
623 }
624
625 // If loop header includes loop variant instruction operands then
626 // this loop can not be eliminated. This is used by processOneIterationLoop().
627 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
628
629   Instruction *Terminator = Header->getTerminator();
630   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
631       BI != BE; ++BI) {
632     Instruction *I = BI;
633
634     // PHI Nodes are OK.
635     if (isa<PHINode>(I))
636       continue;
637
638     // SplitCondition itself is OK.
639     if (I == SD.SplitCondition)
640       continue;
641
642     // Induction variable is OK.
643     if (I == IndVar)
644       continue;
645
646     // Induction variable increment is OK.
647     if (I == IndVarIncrement)
648       continue;
649
650     // Terminator is also harmless.
651     if (I == Terminator)
652       continue;
653
654     // Otherwise we have a instruction that may not be safe.
655     return false;
656   }
657   
658   return true;
659 }
660
661 // If Exiting block includes loop variant instructions then this
662 // loop may not be eliminated. This is used by processOneIterationLoop().
663 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD, 
664                                        BasicBlock *ExitingBlock) {
665
666   for (BasicBlock::iterator BI = ExitingBlock->begin(), 
667          BE = ExitingBlock->end(); BI != BE; ++BI) {
668     Instruction *I = BI;
669
670     // PHI Nodes are OK.
671     if (isa<PHINode>(I))
672       continue;
673
674     // Induction variable increment is OK.
675     if (IndVarIncrement && IndVarIncrement == I)
676       continue;
677
678     // Check if I is induction variable increment instruction.
679     if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
680
681       Value *Op0 = I->getOperand(0);
682       Value *Op1 = I->getOperand(1);
683       PHINode *PN = NULL;
684       ConstantInt *CI = NULL;
685
686       if ((PN = dyn_cast<PHINode>(Op0))) {
687         if ((CI = dyn_cast<ConstantInt>(Op1)))
688           IndVarIncrement = I;
689       } else 
690         if ((PN = dyn_cast<PHINode>(Op1))) {
691           if ((CI = dyn_cast<ConstantInt>(Op0)))
692             IndVarIncrement = I;
693       }
694           
695       if (IndVarIncrement && PN == IndVar && CI->isOne())
696         continue;
697     }
698
699     // I is an Exit condition if next instruction is block terminator.
700     // Exit condition is OK if it compares loop invariant exit value,
701     // which is checked below.
702     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
703       if (EC == ExitCondition)
704         continue;
705     }
706
707     if (I == ExitingBlock->getTerminator())
708       continue;
709
710     // Otherwise we have instruction that may not be safe.
711     return false;
712   }
713
714   // We could not find any reason to consider ExitingBlock unsafe.
715   return true;
716 }
717
718 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
719
720   Value *V0 = CI->getOperand(0);
721   Value *V1 = CI->getOperand(1);
722   Value *NV = NULL;
723
724   SCEVHandle SH0 = SE->getSCEV(V0);
725   
726   if (SH0->isLoopInvariant(L))
727     NV = V0;
728   else
729     NV = V1;
730
731   switch (CI->getPredicate()) {
732   case ICmpInst::ICMP_ULE:
733   case ICmpInst::ICMP_SLE:
734     // for (i = LB; i < UB; ++i)
735     //   if (i <= NV && ...)
736     //      LOOP_BODY
737     // 
738     // is transformed into
739     // NUB = min (NV+1, UB)
740     // for (i = LB; i < NUB ; ++i)
741     //   LOOP_BODY
742     //
743
744
745
746     // for (i = LB; i <= UB; ++i)
747     //   if (i <= NV && ...)
748     //      LOOP_BODY
749     // 
750     // is transformed into
751     // NUB = min (NV, UB)
752     // for (i = LB; i <= NUB ; ++i)
753     //   LOOP_BODY
754     //
755     break;
756   case ICmpInst::ICMP_ULT:
757   case ICmpInst::ICMP_SLT:
758     // for (i = LB; i < UB; ++i)
759     //   if (i < NV && ...)
760     //      LOOP_BODY
761     // 
762     // is transformed into
763     // NUB = min (NV, UB)
764     // for (i = LB; i < NUB ; ++i)
765     //   LOOP_BODY
766     //
767
768
769
770     // for (i = LB; i <= UB; ++i)
771     //   if (i < NV && ...)
772     //      LOOP_BODY
773     // 
774     // is transformed into
775     // NUB = min (NV -1 , UB)
776     // for (i = LB; i <= NUB ; ++i)
777     //   LOOP_BODY
778     //
779     break;
780   case ICmpInst::ICMP_UGE:
781   case ICmpInst::ICMP_SGE:
782     // for (i = LB; i (< or <=) UB; ++i)
783     //   if (i >= NV && ...)
784     //      LOOP_BODY
785     // 
786     // is transformed into
787     // NLB = max (NV, LB)
788     // for (i = NLB; i (< or <=) UB ; ++i)
789     //   LOOP_BODY
790     //
791     break;
792   case ICmpInst::ICMP_UGT:
793   case ICmpInst::ICMP_SGT:
794     // for (i = LB; i (< or <=) UB; ++i)
795     //   if (i > NV && ...)
796     //      LOOP_BODY
797     // 
798     // is transformed into
799     // NLB = max (NV+1, LB)
800     // for (i = NLB; i (< or <=) UB ; ++i)
801     //   LOOP_BODY
802     //
803     break;
804   default:
805     assert ( 0 && "Unexpected split condition predicate");
806   }
807 }
808 /// updateLoopIterationSpace - Current loop body is covered by an AND
809 /// instruction whose operands compares induction variables with loop
810 /// invariants. If possible, hoist this check outside the loop by
811 /// updating appropriate start and end values for induction variable.
812 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
813   BasicBlock *Header = L->getHeader();
814   ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
815   ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
816
817   if (Op0->getPredicate() == ICmpInst::ICMP_EQ 
818       || Op0->getPredicate() == ICmpInst::ICMP_NE
819       || Op0->getPredicate() == ICmpInst::ICMP_EQ 
820       || Op0->getPredicate() == ICmpInst::ICMP_NE)
821     return false;
822
823   // Check if SplitCondition dominates entire loop body
824   // or not.
825   
826   // If SplitCondition is not in loop header then this loop is not suitable
827   // for this transformation.
828   if (SD.SplitCondition->getParent() != Header)
829     return false;
830   
831   // If loop header includes loop variant instruction operands then
832   // this loop may not be eliminated.
833   Instruction *Terminator = Header->getTerminator();
834   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
835       BI != BE; ++BI) {
836     Instruction *I = BI;
837
838     // PHI Nodes are OK.
839     if (isa<PHINode>(I))
840       continue;
841
842     // SplitCondition itself is OK.
843     if (I == SD.SplitCondition)
844       continue;
845     if (I == Op0 || I == Op1)
846       continue;
847
848     // Induction variable is OK.
849     if (I == IndVar)
850       continue;
851
852     // Induction variable increment is OK.
853     if (I == IndVarIncrement)
854       continue;
855
856     // Terminator is also harmless.
857     if (I == Terminator)
858       continue;
859
860     // Otherwise we have a instruction that may not be safe.
861     return false;
862   }
863
864   // If Exiting block includes loop variant instructions then this
865   // loop may not be eliminated.
866   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
867     return false;
868
869   updateLoopBounds(Op0);
870   updateLoopBounds(Op1);
871   // Update CFG
872   return false;
873 }
874
875
876 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
877 /// This routine is used to remove split condition's dead branch, dominated by
878 /// DeadBB. LiveBB dominates split conidition's other branch.
879 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
880                                   BasicBlock *LiveBB) {
881
882   // First update DeadBB's dominance frontier. 
883   SmallVector<BasicBlock *, 8> FrontierBBs;
884   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
885   if (DeadBBDF != DF->end()) {
886     SmallVector<BasicBlock *, 8> PredBlocks;
887     
888     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
889     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
890            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
891       BasicBlock *FrontierBB = *DeadBBSetI;
892       FrontierBBs.push_back(FrontierBB);
893
894       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
895       PredBlocks.clear();
896       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
897           PI != PE; ++PI) {
898         BasicBlock *P = *PI;
899         if (P == DeadBB || DT->dominates(DeadBB, P))
900           PredBlocks.push_back(P);
901       }
902
903       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
904           FBI != FBE; ++FBI) {
905         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
906           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
907                 PE = PredBlocks.end(); PI != PE; ++PI) {
908             BasicBlock *P = *PI;
909             PN->removeIncomingValue(P);
910           }
911         }
912         else
913           break;
914       }      
915     }
916   }
917   
918   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
919   SmallVector<BasicBlock *, 32> WorkList;
920   DomTreeNode *DN = DT->getNode(DeadBB);
921   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
922          E = df_end(DN); DI != E; ++DI) {
923     BasicBlock *BB = DI->getBlock();
924     WorkList.push_back(BB);
925     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
926   }
927
928   while (!WorkList.empty()) {
929     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
930     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
931         BBI != BBE; ++BBI) {
932       Instruction *I = BBI;
933       I->replaceAllUsesWith(UndefValue::get(I->getType()));
934       I->eraseFromParent();
935     }
936     LPM->deleteSimpleAnalysisValue(BB, LP);
937     DT->eraseNode(BB);
938     DF->removeBlock(BB);
939     LI->removeBlock(BB);
940     BB->eraseFromParent();
941   }
942
943   // Update Frontier BBs' dominator info.
944   while (!FrontierBBs.empty()) {
945     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
946     BasicBlock *NewDominator = FBB->getSinglePredecessor();
947     if (!NewDominator) {
948       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
949       NewDominator = *PI;
950       ++PI;
951       if (NewDominator != LiveBB) {
952         for(; PI != PE; ++PI) {
953           BasicBlock *P = *PI;
954           if (P == LiveBB) {
955             NewDominator = LiveBB;
956             break;
957           }
958           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
959         }
960       }
961     }
962     assert (NewDominator && "Unable to fix dominator info.");
963     DT->changeImmediateDominator(FBB, NewDominator);
964     DF->changeImmediateDominator(FBB, NewDominator, DT);
965   }
966
967 }
968
969 /// safeSplitCondition - Return true if it is possible to
970 /// split loop using given split condition.
971 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
972
973   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
974   BasicBlock *Latch = L->getLoopLatch();  
975   BranchInst *SplitTerminator = 
976     cast<BranchInst>(SplitCondBlock->getTerminator());
977   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
978   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
979
980   // Finally this split condition is safe only if merge point for
981   // split condition branch is loop latch. This check along with previous
982   // check, to ensure that exit condition is in either loop latch or header,
983   // filters all loops with non-empty loop body between merge point
984   // and exit condition.
985   DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
986   assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
987   if (Succ0DF->second.count(Latch))
988     return true;
989
990   DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
991   assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
992   if (Succ1DF->second.count(Latch))
993     return true;
994   
995   return false;
996 }
997
998 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
999 /// based on split value. 
1000 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1001
1002   ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1003   ICmpInst::Predicate SP = SC->getPredicate();
1004   const Type *Ty = SD.SplitValue->getType();
1005   bool Sign = ExitCondition->isSignedPredicate();
1006   BasicBlock *Preheader = L->getLoopPreheader();
1007   Instruction *PHTerminator = Preheader->getTerminator();
1008
1009   // Initially use split value as upper loop bound for first loop and lower loop
1010   // bound for second loop.
1011   Value *AEV = SD.SplitValue;
1012   Value *BSV = SD.SplitValue;
1013
1014   switch (ExitCondition->getPredicate()) {
1015   case ICmpInst::ICMP_SGT:
1016   case ICmpInst::ICMP_UGT:
1017   case ICmpInst::ICMP_SGE:
1018   case ICmpInst::ICMP_UGE:
1019   default:
1020     assert (0 && "Unexpected exit condition predicate");
1021
1022   case ICmpInst::ICMP_SLT:
1023   case ICmpInst::ICMP_ULT:
1024     {
1025       switch (SP) {
1026       case ICmpInst::ICMP_SLT:
1027       case ICmpInst::ICMP_ULT:
1028         //
1029         // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1030         //
1031         // is transformed into
1032         // AEV = BSV = SV
1033         // for (i = LB; i < min(UB, AEV); ++i)
1034         //    A;
1035         // for (i = max(LB, BSV); i < UB; ++i);
1036         //    B;
1037         break;
1038       case ICmpInst::ICMP_SLE:
1039       case ICmpInst::ICMP_ULE:
1040         {
1041           //
1042           // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1043           //
1044           // is transformed into
1045           //
1046           // AEV = SV + 1
1047           // BSV = SV + 1
1048           // for (i = LB; i < min(UB, AEV); ++i) 
1049           //       A;
1050           // for (i = max(LB, BSV); i < UB; ++i) 
1051           //       B;
1052           BSV = BinaryOperator::createAdd(SD.SplitValue,
1053                                           ConstantInt::get(Ty, 1, Sign),
1054                                           "lsplit.add", PHTerminator);
1055           AEV = BSV;
1056         }
1057         break;
1058       case ICmpInst::ICMP_SGE:
1059       case ICmpInst::ICMP_UGE: 
1060         //
1061         // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1062         // 
1063         // is transformed into
1064         // AEV = BSV = SV
1065         // for (i = LB; i < min(UB, AEV); ++i)
1066         //    B;
1067         // for (i = max(BSV, LB); i < UB; ++i)
1068         //    A;
1069         break;
1070       case ICmpInst::ICMP_SGT:
1071       case ICmpInst::ICMP_UGT: 
1072         {
1073           //
1074           // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1075           //
1076           // is transformed into
1077           //
1078           // BSV = AEV = SV + 1
1079           // for (i = LB; i < min(UB, AEV); ++i) 
1080           //       B;
1081           // for (i = max(LB, BSV); i < UB; ++i) 
1082           //       A;
1083           BSV = BinaryOperator::createAdd(SD.SplitValue,
1084                                           ConstantInt::get(Ty, 1, Sign),
1085                                           "lsplit.add", PHTerminator);
1086           AEV = BSV;
1087         }
1088         break;
1089       default:
1090         assert (0 && "Unexpected split condition predicate");
1091         break;
1092       } // end switch (SP)
1093     }
1094     break;
1095   case ICmpInst::ICMP_SLE:
1096   case ICmpInst::ICMP_ULE:
1097     {
1098       switch (SP) {
1099       case ICmpInst::ICMP_SLT:
1100       case ICmpInst::ICMP_ULT:
1101         //
1102         // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1103         //
1104         // is transformed into
1105         // AEV = SV - 1;
1106         // BSV = SV;
1107         // for (i = LB; i <= min(UB, AEV); ++i) 
1108         //       A;
1109         // for (i = max(LB, BSV); i <= UB; ++i) 
1110         //       B;
1111         AEV = BinaryOperator::createSub(SD.SplitValue,
1112                                         ConstantInt::get(Ty, 1, Sign),
1113                                         "lsplit.sub", PHTerminator);
1114         break;
1115       case ICmpInst::ICMP_SLE:
1116       case ICmpInst::ICMP_ULE:
1117         //
1118         // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1119         //
1120         // is transformed into
1121         // AEV = SV;
1122         // BSV = SV + 1;
1123         // for (i = LB; i <= min(UB, AEV); ++i) 
1124         //       A;
1125         // for (i = max(LB, BSV); i <= UB; ++i) 
1126         //       B;
1127         BSV = BinaryOperator::createAdd(SD.SplitValue,
1128                                         ConstantInt::get(Ty, 1, Sign),
1129                                         "lsplit.add", PHTerminator);
1130         break;
1131       case ICmpInst::ICMP_SGT:
1132       case ICmpInst::ICMP_UGT: 
1133         //
1134         // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1135         //
1136         // is transformed into
1137         // AEV = SV;
1138         // BSV = SV + 1;
1139         // for (i = LB; i <= min(AEV, UB); ++i)
1140         //      B;
1141         // for (i = max(LB, BSV); i <= UB; ++i)
1142         //      A;
1143         BSV = BinaryOperator::createAdd(SD.SplitValue,
1144                                         ConstantInt::get(Ty, 1, Sign),
1145                                         "lsplit.add", PHTerminator);
1146         break;
1147       case ICmpInst::ICMP_SGE:
1148       case ICmpInst::ICMP_UGE: 
1149         // ** TODO **
1150         //
1151         // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1152         //
1153         // is transformed into
1154         // AEV = SV - 1;
1155         // BSV = SV;
1156         // for (i = LB; i <= min(AEV, UB); ++i)
1157         //      B;
1158         // for (i = max(LB, BSV); i <= UB; ++i)
1159         //      A;
1160         AEV = BinaryOperator::createSub(SD.SplitValue,
1161                                         ConstantInt::get(Ty, 1, Sign),
1162                                         "lsplit.sub", PHTerminator);
1163         break;
1164       default:
1165         assert (0 && "Unexpected split condition predicate");
1166         break;
1167       } // end switch (SP)
1168     }
1169     break;
1170   }
1171
1172   // Calculate ALoop induction variable's new exiting value and
1173   // BLoop induction variable's new starting value. Calculuate these
1174   // values in original loop's preheader.
1175   //      A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1176   //      B_StartValue = max(SplitValue, OriginalLoopStartValue)
1177   Value *C1 = new ICmpInst(Sign ?
1178                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1179                            AEV,
1180                            ExitCondition->getOperand(ExitValueNum), 
1181                            "lsplit.ev", PHTerminator);
1182   SD.A_ExitValue = new SelectInst(C1, AEV,
1183                                   ExitCondition->getOperand(ExitValueNum), 
1184                                   "lsplit.ev", PHTerminator);
1185   
1186   Value *C2 = new ICmpInst(Sign ?
1187                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1188                            BSV, StartValue, "lsplit.sv",
1189                            PHTerminator);
1190   SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
1191                                    "lsplit.sv", PHTerminator);
1192 }
1193
1194 /// splitLoop - Split current loop L in two loops using split information
1195 /// SD. Update dominator information. Maintain LCSSA form.
1196 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1197
1198   if (!safeSplitCondition(SD))
1199     return false;
1200
1201   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1202   
1203   // Unable to handle triange loops at the moment.
1204   // In triangle loop, split condition is in header and one of the
1205   // the split destination is loop latch. If split condition is EQ
1206   // then such loops are already handle in processOneIterationLoop().
1207   BasicBlock *Latch = L->getLoopLatch();
1208   BranchInst *SplitTerminator = 
1209     cast<BranchInst>(SplitCondBlock->getTerminator());
1210   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1211   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1212   if (L->getHeader() == SplitCondBlock 
1213       && (Latch == Succ0 || Latch == Succ1))
1214     return false;
1215
1216   // If split condition branches heads do not have single predecessor, 
1217   // SplitCondBlock, then is not possible to remove inactive branch.
1218   if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1219     return false;
1220
1221   // After loop is cloned there are two loops.
1222   //
1223   // First loop, referred as ALoop, executes first part of loop's iteration
1224   // space split.  Second loop, referred as BLoop, executes remaining
1225   // part of loop's iteration space. 
1226   //
1227   // ALoop's exit edge enters BLoop's header through a forwarding block which 
1228   // acts as a BLoop's preheader.
1229   BasicBlock *Preheader = L->getLoopPreheader();
1230
1231   // Calculate ALoop induction variable's new exiting value and
1232   // BLoop induction variable's new starting value.
1233   calculateLoopBounds(SD);
1234
1235   //[*] Clone loop.
1236   DenseMap<const Value *, Value *> ValueMap;
1237   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1238   Loop *ALoop = L;
1239   BasicBlock *B_Header = BLoop->getHeader();
1240
1241   //[*] ALoop's exiting edge BLoop's header.
1242   //    ALoop's original exit block becomes BLoop's exit block.
1243   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1244   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1245   BranchInst *A_ExitInsn =
1246     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1247   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1248   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1249   if (L->contains(B_ExitBlock)) {
1250     B_ExitBlock = A_ExitInsn->getSuccessor(0);
1251     A_ExitInsn->setSuccessor(0, B_Header);
1252   } else
1253     A_ExitInsn->setSuccessor(1, B_Header);
1254
1255   //[*] Update ALoop's exit value using new exit value.
1256   ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1257   
1258   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1259   //     original loop's preheader. Add incoming PHINode values from
1260   //     ALoop's exiting block. Update BLoop header's domiantor info.
1261
1262   // Collect inverse map of Header PHINodes.
1263   DenseMap<Value *, Value *> InverseMap;
1264   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
1265          BE = L->getHeader()->end(); BI != BE; ++BI) {
1266     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1267       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1268       InverseMap[PNClone] = PN;
1269     } else
1270       break;
1271   }
1272
1273   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1274        BI != BE; ++BI) {
1275     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1276       // Remove incoming value from original preheader.
1277       PN->removeIncomingValue(Preheader);
1278
1279       // Add incoming value from A_ExitingBlock.
1280       if (PN == B_IndVar)
1281         PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1282       else { 
1283         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1284         Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1285         PN->addIncoming(V2, A_ExitingBlock);
1286       }
1287     } else
1288       break;
1289   }
1290   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1291   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1292   
1293   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1294   //     block. Remove incoming PHINode values from ALoop's exiting block.
1295   //     Add new incoming values from BLoop's incoming exiting value.
1296   //     Update BLoop exit block's dominator info..
1297   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1298   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1299        BI != BE; ++BI) {
1300     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1301       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1302                                                             B_ExitingBlock);
1303       PN->removeIncomingValue(A_ExitingBlock);
1304     } else
1305       break;
1306   }
1307
1308   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1309   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1310
1311   //[*] Split ALoop's exit edge. This creates a new block which
1312   //    serves two purposes. First one is to hold PHINode defnitions
1313   //    to ensure that ALoop's LCSSA form. Second use it to act
1314   //    as a preheader for BLoop.
1315   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1316
1317   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1318   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1319   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1320       BI != BE; ++BI) {
1321     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1322       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1323       PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
1324       newPHI->addIncoming(V1, A_ExitingBlock);
1325       A_ExitBlock->getInstList().push_front(newPHI);
1326       PN->removeIncomingValue(A_ExitBlock);
1327       PN->addIncoming(newPHI, A_ExitBlock);
1328     } else
1329       break;
1330   }
1331
1332   //[*] Eliminate split condition's inactive branch from ALoop.
1333   BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1334   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1335   BasicBlock *A_InactiveBranch = NULL;
1336   BasicBlock *A_ActiveBranch = NULL;
1337   if (SD.UseTrueBranchFirst) {
1338     A_ActiveBranch = A_BR->getSuccessor(0);
1339     A_InactiveBranch = A_BR->getSuccessor(1);
1340   } else {
1341     A_ActiveBranch = A_BR->getSuccessor(1);
1342     A_InactiveBranch = A_BR->getSuccessor(0);
1343   }
1344   A_BR->setUnconditionalDest(A_ActiveBranch);
1345   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1346
1347   //[*] Eliminate split condition's inactive branch in from BLoop.
1348   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1349   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1350   BasicBlock *B_InactiveBranch = NULL;
1351   BasicBlock *B_ActiveBranch = NULL;
1352   if (SD.UseTrueBranchFirst) {
1353     B_ActiveBranch = B_BR->getSuccessor(1);
1354     B_InactiveBranch = B_BR->getSuccessor(0);
1355   } else {
1356     B_ActiveBranch = B_BR->getSuccessor(0);
1357     B_InactiveBranch = B_BR->getSuccessor(1);
1358   }
1359   B_BR->setUnconditionalDest(B_ActiveBranch);
1360   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1361
1362   BasicBlock *A_Header = L->getHeader();
1363   if (A_ExitingBlock == A_Header)
1364     return true;
1365
1366   //[*] Move exit condition into split condition block to avoid
1367   //    executing dead loop iteration.
1368   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1369   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1370   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1371
1372   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1373                     cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement, 
1374                     ALoop);
1375
1376   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1377                     B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1378
1379   return true;
1380 }
1381
1382 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1383 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1384                                        BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1385                                        PHINode *IV, Instruction *IVAdd, Loop *LP) {
1386
1387   BasicBlock *ExitingBB = EC->getParent();
1388   Instruction *CurrentBR = CondBB->getTerminator();
1389
1390   // Move exit condition into split condition block.
1391   EC->moveBefore(CurrentBR);
1392   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1393
1394   // Move exiting block's branch into split condition block. Update its branch
1395   // destination.
1396   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1397   ExitingBR->moveBefore(CurrentBR);
1398   if (ExitingBR->getSuccessor(0) == ExitBB)
1399     ExitingBR->setSuccessor(1, ActiveBB);
1400   else
1401     ExitingBR->setSuccessor(0, ActiveBB);
1402     
1403   // Remove split condition and current split condition branch.
1404   SC->eraseFromParent();
1405   CurrentBR->eraseFromParent();
1406
1407   // Connect exiting block to split condition block.
1408   new BranchInst(CondBB, ExitingBB);
1409
1410   // Update PHINodes
1411   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1412
1413   // Fix dominator info.
1414   // ExitBB is now dominated by CondBB
1415   DT->changeImmediateDominator(ExitBB, CondBB);
1416   DF->changeImmediateDominator(ExitBB, CondBB, DT);
1417   
1418   // Basicblocks dominated by ActiveBB may have ExitingBB or
1419   // a basic block outside the loop in their DF list. If so,
1420   // replace it with CondBB.
1421   DomTreeNode *Node = DT->getNode(ActiveBB);
1422   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1423        DI != DE; ++DI) {
1424     BasicBlock *BB = DI->getBlock();
1425     DominanceFrontier::iterator BBDF = DF->find(BB);
1426     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1427     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1428     while (DomSetI != DomSetE) {
1429       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1430       ++DomSetI;
1431       BasicBlock *DFBB = *CurrentItr;
1432       if (DFBB == ExitingBB || !L->contains(DFBB)) {
1433         BBDF->second.erase(DFBB);
1434         BBDF->second.insert(CondBB);
1435       }
1436     }
1437   }
1438 }
1439
1440 /// updatePHINodes - CFG has been changed. 
1441 /// Before 
1442 ///   - ExitBB's single predecessor was Latch
1443 ///   - Latch's second successor was Header
1444 /// Now
1445 ///   - ExitBB's single predecessor was Header
1446 ///   - Latch's one and only successor was Header
1447 ///
1448 /// Update ExitBB PHINodes' to reflect this change.
1449 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
1450                                     BasicBlock *Header,
1451                                     PHINode *IV, Instruction *IVIncrement) {
1452
1453   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
1454        BI != BE; ++BI) {
1455     PHINode *PN = dyn_cast<PHINode>(BI);
1456     if (!PN)
1457       break;
1458
1459     Value *V = PN->getIncomingValueForBlock(Latch);
1460     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1461       // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode 
1462       // (i.e. PN :)). 
1463       // The second use is in Header and it is new incoming value for PN.
1464       PHINode *U1 = NULL;
1465       PHINode *U2 = NULL;
1466       Value *NewV = NULL;
1467       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
1468            UI != E; ++UI) {
1469         if (!U1)
1470           U1 = cast<PHINode>(*UI);
1471         else if (!U2)
1472           U2 = cast<PHINode>(*UI);
1473         else
1474           assert ( 0 && "Unexpected third use of this PHINode");
1475       }
1476       assert (U1 && U2 && "Unable to find two uses");
1477       
1478       if (U1->getParent() == Header) 
1479         NewV = U1;
1480       else
1481         NewV = U2;
1482       PN->addIncoming(NewV, Header);
1483
1484     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1485       // If this instruction is IVIncrement then IV is new incoming value 
1486       // from header otherwise this instruction must be incoming value from 
1487       // header because loop is in LCSSA form.
1488       if (PHI == IVIncrement)
1489         PN->addIncoming(IV, Header);
1490       else
1491         PN->addIncoming(V, Header);
1492     } else
1493       // Otherwise this is an incoming value from header because loop is in 
1494       // LCSSA form.
1495       PN->addIncoming(V, Header);
1496     
1497     // Remove incoming value from Latch.
1498     PN->removeIncomingValue(Latch);
1499   }
1500 }