IndVarSimplify.cpp revision a25502acd7c0d56cbd20da37f25830d81be834c5
16148c02591bd83da7b957589c4bbf6f9720d503fChris Lattner//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
3b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//                     The LLVM Compiler Infrastructure
4b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
5b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell// This file was developed by the LLVM research group and is distributed under
6b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell// the University of Illinois Open Source License. See LICENSE.TXT for details.
7b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
8b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//===----------------------------------------------------------------------===//
96148c02591bd83da7b957589c4bbf6f9720d503fChris Lattner//
1040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// This transformation analyzes and transforms the induction variables (and
1140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// computations derived from them) into simpler forms suitable for subsequent
1240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// analysis and transformation.
1340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//
1440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// This transformation make the following changes to each loop with an
1540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// identifiable induction variable:
1640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//   1. All loops are transformed to have a SINGLE canonical induction variable
1740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//      which starts at zero and steps by one.
1840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//   2. The canonical induction variable is guaranteed to be the first PHI node
1940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//      in the loop header block.
2040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//   3. Any pointer arithmetic recurrences are raised to use array subscripts.
2140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//
2240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// If the trip count of a loop is computable, this pass also makes the following
2340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// changes:
2440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//   1. The exit condition for the loop is canonicalized to compare the
2540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//      induction value against the exit value.  This turns loops like:
2640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
2740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//   2. Any use outside of the loop of an expression derived from the indvar
2840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//      is changed to compute the derived value outside of the loop, eliminating
2940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//      the dependence on the exit value of the induction variable.  If the only
3040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//      purpose of the loop is to compute the exit value of some derived
3140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//      expression, this transformation will make the loop dead.
3240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner//
3340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// This transformation should be followed by strength reduction after all of the
3440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// desired loop transformations have been performed.  Additionally, on targets
3540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// where it is profitable, the loop could be transformed to count down to zero
3640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner// (the "do loop" optimization).
376148c02591bd83da7b957589c4bbf6f9720d503fChris Lattner//
386148c02591bd83da7b957589c4bbf6f9720d503fChris Lattner//===----------------------------------------------------------------------===//
396148c02591bd83da7b957589c4bbf6f9720d503fChris Lattner
40022103b3f33febb7e54b8fdf2c9bc461eea78cbaChris Lattner#include "llvm/Transforms/Scalar.h"
4140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner#include "llvm/BasicBlock.h"
4259fdaeeae8f183e18bb6ad5c382ca23e28e6aaf6Chris Lattner#include "llvm/Constants.h"
4318b3c97bc773b24a66eb779e85da1820b0f16b31Chris Lattner#include "llvm/Instructions.h"
4440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner#include "llvm/Type.h"
4559fdaeeae8f183e18bb6ad5c382ca23e28e6aaf6Chris Lattner#include "llvm/Analysis/ScalarEvolutionExpressions.h"
4647df12d80db90e125e9f2ff764286ee11665476dJohn Criswell#include "llvm/Analysis/LoopInfo.h"
47455889aa79e3463a4b0f2161e3d9d72a683268b6Chris Lattner#include "llvm/Support/CFG.h"
4847df12d80db90e125e9f2ff764286ee11665476dJohn Criswell#include "llvm/Transforms/Utils/Local.h"
4940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner#include "Support/CommandLine.h"
50a92f696b74a99325026ebbdbffd2a44317e0c10bChris Lattner#include "Support/Statistic.h"
5147df12d80db90e125e9f2ff764286ee11665476dJohn Criswellusing namespace llvm;
52d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
535e76140536ba66fadeced1cd892f79616f407e3cChris Lattnernamespace {
544a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  /// SCEVExpander - This class uses information about analyze scalars to
554a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  /// rewrite expressions in canonical form.
564a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  ///
574a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  /// Clients should create an instance of this class when rewriting is needed,
584a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  /// and destroying it when finished to allow the release of the associated
594a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  /// memory.
604a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  struct SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
614a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    ScalarEvolution &SE;
624a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    LoopInfo &LI;
634a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    std::map<SCEVHandle, Value*> InsertedExpressions;
644a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    std::set<Instruction*> InsertedInstructions;
654a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
664a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Instruction *InsertPt;
674a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
684a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    friend class SCEVVisitor<SCEVExpander, Value*>;
694a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  public:
704a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    SCEVExpander(ScalarEvolution &se, LoopInfo &li) : SE(se), LI(li) {}
714a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
724a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// isInsertedInstruction - Return true if the specified instruction was
734a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// inserted by the code rewriter.  If so, the client should not modify the
744a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// instruction.
754a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    bool isInsertedInstruction(Instruction *I) const {
764a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return InsertedInstructions.count(I);
774a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
784a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
794a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// getOrInsertCanonicalInductionVariable - This method returns the
804a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// canonical induction variable of the specified type for the specified
814a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// loop (inserting one if there is none).  A canonical induction variable
824a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// starts at zero and steps by one on each iteration.
834a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *getOrInsertCanonicalInductionVariable(const Loop *L, const Type *Ty){
844a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
854a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner             "Can only insert integer or floating point induction variables!");
864a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      SCEVHandle H = SCEVAddRecExpr::get(SCEVUnknown::getIntegerSCEV(0, Ty),
874a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                                         SCEVUnknown::getIntegerSCEV(1, Ty), L);
884a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return expand(H);
894a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
904a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
914a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// addInsertedValue - Remember the specified instruction as being the
924a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// canonical form for the specified SCEV.
934a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    void addInsertedValue(Instruction *I, SCEV *S) {
944a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      InsertedExpressions[S] = (Value*)I;
954a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      InsertedInstructions.insert(I);
964a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
974a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
984a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// expandCodeFor - Insert code to directly compute the specified SCEV
994a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// expression into the program.  The inserted code is inserted into the
1004a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// specified block.
1014a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    ///
1024a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// If a particular value sign is required, a type may be specified for the
1034a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    /// result.
1044a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *expandCodeFor(SCEVHandle SH, Instruction *IP, const Type *Ty = 0) {
1054a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      // Expand the code for this SCEV.
1064a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      this->InsertPt = IP;
1074a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return expandInTy(SH, Ty);
1084a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1094a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1104a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  protected:
1114a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *expand(SCEV *S) {
1124a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      // Check to see if we already expanded this.
1134a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
1144a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      if (I != InsertedExpressions.end())
1154a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner        return I->second;
1164a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1174a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      Value *V = visit(S);
1184a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      InsertedExpressions[S] = V;
1194a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return V;
1204a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1214a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1224a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *expandInTy(SCEV *S, const Type *Ty) {
1234a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      Value *V = expand(S);
1244a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      if (Ty && V->getType() != Ty) {
1254a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner        // FIXME: keep track of the cast instruction.
1264a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner        if (Constant *C = dyn_cast<Constant>(V))
1274a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          return ConstantExpr::getCast(C, Ty);
1284a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner        else if (Instruction *I = dyn_cast<Instruction>(V)) {
1294a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          // Check to see if there is already a cast.  If there is, use it.
1304a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1314a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner               UI != E; ++UI) {
1324a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner            if ((*UI)->getType() == Ty)
1334a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner              if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
1344a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                BasicBlock::iterator It = I; ++It;
1354a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                while (isa<PHINode>(It)) ++It;
1364a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                if (It != BasicBlock::iterator(CI)) {
1374a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                  // Splice the cast immediately after the operand in question.
1384a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                  I->getParent()->getInstList().splice(It,
1394a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                                                       CI->getParent()->getInstList(),
1404a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                                                       CI);
1414a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                }
1424a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                return CI;
1434a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner              }
1444a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          }
1454a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          BasicBlock::iterator IP = I; ++IP;
1464a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          if (InvokeInst *II = dyn_cast<InvokeInst>(I))
1474a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner            IP = II->getNormalDest()->begin();
1484a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          while (isa<PHINode>(IP)) ++IP;
1494a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          return new CastInst(V, Ty, V->getName(), IP);
1504a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner        } else {
1514a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          // FIXME: check to see if there is already a cast!
1524a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          return new CastInst(V, Ty, V->getName(), InsertPt);
1534a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner        }
1544a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      }
1554a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return V;
1564a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1574a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1584a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *visitConstant(SCEVConstant *S) {
1594a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return S->getValue();
1604a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1614a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1624a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *visitTruncateExpr(SCEVTruncateExpr *S) {
1634a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      Value *V = expand(S->getOperand());
1644a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return new CastInst(V, S->getType(), "tmp.", InsertPt);
1654a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1664a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1674a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
1682b994c7206b3872d908468fc926ba8db483cf0a3Chris Lattner      Value *V = expandInTy(S->getOperand(),S->getType()->getUnsignedVersion());
1694a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return new CastInst(V, S->getType(), "tmp.", InsertPt);
1704a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1714a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1724a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *visitAddExpr(SCEVAddExpr *S) {
1734a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      const Type *Ty = S->getType();
1744a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      Value *V = expandInTy(S->getOperand(S->getNumOperands()-1), Ty);
1754a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1764a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      // Emit a bunch of add instructions
1774a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      for (int i = S->getNumOperands()-2; i >= 0; --i)
178c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner        V = BinaryOperator::createAdd(V, expandInTy(S->getOperand(i), Ty),
179c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner                                      "tmp.", InsertPt);
1804a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return V;
1814a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1824a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1834a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *visitMulExpr(SCEVMulExpr *S);
1844a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1854a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *visitUDivExpr(SCEVUDivExpr *S) {
1864a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      const Type *Ty = S->getType();
1874a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      Value *LHS = expandInTy(S->getLHS(), Ty);
1884a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      Value *RHS = expandInTy(S->getRHS(), Ty);
189c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner      return BinaryOperator::createDiv(LHS, RHS, "tmp.", InsertPt);
1904a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1914a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1924a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *visitAddRecExpr(SCEVAddRecExpr *S);
1934a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
1944a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *visitUnknown(SCEVUnknown *S) {
1954a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      return S->getValue();
1964a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    }
1974a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  };
1984a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner}
1994a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2004a7553e2da506a718f59869c03c5ce113eb40f7aChris LattnerValue *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
2014a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  const Type *Ty = S->getType();
2024a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  int FirstOp = 0;  // Set if we should emit a subtract.
2034a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
2044a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    if (SC->getValue()->isAllOnesValue())
2054a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      FirstOp = 1;
2064a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2074a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  int i = S->getNumOperands()-2;
2084a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  Value *V = expandInTy(S->getOperand(i+1), Ty);
2094a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2104a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // Emit a bunch of multiply instructions
2114a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  for (; i >= FirstOp; --i)
212c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner    V = BinaryOperator::createMul(V, expandInTy(S->getOperand(i), Ty),
213c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner                                  "tmp.", InsertPt);
2144a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // -1 * ...  --->  0 - ...
2154a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  if (FirstOp == 1)
216c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner    V = BinaryOperator::createNeg(V, "tmp.", InsertPt);
2174a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  return V;
2184a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner}
2194a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2204a7553e2da506a718f59869c03c5ce113eb40f7aChris LattnerValue *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
2214a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  const Type *Ty = S->getType();
2224a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  const Loop *L = S->getLoop();
2234a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
2244a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  assert(Ty->isIntegral() && "Cannot expand fp recurrences yet!");
2254a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2264a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // {X,+,F} --> X + {0,+,F}
2274a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  if (!isa<SCEVConstant>(S->getStart()) ||
2284a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      !cast<SCEVConstant>(S->getStart())->getValue()->isNullValue()) {
2294a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *Start = expandInTy(S->getStart(), Ty);
2304a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
2314a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    NewOps[0] = SCEVUnknown::getIntegerSCEV(0, Ty);
2324a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *Rest = expandInTy(SCEVAddRecExpr::get(NewOps, L), Ty);
2334a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2344a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    // FIXME: look for an existing add to use.
235c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner    return BinaryOperator::createAdd(Rest, Start, "tmp.", InsertPt);
2364a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  }
2374a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2384a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // {0,+,1} --> Insert a canonical induction variable into the loop!
2394a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  if (S->getNumOperands() == 2 &&
2404a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      S->getOperand(1) == SCEVUnknown::getIntegerSCEV(1, Ty)) {
2414a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    // Create and insert the PHI node for the induction variable in the
2424a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    // specified loop.
2434a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    BasicBlock *Header = L->getHeader();
2444a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
2454a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
2464a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2474a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    pred_iterator HPI = pred_begin(Header);
2484a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    assert(HPI != pred_end(Header) && "Loop with zero preds???");
2494a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    if (!L->contains(*HPI)) ++HPI;
2504a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    assert(HPI != pred_end(Header) && L->contains(*HPI) &&
2514a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner           "No backedge in loop?");
2524a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2534a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    // Insert a unit add instruction right before the terminator corresponding
2544a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    // to the back-edge.
2554a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Constant *One = Ty->isFloatingPoint() ? (Constant*)ConstantFP::get(Ty, 1.0)
2564a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                                          : ConstantInt::get(Ty, 1);
257c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner    Instruction *Add = BinaryOperator::createAdd(PN, One, "indvar.next",
258c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner                                                 (*HPI)->getTerminator());
2594a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2604a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    pred_iterator PI = pred_begin(Header);
2614a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    if (*PI == L->getLoopPreheader())
2624a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      ++PI;
2634a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    PN->addIncoming(Add, *PI);
2644a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    return PN;
2654a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  }
2664a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2674a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // Get the canonical induction variable I for this loop.
2684a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
2694a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2704a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  if (S->getNumOperands() == 2) {   // {0,+,F} --> i*F
2714a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *F = expandInTy(S->getOperand(1), Ty);
272c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner    return BinaryOperator::createMul(I, F, "tmp.", InsertPt);
2734a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  }
2744a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2754a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // If this is a chain of recurrences, turn it into a closed form, using the
2764a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // folders, then expandCodeFor the closed form.  This allows the folders to
2774a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // simplify the expression without having to build a bunch of special code
2784a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  // into this folder.
2794a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  SCEVHandle IH = SCEVUnknown::get(I);   // Get I as a "symbolic" SCEV.
2804a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2814a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  SCEVHandle V = S->evaluateAtIteration(IH);
2824a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  //std::cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
2834a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2844a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  return expandInTy(V, Ty);
2854a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner}
2864a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2874a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner
2884a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattnernamespace {
289a92f696b74a99325026ebbdbffd2a44317e0c10bChris Lattner  Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
29040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
2913adf51d022348b06a1adeef7649fa35928ad9358Chris Lattner  Statistic<> NumInserted("indvars", "Number of canonical indvars added");
29240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  Statistic<> NumReplaced("indvars", "Number of exit values replaced");
29340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  Statistic<> NumLFTR    ("indvars", "Number of loop exit tests replaced");
2943324e718bc9ac2ede08a14c325848b576849542bChris Lattner
2953324e718bc9ac2ede08a14c325848b576849542bChris Lattner  class IndVarSimplify : public FunctionPass {
29640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    LoopInfo        *LI;
29740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    ScalarEvolution *SE;
29815cad759fe2048ac5eb137c6bb0ab7287538677eChris Lattner    bool Changed;
2993324e718bc9ac2ede08a14c325848b576849542bChris Lattner  public:
3003324e718bc9ac2ede08a14c325848b576849542bChris Lattner    virtual bool runOnFunction(Function &) {
30140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      LI = &getAnalysis<LoopInfo>();
30240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      SE = &getAnalysis<ScalarEvolution>();
30315cad759fe2048ac5eb137c6bb0ab7287538677eChris Lattner      Changed = false;
30415cad759fe2048ac5eb137c6bb0ab7287538677eChris Lattner
3053324e718bc9ac2ede08a14c325848b576849542bChris Lattner      // Induction Variables live in the header nodes of loops
30640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
307329c1c6c949d07e3fe9722ec633b4258217fd99dChris Lattner        runOnLoop(*I);
3083324e718bc9ac2ede08a14c325848b576849542bChris Lattner      return Changed;
3093324e718bc9ac2ede08a14c325848b576849542bChris Lattner    }
3103324e718bc9ac2ede08a14c325848b576849542bChris Lattner
3113324e718bc9ac2ede08a14c325848b576849542bChris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
3123324e718bc9ac2ede08a14c325848b576849542bChris Lattner      AU.addRequiredID(LoopSimplifyID);
31340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      AU.addRequired<ScalarEvolution>();
31440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      AU.addRequired<LoopInfo>();
3153324e718bc9ac2ede08a14c325848b576849542bChris Lattner      AU.addPreservedID(LoopSimplifyID);
3163324e718bc9ac2ede08a14c325848b576849542bChris Lattner      AU.setPreservesCFG();
3173324e718bc9ac2ede08a14c325848b576849542bChris Lattner    }
31840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  private:
31940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    void runOnLoop(Loop *L);
32040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
32140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                                    std::set<Instruction*> &DeadInsts);
32240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
3234a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                                   SCEVExpander &RW);
32440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    void RewriteLoopExitValues(Loop *L);
32540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
32640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
3273324e718bc9ac2ede08a14c325848b576849542bChris Lattner  };
3283324e718bc9ac2ede08a14c325848b576849542bChris Lattner  RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
3295e76140536ba66fadeced1cd892f79616f407e3cChris Lattner}
330394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner
3313324e718bc9ac2ede08a14c325848b576849542bChris LattnerPass *llvm::createIndVarSimplifyPass() {
3323324e718bc9ac2ede08a14c325848b576849542bChris Lattner  return new IndVarSimplify();
333394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner}
334394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner
33540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// DeleteTriviallyDeadInstructions - If any of the instructions is the
33640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// specified set are trivially dead, delete them and see if this makes any of
33740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// their operands subsequently dead.
33840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattnervoid IndVarSimplify::
33940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris LattnerDeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
34040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  while (!Insts.empty()) {
34140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    Instruction *I = *Insts.begin();
34240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    Insts.erase(Insts.begin());
34340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    if (isInstructionTriviallyDead(I)) {
34440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
34540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
34640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner          Insts.insert(U);
34740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      SE->deleteInstructionFromRecords(I);
34840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      I->getParent()->getInstList().erase(I);
34940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      Changed = true;
35040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    }
35140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  }
35240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner}
3533324e718bc9ac2ede08a14c325848b576849542bChris Lattner
3546148c02591bd83da7b957589c4bbf6f9720d503fChris Lattner
35540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
35640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// recurrence.  If so, change it into an integer recurrence, permitting
35740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// analysis by the SCEV routines.
35840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattnervoid IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
35940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                                                BasicBlock *Preheader,
36040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                                            std::set<Instruction*> &DeadInsts) {
36140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
36240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
36340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  unsigned BackedgeIdx = PreheaderIdx^1;
36440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  if (GetElementPtrInst *GEPI =
36540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
36640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    if (GEPI->getOperand(0) == PN) {
36740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      assert(GEPI->getNumOperands() == 2 && "GEP types must mismatch!");
36840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
36940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // Okay, we found a pointer recurrence.  Transform this pointer
37040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // recurrence into an integer recurrence.  Compute the value that gets
37140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // added to the pointer at every iteration.
37240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      Value *AddedVal = GEPI->getOperand(1);
37340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
37440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // Insert a new integer PHI node into the top of the block.
37540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      PHINode *NewPhi = new PHINode(AddedVal->getType(),
37640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                                    PN->getName()+".rec", PN);
377c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner      NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
378c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner
37940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // Create the new add instruction.
380c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner      Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
381c5c5e6afe584ffbd2bf2ce755e65bc89f170053aChris Lattner                                                GEPI->getName()+".rec", GEPI);
38240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
38340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
38440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // Update the existing GEP to use the recurrence.
38540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
38640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
38740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // Update the GEP to use the new recurrence we just inserted.
38840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      GEPI->setOperand(1, NewAdd);
38940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
39040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // Finally, if there are any other users of the PHI node, we must
39140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // insert a new GEP instruction that uses the pre-incremented version
39240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // of the induction amount.
39340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      if (!PN->use_empty()) {
39440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        BasicBlock::iterator InsertPos = PN; ++InsertPos;
39540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        while (isa<PHINode>(InsertPos)) ++InsertPos;
39640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        std::string Name = PN->getName(); PN->setName("");
39740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        Value *PreInc =
39840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner          new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
39940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                                std::vector<Value*>(1, NewPhi), Name,
40040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                                InsertPos);
40140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        PN->replaceAllUsesWith(PreInc);
40240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      }
40340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
40440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      // Delete the old PHI for sure, and the GEP if its otherwise unused.
40540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      DeadInsts.insert(PN);
4063324e718bc9ac2ede08a14c325848b576849542bChris Lattner
40740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      ++NumPointer;
40840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      Changed = true;
40940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    }
41040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner}
4113324e718bc9ac2ede08a14c325848b576849542bChris Lattner
41240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// LinearFunctionTestReplace - This method rewrites the exit condition of the
41359fdaeeae8f183e18bb6ad5c382ca23e28e6aaf6Chris Lattner/// loop to be a canonical != comparison against the incremented loop induction
41459fdaeeae8f183e18bb6ad5c382ca23e28e6aaf6Chris Lattner/// variable.  This pass is able to rewrite the exit tests of any loop where the
41559fdaeeae8f183e18bb6ad5c382ca23e28e6aaf6Chris Lattner/// SCEV analysis can determine a loop-invariant trip count of the loop, which
41659fdaeeae8f183e18bb6ad5c382ca23e28e6aaf6Chris Lattner/// is actually a much broader range than just linear tests.
41740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattnervoid IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
4184a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                                               SCEVExpander &RW) {
41940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Find the exit block for the loop.  We can currently only handle loops with
42040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // a single exit.
421f1ab4b4eac5603d19c20f4a508f93a118a52bdd5Chris Lattner  std::vector<BasicBlock*> ExitBlocks;
422f1ab4b4eac5603d19c20f4a508f93a118a52bdd5Chris Lattner  L->getExitBlocks(ExitBlocks);
423f1ab4b4eac5603d19c20f4a508f93a118a52bdd5Chris Lattner  if (ExitBlocks.size() != 1) return;
424f1ab4b4eac5603d19c20f4a508f93a118a52bdd5Chris Lattner  BasicBlock *ExitBlock = ExitBlocks[0];
42540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
42640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Make sure there is only one predecessor block in the loop.
42740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BasicBlock *ExitingBlock = 0;
42840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
42940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner       PI != PE; ++PI)
43040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    if (L->contains(*PI)) {
43140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      if (ExitingBlock == 0)
43240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        ExitingBlock = *PI;
43340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      else
43440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        return;  // Multiple exits from loop to this block.
43540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    }
43640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  assert(ExitingBlock && "Loop info is broken");
43740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
43840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  if (!isa<BranchInst>(ExitingBlock->getTerminator()))
43940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    return;  // Can't rewrite non-branch yet
44040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
44140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  assert(BI->isConditional() && "Must be conditional to be part of loop!");
44240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
44340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  std::set<Instruction*> InstructionsToDelete;
44440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
44540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    InstructionsToDelete.insert(Cond);
44640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
447d244057a48660c3cd30d219118ece3f947947790Chris Lattner  // If the exiting block is not the same as the backedge block, we must compare
448d244057a48660c3cd30d219118ece3f947947790Chris Lattner  // against the preincremented value, otherwise we prefer to compare against
449d244057a48660c3cd30d219118ece3f947947790Chris Lattner  // the post-incremented value.
450d244057a48660c3cd30d219118ece3f947947790Chris Lattner  BasicBlock *Header = L->getHeader();
451d244057a48660c3cd30d219118ece3f947947790Chris Lattner  pred_iterator HPI = pred_begin(Header);
452d244057a48660c3cd30d219118ece3f947947790Chris Lattner  assert(HPI != pred_end(Header) && "Loop with zero preds???");
453d244057a48660c3cd30d219118ece3f947947790Chris Lattner  if (!L->contains(*HPI)) ++HPI;
454d244057a48660c3cd30d219118ece3f947947790Chris Lattner  assert(HPI != pred_end(Header) && L->contains(*HPI) &&
455d244057a48660c3cd30d219118ece3f947947790Chris Lattner         "No backedge in loop?");
456d244057a48660c3cd30d219118ece3f947947790Chris Lattner
457d244057a48660c3cd30d219118ece3f947947790Chris Lattner  SCEVHandle TripCount = IterationCount;
458d244057a48660c3cd30d219118ece3f947947790Chris Lattner  Value *IndVar;
459d244057a48660c3cd30d219118ece3f947947790Chris Lattner  if (*HPI == ExitingBlock) {
460d244057a48660c3cd30d219118ece3f947947790Chris Lattner    // The IterationCount expression contains the number of times that the
461d244057a48660c3cd30d219118ece3f947947790Chris Lattner    // backedge actually branches to the loop header.  This is one less than the
462d244057a48660c3cd30d219118ece3f947947790Chris Lattner    // number of times the loop executes, so add one to it.
463d244057a48660c3cd30d219118ece3f947947790Chris Lattner    Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
464d244057a48660c3cd30d219118ece3f947947790Chris Lattner    TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
465d244057a48660c3cd30d219118ece3f947947790Chris Lattner    IndVar = L->getCanonicalInductionVariableIncrement();
466d244057a48660c3cd30d219118ece3f947947790Chris Lattner  } else {
467d244057a48660c3cd30d219118ece3f947947790Chris Lattner    // We have to use the preincremented value...
468d244057a48660c3cd30d219118ece3f947947790Chris Lattner    IndVar = L->getCanonicalInductionVariable();
469d244057a48660c3cd30d219118ece3f947947790Chris Lattner  }
47059fdaeeae8f183e18bb6ad5c382ca23e28e6aaf6Chris Lattner
47140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Expand the code for the iteration count into the preheader of the loop.
47240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BasicBlock *Preheader = L->getLoopPreheader();
4734a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
47440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                                    IndVar->getType());
47540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
47640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Insert a new setne or seteq instruction before the branch.
47740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  Instruction::BinaryOps Opcode;
47840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  if (L->contains(BI->getSuccessor(0)))
47940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    Opcode = Instruction::SetNE;
48040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  else
48140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    Opcode = Instruction::SetEQ;
48240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
48340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
48440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BI->setCondition(Cond);
48540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  ++NumLFTR;
48640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  Changed = true;
48740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
48840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  DeleteTriviallyDeadInstructions(InstructionsToDelete);
48940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner}
4903324e718bc9ac2ede08a14c325848b576849542bChris Lattner
4913324e718bc9ac2ede08a14c325848b576849542bChris Lattner
49240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// RewriteLoopExitValues - Check to see if this loop has a computable
49340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// loop-invariant execution count.  If so, this means that we can compute the
49440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// final value of any expressions that are recurrent in the loop, and
49540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// substitute the exit values from the loop into any instructions outside of
49640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner/// the loop that use the final values of the current expressions.
49740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattnervoid IndVarSimplify::RewriteLoopExitValues(Loop *L) {
49840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BasicBlock *Preheader = L->getLoopPreheader();
49940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
50040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Scan all of the instructions in the loop, looking at those that have
50140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // extra-loop users and which are recurrences.
5024a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  SCEVExpander Rewriter(*SE, *LI);
50340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
50440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // We insert the code into the preheader of the loop if the loop contains
50540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // multiple exit blocks, or in the exit block if there is exactly one.
50640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BasicBlock *BlockToInsertInto;
507f1ab4b4eac5603d19c20f4a508f93a118a52bdd5Chris Lattner  std::vector<BasicBlock*> ExitBlocks;
508f1ab4b4eac5603d19c20f4a508f93a118a52bdd5Chris Lattner  L->getExitBlocks(ExitBlocks);
509f1ab4b4eac5603d19c20f4a508f93a118a52bdd5Chris Lattner  if (ExitBlocks.size() == 1)
510f1ab4b4eac5603d19c20f4a508f93a118a52bdd5Chris Lattner    BlockToInsertInto = ExitBlocks[0];
51140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  else
51240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    BlockToInsertInto = Preheader;
51340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
51440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  while (isa<PHINode>(InsertPt)) ++InsertPt;
51540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
51620aa098ba694aa7e3f5fb5a52d22dba7c1e857aeChris Lattner  bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
51720aa098ba694aa7e3f5fb5a52d22dba7c1e857aeChris Lattner
51840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  std::set<Instruction*> InstructionsToDelete;
51940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
52040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
52140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
52240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      BasicBlock *BB = L->getBlocks()[i];
52340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
52440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        if (I->getType()->isInteger()) {      // Is an integer instruction
52540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner          SCEVHandle SH = SE->getSCEV(I);
52620aa098ba694aa7e3f5fb5a52d22dba7c1e857aeChris Lattner          if (SH->hasComputableLoopEvolution(L) ||    // Varies predictably
52720aa098ba694aa7e3f5fb5a52d22dba7c1e857aeChris Lattner              HasConstantItCount) {
52840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner            // Find out if this predictably varying value is actually used
52940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner            // outside of the loop.  "extra" as opposed to "intra".
53040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner            std::vector<User*> ExtraLoopUsers;
53140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner            for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
53240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                 UI != E; ++UI)
53340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner              if (!L->contains(cast<Instruction>(*UI)->getParent()))
53440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                ExtraLoopUsers.push_back(*UI);
53540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner            if (!ExtraLoopUsers.empty()) {
53640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner              // Okay, this instruction has a user outside of the current loop
53740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner              // and varies predictably in this loop.  Evaluate the value it
53840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner              // contains when the loop exits, and insert code for it.
53920aa098ba694aa7e3f5fb5a52d22dba7c1e857aeChris Lattner              SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
54040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner              if (!isa<SCEVCouldNotCompute>(ExitValue)) {
54140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                Changed = true;
54240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                ++NumReplaced;
5434a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner                Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
54440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                                                       I->getType());
54540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
54640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                // Rewrite any users of the computed value outside of the loop
54740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                // with the newly computed value.
54840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i)
54940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                  ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
55040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
55140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                // If this instruction is dead now, schedule it to be removed.
55240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                if (I->use_empty())
55340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner                  InstructionsToDelete.insert(I);
55440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner              }
55540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner            }
55640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner          }
55740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        }
5583324e718bc9ac2ede08a14c325848b576849542bChris Lattner    }
5596148c02591bd83da7b957589c4bbf6f9720d503fChris Lattner
56040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  DeleteTriviallyDeadInstructions(InstructionsToDelete);
56140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner}
56215cad759fe2048ac5eb137c6bb0ab7287538677eChris Lattner
56315cad759fe2048ac5eb137c6bb0ab7287538677eChris Lattner
56440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattnervoid IndVarSimplify::runOnLoop(Loop *L) {
56540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // First step.  Check to see if there are any trivial GEP pointer recurrences.
56640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // If there are, change them into integer recurrences, permitting analysis by
56740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // the SCEV routines.
56815cad759fe2048ac5eb137c6bb0ab7287538677eChris Lattner  //
56940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BasicBlock *Header    = L->getHeader();
57040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BasicBlock *Preheader = L->getLoopPreheader();
57140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
57240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  std::set<Instruction*> DeadInsts;
57340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  for (BasicBlock::iterator I = Header->begin();
57440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner       PHINode *PN = dyn_cast<PHINode>(I); ++I)
57540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    if (isa<PointerType>(PN->getType()))
57640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      EliminatePointerRecurrence(PN, Preheader, DeadInsts);
57715cad759fe2048ac5eb137c6bb0ab7287538677eChris Lattner
57840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  if (!DeadInsts.empty())
57940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    DeleteTriviallyDeadInstructions(DeadInsts);
580394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner
581394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner
58240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Next, transform all loops nesting inside of this loop.
58340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
58440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    runOnLoop(*I);
585394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner
58640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Check to see if this loop has a computable loop-invariant execution count.
58740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // If so, this means that we can compute the final value of any expressions
58840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // that are recurrent in the loop, and substitute the exit values from the
58940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // loop into any instructions outside of the loop that use the final values of
59040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // the current expressions.
591394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner  //
59240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  SCEVHandle IterationCount = SE->getIterationCount(L);
59340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  if (!isa<SCEVCouldNotCompute>(IterationCount))
59440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    RewriteLoopExitValues(L);
59540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
59640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Next, analyze all of the induction variables in the loop, canonicalizing
59740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // auxillary induction variables.
59840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
59940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
60040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  for (BasicBlock::iterator I = Header->begin();
60140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner       PHINode *PN = dyn_cast<PHINode>(I); ++I)
60240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    if (PN->getType()->isInteger()) {  // FIXME: when we have fast-math, enable!
60340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      SCEVHandle SCEV = SE->getSCEV(PN);
60440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      if (SCEV->hasComputableLoopEvolution(L))
605a25502acd7c0d56cbd20da37f25830d81be834c5Chris Lattner        // FIXME: Without a strength reduction pass, it is an extremely bad idea
606a25502acd7c0d56cbd20da37f25830d81be834c5Chris Lattner        // to indvar substitute anything more complex than a linear induction
607a25502acd7c0d56cbd20da37f25830d81be834c5Chris Lattner        // variable.  Doing so will put expensive multiply instructions inside
608a25502acd7c0d56cbd20da37f25830d81be834c5Chris Lattner        // of the loop.  For now just disable indvar subst on anything more
609a25502acd7c0d56cbd20da37f25830d81be834c5Chris Lattner        // complex than a linear addrec.
610a25502acd7c0d56cbd20da37f25830d81be834c5Chris Lattner        if (!isa<SCEVAddRecExpr>(SCEV) ||
611a25502acd7c0d56cbd20da37f25830d81be834c5Chris Lattner            cast<SCEVAddRecExpr>(SCEV)->getNumOperands() < 3)
61240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner          IndVars.push_back(std::make_pair(PN, SCEV));
61340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    }
614f016ea4ff80c56c467247a90567dd07bddb590f3Chris Lattner
61540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // If there are no induction variables in the loop, there is nothing more to
61640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // do.
617f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner  if (IndVars.empty()) {
618f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner    // Actually, if we know how many times the loop iterates, lets insert a
619f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner    // canonical induction variable to help subsequent passes.
620f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner    if (!isa<SCEVCouldNotCompute>(IterationCount)) {
6214a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      SCEVExpander Rewriter(*SE, *LI);
6224a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner      Rewriter.getOrInsertCanonicalInductionVariable(L,
623f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner                                                     IterationCount->getType());
624f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner      LinearFunctionTestReplace(L, IterationCount, Rewriter);
625f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner    }
626f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner    return;
627f50af088f19f525f3d1026eb61db77e0037a9f43Chris Lattner  }
628f016ea4ff80c56c467247a90567dd07bddb590f3Chris Lattner
62940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Compute the type of the largest recurrence expression.
63040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  //
63140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  const Type *LargestType = IndVars[0].first->getType();
632fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner  bool DifferingSizes = false;
63340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
63440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    const Type *Ty = IndVars[i].first->getType();
635fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner    DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
63640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
63740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      LargestType = Ty;
638500597a1c39e91a3020587318ed61e737b6c613aChris Lattner  }
639394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner
64040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Create a rewriter object which we'll use to transform the code with.
6414a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  SCEVExpander Rewriter(*SE, *LI);
64240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
64340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Now that we know the largest of of the induction variables in this loop,
64440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // insert a canonical induction variable of the largest size.
645006118fe8c73d8009d7952b84cabd50882ed0033Chris Lattner  LargestType = LargestType->getUnsignedVersion();
6464a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner  Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
64740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  ++NumInserted;
64840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  Changed = true;
64940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
65040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  if (!isa<SCEVCouldNotCompute>(IterationCount))
65159fdaeeae8f183e18bb6ad5c382ca23e28e6aaf6Chris Lattner    LinearFunctionTestReplace(L, IterationCount, Rewriter);
65240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
65340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // Now that we have a canonical induction variable, we can rewrite any
65440bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // recurrences in terms of the induction variable.  Start with the auxillary
65540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  // induction variables, and recursively rewrite any of their uses.
65640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  BasicBlock::iterator InsertPt = Header->begin();
65740bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  while (isa<PHINode>(InsertPt)) ++InsertPt;
65840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner
6595d461d20aea308471f2a31b718a274bfee28b60cChris Lattner  // If there were induction variables of other sizes, cast the primary
6605d461d20aea308471f2a31b718a274bfee28b60cChris Lattner  // induction variable to the right size for them, avoiding the need for the
6615d461d20aea308471f2a31b718a274bfee28b60cChris Lattner  // code evaluation methods to insert induction variables of different sizes.
662fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner  if (DifferingSizes) {
663fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner    bool InsertedSizes[17] = { false };
664fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner    InsertedSizes[LargestType->getPrimitiveSize()] = true;
665fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner    for (unsigned i = 0, e = IndVars.size(); i != e; ++i)
666fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner      if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) {
667fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner        PHINode *PN = IndVars[i].first;
668fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner        InsertedSizes[PN->getType()->getPrimitiveSize()] = true;
669fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner        Instruction *New = new CastInst(IndVar,
670fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner                                        PN->getType()->getUnsignedVersion(),
671fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner                                        "indvar", InsertPt);
672fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner        Rewriter.addInsertedValue(New, SE->getSCEV(New));
673fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner      }
674fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner  }
675fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner
676fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner  // If there were induction variables of other sizes, cast the primary
677fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner  // induction variable to the right size for them, avoiding the need for the
678fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner  // code evaluation methods to insert induction variables of different sizes.
6795d461d20aea308471f2a31b718a274bfee28b60cChris Lattner  std::map<unsigned, Value*> InsertedSizes;
68040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  while (!IndVars.empty()) {
68140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    PHINode *PN = IndVars.back().first;
6824a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner    Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
683fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner                                           PN->getType());
684fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner    std::string Name = PN->getName();
685fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner    PN->setName("");
686fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner    NewVal->setName(Name);
6875d461d20aea308471f2a31b718a274bfee28b60cChris Lattner
68840bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    // Replace the old PHI Node with the inserted computation.
689fcb81f5f4cbac61851b7dec403961cf88e614aa1Chris Lattner    PN->replaceAllUsesWith(NewVal);
69040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    DeadInsts.insert(PN);
69140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    IndVars.pop_back();
69240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    ++NumRemoved;
69340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    Changed = true;
694500597a1c39e91a3020587318ed61e737b6c613aChris Lattner  }
695ba4f3f6a419326df190599421fa149c90235cb72Chris Lattner
696b4782d13d1444d9d18c0a681292cf0d0a32cf3efChris Lattner#if 0
6971363e85df74627530ceede53280613c62a4cdbe3Chris Lattner  // Now replace all derived expressions in the loop body with simpler
6981363e85df74627530ceede53280613c62a4cdbe3Chris Lattner  // expressions.
69940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner  for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
70040bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner    if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
70140bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      BasicBlock *BB = L->getBlocks()[i];
70240bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
70340bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        if (I->getType()->isInteger() &&      // Is an integer instruction
7041363e85df74627530ceede53280613c62a4cdbe3Chris Lattner            !I->use_empty() &&
70540bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner            !Rewriter.isInsertedInstruction(I)) {
70640bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner          SCEVHandle SH = SE->getSCEV(I);
7074a7553e2da506a718f59869c03c5ce113eb40f7aChris Lattner          Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
7081363e85df74627530ceede53280613c62a4cdbe3Chris Lattner          if (V != I) {
7091363e85df74627530ceede53280613c62a4cdbe3Chris Lattner            if (isa<Instruction>(V)) {
7101363e85df74627530ceede53280613c62a4cdbe3Chris Lattner              std::string Name = I->getName();
7111363e85df74627530ceede53280613c62a4cdbe3Chris Lattner              I->setName("");
7121363e85df74627530ceede53280613c62a4cdbe3Chris Lattner              V->setName(Name);
7131363e85df74627530ceede53280613c62a4cdbe3Chris Lattner            }
7141363e85df74627530ceede53280613c62a4cdbe3Chris Lattner            I->replaceAllUsesWith(V);
7151363e85df74627530ceede53280613c62a4cdbe3Chris Lattner            DeadInsts.insert(I);
7161363e85df74627530ceede53280613c62a4cdbe3Chris Lattner            ++NumRemoved;
7171363e85df74627530ceede53280613c62a4cdbe3Chris Lattner            Changed = true;
7181363e85df74627530ceede53280613c62a4cdbe3Chris Lattner          }
71940bf8b48cdb9961898dba1bc67320be1e49e3da1Chris Lattner        }
720394437ff7eaccfe1de92fe14d0022ca0addf3e41Chris Lattner    }
721b4782d13d1444d9d18c0a681292cf0d0a32cf3efChris Lattner#endif
7221363e85df74627530ceede53280613c62a4cdbe3Chris Lattner
7231363e85df74627530ceede53280613c62a4cdbe3Chris Lattner  DeleteTriviallyDeadInstructions(DeadInsts);
7246148c02591bd83da7b957589c4bbf6f9720d503fChris Lattner}
725