Home | History | Annotate | Download | only in Scalar
      1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This pass implements a simple loop unroller.  It works best when loops have
     11 // been canonicalized by the -indvars pass, allowing it to determine the trip
     12 // counts of loops easily.
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "llvm/Transforms/Scalar.h"
     16 #include "llvm/ADT/SetVector.h"
     17 #include "llvm/Analysis/GlobalsModRef.h"
     18 #include "llvm/Analysis/AssumptionCache.h"
     19 #include "llvm/Analysis/CodeMetrics.h"
     20 #include "llvm/Analysis/InstructionSimplify.h"
     21 #include "llvm/Analysis/LoopPass.h"
     22 #include "llvm/Analysis/ScalarEvolution.h"
     23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
     24 #include "llvm/Analysis/TargetTransformInfo.h"
     25 #include "llvm/IR/DataLayout.h"
     26 #include "llvm/IR/DiagnosticInfo.h"
     27 #include "llvm/IR/Dominators.h"
     28 #include "llvm/IR/InstVisitor.h"
     29 #include "llvm/IR/IntrinsicInst.h"
     30 #include "llvm/IR/Metadata.h"
     31 #include "llvm/Support/CommandLine.h"
     32 #include "llvm/Support/Debug.h"
     33 #include "llvm/Support/raw_ostream.h"
     34 #include "llvm/Transforms/Utils/UnrollLoop.h"
     35 #include <climits>
     36 
     37 using namespace llvm;
     38 
     39 #define DEBUG_TYPE "loop-unroll"
     40 
     41 static cl::opt<unsigned>
     42     UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
     43                     cl::desc("The baseline cost threshold for loop unrolling"));
     44 
     45 static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
     46     "unroll-percent-dynamic-cost-saved-threshold", cl::init(20), cl::Hidden,
     47     cl::desc("The percentage of estimated dynamic cost which must be saved by "
     48              "unrolling to allow unrolling up to the max threshold."));
     49 
     50 static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
     51     "unroll-dynamic-cost-savings-discount", cl::init(2000), cl::Hidden,
     52     cl::desc("This is the amount discounted from the total unroll cost when "
     53              "the unrolled form has a high dynamic cost savings (triggered by "
     54              "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
     55 
     56 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
     57     "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
     58     cl::desc("Don't allow loop unrolling to simulate more than this number of"
     59              "iterations when checking full unroll profitability"));
     60 
     61 static cl::opt<unsigned>
     62 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
     63   cl::desc("Use this unroll count for all loops including those with "
     64            "unroll_count pragma values, for testing purposes"));
     65 
     66 static cl::opt<bool>
     67 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
     68   cl::desc("Allows loops to be partially unrolled until "
     69            "-unroll-threshold loop size is reached."));
     70 
     71 static cl::opt<bool>
     72 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
     73   cl::desc("Unroll loops with run-time trip counts"));
     74 
     75 static cl::opt<unsigned>
     76 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
     77   cl::desc("Unrolled size limit for loops with an unroll(full) or "
     78            "unroll_count pragma."));
     79 
     80 namespace {
     81   class LoopUnroll : public LoopPass {
     82   public:
     83     static char ID; // Pass ID, replacement for typeid
     84     LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
     85       CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
     86       CurrentPercentDynamicCostSavedThreshold =
     87           UnrollPercentDynamicCostSavedThreshold;
     88       CurrentDynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
     89       CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
     90       CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
     91       CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
     92 
     93       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
     94       UserPercentDynamicCostSavedThreshold =
     95           (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0);
     96       UserDynamicCostSavingsDiscount =
     97           (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0);
     98       UserAllowPartial = (P != -1) ||
     99                          (UnrollAllowPartial.getNumOccurrences() > 0);
    100       UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
    101       UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
    102 
    103       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
    104     }
    105 
    106     /// A magic value for use with the Threshold parameter to indicate
    107     /// that the loop unroll should be performed regardless of how much
    108     /// code expansion would result.
    109     static const unsigned NoThreshold = UINT_MAX;
    110 
    111     // Threshold to use when optsize is specified (and there is no
    112     // explicit -unroll-threshold).
    113     static const unsigned OptSizeUnrollThreshold = 50;
    114 
    115     // Default unroll count for loops with run-time trip count if
    116     // -unroll-count is not set
    117     static const unsigned UnrollRuntimeCount = 8;
    118 
    119     unsigned CurrentCount;
    120     unsigned CurrentThreshold;
    121     unsigned CurrentPercentDynamicCostSavedThreshold;
    122     unsigned CurrentDynamicCostSavingsDiscount;
    123     bool CurrentAllowPartial;
    124     bool CurrentRuntime;
    125 
    126     // Flags for whether the 'current' settings are user-specified.
    127     bool UserCount;
    128     bool UserThreshold;
    129     bool UserPercentDynamicCostSavedThreshold;
    130     bool UserDynamicCostSavingsDiscount;
    131     bool UserAllowPartial;
    132     bool UserRuntime;
    133 
    134     bool runOnLoop(Loop *L, LPPassManager &) override;
    135 
    136     /// This transformation requires natural loop information & requires that
    137     /// loop preheaders be inserted into the CFG...
    138     ///
    139     void getAnalysisUsage(AnalysisUsage &AU) const override {
    140       AU.addRequired<AssumptionCacheTracker>();
    141       AU.addRequired<DominatorTreeWrapperPass>();
    142       AU.addRequired<LoopInfoWrapperPass>();
    143       AU.addPreserved<LoopInfoWrapperPass>();
    144       AU.addRequiredID(LoopSimplifyID);
    145       AU.addPreservedID(LoopSimplifyID);
    146       AU.addRequiredID(LCSSAID);
    147       AU.addPreservedID(LCSSAID);
    148       AU.addRequired<ScalarEvolutionWrapperPass>();
    149       AU.addPreserved<ScalarEvolutionWrapperPass>();
    150       AU.addRequired<TargetTransformInfoWrapperPass>();
    151       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
    152       // If loop unroll does not preserve dom info then LCSSA pass on next
    153       // loop will receive invalid dom info.
    154       // For now, recreate dom info, if loop is unrolled.
    155       AU.addPreserved<DominatorTreeWrapperPass>();
    156       AU.addPreserved<GlobalsAAWrapperPass>();
    157     }
    158 
    159     // Fill in the UnrollingPreferences parameter with values from the
    160     // TargetTransformationInfo.
    161     void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
    162                                  TargetTransformInfo::UnrollingPreferences &UP) {
    163       UP.Threshold = CurrentThreshold;
    164       UP.PercentDynamicCostSavedThreshold =
    165           CurrentPercentDynamicCostSavedThreshold;
    166       UP.DynamicCostSavingsDiscount = CurrentDynamicCostSavingsDiscount;
    167       UP.OptSizeThreshold = OptSizeUnrollThreshold;
    168       UP.PartialThreshold = CurrentThreshold;
    169       UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
    170       UP.Count = CurrentCount;
    171       UP.MaxCount = UINT_MAX;
    172       UP.Partial = CurrentAllowPartial;
    173       UP.Runtime = CurrentRuntime;
    174       UP.AllowExpensiveTripCount = false;
    175       TTI.getUnrollingPreferences(L, UP);
    176     }
    177 
    178     // Select and return an unroll count based on parameters from
    179     // user, unroll preferences, unroll pragmas, or a heuristic.
    180     // SetExplicitly is set to true if the unroll count is is set by
    181     // the user or a pragma rather than selected heuristically.
    182     unsigned
    183     selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
    184                       unsigned PragmaCount,
    185                       const TargetTransformInfo::UnrollingPreferences &UP,
    186                       bool &SetExplicitly);
    187 
    188     // Select threshold values used to limit unrolling based on a
    189     // total unrolled size.  Parameters Threshold and PartialThreshold
    190     // are set to the maximum unrolled size for fully and partially
    191     // unrolled loops respectively.
    192     void selectThresholds(const Loop *L, bool UsePragmaThreshold,
    193                           const TargetTransformInfo::UnrollingPreferences &UP,
    194                           unsigned &Threshold, unsigned &PartialThreshold,
    195                           unsigned &PercentDynamicCostSavedThreshold,
    196                           unsigned &DynamicCostSavingsDiscount) {
    197       // Determine the current unrolling threshold.  While this is
    198       // normally set from UnrollThreshold, it is overridden to a
    199       // smaller value if the current function is marked as
    200       // optimize-for-size, and the unroll threshold was not user
    201       // specified.
    202       Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
    203       PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
    204       PercentDynamicCostSavedThreshold =
    205           UserPercentDynamicCostSavedThreshold
    206               ? CurrentPercentDynamicCostSavedThreshold
    207               : UP.PercentDynamicCostSavedThreshold;
    208       DynamicCostSavingsDiscount = UserDynamicCostSavingsDiscount
    209                                        ? CurrentDynamicCostSavingsDiscount
    210                                        : UP.DynamicCostSavingsDiscount;
    211 
    212       if (!UserThreshold &&
    213           // FIXME: Use Function::optForSize().
    214           L->getHeader()->getParent()->hasFnAttribute(
    215               Attribute::OptimizeForSize)) {
    216         Threshold = UP.OptSizeThreshold;
    217         PartialThreshold = UP.PartialOptSizeThreshold;
    218       }
    219       if (UsePragmaThreshold) {
    220         // If the loop has an unrolling pragma, we want to be more
    221         // aggressive with unrolling limits.  Set thresholds to at
    222         // least the PragmaTheshold value which is larger than the
    223         // default limits.
    224         if (Threshold != NoThreshold)
    225           Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
    226         if (PartialThreshold != NoThreshold)
    227           PartialThreshold =
    228               std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
    229       }
    230     }
    231     bool canUnrollCompletely(Loop *L, unsigned Threshold,
    232                              unsigned PercentDynamicCostSavedThreshold,
    233                              unsigned DynamicCostSavingsDiscount,
    234                              uint64_t UnrolledCost, uint64_t RolledDynamicCost);
    235   };
    236 }
    237 
    238 char LoopUnroll::ID = 0;
    239 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
    240 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
    241 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
    242 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
    243 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
    244 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
    245 INITIALIZE_PASS_DEPENDENCY(LCSSA)
    246 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
    247 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
    248 
    249 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
    250                                  int Runtime) {
    251   return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
    252 }
    253 
    254 Pass *llvm::createSimpleLoopUnrollPass() {
    255   return llvm::createLoopUnrollPass(-1, -1, 0, 0);
    256 }
    257 
    258 namespace {
    259 // This class is used to get an estimate of the optimization effects that we
    260 // could get from complete loop unrolling. It comes from the fact that some
    261 // loads might be replaced with concrete constant values and that could trigger
    262 // a chain of instruction simplifications.
    263 //
    264 // E.g. we might have:
    265 //   int a[] = {0, 1, 0};
    266 //   v = 0;
    267 //   for (i = 0; i < 3; i ++)
    268 //     v += b[i]*a[i];
    269 // If we completely unroll the loop, we would get:
    270 //   v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
    271 // Which then will be simplified to:
    272 //   v = b[0]* 0 + b[1]* 1 + b[2]* 0
    273 // And finally:
    274 //   v = b[1]
    275 class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> {
    276   typedef InstVisitor<UnrolledInstAnalyzer, bool> Base;
    277   friend class InstVisitor<UnrolledInstAnalyzer, bool>;
    278   struct SimplifiedAddress {
    279     Value *Base = nullptr;
    280     ConstantInt *Offset = nullptr;
    281   };
    282 
    283 public:
    284   UnrolledInstAnalyzer(unsigned Iteration,
    285                        DenseMap<Value *, Constant *> &SimplifiedValues,
    286                        ScalarEvolution &SE)
    287       : SimplifiedValues(SimplifiedValues), SE(SE) {
    288       IterationNumber = SE.getConstant(APInt(64, Iteration));
    289   }
    290 
    291   // Allow access to the initial visit method.
    292   using Base::visit;
    293 
    294 private:
    295   /// \brief A cache of pointer bases and constant-folded offsets corresponding
    296   /// to GEP (or derived from GEP) instructions.
    297   ///
    298   /// In order to find the base pointer one needs to perform non-trivial
    299   /// traversal of the corresponding SCEV expression, so it's good to have the
    300   /// results saved.
    301   DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses;
    302 
    303   /// \brief SCEV expression corresponding to number of currently simulated
    304   /// iteration.
    305   const SCEV *IterationNumber;
    306 
    307   /// \brief A Value->Constant map for keeping values that we managed to
    308   /// constant-fold on the given iteration.
    309   ///
    310   /// While we walk the loop instructions, we build up and maintain a mapping
    311   /// of simplified values specific to this iteration.  The idea is to propagate
    312   /// any special information we have about loads that can be replaced with
    313   /// constants after complete unrolling, and account for likely simplifications
    314   /// post-unrolling.
    315   DenseMap<Value *, Constant *> &SimplifiedValues;
    316 
    317   ScalarEvolution &SE;
    318 
    319   /// \brief Try to simplify instruction \param I using its SCEV expression.
    320   ///
    321   /// The idea is that some AddRec expressions become constants, which then
    322   /// could trigger folding of other instructions. However, that only happens
    323   /// for expressions whose start value is also constant, which isn't always the
    324   /// case. In another common and important case the start value is just some
    325   /// address (i.e. SCEVUnknown) - in this case we compute the offset and save
    326   /// it along with the base address instead.
    327   bool simplifyInstWithSCEV(Instruction *I) {
    328     if (!SE.isSCEVable(I->getType()))
    329       return false;
    330 
    331     const SCEV *S = SE.getSCEV(I);
    332     if (auto *SC = dyn_cast<SCEVConstant>(S)) {
    333       SimplifiedValues[I] = SC->getValue();
    334       return true;
    335     }
    336 
    337     auto *AR = dyn_cast<SCEVAddRecExpr>(S);
    338     if (!AR)
    339       return false;
    340 
    341     const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE);
    342     // Check if the AddRec expression becomes a constant.
    343     if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) {
    344       SimplifiedValues[I] = SC->getValue();
    345       return true;
    346     }
    347 
    348     // Check if the offset from the base address becomes a constant.
    349     auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S));
    350     if (!Base)
    351       return false;
    352     auto *Offset =
    353         dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base));
    354     if (!Offset)
    355       return false;
    356     SimplifiedAddress Address;
    357     Address.Base = Base->getValue();
    358     Address.Offset = Offset->getValue();
    359     SimplifiedAddresses[I] = Address;
    360     return true;
    361   }
    362 
    363   /// Base case for the instruction visitor.
    364   bool visitInstruction(Instruction &I) {
    365     return simplifyInstWithSCEV(&I);
    366   }
    367 
    368   /// Try to simplify binary operator I.
    369   ///
    370   /// TODO: Probably it's worth to hoist the code for estimating the
    371   /// simplifications effects to a separate class, since we have a very similar
    372   /// code in InlineCost already.
    373   bool visitBinaryOperator(BinaryOperator &I) {
    374     Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
    375     if (!isa<Constant>(LHS))
    376       if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
    377         LHS = SimpleLHS;
    378     if (!isa<Constant>(RHS))
    379       if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
    380         RHS = SimpleRHS;
    381 
    382     Value *SimpleV = nullptr;
    383     const DataLayout &DL = I.getModule()->getDataLayout();
    384     if (auto FI = dyn_cast<FPMathOperator>(&I))
    385       SimpleV =
    386           SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
    387     else
    388       SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
    389 
    390     if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
    391       SimplifiedValues[&I] = C;
    392 
    393     if (SimpleV)
    394       return true;
    395     return Base::visitBinaryOperator(I);
    396   }
    397 
    398   /// Try to fold load I.
    399   bool visitLoad(LoadInst &I) {
    400     Value *AddrOp = I.getPointerOperand();
    401 
    402     auto AddressIt = SimplifiedAddresses.find(AddrOp);
    403     if (AddressIt == SimplifiedAddresses.end())
    404       return false;
    405     ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset;
    406 
    407     auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base);
    408     // We're only interested in loads that can be completely folded to a
    409     // constant.
    410     if (!GV || !GV->hasDefinitiveInitializer() || !GV->isConstant())
    411       return false;
    412 
    413     ConstantDataSequential *CDS =
    414         dyn_cast<ConstantDataSequential>(GV->getInitializer());
    415     if (!CDS)
    416       return false;
    417 
    418     // We might have a vector load from an array. FIXME: for now we just bail
    419     // out in this case, but we should be able to resolve and simplify such
    420     // loads.
    421     if(!CDS->isElementTypeCompatible(I.getType()))
    422       return false;
    423 
    424     int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
    425     assert(SimplifiedAddrOp->getValue().getActiveBits() < 64 &&
    426            "Unexpectedly large index value.");
    427     int64_t Index = SimplifiedAddrOp->getSExtValue() / ElemSize;
    428     if (Index >= CDS->getNumElements()) {
    429       // FIXME: For now we conservatively ignore out of bound accesses, but
    430       // we're allowed to perform the optimization in this case.
    431       return false;
    432     }
    433 
    434     Constant *CV = CDS->getElementAsConstant(Index);
    435     assert(CV && "Constant expected.");
    436     SimplifiedValues[&I] = CV;
    437 
    438     return true;
    439   }
    440 
    441   bool visitCastInst(CastInst &I) {
    442     // Propagate constants through casts.
    443     Constant *COp = dyn_cast<Constant>(I.getOperand(0));
    444     if (!COp)
    445       COp = SimplifiedValues.lookup(I.getOperand(0));
    446     if (COp)
    447       if (Constant *C =
    448               ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
    449         SimplifiedValues[&I] = C;
    450         return true;
    451       }
    452 
    453     return Base::visitCastInst(I);
    454   }
    455 
    456   bool visitCmpInst(CmpInst &I) {
    457     Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
    458 
    459     // First try to handle simplified comparisons.
    460     if (!isa<Constant>(LHS))
    461       if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
    462         LHS = SimpleLHS;
    463     if (!isa<Constant>(RHS))
    464       if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
    465         RHS = SimpleRHS;
    466 
    467     if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) {
    468       auto SimplifiedLHS = SimplifiedAddresses.find(LHS);
    469       if (SimplifiedLHS != SimplifiedAddresses.end()) {
    470         auto SimplifiedRHS = SimplifiedAddresses.find(RHS);
    471         if (SimplifiedRHS != SimplifiedAddresses.end()) {
    472           SimplifiedAddress &LHSAddr = SimplifiedLHS->second;
    473           SimplifiedAddress &RHSAddr = SimplifiedRHS->second;
    474           if (LHSAddr.Base == RHSAddr.Base) {
    475             LHS = LHSAddr.Offset;
    476             RHS = RHSAddr.Offset;
    477           }
    478         }
    479       }
    480     }
    481 
    482     if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
    483       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
    484         if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
    485           SimplifiedValues[&I] = C;
    486           return true;
    487         }
    488       }
    489     }
    490 
    491     return Base::visitCmpInst(I);
    492   }
    493 };
    494 } // namespace
    495 
    496 
    497 namespace {
    498 struct EstimatedUnrollCost {
    499   /// \brief The estimated cost after unrolling.
    500   int UnrolledCost;
    501 
    502   /// \brief The estimated dynamic cost of executing the instructions in the
    503   /// rolled form.
    504   int RolledDynamicCost;
    505 };
    506 }
    507 
    508 /// \brief Figure out if the loop is worth full unrolling.
    509 ///
    510 /// Complete loop unrolling can make some loads constant, and we need to know
    511 /// if that would expose any further optimization opportunities.  This routine
    512 /// estimates this optimization.  It computes cost of unrolled loop
    513 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
    514 /// dynamic cost we mean that we won't count costs of blocks that are known not
    515 /// to be executed (i.e. if we have a branch in the loop and we know that at the
    516 /// given iteration its condition would be resolved to true, we won't add up the
    517 /// cost of the 'false'-block).
    518 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
    519 /// the analysis failed (no benefits expected from the unrolling, or the loop is
    520 /// too big to analyze), the returned value is None.
    521 static Optional<EstimatedUnrollCost>
    522 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
    523                       ScalarEvolution &SE, const TargetTransformInfo &TTI,
    524                       int MaxUnrolledLoopSize) {
    525   // We want to be able to scale offsets by the trip count and add more offsets
    526   // to them without checking for overflows, and we already don't want to
    527   // analyze *massive* trip counts, so we force the max to be reasonably small.
    528   assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
    529          "The unroll iterations max is too large!");
    530 
    531   // Don't simulate loops with a big or unknown tripcount
    532   if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
    533       TripCount > UnrollMaxIterationsCountToAnalyze)
    534     return None;
    535 
    536   SmallSetVector<BasicBlock *, 16> BBWorklist;
    537   DenseMap<Value *, Constant *> SimplifiedValues;
    538   SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
    539 
    540   // The estimated cost of the unrolled form of the loop. We try to estimate
    541   // this by simplifying as much as we can while computing the estimate.
    542   int UnrolledCost = 0;
    543   // We also track the estimated dynamic (that is, actually executed) cost in
    544   // the rolled form. This helps identify cases when the savings from unrolling
    545   // aren't just exposing dead control flows, but actual reduced dynamic
    546   // instructions due to the simplifications which we expect to occur after
    547   // unrolling.
    548   int RolledDynamicCost = 0;
    549 
    550   // Ensure that we don't violate the loop structure invariants relied on by
    551   // this analysis.
    552   assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
    553   assert(L->isLCSSAForm(DT) &&
    554          "Must have loops in LCSSA form to track live-out values.");
    555 
    556   DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
    557 
    558   // Simulate execution of each iteration of the loop counting instructions,
    559   // which would be simplified.
    560   // Since the same load will take different values on different iterations,
    561   // we literally have to go through all loop's iterations.
    562   for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
    563     DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
    564 
    565     // Prepare for the iteration by collecting any simplified entry or backedge
    566     // inputs.
    567     for (Instruction &I : *L->getHeader()) {
    568       auto *PHI = dyn_cast<PHINode>(&I);
    569       if (!PHI)
    570         break;
    571 
    572       // The loop header PHI nodes must have exactly two input: one from the
    573       // loop preheader and one from the loop latch.
    574       assert(
    575           PHI->getNumIncomingValues() == 2 &&
    576           "Must have an incoming value only for the preheader and the latch.");
    577 
    578       Value *V = PHI->getIncomingValueForBlock(
    579           Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
    580       Constant *C = dyn_cast<Constant>(V);
    581       if (Iteration != 0 && !C)
    582         C = SimplifiedValues.lookup(V);
    583       if (C)
    584         SimplifiedInputValues.push_back({PHI, C});
    585     }
    586 
    587     // Now clear and re-populate the map for the next iteration.
    588     SimplifiedValues.clear();
    589     while (!SimplifiedInputValues.empty())
    590       SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
    591 
    592     UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE);
    593 
    594     BBWorklist.clear();
    595     BBWorklist.insert(L->getHeader());
    596     // Note that we *must not* cache the size, this loop grows the worklist.
    597     for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
    598       BasicBlock *BB = BBWorklist[Idx];
    599 
    600       // Visit all instructions in the given basic block and try to simplify
    601       // it.  We don't change the actual IR, just count optimization
    602       // opportunities.
    603       for (Instruction &I : *BB) {
    604         int InstCost = TTI.getUserCost(&I);
    605 
    606         // Visit the instruction to analyze its loop cost after unrolling,
    607         // and if the visitor returns false, include this instruction in the
    608         // unrolled cost.
    609         if (!Analyzer.visit(I))
    610           UnrolledCost += InstCost;
    611         else {
    612           DEBUG(dbgs() << "  " << I
    613                        << " would be simplified if loop is unrolled.\n");
    614           (void)0;
    615         }
    616 
    617         // Also track this instructions expected cost when executing the rolled
    618         // loop form.
    619         RolledDynamicCost += InstCost;
    620 
    621         // If unrolled body turns out to be too big, bail out.
    622         if (UnrolledCost > MaxUnrolledLoopSize) {
    623           DEBUG(dbgs() << "  Exceeded threshold.. exiting.\n"
    624                        << "  UnrolledCost: " << UnrolledCost
    625                        << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
    626                        << "\n");
    627           return None;
    628         }
    629       }
    630 
    631       TerminatorInst *TI = BB->getTerminator();
    632 
    633       // Add in the live successors by first checking whether we have terminator
    634       // that may be simplified based on the values simplified by this call.
    635       if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
    636         if (BI->isConditional()) {
    637           if (Constant *SimpleCond =
    638                   SimplifiedValues.lookup(BI->getCondition())) {
    639             BasicBlock *Succ = nullptr;
    640             // Just take the first successor if condition is undef
    641             if (isa<UndefValue>(SimpleCond))
    642               Succ = BI->getSuccessor(0);
    643             else
    644               Succ = BI->getSuccessor(
    645                   cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0);
    646             if (L->contains(Succ))
    647               BBWorklist.insert(Succ);
    648             continue;
    649           }
    650         }
    651       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
    652         if (Constant *SimpleCond =
    653                 SimplifiedValues.lookup(SI->getCondition())) {
    654           BasicBlock *Succ = nullptr;
    655           // Just take the first successor if condition is undef
    656           if (isa<UndefValue>(SimpleCond))
    657             Succ = SI->getSuccessor(0);
    658           else
    659             Succ = SI->findCaseValue(cast<ConstantInt>(SimpleCond))
    660                        .getCaseSuccessor();
    661           if (L->contains(Succ))
    662             BBWorklist.insert(Succ);
    663           continue;
    664         }
    665       }
    666 
    667       // Add BB's successors to the worklist.
    668       for (BasicBlock *Succ : successors(BB))
    669         if (L->contains(Succ))
    670           BBWorklist.insert(Succ);
    671     }
    672 
    673     // If we found no optimization opportunities on the first iteration, we
    674     // won't find them on later ones too.
    675     if (UnrolledCost == RolledDynamicCost) {
    676       DEBUG(dbgs() << "  No opportunities found.. exiting.\n"
    677                    << "  UnrolledCost: " << UnrolledCost << "\n");
    678       return None;
    679     }
    680   }
    681   DEBUG(dbgs() << "Analysis finished:\n"
    682                << "UnrolledCost: " << UnrolledCost << ", "
    683                << "RolledDynamicCost: " << RolledDynamicCost << "\n");
    684   return {{UnrolledCost, RolledDynamicCost}};
    685 }
    686 
    687 /// ApproximateLoopSize - Approximate the size of the loop.
    688 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
    689                                     bool &NotDuplicatable,
    690                                     const TargetTransformInfo &TTI,
    691                                     AssumptionCache *AC) {
    692   SmallPtrSet<const Value *, 32> EphValues;
    693   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
    694 
    695   CodeMetrics Metrics;
    696   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
    697        I != E; ++I)
    698     Metrics.analyzeBasicBlock(*I, TTI, EphValues);
    699   NumCalls = Metrics.NumInlineCandidates;
    700   NotDuplicatable = Metrics.notDuplicatable;
    701 
    702   unsigned LoopSize = Metrics.NumInsts;
    703 
    704   // Don't allow an estimate of size zero.  This would allows unrolling of loops
    705   // with huge iteration counts, which is a compile time problem even if it's
    706   // not a problem for code quality. Also, the code using this size may assume
    707   // that each loop has at least three instructions (likely a conditional
    708   // branch, a comparison feeding that branch, and some kind of loop increment
    709   // feeding that comparison instruction).
    710   LoopSize = std::max(LoopSize, 3u);
    711 
    712   return LoopSize;
    713 }
    714 
    715 // Returns the loop hint metadata node with the given name (for example,
    716 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
    717 // returned.
    718 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
    719   if (MDNode *LoopID = L->getLoopID())
    720     return GetUnrollMetadata(LoopID, Name);
    721   return nullptr;
    722 }
    723 
    724 // Returns true if the loop has an unroll(full) pragma.
    725 static bool HasUnrollFullPragma(const Loop *L) {
    726   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
    727 }
    728 
    729 // Returns true if the loop has an unroll(enable) pragma. This metadata is used
    730 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
    731 static bool HasUnrollEnablePragma(const Loop *L) {
    732   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
    733 }
    734 
    735 // Returns true if the loop has an unroll(disable) pragma.
    736 static bool HasUnrollDisablePragma(const Loop *L) {
    737   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
    738 }
    739 
    740 // Returns true if the loop has an runtime unroll(disable) pragma.
    741 static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
    742   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
    743 }
    744 
    745 // If loop has an unroll_count pragma return the (necessarily
    746 // positive) value from the pragma.  Otherwise return 0.
    747 static unsigned UnrollCountPragmaValue(const Loop *L) {
    748   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
    749   if (MD) {
    750     assert(MD->getNumOperands() == 2 &&
    751            "Unroll count hint metadata should have two operands.");
    752     unsigned Count =
    753         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
    754     assert(Count >= 1 && "Unroll count must be positive.");
    755     return Count;
    756   }
    757   return 0;
    758 }
    759 
    760 // Remove existing unroll metadata and add unroll disable metadata to
    761 // indicate the loop has already been unrolled.  This prevents a loop
    762 // from being unrolled more than is directed by a pragma if the loop
    763 // unrolling pass is run more than once (which it generally is).
    764 static void SetLoopAlreadyUnrolled(Loop *L) {
    765   MDNode *LoopID = L->getLoopID();
    766   if (!LoopID) return;
    767 
    768   // First remove any existing loop unrolling metadata.
    769   SmallVector<Metadata *, 4> MDs;
    770   // Reserve first location for self reference to the LoopID metadata node.
    771   MDs.push_back(nullptr);
    772   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
    773     bool IsUnrollMetadata = false;
    774     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
    775     if (MD) {
    776       const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
    777       IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
    778     }
    779     if (!IsUnrollMetadata)
    780       MDs.push_back(LoopID->getOperand(i));
    781   }
    782 
    783   // Add unroll(disable) metadata to disable future unrolling.
    784   LLVMContext &Context = L->getHeader()->getContext();
    785   SmallVector<Metadata *, 1> DisableOperands;
    786   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
    787   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
    788   MDs.push_back(DisableNode);
    789 
    790   MDNode *NewLoopID = MDNode::get(Context, MDs);
    791   // Set operand 0 to refer to the loop id itself.
    792   NewLoopID->replaceOperandWith(0, NewLoopID);
    793   L->setLoopID(NewLoopID);
    794 }
    795 
    796 bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold,
    797                                      unsigned PercentDynamicCostSavedThreshold,
    798                                      unsigned DynamicCostSavingsDiscount,
    799                                      uint64_t UnrolledCost,
    800                                      uint64_t RolledDynamicCost) {
    801 
    802   if (Threshold == NoThreshold) {
    803     DEBUG(dbgs() << "  Can fully unroll, because no threshold is set.\n");
    804     return true;
    805   }
    806 
    807   if (UnrolledCost <= Threshold) {
    808     DEBUG(dbgs() << "  Can fully unroll, because unrolled cost: "
    809                  << UnrolledCost << "<" << Threshold << "\n");
    810     return true;
    811   }
    812 
    813   assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
    814   assert(RolledDynamicCost >= UnrolledCost &&
    815          "Cannot have a higher unrolled cost than a rolled cost!");
    816 
    817   // Compute the percentage of the dynamic cost in the rolled form that is
    818   // saved when unrolled. If unrolling dramatically reduces the estimated
    819   // dynamic cost of the loop, we use a higher threshold to allow more
    820   // unrolling.
    821   unsigned PercentDynamicCostSaved =
    822       (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
    823 
    824   if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
    825       (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
    826           (int64_t)Threshold) {
    827     DEBUG(dbgs() << "  Can fully unroll, because unrolling will reduce the "
    828                     "expected dynamic cost by " << PercentDynamicCostSaved
    829                  << "% (threshold: " << PercentDynamicCostSavedThreshold
    830                  << "%)\n"
    831                  << "  and the unrolled cost (" << UnrolledCost
    832                  << ") is less than the max threshold ("
    833                  << DynamicCostSavingsDiscount << ").\n");
    834     return true;
    835   }
    836 
    837   DEBUG(dbgs() << "  Too large to fully unroll:\n");
    838   DEBUG(dbgs() << "    Threshold: " << Threshold << "\n");
    839   DEBUG(dbgs() << "    Max threshold: " << DynamicCostSavingsDiscount << "\n");
    840   DEBUG(dbgs() << "    Percent cost saved threshold: "
    841                << PercentDynamicCostSavedThreshold << "%\n");
    842   DEBUG(dbgs() << "    Unrolled cost: " << UnrolledCost << "\n");
    843   DEBUG(dbgs() << "    Rolled dynamic cost: " << RolledDynamicCost << "\n");
    844   DEBUG(dbgs() << "    Percent cost saved: " << PercentDynamicCostSaved
    845                << "\n");
    846   return false;
    847 }
    848 
    849 unsigned LoopUnroll::selectUnrollCount(
    850     const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
    851     unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
    852     bool &SetExplicitly) {
    853   SetExplicitly = true;
    854 
    855   // User-specified count (either as a command-line option or
    856   // constructor parameter) has highest precedence.
    857   unsigned Count = UserCount ? CurrentCount : 0;
    858 
    859   // If there is no user-specified count, unroll pragmas have the next
    860   // highest precedence.
    861   if (Count == 0) {
    862     if (PragmaCount) {
    863       Count = PragmaCount;
    864     } else if (PragmaFullUnroll) {
    865       Count = TripCount;
    866     }
    867   }
    868 
    869   if (Count == 0)
    870     Count = UP.Count;
    871 
    872   if (Count == 0) {
    873     SetExplicitly = false;
    874     if (TripCount == 0)
    875       // Runtime trip count.
    876       Count = UnrollRuntimeCount;
    877     else
    878       // Conservative heuristic: if we know the trip count, see if we can
    879       // completely unroll (subject to the threshold, checked below); otherwise
    880       // try to find greatest modulo of the trip count which is still under
    881       // threshold value.
    882       Count = TripCount;
    883   }
    884   if (TripCount && Count > TripCount)
    885     return TripCount;
    886   return Count;
    887 }
    888 
    889 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &) {
    890   if (skipOptnoneFunction(L))
    891     return false;
    892 
    893   Function &F = *L->getHeader()->getParent();
    894 
    895   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
    896   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
    897   ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
    898   const TargetTransformInfo &TTI =
    899       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
    900   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
    901   bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
    902 
    903   BasicBlock *Header = L->getHeader();
    904   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
    905         << "] Loop %" << Header->getName() << "\n");
    906 
    907   if (HasUnrollDisablePragma(L)) {
    908     return false;
    909   }
    910   bool PragmaFullUnroll = HasUnrollFullPragma(L);
    911   bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
    912   unsigned PragmaCount = UnrollCountPragmaValue(L);
    913   bool HasPragma = PragmaFullUnroll || PragmaEnableUnroll || PragmaCount > 0;
    914 
    915   TargetTransformInfo::UnrollingPreferences UP;
    916   getUnrollingPreferences(L, TTI, UP);
    917 
    918   // Find trip count and trip multiple if count is not available
    919   unsigned TripCount = 0;
    920   unsigned TripMultiple = 1;
    921   // If there are multiple exiting blocks but one of them is the latch, use the
    922   // latch for the trip count estimation. Otherwise insist on a single exiting
    923   // block for the trip count estimation.
    924   BasicBlock *ExitingBlock = L->getLoopLatch();
    925   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
    926     ExitingBlock = L->getExitingBlock();
    927   if (ExitingBlock) {
    928     TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
    929     TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
    930   }
    931 
    932   // Select an initial unroll count.  This may be reduced later based
    933   // on size thresholds.
    934   bool CountSetExplicitly;
    935   unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
    936                                      PragmaCount, UP, CountSetExplicitly);
    937 
    938   unsigned NumInlineCandidates;
    939   bool notDuplicatable;
    940   unsigned LoopSize =
    941       ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
    942   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
    943 
    944   // When computing the unrolled size, note that the conditional branch on the
    945   // backedge and the comparison feeding it are not replicated like the rest of
    946   // the loop body (which is why 2 is subtracted).
    947   uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
    948   if (notDuplicatable) {
    949     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
    950                  << " instructions.\n");
    951     return false;
    952   }
    953   if (NumInlineCandidates != 0) {
    954     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
    955     return false;
    956   }
    957 
    958   unsigned Threshold, PartialThreshold;
    959   unsigned PercentDynamicCostSavedThreshold;
    960   unsigned DynamicCostSavingsDiscount;
    961   // Only use the high pragma threshold when we have a target unroll factor such
    962   // as with "#pragma unroll N" or a pragma indicating full unrolling and the
    963   // trip count is known. Otherwise we rely on the standard threshold to
    964   // heuristically select a reasonable unroll count.
    965   bool UsePragmaThreshold =
    966       PragmaCount > 0 ||
    967       ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount != 0);
    968 
    969   selectThresholds(L, UsePragmaThreshold, UP, Threshold, PartialThreshold,
    970                    PercentDynamicCostSavedThreshold,
    971                    DynamicCostSavingsDiscount);
    972 
    973   // Given Count, TripCount and thresholds determine the type of
    974   // unrolling which is to be performed.
    975   enum { Full = 0, Partial = 1, Runtime = 2 };
    976   int Unrolling;
    977   if (TripCount && Count == TripCount) {
    978     Unrolling = Partial;
    979     // If the loop is really small, we don't need to run an expensive analysis.
    980     if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount,
    981                             UnrolledSize, UnrolledSize)) {
    982       Unrolling = Full;
    983     } else {
    984       // The loop isn't that small, but we still can fully unroll it if that
    985       // helps to remove a significant number of instructions.
    986       // To check that, run additional analysis on the loop.
    987       if (Optional<EstimatedUnrollCost> Cost =
    988               analyzeLoopUnrollCost(L, TripCount, DT, *SE, TTI,
    989                                     Threshold + DynamicCostSavingsDiscount))
    990         if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold,
    991                                 DynamicCostSavingsDiscount, Cost->UnrolledCost,
    992                                 Cost->RolledDynamicCost)) {
    993           Unrolling = Full;
    994         }
    995     }
    996   } else if (TripCount && Count < TripCount) {
    997     Unrolling = Partial;
    998   } else {
    999     Unrolling = Runtime;
   1000   }
   1001 
   1002   // Reduce count based on the type of unrolling and the threshold values.
   1003   unsigned OriginalCount = Count;
   1004   bool AllowRuntime = PragmaEnableUnroll || (PragmaCount > 0) ||
   1005                       (UserRuntime ? CurrentRuntime : UP.Runtime);
   1006   // Don't unroll a runtime trip count loop with unroll full pragma.
   1007   if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
   1008     AllowRuntime = false;
   1009   }
   1010   if (Unrolling == Partial) {
   1011     bool AllowPartial = PragmaEnableUnroll ||
   1012                         (UserAllowPartial ? CurrentAllowPartial : UP.Partial);
   1013     if (!AllowPartial && !CountSetExplicitly) {
   1014       DEBUG(dbgs() << "  will not try to unroll partially because "
   1015                    << "-unroll-allow-partial not given\n");
   1016       return false;
   1017     }
   1018     if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
   1019       // Reduce unroll count to be modulo of TripCount for partial unrolling.
   1020       Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
   1021       while (Count != 0 && TripCount % Count != 0)
   1022         Count--;
   1023     }
   1024   } else if (Unrolling == Runtime) {
   1025     if (!AllowRuntime && !CountSetExplicitly) {
   1026       DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
   1027                    << "-unroll-runtime not given\n");
   1028       return false;
   1029     }
   1030     // Reduce unroll count to be the largest power-of-two factor of
   1031     // the original count which satisfies the threshold limit.
   1032     while (Count != 0 && UnrolledSize > PartialThreshold) {
   1033       Count >>= 1;
   1034       UnrolledSize = (LoopSize-2) * Count + 2;
   1035     }
   1036     if (Count > UP.MaxCount)
   1037       Count = UP.MaxCount;
   1038     DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
   1039   }
   1040 
   1041   if (HasPragma) {
   1042     if (PragmaCount != 0)
   1043       // If loop has an unroll count pragma mark loop as unrolled to prevent
   1044       // unrolling beyond that requested by the pragma.
   1045       SetLoopAlreadyUnrolled(L);
   1046 
   1047     // Emit optimization remarks if we are unable to unroll the loop
   1048     // as directed by a pragma.
   1049     DebugLoc LoopLoc = L->getStartLoc();
   1050     Function *F = Header->getParent();
   1051     LLVMContext &Ctx = F->getContext();
   1052     if ((PragmaCount > 0) && Count != OriginalCount) {
   1053       emitOptimizationRemarkMissed(
   1054           Ctx, DEBUG_TYPE, *F, LoopLoc,
   1055           "Unable to unroll loop the number of times directed by "
   1056           "unroll_count pragma because unrolled size is too large.");
   1057     } else if (PragmaFullUnroll && !TripCount) {
   1058       emitOptimizationRemarkMissed(
   1059           Ctx, DEBUG_TYPE, *F, LoopLoc,
   1060           "Unable to fully unroll loop as directed by unroll(full) pragma "
   1061           "because loop has a runtime trip count.");
   1062     } else if (PragmaEnableUnroll && Count != TripCount && Count < 2) {
   1063       emitOptimizationRemarkMissed(
   1064           Ctx, DEBUG_TYPE, *F, LoopLoc,
   1065           "Unable to unroll loop as directed by unroll(enable) pragma because "
   1066           "unrolled size is too large.");
   1067     } else if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
   1068                Count != TripCount) {
   1069       emitOptimizationRemarkMissed(
   1070           Ctx, DEBUG_TYPE, *F, LoopLoc,
   1071           "Unable to fully unroll loop as directed by unroll pragma because "
   1072           "unrolled size is too large.");
   1073     }
   1074   }
   1075 
   1076   if (Unrolling != Full && Count < 2) {
   1077     // Partial unrolling by 1 is a nop.  For full unrolling, a factor
   1078     // of 1 makes sense because loop control can be eliminated.
   1079     return false;
   1080   }
   1081 
   1082   // Unroll the loop.
   1083   if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
   1084                   TripMultiple, LI, SE, &DT, &AC, PreserveLCSSA))
   1085     return false;
   1086 
   1087   return true;
   1088 }
   1089