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