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/AssumptionCache.h"
     18 #include "llvm/Analysis/CodeMetrics.h"
     19 #include "llvm/Analysis/InstructionSimplify.h"
     20 #include "llvm/Analysis/LoopPass.h"
     21 #include "llvm/Analysis/ScalarEvolution.h"
     22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
     23 #include "llvm/Analysis/TargetTransformInfo.h"
     24 #include "llvm/IR/DataLayout.h"
     25 #include "llvm/IR/DiagnosticInfo.h"
     26 #include "llvm/IR/Dominators.h"
     27 #include "llvm/IR/InstVisitor.h"
     28 #include "llvm/IR/IntrinsicInst.h"
     29 #include "llvm/IR/Metadata.h"
     30 #include "llvm/Support/CommandLine.h"
     31 #include "llvm/Support/Debug.h"
     32 #include "llvm/Support/raw_ostream.h"
     33 #include "llvm/Transforms/Utils/UnrollLoop.h"
     34 #include <climits>
     35 
     36 using namespace llvm;
     37 
     38 #define DEBUG_TYPE "loop-unroll"
     39 
     40 static cl::opt<unsigned>
     41 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
     42   cl::desc("The cut-off point for automatic loop unrolling"));
     43 
     44 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
     45     "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
     46     cl::desc("Don't allow loop unrolling to simulate more than this number of"
     47              "iterations when checking full unroll profitability"));
     48 
     49 static cl::opt<unsigned> UnrollMinPercentOfOptimized(
     50     "unroll-percent-of-optimized-for-complete-unroll", cl::init(20), cl::Hidden,
     51     cl::desc("If complete unrolling could trigger further optimizations, and, "
     52              "by that, remove the given percent of instructions, perform the "
     53              "complete unroll even if it's beyond the threshold"));
     54 
     55 static cl::opt<unsigned> UnrollAbsoluteThreshold(
     56     "unroll-absolute-threshold", cl::init(2000), cl::Hidden,
     57     cl::desc("Don't unroll if the unrolled size is bigger than this threshold,"
     58              " even if we can remove big portion of instructions later."));
     59 
     60 static cl::opt<unsigned>
     61 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
     62   cl::desc("Use this unroll count for all loops including those with "
     63            "unroll_count pragma values, for testing purposes"));
     64 
     65 static cl::opt<bool>
     66 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
     67   cl::desc("Allows loops to be partially unrolled until "
     68            "-unroll-threshold loop size is reached."));
     69 
     70 static cl::opt<bool>
     71 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
     72   cl::desc("Unroll loops with run-time trip counts"));
     73 
     74 static cl::opt<unsigned>
     75 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
     76   cl::desc("Unrolled size limit for loops with an unroll(full) or "
     77            "unroll_count pragma."));
     78 
     79 namespace {
     80   class LoopUnroll : public LoopPass {
     81   public:
     82     static char ID; // Pass ID, replacement for typeid
     83     LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
     84       CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
     85       CurrentAbsoluteThreshold = UnrollAbsoluteThreshold;
     86       CurrentMinPercentOfOptimized = UnrollMinPercentOfOptimized;
     87       CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
     88       CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
     89       CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
     90 
     91       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
     92       UserAbsoluteThreshold = (UnrollAbsoluteThreshold.getNumOccurrences() > 0);
     93       UserPercentOfOptimized =
     94           (UnrollMinPercentOfOptimized.getNumOccurrences() > 0);
     95       UserAllowPartial = (P != -1) ||
     96                          (UnrollAllowPartial.getNumOccurrences() > 0);
     97       UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
     98       UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
     99 
    100       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
    101     }
    102 
    103     /// A magic value for use with the Threshold parameter to indicate
    104     /// that the loop unroll should be performed regardless of how much
    105     /// code expansion would result.
    106     static const unsigned NoThreshold = UINT_MAX;
    107 
    108     // Threshold to use when optsize is specified (and there is no
    109     // explicit -unroll-threshold).
    110     static const unsigned OptSizeUnrollThreshold = 50;
    111 
    112     // Default unroll count for loops with run-time trip count if
    113     // -unroll-count is not set
    114     static const unsigned UnrollRuntimeCount = 8;
    115 
    116     unsigned CurrentCount;
    117     unsigned CurrentThreshold;
    118     unsigned CurrentAbsoluteThreshold;
    119     unsigned CurrentMinPercentOfOptimized;
    120     bool     CurrentAllowPartial;
    121     bool     CurrentRuntime;
    122     bool     UserCount;            // CurrentCount is user-specified.
    123     bool     UserThreshold;        // CurrentThreshold is user-specified.
    124     bool UserAbsoluteThreshold;    // CurrentAbsoluteThreshold is
    125                                    // user-specified.
    126     bool UserPercentOfOptimized;   // CurrentMinPercentOfOptimized is
    127                                    // user-specified.
    128     bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
    129     bool     UserRuntime;          // CurrentRuntime is user-specified.
    130 
    131     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
    132 
    133     /// This transformation requires natural loop information & requires that
    134     /// loop preheaders be inserted into the CFG...
    135     ///
    136     void getAnalysisUsage(AnalysisUsage &AU) const override {
    137       AU.addRequired<AssumptionCacheTracker>();
    138       AU.addRequired<LoopInfoWrapperPass>();
    139       AU.addPreserved<LoopInfoWrapperPass>();
    140       AU.addRequiredID(LoopSimplifyID);
    141       AU.addPreservedID(LoopSimplifyID);
    142       AU.addRequiredID(LCSSAID);
    143       AU.addPreservedID(LCSSAID);
    144       AU.addRequired<ScalarEvolution>();
    145       AU.addPreserved<ScalarEvolution>();
    146       AU.addRequired<TargetTransformInfoWrapperPass>();
    147       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
    148       // If loop unroll does not preserve dom info then LCSSA pass on next
    149       // loop will receive invalid dom info.
    150       // For now, recreate dom info, if loop is unrolled.
    151       AU.addPreserved<DominatorTreeWrapperPass>();
    152     }
    153 
    154     // Fill in the UnrollingPreferences parameter with values from the
    155     // TargetTransformationInfo.
    156     void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
    157                                  TargetTransformInfo::UnrollingPreferences &UP) {
    158       UP.Threshold = CurrentThreshold;
    159       UP.AbsoluteThreshold = CurrentAbsoluteThreshold;
    160       UP.MinPercentOfOptimized = CurrentMinPercentOfOptimized;
    161       UP.OptSizeThreshold = OptSizeUnrollThreshold;
    162       UP.PartialThreshold = CurrentThreshold;
    163       UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
    164       UP.Count = CurrentCount;
    165       UP.MaxCount = UINT_MAX;
    166       UP.Partial = CurrentAllowPartial;
    167       UP.Runtime = CurrentRuntime;
    168       UP.AllowExpensiveTripCount = false;
    169       TTI.getUnrollingPreferences(L, UP);
    170     }
    171 
    172     // Select and return an unroll count based on parameters from
    173     // user, unroll preferences, unroll pragmas, or a heuristic.
    174     // SetExplicitly is set to true if the unroll count is is set by
    175     // the user or a pragma rather than selected heuristically.
    176     unsigned
    177     selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
    178                       unsigned PragmaCount,
    179                       const TargetTransformInfo::UnrollingPreferences &UP,
    180                       bool &SetExplicitly);
    181 
    182     // Select threshold values used to limit unrolling based on a
    183     // total unrolled size.  Parameters Threshold and PartialThreshold
    184     // are set to the maximum unrolled size for fully and partially
    185     // unrolled loops respectively.
    186     void selectThresholds(const Loop *L, bool HasPragma,
    187                           const TargetTransformInfo::UnrollingPreferences &UP,
    188                           unsigned &Threshold, unsigned &PartialThreshold,
    189                           unsigned NumberOfOptimizedInstructions) {
    190       // Determine the current unrolling threshold.  While this is
    191       // normally set from UnrollThreshold, it is overridden to a
    192       // smaller value if the current function is marked as
    193       // optimize-for-size, and the unroll threshold was not user
    194       // specified.
    195       Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
    196 
    197       // If we are allowed to completely unroll if we can remove M% of
    198       // instructions, and we know that with complete unrolling we'll be able
    199       // to kill N instructions, then we can afford to completely unroll loops
    200       // with unrolled size up to N*100/M.
    201       // Adjust the threshold according to that:
    202       unsigned PercentOfOptimizedForCompleteUnroll =
    203           UserPercentOfOptimized ? CurrentMinPercentOfOptimized
    204                                  : UP.MinPercentOfOptimized;
    205       unsigned AbsoluteThreshold = UserAbsoluteThreshold
    206                                        ? CurrentAbsoluteThreshold
    207                                        : UP.AbsoluteThreshold;
    208       if (PercentOfOptimizedForCompleteUnroll)
    209         Threshold = std::max<unsigned>(Threshold,
    210                                        NumberOfOptimizedInstructions * 100 /
    211                                            PercentOfOptimizedForCompleteUnroll);
    212       // But don't allow unrolling loops bigger than absolute threshold.
    213       Threshold = std::min<unsigned>(Threshold, AbsoluteThreshold);
    214 
    215       PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
    216       if (!UserThreshold &&
    217           L->getHeader()->getParent()->hasFnAttribute(
    218               Attribute::OptimizeForSize)) {
    219         Threshold = UP.OptSizeThreshold;
    220         PartialThreshold = UP.PartialOptSizeThreshold;
    221       }
    222       if (HasPragma) {
    223         // If the loop has an unrolling pragma, we want to be more
    224         // aggressive with unrolling limits.  Set thresholds to at
    225         // least the PragmaTheshold value which is larger than the
    226         // default limits.
    227         if (Threshold != NoThreshold)
    228           Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
    229         if (PartialThreshold != NoThreshold)
    230           PartialThreshold =
    231               std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
    232       }
    233     }
    234   };
    235 }
    236 
    237 char LoopUnroll::ID = 0;
    238 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
    239 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
    240 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
    241 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
    242 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
    243 INITIALIZE_PASS_DEPENDENCY(LCSSA)
    244 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
    245 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
    246 
    247 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
    248                                  int Runtime) {
    249   return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
    250 }
    251 
    252 Pass *llvm::createSimpleLoopUnrollPass() {
    253   return llvm::createLoopUnrollPass(-1, -1, 0, 0);
    254 }
    255 
    256 static bool isLoadFromConstantInitializer(Value *V) {
    257   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
    258     if (GV->isConstant() && GV->hasDefinitiveInitializer())
    259       return GV->getInitializer();
    260   return false;
    261 }
    262 
    263 namespace {
    264 struct FindConstantPointers {
    265   bool LoadCanBeConstantFolded;
    266   bool IndexIsConstant;
    267   APInt Step;
    268   APInt StartValue;
    269   Value *BaseAddress;
    270   const Loop *L;
    271   ScalarEvolution &SE;
    272   FindConstantPointers(const Loop *loop, ScalarEvolution &SE)
    273       : LoadCanBeConstantFolded(true), IndexIsConstant(true), L(loop), SE(SE) {}
    274 
    275   bool follow(const SCEV *S) {
    276     if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) {
    277       // We've reached the leaf node of SCEV, it's most probably just a
    278       // variable. Now it's time to see if it corresponds to a global constant
    279       // global (in which case we can eliminate the load), or not.
    280       BaseAddress = SC->getValue();
    281       LoadCanBeConstantFolded =
    282           IndexIsConstant && isLoadFromConstantInitializer(BaseAddress);
    283       return false;
    284     }
    285     if (isa<SCEVConstant>(S))
    286       return true;
    287     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
    288       // If the current SCEV expression is AddRec, and its loop isn't the loop
    289       // we are about to unroll, then we won't get a constant address after
    290       // unrolling, and thus, won't be able to eliminate the load.
    291       if (AR->getLoop() != L)
    292         return IndexIsConstant = false;
    293       // If the step isn't constant, we won't get constant addresses in unrolled
    294       // version. Bail out.
    295       if (const SCEVConstant *StepSE =
    296               dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
    297         Step = StepSE->getValue()->getValue();
    298       else
    299         return IndexIsConstant = false;
    300 
    301       return IndexIsConstant;
    302     }
    303     // If Result is true, continue traversal.
    304     // Otherwise, we have found something that prevents us from (possible) load
    305     // elimination.
    306     return IndexIsConstant;
    307   }
    308   bool isDone() const { return !IndexIsConstant; }
    309 };
    310 
    311 // This class is used to get an estimate of the optimization effects that we
    312 // could get from complete loop unrolling. It comes from the fact that some
    313 // loads might be replaced with concrete constant values and that could trigger
    314 // a chain of instruction simplifications.
    315 //
    316 // E.g. we might have:
    317 //   int a[] = {0, 1, 0};
    318 //   v = 0;
    319 //   for (i = 0; i < 3; i ++)
    320 //     v += b[i]*a[i];
    321 // If we completely unroll the loop, we would get:
    322 //   v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
    323 // Which then will be simplified to:
    324 //   v = b[0]* 0 + b[1]* 1 + b[2]* 0
    325 // And finally:
    326 //   v = b[1]
    327 class UnrollAnalyzer : public InstVisitor<UnrollAnalyzer, bool> {
    328   typedef InstVisitor<UnrollAnalyzer, bool> Base;
    329   friend class InstVisitor<UnrollAnalyzer, bool>;
    330 
    331   const Loop *L;
    332   unsigned TripCount;
    333   ScalarEvolution &SE;
    334   const TargetTransformInfo &TTI;
    335 
    336   DenseMap<Value *, Constant *> SimplifiedValues;
    337   DenseMap<LoadInst *, Value *> LoadBaseAddresses;
    338   SmallPtrSet<Instruction *, 32> CountedInstructions;
    339 
    340   /// \brief Count the number of optimized instructions.
    341   unsigned NumberOfOptimizedInstructions;
    342 
    343   // Provide base case for our instruction visit.
    344   bool visitInstruction(Instruction &I) { return false; };
    345   // TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt,
    346   // FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select,
    347   // ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue.
    348   //
    349   // Probaly it's worth to hoist the code for estimating the simplifications
    350   // effects to a separate class, since we have a very similar code in
    351   // InlineCost already.
    352   bool visitBinaryOperator(BinaryOperator &I) {
    353     Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
    354     if (!isa<Constant>(LHS))
    355       if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
    356         LHS = SimpleLHS;
    357     if (!isa<Constant>(RHS))
    358       if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
    359         RHS = SimpleRHS;
    360     Value *SimpleV = nullptr;
    361     const DataLayout &DL = I.getModule()->getDataLayout();
    362     if (auto FI = dyn_cast<FPMathOperator>(&I))
    363       SimpleV =
    364           SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
    365     else
    366       SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
    367 
    368     if (SimpleV && CountedInstructions.insert(&I).second)
    369       NumberOfOptimizedInstructions += TTI.getUserCost(&I);
    370 
    371     if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
    372       SimplifiedValues[&I] = C;
    373       return true;
    374     }
    375     return false;
    376   }
    377 
    378   Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) {
    379     if (!LI)
    380       return nullptr;
    381     Value *BaseAddr = LoadBaseAddresses[LI];
    382     if (!BaseAddr)
    383       return nullptr;
    384 
    385     auto GV = dyn_cast<GlobalVariable>(BaseAddr);
    386     if (!GV)
    387       return nullptr;
    388 
    389     ConstantDataSequential *CDS =
    390         dyn_cast<ConstantDataSequential>(GV->getInitializer());
    391     if (!CDS)
    392       return nullptr;
    393 
    394     const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr);
    395     const SCEV *S = SE.getSCEV(LI->getPointerOperand());
    396     const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);
    397 
    398     APInt StepC, StartC;
    399     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);
    400     if (!AR)
    401       return nullptr;
    402 
    403     if (const SCEVConstant *StepSE =
    404             dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
    405       StepC = StepSE->getValue()->getValue();
    406     else
    407       return nullptr;
    408 
    409     if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart()))
    410       StartC = StartSE->getValue()->getValue();
    411     else
    412       return nullptr;
    413 
    414     unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
    415     unsigned Start = StartC.getLimitedValue();
    416     unsigned Step = StepC.getLimitedValue();
    417 
    418     unsigned Index = (Start + Step * Iteration) / ElemSize;
    419     if (Index >= CDS->getNumElements())
    420       return nullptr;
    421 
    422     Constant *CV = CDS->getElementAsConstant(Index);
    423 
    424     return CV;
    425   }
    426 
    427 public:
    428   UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
    429                  const TargetTransformInfo &TTI)
    430       : L(L), TripCount(TripCount), SE(SE), TTI(TTI),
    431         NumberOfOptimizedInstructions(0) {}
    432 
    433   // Visit all loads the loop L, and for those that, after complete loop
    434   // unrolling, would have a constant address and it will point to a known
    435   // constant initializer, record its base address for future use.  It is used
    436   // when we estimate number of potentially simplified instructions.
    437   void findConstFoldableLoads() {
    438     for (auto BB : L->getBlocks()) {
    439       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
    440         if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
    441           if (!LI->isSimple())
    442             continue;
    443           Value *AddrOp = LI->getPointerOperand();
    444           const SCEV *S = SE.getSCEV(AddrOp);
    445           FindConstantPointers Visitor(L, SE);
    446           SCEVTraversal<FindConstantPointers> T(Visitor);
    447           T.visitAll(S);
    448           if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) {
    449             LoadBaseAddresses[LI] = Visitor.BaseAddress;
    450           }
    451         }
    452       }
    453     }
    454   }
    455 
    456   // Given a list of loads that could be constant-folded (LoadBaseAddresses),
    457   // estimate number of optimized instructions after substituting the concrete
    458   // values for the given Iteration. Also track how many instructions become
    459   // dead through this process.
    460   unsigned estimateNumberOfOptimizedInstructions(unsigned Iteration) {
    461     // We keep a set vector for the worklist so that we don't wast space in the
    462     // worklist queuing up the same instruction repeatedly. This can happen due
    463     // to multiple operands being the same instruction or due to the same
    464     // instruction being an operand of lots of things that end up dead or
    465     // simplified.
    466     SmallSetVector<Instruction *, 8> Worklist;
    467 
    468     // Clear the simplified values and counts for this iteration.
    469     SimplifiedValues.clear();
    470     CountedInstructions.clear();
    471     NumberOfOptimizedInstructions = 0;
    472 
    473     // We start by adding all loads to the worklist.
    474     for (auto &LoadDescr : LoadBaseAddresses) {
    475       LoadInst *LI = LoadDescr.first;
    476       SimplifiedValues[LI] = computeLoadValue(LI, Iteration);
    477       if (CountedInstructions.insert(LI).second)
    478         NumberOfOptimizedInstructions += TTI.getUserCost(LI);
    479 
    480       for (User *U : LI->users())
    481         Worklist.insert(cast<Instruction>(U));
    482     }
    483 
    484     // And then we try to simplify every user of every instruction from the
    485     // worklist. If we do simplify a user, add it to the worklist to process
    486     // its users as well.
    487     while (!Worklist.empty()) {
    488       Instruction *I = Worklist.pop_back_val();
    489       if (!L->contains(I))
    490         continue;
    491       if (!visit(I))
    492         continue;
    493       for (User *U : I->users())
    494         Worklist.insert(cast<Instruction>(U));
    495     }
    496 
    497     // Now that we know the potentially simplifed instructions, estimate number
    498     // of instructions that would become dead if we do perform the
    499     // simplification.
    500 
    501     // The dead instructions are held in a separate set. This is used to
    502     // prevent us from re-examining instructions and make sure we only count
    503     // the benifit once. The worklist's internal set handles insertion
    504     // deduplication.
    505     SmallPtrSet<Instruction *, 16> DeadInstructions;
    506 
    507     // Lambda to enque operands onto the worklist.
    508     auto EnqueueOperands = [&](Instruction &I) {
    509       for (auto *Op : I.operand_values())
    510         if (auto *OpI = dyn_cast<Instruction>(Op))
    511           if (!OpI->use_empty())
    512             Worklist.insert(OpI);
    513     };
    514 
    515     // Start by initializing worklist with simplified instructions.
    516     for (auto &FoldedKeyValue : SimplifiedValues)
    517       if (auto *FoldedInst = dyn_cast<Instruction>(FoldedKeyValue.first)) {
    518         DeadInstructions.insert(FoldedInst);
    519 
    520         // Add each instruction operand of this dead instruction to the
    521         // worklist.
    522         EnqueueOperands(*FoldedInst);
    523       }
    524 
    525     // If a definition of an insn is only used by simplified or dead
    526     // instructions, it's also dead. Check defs of all instructions from the
    527     // worklist.
    528     while (!Worklist.empty()) {
    529       Instruction *I = Worklist.pop_back_val();
    530       if (!L->contains(I))
    531         continue;
    532       if (DeadInstructions.count(I))
    533         continue;
    534 
    535       if (std::all_of(I->user_begin(), I->user_end(), [&](User *U) {
    536             return DeadInstructions.count(cast<Instruction>(U));
    537           })) {
    538         NumberOfOptimizedInstructions += TTI.getUserCost(I);
    539         DeadInstructions.insert(I);
    540         EnqueueOperands(*I);
    541       }
    542     }
    543     return NumberOfOptimizedInstructions;
    544   }
    545 };
    546 } // namespace
    547 
    548 // Complete loop unrolling can make some loads constant, and we need to know if
    549 // that would expose any further optimization opportunities.
    550 // This routine estimates this optimization effect and returns the number of
    551 // instructions, that potentially might be optimized away.
    552 static unsigned
    553 approximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE,
    554                                          unsigned TripCount,
    555                                          const TargetTransformInfo &TTI) {
    556   if (!TripCount || !UnrollMaxIterationsCountToAnalyze)
    557     return 0;
    558 
    559   UnrollAnalyzer UA(L, TripCount, SE, TTI);
    560   UA.findConstFoldableLoads();
    561 
    562   // Estimate number of instructions, that could be simplified if we replace a
    563   // load with the corresponding constant. Since the same load will take
    564   // different values on different iterations, we have to go through all loop's
    565   // iterations here. To limit ourselves here, we check only first N
    566   // iterations, and then scale the found number, if necessary.
    567   unsigned IterationsNumberForEstimate =
    568       std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount);
    569   unsigned NumberOfOptimizedInstructions = 0;
    570   for (unsigned i = 0; i < IterationsNumberForEstimate; ++i)
    571     NumberOfOptimizedInstructions +=
    572         UA.estimateNumberOfOptimizedInstructions(i);
    573 
    574   NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate;
    575 
    576   return NumberOfOptimizedInstructions;
    577 }
    578 
    579 /// ApproximateLoopSize - Approximate the size of the loop.
    580 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
    581                                     bool &NotDuplicatable,
    582                                     const TargetTransformInfo &TTI,
    583                                     AssumptionCache *AC) {
    584   SmallPtrSet<const Value *, 32> EphValues;
    585   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
    586 
    587   CodeMetrics Metrics;
    588   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
    589        I != E; ++I)
    590     Metrics.analyzeBasicBlock(*I, TTI, EphValues);
    591   NumCalls = Metrics.NumInlineCandidates;
    592   NotDuplicatable = Metrics.notDuplicatable;
    593 
    594   unsigned LoopSize = Metrics.NumInsts;
    595 
    596   // Don't allow an estimate of size zero.  This would allows unrolling of loops
    597   // with huge iteration counts, which is a compile time problem even if it's
    598   // not a problem for code quality. Also, the code using this size may assume
    599   // that each loop has at least three instructions (likely a conditional
    600   // branch, a comparison feeding that branch, and some kind of loop increment
    601   // feeding that comparison instruction).
    602   LoopSize = std::max(LoopSize, 3u);
    603 
    604   return LoopSize;
    605 }
    606 
    607 // Returns the loop hint metadata node with the given name (for example,
    608 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
    609 // returned.
    610 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
    611   if (MDNode *LoopID = L->getLoopID())
    612     return GetUnrollMetadata(LoopID, Name);
    613   return nullptr;
    614 }
    615 
    616 // Returns true if the loop has an unroll(full) pragma.
    617 static bool HasUnrollFullPragma(const Loop *L) {
    618   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
    619 }
    620 
    621 // Returns true if the loop has an unroll(disable) pragma.
    622 static bool HasUnrollDisablePragma(const Loop *L) {
    623   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
    624 }
    625 
    626 // Returns true if the loop has an runtime unroll(disable) pragma.
    627 static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
    628   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
    629 }
    630 
    631 // If loop has an unroll_count pragma return the (necessarily
    632 // positive) value from the pragma.  Otherwise return 0.
    633 static unsigned UnrollCountPragmaValue(const Loop *L) {
    634   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
    635   if (MD) {
    636     assert(MD->getNumOperands() == 2 &&
    637            "Unroll count hint metadata should have two operands.");
    638     unsigned Count =
    639         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
    640     assert(Count >= 1 && "Unroll count must be positive.");
    641     return Count;
    642   }
    643   return 0;
    644 }
    645 
    646 // Remove existing unroll metadata and add unroll disable metadata to
    647 // indicate the loop has already been unrolled.  This prevents a loop
    648 // from being unrolled more than is directed by a pragma if the loop
    649 // unrolling pass is run more than once (which it generally is).
    650 static void SetLoopAlreadyUnrolled(Loop *L) {
    651   MDNode *LoopID = L->getLoopID();
    652   if (!LoopID) return;
    653 
    654   // First remove any existing loop unrolling metadata.
    655   SmallVector<Metadata *, 4> MDs;
    656   // Reserve first location for self reference to the LoopID metadata node.
    657   MDs.push_back(nullptr);
    658   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
    659     bool IsUnrollMetadata = false;
    660     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
    661     if (MD) {
    662       const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
    663       IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
    664     }
    665     if (!IsUnrollMetadata)
    666       MDs.push_back(LoopID->getOperand(i));
    667   }
    668 
    669   // Add unroll(disable) metadata to disable future unrolling.
    670   LLVMContext &Context = L->getHeader()->getContext();
    671   SmallVector<Metadata *, 1> DisableOperands;
    672   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
    673   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
    674   MDs.push_back(DisableNode);
    675 
    676   MDNode *NewLoopID = MDNode::get(Context, MDs);
    677   // Set operand 0 to refer to the loop id itself.
    678   NewLoopID->replaceOperandWith(0, NewLoopID);
    679   L->setLoopID(NewLoopID);
    680 }
    681 
    682 unsigned LoopUnroll::selectUnrollCount(
    683     const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
    684     unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
    685     bool &SetExplicitly) {
    686   SetExplicitly = true;
    687 
    688   // User-specified count (either as a command-line option or
    689   // constructor parameter) has highest precedence.
    690   unsigned Count = UserCount ? CurrentCount : 0;
    691 
    692   // If there is no user-specified count, unroll pragmas have the next
    693   // highest precendence.
    694   if (Count == 0) {
    695     if (PragmaCount) {
    696       Count = PragmaCount;
    697     } else if (PragmaFullUnroll) {
    698       Count = TripCount;
    699     }
    700   }
    701 
    702   if (Count == 0)
    703     Count = UP.Count;
    704 
    705   if (Count == 0) {
    706     SetExplicitly = false;
    707     if (TripCount == 0)
    708       // Runtime trip count.
    709       Count = UnrollRuntimeCount;
    710     else
    711       // Conservative heuristic: if we know the trip count, see if we can
    712       // completely unroll (subject to the threshold, checked below); otherwise
    713       // try to find greatest modulo of the trip count which is still under
    714       // threshold value.
    715       Count = TripCount;
    716   }
    717   if (TripCount && Count > TripCount)
    718     return TripCount;
    719   return Count;
    720 }
    721 
    722 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
    723   if (skipOptnoneFunction(L))
    724     return false;
    725 
    726   Function &F = *L->getHeader()->getParent();
    727 
    728   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
    729   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
    730   const TargetTransformInfo &TTI =
    731       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
    732   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
    733 
    734   BasicBlock *Header = L->getHeader();
    735   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
    736         << "] Loop %" << Header->getName() << "\n");
    737 
    738   if (HasUnrollDisablePragma(L)) {
    739     return false;
    740   }
    741   bool PragmaFullUnroll = HasUnrollFullPragma(L);
    742   unsigned PragmaCount = UnrollCountPragmaValue(L);
    743   bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
    744 
    745   TargetTransformInfo::UnrollingPreferences UP;
    746   getUnrollingPreferences(L, TTI, UP);
    747 
    748   // Find trip count and trip multiple if count is not available
    749   unsigned TripCount = 0;
    750   unsigned TripMultiple = 1;
    751   // If there are multiple exiting blocks but one of them is the latch, use the
    752   // latch for the trip count estimation. Otherwise insist on a single exiting
    753   // block for the trip count estimation.
    754   BasicBlock *ExitingBlock = L->getLoopLatch();
    755   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
    756     ExitingBlock = L->getExitingBlock();
    757   if (ExitingBlock) {
    758     TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
    759     TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
    760   }
    761 
    762   // Select an initial unroll count.  This may be reduced later based
    763   // on size thresholds.
    764   bool CountSetExplicitly;
    765   unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
    766                                      PragmaCount, UP, CountSetExplicitly);
    767 
    768   unsigned NumInlineCandidates;
    769   bool notDuplicatable;
    770   unsigned LoopSize =
    771       ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
    772   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
    773 
    774   // When computing the unrolled size, note that the conditional branch on the
    775   // backedge and the comparison feeding it are not replicated like the rest of
    776   // the loop body (which is why 2 is subtracted).
    777   uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
    778   if (notDuplicatable) {
    779     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
    780                  << " instructions.\n");
    781     return false;
    782   }
    783   if (NumInlineCandidates != 0) {
    784     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
    785     return false;
    786   }
    787 
    788   unsigned NumberOfOptimizedInstructions =
    789       approximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI);
    790   DEBUG(dbgs() << "  Complete unrolling could save: "
    791                << NumberOfOptimizedInstructions << "\n");
    792 
    793   unsigned Threshold, PartialThreshold;
    794   selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
    795                    NumberOfOptimizedInstructions);
    796 
    797   // Given Count, TripCount and thresholds determine the type of
    798   // unrolling which is to be performed.
    799   enum { Full = 0, Partial = 1, Runtime = 2 };
    800   int Unrolling;
    801   if (TripCount && Count == TripCount) {
    802     if (Threshold != NoThreshold && UnrolledSize > Threshold) {
    803       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
    804                    << " because size: " << UnrolledSize << ">" << Threshold
    805                    << "\n");
    806       Unrolling = Partial;
    807     } else {
    808       Unrolling = Full;
    809     }
    810   } else if (TripCount && Count < TripCount) {
    811     Unrolling = Partial;
    812   } else {
    813     Unrolling = Runtime;
    814   }
    815 
    816   // Reduce count based on the type of unrolling and the threshold values.
    817   unsigned OriginalCount = Count;
    818   bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
    819   if (HasRuntimeUnrollDisablePragma(L)) {
    820     AllowRuntime = false;
    821   }
    822   if (Unrolling == Partial) {
    823     bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
    824     if (!AllowPartial && !CountSetExplicitly) {
    825       DEBUG(dbgs() << "  will not try to unroll partially because "
    826                    << "-unroll-allow-partial not given\n");
    827       return false;
    828     }
    829     if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
    830       // Reduce unroll count to be modulo of TripCount for partial unrolling.
    831       Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
    832       while (Count != 0 && TripCount % Count != 0)
    833         Count--;
    834     }
    835   } else if (Unrolling == Runtime) {
    836     if (!AllowRuntime && !CountSetExplicitly) {
    837       DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
    838                    << "-unroll-runtime not given\n");
    839       return false;
    840     }
    841     // Reduce unroll count to be the largest power-of-two factor of
    842     // the original count which satisfies the threshold limit.
    843     while (Count != 0 && UnrolledSize > PartialThreshold) {
    844       Count >>= 1;
    845       UnrolledSize = (LoopSize-2) * Count + 2;
    846     }
    847     if (Count > UP.MaxCount)
    848       Count = UP.MaxCount;
    849     DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
    850   }
    851 
    852   if (HasPragma) {
    853     if (PragmaCount != 0)
    854       // If loop has an unroll count pragma mark loop as unrolled to prevent
    855       // unrolling beyond that requested by the pragma.
    856       SetLoopAlreadyUnrolled(L);
    857 
    858     // Emit optimization remarks if we are unable to unroll the loop
    859     // as directed by a pragma.
    860     DebugLoc LoopLoc = L->getStartLoc();
    861     Function *F = Header->getParent();
    862     LLVMContext &Ctx = F->getContext();
    863     if (PragmaFullUnroll && PragmaCount == 0) {
    864       if (TripCount && Count != TripCount) {
    865         emitOptimizationRemarkMissed(
    866             Ctx, DEBUG_TYPE, *F, LoopLoc,
    867             "Unable to fully unroll loop as directed by unroll(full) pragma "
    868             "because unrolled size is too large.");
    869       } else if (!TripCount) {
    870         emitOptimizationRemarkMissed(
    871             Ctx, DEBUG_TYPE, *F, LoopLoc,
    872             "Unable to fully unroll loop as directed by unroll(full) pragma "
    873             "because loop has a runtime trip count.");
    874       }
    875     } else if (PragmaCount > 0 && Count != OriginalCount) {
    876       emitOptimizationRemarkMissed(
    877           Ctx, DEBUG_TYPE, *F, LoopLoc,
    878           "Unable to unroll loop the number of times directed by "
    879           "unroll_count pragma because unrolled size is too large.");
    880     }
    881   }
    882 
    883   if (Unrolling != Full && Count < 2) {
    884     // Partial unrolling by 1 is a nop.  For full unrolling, a factor
    885     // of 1 makes sense because loop control can be eliminated.
    886     return false;
    887   }
    888 
    889   // Unroll the loop.
    890   if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
    891                   TripMultiple, LI, this, &LPM, &AC))
    892     return false;
    893 
    894   return true;
    895 }
    896