LoopUnrollPass.cpp revision ed38f1ca2ede643b058211ec09b205ed30d2a256
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#define DEBUG_TYPE "loop-unroll"
16#include "llvm/IntrinsicInst.h"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/CodeMetrics.h"
20#include "llvm/Analysis/ScalarEvolution.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/raw_ostream.h"
24#include "llvm/Transforms/Utils/UnrollLoop.h"
25#include "llvm/Target/TargetData.h"
26#include <climits>
27
28using namespace llvm;
29
30static cl::opt<unsigned>
31UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
32  cl::desc("The cut-off point for automatic loop unrolling"));
33
34static cl::opt<unsigned>
35UnrollCount("unroll-count", cl::init(0), cl::Hidden,
36  cl::desc("Use this unroll count for all loops, for testing purposes"));
37
38static cl::opt<bool>
39UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
40  cl::desc("Allows loops to be partially unrolled until "
41           "-unroll-threshold loop size is reached."));
42
43namespace {
44  class LoopUnroll : public LoopPass {
45  public:
46    static char ID; // Pass ID, replacement for typeid
47    LoopUnroll(int T = -1, int C = -1,  int P = -1) : LoopPass(ID) {
48      CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
49      CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
50      CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
51
52      UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
53
54      initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
55    }
56
57    /// A magic value for use with the Threshold parameter to indicate
58    /// that the loop unroll should be performed regardless of how much
59    /// code expansion would result.
60    static const unsigned NoThreshold = UINT_MAX;
61
62    // Threshold to use when optsize is specified (and there is no
63    // explicit -unroll-threshold).
64    static const unsigned OptSizeUnrollThreshold = 50;
65
66    unsigned CurrentCount;
67    unsigned CurrentThreshold;
68    bool     CurrentAllowPartial;
69    bool     UserThreshold;        // CurrentThreshold is user-specified.
70
71    bool runOnLoop(Loop *L, LPPassManager &LPM);
72
73    /// This transformation requires natural loop information & requires that
74    /// loop preheaders be inserted into the CFG...
75    ///
76    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77      AU.addRequired<LoopInfo>();
78      AU.addPreserved<LoopInfo>();
79      AU.addRequiredID(LoopSimplifyID);
80      AU.addPreservedID(LoopSimplifyID);
81      AU.addRequiredID(LCSSAID);
82      AU.addPreservedID(LCSSAID);
83      AU.addRequired<ScalarEvolution>();
84      AU.addPreserved<ScalarEvolution>();
85      // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
86      // If loop unroll does not preserve dom info then LCSSA pass on next
87      // loop will receive invalid dom info.
88      // For now, recreate dom info, if loop is unrolled.
89      AU.addPreserved<DominatorTree>();
90    }
91  };
92}
93
94char LoopUnroll::ID = 0;
95INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
96INITIALIZE_PASS_DEPENDENCY(LoopInfo)
97INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
98INITIALIZE_PASS_DEPENDENCY(LCSSA)
99INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
100INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
101
102Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) {
103  return new LoopUnroll(Threshold, Count, AllowPartial);
104}
105
106/// ApproximateLoopSize - Approximate the size of the loop.
107static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
108                                    const TargetData *TD) {
109  CodeMetrics Metrics;
110  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
111       I != E; ++I)
112    Metrics.analyzeBasicBlock(*I, TD);
113  NumCalls = Metrics.NumInlineCandidates;
114
115  unsigned LoopSize = Metrics.NumInsts;
116
117  // Don't allow an estimate of size zero.  This would allows unrolling of loops
118  // with huge iteration counts, which is a compile time problem even if it's
119  // not a problem for code quality.
120  if (LoopSize == 0) LoopSize = 1;
121
122  return LoopSize;
123}
124
125bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
126  LoopInfo *LI = &getAnalysis<LoopInfo>();
127  ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
128
129  BasicBlock *Header = L->getHeader();
130  DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
131        << "] Loop %" << Header->getName() << "\n");
132  (void)Header;
133
134  // Determine the current unrolling threshold.  While this is normally set
135  // from UnrollThreshold, it is overridden to a smaller value if the current
136  // function is marked as optimize-for-size, and the unroll threshold was
137  // not user specified.
138  unsigned Threshold = CurrentThreshold;
139  if (!UserThreshold &&
140      Header->getParent()->hasFnAttr(Attribute::OptimizeForSize))
141    Threshold = OptSizeUnrollThreshold;
142
143  // Find trip count and trip multiple if count is not available
144  unsigned TripCount = 0;
145  unsigned TripMultiple = 1;
146  // Find "latch trip count". UnrollLoop assumes that control cannot exit
147  // via the loop latch on any iteration prior to TripCount. The loop may exit
148  // early via an earlier branch.
149  BasicBlock *LatchBlock = L->getLoopLatch();
150  if (LatchBlock) {
151    TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
152    TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
153  }
154  // Automatically select an unroll count.
155  unsigned Count = CurrentCount;
156  if (Count == 0) {
157    // Conservative heuristic: if we know the trip count, see if we can
158    // completely unroll (subject to the threshold, checked below); otherwise
159    // try to find greatest modulo of the trip count which is still under
160    // threshold value.
161    if (TripCount == 0)
162      return false;
163    Count = TripCount;
164  }
165
166  // Enforce the threshold.
167  if (Threshold != NoThreshold) {
168    const TargetData *TD = getAnalysisIfAvailable<TargetData>();
169    unsigned NumInlineCandidates;
170    unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates, TD);
171    DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
172    if (NumInlineCandidates != 0) {
173      DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
174      return false;
175    }
176    uint64_t Size = (uint64_t)LoopSize*Count;
177    if (TripCount != 1 && Size > Threshold) {
178      DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
179            << " because size: " << Size << ">" << Threshold << "\n");
180      if (!CurrentAllowPartial) {
181        DEBUG(dbgs() << "  will not try to unroll partially because "
182              << "-unroll-allow-partial not given\n");
183        return false;
184      }
185      // Reduce unroll count to be modulo of TripCount for partial unrolling
186      Count = Threshold / LoopSize;
187      while (Count != 0 && TripCount%Count != 0) {
188        Count--;
189      }
190      if (Count < 2) {
191        DEBUG(dbgs() << "  could not unroll partially\n");
192        return false;
193      }
194      DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
195    }
196  }
197
198  // Unroll the loop.
199  if (!UnrollLoop(L, Count, TripCount, TripMultiple, LI, &LPM))
200    return false;
201
202  return true;
203}
204