LoopUnrollPass.cpp revision dce4a407a24b04eebc6a376f8e62b41aaa7b071f
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/Analysis/CodeMetrics.h"
17#include "llvm/Analysis/LoopPass.h"
18#include "llvm/Analysis/ScalarEvolution.h"
19#include "llvm/Analysis/TargetTransformInfo.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/Dominators.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/Transforms/Utils/UnrollLoop.h"
27#include <climits>
28
29using namespace llvm;
30
31#define DEBUG_TYPE "loop-unroll"
32
33static cl::opt<unsigned>
34UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
35  cl::desc("The cut-off point for automatic loop unrolling"));
36
37static cl::opt<unsigned>
38UnrollCount("unroll-count", cl::init(0), cl::Hidden,
39  cl::desc("Use this unroll count for all loops, for testing purposes"));
40
41static cl::opt<bool>
42UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
43  cl::desc("Allows loops to be partially unrolled until "
44           "-unroll-threshold loop size is reached."));
45
46static cl::opt<bool>
47UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
48  cl::desc("Unroll loops with run-time trip counts"));
49
50namespace {
51  class LoopUnroll : public LoopPass {
52  public:
53    static char ID; // Pass ID, replacement for typeid
54    LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
55      CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
56      CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
57      CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
58      CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
59
60      UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
61      UserAllowPartial = (P != -1) ||
62                         (UnrollAllowPartial.getNumOccurrences() > 0);
63      UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
64      UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
65
66      initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
67    }
68
69    /// A magic value for use with the Threshold parameter to indicate
70    /// that the loop unroll should be performed regardless of how much
71    /// code expansion would result.
72    static const unsigned NoThreshold = UINT_MAX;
73
74    // Threshold to use when optsize is specified (and there is no
75    // explicit -unroll-threshold).
76    static const unsigned OptSizeUnrollThreshold = 50;
77
78    // Default unroll count for loops with run-time trip count if
79    // -unroll-count is not set
80    static const unsigned UnrollRuntimeCount = 8;
81
82    unsigned CurrentCount;
83    unsigned CurrentThreshold;
84    bool     CurrentAllowPartial;
85    bool     CurrentRuntime;
86    bool     UserCount;            // CurrentCount is user-specified.
87    bool     UserThreshold;        // CurrentThreshold is user-specified.
88    bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
89    bool     UserRuntime;          // CurrentRuntime is user-specified.
90
91    bool runOnLoop(Loop *L, LPPassManager &LPM) override;
92
93    /// This transformation requires natural loop information & requires that
94    /// loop preheaders be inserted into the CFG...
95    ///
96    void getAnalysisUsage(AnalysisUsage &AU) const override {
97      AU.addRequired<LoopInfo>();
98      AU.addPreserved<LoopInfo>();
99      AU.addRequiredID(LoopSimplifyID);
100      AU.addPreservedID(LoopSimplifyID);
101      AU.addRequiredID(LCSSAID);
102      AU.addPreservedID(LCSSAID);
103      AU.addRequired<ScalarEvolution>();
104      AU.addPreserved<ScalarEvolution>();
105      AU.addRequired<TargetTransformInfo>();
106      // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
107      // If loop unroll does not preserve dom info then LCSSA pass on next
108      // loop will receive invalid dom info.
109      // For now, recreate dom info, if loop is unrolled.
110      AU.addPreserved<DominatorTreeWrapperPass>();
111    }
112  };
113}
114
115char LoopUnroll::ID = 0;
116INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
117INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
118INITIALIZE_PASS_DEPENDENCY(LoopInfo)
119INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
120INITIALIZE_PASS_DEPENDENCY(LCSSA)
121INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
122INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
123
124Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
125                                 int Runtime) {
126  return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
127}
128
129Pass *llvm::createSimpleLoopUnrollPass() {
130  return llvm::createLoopUnrollPass(-1, -1, 0, 0);
131}
132
133/// ApproximateLoopSize - Approximate the size of the loop.
134static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
135                                    bool &NotDuplicatable,
136                                    const TargetTransformInfo &TTI) {
137  CodeMetrics Metrics;
138  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
139       I != E; ++I)
140    Metrics.analyzeBasicBlock(*I, TTI);
141  NumCalls = Metrics.NumInlineCandidates;
142  NotDuplicatable = Metrics.notDuplicatable;
143
144  unsigned LoopSize = Metrics.NumInsts;
145
146  // Don't allow an estimate of size zero.  This would allows unrolling of loops
147  // with huge iteration counts, which is a compile time problem even if it's
148  // not a problem for code quality.
149  if (LoopSize == 0) LoopSize = 1;
150
151  return LoopSize;
152}
153
154bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
155  if (skipOptnoneFunction(L))
156    return false;
157
158  LoopInfo *LI = &getAnalysis<LoopInfo>();
159  ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
160  const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
161
162  BasicBlock *Header = L->getHeader();
163  DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
164        << "] Loop %" << Header->getName() << "\n");
165  (void)Header;
166
167  TargetTransformInfo::UnrollingPreferences UP;
168  UP.Threshold = CurrentThreshold;
169  UP.OptSizeThreshold = OptSizeUnrollThreshold;
170  UP.PartialThreshold = CurrentThreshold;
171  UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
172  UP.Count = CurrentCount;
173  UP.MaxCount = UINT_MAX;
174  UP.Partial = CurrentAllowPartial;
175  UP.Runtime = CurrentRuntime;
176  TTI.getUnrollingPreferences(L, UP);
177
178  // Determine the current unrolling threshold.  While this is normally set
179  // from UnrollThreshold, it is overridden to a smaller value if the current
180  // function is marked as optimize-for-size, and the unroll threshold was
181  // not user specified.
182  unsigned Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
183  unsigned PartialThreshold =
184    UserThreshold ? CurrentThreshold : UP.PartialThreshold;
185  if (!UserThreshold &&
186      Header->getParent()->getAttributes().
187        hasAttribute(AttributeSet::FunctionIndex,
188                     Attribute::OptimizeForSize)) {
189    Threshold = UP.OptSizeThreshold;
190    PartialThreshold = UP.PartialOptSizeThreshold;
191  }
192
193  // Find trip count and trip multiple if count is not available
194  unsigned TripCount = 0;
195  unsigned TripMultiple = 1;
196  // Find "latch trip count". UnrollLoop assumes that control cannot exit
197  // via the loop latch on any iteration prior to TripCount. The loop may exit
198  // early via an earlier branch.
199  BasicBlock *LatchBlock = L->getLoopLatch();
200  if (LatchBlock) {
201    TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
202    TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
203  }
204
205  bool Runtime = UserRuntime ? CurrentRuntime : UP.Runtime;
206
207  // Use a default unroll-count if the user doesn't specify a value
208  // and the trip count is a run-time value.  The default is different
209  // for run-time or compile-time trip count loops.
210  unsigned Count = UserCount ? CurrentCount : UP.Count;
211  if (Runtime && Count == 0 && TripCount == 0)
212    Count = UnrollRuntimeCount;
213
214  if (Count == 0) {
215    // Conservative heuristic: if we know the trip count, see if we can
216    // completely unroll (subject to the threshold, checked below); otherwise
217    // try to find greatest modulo of the trip count which is still under
218    // threshold value.
219    if (TripCount == 0)
220      return false;
221    Count = TripCount;
222  }
223
224  // Enforce the threshold.
225  if (Threshold != NoThreshold && PartialThreshold != NoThreshold) {
226    unsigned NumInlineCandidates;
227    bool notDuplicatable;
228    unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates,
229                                            notDuplicatable, TTI);
230    DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
231    if (notDuplicatable) {
232      DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
233            << " instructions.\n");
234      return false;
235    }
236    if (NumInlineCandidates != 0) {
237      DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
238      return false;
239    }
240    uint64_t Size = (uint64_t)LoopSize*Count;
241    if (TripCount != 1 &&
242        (Size > Threshold || (Count != TripCount && Size > PartialThreshold))) {
243      if (Size > Threshold)
244        DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
245                     << " because size: " << Size << ">" << Threshold << "\n");
246
247      bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
248      if (!AllowPartial && !(Runtime && TripCount == 0)) {
249        DEBUG(dbgs() << "  will not try to unroll partially because "
250              << "-unroll-allow-partial not given\n");
251        return false;
252      }
253      if (TripCount) {
254        // Reduce unroll count to be modulo of TripCount for partial unrolling
255        Count = PartialThreshold / LoopSize;
256        while (Count != 0 && TripCount%Count != 0)
257          Count--;
258      }
259      else if (Runtime) {
260        // Reduce unroll count to be a lower power-of-two value
261        while (Count != 0 && Size > PartialThreshold) {
262          Count >>= 1;
263          Size = LoopSize*Count;
264        }
265      }
266      if (Count > UP.MaxCount)
267        Count = UP.MaxCount;
268      if (Count < 2) {
269        DEBUG(dbgs() << "  could not unroll partially\n");
270        return false;
271      }
272      DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
273    }
274  }
275
276  // Unroll the loop.
277  if (!UnrollLoop(L, Count, TripCount, Runtime, TripMultiple, LI, this, &LPM))
278    return false;
279
280  return true;
281}
282