LLVM API Documentation

LoopUnrollPass.cpp
Go to the documentation of this file.
00001 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass implements a simple loop unroller.  It works best when loops have
00011 // been canonicalized by the -indvars pass, allowing it to determine the trip
00012 // counts of loops easily.
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/Analysis/AssumptionTracker.h"
00017 #include "llvm/Analysis/CodeMetrics.h"
00018 #include "llvm/Analysis/FunctionTargetTransformInfo.h"
00019 #include "llvm/Analysis/LoopPass.h"
00020 #include "llvm/Analysis/ScalarEvolution.h"
00021 #include "llvm/Analysis/TargetTransformInfo.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/DiagnosticInfo.h"
00024 #include "llvm/IR/Dominators.h"
00025 #include "llvm/IR/IntrinsicInst.h"
00026 #include "llvm/IR/Metadata.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Transforms/Utils/UnrollLoop.h"
00031 #include <climits>
00032 
00033 using namespace llvm;
00034 
00035 #define DEBUG_TYPE "loop-unroll"
00036 
00037 static cl::opt<unsigned>
00038 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
00039   cl::desc("The cut-off point for automatic loop unrolling"));
00040 
00041 static cl::opt<unsigned>
00042 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
00043   cl::desc("Use this unroll count for all loops including those with "
00044            "unroll_count pragma values, for testing purposes"));
00045 
00046 static cl::opt<bool>
00047 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
00048   cl::desc("Allows loops to be partially unrolled until "
00049            "-unroll-threshold loop size is reached."));
00050 
00051 static cl::opt<bool>
00052 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
00053   cl::desc("Unroll loops with run-time trip counts"));
00054 
00055 static cl::opt<unsigned>
00056 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
00057   cl::desc("Unrolled size limit for loops with an unroll(full) or "
00058            "unroll_count pragma."));
00059 
00060 namespace {
00061   class LoopUnroll : public LoopPass {
00062   public:
00063     static char ID; // Pass ID, replacement for typeid
00064     LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
00065       CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
00066       CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
00067       CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
00068       CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
00069 
00070       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
00071       UserAllowPartial = (P != -1) ||
00072                          (UnrollAllowPartial.getNumOccurrences() > 0);
00073       UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
00074       UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
00075 
00076       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
00077     }
00078 
00079     /// A magic value for use with the Threshold parameter to indicate
00080     /// that the loop unroll should be performed regardless of how much
00081     /// code expansion would result.
00082     static const unsigned NoThreshold = UINT_MAX;
00083 
00084     // Threshold to use when optsize is specified (and there is no
00085     // explicit -unroll-threshold).
00086     static const unsigned OptSizeUnrollThreshold = 50;
00087 
00088     // Default unroll count for loops with run-time trip count if
00089     // -unroll-count is not set
00090     static const unsigned UnrollRuntimeCount = 8;
00091 
00092     unsigned CurrentCount;
00093     unsigned CurrentThreshold;
00094     bool     CurrentAllowPartial;
00095     bool     CurrentRuntime;
00096     bool     UserCount;            // CurrentCount is user-specified.
00097     bool     UserThreshold;        // CurrentThreshold is user-specified.
00098     bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
00099     bool     UserRuntime;          // CurrentRuntime is user-specified.
00100 
00101     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
00102 
00103     /// This transformation requires natural loop information & requires that
00104     /// loop preheaders be inserted into the CFG...
00105     ///
00106     void getAnalysisUsage(AnalysisUsage &AU) const override {
00107       AU.addRequired<AssumptionTracker>();
00108       AU.addRequired<LoopInfo>();
00109       AU.addPreserved<LoopInfo>();
00110       AU.addRequiredID(LoopSimplifyID);
00111       AU.addPreservedID(LoopSimplifyID);
00112       AU.addRequiredID(LCSSAID);
00113       AU.addPreservedID(LCSSAID);
00114       AU.addRequired<ScalarEvolution>();
00115       AU.addPreserved<ScalarEvolution>();
00116       AU.addRequired<TargetTransformInfo>();
00117       AU.addRequired<FunctionTargetTransformInfo>();
00118       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
00119       // If loop unroll does not preserve dom info then LCSSA pass on next
00120       // loop will receive invalid dom info.
00121       // For now, recreate dom info, if loop is unrolled.
00122       AU.addPreserved<DominatorTreeWrapperPass>();
00123     }
00124 
00125     // Fill in the UnrollingPreferences parameter with values from the
00126     // TargetTransformationInfo.
00127     void getUnrollingPreferences(Loop *L, const FunctionTargetTransformInfo &FTTI,
00128                                  TargetTransformInfo::UnrollingPreferences &UP) {
00129       UP.Threshold = CurrentThreshold;
00130       UP.OptSizeThreshold = OptSizeUnrollThreshold;
00131       UP.PartialThreshold = CurrentThreshold;
00132       UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
00133       UP.Count = CurrentCount;
00134       UP.MaxCount = UINT_MAX;
00135       UP.Partial = CurrentAllowPartial;
00136       UP.Runtime = CurrentRuntime;
00137       FTTI.getUnrollingPreferences(L, UP);
00138     }
00139 
00140     // Select and return an unroll count based on parameters from
00141     // user, unroll preferences, unroll pragmas, or a heuristic.
00142     // SetExplicitly is set to true if the unroll count is is set by
00143     // the user or a pragma rather than selected heuristically.
00144     unsigned
00145     selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
00146                       unsigned PragmaCount,
00147                       const TargetTransformInfo::UnrollingPreferences &UP,
00148                       bool &SetExplicitly);
00149 
00150     // Select threshold values used to limit unrolling based on a
00151     // total unrolled size.  Parameters Threshold and PartialThreshold
00152     // are set to the maximum unrolled size for fully and partially
00153     // unrolled loops respectively.
00154     void selectThresholds(const Loop *L, bool HasPragma,
00155                           const TargetTransformInfo::UnrollingPreferences &UP,
00156                           unsigned &Threshold, unsigned &PartialThreshold) {
00157       // Determine the current unrolling threshold.  While this is
00158       // normally set from UnrollThreshold, it is overridden to a
00159       // smaller value if the current function is marked as
00160       // optimize-for-size, and the unroll threshold was not user
00161       // specified.
00162       Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
00163       PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
00164       if (!UserThreshold &&
00165           L->getHeader()->getParent()->getAttributes().
00166               hasAttribute(AttributeSet::FunctionIndex,
00167                            Attribute::OptimizeForSize)) {
00168         Threshold = UP.OptSizeThreshold;
00169         PartialThreshold = UP.PartialOptSizeThreshold;
00170       }
00171       if (HasPragma) {
00172         // If the loop has an unrolling pragma, we want to be more
00173         // aggressive with unrolling limits.  Set thresholds to at
00174         // least the PragmaTheshold value which is larger than the
00175         // default limits.
00176         if (Threshold != NoThreshold)
00177           Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
00178         if (PartialThreshold != NoThreshold)
00179           PartialThreshold =
00180               std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
00181       }
00182     }
00183   };
00184 }
00185 
00186 char LoopUnroll::ID = 0;
00187 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
00188 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
00189 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
00190 INITIALIZE_PASS_DEPENDENCY(FunctionTargetTransformInfo)
00191 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
00192 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00193 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00194 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
00195 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
00196 
00197 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
00198                                  int Runtime) {
00199   return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
00200 }
00201 
00202 Pass *llvm::createSimpleLoopUnrollPass() {
00203   return llvm::createLoopUnrollPass(-1, -1, 0, 0);
00204 }
00205 
00206 /// ApproximateLoopSize - Approximate the size of the loop.
00207 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
00208                                     bool &NotDuplicatable,
00209                                     const TargetTransformInfo &TTI,
00210                                     AssumptionTracker *AT) {
00211   SmallPtrSet<const Value *, 32> EphValues;
00212   CodeMetrics::collectEphemeralValues(L, AT, EphValues);
00213 
00214   CodeMetrics Metrics;
00215   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00216        I != E; ++I)
00217     Metrics.analyzeBasicBlock(*I, TTI, EphValues);
00218   NumCalls = Metrics.NumInlineCandidates;
00219   NotDuplicatable = Metrics.notDuplicatable;
00220 
00221   unsigned LoopSize = Metrics.NumInsts;
00222 
00223   // Don't allow an estimate of size zero.  This would allows unrolling of loops
00224   // with huge iteration counts, which is a compile time problem even if it's
00225   // not a problem for code quality.
00226   if (LoopSize == 0) LoopSize = 1;
00227 
00228   return LoopSize;
00229 }
00230 
00231 // Returns the loop hint metadata node with the given name (for example,
00232 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
00233 // returned.
00234 static const MDNode *GetUnrollMetadata(const Loop *L, StringRef Name) {
00235   MDNode *LoopID = L->getLoopID();
00236   if (!LoopID)
00237     return nullptr;
00238 
00239   // First operand should refer to the loop id itself.
00240   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
00241   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
00242 
00243   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
00244     const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
00245     if (!MD)
00246       continue;
00247 
00248     const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
00249     if (!S)
00250       continue;
00251 
00252     if (Name.equals(S->getString()))
00253       return MD;
00254   }
00255   return nullptr;
00256 }
00257 
00258 // Returns true if the loop has an unroll(full) pragma.
00259 static bool HasUnrollFullPragma(const Loop *L) {
00260   return GetUnrollMetadata(L, "llvm.loop.unroll.full");
00261 }
00262 
00263 // Returns true if the loop has an unroll(disable) pragma.
00264 static bool HasUnrollDisablePragma(const Loop *L) {
00265   return GetUnrollMetadata(L, "llvm.loop.unroll.disable");
00266 }
00267 
00268 // If loop has an unroll_count pragma return the (necessarily
00269 // positive) value from the pragma.  Otherwise return 0.
00270 static unsigned UnrollCountPragmaValue(const Loop *L) {
00271   const MDNode *MD = GetUnrollMetadata(L, "llvm.loop.unroll.count");
00272   if (MD) {
00273     assert(MD->getNumOperands() == 2 &&
00274            "Unroll count hint metadata should have two operands.");
00275     unsigned Count = cast<ConstantInt>(MD->getOperand(1))->getZExtValue();
00276     assert(Count >= 1 && "Unroll count must be positive.");
00277     return Count;
00278   }
00279   return 0;
00280 }
00281 
00282 // Remove existing unroll metadata and add unroll disable metadata to
00283 // indicate the loop has already been unrolled.  This prevents a loop
00284 // from being unrolled more than is directed by a pragma if the loop
00285 // unrolling pass is run more than once (which it generally is).
00286 static void SetLoopAlreadyUnrolled(Loop *L) {
00287   MDNode *LoopID = L->getLoopID();
00288   if (!LoopID) return;
00289 
00290   // First remove any existing loop unrolling metadata.
00291   SmallVector<Value *, 4> Vals;
00292   // Reserve first location for self reference to the LoopID metadata node.
00293   Vals.push_back(nullptr);
00294   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
00295     bool IsUnrollMetadata = false;
00296     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
00297     if (MD) {
00298       const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
00299       IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
00300     }
00301     if (!IsUnrollMetadata) Vals.push_back(LoopID->getOperand(i));
00302   }
00303 
00304   // Add unroll(disable) metadata to disable future unrolling.
00305   LLVMContext &Context = L->getHeader()->getContext();
00306   SmallVector<Value *, 1> DisableOperands;
00307   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
00308   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
00309   Vals.push_back(DisableNode);
00310 
00311   MDNode *NewLoopID = MDNode::get(Context, Vals);
00312   // Set operand 0 to refer to the loop id itself.
00313   NewLoopID->replaceOperandWith(0, NewLoopID);
00314   L->setLoopID(NewLoopID);
00315 }
00316 
00317 unsigned LoopUnroll::selectUnrollCount(
00318     const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
00319     unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
00320     bool &SetExplicitly) {
00321   SetExplicitly = true;
00322 
00323   // User-specified count (either as a command-line option or
00324   // constructor parameter) has highest precedence.
00325   unsigned Count = UserCount ? CurrentCount : 0;
00326 
00327   // If there is no user-specified count, unroll pragmas have the next
00328   // highest precendence.
00329   if (Count == 0) {
00330     if (PragmaCount) {
00331       Count = PragmaCount;
00332     } else if (PragmaFullUnroll) {
00333       Count = TripCount;
00334     }
00335   }
00336 
00337   if (Count == 0)
00338     Count = UP.Count;
00339 
00340   if (Count == 0) {
00341     SetExplicitly = false;
00342     if (TripCount == 0)
00343       // Runtime trip count.
00344       Count = UnrollRuntimeCount;
00345     else
00346       // Conservative heuristic: if we know the trip count, see if we can
00347       // completely unroll (subject to the threshold, checked below); otherwise
00348       // try to find greatest modulo of the trip count which is still under
00349       // threshold value.
00350       Count = TripCount;
00351   }
00352   if (TripCount && Count > TripCount)
00353     return TripCount;
00354   return Count;
00355 }
00356 
00357 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
00358   if (skipOptnoneFunction(L))
00359     return false;
00360 
00361   LoopInfo *LI = &getAnalysis<LoopInfo>();
00362   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
00363   const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
00364   const FunctionTargetTransformInfo &FTTI =
00365       getAnalysis<FunctionTargetTransformInfo>();
00366   AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
00367 
00368   BasicBlock *Header = L->getHeader();
00369   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
00370         << "] Loop %" << Header->getName() << "\n");
00371 
00372   if (HasUnrollDisablePragma(L)) {
00373     return false;
00374   }
00375   bool PragmaFullUnroll = HasUnrollFullPragma(L);
00376   unsigned PragmaCount = UnrollCountPragmaValue(L);
00377   bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
00378 
00379   TargetTransformInfo::UnrollingPreferences UP;
00380   getUnrollingPreferences(L, FTTI, UP);
00381 
00382   // Find trip count and trip multiple if count is not available
00383   unsigned TripCount = 0;
00384   unsigned TripMultiple = 1;
00385   // Find "latch trip count". UnrollLoop assumes that control cannot exit
00386   // via the loop latch on any iteration prior to TripCount. The loop may exit
00387   // early via an earlier branch.
00388   BasicBlock *LatchBlock = L->getLoopLatch();
00389   if (LatchBlock) {
00390     TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
00391     TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
00392   }
00393 
00394   // Select an initial unroll count.  This may be reduced later based
00395   // on size thresholds.
00396   bool CountSetExplicitly;
00397   unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
00398                                      PragmaCount, UP, CountSetExplicitly);
00399 
00400   unsigned NumInlineCandidates;
00401   bool notDuplicatable;
00402   unsigned LoopSize =
00403       ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, AT);
00404   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
00405   uint64_t UnrolledSize = (uint64_t)LoopSize * Count;
00406   if (notDuplicatable) {
00407     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
00408                  << " instructions.\n");
00409     return false;
00410   }
00411   if (NumInlineCandidates != 0) {
00412     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
00413     return false;
00414   }
00415 
00416   unsigned Threshold, PartialThreshold;
00417   selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold);
00418 
00419   // Given Count, TripCount and thresholds determine the type of
00420   // unrolling which is to be performed.
00421   enum { Full = 0, Partial = 1, Runtime = 2 };
00422   int Unrolling;
00423   if (TripCount && Count == TripCount) {
00424     if (Threshold != NoThreshold && UnrolledSize > Threshold) {
00425       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
00426                    << " because size: " << UnrolledSize << ">" << Threshold
00427                    << "\n");
00428       Unrolling = Partial;
00429     } else {
00430       Unrolling = Full;
00431     }
00432   } else if (TripCount && Count < TripCount) {
00433     Unrolling = Partial;
00434   } else {
00435     Unrolling = Runtime;
00436   }
00437 
00438   // Reduce count based on the type of unrolling and the threshold values.
00439   unsigned OriginalCount = Count;
00440   bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
00441   if (Unrolling == Partial) {
00442     bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
00443     if (!AllowPartial && !CountSetExplicitly) {
00444       DEBUG(dbgs() << "  will not try to unroll partially because "
00445                    << "-unroll-allow-partial not given\n");
00446       return false;
00447     }
00448     if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
00449       // Reduce unroll count to be modulo of TripCount for partial unrolling.
00450       Count = PartialThreshold / LoopSize;
00451       while (Count != 0 && TripCount % Count != 0)
00452         Count--;
00453     }
00454   } else if (Unrolling == Runtime) {
00455     if (!AllowRuntime && !CountSetExplicitly) {
00456       DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
00457                    << "-unroll-runtime not given\n");
00458       return false;
00459     }
00460     // Reduce unroll count to be the largest power-of-two factor of
00461     // the original count which satisfies the threshold limit.
00462     while (Count != 0 && UnrolledSize > PartialThreshold) {
00463       Count >>= 1;
00464       UnrolledSize = LoopSize * Count;
00465     }
00466     if (Count > UP.MaxCount)
00467       Count = UP.MaxCount;
00468     DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
00469   }
00470 
00471   if (HasPragma) {
00472     if (PragmaCount != 0)
00473       // If loop has an unroll count pragma mark loop as unrolled to prevent
00474       // unrolling beyond that requested by the pragma.
00475       SetLoopAlreadyUnrolled(L);
00476 
00477     // Emit optimization remarks if we are unable to unroll the loop
00478     // as directed by a pragma.
00479     DebugLoc LoopLoc = L->getStartLoc();
00480     Function *F = Header->getParent();
00481     LLVMContext &Ctx = F->getContext();
00482     if (PragmaFullUnroll && PragmaCount == 0) {
00483       if (TripCount && Count != TripCount) {
00484         emitOptimizationRemarkMissed(
00485             Ctx, DEBUG_TYPE, *F, LoopLoc,
00486             "Unable to fully unroll loop as directed by unroll(full) pragma "
00487             "because unrolled size is too large.");
00488       } else if (!TripCount) {
00489         emitOptimizationRemarkMissed(
00490             Ctx, DEBUG_TYPE, *F, LoopLoc,
00491             "Unable to fully unroll loop as directed by unroll(full) pragma "
00492             "because loop has a runtime trip count.");
00493       }
00494     } else if (PragmaCount > 0 && Count != OriginalCount) {
00495       emitOptimizationRemarkMissed(
00496           Ctx, DEBUG_TYPE, *F, LoopLoc,
00497           "Unable to unroll loop the number of times directed by "
00498           "unroll_count pragma because unrolled size is too large.");
00499     }
00500   }
00501 
00502   if (Unrolling != Full && Count < 2) {
00503     // Partial unrolling by 1 is a nop.  For full unrolling, a factor
00504     // of 1 makes sense because loop control can be eliminated.
00505     return false;
00506   }
00507 
00508   // Unroll the loop.
00509   if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,
00510                   &LPM, AT))
00511     return false;
00512 
00513   return true;
00514 }