<div dir="ltr">If they cover the same different use cases, most notably the *specific* reason for using a percentage based threshold, that's what I was looking for.<br></div><br><div class="gmail_quote">On Thu, May 14, 2015 at 5:16 PM Michael Zolotukhin <<a href="mailto:mzolotukhin@apple.com">mzolotukhin@apple.com</a>> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hi Chandler,<br>
<br>
We agreed that I’ll follow-up on this with adding examples from our discussion as tests. However, the original tests (test/Transforms/LoopUnroll/full-unroll-heuristics.ll) are essentially covering the same cases. Did you mean some other tests, or these are sufficient?<br>
<br>
Thanks,<br>
Michael<br>
<br>
> On May 12, 2015, at 10:20 AM, Michael Zolotukhin <<a href="mailto:mzolotukhin@apple.com" target="_blank">mzolotukhin@apple.com</a>> wrote:<br>
><br>
> Author: mzolotukhin<br>
> Date: Tue May 12 12:20:03 2015<br>
> New Revision: 237156<br>
><br>
> URL: <a href="https://urldefense.proofpoint.com/v2/url?u=http-3A__llvm.org_viewvc_llvm-2Dproject-3Frev-3D237156-26view-3Drev&d=AwMFaQ&c=8hUWFZcy2Z-Za5rBPlktOQ&r=mQ4LZ2PUj9hpadE3cDHZnIdEwhEBrbAstXeMaFoB9tg&m=-SpI0905drQheNhlFb1R0Es0Lpj3x3iYMYgNlqIRN_E&s=Pq58z6NLOWkGcYFEykKAkJnoZlFF0NEVP7mSkOaD3eg&e=" target="_blank">http://llvm.org/viewvc/llvm-project?rev=237156&view=rev</a><br>
> Log:<br>
> Reimplement heuristic for estimating complete-unroll optimization effects.<br>
><br>
> Summary:<br>
> This patch reimplements heuristic that tries to estimate optimization beneftis<br>
> from complete loop unrolling.<br>
><br>
> In this patch I kept the minimal changes - e.g. I removed code handling<br>
> branches and folding compares. That's a promising area, but now there<br>
> are too many questions to discuss before we can enable it.<br>
><br>
> Test Plan: Tests are included in the patch.<br>
><br>
> Reviewers: hfinkel, chandlerc<br>
><br>
> Subscribers: llvm-commits<br>
><br>
> Differential Revision: <a href="https://urldefense.proofpoint.com/v2/url?u=http-3A__reviews.llvm.org_D8816&d=AwMFaQ&c=8hUWFZcy2Z-Za5rBPlktOQ&r=mQ4LZ2PUj9hpadE3cDHZnIdEwhEBrbAstXeMaFoB9tg&m=-SpI0905drQheNhlFb1R0Es0Lpj3x3iYMYgNlqIRN_E&s=DkhITnJVz1TfcBKpsOFwjdcz3yek0c0QYfRbzsFCMZo&e=" target="_blank">http://reviews.llvm.org/D8816</a><br>
><br>
> Added:<br>
>    llvm/trunk/test/Transforms/LoopUnroll/full-unroll-bad-geps.ll<br>
> Modified:<br>
>    llvm/trunk/lib/Transforms/Scalar/LoopUnrollPass.cpp<br>
>    llvm/trunk/test/Transforms/LoopUnroll/full-unroll-heuristics.ll<br>
><br>
> Modified: llvm/trunk/lib/Transforms/Scalar/LoopUnrollPass.cpp<br>
> URL: <a href="https://urldefense.proofpoint.com/v2/url?u=http-3A__llvm.org_viewvc_llvm-2Dproject_llvm_trunk_lib_Transforms_Scalar_LoopUnrollPass.cpp-3Frev-3D237156-26r1-3D237155-26r2-3D237156-26view-3Ddiff&d=AwMFaQ&c=8hUWFZcy2Z-Za5rBPlktOQ&r=mQ4LZ2PUj9hpadE3cDHZnIdEwhEBrbAstXeMaFoB9tg&m=-SpI0905drQheNhlFb1R0Es0Lpj3x3iYMYgNlqIRN_E&s=IaMMp0g0a6UugwRpGLT6OBFpYLAyYDV5Gbyx7ARFong&e=" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/LoopUnrollPass.cpp?rev=237156&r1=237155&r2=237156&view=diff</a><br>
> ==============================================================================<br>
> --- llvm/trunk/lib/Transforms/Scalar/LoopUnrollPass.cpp (original)<br>
> +++ llvm/trunk/lib/Transforms/Scalar/LoopUnrollPass.cpp Tue May 12 12:20:03 2015<br>
> @@ -186,33 +186,21 @@ namespace {<br>
>     void selectThresholds(const Loop *L, bool HasPragma,<br>
>                           const TargetTransformInfo::UnrollingPreferences &UP,<br>
>                           unsigned &Threshold, unsigned &PartialThreshold,<br>
> -                          unsigned NumberOfOptimizedInstructions) {<br>
> +                          unsigned &AbsoluteThreshold,<br>
> +                          unsigned &PercentOfOptimizedForCompleteUnroll) {<br>
>       // Determine the current unrolling threshold.  While this is<br>
>       // normally set from UnrollThreshold, it is overridden to a<br>
>       // smaller value if the current function is marked as<br>
>       // optimize-for-size, and the unroll threshold was not user<br>
>       // specified.<br>
>       Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;<br>
> -<br>
> -      // If we are allowed to completely unroll if we can remove M% of<br>
> -      // instructions, and we know that with complete unrolling we'll be able<br>
> -      // to kill N instructions, then we can afford to completely unroll loops<br>
> -      // with unrolled size up to N*100/M.<br>
> -      // Adjust the threshold according to that:<br>
> -      unsigned PercentOfOptimizedForCompleteUnroll =<br>
> -          UserPercentOfOptimized ? CurrentMinPercentOfOptimized<br>
> -                                 : UP.MinPercentOfOptimized;<br>
> -      unsigned AbsoluteThreshold = UserAbsoluteThreshold<br>
> -                                       ? CurrentAbsoluteThreshold<br>
> -                                       : UP.AbsoluteThreshold;<br>
> -      if (PercentOfOptimizedForCompleteUnroll)<br>
> -        Threshold = std::max<unsigned>(Threshold,<br>
> -                                       NumberOfOptimizedInstructions * 100 /<br>
> -                                           PercentOfOptimizedForCompleteUnroll);<br>
> -      // But don't allow unrolling loops bigger than absolute threshold.<br>
> -      Threshold = std::min<unsigned>(Threshold, AbsoluteThreshold);<br>
> -<br>
>       PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;<br>
> +      AbsoluteThreshold = UserAbsoluteThreshold ? CurrentAbsoluteThreshold<br>
> +                                                : UP.AbsoluteThreshold;<br>
> +      PercentOfOptimizedForCompleteUnroll = UserPercentOfOptimized<br>
> +                                                ? CurrentMinPercentOfOptimized<br>
> +                                                : UP.MinPercentOfOptimized;<br>
> +<br>
>       if (!UserThreshold &&<br>
>           L->getHeader()->getParent()->hasFnAttribute(<br>
>               Attribute::OptimizeForSize)) {<br>
> @@ -231,6 +219,10 @@ namespace {<br>
>               std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);<br>
>       }<br>
>     }<br>
> +    bool canUnrollCompletely(Loop *L, unsigned Threshold,<br>
> +                             unsigned AbsoluteThreshold, uint64_t UnrolledSize,<br>
> +                             unsigned NumberOfOptimizedInstructions,<br>
> +                             unsigned PercentOfOptimizedForCompleteUnroll);<br>
>   };<br>
> }<br>
><br>
> @@ -253,57 +245,75 @@ Pass *llvm::createSimpleLoopUnrollPass()<br>
>   return llvm::createLoopUnrollPass(-1, -1, 0, 0);<br>
> }<br>
><br>
> -static bool isLoadFromConstantInitializer(Value *V) {<br>
> -  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))<br>
> -    if (GV->isConstant() && GV->hasDefinitiveInitializer())<br>
> -      return GV->getInitializer();<br>
> -  return false;<br>
> -}<br>
> -<br>
> namespace {<br>
> +/// \brief SCEV expressions visitor used for finding expressions that would<br>
> +/// become constants if the loop L is unrolled.<br>
> struct FindConstantPointers {<br>
> -  bool LoadCanBeConstantFolded;<br>
> +  /// \brief Shows whether the expression is ConstAddress+Constant or not.<br>
>   bool IndexIsConstant;<br>
> -  APInt Step;<br>
> -  APInt StartValue;<br>
> +<br>
> +  /// \brief Used for filtering out SCEV expressions with two or more AddRec<br>
> +  /// subexpressions.<br>
> +  ///<br>
> +  /// Used to filter out complicated SCEV expressions, having several AddRec<br>
> +  /// sub-expressions. We don't handle them, because unrolling one loop<br>
> +  /// would help to replace only one of these inductions with a constant, and<br>
> +  /// consequently, the expression would remain non-constant.<br>
> +  bool HaveSeenAR;<br>
> +<br>
> +  /// \brief If the SCEV expression becomes ConstAddress+Constant, this value<br>
> +  /// holds ConstAddress. Otherwise, it's nullptr.<br>
>   Value *BaseAddress;<br>
> +<br>
> +  /// \brief The loop, which we try to completely unroll.<br>
>   const Loop *L;<br>
> +<br>
>   ScalarEvolution &SE;<br>
> -  FindConstantPointers(const Loop *loop, ScalarEvolution &SE)<br>
> -      : LoadCanBeConstantFolded(true), IndexIsConstant(true), L(loop), SE(SE) {}<br>
><br>
> +  FindConstantPointers(const Loop *L, ScalarEvolution &SE)<br>
> +      : IndexIsConstant(true), HaveSeenAR(false), BaseAddress(nullptr),<br>
> +        L(L), SE(SE) {}<br>
> +<br>
> +  /// Examine the given expression S and figure out, if it can be a part of an<br>
> +  /// expression, that could become a constant after the loop is unrolled.<br>
> +  /// The routine sets IndexIsConstant and HaveSeenAR according to the analysis<br>
> +  /// results.<br>
> +  /// \returns true if we need to examine subexpressions, and false otherwise.<br>
>   bool follow(const SCEV *S) {<br>
>     if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) {<br>
>       // We've reached the leaf node of SCEV, it's most probably just a<br>
> -      // variable. Now it's time to see if it corresponds to a global constant<br>
> -      // global (in which case we can eliminate the load), or not.<br>
> +      // variable.<br>
> +      // If it's the only one SCEV-subexpression, then it might be a base<br>
> +      // address of an index expression.<br>
> +      // If we've already recorded base address, then just give up on this SCEV<br>
> +      // - it's too complicated.<br>
> +      if (BaseAddress) {<br>
> +        IndexIsConstant = false;<br>
> +        return false;<br>
> +      }<br>
>       BaseAddress = SC->getValue();<br>
> -      LoadCanBeConstantFolded =<br>
> -          IndexIsConstant && isLoadFromConstantInitializer(BaseAddress);<br>
>       return false;<br>
>     }<br>
>     if (isa<SCEVConstant>(S))<br>
> -      return true;<br>
> +      return false;<br>
>     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {<br>
>       // If the current SCEV expression is AddRec, and its loop isn't the loop<br>
>       // we are about to unroll, then we won't get a constant address after<br>
>       // unrolling, and thus, won't be able to eliminate the load.<br>
> -      if (AR->getLoop() != L)<br>
> -        return IndexIsConstant = false;<br>
> -      // If the step isn't constant, we won't get constant addresses in unrolled<br>
> -      // version. Bail out.<br>
> -      if (const SCEVConstant *StepSE =<br>
> -              dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))<br>
> -        Step = StepSE->getValue()->getValue();<br>
> -      else<br>
> -        return IndexIsConstant = false;<br>
> -<br>
> -      return IndexIsConstant;<br>
> +      if (AR->getLoop() != L) {<br>
> +        IndexIsConstant = false;<br>
> +        return false;<br>
> +      }<br>
> +      // We don't handle multiple AddRecs here, so give up in this case.<br>
> +      if (HaveSeenAR) {<br>
> +        IndexIsConstant = false;<br>
> +        return false;<br>
> +      }<br>
> +      HaveSeenAR = true;<br>
>     }<br>
> -    // If Result is true, continue traversal.<br>
> -    // Otherwise, we have found something that prevents us from (possible) load<br>
> -    // elimination.<br>
> -    return IndexIsConstant;<br>
> +<br>
> +    // Continue traversal.<br>
> +    return true;<br>
>   }<br>
>   bool isDone() const { return !IndexIsConstant; }<br>
> };<br>
> @@ -328,27 +338,54 @@ class UnrollAnalyzer : public InstVisito<br>
>   typedef InstVisitor<UnrollAnalyzer, bool> Base;<br>
>   friend class InstVisitor<UnrollAnalyzer, bool>;<br>
><br>
> +  struct SCEVGEPDescriptor {<br>
> +    Value *BaseAddr;<br>
> +    APInt Start;<br>
> +    APInt Step;<br>
> +  };<br>
> +<br>
> +  /// \brief The loop we're going to analyze.<br>
>   const Loop *L;<br>
> +<br>
> +  /// \brief TripCount of the given loop.<br>
>   unsigned TripCount;<br>
> +<br>
>   ScalarEvolution &SE;<br>
> +<br>
>   const TargetTransformInfo &TTI;<br>
><br>
> +  // While we walk the loop instructions, we we build up and maintain a mapping<br>
> +  // of simplified values specific to this iteration.  The idea is to propagate<br>
> +  // any special information we have about loads that can be replaced with<br>
> +  // constants after complete unrolling, and account for likely simplifications<br>
> +  // post-unrolling.<br>
>   DenseMap<Value *, Constant *> SimplifiedValues;<br>
> -  DenseMap<LoadInst *, Value *> LoadBaseAddresses;<br>
> -  SmallPtrSet<Instruction *, 32> CountedInstructions;<br>
><br>
> -  /// \brief Count the number of optimized instructions.<br>
> -  unsigned NumberOfOptimizedInstructions;<br>
> +  // To avoid requesting SCEV info on every iteration, request it once, and<br>
> +  // for each value that would become ConstAddress+Constant after loop<br>
> +  // unrolling, save the corresponding data.<br>
> +  SmallDenseMap<Value *, SCEVGEPDescriptor> SCEVCache;<br>
> +<br>
> +  /// \brief Number of currently simulated iteration.<br>
> +  ///<br>
> +  /// If an expression is ConstAddress+Constant, then the Constant is<br>
> +  /// Start + Iteration*Step, where Start and Step could be obtained from<br>
> +  /// SCEVCache.<br>
> +  unsigned Iteration;<br>
> +<br>
> +  /// \brief Upper threshold for complete unrolling.<br>
> +  unsigned MaxUnrolledLoopSize;<br>
><br>
> -  // Provide base case for our instruction visit.<br>
> +  /// Base case for the instruction visitor.<br>
>   bool visitInstruction(Instruction &I) { return false; };<br>
> -  // TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt,<br>
> -  // FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select,<br>
> -  // ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue.<br>
> -  //<br>
> -  // Probaly it's worth to hoist the code for estimating the simplifications<br>
> -  // effects to a separate class, since we have a very similar code in<br>
> -  // InlineCost already.<br>
> +<br>
> +  /// TODO: Add visitors for other instruction types, e.g. ZExt, SExt.<br>
> +<br>
> +  /// Try to simplify binary operator I.<br>
> +  ///<br>
> +  /// TODO: Probaly it's worth to hoist the code for estimating the<br>
> +  /// simplifications effects to a separate class, since we have a very similar<br>
> +  /// code in InlineCost already.<br>
>   bool visitBinaryOperator(BinaryOperator &I) {<br>
>     Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);<br>
>     if (!isa<Constant>(LHS))<br>
> @@ -365,7 +402,7 @@ class UnrollAnalyzer : public InstVisito<br>
>     else<br>
>       SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);<br>
><br>
> -    if (SimpleV && CountedInstructions.insert(&I).second)<br>
> +    if (SimpleV)<br>
>       NumberOfOptimizedInstructions += TTI.getUserCost(&I);<br>
><br>
>     if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {<br>
> @@ -375,207 +412,172 @@ class UnrollAnalyzer : public InstVisito<br>
>     return false;<br>
>   }<br>
><br>
> -  Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) {<br>
> -    if (!LI)<br>
> -      return nullptr;<br>
> -    Value *BaseAddr = LoadBaseAddresses[LI];<br>
> -    if (!BaseAddr)<br>
> -      return nullptr;<br>
> -<br>
> -    auto GV = dyn_cast<GlobalVariable>(BaseAddr);<br>
> -    if (!GV)<br>
> -      return nullptr;<br>
> +  /// Try to fold load I.<br>
> +  bool visitLoad(LoadInst &I) {<br>
> +    Value *AddrOp = I.getPointerOperand();<br>
> +    if (!isa<Constant>(AddrOp))<br>
> +      if (Constant *SimplifiedAddrOp = SimplifiedValues.lookup(AddrOp))<br>
> +        AddrOp = SimplifiedAddrOp;<br>
> +<br>
> +    auto It = SCEVCache.find(AddrOp);<br>
> +    if (It == SCEVCache.end())<br>
> +      return false;<br>
> +    SCEVGEPDescriptor GEPDesc = It->second;<br>
> +<br>
> +    auto GV = dyn_cast<GlobalVariable>(GEPDesc.BaseAddr);<br>
> +    // We're only interested in loads that can be completely folded to a<br>
> +    // constant.<br>
> +    if (!GV || !GV->hasInitializer())<br>
> +      return false;<br>
><br>
>     ConstantDataSequential *CDS =<br>
>         dyn_cast<ConstantDataSequential>(GV->getInitializer());<br>
>     if (!CDS)<br>
> -      return nullptr;<br>
> -<br>
> -    const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr);<br>
> -    const SCEV *S = SE.getSCEV(LI->getPointerOperand());<br>
> -    const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);<br>
> -<br>
> -    APInt StepC, StartC;<br>
> -    const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);<br>
> -    if (!AR)<br>
> -      return nullptr;<br>
> -<br>
> -    if (const SCEVConstant *StepSE =<br>
> -            dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))<br>
> -      StepC = StepSE->getValue()->getValue();<br>
> -    else<br>
> -      return nullptr;<br>
> -<br>
> -    if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart()))<br>
> -      StartC = StartSE->getValue()->getValue();<br>
> -    else<br>
> -      return nullptr;<br>
> +      return false;<br>
><br>
> +    // Check possible overflow.<br>
> +    if (GEPDesc.Start.getActiveBits() > 32 || GEPDesc.Step.getActiveBits() > 32)<br>
> +      return false;<br>
>     unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;<br>
> -    unsigned Start = StartC.getLimitedValue();<br>
> -    unsigned Step = StepC.getLimitedValue();<br>
> -<br>
> -    unsigned Index = (Start + Step * Iteration) / ElemSize;<br>
> -    if (Index >= CDS->getNumElements())<br>
> -      return nullptr;<br>
> +    uint64_t Index = (GEPDesc.Start.getLimitedValue() +<br>
> +                      GEPDesc.Step.getLimitedValue() * Iteration) /<br>
> +                     ElemSize;<br>
> +    if (Index >= CDS->getNumElements()) {<br>
> +      // FIXME: For now we conservatively ignore out of bound accesses, but<br>
> +      // we're allowed to perform the optimization in this case.<br>
> +      return false;<br>
> +    }<br>
><br>
>     Constant *CV = CDS->getElementAsConstant(Index);<br>
> +    assert(CV && "Constant expected.");<br>
> +    SimplifiedValues[&I] = CV;<br>
><br>
> -    return CV;<br>
> +    NumberOfOptimizedInstructions += TTI.getUserCost(&I);<br>
> +    return true;<br>
>   }<br>
><br>
> -public:<br>
> -  UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE,<br>
> -                 const TargetTransformInfo &TTI)<br>
> -      : L(L), TripCount(TripCount), SE(SE), TTI(TTI),<br>
> -        NumberOfOptimizedInstructions(0) {}<br>
> -<br>
> -  // Visit all loads the loop L, and for those that, after complete loop<br>
> -  // unrolling, would have a constant address and it will point to a known<br>
> -  // constant initializer, record its base address for future use.  It is used<br>
> -  // when we estimate number of potentially simplified instructions.<br>
> -  void findConstFoldableLoads() {<br>
> +  /// Visit all GEPs in the loop and find those which after complete loop<br>
> +  /// unrolling would become a constant, or BaseAddress+Constant.<br>
> +  ///<br>
> +  /// Such GEPs could allow to evaluate a load to a constant later - for now we<br>
> +  /// just store the corresponding BaseAddress and StartValue with StepValue in<br>
> +  /// the SCEVCache.<br>
> +  void cacheSCEVResults() {<br>
>     for (auto BB : L->getBlocks()) {<br>
> -      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {<br>
> -        if (LoadInst *LI = dyn_cast<LoadInst>(I)) {<br>
> -          if (!LI->isSimple())<br>
> -            continue;<br>
> -          Value *AddrOp = LI->getPointerOperand();<br>
> -          const SCEV *S = SE.getSCEV(AddrOp);<br>
> +      for (Instruction &I : *BB) {<br>
> +        if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {<br>
> +          Value *V = cast<Value>(GEP);<br>
> +          if (!SE.isSCEVable(V->getType()))<br>
> +              continue;<br>
> +          const SCEV *S = SE.getSCEV(V);<br>
> +          // FIXME: Hoist the initialization out of the loop.<br>
>           FindConstantPointers Visitor(L, SE);<br>
>           SCEVTraversal<FindConstantPointers> T(Visitor);<br>
> +          // Try to find (BaseAddress+Step+Offset) tuple.<br>
> +          // If succeeded, save it to the cache - it might help in folding<br>
> +          // loads.<br>
>           T.visitAll(S);<br>
> -          if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) {<br>
> -            LoadBaseAddresses[LI] = Visitor.BaseAddress;<br>
> -          }<br>
> +          if (!Visitor.IndexIsConstant || !Visitor.BaseAddress)<br>
> +            continue;<br>
> +<br>
> +          const SCEV *BaseAddrSE = SE.getSCEV(Visitor.BaseAddress);<br>
> +          if (BaseAddrSE->getType() != S->getType())<br>
> +            continue;<br>
> +          const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);<br>
> +          const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);<br>
> +<br>
> +          if (!AR)<br>
> +            continue;<br>
> +<br>
> +          const SCEVConstant *StepSE =<br>
> +              dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE));<br>
> +          const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart());<br>
> +          if (!StepSE || !StartSE)<br>
> +            continue;<br>
> +<br>
> +          SCEVCache[V] = {Visitor.BaseAddress, StartSE->getValue()->getValue(),<br>
> +                          StepSE->getValue()->getValue()};<br>
>         }<br>
>       }<br>
>     }<br>
>   }<br>
><br>
> -  // Given a list of loads that could be constant-folded (LoadBaseAddresses),<br>
> -  // estimate number of optimized instructions after substituting the concrete<br>
> -  // values for the given Iteration. Also track how many instructions become<br>
> -  // dead through this process.<br>
> -  unsigned estimateNumberOfOptimizedInstructions(unsigned Iteration) {<br>
> -    // We keep a set vector for the worklist so that we don't wast space in the<br>
> -    // worklist queuing up the same instruction repeatedly. This can happen due<br>
> -    // to multiple operands being the same instruction or due to the same<br>
> -    // instruction being an operand of lots of things that end up dead or<br>
> -    // simplified.<br>
> -    SmallSetVector<Instruction *, 8> Worklist;<br>
> -<br>
> -    // Clear the simplified values and counts for this iteration.<br>
> -    SimplifiedValues.clear();<br>
> -    CountedInstructions.clear();<br>
> -    NumberOfOptimizedInstructions = 0;<br>
> -<br>
> -    // We start by adding all loads to the worklist.<br>
> -    for (auto &LoadDescr : LoadBaseAddresses) {<br>
> -      LoadInst *LI = LoadDescr.first;<br>
> -      SimplifiedValues[LI] = computeLoadValue(LI, Iteration);<br>
> -      if (CountedInstructions.insert(LI).second)<br>
> -        NumberOfOptimizedInstructions += TTI.getUserCost(LI);<br>
> +public:<br>
> +  UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE,<br>
> +                 const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize)<br>
> +      : L(L), TripCount(TripCount), SE(SE), TTI(TTI),<br>
> +        MaxUnrolledLoopSize(MaxUnrolledLoopSize),<br>
> +        NumberOfOptimizedInstructions(0), UnrolledLoopSize(0) {}<br>
><br>
> -      for (User *U : LI->users())<br>
> -        Worklist.insert(cast<Instruction>(U));<br>
> -    }<br>
> +  /// \brief Count the number of optimized instructions.<br>
> +  unsigned NumberOfOptimizedInstructions;<br>
><br>
> -    // And then we try to simplify every user of every instruction from the<br>
> -    // worklist. If we do simplify a user, add it to the worklist to process<br>
> -    // its users as well.<br>
> -    while (!Worklist.empty()) {<br>
> -      Instruction *I = Worklist.pop_back_val();<br>
> -      if (!L->contains(I))<br>
> -        continue;<br>
> -      if (!visit(I))<br>
> -        continue;<br>
> -      for (User *U : I->users())<br>
> -        Worklist.insert(cast<Instruction>(U));<br>
> -    }<br>
> +  /// \brief Count the total number of instructions.<br>
> +  unsigned UnrolledLoopSize;<br>
><br>
> -    // Now that we know the potentially simplifed instructions, estimate number<br>
> -    // of instructions that would become dead if we do perform the<br>
> -    // simplification.<br>
> -<br>
> -    // The dead instructions are held in a separate set. This is used to<br>
> -    // prevent us from re-examining instructions and make sure we only count<br>
> -    // the benifit once. The worklist's internal set handles insertion<br>
> -    // deduplication.<br>
> -    SmallPtrSet<Instruction *, 16> DeadInstructions;<br>
> -<br>
> -    // Lambda to enque operands onto the worklist.<br>
> -    auto EnqueueOperands = [&](Instruction &I) {<br>
> -      for (auto *Op : I.operand_values())<br>
> -        if (auto *OpI = dyn_cast<Instruction>(Op))<br>
> -          if (!OpI->use_empty())<br>
> -            Worklist.insert(OpI);<br>
> -    };<br>
> -<br>
> -    // Start by initializing worklist with simplified instructions.<br>
> -    for (auto &FoldedKeyValue : SimplifiedValues)<br>
> -      if (auto *FoldedInst = dyn_cast<Instruction>(FoldedKeyValue.first)) {<br>
> -        DeadInstructions.insert(FoldedInst);<br>
> -<br>
> -        // Add each instruction operand of this dead instruction to the<br>
> -        // worklist.<br>
> -        EnqueueOperands(*FoldedInst);<br>
> -      }<br>
> +  /// \brief Figure out if the loop is worth full unrolling.<br>
> +  ///<br>
> +  /// Complete loop unrolling can make some loads constant, and we need to know<br>
> +  /// if that would expose any further optimization opportunities.  This routine<br>
> +  /// estimates this optimization.  It assigns computed number of instructions,<br>
> +  /// that potentially might be optimized away, to<br>
> +  /// NumberOfOptimizedInstructions, and total number of instructions to<br>
> +  /// UnrolledLoopSize (not counting blocks that won't be reached, if we were<br>
> +  /// able to compute the condition).<br>
> +  /// \returns false if we can't analyze the loop, or if we discovered that<br>
> +  /// unrolling won't give anything. Otherwise, returns true.<br>
> +  bool analyzeLoop() {<br>
> +    SmallSetVector<BasicBlock *, 16> BBWorklist;<br>
> +<br>
> +    // Don't simulate loops with a big or unknown tripcount<br>
> +    if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||<br>
> +        TripCount > UnrollMaxIterationsCountToAnalyze)<br>
> +      return false;<br>
><br>
> -    // If a definition of an insn is only used by simplified or dead<br>
> -    // instructions, it's also dead. Check defs of all instructions from the<br>
> -    // worklist.<br>
> -    while (!Worklist.empty()) {<br>
> -      Instruction *I = Worklist.pop_back_val();<br>
> -      if (!L->contains(I))<br>
> -        continue;<br>
> -      if (DeadInstructions.count(I))<br>
> -        continue;<br>
> -<br>
> -      if (std::all_of(I->user_begin(), I->user_end(), [&](User *U) {<br>
> -            return DeadInstructions.count(cast<Instruction>(U));<br>
> -          })) {<br>
> -        NumberOfOptimizedInstructions += TTI.getUserCost(I);<br>
> -        DeadInstructions.insert(I);<br>
> -        EnqueueOperands(*I);<br>
> +    // To avoid compute SCEV-expressions on every iteration, compute them once<br>
> +    // and store interesting to us in SCEVCache.<br>
> +    cacheSCEVResults();<br>
> +<br>
> +    // Simulate execution of each iteration of the loop counting instructions,<br>
> +    // which would be simplified.<br>
> +    // Since the same load will take different values on different iterations,<br>
> +    // we literally have to go through all loop's iterations.<br>
> +    for (Iteration = 0; Iteration < TripCount; ++Iteration) {<br>
> +      SimplifiedValues.clear();<br>
> +      BBWorklist.clear();<br>
> +      BBWorklist.insert(L->getHeader());<br>
> +      // Note that we *must not* cache the size, this loop grows the worklist.<br>
> +      for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {<br>
> +        BasicBlock *BB = BBWorklist[Idx];<br>
> +<br>
> +        // Visit all instructions in the given basic block and try to simplify<br>
> +        // it.  We don't change the actual IR, just count optimization<br>
> +        // opportunities.<br>
> +        for (Instruction &I : *BB) {<br>
> +          UnrolledLoopSize += TTI.getUserCost(&I);<br>
> +          Base::visit(I);<br>
> +          // If unrolled body turns out to be too big, bail out.<br>
> +          if (UnrolledLoopSize - NumberOfOptimizedInstructions ><br>
> +              MaxUnrolledLoopSize)<br>
> +            return false;<br>
> +        }<br>
> +<br>
> +        // Add BB's successors to the worklist.<br>
> +        for (BasicBlock *Succ : successors(BB))<br>
> +          if (L->contains(Succ))<br>
> +            BBWorklist.insert(Succ);<br>
>       }<br>
> +<br>
> +      // If we found no optimization opportunities on the first iteration, we<br>
> +      // won't find them on later ones too.<br>
> +      if (!NumberOfOptimizedInstructions)<br>
> +        return false;<br>
>     }<br>
> -    return NumberOfOptimizedInstructions;<br>
> +    return true;<br>
>   }<br>
> };<br>
> } // namespace<br>
><br>
> -// Complete loop unrolling can make some loads constant, and we need to know if<br>
> -// that would expose any further optimization opportunities.<br>
> -// This routine estimates this optimization effect and returns the number of<br>
> -// instructions, that potentially might be optimized away.<br>
> -static unsigned<br>
> -approximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE,<br>
> -                                         unsigned TripCount,<br>
> -                                         const TargetTransformInfo &TTI) {<br>
> -  if (!TripCount || !UnrollMaxIterationsCountToAnalyze)<br>
> -    return 0;<br>
> -<br>
> -  UnrollAnalyzer UA(L, TripCount, SE, TTI);<br>
> -  UA.findConstFoldableLoads();<br>
> -<br>
> -  // Estimate number of instructions, that could be simplified if we replace a<br>
> -  // load with the corresponding constant. Since the same load will take<br>
> -  // different values on different iterations, we have to go through all loop's<br>
> -  // iterations here. To limit ourselves here, we check only first N<br>
> -  // iterations, and then scale the found number, if necessary.<br>
> -  unsigned IterationsNumberForEstimate =<br>
> -      std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount);<br>
> -  unsigned NumberOfOptimizedInstructions = 0;<br>
> -  for (unsigned i = 0; i < IterationsNumberForEstimate; ++i)<br>
> -    NumberOfOptimizedInstructions +=<br>
> -        UA.estimateNumberOfOptimizedInstructions(i);<br>
> -<br>
> -  NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate;<br>
> -<br>
> -  return NumberOfOptimizedInstructions;<br>
> -}<br>
> -<br>
> /// ApproximateLoopSize - Approximate the size of the loop.<br>
> static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,<br>
>                                     bool &NotDuplicatable,<br>
> @@ -679,6 +681,49 @@ static void SetLoopAlreadyUnrolled(Loop<br>
>   L->setLoopID(NewLoopID);<br>
> }<br>
><br>
> +bool LoopUnroll::canUnrollCompletely(<br>
> +    Loop *L, unsigned Threshold, unsigned AbsoluteThreshold,<br>
> +    uint64_t UnrolledSize, unsigned NumberOfOptimizedInstructions,<br>
> +    unsigned PercentOfOptimizedForCompleteUnroll) {<br>
> +<br>
> +  if (Threshold == NoThreshold) {<br>
> +    DEBUG(dbgs() << "  Can fully unroll, because no threshold is set.\n");<br>
> +    return true;<br>
> +  }<br>
> +<br>
> +  if (UnrolledSize <= Threshold) {<br>
> +    DEBUG(dbgs() << "  Can fully unroll, because unrolled size: "<br>
> +                 << UnrolledSize << "<" << Threshold << "\n");<br>
> +    return true;<br>
> +  }<br>
> +<br>
> +  assert(UnrolledSize && "UnrolledSize can't be 0 at this point.");<br>
> +  unsigned PercentOfOptimizedInstructions =<br>
> +      (uint64_t)NumberOfOptimizedInstructions * 100ull / UnrolledSize;<br>
> +<br>
> +  if (UnrolledSize <= AbsoluteThreshold &&<br>
> +      PercentOfOptimizedInstructions >= PercentOfOptimizedForCompleteUnroll) {<br>
> +    DEBUG(dbgs() << "  Can fully unroll, because unrolling will help removing "<br>
> +                 << PercentOfOptimizedInstructions<br>
> +                 << "% instructions (threshold: "<br>
> +                 << PercentOfOptimizedForCompleteUnroll << "%)\n");<br>
> +    DEBUG(dbgs() << "  Unrolled size (" << UnrolledSize<br>
> +                 << ") is less than the threshold (" << AbsoluteThreshold<br>
> +                 << ").\n");<br>
> +    return true;<br>
> +  }<br>
> +<br>
> +  DEBUG(dbgs() << "  Too large to fully unroll:\n");<br>
> +  DEBUG(dbgs() << "    Unrolled size: " << UnrolledSize << "\n");<br>
> +  DEBUG(dbgs() << "    Estimated number of optimized instructions: "<br>
> +               << NumberOfOptimizedInstructions << "\n");<br>
> +  DEBUG(dbgs() << "    Absolute threshold: " << AbsoluteThreshold << "\n");<br>
> +  DEBUG(dbgs() << "    Minimum percent of removed instructions: "<br>
> +               << PercentOfOptimizedForCompleteUnroll << "\n");<br>
> +  DEBUG(dbgs() << "    Threshold for small loops: " << Threshold << "\n");<br>
> +  return false;<br>
> +}<br>
> +<br>
> unsigned LoopUnroll::selectUnrollCount(<br>
>     const Loop *L, unsigned TripCount, bool PragmaFullUnroll,<br>
>     unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,<br>
> @@ -785,27 +830,34 @@ bool LoopUnroll::runOnLoop(Loop *L, LPPa<br>
>     return false;<br>
>   }<br>
><br>
> -  unsigned NumberOfOptimizedInstructions =<br>
> -      approximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI);<br>
> -  DEBUG(dbgs() << "  Complete unrolling could save: "<br>
> -               << NumberOfOptimizedInstructions << "\n");<br>
> -<br>
>   unsigned Threshold, PartialThreshold;<br>
> +  unsigned AbsoluteThreshold, PercentOfOptimizedForCompleteUnroll;<br>
>   selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,<br>
> -                   NumberOfOptimizedInstructions);<br>
> +                   AbsoluteThreshold, PercentOfOptimizedForCompleteUnroll);<br>
><br>
>   // Given Count, TripCount and thresholds determine the type of<br>
>   // unrolling which is to be performed.<br>
>   enum { Full = 0, Partial = 1, Runtime = 2 };<br>
>   int Unrolling;<br>
>   if (TripCount && Count == TripCount) {<br>
> -    if (Threshold != NoThreshold && UnrolledSize > Threshold) {<br>
> -      DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count<br>
> -                   << " because size: " << UnrolledSize << ">" << Threshold<br>
> -                   << "\n");<br>
> -      Unrolling = Partial;<br>
> -    } else {<br>
> +    Unrolling = Partial;<br>
> +    // If the loop is really small, we don't need to run an expensive analysis.<br>
> +    if (canUnrollCompletely(<br>
> +            L, Threshold, AbsoluteThreshold,<br>
> +            UnrolledSize, 0, 100)) {<br>
>       Unrolling = Full;<br>
> +    } else {<br>
> +      // The loop isn't that small, but we still can fully unroll it if that<br>
> +      // helps to remove a significant number of instructions.<br>
> +      // To check that, run additional analysis on the loop.<br>
> +      UnrollAnalyzer UA(L, TripCount, *SE, TTI, AbsoluteThreshold);<br>
> +      if (UA.analyzeLoop() &&<br>
> +          canUnrollCompletely(L, Threshold, AbsoluteThreshold,<br>
> +                              UA.UnrolledLoopSize,<br>
> +                              UA.NumberOfOptimizedInstructions,<br>
> +                              PercentOfOptimizedForCompleteUnroll)) {<br>
> +        Unrolling = Full;<br>
> +      }<br>
>     }<br>
>   } else if (TripCount && Count < TripCount) {<br>
>     Unrolling = Partial;<br>
><br>
> Added: llvm/trunk/test/Transforms/LoopUnroll/full-unroll-bad-geps.ll<br>
> URL: <a href="https://urldefense.proofpoint.com/v2/url?u=http-3A__llvm.org_viewvc_llvm-2Dproject_llvm_trunk_test_Transforms_LoopUnroll_full-2Dunroll-2Dbad-2Dgeps.ll-3Frev-3D237156-26view-3Dauto&d=AwMFaQ&c=8hUWFZcy2Z-Za5rBPlktOQ&r=mQ4LZ2PUj9hpadE3cDHZnIdEwhEBrbAstXeMaFoB9tg&m=-SpI0905drQheNhlFb1R0Es0Lpj3x3iYMYgNlqIRN_E&s=jHcB6YGi88nfOvK1a8zJ3lck7K-MJ7BX0mlFNMKBCWA&e=" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/LoopUnroll/full-unroll-bad-geps.ll?rev=237156&view=auto</a><br>
> ==============================================================================<br>
> --- llvm/trunk/test/Transforms/LoopUnroll/full-unroll-bad-geps.ll (added)<br>
> +++ llvm/trunk/test/Transforms/LoopUnroll/full-unroll-bad-geps.ll Tue May 12 12:20:03 2015<br>
> @@ -0,0 +1,34 @@<br>
> +; Check that we don't crash on corner cases.<br>
> +; RUN: opt < %s -S -loop-unroll -unroll-max-iteration-count-to-analyze=1000 -unroll-absolute-threshold=10  -unroll-threshold=10  -unroll-percent-of-optimized-for-complete-unroll=20 -o /dev/null<br>
> +target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"<br>
> +<br>
> +define void @foo1() {<br>
> +entry:<br>
> +  br label %for.body<br>
> +<br>
> +for.body:<br>
> +  %phi = phi i64 [ 0, %entry ], [ %inc, %for.body ]<br>
> +  %idx = zext i32 undef to i64<br>
> +  %add.ptr = getelementptr inbounds i64, i64* null, i64 %idx<br>
> +  %inc = add nuw nsw i64 %phi, 1<br>
> +  %cmp = icmp ult i64 %inc, 999<br>
> +  br i1 %cmp, label %for.body, label %for.exit<br>
> +<br>
> +for.exit:<br>
> +  ret void<br>
> +}<br>
> +<br>
> +define void @foo2() {<br>
> +entry:<br>
> +  br label %for.body<br>
> +<br>
> +for.body:<br>
> +  %phi = phi i64 [ 0, %entry ], [ %inc, %for.body ]<br>
> +  %x = getelementptr i32, <4 x i32*> undef, <4 x i32> <i32 1, i32 1, i32 1, i32 1><br>
> +  %inc = add nuw nsw i64 %phi, 1<br>
> +  %cmp = icmp ult i64 %inc, 999<br>
> +  br i1 %cmp, label %for.body, label %for.exit<br>
> +<br>
> +for.exit:<br>
> +  ret void<br>
> +}<br>
><br>
> Modified: llvm/trunk/test/Transforms/LoopUnroll/full-unroll-heuristics.ll<br>
> URL: <a href="https://urldefense.proofpoint.com/v2/url?u=http-3A__llvm.org_viewvc_llvm-2Dproject_llvm_trunk_test_Transforms_LoopUnroll_full-2Dunroll-2Dheuristics.ll-3Frev-3D237156-26r1-3D237155-26r2-3D237156-26view-3Ddiff&d=AwMFaQ&c=8hUWFZcy2Z-Za5rBPlktOQ&r=mQ4LZ2PUj9hpadE3cDHZnIdEwhEBrbAstXeMaFoB9tg&m=-SpI0905drQheNhlFb1R0Es0Lpj3x3iYMYgNlqIRN_E&s=oBpjmTBQeji_tN9288ZuBgMPRGAb-E72jhbrzFlOHlk&e=" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/LoopUnroll/full-unroll-heuristics.ll?rev=237156&r1=237155&r2=237156&view=diff</a><br>
> ==============================================================================<br>
> --- llvm/trunk/test/Transforms/LoopUnroll/full-unroll-heuristics.ll (original)<br>
> +++ llvm/trunk/test/Transforms/LoopUnroll/full-unroll-heuristics.ll Tue May 12 12:20:03 2015<br>
> @@ -17,8 +17,8 @@<br>
> ; optimizations to remove ~55% of the instructions, the loop body size is 9,<br>
> ; and unrolled size is 65.<br>
><br>
> -; RUN: opt < %s -S -loop-unroll -unroll-max-iteration-count-to-analyze=1000 -unroll-absolute-threshold=10  -unroll-threshold=10  -unroll-percent-of-optimized-for-complete-unroll=30 | FileCheck %s -check-prefix=TEST1<br>
> -; RUN: opt < %s -S -loop-unroll -unroll-max-iteration-count-to-analyze=1000 -unroll-absolute-threshold=100 -unroll-threshold=10  -unroll-percent-of-optimized-for-complete-unroll=30 | FileCheck %s -check-prefix=TEST2<br>
> +; RUN: opt < %s -S -loop-unroll -unroll-max-iteration-count-to-analyze=1000 -unroll-absolute-threshold=10  -unroll-threshold=10  -unroll-percent-of-optimized-for-complete-unroll=20 | FileCheck %s -check-prefix=TEST1<br>
> +; RUN: opt < %s -S -loop-unroll -unroll-max-iteration-count-to-analyze=1000 -unroll-absolute-threshold=100 -unroll-threshold=10  -unroll-percent-of-optimized-for-complete-unroll=20 | FileCheck %s -check-prefix=TEST2<br>
> ; RUN: opt < %s -S -loop-unroll -unroll-max-iteration-count-to-analyze=1000 -unroll-absolute-threshold=100 -unroll-threshold=10  -unroll-percent-of-optimized-for-complete-unroll=80 | FileCheck %s -check-prefix=TEST3<br>
> ; RUN: opt < %s -S -loop-unroll -unroll-max-iteration-count-to-analyze=1000 -unroll-absolute-threshold=100 -unroll-threshold=100 -unroll-percent-of-optimized-for-complete-unroll=80 | FileCheck %s -check-prefix=TEST4<br>
><br>
><br>
><br>
> _______________________________________________<br>
> llvm-commits mailing list<br>
> <a href="mailto:llvm-commits@cs.uiuc.edu" target="_blank">llvm-commits@cs.uiuc.edu</a><br>
> <a href="http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits" target="_blank">http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits</a><br>
<br>
</blockquote></div>