LLVM API Documentation

ScalarEvolutionExpander.cpp
Go to the documentation of this file.
00001 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the implementation of the scalar evolution expander,
00011 // which is used to generate the code corresponding to a given scalar evolution
00012 // expression.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/Analysis/LoopInfo.h"
00019 #include "llvm/Analysis/TargetTransformInfo.h"
00020 #include "llvm/IR/DataLayout.h"
00021 #include "llvm/IR/IntrinsicInst.h"
00022 #include "llvm/IR/LLVMContext.h"
00023 #include "llvm/Support/Debug.h"
00024 
00025 using namespace llvm;
00026 
00027 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
00028 /// reusing an existing cast if a suitable one exists, moving an existing
00029 /// cast if a suitable one exists but isn't in the right place, or
00030 /// creating a new one.
00031 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
00032                                        Instruction::CastOps Op,
00033                                        BasicBlock::iterator IP) {
00034   // This function must be called with the builder having a valid insertion
00035   // point. It doesn't need to be the actual IP where the uses of the returned
00036   // cast will be added, but it must dominate such IP.
00037   // We use this precondition to produce a cast that will dominate all its
00038   // uses. In particular, this is crucial for the case where the builder's
00039   // insertion point *is* the point where we were asked to put the cast.
00040   // Since we don't know the builder's insertion point is actually
00041   // where the uses will be added (only that it dominates it), we are
00042   // not allowed to move it.
00043   BasicBlock::iterator BIP = Builder.GetInsertPoint();
00044 
00045   Instruction *Ret = NULL;
00046 
00047   // Check to see if there is already a cast!
00048   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
00049        UI != E; ++UI) {
00050     User *U = *UI;
00051     if (U->getType() == Ty)
00052       if (CastInst *CI = dyn_cast<CastInst>(U))
00053         if (CI->getOpcode() == Op) {
00054           // If the cast isn't where we want it, create a new cast at IP.
00055           // Likewise, do not reuse a cast at BIP because it must dominate
00056           // instructions that might be inserted before BIP.
00057           if (BasicBlock::iterator(CI) != IP || BIP == IP) {
00058             // Create a new cast, and leave the old cast in place in case
00059             // it is being used as an insert point. Clear its operand
00060             // so that it doesn't hold anything live.
00061             Ret = CastInst::Create(Op, V, Ty, "", IP);
00062             Ret->takeName(CI);
00063             CI->replaceAllUsesWith(Ret);
00064             CI->setOperand(0, UndefValue::get(V->getType()));
00065             break;
00066           }
00067           Ret = CI;
00068           break;
00069         }
00070   }
00071 
00072   // Create a new cast.
00073   if (!Ret)
00074     Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
00075 
00076   // We assert at the end of the function since IP might point to an
00077   // instruction with different dominance properties than a cast
00078   // (an invoke for example) and not dominate BIP (but the cast does).
00079   assert(SE.DT->dominates(Ret, BIP));
00080 
00081   rememberInstruction(Ret);
00082   return Ret;
00083 }
00084 
00085 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
00086 /// which must be possible with a noop cast, doing what we can to share
00087 /// the casts.
00088 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
00089   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
00090   assert((Op == Instruction::BitCast ||
00091           Op == Instruction::PtrToInt ||
00092           Op == Instruction::IntToPtr) &&
00093          "InsertNoopCastOfTo cannot perform non-noop casts!");
00094   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
00095          "InsertNoopCastOfTo cannot change sizes!");
00096 
00097   // Short-circuit unnecessary bitcasts.
00098   if (Op == Instruction::BitCast) {
00099     if (V->getType() == Ty)
00100       return V;
00101     if (CastInst *CI = dyn_cast<CastInst>(V)) {
00102       if (CI->getOperand(0)->getType() == Ty)
00103         return CI->getOperand(0);
00104     }
00105   }
00106   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
00107   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
00108       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
00109     if (CastInst *CI = dyn_cast<CastInst>(V))
00110       if ((CI->getOpcode() == Instruction::PtrToInt ||
00111            CI->getOpcode() == Instruction::IntToPtr) &&
00112           SE.getTypeSizeInBits(CI->getType()) ==
00113           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
00114         return CI->getOperand(0);
00115     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00116       if ((CE->getOpcode() == Instruction::PtrToInt ||
00117            CE->getOpcode() == Instruction::IntToPtr) &&
00118           SE.getTypeSizeInBits(CE->getType()) ==
00119           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
00120         return CE->getOperand(0);
00121   }
00122 
00123   // Fold a cast of a constant.
00124   if (Constant *C = dyn_cast<Constant>(V))
00125     return ConstantExpr::getCast(Op, C, Ty);
00126 
00127   // Cast the argument at the beginning of the entry block, after
00128   // any bitcasts of other arguments.
00129   if (Argument *A = dyn_cast<Argument>(V)) {
00130     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
00131     while ((isa<BitCastInst>(IP) &&
00132             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
00133             cast<BitCastInst>(IP)->getOperand(0) != A) ||
00134            isa<DbgInfoIntrinsic>(IP) ||
00135            isa<LandingPadInst>(IP))
00136       ++IP;
00137     return ReuseOrCreateCast(A, Ty, Op, IP);
00138   }
00139 
00140   // Cast the instruction immediately after the instruction.
00141   Instruction *I = cast<Instruction>(V);
00142   BasicBlock::iterator IP = I; ++IP;
00143   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
00144     IP = II->getNormalDest()->begin();
00145   while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
00146     ++IP;
00147   return ReuseOrCreateCast(I, Ty, Op, IP);
00148 }
00149 
00150 /// InsertBinop - Insert the specified binary operator, doing a small amount
00151 /// of work to avoid inserting an obviously redundant operation.
00152 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
00153                                  Value *LHS, Value *RHS) {
00154   // Fold a binop with constant operands.
00155   if (Constant *CLHS = dyn_cast<Constant>(LHS))
00156     if (Constant *CRHS = dyn_cast<Constant>(RHS))
00157       return ConstantExpr::get(Opcode, CLHS, CRHS);
00158 
00159   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
00160   unsigned ScanLimit = 6;
00161   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
00162   // Scanning starts from the last instruction before the insertion point.
00163   BasicBlock::iterator IP = Builder.GetInsertPoint();
00164   if (IP != BlockBegin) {
00165     --IP;
00166     for (; ScanLimit; --IP, --ScanLimit) {
00167       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
00168       // generated code.
00169       if (isa<DbgInfoIntrinsic>(IP))
00170         ScanLimit++;
00171       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
00172           IP->getOperand(1) == RHS)
00173         return IP;
00174       if (IP == BlockBegin) break;
00175     }
00176   }
00177 
00178   // Save the original insertion point so we can restore it when we're done.
00179   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
00180   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
00181 
00182   // Move the insertion point out of as many loops as we can.
00183   while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
00184     if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
00185     BasicBlock *Preheader = L->getLoopPreheader();
00186     if (!Preheader) break;
00187 
00188     // Ok, move up a level.
00189     Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
00190   }
00191 
00192   // If we haven't found this binop, insert it.
00193   Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
00194   BO->setDebugLoc(SaveInsertPt->getDebugLoc());
00195   rememberInstruction(BO);
00196 
00197   // Restore the original insert point.
00198   if (SaveInsertBB)
00199     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
00200 
00201   return BO;
00202 }
00203 
00204 /// FactorOutConstant - Test if S is divisible by Factor, using signed
00205 /// division. If so, update S with Factor divided out and return true.
00206 /// S need not be evenly divisible if a reasonable remainder can be
00207 /// computed.
00208 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
00209 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
00210 /// check to see if the divide was folded.
00211 static bool FactorOutConstant(const SCEV *&S,
00212                               const SCEV *&Remainder,
00213                               const SCEV *Factor,
00214                               ScalarEvolution &SE,
00215                               const DataLayout *TD) {
00216   // Everything is divisible by one.
00217   if (Factor->isOne())
00218     return true;
00219 
00220   // x/x == 1.
00221   if (S == Factor) {
00222     S = SE.getConstant(S->getType(), 1);
00223     return true;
00224   }
00225 
00226   // For a Constant, check for a multiple of the given factor.
00227   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
00228     // 0/x == 0.
00229     if (C->isZero())
00230       return true;
00231     // Check for divisibility.
00232     if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
00233       ConstantInt *CI =
00234         ConstantInt::get(SE.getContext(),
00235                          C->getValue()->getValue().sdiv(
00236                                                    FC->getValue()->getValue()));
00237       // If the quotient is zero and the remainder is non-zero, reject
00238       // the value at this scale. It will be considered for subsequent
00239       // smaller scales.
00240       if (!CI->isZero()) {
00241         const SCEV *Div = SE.getConstant(CI);
00242         S = Div;
00243         Remainder =
00244           SE.getAddExpr(Remainder,
00245                         SE.getConstant(C->getValue()->getValue().srem(
00246                                                   FC->getValue()->getValue())));
00247         return true;
00248       }
00249     }
00250   }
00251 
00252   // In a Mul, check if there is a constant operand which is a multiple
00253   // of the given factor.
00254   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
00255     if (TD) {
00256       // With DataLayout, the size is known. Check if there is a constant
00257       // operand which is a multiple of the given factor. If so, we can
00258       // factor it.
00259       const SCEVConstant *FC = cast<SCEVConstant>(Factor);
00260       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
00261         if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
00262           SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
00263           NewMulOps[0] =
00264             SE.getConstant(C->getValue()->getValue().sdiv(
00265                                                    FC->getValue()->getValue()));
00266           S = SE.getMulExpr(NewMulOps);
00267           return true;
00268         }
00269     } else {
00270       // Without DataLayout, check if Factor can be factored out of any of the
00271       // Mul's operands. If so, we can just remove it.
00272       for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
00273         const SCEV *SOp = M->getOperand(i);
00274         const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
00275         if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
00276             Remainder->isZero()) {
00277           SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
00278           NewMulOps[i] = SOp;
00279           S = SE.getMulExpr(NewMulOps);
00280           return true;
00281         }
00282       }
00283     }
00284   }
00285 
00286   // In an AddRec, check if both start and step are divisible.
00287   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
00288     const SCEV *Step = A->getStepRecurrence(SE);
00289     const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
00290     if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
00291       return false;
00292     if (!StepRem->isZero())
00293       return false;
00294     const SCEV *Start = A->getStart();
00295     if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
00296       return false;
00297     // FIXME: can use A->getNoWrapFlags(FlagNW)
00298     S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
00299     return true;
00300   }
00301 
00302   return false;
00303 }
00304 
00305 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
00306 /// is the number of SCEVAddRecExprs present, which are kept at the end of
00307 /// the list.
00308 ///
00309 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
00310                                 Type *Ty,
00311                                 ScalarEvolution &SE) {
00312   unsigned NumAddRecs = 0;
00313   for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
00314     ++NumAddRecs;
00315   // Group Ops into non-addrecs and addrecs.
00316   SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
00317   SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
00318   // Let ScalarEvolution sort and simplify the non-addrecs list.
00319   const SCEV *Sum = NoAddRecs.empty() ?
00320                     SE.getConstant(Ty, 0) :
00321                     SE.getAddExpr(NoAddRecs);
00322   // If it returned an add, use the operands. Otherwise it simplified
00323   // the sum into a single value, so just use that.
00324   Ops.clear();
00325   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
00326     Ops.append(Add->op_begin(), Add->op_end());
00327   else if (!Sum->isZero())
00328     Ops.push_back(Sum);
00329   // Then append the addrecs.
00330   Ops.append(AddRecs.begin(), AddRecs.end());
00331 }
00332 
00333 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
00334 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
00335 /// This helps expose more opportunities for folding parts of the expressions
00336 /// into GEP indices.
00337 ///
00338 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
00339                          Type *Ty,
00340                          ScalarEvolution &SE) {
00341   // Find the addrecs.
00342   SmallVector<const SCEV *, 8> AddRecs;
00343   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
00344     while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
00345       const SCEV *Start = A->getStart();
00346       if (Start->isZero()) break;
00347       const SCEV *Zero = SE.getConstant(Ty, 0);
00348       AddRecs.push_back(SE.getAddRecExpr(Zero,
00349                                          A->getStepRecurrence(SE),
00350                                          A->getLoop(),
00351                                          // FIXME: A->getNoWrapFlags(FlagNW)
00352                                          SCEV::FlagAnyWrap));
00353       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
00354         Ops[i] = Zero;
00355         Ops.append(Add->op_begin(), Add->op_end());
00356         e += Add->getNumOperands();
00357       } else {
00358         Ops[i] = Start;
00359       }
00360     }
00361   if (!AddRecs.empty()) {
00362     // Add the addrecs onto the end of the list.
00363     Ops.append(AddRecs.begin(), AddRecs.end());
00364     // Resort the operand list, moving any constants to the front.
00365     SimplifyAddOperands(Ops, Ty, SE);
00366   }
00367 }
00368 
00369 /// expandAddToGEP - Expand an addition expression with a pointer type into
00370 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
00371 /// BasicAliasAnalysis and other passes analyze the result. See the rules
00372 /// for getelementptr vs. inttoptr in
00373 /// http://llvm.org/docs/LangRef.html#pointeraliasing
00374 /// for details.
00375 ///
00376 /// Design note: The correctness of using getelementptr here depends on
00377 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
00378 /// they may introduce pointer arithmetic which may not be safely converted
00379 /// into getelementptr.
00380 ///
00381 /// Design note: It might seem desirable for this function to be more
00382 /// loop-aware. If some of the indices are loop-invariant while others
00383 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
00384 /// loop-invariant portions of the overall computation outside the loop.
00385 /// However, there are a few reasons this is not done here. Hoisting simple
00386 /// arithmetic is a low-level optimization that often isn't very
00387 /// important until late in the optimization process. In fact, passes
00388 /// like InstructionCombining will combine GEPs, even if it means
00389 /// pushing loop-invariant computation down into loops, so even if the
00390 /// GEPs were split here, the work would quickly be undone. The
00391 /// LoopStrengthReduction pass, which is usually run quite late (and
00392 /// after the last InstructionCombining pass), takes care of hoisting
00393 /// loop-invariant portions of expressions, after considering what
00394 /// can be folded using target addressing modes.
00395 ///
00396 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
00397                                     const SCEV *const *op_end,
00398                                     PointerType *PTy,
00399                                     Type *Ty,
00400                                     Value *V) {
00401   Type *ElTy = PTy->getElementType();
00402   SmallVector<Value *, 4> GepIndices;
00403   SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
00404   bool AnyNonZeroIndices = false;
00405 
00406   // Split AddRecs up into parts as either of the parts may be usable
00407   // without the other.
00408   SplitAddRecs(Ops, Ty, SE);
00409 
00410   // Descend down the pointer's type and attempt to convert the other
00411   // operands into GEP indices, at each level. The first index in a GEP
00412   // indexes into the array implied by the pointer operand; the rest of
00413   // the indices index into the element or field type selected by the
00414   // preceding index.
00415   for (;;) {
00416     // If the scale size is not 0, attempt to factor out a scale for
00417     // array indexing.
00418     SmallVector<const SCEV *, 8> ScaledOps;
00419     if (ElTy->isSized()) {
00420       const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
00421       if (!ElSize->isZero()) {
00422         SmallVector<const SCEV *, 8> NewOps;
00423         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00424           const SCEV *Op = Ops[i];
00425           const SCEV *Remainder = SE.getConstant(Ty, 0);
00426           if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
00427             // Op now has ElSize factored out.
00428             ScaledOps.push_back(Op);
00429             if (!Remainder->isZero())
00430               NewOps.push_back(Remainder);
00431             AnyNonZeroIndices = true;
00432           } else {
00433             // The operand was not divisible, so add it to the list of operands
00434             // we'll scan next iteration.
00435             NewOps.push_back(Ops[i]);
00436           }
00437         }
00438         // If we made any changes, update Ops.
00439         if (!ScaledOps.empty()) {
00440           Ops = NewOps;
00441           SimplifyAddOperands(Ops, Ty, SE);
00442         }
00443       }
00444     }
00445 
00446     // Record the scaled array index for this level of the type. If
00447     // we didn't find any operands that could be factored, tentatively
00448     // assume that element zero was selected (since the zero offset
00449     // would obviously be folded away).
00450     Value *Scaled = ScaledOps.empty() ?
00451                     Constant::getNullValue(Ty) :
00452                     expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
00453     GepIndices.push_back(Scaled);
00454 
00455     // Collect struct field index operands.
00456     while (StructType *STy = dyn_cast<StructType>(ElTy)) {
00457       bool FoundFieldNo = false;
00458       // An empty struct has no fields.
00459       if (STy->getNumElements() == 0) break;
00460       if (SE.TD) {
00461         // With DataLayout, field offsets are known. See if a constant offset
00462         // falls within any of the struct fields.
00463         if (Ops.empty()) break;
00464         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
00465           if (SE.getTypeSizeInBits(C->getType()) <= 64) {
00466             const StructLayout &SL = *SE.TD->getStructLayout(STy);
00467             uint64_t FullOffset = C->getValue()->getZExtValue();
00468             if (FullOffset < SL.getSizeInBytes()) {
00469               unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
00470               GepIndices.push_back(
00471                   ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
00472               ElTy = STy->getTypeAtIndex(ElIdx);
00473               Ops[0] =
00474                 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
00475               AnyNonZeroIndices = true;
00476               FoundFieldNo = true;
00477             }
00478           }
00479       } else {
00480         // Without DataLayout, just check for an offsetof expression of the
00481         // appropriate struct type.
00482         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
00483           if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
00484             Type *CTy;
00485             Constant *FieldNo;
00486             if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
00487               GepIndices.push_back(FieldNo);
00488               ElTy =
00489                 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
00490               Ops[i] = SE.getConstant(Ty, 0);
00491               AnyNonZeroIndices = true;
00492               FoundFieldNo = true;
00493               break;
00494             }
00495           }
00496       }
00497       // If no struct field offsets were found, tentatively assume that
00498       // field zero was selected (since the zero offset would obviously
00499       // be folded away).
00500       if (!FoundFieldNo) {
00501         ElTy = STy->getTypeAtIndex(0u);
00502         GepIndices.push_back(
00503           Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
00504       }
00505     }
00506 
00507     if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
00508       ElTy = ATy->getElementType();
00509     else
00510       break;
00511   }
00512 
00513   // If none of the operands were convertible to proper GEP indices, cast
00514   // the base to i8* and do an ugly getelementptr with that. It's still
00515   // better than ptrtoint+arithmetic+inttoptr at least.
00516   if (!AnyNonZeroIndices) {
00517     // Cast the base to i8*.
00518     V = InsertNoopCastOfTo(V,
00519        Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
00520 
00521     assert(!isa<Instruction>(V) ||
00522            SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
00523 
00524     // Expand the operands for a plain byte offset.
00525     Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
00526 
00527     // Fold a GEP with constant operands.
00528     if (Constant *CLHS = dyn_cast<Constant>(V))
00529       if (Constant *CRHS = dyn_cast<Constant>(Idx))
00530         return ConstantExpr::getGetElementPtr(CLHS, CRHS);
00531 
00532     // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
00533     unsigned ScanLimit = 6;
00534     BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
00535     // Scanning starts from the last instruction before the insertion point.
00536     BasicBlock::iterator IP = Builder.GetInsertPoint();
00537     if (IP != BlockBegin) {
00538       --IP;
00539       for (; ScanLimit; --IP, --ScanLimit) {
00540         // Don't count dbg.value against the ScanLimit, to avoid perturbing the
00541         // generated code.
00542         if (isa<DbgInfoIntrinsic>(IP))
00543           ScanLimit++;
00544         if (IP->getOpcode() == Instruction::GetElementPtr &&
00545             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
00546           return IP;
00547         if (IP == BlockBegin) break;
00548       }
00549     }
00550 
00551     // Save the original insertion point so we can restore it when we're done.
00552     BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
00553     BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
00554 
00555     // Move the insertion point out of as many loops as we can.
00556     while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
00557       if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
00558       BasicBlock *Preheader = L->getLoopPreheader();
00559       if (!Preheader) break;
00560 
00561       // Ok, move up a level.
00562       Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
00563     }
00564 
00565     // Emit a GEP.
00566     Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
00567     rememberInstruction(GEP);
00568 
00569     // Restore the original insert point.
00570     if (SaveInsertBB)
00571       restoreInsertPoint(SaveInsertBB, SaveInsertPt);
00572 
00573     return GEP;
00574   }
00575 
00576   // Save the original insertion point so we can restore it when we're done.
00577   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
00578   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
00579 
00580   // Move the insertion point out of as many loops as we can.
00581   while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
00582     if (!L->isLoopInvariant(V)) break;
00583 
00584     bool AnyIndexNotLoopInvariant = false;
00585     for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
00586          E = GepIndices.end(); I != E; ++I)
00587       if (!L->isLoopInvariant(*I)) {
00588         AnyIndexNotLoopInvariant = true;
00589         break;
00590       }
00591     if (AnyIndexNotLoopInvariant)
00592       break;
00593 
00594     BasicBlock *Preheader = L->getLoopPreheader();
00595     if (!Preheader) break;
00596 
00597     // Ok, move up a level.
00598     Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
00599   }
00600 
00601   // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
00602   // because ScalarEvolution may have changed the address arithmetic to
00603   // compute a value which is beyond the end of the allocated object.
00604   Value *Casted = V;
00605   if (V->getType() != PTy)
00606     Casted = InsertNoopCastOfTo(Casted, PTy);
00607   Value *GEP = Builder.CreateGEP(Casted,
00608                                  GepIndices,
00609                                  "scevgep");
00610   Ops.push_back(SE.getUnknown(GEP));
00611   rememberInstruction(GEP);
00612 
00613   // Restore the original insert point.
00614   if (SaveInsertBB)
00615     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
00616 
00617   return expand(SE.getAddExpr(Ops));
00618 }
00619 
00620 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
00621 /// SCEV expansion. If they are nested, this is the most nested. If they are
00622 /// neighboring, pick the later.
00623 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
00624                                         DominatorTree &DT) {
00625   if (!A) return B;
00626   if (!B) return A;
00627   if (A->contains(B)) return B;
00628   if (B->contains(A)) return A;
00629   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
00630   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
00631   return A; // Arbitrarily break the tie.
00632 }
00633 
00634 /// getRelevantLoop - Get the most relevant loop associated with the given
00635 /// expression, according to PickMostRelevantLoop.
00636 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
00637   // Test whether we've already computed the most relevant loop for this SCEV.
00638   std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
00639     RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
00640   if (!Pair.second)
00641     return Pair.first->second;
00642 
00643   if (isa<SCEVConstant>(S))
00644     // A constant has no relevant loops.
00645     return 0;
00646   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
00647     if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
00648       return Pair.first->second = SE.LI->getLoopFor(I->getParent());
00649     // A non-instruction has no relevant loops.
00650     return 0;
00651   }
00652   if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
00653     const Loop *L = 0;
00654     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
00655       L = AR->getLoop();
00656     for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
00657          I != E; ++I)
00658       L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
00659     return RelevantLoops[N] = L;
00660   }
00661   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
00662     const Loop *Result = getRelevantLoop(C->getOperand());
00663     return RelevantLoops[C] = Result;
00664   }
00665   if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
00666     const Loop *Result =
00667       PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
00668                            getRelevantLoop(D->getRHS()),
00669                            *SE.DT);
00670     return RelevantLoops[D] = Result;
00671   }
00672   llvm_unreachable("Unexpected SCEV type!");
00673 }
00674 
00675 namespace {
00676 
00677 /// LoopCompare - Compare loops by PickMostRelevantLoop.
00678 class LoopCompare {
00679   DominatorTree &DT;
00680 public:
00681   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
00682 
00683   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
00684                   std::pair<const Loop *, const SCEV *> RHS) const {
00685     // Keep pointer operands sorted at the end.
00686     if (LHS.second->getType()->isPointerTy() !=
00687         RHS.second->getType()->isPointerTy())
00688       return LHS.second->getType()->isPointerTy();
00689 
00690     // Compare loops with PickMostRelevantLoop.
00691     if (LHS.first != RHS.first)
00692       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
00693 
00694     // If one operand is a non-constant negative and the other is not,
00695     // put the non-constant negative on the right so that a sub can
00696     // be used instead of a negate and add.
00697     if (LHS.second->isNonConstantNegative()) {
00698       if (!RHS.second->isNonConstantNegative())
00699         return false;
00700     } else if (RHS.second->isNonConstantNegative())
00701       return true;
00702 
00703     // Otherwise they are equivalent according to this comparison.
00704     return false;
00705   }
00706 };
00707 
00708 }
00709 
00710 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
00711   Type *Ty = SE.getEffectiveSCEVType(S->getType());
00712 
00713   // Collect all the add operands in a loop, along with their associated loops.
00714   // Iterate in reverse so that constants are emitted last, all else equal, and
00715   // so that pointer operands are inserted first, which the code below relies on
00716   // to form more involved GEPs.
00717   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
00718   for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
00719        E(S->op_begin()); I != E; ++I)
00720     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
00721 
00722   // Sort by loop. Use a stable sort so that constants follow non-constants and
00723   // pointer operands precede non-pointer operands.
00724   std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
00725 
00726   // Emit instructions to add all the operands. Hoist as much as possible
00727   // out of loops, and form meaningful getelementptrs where possible.
00728   Value *Sum = 0;
00729   for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
00730        I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
00731     const Loop *CurLoop = I->first;
00732     const SCEV *Op = I->second;
00733     if (!Sum) {
00734       // This is the first operand. Just expand it.
00735       Sum = expand(Op);
00736       ++I;
00737     } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
00738       // The running sum expression is a pointer. Try to form a getelementptr
00739       // at this level with that as the base.
00740       SmallVector<const SCEV *, 4> NewOps;
00741       for (; I != E && I->first == CurLoop; ++I) {
00742         // If the operand is SCEVUnknown and not instructions, peek through
00743         // it, to enable more of it to be folded into the GEP.
00744         const SCEV *X = I->second;
00745         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
00746           if (!isa<Instruction>(U->getValue()))
00747             X = SE.getSCEV(U->getValue());
00748         NewOps.push_back(X);
00749       }
00750       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
00751     } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
00752       // The running sum is an integer, and there's a pointer at this level.
00753       // Try to form a getelementptr. If the running sum is instructions,
00754       // use a SCEVUnknown to avoid re-analyzing them.
00755       SmallVector<const SCEV *, 4> NewOps;
00756       NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
00757                                                SE.getSCEV(Sum));
00758       for (++I; I != E && I->first == CurLoop; ++I)
00759         NewOps.push_back(I->second);
00760       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
00761     } else if (Op->isNonConstantNegative()) {
00762       // Instead of doing a negate and add, just do a subtract.
00763       Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
00764       Sum = InsertNoopCastOfTo(Sum, Ty);
00765       Sum = InsertBinop(Instruction::Sub, Sum, W);
00766       ++I;
00767     } else {
00768       // A simple add.
00769       Value *W = expandCodeFor(Op, Ty);
00770       Sum = InsertNoopCastOfTo(Sum, Ty);
00771       // Canonicalize a constant to the RHS.
00772       if (isa<Constant>(Sum)) std::swap(Sum, W);
00773       Sum = InsertBinop(Instruction::Add, Sum, W);
00774       ++I;
00775     }
00776   }
00777 
00778   return Sum;
00779 }
00780 
00781 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
00782   Type *Ty = SE.getEffectiveSCEVType(S->getType());
00783 
00784   // Collect all the mul operands in a loop, along with their associated loops.
00785   // Iterate in reverse so that constants are emitted last, all else equal.
00786   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
00787   for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
00788        E(S->op_begin()); I != E; ++I)
00789     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
00790 
00791   // Sort by loop. Use a stable sort so that constants follow non-constants.
00792   std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
00793 
00794   // Emit instructions to mul all the operands. Hoist as much as possible
00795   // out of loops.
00796   Value *Prod = 0;
00797   for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
00798        I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
00799     const SCEV *Op = I->second;
00800     if (!Prod) {
00801       // This is the first operand. Just expand it.
00802       Prod = expand(Op);
00803       ++I;
00804     } else if (Op->isAllOnesValue()) {
00805       // Instead of doing a multiply by negative one, just do a negate.
00806       Prod = InsertNoopCastOfTo(Prod, Ty);
00807       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
00808       ++I;
00809     } else {
00810       // A simple mul.
00811       Value *W = expandCodeFor(Op, Ty);
00812       Prod = InsertNoopCastOfTo(Prod, Ty);
00813       // Canonicalize a constant to the RHS.
00814       if (isa<Constant>(Prod)) std::swap(Prod, W);
00815       Prod = InsertBinop(Instruction::Mul, Prod, W);
00816       ++I;
00817     }
00818   }
00819 
00820   return Prod;
00821 }
00822 
00823 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
00824   Type *Ty = SE.getEffectiveSCEVType(S->getType());
00825 
00826   Value *LHS = expandCodeFor(S->getLHS(), Ty);
00827   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
00828     const APInt &RHS = SC->getValue()->getValue();
00829     if (RHS.isPowerOf2())
00830       return InsertBinop(Instruction::LShr, LHS,
00831                          ConstantInt::get(Ty, RHS.logBase2()));
00832   }
00833 
00834   Value *RHS = expandCodeFor(S->getRHS(), Ty);
00835   return InsertBinop(Instruction::UDiv, LHS, RHS);
00836 }
00837 
00838 /// Move parts of Base into Rest to leave Base with the minimal
00839 /// expression that provides a pointer operand suitable for a
00840 /// GEP expansion.
00841 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
00842                               ScalarEvolution &SE) {
00843   while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
00844     Base = A->getStart();
00845     Rest = SE.getAddExpr(Rest,
00846                          SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
00847                                           A->getStepRecurrence(SE),
00848                                           A->getLoop(),
00849                                           // FIXME: A->getNoWrapFlags(FlagNW)
00850                                           SCEV::FlagAnyWrap));
00851   }
00852   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
00853     Base = A->getOperand(A->getNumOperands()-1);
00854     SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
00855     NewAddOps.back() = Rest;
00856     Rest = SE.getAddExpr(NewAddOps);
00857     ExposePointerBase(Base, Rest, SE);
00858   }
00859 }
00860 
00861 /// Determine if this is a well-behaved chain of instructions leading back to
00862 /// the PHI. If so, it may be reused by expanded expressions.
00863 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
00864                                          const Loop *L) {
00865   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
00866       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
00867     return false;
00868   // If any of the operands don't dominate the insert position, bail.
00869   // Addrec operands are always loop-invariant, so this can only happen
00870   // if there are instructions which haven't been hoisted.
00871   if (L == IVIncInsertLoop) {
00872     for (User::op_iterator OI = IncV->op_begin()+1,
00873            OE = IncV->op_end(); OI != OE; ++OI)
00874       if (Instruction *OInst = dyn_cast<Instruction>(OI))
00875         if (!SE.DT->dominates(OInst, IVIncInsertPos))
00876           return false;
00877   }
00878   // Advance to the next instruction.
00879   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
00880   if (!IncV)
00881     return false;
00882 
00883   if (IncV->mayHaveSideEffects())
00884     return false;
00885 
00886   if (IncV != PN)
00887     return true;
00888 
00889   return isNormalAddRecExprPHI(PN, IncV, L);
00890 }
00891 
00892 /// getIVIncOperand returns an induction variable increment's induction
00893 /// variable operand.
00894 ///
00895 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
00896 /// operands dominate InsertPos.
00897 ///
00898 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
00899 /// simple patterns generated by getAddRecExprPHILiterally and
00900 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
00901 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
00902                                            Instruction *InsertPos,
00903                                            bool allowScale) {
00904   if (IncV == InsertPos)
00905     return NULL;
00906 
00907   switch (IncV->getOpcode()) {
00908   default:
00909     return NULL;
00910   // Check for a simple Add/Sub or GEP of a loop invariant step.
00911   case Instruction::Add:
00912   case Instruction::Sub: {
00913     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
00914     if (!OInst || SE.DT->dominates(OInst, InsertPos))
00915       return dyn_cast<Instruction>(IncV->getOperand(0));
00916     return NULL;
00917   }
00918   case Instruction::BitCast:
00919     return dyn_cast<Instruction>(IncV->getOperand(0));
00920   case Instruction::GetElementPtr:
00921     for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
00922          I != E; ++I) {
00923       if (isa<Constant>(*I))
00924         continue;
00925       if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
00926         if (!SE.DT->dominates(OInst, InsertPos))
00927           return NULL;
00928       }
00929       if (allowScale) {
00930         // allow any kind of GEP as long as it can be hoisted.
00931         continue;
00932       }
00933       // This must be a pointer addition of constants (pretty), which is already
00934       // handled, or some number of address-size elements (ugly). Ugly geps
00935       // have 2 operands. i1* is used by the expander to represent an
00936       // address-size element.
00937       if (IncV->getNumOperands() != 2)
00938         return NULL;
00939       unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
00940       if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
00941           && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
00942         return NULL;
00943       break;
00944     }
00945     return dyn_cast<Instruction>(IncV->getOperand(0));
00946   }
00947 }
00948 
00949 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
00950 /// it available to other uses in this loop. Recursively hoist any operands,
00951 /// until we reach a value that dominates InsertPos.
00952 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
00953   if (SE.DT->dominates(IncV, InsertPos))
00954       return true;
00955 
00956   // InsertPos must itself dominate IncV so that IncV's new position satisfies
00957   // its existing users.
00958   if (isa<PHINode>(InsertPos)
00959       || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
00960     return false;
00961 
00962   // Check that the chain of IV operands leading back to Phi can be hoisted.
00963   SmallVector<Instruction*, 4> IVIncs;
00964   for(;;) {
00965     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
00966     if (!Oper)
00967       return false;
00968     // IncV is safe to hoist.
00969     IVIncs.push_back(IncV);
00970     IncV = Oper;
00971     if (SE.DT->dominates(IncV, InsertPos))
00972       break;
00973   }
00974   for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
00975          E = IVIncs.rend(); I != E; ++I) {
00976     (*I)->moveBefore(InsertPos);
00977   }
00978   return true;
00979 }
00980 
00981 /// Determine if this cyclic phi is in a form that would have been generated by
00982 /// LSR. We don't care if the phi was actually expanded in this pass, as long
00983 /// as it is in a low-cost form, for example, no implied multiplication. This
00984 /// should match any patterns generated by getAddRecExprPHILiterally and
00985 /// expandAddtoGEP.
00986 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
00987                                            const Loop *L) {
00988   for(Instruction *IVOper = IncV;
00989       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
00990                                 /*allowScale=*/false));) {
00991     if (IVOper == PN)
00992       return true;
00993   }
00994   return false;
00995 }
00996 
00997 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
00998 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
00999 /// need to materialize IV increments elsewhere to handle difficult situations.
01000 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
01001                                  Type *ExpandTy, Type *IntTy,
01002                                  bool useSubtract) {
01003   Value *IncV;
01004   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
01005   if (ExpandTy->isPointerTy()) {
01006     PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
01007     // If the step isn't constant, don't use an implicitly scaled GEP, because
01008     // that would require a multiply inside the loop.
01009     if (!isa<ConstantInt>(StepV))
01010       GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
01011                                   GEPPtrTy->getAddressSpace());
01012     const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
01013     IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
01014     if (IncV->getType() != PN->getType()) {
01015       IncV = Builder.CreateBitCast(IncV, PN->getType());
01016       rememberInstruction(IncV);
01017     }
01018   } else {
01019     IncV = useSubtract ?
01020       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
01021       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
01022     rememberInstruction(IncV);
01023   }
01024   return IncV;
01025 }
01026 
01027 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
01028 /// the base addrec, which is the addrec without any non-loop-dominating
01029 /// values, and return the PHI.
01030 PHINode *
01031 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
01032                                         const Loop *L,
01033                                         Type *ExpandTy,
01034                                         Type *IntTy) {
01035   assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
01036 
01037   // Reuse a previously-inserted PHI, if present.
01038   BasicBlock *LatchBlock = L->getLoopLatch();
01039   if (LatchBlock) {
01040     for (BasicBlock::iterator I = L->getHeader()->begin();
01041          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
01042       if (!SE.isSCEVable(PN->getType()) ||
01043           (SE.getEffectiveSCEVType(PN->getType()) !=
01044            SE.getEffectiveSCEVType(Normalized->getType())) ||
01045           SE.getSCEV(PN) != Normalized)
01046         continue;
01047 
01048       Instruction *IncV =
01049         cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
01050 
01051       if (LSRMode) {
01052         if (!isExpandedAddRecExprPHI(PN, IncV, L))
01053           continue;
01054         if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
01055           continue;
01056       }
01057       else {
01058         if (!isNormalAddRecExprPHI(PN, IncV, L))
01059           continue;
01060         if (L == IVIncInsertLoop)
01061           do {
01062             if (SE.DT->dominates(IncV, IVIncInsertPos))
01063               break;
01064             // Make sure the increment is where we want it. But don't move it
01065             // down past a potential existing post-inc user.
01066             IncV->moveBefore(IVIncInsertPos);
01067             IVIncInsertPos = IncV;
01068             IncV = cast<Instruction>(IncV->getOperand(0));
01069           } while (IncV != PN);
01070       }
01071       // Ok, the add recurrence looks usable.
01072       // Remember this PHI, even in post-inc mode.
01073       InsertedValues.insert(PN);
01074       // Remember the increment.
01075       rememberInstruction(IncV);
01076       return PN;
01077     }
01078   }
01079 
01080   // Save the original insertion point so we can restore it when we're done.
01081   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
01082   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
01083 
01084   // Another AddRec may need to be recursively expanded below. For example, if
01085   // this AddRec is quadratic, the StepV may itself be an AddRec in this
01086   // loop. Remove this loop from the PostIncLoops set before expanding such
01087   // AddRecs. Otherwise, we cannot find a valid position for the step
01088   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
01089   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
01090   // so it's not worth implementing SmallPtrSet::swap.
01091   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
01092   PostIncLoops.clear();
01093 
01094   // Expand code for the start value.
01095   Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
01096                                 L->getHeader()->begin());
01097 
01098   // StartV must be hoisted into L's preheader to dominate the new phi.
01099   assert(!isa<Instruction>(StartV) ||
01100          SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
01101                                   L->getHeader()));
01102 
01103   // Expand code for the step value. Do this before creating the PHI so that PHI
01104   // reuse code doesn't see an incomplete PHI.
01105   const SCEV *Step = Normalized->getStepRecurrence(SE);
01106   // If the stride is negative, insert a sub instead of an add for the increment
01107   // (unless it's a constant, because subtracts of constants are canonicalized
01108   // to adds).
01109   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
01110   if (useSubtract)
01111     Step = SE.getNegativeSCEV(Step);
01112   // Expand the step somewhere that dominates the loop header.
01113   Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
01114 
01115   // Create the PHI.
01116   BasicBlock *Header = L->getHeader();
01117   Builder.SetInsertPoint(Header, Header->begin());
01118   pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
01119   PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
01120                                   Twine(IVName) + ".iv");
01121   rememberInstruction(PN);
01122 
01123   // Create the step instructions and populate the PHI.
01124   for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
01125     BasicBlock *Pred = *HPI;
01126 
01127     // Add a start value.
01128     if (!L->contains(Pred)) {
01129       PN->addIncoming(StartV, Pred);
01130       continue;
01131     }
01132 
01133     // Create a step value and add it to the PHI.
01134     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
01135     // instructions at IVIncInsertPos.
01136     Instruction *InsertPos = L == IVIncInsertLoop ?
01137       IVIncInsertPos : Pred->getTerminator();
01138     Builder.SetInsertPoint(InsertPos);
01139     Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
01140 
01141     PN->addIncoming(IncV, Pred);
01142   }
01143 
01144   // Restore the original insert point.
01145   if (SaveInsertBB)
01146     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
01147 
01148   // After expanding subexpressions, restore the PostIncLoops set so the caller
01149   // can ensure that IVIncrement dominates the current uses.
01150   PostIncLoops = SavedPostIncLoops;
01151 
01152   // Remember this PHI, even in post-inc mode.
01153   InsertedValues.insert(PN);
01154 
01155   return PN;
01156 }
01157 
01158 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
01159   Type *STy = S->getType();
01160   Type *IntTy = SE.getEffectiveSCEVType(STy);
01161   const Loop *L = S->getLoop();
01162 
01163   // Determine a normalized form of this expression, which is the expression
01164   // before any post-inc adjustment is made.
01165   const SCEVAddRecExpr *Normalized = S;
01166   if (PostIncLoops.count(L)) {
01167     PostIncLoopSet Loops;
01168     Loops.insert(L);
01169     Normalized =
01170       cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
01171                                                   Loops, SE, *SE.DT));
01172   }
01173 
01174   // Strip off any non-loop-dominating component from the addrec start.
01175   const SCEV *Start = Normalized->getStart();
01176   const SCEV *PostLoopOffset = 0;
01177   if (!SE.properlyDominates(Start, L->getHeader())) {
01178     PostLoopOffset = Start;
01179     Start = SE.getConstant(Normalized->getType(), 0);
01180     Normalized = cast<SCEVAddRecExpr>(
01181       SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
01182                        Normalized->getLoop(),
01183                        // FIXME: Normalized->getNoWrapFlags(FlagNW)
01184                        SCEV::FlagAnyWrap));
01185   }
01186 
01187   // Strip off any non-loop-dominating component from the addrec step.
01188   const SCEV *Step = Normalized->getStepRecurrence(SE);
01189   const SCEV *PostLoopScale = 0;
01190   if (!SE.dominates(Step, L->getHeader())) {
01191     PostLoopScale = Step;
01192     Step = SE.getConstant(Normalized->getType(), 1);
01193     Normalized =
01194       cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
01195                                             Normalized->getLoop(),
01196                                             // FIXME: Normalized
01197                                             // ->getNoWrapFlags(FlagNW)
01198                                             SCEV::FlagAnyWrap));
01199   }
01200 
01201   // Expand the core addrec. If we need post-loop scaling, force it to
01202   // expand to an integer type to avoid the need for additional casting.
01203   Type *ExpandTy = PostLoopScale ? IntTy : STy;
01204   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
01205 
01206   // Accommodate post-inc mode, if necessary.
01207   Value *Result;
01208   if (!PostIncLoops.count(L))
01209     Result = PN;
01210   else {
01211     // In PostInc mode, use the post-incremented value.
01212     BasicBlock *LatchBlock = L->getLoopLatch();
01213     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
01214     Result = PN->getIncomingValueForBlock(LatchBlock);
01215 
01216     // For an expansion to use the postinc form, the client must call
01217     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
01218     // or dominated by IVIncInsertPos.
01219     if (isa<Instruction>(Result)
01220         && !SE.DT->dominates(cast<Instruction>(Result),
01221                              Builder.GetInsertPoint())) {
01222       // The induction variable's postinc expansion does not dominate this use.
01223       // IVUsers tries to prevent this case, so it is rare. However, it can
01224       // happen when an IVUser outside the loop is not dominated by the latch
01225       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
01226       // all cases. Consider a phi outide whose operand is replaced during
01227       // expansion with the value of the postinc user. Without fundamentally
01228       // changing the way postinc users are tracked, the only remedy is
01229       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
01230       // but hopefully expandCodeFor handles that.
01231       bool useSubtract =
01232         !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
01233       if (useSubtract)
01234         Step = SE.getNegativeSCEV(Step);
01235       // Expand the step somewhere that dominates the loop header.
01236       BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
01237       BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
01238       Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
01239       // Restore the insertion point to the place where the caller has
01240       // determined dominates all uses.
01241       restoreInsertPoint(SaveInsertBB, SaveInsertPt);
01242       Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
01243     }
01244   }
01245 
01246   // Re-apply any non-loop-dominating scale.
01247   if (PostLoopScale) {
01248     Result = InsertNoopCastOfTo(Result, IntTy);
01249     Result = Builder.CreateMul(Result,
01250                                expandCodeFor(PostLoopScale, IntTy));
01251     rememberInstruction(Result);
01252   }
01253 
01254   // Re-apply any non-loop-dominating offset.
01255   if (PostLoopOffset) {
01256     if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
01257       const SCEV *const OffsetArray[1] = { PostLoopOffset };
01258       Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
01259     } else {
01260       Result = InsertNoopCastOfTo(Result, IntTy);
01261       Result = Builder.CreateAdd(Result,
01262                                  expandCodeFor(PostLoopOffset, IntTy));
01263       rememberInstruction(Result);
01264     }
01265   }
01266 
01267   return Result;
01268 }
01269 
01270 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
01271   if (!CanonicalMode) return expandAddRecExprLiterally(S);
01272 
01273   Type *Ty = SE.getEffectiveSCEVType(S->getType());
01274   const Loop *L = S->getLoop();
01275 
01276   // First check for an existing canonical IV in a suitable type.
01277   PHINode *CanonicalIV = 0;
01278   if (PHINode *PN = L->getCanonicalInductionVariable())
01279     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
01280       CanonicalIV = PN;
01281 
01282   // Rewrite an AddRec in terms of the canonical induction variable, if
01283   // its type is more narrow.
01284   if (CanonicalIV &&
01285       SE.getTypeSizeInBits(CanonicalIV->getType()) >
01286       SE.getTypeSizeInBits(Ty)) {
01287     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
01288     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
01289       NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
01290     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
01291                                        // FIXME: S->getNoWrapFlags(FlagNW)
01292                                        SCEV::FlagAnyWrap));
01293     BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
01294     BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
01295     BasicBlock::iterator NewInsertPt =
01296       llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
01297     while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
01298            isa<LandingPadInst>(NewInsertPt))
01299       ++NewInsertPt;
01300     V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
01301                       NewInsertPt);
01302     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
01303     return V;
01304   }
01305 
01306   // {X,+,F} --> X + {0,+,F}
01307   if (!S->getStart()->isZero()) {
01308     SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
01309     NewOps[0] = SE.getConstant(Ty, 0);
01310     // FIXME: can use S->getNoWrapFlags()
01311     const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
01312 
01313     // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
01314     // comments on expandAddToGEP for details.
01315     const SCEV *Base = S->getStart();
01316     const SCEV *RestArray[1] = { Rest };
01317     // Dig into the expression to find the pointer base for a GEP.
01318     ExposePointerBase(Base, RestArray[0], SE);
01319     // If we found a pointer, expand the AddRec with a GEP.
01320     if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
01321       // Make sure the Base isn't something exotic, such as a multiplied
01322       // or divided pointer value. In those cases, the result type isn't
01323       // actually a pointer type.
01324       if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
01325         Value *StartV = expand(Base);
01326         assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
01327         return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
01328       }
01329     }
01330 
01331     // Just do a normal add. Pre-expand the operands to suppress folding.
01332     return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
01333                                 SE.getUnknown(expand(Rest))));
01334   }
01335 
01336   // If we don't yet have a canonical IV, create one.
01337   if (!CanonicalIV) {
01338     // Create and insert the PHI node for the induction variable in the
01339     // specified loop.
01340     BasicBlock *Header = L->getHeader();
01341     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
01342     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
01343                                   Header->begin());
01344     rememberInstruction(CanonicalIV);
01345 
01346     Constant *One = ConstantInt::get(Ty, 1);
01347     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
01348       BasicBlock *HP = *HPI;
01349       if (L->contains(HP)) {
01350         // Insert a unit add instruction right before the terminator
01351         // corresponding to the back-edge.
01352         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
01353                                                      "indvar.next",
01354                                                      HP->getTerminator());
01355         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
01356         rememberInstruction(Add);
01357         CanonicalIV->addIncoming(Add, HP);
01358       } else {
01359         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
01360       }
01361     }
01362   }
01363 
01364   // {0,+,1} --> Insert a canonical induction variable into the loop!
01365   if (S->isAffine() && S->getOperand(1)->isOne()) {
01366     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
01367            "IVs with types different from the canonical IV should "
01368            "already have been handled!");
01369     return CanonicalIV;
01370   }
01371 
01372   // {0,+,F} --> {0,+,1} * F
01373 
01374   // If this is a simple linear addrec, emit it now as a special case.
01375   if (S->isAffine())    // {0,+,F} --> i*F
01376     return
01377       expand(SE.getTruncateOrNoop(
01378         SE.getMulExpr(SE.getUnknown(CanonicalIV),
01379                       SE.getNoopOrAnyExtend(S->getOperand(1),
01380                                             CanonicalIV->getType())),
01381         Ty));
01382 
01383   // If this is a chain of recurrences, turn it into a closed form, using the
01384   // folders, then expandCodeFor the closed form.  This allows the folders to
01385   // simplify the expression without having to build a bunch of special code
01386   // into this folder.
01387   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
01388 
01389   // Promote S up to the canonical IV type, if the cast is foldable.
01390   const SCEV *NewS = S;
01391   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
01392   if (isa<SCEVAddRecExpr>(Ext))
01393     NewS = Ext;
01394 
01395   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
01396   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
01397 
01398   // Truncate the result down to the original type, if needed.
01399   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
01400   return expand(T);
01401 }
01402 
01403 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
01404   Type *Ty = SE.getEffectiveSCEVType(S->getType());
01405   Value *V = expandCodeFor(S->getOperand(),
01406                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
01407   Value *I = Builder.CreateTrunc(V, Ty);
01408   rememberInstruction(I);
01409   return I;
01410 }
01411 
01412 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
01413   Type *Ty = SE.getEffectiveSCEVType(S->getType());
01414   Value *V = expandCodeFor(S->getOperand(),
01415                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
01416   Value *I = Builder.CreateZExt(V, Ty);
01417   rememberInstruction(I);
01418   return I;
01419 }
01420 
01421 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
01422   Type *Ty = SE.getEffectiveSCEVType(S->getType());
01423   Value *V = expandCodeFor(S->getOperand(),
01424                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
01425   Value *I = Builder.CreateSExt(V, Ty);
01426   rememberInstruction(I);
01427   return I;
01428 }
01429 
01430 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
01431   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
01432   Type *Ty = LHS->getType();
01433   for (int i = S->getNumOperands()-2; i >= 0; --i) {
01434     // In the case of mixed integer and pointer types, do the
01435     // rest of the comparisons as integer.
01436     if (S->getOperand(i)->getType() != Ty) {
01437       Ty = SE.getEffectiveSCEVType(Ty);
01438       LHS = InsertNoopCastOfTo(LHS, Ty);
01439     }
01440     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
01441     Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
01442     rememberInstruction(ICmp);
01443     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
01444     rememberInstruction(Sel);
01445     LHS = Sel;
01446   }
01447   // In the case of mixed integer and pointer types, cast the
01448   // final result back to the pointer type.
01449   if (LHS->getType() != S->getType())
01450     LHS = InsertNoopCastOfTo(LHS, S->getType());
01451   return LHS;
01452 }
01453 
01454 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
01455   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
01456   Type *Ty = LHS->getType();
01457   for (int i = S->getNumOperands()-2; i >= 0; --i) {
01458     // In the case of mixed integer and pointer types, do the
01459     // rest of the comparisons as integer.
01460     if (S->getOperand(i)->getType() != Ty) {
01461       Ty = SE.getEffectiveSCEVType(Ty);
01462       LHS = InsertNoopCastOfTo(LHS, Ty);
01463     }
01464     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
01465     Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
01466     rememberInstruction(ICmp);
01467     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
01468     rememberInstruction(Sel);
01469     LHS = Sel;
01470   }
01471   // In the case of mixed integer and pointer types, cast the
01472   // final result back to the pointer type.
01473   if (LHS->getType() != S->getType())
01474     LHS = InsertNoopCastOfTo(LHS, S->getType());
01475   return LHS;
01476 }
01477 
01478 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
01479                                    Instruction *IP) {
01480   Builder.SetInsertPoint(IP->getParent(), IP);
01481   return expandCodeFor(SH, Ty);
01482 }
01483 
01484 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
01485   // Expand the code for this SCEV.
01486   Value *V = expand(SH);
01487   if (Ty) {
01488     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
01489            "non-trivial casts should be done with the SCEVs directly!");
01490     V = InsertNoopCastOfTo(V, Ty);
01491   }
01492   return V;
01493 }
01494 
01495 Value *SCEVExpander::expand(const SCEV *S) {
01496   // Compute an insertion point for this SCEV object. Hoist the instructions
01497   // as far out in the loop nest as possible.
01498   Instruction *InsertPt = Builder.GetInsertPoint();
01499   for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
01500        L = L->getParentLoop())
01501     if (SE.isLoopInvariant(S, L)) {
01502       if (!L) break;
01503       if (BasicBlock *Preheader = L->getLoopPreheader())
01504         InsertPt = Preheader->getTerminator();
01505       else {
01506         // LSR sets the insertion point for AddRec start/step values to the
01507         // block start to simplify value reuse, even though it's an invalid
01508         // position. SCEVExpander must correct for this in all cases.
01509         InsertPt = L->getHeader()->getFirstInsertionPt();
01510       }
01511     } else {
01512       // If the SCEV is computable at this level, insert it into the header
01513       // after the PHIs (and after any other instructions that we've inserted
01514       // there) so that it is guaranteed to dominate any user inside the loop.
01515       if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
01516         InsertPt = L->getHeader()->getFirstInsertionPt();
01517       while (InsertPt != Builder.GetInsertPoint()
01518              && (isInsertedInstruction(InsertPt)
01519                  || isa<DbgInfoIntrinsic>(InsertPt))) {
01520         InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
01521       }
01522       break;
01523     }
01524 
01525   // Check to see if we already expanded this here.
01526   std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
01527     I = InsertedExpressions.find(std::make_pair(S, InsertPt));
01528   if (I != InsertedExpressions.end())
01529     return I->second;
01530 
01531   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
01532   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
01533   Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
01534 
01535   // Expand the expression into instructions.
01536   Value *V = visit(S);
01537 
01538   // Remember the expanded value for this SCEV at this location.
01539   //
01540   // This is independent of PostIncLoops. The mapped value simply materializes
01541   // the expression at this insertion point. If the mapped value happened to be
01542   // a postinc expansion, it could be reused by a non postinc user, but only if
01543   // its insertion point was already at the head of the loop.
01544   InsertedExpressions[std::make_pair(S, InsertPt)] = V;
01545 
01546   restoreInsertPoint(SaveInsertBB, SaveInsertPt);
01547   return V;
01548 }
01549 
01550 void SCEVExpander::rememberInstruction(Value *I) {
01551   if (!PostIncLoops.empty())
01552     InsertedPostIncValues.insert(I);
01553   else
01554     InsertedValues.insert(I);
01555 }
01556 
01557 void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
01558   Builder.SetInsertPoint(BB, I);
01559 }
01560 
01561 /// getOrInsertCanonicalInductionVariable - This method returns the
01562 /// canonical induction variable of the specified type for the specified
01563 /// loop (inserting one if there is none).  A canonical induction variable
01564 /// starts at zero and steps by one on each iteration.
01565 PHINode *
01566 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
01567                                                     Type *Ty) {
01568   assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
01569 
01570   // Build a SCEV for {0,+,1}<L>.
01571   // Conservatively use FlagAnyWrap for now.
01572   const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
01573                                    SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
01574 
01575   // Emit code for it.
01576   BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
01577   BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
01578   PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
01579   if (SaveInsertBB)
01580     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
01581 
01582   return V;
01583 }
01584 
01585 /// Sort values by integer width for replaceCongruentIVs.
01586 static bool width_descending(Value *lhs, Value *rhs) {
01587   // Put pointers at the back and make sure pointer < pointer = false.
01588   if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
01589     return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
01590   return rhs->getType()->getPrimitiveSizeInBits()
01591     < lhs->getType()->getPrimitiveSizeInBits();
01592 }
01593 
01594 /// replaceCongruentIVs - Check for congruent phis in this loop header and
01595 /// replace them with their most canonical representative. Return the number of
01596 /// phis eliminated.
01597 ///
01598 /// This does not depend on any SCEVExpander state but should be used in
01599 /// the same context that SCEVExpander is used.
01600 unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
01601                                            SmallVectorImpl<WeakVH> &DeadInsts,
01602                                            const TargetTransformInfo *TTI) {
01603   // Find integer phis in order of increasing width.
01604   SmallVector<PHINode*, 8> Phis;
01605   for (BasicBlock::iterator I = L->getHeader()->begin();
01606        PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
01607     Phis.push_back(Phi);
01608   }
01609   if (TTI)
01610     std::sort(Phis.begin(), Phis.end(), width_descending);
01611 
01612   unsigned NumElim = 0;
01613   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
01614   // Process phis from wide to narrow. Mapping wide phis to the their truncation
01615   // so narrow phis can reuse them.
01616   for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
01617          PEnd = Phis.end(); PIter != PEnd; ++PIter) {
01618     PHINode *Phi = *PIter;
01619 
01620     // Fold constant phis. They may be congruent to other constant phis and
01621     // would confuse the logic below that expects proper IVs.
01622     if (Value *V = Phi->hasConstantValue()) {
01623       Phi->replaceAllUsesWith(V);
01624       DeadInsts.push_back(Phi);
01625       ++NumElim;
01626       DEBUG_WITH_TYPE(DebugType, dbgs()
01627                       << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
01628       continue;
01629     }
01630 
01631     if (!SE.isSCEVable(Phi->getType()))
01632       continue;
01633 
01634     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
01635     if (!OrigPhiRef) {
01636       OrigPhiRef = Phi;
01637       if (Phi->getType()->isIntegerTy() && TTI
01638           && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
01639         // This phi can be freely truncated to the narrowest phi type. Map the
01640         // truncated expression to it so it will be reused for narrow types.
01641         const SCEV *TruncExpr =
01642           SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
01643         ExprToIVMap[TruncExpr] = Phi;
01644       }
01645       continue;
01646     }
01647 
01648     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
01649     // sense.
01650     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
01651       continue;
01652 
01653     if (BasicBlock *LatchBlock = L->getLoopLatch()) {
01654       Instruction *OrigInc =
01655         cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
01656       Instruction *IsomorphicInc =
01657         cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
01658 
01659       // If this phi has the same width but is more canonical, replace the
01660       // original with it. As part of the "more canonical" determination,
01661       // respect a prior decision to use an IV chain.
01662       if (OrigPhiRef->getType() == Phi->getType()
01663           && !(ChainedPhis.count(Phi)
01664                || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
01665           && (ChainedPhis.count(Phi)
01666               || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
01667         std::swap(OrigPhiRef, Phi);
01668         std::swap(OrigInc, IsomorphicInc);
01669       }
01670       // Replacing the congruent phi is sufficient because acyclic redundancy
01671       // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
01672       // that a phi is congruent, it's often the head of an IV user cycle that
01673       // is isomorphic with the original phi. It's worth eagerly cleaning up the
01674       // common case of a single IV increment so that DeleteDeadPHIs can remove
01675       // cycles that had postinc uses.
01676       const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
01677                                                    IsomorphicInc->getType());
01678       if (OrigInc != IsomorphicInc
01679           && TruncExpr == SE.getSCEV(IsomorphicInc)
01680           && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
01681               || hoistIVInc(OrigInc, IsomorphicInc))) {
01682         DEBUG_WITH_TYPE(DebugType, dbgs()
01683                         << "INDVARS: Eliminated congruent iv.inc: "
01684                         << *IsomorphicInc << '\n');
01685         Value *NewInc = OrigInc;
01686         if (OrigInc->getType() != IsomorphicInc->getType()) {
01687           Instruction *IP = isa<PHINode>(OrigInc)
01688             ? (Instruction*)L->getHeader()->getFirstInsertionPt()
01689             : OrigInc->getNextNode();
01690           IRBuilder<> Builder(IP);
01691           Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
01692           NewInc = Builder.
01693             CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
01694         }
01695         IsomorphicInc->replaceAllUsesWith(NewInc);
01696         DeadInsts.push_back(IsomorphicInc);
01697       }
01698     }
01699     DEBUG_WITH_TYPE(DebugType, dbgs()
01700                     << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
01701     ++NumElim;
01702     Value *NewIV = OrigPhiRef;
01703     if (OrigPhiRef->getType() != Phi->getType()) {
01704       IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
01705       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
01706       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
01707     }
01708     Phi->replaceAllUsesWith(NewIV);
01709     DeadInsts.push_back(Phi);
01710   }
01711   return NumElim;
01712 }
01713 
01714 namespace {
01715 // Search for a SCEV subexpression that is not safe to expand.  Any expression
01716 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
01717 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
01718 // instruction, but the important thing is that we prove the denominator is
01719 // nonzero before expansion.
01720 //
01721 // IVUsers already checks that IV-derived expressions are safe. So this check is
01722 // only needed when the expression includes some subexpression that is not IV
01723 // derived.
01724 //
01725 // Currently, we only allow division by a nonzero constant here. If this is
01726 // inadequate, we could easily allow division by SCEVUnknown by using
01727 // ValueTracking to check isKnownNonZero().
01728 struct SCEVFindUnsafe {
01729   bool IsUnsafe;
01730 
01731   SCEVFindUnsafe(): IsUnsafe(false) {}
01732 
01733   bool follow(const SCEV *S) {
01734     const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S);
01735     if (!D)
01736       return true;
01737     const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
01738     if (SC && !SC->getValue()->isZero())
01739       return true;
01740     IsUnsafe = true;
01741     return false;
01742   }
01743   bool isDone() const { return IsUnsafe; }
01744 };
01745 }
01746 
01747 namespace llvm {
01748 bool isSafeToExpand(const SCEV *S) {
01749   SCEVFindUnsafe Search;
01750   visitAll(S, Search);
01751   return !Search.IsUnsafe;
01752 }
01753 }