IndVarSimplify.cpp revision 4dfdf242c1917e98f407818eb5b68ae0b4678f26
1c91307af2622f6625525f3c1f9c954376df950adChia-chi Yeh//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
20a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//
30a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//                     The LLVM Compiler Infrastructure
40a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//
50a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// This file is distributed under the University of Illinois Open Source
60a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// License. See LICENSE.TXT for details.
70a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//
80a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//===----------------------------------------------------------------------===//
90a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//
100a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// This transformation analyzes and transforms the induction variables (and
110a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// computations derived from them) into simpler forms suitable for subsequent
120a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// analysis and transformation.
130a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//
140a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// This transformation makes the following changes to each loop with an
150a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// identifiable induction variable:
160a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//   1. All loops are transformed to have a SINGLE canonical induction variable
170a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      which starts at zero and steps by one.
180a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//   2. The canonical induction variable is guaranteed to be the first PHI node
190a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      in the loop header block.
200a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//   3. The canonical induction variable is guaranteed to be in a wide enough
210a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      type so that IV expressions need not be (directly) zero-extended or
220a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      sign-extended.
230a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//   4. Any pointer arithmetic recurrences are raised to use array subscripts.
240a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//
250a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// If the trip count of a loop is computable, this pass also makes the following
260a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// changes:
270a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//   1. The exit condition for the loop is canonicalized to compare the
280a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      induction value against the exit value.  This turns loops like:
290a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
300a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//   2. Any use outside of the loop of an expression derived from the indvar
310a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      is changed to compute the derived value outside of the loop, eliminating
320a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      the dependence on the exit value of the induction variable.  If the only
330a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      purpose of the loop is to compute the exit value of some derived
340a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//      expression, this transformation will make the loop dead.
350a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//
360a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// This transformation should be followed by strength reduction after all of the
370a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang// desired loop transformations have been performed.
380a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//
390a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang//===----------------------------------------------------------------------===//
400a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
410a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#define DEBUG_TYPE "indvars"
420a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Transforms/Scalar.h"
430a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/BasicBlock.h"
440a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Constants.h"
450a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Instructions.h"
460a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/IntrinsicInst.h"
470a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/LLVMContext.h"
480a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Type.h"
490a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Analysis/Dominators.h"
500a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Analysis/IVUsers.h"
510a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Analysis/ScalarEvolutionExpander.h"
520a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Analysis/LoopInfo.h"
530a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Analysis/LoopPass.h"
540a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Support/CFG.h"
550a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Support/CommandLine.h"
560a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Support/Debug.h"
570a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Support/raw_ostream.h"
580a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Transforms/Utils/Local.h"
590a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/Transforms/Utils/BasicBlockUtils.h"
600a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/ADT/SmallVector.h"
610a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/ADT/Statistic.h"
620a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang#include "llvm/ADT/STLExtras.h"
630a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wangusing namespace llvm;
640a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
650a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangSTATISTIC(NumRemoved , "Number of aux indvars removed");
660a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangSTATISTIC(NumInserted, "Number of canonical indvars added");
670a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangSTATISTIC(NumReplaced, "Number of exit values replaced");
680a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangSTATISTIC(NumLFTR    , "Number of loop exit tests replaced");
690a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
700a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wangnamespace {
710a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  class IndVarSimplify : public LoopPass {
720a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    IVUsers         *IU;
730a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    LoopInfo        *LI;
740a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    ScalarEvolution *SE;
750a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    DominatorTree   *DT;
760a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    SmallVector<WeakVH, 16> DeadInsts;
770a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    bool Changed;
780a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  public:
790a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
800a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    static char ID; // Pass identification, replacement for typeid
810a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    IndVarSimplify() : LoopPass(ID) {
820a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
830a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    }
840a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
850a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
860a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
870a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
880a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addRequired<DominatorTree>();
890a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addRequired<LoopInfo>();
900a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addRequired<ScalarEvolution>();
91c91307af2622f6625525f3c1f9c954376df950adChia-chi Yeh      AU.addRequiredID(LoopSimplifyID);
920a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addRequiredID(LCSSAID);
930a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addRequired<IVUsers>();
940a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addPreserved<ScalarEvolution>();
950a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addPreservedID(LoopSimplifyID);
960a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addPreservedID(LCSSAID);
970a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.addPreserved<IVUsers>();
980a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      AU.setPreservesCFG();
990a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    }
1000a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1010a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  private:
1020a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    bool isValidRewrite(Value *FromVal, Value *ToVal);
1030a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1040a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    void EliminateIVComparisons();
1050a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    void EliminateIVRemainders();
1060a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    void RewriteNonIntegerIVs(Loop *L);
1070a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1080a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    bool canExpandBackedgeTakenCount(Loop *L,
1090a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang                                     const SCEV *BackedgeTakenCount);
1100a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1110a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
1120a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang                                        PHINode *IndVar,
1130a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang                                        SCEVExpander &Rewriter);
1140a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
1150a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1160a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
1170a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1180a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    void SinkUnusedInvariants(Loop *L);
1190a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1200a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    void HandleFloatingPointIV(Loop *L, PHINode *PH);
1210a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  };
1220a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang}
1230a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1240a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wangchar IndVarSimplify::ID = 0;
1250a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangINITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
1260a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang                "Canonicalize Induction Variables", false, false)
1270a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangINITIALIZE_PASS_DEPENDENCY(DominatorTree)
1280a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangINITIALIZE_PASS_DEPENDENCY(LoopInfo)
1290a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangINITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1300a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangINITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1310a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangINITIALIZE_PASS_DEPENDENCY(LCSSA)
1320a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangINITIALIZE_PASS_DEPENDENCY(IVUsers)
1330a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangINITIALIZE_PASS_END(IndVarSimplify, "indvars",
1340a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang                "Canonicalize Induction Variables", false, false)
1350a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1360a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangPass *llvm::createIndVarSimplifyPass() {
1370a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  return new IndVarSimplify();
1380a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang}
1390a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1400a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang/// isValidRewrite - Return true if the SCEV expansion generated by the
1410a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang/// rewriter can replace the original value. SCEV guarantees that it
1420a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang/// produces the same value, but the way it is produced may be illegal IR.
1430a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang/// Ideally, this function will only be called for verification.
1440a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wangbool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
1450a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // If an SCEV expression subsumed multiple pointers, its expansion could
1460a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // reassociate the GEP changing the base pointer. This is illegal because the
1470a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // final address produced by a GEP chain must be inbounds relative to its
1480a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // underlying object. Otherwise basic alias analysis, among other things,
1490a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
1500a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // producing an expression involving multiple pointers. Until then, we must
1510a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // bail out here.
1520a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  //
1530a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
1540a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // because it understands lcssa phis while SCEV does not.
1550a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  Value *FromPtr = FromVal;
1560a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  Value *ToPtr = ToVal;
1570a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
1580a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    FromPtr = GEP->getPointerOperand();
1590a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  }
1600a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
1610a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    ToPtr = GEP->getPointerOperand();
1620a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  }
1630a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  if (FromPtr != FromVal || ToPtr != ToVal) {
1640a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    // Quickly check the common case
1650a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    if (FromPtr == ToPtr)
1660a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      return true;
1670a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1680a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    // SCEV may have rewritten an expression that produces the GEP's pointer
1690a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    // operand. That's ok as long as the pointer operand has the same base
1700a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
1710a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    // base of a recurrence. This handles the case in which SCEV expansion
1720a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    // converts a pointer type recurrence into a nonrecurrent pointer base
1730a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    // indexed by an integer recurrence.
1740a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
1750a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
1760a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    if (FromBase == ToBase)
1770a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      return true;
1780a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1790a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
1800a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang          << *FromBase << " != " << *ToBase << "\n");
1810a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1820a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    return false;
1830a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  }
1840a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  return true;
1850a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang}
1860a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1870a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1880a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang/// count expression can be safely and cheaply expanded into an instruction
1890a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang/// sequence that can be used by LinearFunctionTestReplace.
1900a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wangbool IndVarSimplify::
1910a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih WangcanExpandBackedgeTakenCount(Loop *L,
1920a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang                            const SCEV *BackedgeTakenCount) {
1930a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1940a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang      BackedgeTakenCount->isZero())
1950a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    return false;
1960a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
1970a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  if (!L->getExitingBlock())
1980a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    return false;
1990a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
2000a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // Can't rewrite non-branch yet.
2010a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
2020a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  if (!BI)
2030a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    return false;
2040a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang
2050a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // Special case: If the backedge-taken count is a UDiv, it's very likely a
2060a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // UDiv that ScalarEvolution produced in order to compute a precise
2070a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // expression, rather than a UDiv from the user's code. If we can't find a
2080a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // UDiv in the code with some simple searching, assume the former and forego
2090a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  // rewriting the loop.
2100a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang  if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
2110a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
2120a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    if (!OrigCond) return 0;
2130a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
2140a1907d434839af6a9cb6329bbde60b237bf53dcChung-yih Wang    R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
215    if (R != BackedgeTakenCount) {
216      const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
217      L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
218      if (L != BackedgeTakenCount)
219        return false;
220    }
221  }
222  return true;
223}
224
225/// LinearFunctionTestReplace - This method rewrites the exit condition of the
226/// loop to be a canonical != comparison against the incremented loop induction
227/// variable.  This pass is able to rewrite the exit tests of any loop where the
228/// SCEV analysis can determine a loop-invariant trip count of the loop, which
229/// is actually a much broader range than just linear tests.
230ICmpInst *IndVarSimplify::
231LinearFunctionTestReplace(Loop *L,
232                          const SCEV *BackedgeTakenCount,
233                          PHINode *IndVar,
234                          SCEVExpander &Rewriter) {
235  assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) && "precondition");
236  BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
237
238  // If the exiting block is not the same as the backedge block, we must compare
239  // against the preincremented value, otherwise we prefer to compare against
240  // the post-incremented value.
241  Value *CmpIndVar;
242  const SCEV *RHS = BackedgeTakenCount;
243  if (L->getExitingBlock() == L->getLoopLatch()) {
244    // Add one to the "backedge-taken" count to get the trip count.
245    // If this addition may overflow, we have to be more pessimistic and
246    // cast the induction variable before doing the add.
247    const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
248    const SCEV *N =
249      SE->getAddExpr(BackedgeTakenCount,
250                     SE->getConstant(BackedgeTakenCount->getType(), 1));
251    if ((isa<SCEVConstant>(N) && !N->isZero()) ||
252        SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
253      // No overflow. Cast the sum.
254      RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
255    } else {
256      // Potential overflow. Cast before doing the add.
257      RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
258                                        IndVar->getType());
259      RHS = SE->getAddExpr(RHS,
260                           SE->getConstant(IndVar->getType(), 1));
261    }
262
263    // The BackedgeTaken expression contains the number of times that the
264    // backedge branches to the loop header.  This is one less than the
265    // number of times the loop executes, so use the incremented indvar.
266    CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
267  } else {
268    // We have to use the preincremented value...
269    RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
270                                      IndVar->getType());
271    CmpIndVar = IndVar;
272  }
273
274  // Expand the code for the iteration count.
275  assert(SE->isLoopInvariant(RHS, L) &&
276         "Computed iteration count is not loop invariant!");
277  Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
278
279  // Insert a new icmp_ne or icmp_eq instruction before the branch.
280  ICmpInst::Predicate Opcode;
281  if (L->contains(BI->getSuccessor(0)))
282    Opcode = ICmpInst::ICMP_NE;
283  else
284    Opcode = ICmpInst::ICMP_EQ;
285
286  DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
287               << "      LHS:" << *CmpIndVar << '\n'
288               << "       op:\t"
289               << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
290               << "      RHS:\t" << *RHS << "\n");
291
292  ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
293
294  Value *OrigCond = BI->getCondition();
295  // It's tempting to use replaceAllUsesWith here to fully replace the old
296  // comparison, but that's not immediately safe, since users of the old
297  // comparison may not be dominated by the new comparison. Instead, just
298  // update the branch to use the new comparison; in the common case this
299  // will make old comparison dead.
300  BI->setCondition(Cond);
301  DeadInsts.push_back(OrigCond);
302
303  ++NumLFTR;
304  Changed = true;
305  return Cond;
306}
307
308/// RewriteLoopExitValues - Check to see if this loop has a computable
309/// loop-invariant execution count.  If so, this means that we can compute the
310/// final value of any expressions that are recurrent in the loop, and
311/// substitute the exit values from the loop into any instructions outside of
312/// the loop that use the final values of the current expressions.
313///
314/// This is mostly redundant with the regular IndVarSimplify activities that
315/// happen later, except that it's more powerful in some cases, because it's
316/// able to brute-force evaluate arbitrary instructions as long as they have
317/// constant operands at the beginning of the loop.
318void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
319  // Verify the input to the pass in already in LCSSA form.
320  assert(L->isLCSSAForm(*DT));
321
322  SmallVector<BasicBlock*, 8> ExitBlocks;
323  L->getUniqueExitBlocks(ExitBlocks);
324
325  // Find all values that are computed inside the loop, but used outside of it.
326  // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
327  // the exit blocks of the loop to find them.
328  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
329    BasicBlock *ExitBB = ExitBlocks[i];
330
331    // If there are no PHI nodes in this exit block, then no values defined
332    // inside the loop are used on this path, skip it.
333    PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
334    if (!PN) continue;
335
336    unsigned NumPreds = PN->getNumIncomingValues();
337
338    // Iterate over all of the PHI nodes.
339    BasicBlock::iterator BBI = ExitBB->begin();
340    while ((PN = dyn_cast<PHINode>(BBI++))) {
341      if (PN->use_empty())
342        continue; // dead use, don't replace it
343
344      // SCEV only supports integer expressions for now.
345      if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
346        continue;
347
348      // It's necessary to tell ScalarEvolution about this explicitly so that
349      // it can walk the def-use list and forget all SCEVs, as it may not be
350      // watching the PHI itself. Once the new exit value is in place, there
351      // may not be a def-use connection between the loop and every instruction
352      // which got a SCEVAddRecExpr for that loop.
353      SE->forgetValue(PN);
354
355      // Iterate over all of the values in all the PHI nodes.
356      for (unsigned i = 0; i != NumPreds; ++i) {
357        // If the value being merged in is not integer or is not defined
358        // in the loop, skip it.
359        Value *InVal = PN->getIncomingValue(i);
360        if (!isa<Instruction>(InVal))
361          continue;
362
363        // If this pred is for a subloop, not L itself, skip it.
364        if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
365          continue; // The Block is in a subloop, skip it.
366
367        // Check that InVal is defined in the loop.
368        Instruction *Inst = cast<Instruction>(InVal);
369        if (!L->contains(Inst))
370          continue;
371
372        // Okay, this instruction has a user outside of the current loop
373        // and varies predictably *inside* the loop.  Evaluate the value it
374        // contains when the loop exits, if possible.
375        const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
376        if (!SE->isLoopInvariant(ExitValue, L))
377          continue;
378
379        Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
380
381        DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
382                     << "  LoopVal = " << *Inst << "\n");
383
384        if (!isValidRewrite(Inst, ExitVal)) {
385          DeadInsts.push_back(ExitVal);
386          continue;
387        }
388        Changed = true;
389        ++NumReplaced;
390
391        PN->setIncomingValue(i, ExitVal);
392
393        // If this instruction is dead now, delete it.
394        RecursivelyDeleteTriviallyDeadInstructions(Inst);
395
396        if (NumPreds == 1) {
397          // Completely replace a single-pred PHI. This is safe, because the
398          // NewVal won't be variant in the loop, so we don't need an LCSSA phi
399          // node anymore.
400          PN->replaceAllUsesWith(ExitVal);
401          RecursivelyDeleteTriviallyDeadInstructions(PN);
402        }
403      }
404      if (NumPreds != 1) {
405        // Clone the PHI and delete the original one. This lets IVUsers and
406        // any other maps purge the original user from their records.
407        PHINode *NewPN = cast<PHINode>(PN->clone());
408        NewPN->takeName(PN);
409        NewPN->insertBefore(PN);
410        PN->replaceAllUsesWith(NewPN);
411        PN->eraseFromParent();
412      }
413    }
414  }
415
416  // The insertion point instruction may have been deleted; clear it out
417  // so that the rewriter doesn't trip over it later.
418  Rewriter.clearInsertPoint();
419}
420
421void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
422  // First step.  Check to see if there are any floating-point recurrences.
423  // If there are, change them into integer recurrences, permitting analysis by
424  // the SCEV routines.
425  //
426  BasicBlock *Header = L->getHeader();
427
428  SmallVector<WeakVH, 8> PHIs;
429  for (BasicBlock::iterator I = Header->begin();
430       PHINode *PN = dyn_cast<PHINode>(I); ++I)
431    PHIs.push_back(PN);
432
433  for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
434    if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
435      HandleFloatingPointIV(L, PN);
436
437  // If the loop previously had floating-point IV, ScalarEvolution
438  // may not have been able to compute a trip count. Now that we've done some
439  // re-writing, the trip count may be computable.
440  if (Changed)
441    SE->forgetLoop(L);
442}
443
444void IndVarSimplify::EliminateIVComparisons() {
445  // Look for ICmp users.
446  for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
447    IVStrideUse &UI = *I;
448    ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
449    if (!ICmp) continue;
450
451    bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
452    ICmpInst::Predicate Pred = ICmp->getPredicate();
453    if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
454
455    // Get the SCEVs for the ICmp operands.
456    const SCEV *S = IU->getReplacementExpr(UI);
457    const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
458
459    // Simplify unnecessary loops away.
460    const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
461    S = SE->getSCEVAtScope(S, ICmpLoop);
462    X = SE->getSCEVAtScope(X, ICmpLoop);
463
464    // If the condition is always true or always false, replace it with
465    // a constant value.
466    if (SE->isKnownPredicate(Pred, S, X))
467      ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
468    else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
469      ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
470    else
471      continue;
472
473    DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
474    DeadInsts.push_back(ICmp);
475  }
476}
477
478void IndVarSimplify::EliminateIVRemainders() {
479  // Look for SRem and URem users.
480  for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
481    IVStrideUse &UI = *I;
482    BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser());
483    if (!Rem) continue;
484
485    bool isSigned = Rem->getOpcode() == Instruction::SRem;
486    if (!isSigned && Rem->getOpcode() != Instruction::URem)
487      continue;
488
489    // We're only interested in the case where we know something about
490    // the numerator.
491    if (UI.getOperandValToReplace() != Rem->getOperand(0))
492      continue;
493
494    // Get the SCEVs for the ICmp operands.
495    const SCEV *S = SE->getSCEV(Rem->getOperand(0));
496    const SCEV *X = SE->getSCEV(Rem->getOperand(1));
497
498    // Simplify unnecessary loops away.
499    const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
500    S = SE->getSCEVAtScope(S, ICmpLoop);
501    X = SE->getSCEVAtScope(X, ICmpLoop);
502
503    // i % n  -->  i  if i is in [0,n).
504    if ((!isSigned || SE->isKnownNonNegative(S)) &&
505        SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
506                             S, X))
507      Rem->replaceAllUsesWith(Rem->getOperand(0));
508    else {
509      // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
510      const SCEV *LessOne =
511        SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
512      if ((!isSigned || SE->isKnownNonNegative(LessOne)) &&
513          SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
514                               LessOne, X)) {
515        ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
516                                      Rem->getOperand(0), Rem->getOperand(1),
517                                      "tmp");
518        SelectInst *Sel =
519          SelectInst::Create(ICmp,
520                             ConstantInt::get(Rem->getType(), 0),
521                             Rem->getOperand(0), "tmp", Rem);
522        Rem->replaceAllUsesWith(Sel);
523      } else
524        continue;
525    }
526
527    // Inform IVUsers about the new users.
528    if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
529      IU->AddUsersIfInteresting(I);
530
531    DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
532    DeadInsts.push_back(Rem);
533  }
534}
535
536bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
537  // If LoopSimplify form is not available, stay out of trouble. Some notes:
538  //  - LSR currently only supports LoopSimplify-form loops. Indvars'
539  //    canonicalization can be a pessimization without LSR to "clean up"
540  //    afterwards.
541  //  - We depend on having a preheader; in particular,
542  //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
543  //    and we're in trouble if we can't find the induction variable even when
544  //    we've manually inserted one.
545  if (!L->isLoopSimplifyForm())
546    return false;
547
548  IU = &getAnalysis<IVUsers>();
549  LI = &getAnalysis<LoopInfo>();
550  SE = &getAnalysis<ScalarEvolution>();
551  DT = &getAnalysis<DominatorTree>();
552  DeadInsts.clear();
553  Changed = false;
554
555  // If there are any floating-point recurrences, attempt to
556  // transform them to use integer recurrences.
557  RewriteNonIntegerIVs(L);
558
559  const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
560
561  // Create a rewriter object which we'll use to transform the code with.
562  SCEVExpander Rewriter(*SE);
563
564  // Check to see if this loop has a computable loop-invariant execution count.
565  // If so, this means that we can compute the final value of any expressions
566  // that are recurrent in the loop, and substitute the exit values from the
567  // loop into any instructions outside of the loop that use the final values of
568  // the current expressions.
569  //
570  if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
571    RewriteLoopExitValues(L, Rewriter);
572
573  // Simplify ICmp IV users.
574  EliminateIVComparisons();
575
576  // Simplify SRem and URem IV users.
577  EliminateIVRemainders();
578
579  // Compute the type of the largest recurrence expression, and decide whether
580  // a canonical induction variable should be inserted.
581  const Type *LargestType = 0;
582  bool NeedCannIV = false;
583  bool ExpandBECount = canExpandBackedgeTakenCount(L, BackedgeTakenCount);
584  if (ExpandBECount) {
585    // If we have a known trip count and a single exit block, we'll be
586    // rewriting the loop exit test condition below, which requires a
587    // canonical induction variable.
588    NeedCannIV = true;
589    const Type *Ty = BackedgeTakenCount->getType();
590    if (!LargestType ||
591        SE->getTypeSizeInBits(Ty) >
592        SE->getTypeSizeInBits(LargestType))
593      LargestType = SE->getEffectiveSCEVType(Ty);
594  }
595  for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
596    NeedCannIV = true;
597    const Type *Ty =
598      SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
599    if (!LargestType ||
600        SE->getTypeSizeInBits(Ty) >
601          SE->getTypeSizeInBits(LargestType))
602      LargestType = Ty;
603  }
604
605  // Now that we know the largest of the induction variable expressions
606  // in this loop, insert a canonical induction variable of the largest size.
607  PHINode *IndVar = 0;
608  if (NeedCannIV) {
609    // Check to see if the loop already has any canonical-looking induction
610    // variables. If any are present and wider than the planned canonical
611    // induction variable, temporarily remove them, so that the Rewriter
612    // doesn't attempt to reuse them.
613    SmallVector<PHINode *, 2> OldCannIVs;
614    while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
615      if (SE->getTypeSizeInBits(OldCannIV->getType()) >
616          SE->getTypeSizeInBits(LargestType))
617        OldCannIV->removeFromParent();
618      else
619        break;
620      OldCannIVs.push_back(OldCannIV);
621    }
622
623    IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
624
625    ++NumInserted;
626    Changed = true;
627    DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
628
629    // Now that the official induction variable is established, reinsert
630    // any old canonical-looking variables after it so that the IR remains
631    // consistent. They will be deleted as part of the dead-PHI deletion at
632    // the end of the pass.
633    while (!OldCannIVs.empty()) {
634      PHINode *OldCannIV = OldCannIVs.pop_back_val();
635      OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
636    }
637  }
638
639  // If we have a trip count expression, rewrite the loop's exit condition
640  // using it.  We can currently only handle loops with a single exit.
641  ICmpInst *NewICmp = 0;
642  if (ExpandBECount) {
643    assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) &&
644           "canonical IV disrupted BackedgeTaken expansion");
645    assert(NeedCannIV &&
646           "LinearFunctionTestReplace requires a canonical induction variable");
647    NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
648                                        Rewriter);
649  }
650
651  // Rewrite IV-derived expressions.
652  RewriteIVExpressions(L, Rewriter);
653
654  // Clear the rewriter cache, because values that are in the rewriter's cache
655  // can be deleted in the loop below, causing the AssertingVH in the cache to
656  // trigger.
657  Rewriter.clear();
658
659  // Now that we're done iterating through lists, clean up any instructions
660  // which are now dead.
661  while (!DeadInsts.empty())
662    if (Instruction *Inst =
663          dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
664      RecursivelyDeleteTriviallyDeadInstructions(Inst);
665
666  // The Rewriter may not be used from this point on.
667
668  // Loop-invariant instructions in the preheader that aren't used in the
669  // loop may be sunk below the loop to reduce register pressure.
670  SinkUnusedInvariants(L);
671
672  // For completeness, inform IVUsers of the IV use in the newly-created
673  // loop exit test instruction.
674  if (NewICmp)
675    IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
676
677  // Clean up dead instructions.
678  Changed |= DeleteDeadPHIs(L->getHeader());
679  // Check a post-condition.
680  assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
681  return Changed;
682}
683
684// FIXME: It is an extremely bad idea to indvar substitute anything more
685// complex than affine induction variables.  Doing so will put expensive
686// polynomial evaluations inside of the loop, and the str reduction pass
687// currently can only reduce affine polynomials.  For now just disable
688// indvar subst on anything more complex than an affine addrec, unless
689// it can be expanded to a trivial value.
690static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
691  // Loop-invariant values are safe.
692  if (SE->isLoopInvariant(S, L)) return true;
693
694  // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
695  // to transform them into efficient code.
696  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
697    return AR->isAffine();
698
699  // An add is safe it all its operands are safe.
700  if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
701    for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
702         E = Commutative->op_end(); I != E; ++I)
703      if (!isSafe(*I, L, SE)) return false;
704    return true;
705  }
706
707  // A cast is safe if its operand is.
708  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
709    return isSafe(C->getOperand(), L, SE);
710
711  // A udiv is safe if its operands are.
712  if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
713    return isSafe(UD->getLHS(), L, SE) &&
714           isSafe(UD->getRHS(), L, SE);
715
716  // SCEVUnknown is always safe.
717  if (isa<SCEVUnknown>(S))
718    return true;
719
720  // Nothing else is safe.
721  return false;
722}
723
724void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
725  // Rewrite all induction variable expressions in terms of the canonical
726  // induction variable.
727  //
728  // If there were induction variables of other sizes or offsets, manually
729  // add the offsets to the primary induction variable and cast, avoiding
730  // the need for the code evaluation methods to insert induction variables
731  // of different sizes.
732  for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
733    Value *Op = UI->getOperandValToReplace();
734    const Type *UseTy = Op->getType();
735    Instruction *User = UI->getUser();
736
737    // Compute the final addrec to expand into code.
738    const SCEV *AR = IU->getReplacementExpr(*UI);
739
740    // Evaluate the expression out of the loop, if possible.
741    if (!L->contains(UI->getUser())) {
742      const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
743      if (SE->isLoopInvariant(ExitVal, L))
744        AR = ExitVal;
745    }
746
747    // FIXME: It is an extremely bad idea to indvar substitute anything more
748    // complex than affine induction variables.  Doing so will put expensive
749    // polynomial evaluations inside of the loop, and the str reduction pass
750    // currently can only reduce affine polynomials.  For now just disable
751    // indvar subst on anything more complex than an affine addrec, unless
752    // it can be expanded to a trivial value.
753    if (!isSafe(AR, L, SE))
754      continue;
755
756    // Determine the insertion point for this user. By default, insert
757    // immediately before the user. The SCEVExpander class will automatically
758    // hoist loop invariants out of the loop. For PHI nodes, there may be
759    // multiple uses, so compute the nearest common dominator for the
760    // incoming blocks.
761    Instruction *InsertPt = User;
762    if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
763      for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
764        if (PHI->getIncomingValue(i) == Op) {
765          if (InsertPt == User)
766            InsertPt = PHI->getIncomingBlock(i)->getTerminator();
767          else
768            InsertPt =
769              DT->findNearestCommonDominator(InsertPt->getParent(),
770                                             PHI->getIncomingBlock(i))
771                    ->getTerminator();
772        }
773
774    // Now expand it into actual Instructions and patch it into place.
775    Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
776
777    DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
778                 << "   into = " << *NewVal << "\n");
779
780    if (!isValidRewrite(Op, NewVal)) {
781      DeadInsts.push_back(NewVal);
782      continue;
783    }
784    // Inform ScalarEvolution that this value is changing. The change doesn't
785    // affect its value, but it does potentially affect which use lists the
786    // value will be on after the replacement, which affects ScalarEvolution's
787    // ability to walk use lists and drop dangling pointers when a value is
788    // deleted.
789    SE->forgetValue(User);
790
791    // Patch the new value into place.
792    if (Op->hasName())
793      NewVal->takeName(Op);
794    User->replaceUsesOfWith(Op, NewVal);
795    UI->setOperandValToReplace(NewVal);
796
797    ++NumRemoved;
798    Changed = true;
799
800    // The old value may be dead now.
801    DeadInsts.push_back(Op);
802  }
803}
804
805/// If there's a single exit block, sink any loop-invariant values that
806/// were defined in the preheader but not used inside the loop into the
807/// exit block to reduce register pressure in the loop.
808void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
809  BasicBlock *ExitBlock = L->getExitBlock();
810  if (!ExitBlock) return;
811
812  BasicBlock *Preheader = L->getLoopPreheader();
813  if (!Preheader) return;
814
815  Instruction *InsertPt = ExitBlock->getFirstNonPHI();
816  BasicBlock::iterator I = Preheader->getTerminator();
817  while (I != Preheader->begin()) {
818    --I;
819    // New instructions were inserted at the end of the preheader.
820    if (isa<PHINode>(I))
821      break;
822
823    // Don't move instructions which might have side effects, since the side
824    // effects need to complete before instructions inside the loop.  Also don't
825    // move instructions which might read memory, since the loop may modify
826    // memory. Note that it's okay if the instruction might have undefined
827    // behavior: LoopSimplify guarantees that the preheader dominates the exit
828    // block.
829    if (I->mayHaveSideEffects() || I->mayReadFromMemory())
830      continue;
831
832    // Skip debug info intrinsics.
833    if (isa<DbgInfoIntrinsic>(I))
834      continue;
835
836    // Don't sink static AllocaInsts out of the entry block, which would
837    // turn them into dynamic allocas!
838    if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
839      if (AI->isStaticAlloca())
840        continue;
841
842    // Determine if there is a use in or before the loop (direct or
843    // otherwise).
844    bool UsedInLoop = false;
845    for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
846         UI != UE; ++UI) {
847      User *U = *UI;
848      BasicBlock *UseBB = cast<Instruction>(U)->getParent();
849      if (PHINode *P = dyn_cast<PHINode>(U)) {
850        unsigned i =
851          PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
852        UseBB = P->getIncomingBlock(i);
853      }
854      if (UseBB == Preheader || L->contains(UseBB)) {
855        UsedInLoop = true;
856        break;
857      }
858    }
859
860    // If there is, the def must remain in the preheader.
861    if (UsedInLoop)
862      continue;
863
864    // Otherwise, sink it to the exit block.
865    Instruction *ToMove = I;
866    bool Done = false;
867
868    if (I != Preheader->begin()) {
869      // Skip debug info intrinsics.
870      do {
871        --I;
872      } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
873
874      if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
875        Done = true;
876    } else {
877      Done = true;
878    }
879
880    ToMove->moveBefore(InsertPt);
881    if (Done) break;
882    InsertPt = ToMove;
883  }
884}
885
886/// ConvertToSInt - Convert APF to an integer, if possible.
887static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
888  bool isExact = false;
889  if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
890    return false;
891  // See if we can convert this to an int64_t
892  uint64_t UIntVal;
893  if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
894                           &isExact) != APFloat::opOK || !isExact)
895    return false;
896  IntVal = UIntVal;
897  return true;
898}
899
900/// HandleFloatingPointIV - If the loop has floating induction variable
901/// then insert corresponding integer induction variable if possible.
902/// For example,
903/// for(double i = 0; i < 10000; ++i)
904///   bar(i)
905/// is converted into
906/// for(int i = 0; i < 10000; ++i)
907///   bar((double)i);
908///
909void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
910  unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
911  unsigned BackEdge     = IncomingEdge^1;
912
913  // Check incoming value.
914  ConstantFP *InitValueVal =
915    dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
916
917  int64_t InitValue;
918  if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
919    return;
920
921  // Check IV increment. Reject this PN if increment operation is not
922  // an add or increment value can not be represented by an integer.
923  BinaryOperator *Incr =
924    dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
925  if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
926
927  // If this is not an add of the PHI with a constantfp, or if the constant fp
928  // is not an integer, bail out.
929  ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
930  int64_t IncValue;
931  if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
932      !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
933    return;
934
935  // Check Incr uses. One user is PN and the other user is an exit condition
936  // used by the conditional terminator.
937  Value::use_iterator IncrUse = Incr->use_begin();
938  Instruction *U1 = cast<Instruction>(*IncrUse++);
939  if (IncrUse == Incr->use_end()) return;
940  Instruction *U2 = cast<Instruction>(*IncrUse++);
941  if (IncrUse != Incr->use_end()) return;
942
943  // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
944  // only used by a branch, we can't transform it.
945  FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
946  if (!Compare)
947    Compare = dyn_cast<FCmpInst>(U2);
948  if (Compare == 0 || !Compare->hasOneUse() ||
949      !isa<BranchInst>(Compare->use_back()))
950    return;
951
952  BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
953
954  // We need to verify that the branch actually controls the iteration count
955  // of the loop.  If not, the new IV can overflow and no one will notice.
956  // The branch block must be in the loop and one of the successors must be out
957  // of the loop.
958  assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
959  if (!L->contains(TheBr->getParent()) ||
960      (L->contains(TheBr->getSuccessor(0)) &&
961       L->contains(TheBr->getSuccessor(1))))
962    return;
963
964
965  // If it isn't a comparison with an integer-as-fp (the exit value), we can't
966  // transform it.
967  ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
968  int64_t ExitValue;
969  if (ExitValueVal == 0 ||
970      !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
971    return;
972
973  // Find new predicate for integer comparison.
974  CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
975  switch (Compare->getPredicate()) {
976  default: return;  // Unknown comparison.
977  case CmpInst::FCMP_OEQ:
978  case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
979  case CmpInst::FCMP_ONE:
980  case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
981  case CmpInst::FCMP_OGT:
982  case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
983  case CmpInst::FCMP_OGE:
984  case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
985  case CmpInst::FCMP_OLT:
986  case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
987  case CmpInst::FCMP_OLE:
988  case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
989  }
990
991  // We convert the floating point induction variable to a signed i32 value if
992  // we can.  This is only safe if the comparison will not overflow in a way
993  // that won't be trapped by the integer equivalent operations.  Check for this
994  // now.
995  // TODO: We could use i64 if it is native and the range requires it.
996
997  // The start/stride/exit values must all fit in signed i32.
998  if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
999    return;
1000
1001  // If not actually striding (add x, 0.0), avoid touching the code.
1002  if (IncValue == 0)
1003    return;
1004
1005  // Positive and negative strides have different safety conditions.
1006  if (IncValue > 0) {
1007    // If we have a positive stride, we require the init to be less than the
1008    // exit value and an equality or less than comparison.
1009    if (InitValue >= ExitValue ||
1010        NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1011      return;
1012
1013    uint32_t Range = uint32_t(ExitValue-InitValue);
1014    if (NewPred == CmpInst::ICMP_SLE) {
1015      // Normalize SLE -> SLT, check for infinite loop.
1016      if (++Range == 0) return;  // Range overflows.
1017    }
1018
1019    unsigned Leftover = Range % uint32_t(IncValue);
1020
1021    // If this is an equality comparison, we require that the strided value
1022    // exactly land on the exit value, otherwise the IV condition will wrap
1023    // around and do things the fp IV wouldn't.
1024    if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1025        Leftover != 0)
1026      return;
1027
1028    // If the stride would wrap around the i32 before exiting, we can't
1029    // transform the IV.
1030    if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1031      return;
1032
1033  } else {
1034    // If we have a negative stride, we require the init to be greater than the
1035    // exit value and an equality or greater than comparison.
1036    if (InitValue >= ExitValue ||
1037        NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1038      return;
1039
1040    uint32_t Range = uint32_t(InitValue-ExitValue);
1041    if (NewPred == CmpInst::ICMP_SGE) {
1042      // Normalize SGE -> SGT, check for infinite loop.
1043      if (++Range == 0) return;  // Range overflows.
1044    }
1045
1046    unsigned Leftover = Range % uint32_t(-IncValue);
1047
1048    // If this is an equality comparison, we require that the strided value
1049    // exactly land on the exit value, otherwise the IV condition will wrap
1050    // around and do things the fp IV wouldn't.
1051    if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1052        Leftover != 0)
1053      return;
1054
1055    // If the stride would wrap around the i32 before exiting, we can't
1056    // transform the IV.
1057    if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1058      return;
1059  }
1060
1061  const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
1062
1063  // Insert new integer induction variable.
1064  PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
1065  NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
1066                      PN->getIncomingBlock(IncomingEdge));
1067
1068  Value *NewAdd =
1069    BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
1070                              Incr->getName()+".int", Incr);
1071  NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
1072
1073  ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1074                                      ConstantInt::get(Int32Ty, ExitValue),
1075                                      Compare->getName());
1076
1077  // In the following deletions, PN may become dead and may be deleted.
1078  // Use a WeakVH to observe whether this happens.
1079  WeakVH WeakPH = PN;
1080
1081  // Delete the old floating point exit comparison.  The branch starts using the
1082  // new comparison.
1083  NewCompare->takeName(Compare);
1084  Compare->replaceAllUsesWith(NewCompare);
1085  RecursivelyDeleteTriviallyDeadInstructions(Compare);
1086
1087  // Delete the old floating point increment.
1088  Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1089  RecursivelyDeleteTriviallyDeadInstructions(Incr);
1090
1091  // If the FP induction variable still has uses, this is because something else
1092  // in the loop uses its value.  In order to canonicalize the induction
1093  // variable, we chose to eliminate the IV and rewrite it in terms of an
1094  // int->fp cast.
1095  //
1096  // We give preference to sitofp over uitofp because it is faster on most
1097  // platforms.
1098  if (WeakPH) {
1099    Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1100                                 PN->getParent()->getFirstNonPHI());
1101    PN->replaceAllUsesWith(Conv);
1102    RecursivelyDeleteTriviallyDeadInstructions(PN);
1103  }
1104
1105  // Add a new IVUsers entry for the newly-created integer PHI.
1106  IU->AddUsersIfInteresting(NewPHI);
1107}
1108