LLVM API Documentation

IndVarSimplify.cpp

Go to the documentation of this file.
00001 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This transformation analyzes and transforms the induction variables (and
00011 // computations derived from them) into simpler forms suitable for subsequent
00012 // analysis and transformation.
00013 //
00014 // This transformation makes the following changes to each loop with an
00015 // identifiable induction variable:
00016 //   1. All loops are transformed to have a SINGLE canonical induction variable
00017 //      which starts at zero and steps by one.
00018 //   2. The canonical induction variable is guaranteed to be the first PHI node
00019 //      in the loop header block.
00020 //   3. Any pointer arithmetic recurrences are raised to use array subscripts.
00021 //
00022 // If the trip count of a loop is computable, this pass also makes the following
00023 // changes:
00024 //   1. The exit condition for the loop is canonicalized to compare the
00025 //      induction value against the exit value.  This turns loops like:
00026 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
00027 //   2. Any use outside of the loop of an expression derived from the indvar
00028 //      is changed to compute the derived value outside of the loop, eliminating
00029 //      the dependence on the exit value of the induction variable.  If the only
00030 //      purpose of the loop is to compute the exit value of some derived
00031 //      expression, this transformation will make the loop dead.
00032 //
00033 // This transformation should be followed by strength reduction after all of the
00034 // desired loop transformations have been performed.  Additionally, on targets
00035 // where it is profitable, the loop could be transformed to count down to zero
00036 // (the "do loop" optimization).
00037 //
00038 //===----------------------------------------------------------------------===//
00039 
00040 #define DEBUG_TYPE "indvars"
00041 #include "llvm/Transforms/Scalar.h"
00042 #include "llvm/BasicBlock.h"
00043 #include "llvm/Constants.h"
00044 #include "llvm/Instructions.h"
00045 #include "llvm/Type.h"
00046 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00047 #include "llvm/Analysis/LoopInfo.h"
00048 #include "llvm/Analysis/LoopPass.h"
00049 #include "llvm/Support/CFG.h"
00050 #include "llvm/Support/Compiler.h"
00051 #include "llvm/Support/Debug.h"
00052 #include "llvm/Support/GetElementPtrTypeIterator.h"
00053 #include "llvm/Transforms/Utils/Local.h"
00054 #include "llvm/Support/CommandLine.h"
00055 #include "llvm/ADT/SmallVector.h"
00056 #include "llvm/ADT/SmallPtrSet.h"
00057 #include "llvm/ADT/Statistic.h"
00058 using namespace llvm;
00059 
00060 STATISTIC(NumRemoved , "Number of aux indvars removed");
00061 STATISTIC(NumPointer , "Number of pointer indvars promoted");
00062 STATISTIC(NumInserted, "Number of canonical indvars added");
00063 STATISTIC(NumReplaced, "Number of exit values replaced");
00064 STATISTIC(NumLFTR    , "Number of loop exit tests replaced");
00065 
00066 namespace {
00067   class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
00068     LoopInfo        *LI;
00069     ScalarEvolution *SE;
00070     bool Changed;
00071   public:
00072 
00073    static char ID; // Pass identification, replacement for typeid
00074    IndVarSimplify() : LoopPass(&ID) {}
00075 
00076    bool runOnLoop(Loop *L, LPPassManager &LPM);
00077    bool doInitialization(Loop *L, LPPassManager &LPM);
00078    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00079      AU.addRequired<ScalarEvolution>();
00080      AU.addRequiredID(LCSSAID);
00081      AU.addRequiredID(LoopSimplifyID);
00082      AU.addRequired<LoopInfo>();
00083      AU.addPreservedID(LoopSimplifyID);
00084      AU.addPreservedID(LCSSAID);
00085      AU.setPreservesCFG();
00086    }
00087 
00088   private:
00089 
00090     void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
00091                                     SmallPtrSet<Instruction*, 16> &DeadInsts);
00092     Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
00093                                            SCEVExpander &RW);
00094     void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
00095 
00096     void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
00097 
00098     void OptimizeCanonicalIVType(Loop *L);
00099     void HandleFloatingPointIV(Loop *L, PHINode *PH, 
00100                                SmallPtrSet<Instruction*, 16> &DeadInsts);
00101   };
00102 }
00103 
00104 char IndVarSimplify::ID = 0;
00105 static RegisterPass<IndVarSimplify>
00106 X("indvars", "Canonicalize Induction Variables");
00107 
00108 Pass *llvm::createIndVarSimplifyPass() {
00109   return new IndVarSimplify();
00110 }
00111 
00112 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
00113 /// specified set are trivially dead, delete them and see if this makes any of
00114 /// their operands subsequently dead.
00115 void IndVarSimplify::
00116 DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
00117   while (!Insts.empty()) {
00118     Instruction *I = *Insts.begin();
00119     Insts.erase(I);
00120     if (isInstructionTriviallyDead(I)) {
00121       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00122         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
00123           Insts.insert(U);
00124       SE->deleteValueFromRecords(I);
00125       DOUT << "INDVARS: Deleting: " << *I;
00126       I->eraseFromParent();
00127       Changed = true;
00128     }
00129   }
00130 }
00131 
00132 
00133 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
00134 /// recurrence.  If so, change it into an integer recurrence, permitting
00135 /// analysis by the SCEV routines.
00136 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
00137                                                 BasicBlock *Preheader,
00138                                      SmallPtrSet<Instruction*, 16> &DeadInsts) {
00139   assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
00140   unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
00141   unsigned BackedgeIdx = PreheaderIdx^1;
00142   if (GetElementPtrInst *GEPI =
00143           dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
00144     if (GEPI->getOperand(0) == PN) {
00145       assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
00146       DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
00147       
00148       // Okay, we found a pointer recurrence.  Transform this pointer
00149       // recurrence into an integer recurrence.  Compute the value that gets
00150       // added to the pointer at every iteration.
00151       Value *AddedVal = GEPI->getOperand(1);
00152 
00153       // Insert a new integer PHI node into the top of the block.
00154       PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
00155                                         PN->getName()+".rec", PN);
00156       NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
00157 
00158       // Create the new add instruction.
00159       Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
00160                                                 GEPI->getName()+".rec", GEPI);
00161       NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
00162 
00163       // Update the existing GEP to use the recurrence.
00164       GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
00165 
00166       // Update the GEP to use the new recurrence we just inserted.
00167       GEPI->setOperand(1, NewAdd);
00168 
00169       // If the incoming value is a constant expr GEP, try peeling out the array
00170       // 0 index if possible to make things simpler.
00171       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
00172         if (CE->getOpcode() == Instruction::GetElementPtr) {
00173           unsigned NumOps = CE->getNumOperands();
00174           assert(NumOps > 1 && "CE folding didn't work!");
00175           if (CE->getOperand(NumOps-1)->isNullValue()) {
00176             // Check to make sure the last index really is an array index.
00177             gep_type_iterator GTI = gep_type_begin(CE);
00178             for (unsigned i = 1, e = CE->getNumOperands()-1;
00179                  i != e; ++i, ++GTI)
00180               /*empty*/;
00181             if (isa<SequentialType>(*GTI)) {
00182               // Pull the last index out of the constant expr GEP.
00183               SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
00184               Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
00185                                                              &CEIdxs[0],
00186                                                              CEIdxs.size());
00187               Value *Idx[2];
00188               Idx[0] = Constant::getNullValue(Type::Int32Ty);
00189               Idx[1] = NewAdd;
00190               GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
00191                   NCE, Idx, Idx + 2, 
00192                   GEPI->getName(), GEPI);
00193               SE->deleteValueFromRecords(GEPI);
00194               GEPI->replaceAllUsesWith(NGEPI);
00195               GEPI->eraseFromParent();
00196               GEPI = NGEPI;
00197             }
00198           }
00199         }
00200 
00201 
00202       // Finally, if there are any other users of the PHI node, we must
00203       // insert a new GEP instruction that uses the pre-incremented version
00204       // of the induction amount.
00205       if (!PN->use_empty()) {
00206         BasicBlock::iterator InsertPos = PN; ++InsertPos;
00207         while (isa<PHINode>(InsertPos)) ++InsertPos;
00208         Value *PreInc =
00209           GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
00210                                     NewPhi, "", InsertPos);
00211         PreInc->takeName(PN);
00212         PN->replaceAllUsesWith(PreInc);
00213       }
00214 
00215       // Delete the old PHI for sure, and the GEP if its otherwise unused.
00216       DeadInsts.insert(PN);
00217 
00218       ++NumPointer;
00219       Changed = true;
00220     }
00221 }
00222 
00223 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
00224 /// loop to be a canonical != comparison against the incremented loop induction
00225 /// variable.  This pass is able to rewrite the exit tests of any loop where the
00226 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
00227 /// is actually a much broader range than just linear tests.
00228 ///
00229 /// This method returns a "potentially dead" instruction whose computation chain
00230 /// should be deleted when convenient.
00231 Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
00232                                                        SCEV *IterationCount,
00233                                                        SCEVExpander &RW) {
00234   // Find the exit block for the loop.  We can currently only handle loops with
00235   // a single exit.
00236   SmallVector<BasicBlock*, 8> ExitBlocks;
00237   L->getExitBlocks(ExitBlocks);
00238   if (ExitBlocks.size() != 1) return 0;
00239   BasicBlock *ExitBlock = ExitBlocks[0];
00240 
00241   // Make sure there is only one predecessor block in the loop.
00242   BasicBlock *ExitingBlock = 0;
00243   for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
00244        PI != PE; ++PI)
00245     if (L->contains(*PI)) {
00246       if (ExitingBlock == 0)
00247         ExitingBlock = *PI;
00248       else
00249         return 0;  // Multiple exits from loop to this block.
00250     }
00251   assert(ExitingBlock && "Loop info is broken");
00252 
00253   if (!isa<BranchInst>(ExitingBlock->getTerminator()))
00254     return 0;  // Can't rewrite non-branch yet
00255   BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
00256   assert(BI->isConditional() && "Must be conditional to be part of loop!");
00257 
00258   Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
00259   
00260   // If the exiting block is not the same as the backedge block, we must compare
00261   // against the preincremented value, otherwise we prefer to compare against
00262   // the post-incremented value.
00263   BasicBlock *Header = L->getHeader();
00264   pred_iterator HPI = pred_begin(Header);
00265   assert(HPI != pred_end(Header) && "Loop with zero preds???");
00266   if (!L->contains(*HPI)) ++HPI;
00267   assert(HPI != pred_end(Header) && L->contains(*HPI) &&
00268          "No backedge in loop?");
00269 
00270   SCEVHandle TripCount = IterationCount;
00271   Value *IndVar;
00272   if (*HPI == ExitingBlock) {
00273     // The IterationCount expression contains the number of times that the
00274     // backedge actually branches to the loop header.  This is one less than the
00275     // number of times the loop executes, so add one to it.
00276     ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
00277     TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
00278     IndVar = L->getCanonicalInductionVariableIncrement();
00279   } else {
00280     // We have to use the preincremented value...
00281     IndVar = L->getCanonicalInductionVariable();
00282   }
00283   
00284   DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
00285        << "  IndVar = " << *IndVar << "\n";
00286 
00287   // Expand the code for the iteration count into the preheader of the loop.
00288   BasicBlock *Preheader = L->getLoopPreheader();
00289   Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
00290 
00291   // Insert a new icmp_ne or icmp_eq instruction before the branch.
00292   ICmpInst::Predicate Opcode;
00293   if (L->contains(BI->getSuccessor(0)))
00294     Opcode = ICmpInst::ICMP_NE;
00295   else
00296     Opcode = ICmpInst::ICMP_EQ;
00297 
00298   Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
00299   BI->setCondition(Cond);
00300   ++NumLFTR;
00301   Changed = true;
00302   return PotentiallyDeadInst;
00303 }
00304 
00305 
00306 /// RewriteLoopExitValues - Check to see if this loop has a computable
00307 /// loop-invariant execution count.  If so, this means that we can compute the
00308 /// final value of any expressions that are recurrent in the loop, and
00309 /// substitute the exit values from the loop into any instructions outside of
00310 /// the loop that use the final values of the current expressions.
00311 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
00312   BasicBlock *Preheader = L->getLoopPreheader();
00313 
00314   // Scan all of the instructions in the loop, looking at those that have
00315   // extra-loop users and which are recurrences.
00316   SCEVExpander Rewriter(*SE, *LI);
00317 
00318   // We insert the code into the preheader of the loop if the loop contains
00319   // multiple exit blocks, or in the exit block if there is exactly one.
00320   BasicBlock *BlockToInsertInto;
00321   SmallVector<BasicBlock*, 8> ExitBlocks;
00322   L->getUniqueExitBlocks(ExitBlocks);
00323   if (ExitBlocks.size() == 1)
00324     BlockToInsertInto = ExitBlocks[0];
00325   else
00326     BlockToInsertInto = Preheader;
00327   BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
00328 
00329   bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
00330 
00331   SmallPtrSet<Instruction*, 16> InstructionsToDelete;
00332   std::map<Instruction*, Value*> ExitValues;
00333 
00334   // Find all values that are computed inside the loop, but used outside of it.
00335   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
00336   // the exit blocks of the loop to find them.
00337   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00338     BasicBlock *ExitBB = ExitBlocks[i];
00339     
00340     // If there are no PHI nodes in this exit block, then no values defined
00341     // inside the loop are used on this path, skip it.
00342     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
00343     if (!PN) continue;
00344     
00345     unsigned NumPreds = PN->getNumIncomingValues();
00346     
00347     // Iterate over all of the PHI nodes.
00348     BasicBlock::iterator BBI = ExitBB->begin();
00349     while ((PN = dyn_cast<PHINode>(BBI++))) {
00350       
00351       // Iterate over all of the values in all the PHI nodes.
00352       for (unsigned i = 0; i != NumPreds; ++i) {
00353         // If the value being merged in is not integer or is not defined
00354         // in the loop, skip it.
00355         Value *InVal = PN->getIncomingValue(i);
00356         if (!isa<Instruction>(InVal) ||
00357             // SCEV only supports integer expressions for now.
00358             !isa<IntegerType>(InVal->getType()))
00359           continue;
00360 
00361         // If this pred is for a subloop, not L itself, skip it.
00362         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 
00363           continue; // The Block is in a subloop, skip it.
00364 
00365         // Check that InVal is defined in the loop.
00366         Instruction *Inst = cast<Instruction>(InVal);
00367         if (!L->contains(Inst->getParent()))
00368           continue;
00369         
00370         // We require that this value either have a computable evolution or that
00371         // the loop have a constant iteration count.  In the case where the loop
00372         // has a constant iteration count, we can sometimes force evaluation of
00373         // the exit value through brute force.
00374         SCEVHandle SH = SE->getSCEV(Inst);
00375         if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
00376           continue;          // Cannot get exit evolution for the loop value.
00377         
00378         // Okay, this instruction has a user outside of the current loop
00379         // and varies predictably *inside* the loop.  Evaluate the value it
00380         // contains when the loop exits, if possible.
00381         SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
00382         if (isa<SCEVCouldNotCompute>(ExitValue) ||
00383             !ExitValue->isLoopInvariant(L))
00384           continue;
00385 
00386         Changed = true;
00387         ++NumReplaced;
00388         
00389         // See if we already computed the exit value for the instruction, if so,
00390         // just reuse it.
00391         Value *&ExitVal = ExitValues[Inst];
00392         if (!ExitVal)
00393           ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
00394         
00395         DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
00396              << "  LoopVal = " << *Inst << "\n";
00397 
00398         PN->setIncomingValue(i, ExitVal);
00399         
00400         // If this instruction is dead now, schedule it to be removed.
00401         if (Inst->use_empty())
00402           InstructionsToDelete.insert(Inst);
00403         
00404         // See if this is a single-entry LCSSA PHI node.  If so, we can (and
00405         // have to) remove
00406         // the PHI entirely.  This is safe, because the NewVal won't be variant
00407         // in the loop, so we don't need an LCSSA phi node anymore.
00408         if (NumPreds == 1) {
00409           SE->deleteValueFromRecords(PN);
00410           PN->replaceAllUsesWith(ExitVal);
00411           PN->eraseFromParent();
00412           break;
00413         }
00414       }
00415     }
00416   }
00417   
00418   DeleteTriviallyDeadInstructions(InstructionsToDelete);
00419 }
00420 
00421 bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
00422 
00423   Changed = false;
00424   // First step.  Check to see if there are any trivial GEP pointer recurrences.
00425   // If there are, change them into integer recurrences, permitting analysis by
00426   // the SCEV routines.
00427   //
00428   BasicBlock *Header    = L->getHeader();
00429   BasicBlock *Preheader = L->getLoopPreheader();
00430   SE = &LPM.getAnalysis<ScalarEvolution>();
00431 
00432   SmallPtrSet<Instruction*, 16> DeadInsts;
00433   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00434     PHINode *PN = cast<PHINode>(I);
00435     if (isa<PointerType>(PN->getType()))
00436       EliminatePointerRecurrence(PN, Preheader, DeadInsts);
00437     else
00438       HandleFloatingPointIV(L, PN, DeadInsts);
00439   }
00440 
00441   if (!DeadInsts.empty())
00442     DeleteTriviallyDeadInstructions(DeadInsts);
00443 
00444   return Changed;
00445 }
00446 
00447 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
00448 
00449   LI = &getAnalysis<LoopInfo>();
00450   SE = &getAnalysis<ScalarEvolution>();
00451 
00452   Changed = false;
00453   BasicBlock *Header    = L->getHeader();
00454   SmallPtrSet<Instruction*, 16> DeadInsts;
00455   
00456   // Verify the input to the pass in already in LCSSA form.
00457   assert(L->isLCSSAForm());
00458 
00459   // Check to see if this loop has a computable loop-invariant execution count.
00460   // If so, this means that we can compute the final value of any expressions
00461   // that are recurrent in the loop, and substitute the exit values from the
00462   // loop into any instructions outside of the loop that use the final values of
00463   // the current expressions.
00464   //
00465   SCEVHandle IterationCount = SE->getIterationCount(L);
00466   if (!isa<SCEVCouldNotCompute>(IterationCount))
00467     RewriteLoopExitValues(L, IterationCount);
00468 
00469   // Next, analyze all of the induction variables in the loop, canonicalizing
00470   // auxillary induction variables.
00471   std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
00472 
00473   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00474     PHINode *PN = cast<PHINode>(I);
00475     if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
00476       SCEVHandle SCEV = SE->getSCEV(PN);
00477       if (SCEV->hasComputableLoopEvolution(L))
00478         // FIXME: It is an extremely bad idea to indvar substitute anything more
00479         // complex than affine induction variables.  Doing so will put expensive
00480         // polynomial evaluations inside of the loop, and the str reduction pass
00481         // currently can only reduce affine polynomials.  For now just disable
00482         // indvar subst on anything more complex than an affine addrec.
00483         if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
00484           if (AR->isAffine())
00485             IndVars.push_back(std::make_pair(PN, SCEV));
00486     }
00487   }
00488 
00489   // If there are no induction variables in the loop, there is nothing more to
00490   // do.
00491   if (IndVars.empty()) {
00492     // Actually, if we know how many times the loop iterates, lets insert a
00493     // canonical induction variable to help subsequent passes.
00494     if (!isa<SCEVCouldNotCompute>(IterationCount)) {
00495       SCEVExpander Rewriter(*SE, *LI);
00496       Rewriter.getOrInsertCanonicalInductionVariable(L,
00497                                                      IterationCount->getType());
00498       if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
00499                                                      Rewriter)) {
00500         SmallPtrSet<Instruction*, 16> InstructionsToDelete;
00501         InstructionsToDelete.insert(I);
00502         DeleteTriviallyDeadInstructions(InstructionsToDelete);
00503       }
00504     }
00505     return Changed;
00506   }
00507 
00508   // Compute the type of the largest recurrence expression.
00509   //
00510   const Type *LargestType = IndVars[0].first->getType();
00511   bool DifferingSizes = false;
00512   for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
00513     const Type *Ty = IndVars[i].first->getType();
00514     DifferingSizes |= 
00515       Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
00516     if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
00517       LargestType = Ty;
00518   }
00519 
00520   // Create a rewriter object which we'll use to transform the code with.
00521   SCEVExpander Rewriter(*SE, *LI);
00522 
00523   // Now that we know the largest of of the induction variables in this loop,
00524   // insert a canonical induction variable of the largest size.
00525   Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
00526   ++NumInserted;
00527   Changed = true;
00528   DOUT << "INDVARS: New CanIV: " << *IndVar;
00529 
00530   if (!isa<SCEVCouldNotCompute>(IterationCount)) {
00531     IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
00532     if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
00533       DeadInsts.insert(DI);
00534   }
00535 
00536   // Now that we have a canonical induction variable, we can rewrite any
00537   // recurrences in terms of the induction variable.  Start with the auxillary
00538   // induction variables, and recursively rewrite any of their uses.
00539   BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
00540 
00541   // If there were induction variables of other sizes, cast the primary
00542   // induction variable to the right size for them, avoiding the need for the
00543   // code evaluation methods to insert induction variables of different sizes.
00544   if (DifferingSizes) {
00545     SmallVector<unsigned,4> InsertedSizes;
00546     InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
00547     for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
00548       unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
00549       if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
00550           == InsertedSizes.end()) {
00551         PHINode *PN = IndVars[i].first;
00552         InsertedSizes.push_back(ithSize);
00553         Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
00554                                          InsertPt);
00555         Rewriter.addInsertedValue(New, SE->getSCEV(New));
00556         DOUT << "INDVARS: Made trunc IV for " << *PN
00557              << "   NewVal = " << *New << "\n";
00558       }
00559     }
00560   }
00561 
00562   // Rewrite all induction variables in terms of the canonical induction
00563   // variable.
00564   while (!IndVars.empty()) {
00565     PHINode *PN = IndVars.back().first;
00566     Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
00567     DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
00568          << "   into = " << *NewVal << "\n";
00569     NewVal->takeName(PN);
00570 
00571     // Replace the old PHI Node with the inserted computation.
00572     PN->replaceAllUsesWith(NewVal);
00573     DeadInsts.insert(PN);
00574     IndVars.pop_back();
00575     ++NumRemoved;
00576     Changed = true;
00577   }
00578 
00579 #if 0
00580   // Now replace all derived expressions in the loop body with simpler
00581   // expressions.
00582   for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
00583        I != E; ++I) {
00584     BasicBlock *BB = *I;
00585     if (LI->getLoopFor(BB) == L) {  // Not in a subloop...
00586       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00587         if (I->getType()->isInteger() &&      // Is an integer instruction
00588             !I->use_empty() &&
00589             !Rewriter.isInsertedInstruction(I)) {
00590           SCEVHandle SH = SE->getSCEV(I);
00591           Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
00592           if (V != I) {
00593             if (isa<Instruction>(V))
00594               V->takeName(I);
00595             I->replaceAllUsesWith(V);
00596             DeadInsts.insert(I);
00597             ++NumRemoved;
00598             Changed = true;
00599           }
00600         }
00601     }
00602   }
00603 #endif
00604 
00605   DeleteTriviallyDeadInstructions(DeadInsts);
00606   OptimizeCanonicalIVType(L);
00607   assert(L->isLCSSAForm());
00608   return Changed;
00609 }
00610 
00611 /// OptimizeCanonicalIVType - If loop induction variable is always
00612 /// sign or zero extended then extend the type of the induction 
00613 /// variable.
00614 void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
00615   PHINode *PH = L->getCanonicalInductionVariable();
00616   if (!PH) return;
00617   
00618   // Check loop iteration count.
00619   SCEVHandle IC = SE->getIterationCount(L);
00620   if (isa<SCEVCouldNotCompute>(IC)) return;
00621   SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
00622   if (!IterationCount) return;
00623 
00624   unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
00625   unsigned BackEdge     = IncomingEdge^1;
00626   
00627   // Check IV uses. If all IV uses are either SEXT or ZEXT (except
00628   // IV increment instruction) then this IV is suitable for this
00629   // transformation.
00630   bool isSEXT = false;
00631   BinaryOperator *Incr = NULL;
00632   const Type *NewType = NULL;
00633   for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end(); 
00634       UI != UE; ++UI) {
00635     const Type *CandidateType = NULL;
00636     if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
00637       CandidateType = ZI->getDestTy();
00638     else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
00639       CandidateType = SI->getDestTy();
00640       isSEXT = true;
00641     }
00642     else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
00643       // Validate IV increment instruction.
00644       if (PH->getIncomingValue(BackEdge) == Incr)
00645         continue;
00646     }
00647     if (!CandidateType) {
00648       NewType = NULL;
00649       break;
00650     }
00651     if (!NewType)
00652       NewType = CandidateType;
00653     else if (NewType != CandidateType) {
00654       NewType = NULL;
00655       break;
00656     }
00657   }
00658 
00659   // IV uses are not suitable then avoid this transformation.
00660   if (!NewType || !Incr)
00661     return;
00662 
00663   // IV increment instruction has two uses, one is loop exit condition
00664   // and second is the IV (phi node) itself.
00665   ICmpInst *Exit = NULL;
00666   for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
00667       II != IE; ++II) {
00668     if (PH == *II)  continue;
00669     Exit = dyn_cast<ICmpInst>(*II);
00670     break;
00671   }
00672   if (!Exit) return;
00673   ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
00674   if (!EV) 
00675     EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
00676   if (!EV) return;
00677 
00678   // Check iteration count max value to avoid loops that wrap around IV.
00679   APInt ICount = IterationCount->getValue()->getValue();
00680   if (ICount.isNegative()) return;
00681   uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
00682   APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
00683   if (ICount.getZExtValue() > Max.getZExtValue())  return;                         
00684 
00685   // Extend IV type.
00686 
00687   SCEVExpander Rewriter(*SE, *LI);
00688   Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
00689   PHINode *NewPH = cast<PHINode>(NewIV);
00690   Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
00691 
00692   // Replace all SEXT or ZEXT uses.
00693   SmallVector<Instruction *, 4> PHUses;
00694   for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end(); 
00695       UI != UE; ++UI) {
00696       Instruction *I = cast<Instruction>(UI);
00697       PHUses.push_back(I);
00698   }
00699   while (!PHUses.empty()){
00700     Instruction *Use = PHUses.back(); PHUses.pop_back();
00701     if (Incr == Use) continue;
00702     
00703     SE->deleteValueFromRecords(Use);
00704     Use->replaceAllUsesWith(NewIV);
00705     Use->eraseFromParent();
00706   }
00707 
00708   // Replace exit condition.
00709   ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
00710   Instruction *NE = new ICmpInst(Exit->getPredicate(),
00711                                  NewIncr, NEV, "new.exit", 
00712                                  Exit->getParent()->getTerminator());
00713   SE->deleteValueFromRecords(Exit);
00714   Exit->replaceAllUsesWith(NE);
00715   Exit->eraseFromParent();
00716   
00717   // Remove old IV and increment instructions.
00718   SE->deleteValueFromRecords(PH);
00719   PH->removeIncomingValue((unsigned)0);
00720   PH->removeIncomingValue((unsigned)0);
00721   SE->deleteValueFromRecords(Incr);
00722   Incr->eraseFromParent();
00723 }
00724 
00725 /// Return true if it is OK to use SIToFPInst for an inducation variable
00726 /// with given inital and exit values.
00727 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
00728                           uint64_t intIV, uint64_t intEV) {
00729 
00730   if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative()) 
00731     return true;
00732 
00733   // If the iteration range can be handled by SIToFPInst then use it.
00734   APInt Max = APInt::getSignedMaxValue(32);
00735   if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
00736     return true;
00737   
00738   return false;
00739 }
00740 
00741 /// convertToInt - Convert APF to an integer, if possible.
00742 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
00743 
00744   bool isExact = false;
00745   if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
00746     return false;
00747   if (APF.convertToInteger(intVal, 32, APF.isNegative(), 
00748                            APFloat::rmTowardZero, &isExact)
00749       != APFloat::opOK)
00750     return false;
00751   if (!isExact) 
00752     return false;
00753   return true;
00754 
00755 }
00756 
00757 /// HandleFloatingPointIV - If the loop has floating induction variable
00758 /// then insert corresponding integer induction variable if possible.
00759 /// For example,
00760 /// for(double i = 0; i < 10000; ++i)
00761 ///   bar(i)
00762 /// is converted into
00763 /// for(int i = 0; i < 10000; ++i)
00764 ///   bar((double)i);
00765 ///
00766 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH, 
00767                                    SmallPtrSet<Instruction*, 16> &DeadInsts) {
00768 
00769   unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
00770   unsigned BackEdge     = IncomingEdge^1;
00771   
00772   // Check incoming value.
00773   ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
00774   if (!InitValue) return;
00775   uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
00776   if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
00777     return;
00778 
00779   // Check IV increment. Reject this PH if increement operation is not
00780   // an add or increment value can not be represented by an integer.
00781   BinaryOperator *Incr = 
00782     dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
00783   if (!Incr) return;
00784   if (Incr->getOpcode() != Instruction::Add) return;
00785   ConstantFP *IncrValue = NULL;
00786   unsigned IncrVIndex = 1;
00787   if (Incr->getOperand(1) == PH)
00788     IncrVIndex = 0;
00789   IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
00790   if (!IncrValue) return;
00791   uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
00792   if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
00793     return;
00794   
00795   // Check Incr uses. One user is PH and the other users is exit condition used
00796   // by the conditional terminator.
00797   Value::use_iterator IncrUse = Incr->use_begin();
00798   Instruction *U1 = cast<Instruction>(IncrUse++);
00799   if (IncrUse == Incr->use_end()) return;
00800   Instruction *U2 = cast<Instruction>(IncrUse++);
00801   if (IncrUse != Incr->use_end()) return;
00802   
00803   // Find exit condition.
00804   FCmpInst *EC = dyn_cast<FCmpInst>(U1);
00805   if (!EC)
00806     EC = dyn_cast<FCmpInst>(U2);
00807   if (!EC) return;
00808 
00809   if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
00810     if (!BI->isConditional()) return;
00811     if (BI->getCondition() != EC) return;
00812   }
00813 
00814   // Find exit value. If exit value can not be represented as an interger then
00815   // do not handle this floating point PH.
00816   ConstantFP *EV = NULL;
00817   unsigned EVIndex = 1;
00818   if (EC->getOperand(1) == Incr)
00819     EVIndex = 0;
00820   EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
00821   if (!EV) return;
00822   uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
00823   if (!convertToInt(EV->getValueAPF(), &intEV))
00824     return;
00825   
00826   // Find new predicate for integer comparison.
00827   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
00828   switch (EC->getPredicate()) {
00829   case CmpInst::FCMP_OEQ:
00830   case CmpInst::FCMP_UEQ:
00831     NewPred = CmpInst::ICMP_EQ;
00832     break;
00833   case CmpInst::FCMP_OGT:
00834   case CmpInst::FCMP_UGT:
00835     NewPred = CmpInst::ICMP_UGT;
00836     break;
00837   case CmpInst::FCMP_OGE:
00838   case CmpInst::FCMP_UGE:
00839     NewPred = CmpInst::ICMP_UGE;
00840     break;
00841   case CmpInst::FCMP_OLT:
00842   case CmpInst::FCMP_ULT:
00843     NewPred = CmpInst::ICMP_ULT;
00844     break;
00845   case CmpInst::FCMP_OLE:
00846   case CmpInst::FCMP_ULE:
00847     NewPred = CmpInst::ICMP_ULE;
00848     break;
00849   default:
00850     break;
00851   }
00852   if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
00853   
00854   // Insert new integer induction variable.
00855   PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
00856                                     PH->getName()+".int", PH);
00857   NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
00858                       PH->getIncomingBlock(IncomingEdge));
00859 
00860   Value *NewAdd = BinaryOperator::CreateAdd(NewPHI, 
00861                                             ConstantInt::get(Type::Int32Ty, 
00862                                                              newIncrValue),
00863                                             Incr->getName()+".int", Incr);
00864   NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
00865 
00866   ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
00867   Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
00868   Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
00869   ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(), 
00870                                  EC->getParent()->getTerminator());
00871   
00872   // Delete old, floating point, exit comparision instruction.
00873   EC->replaceAllUsesWith(NewEC);
00874   DeadInsts.insert(EC);
00875   
00876   // Delete old, floating point, increment instruction.
00877   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
00878   DeadInsts.insert(Incr);
00879   
00880   // Replace floating induction variable. Give SIToFPInst preference over
00881   // UIToFPInst because it is faster on platforms that are widely used.
00882   if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
00883     SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv", 
00884                                       PH->getParent()->getFirstNonPHI());
00885     PH->replaceAllUsesWith(Conv);
00886   } else {
00887     UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv", 
00888                                       PH->getParent()->getFirstNonPHI());
00889     PH->replaceAllUsesWith(Conv);
00890   }
00891   DeadInsts.insert(PH);
00892 }
00893