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