Skeleton for transformations to truncate loop's iteration space.
[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   // Update CFG.
532
533   // Replace index variable with split value in loop body. Loop body is executed
534   // only when index variable is equal to split value.
535   IndVar->replaceAllUsesWith(SD.SplitValue);
536
537   // Remove Latch to Header edge.
538   BasicBlock *Latch = L->getLoopLatch();
539   BasicBlock *LatchSucc = NULL;
540   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
541   if (!BR)
542     return false;
543   Header->removePredecessor(Latch);
544   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
545        SI != E; ++SI) {
546     if (Header != *SI)
547       LatchSucc = *SI;
548   }
549   BR->setUnconditionalDest(LatchSucc);
550
551   Instruction *Terminator = Header->getTerminator();
552   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
553
554   // Replace split condition in header.
555   // Transform 
556   //      SplitCondition : icmp eq i32 IndVar, SplitValue
557   // into
558   //      c1 = icmp uge i32 SplitValue, StartValue
559   //      c2 = icmp ult i32 SplitValue, ExitValue
560   //      and i32 c1, c2 
561   bool SignedPredicate = ExitCondition->isSignedPredicate();
562   Instruction *C1 = new ICmpInst(SignedPredicate ? 
563                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
564                                  SD.SplitValue, StartValue, "lisplit", 
565                                  Terminator);
566   Instruction *C2 = new ICmpInst(SignedPredicate ? 
567                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
568                                  SD.SplitValue, ExitValue, "lisplit", 
569                                  Terminator);
570   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
571                                                       Terminator);
572   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
573   SD.SplitCondition->eraseFromParent();
574
575   // Now, clear latch block. Remove instructions that are responsible
576   // to increment induction variable. 
577   Instruction *LTerminator = Latch->getTerminator();
578   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
579        LB != LE; ) {
580     Instruction *I = LB;
581     ++LB;
582     if (isa<PHINode>(I) || I == LTerminator)
583       continue;
584
585     if (I == IndVarIncrement) 
586       I->replaceAllUsesWith(ExitValue);
587     else
588       I->replaceAllUsesWith(UndefValue::get(I->getType()));
589     I->eraseFromParent();
590   }
591
592   LPM->deleteLoopFromQueue(L);
593
594   // Update Dominator Info.
595   // Only CFG change done is to remove Latch to Header edge. This
596   // does not change dominator tree because Latch did not dominate
597   // Header.
598   if (DF) {
599     DominanceFrontier::iterator HeaderDF = DF->find(Header);
600     if (HeaderDF != DF->end()) 
601       DF->removeFromFrontier(HeaderDF, Header);
602
603     DominanceFrontier::iterator LatchDF = DF->find(Latch);
604     if (LatchDF != DF->end()) 
605       DF->removeFromFrontier(LatchDF, Header);
606   }
607   return true;
608 }
609
610 // If loop header includes loop variant instruction operands then
611 // this loop can not be eliminated. This is used by processOneIterationLoop().
612 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
613
614   Instruction *Terminator = Header->getTerminator();
615   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
616       BI != BE; ++BI) {
617     Instruction *I = BI;
618
619     // PHI Nodes are OK.
620     if (isa<PHINode>(I))
621       continue;
622
623     // SplitCondition itself is OK.
624     if (I == SD.SplitCondition)
625       continue;
626
627     // Induction variable is OK.
628     if (I == IndVar)
629       continue;
630
631     // Induction variable increment is OK.
632     if (I == IndVarIncrement)
633       continue;
634
635     // Terminator is also harmless.
636     if (I == Terminator)
637       continue;
638
639     // Otherwise we have a instruction that may not be safe.
640     return false;
641   }
642   
643   return true;
644 }
645
646 // If Exiting block includes loop variant instructions then this
647 // loop may not be eliminated. This is used by processOneIterationLoop().
648 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD, 
649                                        BasicBlock *ExitingBlock) {
650
651   for (BasicBlock::iterator BI = ExitingBlock->begin(), 
652          BE = ExitingBlock->end(); BI != BE; ++BI) {
653     Instruction *I = BI;
654
655     // PHI Nodes are OK.
656     if (isa<PHINode>(I))
657       continue;
658
659     // Induction variable increment is OK.
660     if (IndVarIncrement && IndVarIncrement == I)
661       continue;
662
663     // Check if I is induction variable increment instruction.
664     if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
665
666       Value *Op0 = I->getOperand(0);
667       Value *Op1 = I->getOperand(1);
668       PHINode *PN = NULL;
669       ConstantInt *CI = NULL;
670
671       if ((PN = dyn_cast<PHINode>(Op0))) {
672         if ((CI = dyn_cast<ConstantInt>(Op1)))
673           IndVarIncrement = I;
674       } else 
675         if ((PN = dyn_cast<PHINode>(Op1))) {
676           if ((CI = dyn_cast<ConstantInt>(Op0)))
677             IndVarIncrement = I;
678       }
679           
680       if (IndVarIncrement && PN == IndVar && CI->isOne())
681         continue;
682     }
683
684     // I is an Exit condition if next instruction is block terminator.
685     // Exit condition is OK if it compares loop invariant exit value,
686     // which is checked below.
687     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
688       if (EC == ExitCondition)
689         continue;
690     }
691
692     if (I == ExitingBlock->getTerminator())
693       continue;
694
695     // Otherwise we have instruction that may not be safe.
696     return false;
697   }
698
699   // We could not find any reason to consider ExitingBlock unsafe.
700   return true;
701 }
702
703 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
704
705   Value *V0 = CI->getOperand(0);
706   Value *V1 = CI->getOperand(1);
707   Value *NV = NULL;
708
709   SCEVHandle SH0 = SE->getSCEV(V0);
710   
711   if (SH0->isLoopInvariant(L))
712     NV = V0;
713   else
714     NV = V1;
715
716   switch (CI->getPredicate()) {
717   case ICmpInst::ICMP_ULE:
718   case ICmpInst::ICMP_SLE:
719     // for (i = LB; i < UB; ++i)
720     //   if (i <= NV && ...)
721     //      LOOP_BODY
722     // 
723     // is transformed into
724     // NUB = min (NV+1, UB)
725     // for (i = LB; i < NUB ; ++i)
726     //   LOOP_BODY
727     //
728
729
730
731     // for (i = LB; i <= UB; ++i)
732     //   if (i <= NV && ...)
733     //      LOOP_BODY
734     // 
735     // is transformed into
736     // NUB = min (NV, UB)
737     // for (i = LB; i <= NUB ; ++i)
738     //   LOOP_BODY
739     //
740     break;
741   case ICmpInst::ICMP_ULT:
742   case ICmpInst::ICMP_SLT:
743     // for (i = LB; i < UB; ++i)
744     //   if (i < NV && ...)
745     //      LOOP_BODY
746     // 
747     // is transformed into
748     // NUB = min (NV, UB)
749     // for (i = LB; i < NUB ; ++i)
750     //   LOOP_BODY
751     //
752
753
754
755     // for (i = LB; i <= UB; ++i)
756     //   if (i < NV && ...)
757     //      LOOP_BODY
758     // 
759     // is transformed into
760     // NUB = min (NV -1 , UB)
761     // for (i = LB; i <= NUB ; ++i)
762     //   LOOP_BODY
763     //
764     break;
765   case ICmpInst::ICMP_UGE:
766   case ICmpInst::ICMP_SGE:
767     // for (i = LB; i (< or <=) UB; ++i)
768     //   if (i >= NV && ...)
769     //      LOOP_BODY
770     // 
771     // is transformed into
772     // NLB = max (NV, LB)
773     // for (i = NLB; i (< or <=) UB ; ++i)
774     //   LOOP_BODY
775     //
776     break;
777   case ICmpInst::ICMP_UGT:
778   case ICmpInst::ICMP_SGT:
779     // for (i = LB; i (< or <=) UB; ++i)
780     //   if (i > NV && ...)
781     //      LOOP_BODY
782     // 
783     // is transformed into
784     // NLB = max (NV+1, LB)
785     // for (i = NLB; i (< or <=) UB ; ++i)
786     //   LOOP_BODY
787     //
788     break;
789   default:
790     assert ( 0 && "Unexpected split condition predicate");
791   }
792 }
793 /// updateLoopIterationSpace - Current loop body is covered by an AND
794 /// instruction whose operands compares induction variables with loop
795 /// invariants. If possible, hoist this check outside the loop by
796 /// updating appropriate start and end values for induction variable.
797 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
798   BasicBlock *Header = L->getHeader();
799   ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
800   ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
801
802   if (Op0->getPredicate() == ICmpInst::ICMP_EQ 
803       || Op0->getPredicate() == ICmpInst::ICMP_NE
804       || Op0->getPredicate() == ICmpInst::ICMP_EQ 
805       || Op0->getPredicate() == ICmpInst::ICMP_NE)
806     return false;
807
808   // Check if SplitCondition dominates entire loop body
809   // or not.
810   
811   // If SplitCondition is not in loop header then this loop is not suitable
812   // for this transformation.
813   if (SD.SplitCondition->getParent() != Header)
814     return false;
815   
816   // If loop header includes loop variant instruction operands then
817   // this loop may not be eliminated.
818   Instruction *Terminator = Header->getTerminator();
819   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
820       BI != BE; ++BI) {
821     Instruction *I = BI;
822
823     // PHI Nodes are OK.
824     if (isa<PHINode>(I))
825       continue;
826
827     // SplitCondition itself is OK.
828     if (I == SD.SplitCondition)
829       continue;
830     if (I == Op0 || I == Op1)
831       continue;
832
833     // Induction variable is OK.
834     if (I == IndVar)
835       continue;
836
837     // Induction variable increment is OK.
838     if (I == IndVarIncrement)
839       continue;
840
841     // Terminator is also harmless.
842     if (I == Terminator)
843       continue;
844
845     // Otherwise we have a instruction that may not be safe.
846     return false;
847   }
848
849   // If Exiting block includes loop variant instructions then this
850   // loop may not be eliminated.
851   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
852     return false;
853
854   updateLoopBounds(Op0);
855   updateLoopBounds(Op1);
856   // Update CFG
857   return true;
858 }
859
860
861 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
862 /// This routine is used to remove split condition's dead branch, dominated by
863 /// DeadBB. LiveBB dominates split conidition's other branch.
864 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
865                                   BasicBlock *LiveBB) {
866
867   // First update DeadBB's dominance frontier. 
868   SmallVector<BasicBlock *, 8> FrontierBBs;
869   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
870   if (DeadBBDF != DF->end()) {
871     SmallVector<BasicBlock *, 8> PredBlocks;
872     
873     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
874     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
875            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
876       BasicBlock *FrontierBB = *DeadBBSetI;
877       FrontierBBs.push_back(FrontierBB);
878
879       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
880       PredBlocks.clear();
881       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
882           PI != PE; ++PI) {
883         BasicBlock *P = *PI;
884         if (P == DeadBB || DT->dominates(DeadBB, P))
885           PredBlocks.push_back(P);
886       }
887
888       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
889           FBI != FBE; ++FBI) {
890         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
891           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
892                 PE = PredBlocks.end(); PI != PE; ++PI) {
893             BasicBlock *P = *PI;
894             PN->removeIncomingValue(P);
895           }
896         }
897         else
898           break;
899       }      
900     }
901   }
902   
903   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
904   SmallVector<BasicBlock *, 32> WorkList;
905   DomTreeNode *DN = DT->getNode(DeadBB);
906   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
907          E = df_end(DN); DI != E; ++DI) {
908     BasicBlock *BB = DI->getBlock();
909     WorkList.push_back(BB);
910     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
911   }
912
913   while (!WorkList.empty()) {
914     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
915     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
916         BBI != BBE; ++BBI) {
917       Instruction *I = BBI;
918       I->replaceAllUsesWith(UndefValue::get(I->getType()));
919       I->eraseFromParent();
920     }
921     LPM->deleteSimpleAnalysisValue(BB, LP);
922     DT->eraseNode(BB);
923     DF->removeBlock(BB);
924     LI->removeBlock(BB);
925     BB->eraseFromParent();
926   }
927
928   // Update Frontier BBs' dominator info.
929   while (!FrontierBBs.empty()) {
930     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
931     BasicBlock *NewDominator = FBB->getSinglePredecessor();
932     if (!NewDominator) {
933       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
934       NewDominator = *PI;
935       ++PI;
936       if (NewDominator != LiveBB) {
937         for(; PI != PE; ++PI) {
938           BasicBlock *P = *PI;
939           if (P == LiveBB) {
940             NewDominator = LiveBB;
941             break;
942           }
943           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
944         }
945       }
946     }
947     assert (NewDominator && "Unable to fix dominator info.");
948     DT->changeImmediateDominator(FBB, NewDominator);
949     DF->changeImmediateDominator(FBB, NewDominator, DT);
950   }
951
952 }
953
954 /// safeSplitCondition - Return true if it is possible to
955 /// split loop using given split condition.
956 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
957
958   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
959   
960   // Unable to handle triange loops at the moment.
961   // In triangle loop, split condition is in header and one of the
962   // the split destination is loop latch. If split condition is EQ
963   // then such loops are already handle in processOneIterationLoop().
964   BasicBlock *Latch = L->getLoopLatch();
965   BranchInst *SplitTerminator = 
966     cast<BranchInst>(SplitCondBlock->getTerminator());
967   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
968   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
969   if (L->getHeader() == SplitCondBlock 
970       && (Latch == Succ0 || Latch == Succ1))
971     return false;
972   
973   // If split condition branches heads do not have single predecessor, 
974   // SplitCondBlock, then is not possible to remove inactive branch.
975   if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
976     return false;
977
978   // Finally this split condition is safe only if merge point for
979   // split condition branch is loop latch. This check along with previous
980   // check, to ensure that exit condition is in either loop latch or header,
981   // filters all loops with non-empty loop body between merge point
982   // and exit condition.
983   DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
984   assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
985   if (Succ0DF->second.count(Latch))
986     return true;
987
988   DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
989   assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
990   if (Succ1DF->second.count(Latch))
991     return true;
992   
993   return false;
994 }
995
996 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
997 /// based on split value. 
998 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
999
1000   ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1001   ICmpInst::Predicate SP = SC->getPredicate();
1002   const Type *Ty = SD.SplitValue->getType();
1003   bool Sign = ExitCondition->isSignedPredicate();
1004   BasicBlock *Preheader = L->getLoopPreheader();
1005   Instruction *PHTerminator = Preheader->getTerminator();
1006
1007   // Initially use split value as upper loop bound for first loop and lower loop
1008   // bound for second loop.
1009   Value *AEV = SD.SplitValue;
1010   Value *BSV = SD.SplitValue;
1011
1012   switch (ExitCondition->getPredicate()) {
1013   case ICmpInst::ICMP_SGT:
1014   case ICmpInst::ICMP_UGT:
1015   case ICmpInst::ICMP_SGE:
1016   case ICmpInst::ICMP_UGE:
1017   default:
1018     assert (0 && "Unexpected exit condition predicate");
1019
1020   case ICmpInst::ICMP_SLT:
1021   case ICmpInst::ICMP_ULT:
1022     {
1023       switch (SP) {
1024       case ICmpInst::ICMP_SLT:
1025       case ICmpInst::ICMP_ULT:
1026         //
1027         // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1028         //
1029         // is transformed into
1030         // AEV = BSV = SV
1031         // for (i = LB; i < min(UB, AEV); ++i)
1032         //    A;
1033         // for (i = max(LB, BSV); i < UB; ++i);
1034         //    B;
1035         break;
1036       case ICmpInst::ICMP_SLE:
1037       case ICmpInst::ICMP_ULE:
1038         {
1039           //
1040           // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1041           //
1042           // is transformed into
1043           //
1044           // AEV = SV + 1
1045           // BSV = SV + 1
1046           // for (i = LB; i < min(UB, AEV); ++i) 
1047           //       A;
1048           // for (i = max(LB, BSV); i < UB; ++i) 
1049           //       B;
1050           BSV = BinaryOperator::createAdd(SD.SplitValue,
1051                                           ConstantInt::get(Ty, 1, Sign),
1052                                           "lsplit.add", PHTerminator);
1053           AEV = BSV;
1054         }
1055         break;
1056       case ICmpInst::ICMP_SGE:
1057       case ICmpInst::ICMP_UGE: 
1058         //
1059         // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1060         // 
1061         // is transformed into
1062         // AEV = BSV = SV
1063         // for (i = LB; i < min(UB, AEV); ++i)
1064         //    B;
1065         // for (i = max(BSV, LB); i < UB; ++i)
1066         //    A;
1067         break;
1068       case ICmpInst::ICMP_SGT:
1069       case ICmpInst::ICMP_UGT: 
1070         {
1071           //
1072           // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1073           //
1074           // is transformed into
1075           //
1076           // BSV = AEV = SV + 1
1077           // for (i = LB; i < min(UB, AEV); ++i) 
1078           //       B;
1079           // for (i = max(LB, BSV); i < UB; ++i) 
1080           //       A;
1081           BSV = BinaryOperator::createAdd(SD.SplitValue,
1082                                           ConstantInt::get(Ty, 1, Sign),
1083                                           "lsplit.add", PHTerminator);
1084           AEV = BSV;
1085         }
1086         break;
1087       default:
1088         assert (0 && "Unexpected split condition predicate");
1089         break;
1090       } // end switch (SP)
1091     }
1092     break;
1093   case ICmpInst::ICMP_SLE:
1094   case ICmpInst::ICMP_ULE:
1095     {
1096       switch (SP) {
1097       case ICmpInst::ICMP_SLT:
1098       case ICmpInst::ICMP_ULT:
1099         //
1100         // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1101         //
1102         // is transformed into
1103         // AEV = SV - 1;
1104         // BSV = SV;
1105         // for (i = LB; i <= min(UB, AEV); ++i) 
1106         //       A;
1107         // for (i = max(LB, BSV); i <= UB; ++i) 
1108         //       B;
1109         AEV = BinaryOperator::createSub(SD.SplitValue,
1110                                         ConstantInt::get(Ty, 1, Sign),
1111                                         "lsplit.sub", PHTerminator);
1112         break;
1113       case ICmpInst::ICMP_SLE:
1114       case ICmpInst::ICMP_ULE:
1115         //
1116         // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1117         //
1118         // is transformed into
1119         // AEV = SV;
1120         // BSV = SV + 1;
1121         // for (i = LB; i <= min(UB, AEV); ++i) 
1122         //       A;
1123         // for (i = max(LB, BSV); i <= UB; ++i) 
1124         //       B;
1125         BSV = BinaryOperator::createAdd(SD.SplitValue,
1126                                         ConstantInt::get(Ty, 1, Sign),
1127                                         "lsplit.add", PHTerminator);
1128         break;
1129       case ICmpInst::ICMP_SGT:
1130       case ICmpInst::ICMP_UGT: 
1131         //
1132         // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1133         //
1134         // is transformed into
1135         // AEV = SV;
1136         // BSV = SV + 1;
1137         // for (i = LB; i <= min(AEV, UB); ++i)
1138         //      B;
1139         // for (i = max(LB, BSV); i <= UB; ++i)
1140         //      A;
1141         BSV = BinaryOperator::createAdd(SD.SplitValue,
1142                                         ConstantInt::get(Ty, 1, Sign),
1143                                         "lsplit.add", PHTerminator);
1144         break;
1145       case ICmpInst::ICMP_SGE:
1146       case ICmpInst::ICMP_UGE: 
1147         // ** TODO **
1148         //
1149         // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1150         //
1151         // is transformed into
1152         // AEV = SV - 1;
1153         // BSV = SV;
1154         // for (i = LB; i <= min(AEV, UB); ++i)
1155         //      B;
1156         // for (i = max(LB, BSV); i <= UB; ++i)
1157         //      A;
1158         AEV = BinaryOperator::createSub(SD.SplitValue,
1159                                         ConstantInt::get(Ty, 1, Sign),
1160                                         "lsplit.sub", PHTerminator);
1161         break;
1162       default:
1163         assert (0 && "Unexpected split condition predicate");
1164         break;
1165       } // end switch (SP)
1166     }
1167     break;
1168   }
1169
1170   // Calculate ALoop induction variable's new exiting value and
1171   // BLoop induction variable's new starting value. Calculuate these
1172   // values in original loop's preheader.
1173   //      A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1174   //      B_StartValue = max(SplitValue, OriginalLoopStartValue)
1175   Value *C1 = new ICmpInst(Sign ?
1176                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1177                            AEV,
1178                            ExitCondition->getOperand(ExitValueNum), 
1179                            "lsplit.ev", PHTerminator);
1180   SD.A_ExitValue = new SelectInst(C1, AEV,
1181                                   ExitCondition->getOperand(ExitValueNum), 
1182                                   "lsplit.ev", PHTerminator);
1183   
1184   Value *C2 = new ICmpInst(Sign ?
1185                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1186                            BSV, StartValue, "lsplit.sv",
1187                            PHTerminator);
1188   SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
1189                                    "lsplit.sv", PHTerminator);
1190 }
1191
1192 /// splitLoop - Split current loop L in two loops using split information
1193 /// SD. Update dominator information. Maintain LCSSA form.
1194 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1195
1196   if (!safeSplitCondition(SD))
1197     return false;
1198
1199   // After loop is cloned there are two loops.
1200   //
1201   // First loop, referred as ALoop, executes first part of loop's iteration
1202   // space split.  Second loop, referred as BLoop, executes remaining
1203   // part of loop's iteration space. 
1204   //
1205   // ALoop's exit edge enters BLoop's header through a forwarding block which 
1206   // acts as a BLoop's preheader.
1207   BasicBlock *Preheader = L->getLoopPreheader();
1208
1209   // Calculate ALoop induction variable's new exiting value and
1210   // BLoop induction variable's new starting value.
1211   calculateLoopBounds(SD);
1212
1213   //[*] Clone loop.
1214   DenseMap<const Value *, Value *> ValueMap;
1215   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1216   Loop *ALoop = L;
1217   BasicBlock *B_Header = BLoop->getHeader();
1218
1219   //[*] ALoop's exiting edge BLoop's header.
1220   //    ALoop's original exit block becomes BLoop's exit block.
1221   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1222   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1223   BranchInst *A_ExitInsn =
1224     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1225   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1226   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1227   if (L->contains(B_ExitBlock)) {
1228     B_ExitBlock = A_ExitInsn->getSuccessor(0);
1229     A_ExitInsn->setSuccessor(0, B_Header);
1230   } else
1231     A_ExitInsn->setSuccessor(1, B_Header);
1232
1233   //[*] Update ALoop's exit value using new exit value.
1234   ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1235   
1236   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1237   //     original loop's preheader. Add incoming PHINode values from
1238   //     ALoop's exiting block. Update BLoop header's domiantor info.
1239
1240   // Collect inverse map of Header PHINodes.
1241   DenseMap<Value *, Value *> InverseMap;
1242   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
1243          BE = L->getHeader()->end(); BI != BE; ++BI) {
1244     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1245       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1246       InverseMap[PNClone] = PN;
1247     } else
1248       break;
1249   }
1250
1251   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1252        BI != BE; ++BI) {
1253     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1254       // Remove incoming value from original preheader.
1255       PN->removeIncomingValue(Preheader);
1256
1257       // Add incoming value from A_ExitingBlock.
1258       if (PN == B_IndVar)
1259         PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1260       else { 
1261         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1262         Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1263         PN->addIncoming(V2, A_ExitingBlock);
1264       }
1265     } else
1266       break;
1267   }
1268   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1269   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1270   
1271   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1272   //     block. Remove incoming PHINode values from ALoop's exiting block.
1273   //     Add new incoming values from BLoop's incoming exiting value.
1274   //     Update BLoop exit block's dominator info..
1275   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1276   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1277        BI != BE; ++BI) {
1278     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1279       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1280                                                             B_ExitingBlock);
1281       PN->removeIncomingValue(A_ExitingBlock);
1282     } else
1283       break;
1284   }
1285
1286   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1287   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1288
1289   //[*] Split ALoop's exit edge. This creates a new block which
1290   //    serves two purposes. First one is to hold PHINode defnitions
1291   //    to ensure that ALoop's LCSSA form. Second use it to act
1292   //    as a preheader for BLoop.
1293   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1294
1295   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1296   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1297   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1298       BI != BE; ++BI) {
1299     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1300       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1301       PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
1302       newPHI->addIncoming(V1, A_ExitingBlock);
1303       A_ExitBlock->getInstList().push_front(newPHI);
1304       PN->removeIncomingValue(A_ExitBlock);
1305       PN->addIncoming(newPHI, A_ExitBlock);
1306     } else
1307       break;
1308   }
1309
1310   //[*] Eliminate split condition's inactive branch from ALoop.
1311   BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1312   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1313   BasicBlock *A_InactiveBranch = NULL;
1314   BasicBlock *A_ActiveBranch = NULL;
1315   if (SD.UseTrueBranchFirst) {
1316     A_ActiveBranch = A_BR->getSuccessor(0);
1317     A_InactiveBranch = A_BR->getSuccessor(1);
1318   } else {
1319     A_ActiveBranch = A_BR->getSuccessor(1);
1320     A_InactiveBranch = A_BR->getSuccessor(0);
1321   }
1322   A_BR->setUnconditionalDest(A_ActiveBranch);
1323   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1324
1325   //[*] Eliminate split condition's inactive branch in from BLoop.
1326   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1327   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1328   BasicBlock *B_InactiveBranch = NULL;
1329   BasicBlock *B_ActiveBranch = NULL;
1330   if (SD.UseTrueBranchFirst) {
1331     B_ActiveBranch = B_BR->getSuccessor(1);
1332     B_InactiveBranch = B_BR->getSuccessor(0);
1333   } else {
1334     B_ActiveBranch = B_BR->getSuccessor(0);
1335     B_InactiveBranch = B_BR->getSuccessor(1);
1336   }
1337   B_BR->setUnconditionalDest(B_ActiveBranch);
1338   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1339
1340   BasicBlock *A_Header = L->getHeader();
1341   if (A_ExitingBlock == A_Header)
1342     return true;
1343
1344   //[*] Move exit condition into split condition block to avoid
1345   //    executing dead loop iteration.
1346   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1347   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1348   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1349
1350   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1351                     cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement, 
1352                     ALoop);
1353
1354   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1355                     B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1356
1357   return true;
1358 }
1359
1360 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1361 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1362                                        BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1363                                        PHINode *IV, Instruction *IVAdd, Loop *LP) {
1364
1365   BasicBlock *ExitingBB = EC->getParent();
1366   Instruction *CurrentBR = CondBB->getTerminator();
1367
1368   // Move exit condition into split condition block.
1369   EC->moveBefore(CurrentBR);
1370   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1371
1372   // Move exiting block's branch into split condition block. Update its branch
1373   // destination.
1374   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1375   ExitingBR->moveBefore(CurrentBR);
1376   if (ExitingBR->getSuccessor(0) == ExitBB)
1377     ExitingBR->setSuccessor(1, ActiveBB);
1378   else
1379     ExitingBR->setSuccessor(0, ActiveBB);
1380     
1381   // Remove split condition and current split condition branch.
1382   SC->eraseFromParent();
1383   CurrentBR->eraseFromParent();
1384
1385   // Connect exiting block to split condition block.
1386   new BranchInst(CondBB, ExitingBB);
1387
1388   // Update PHINodes
1389   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1390
1391   // Fix dominator info.
1392   // ExitBB is now dominated by CondBB
1393   DT->changeImmediateDominator(ExitBB, CondBB);
1394   DF->changeImmediateDominator(ExitBB, CondBB, DT);
1395   
1396   // Basicblocks dominated by ActiveBB may have ExitingBB or
1397   // a basic block outside the loop in their DF list. If so,
1398   // replace it with CondBB.
1399   DomTreeNode *Node = DT->getNode(ActiveBB);
1400   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1401        DI != DE; ++DI) {
1402     BasicBlock *BB = DI->getBlock();
1403     DominanceFrontier::iterator BBDF = DF->find(BB);
1404     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1405     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1406     while (DomSetI != DomSetE) {
1407       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1408       ++DomSetI;
1409       BasicBlock *DFBB = *CurrentItr;
1410       if (DFBB == ExitingBB || !L->contains(DFBB)) {
1411         BBDF->second.erase(DFBB);
1412         BBDF->second.insert(CondBB);
1413       }
1414     }
1415   }
1416 }
1417
1418 /// updatePHINodes - CFG has been changed. 
1419 /// Before 
1420 ///   - ExitBB's single predecessor was Latch
1421 ///   - Latch's second successor was Header
1422 /// Now
1423 ///   - ExitBB's single predecessor was Header
1424 ///   - Latch's one and only successor was Header
1425 ///
1426 /// Update ExitBB PHINodes' to reflect this change.
1427 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
1428                                     BasicBlock *Header,
1429                                     PHINode *IV, Instruction *IVIncrement) {
1430
1431   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
1432        BI != BE; ++BI) {
1433     PHINode *PN = dyn_cast<PHINode>(BI);
1434     if (!PN)
1435       break;
1436
1437     Value *V = PN->getIncomingValueForBlock(Latch);
1438     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1439       // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode 
1440       // (i.e. PN :)). 
1441       // The second use is in Header and it is new incoming value for PN.
1442       PHINode *U1 = NULL;
1443       PHINode *U2 = NULL;
1444       Value *NewV = NULL;
1445       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
1446            UI != E; ++UI) {
1447         if (!U1)
1448           U1 = cast<PHINode>(*UI);
1449         else if (!U2)
1450           U2 = cast<PHINode>(*UI);
1451         else
1452           assert ( 0 && "Unexpected third use of this PHINode");
1453       }
1454       assert (U1 && U2 && "Unable to find two uses");
1455       
1456       if (U1->getParent() == Header) 
1457         NewV = U1;
1458       else
1459         NewV = U2;
1460       PN->addIncoming(NewV, Header);
1461
1462     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1463       // If this instruction is IVIncrement then IV is new incoming value 
1464       // from header otherwise this instruction must be incoming value from 
1465       // header because loop is in LCSSA form.
1466       if (PHI == IVIncrement)
1467         PN->addIncoming(IV, Header);
1468       else
1469         PN->addIncoming(V, Header);
1470     } else
1471       // Otherwise this is an incoming value from header because loop is in 
1472       // LCSSA form.
1473       PN->addIncoming(V, Header);
1474     
1475     // Remove incoming value from Latch.
1476     PN->removeIncomingValue(Latch);
1477   }
1478 }