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