1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
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"
29 static cl::opt
<unsigned>
30 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden
,
31 cl::desc("The cut-off point for automatic loop unrolling"));
33 static cl::opt
<unsigned>
34 UnrollCount("unroll-count", cl::init(0), cl::Hidden
,
35 cl::desc("Use this unroll count for all loops, for testing purposes"));
38 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden
,
39 cl::desc("Allows loops to be partially unrolled until "
40 "-unroll-threshold loop size is reached."));
43 class LoopUnroll
: public LoopPass
{
45 static char ID
; // Pass ID, replacement for typeid
46 LoopUnroll() : LoopPass(ID
) {
47 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
50 /// A magic value for use with the Threshold parameter to indicate
51 /// that the loop unroll should be performed regardless of how much
52 /// code expansion would result.
53 static const unsigned NoThreshold
= UINT_MAX
;
55 // Threshold to use when optsize is specified (and there is no
56 // explicit -unroll-threshold).
57 static const unsigned OptSizeUnrollThreshold
= 50;
59 unsigned CurrentThreshold
;
61 bool runOnLoop(Loop
*L
, LPPassManager
&LPM
);
63 /// This transformation requires natural loop information & requires that
64 /// loop preheaders be inserted into the CFG...
66 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
67 AU
.addRequired
<LoopInfo
>();
68 AU
.addPreserved
<LoopInfo
>();
69 AU
.addRequiredID(LoopSimplifyID
);
70 AU
.addPreservedID(LoopSimplifyID
);
71 AU
.addRequiredID(LCSSAID
);
72 AU
.addPreservedID(LCSSAID
);
73 AU
.addPreserved
<ScalarEvolution
>();
74 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
75 // If loop unroll does not preserve dom info then LCSSA pass on next
76 // loop will receive invalid dom info.
77 // For now, recreate dom info, if loop is unrolled.
78 AU
.addPreserved
<DominatorTree
>();
83 char LoopUnroll::ID
= 0;
84 INITIALIZE_PASS_BEGIN(LoopUnroll
, "loop-unroll", "Unroll loops", false, false)
85 INITIALIZE_PASS_DEPENDENCY(LoopInfo
)
86 INITIALIZE_PASS_DEPENDENCY(LoopSimplify
)
87 INITIALIZE_PASS_DEPENDENCY(LCSSA
)
88 INITIALIZE_PASS_END(LoopUnroll
, "loop-unroll", "Unroll loops", false, false)
90 Pass
*llvm::createLoopUnrollPass() { return new LoopUnroll(); }
92 /// ApproximateLoopSize - Approximate the size of the loop.
93 static unsigned ApproximateLoopSize(const Loop
*L
, unsigned &NumCalls
) {
95 for (Loop::block_iterator I
= L
->block_begin(), E
= L
->block_end();
97 Metrics
.analyzeBasicBlock(*I
);
98 NumCalls
= Metrics
.NumInlineCandidates
;
100 unsigned LoopSize
= Metrics
.NumInsts
;
102 // Don't allow an estimate of size zero. This would allows unrolling of loops
103 // with huge iteration counts, which is a compile time problem even if it's
104 // not a problem for code quality.
105 if (LoopSize
== 0) LoopSize
= 1;
110 bool LoopUnroll::runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
111 LoopInfo
*LI
= &getAnalysis
<LoopInfo
>();
113 BasicBlock
*Header
= L
->getHeader();
114 DEBUG(dbgs() << "Loop Unroll: F[" << Header
->getParent()->getName()
115 << "] Loop %" << Header
->getName() << "\n");
118 // Determine the current unrolling threshold. While this is normally set
119 // from UnrollThreshold, it is overridden to a smaller value if the current
120 // function is marked as optimize-for-size, and the unroll threshold was
121 // not user specified.
122 CurrentThreshold
= UnrollThreshold
;
123 if (Header
->getParent()->hasFnAttr(Attribute::OptimizeForSize
) &&
124 UnrollThreshold
.getNumOccurrences() == 0)
125 CurrentThreshold
= OptSizeUnrollThreshold
;
128 unsigned TripCount
= L
->getSmallConstantTripCount();
129 unsigned Count
= UnrollCount
;
131 // Automatically select an unroll count.
133 // Conservative heuristic: if we know the trip count, see if we can
134 // completely unroll (subject to the threshold, checked below); otherwise
135 // try to find greatest modulo of the trip count which is still under
142 // Enforce the threshold.
143 if (CurrentThreshold
!= NoThreshold
) {
144 unsigned NumInlineCandidates
;
145 unsigned LoopSize
= ApproximateLoopSize(L
, NumInlineCandidates
);
146 DEBUG(dbgs() << " Loop Size = " << LoopSize
<< "\n");
147 if (NumInlineCandidates
!= 0) {
148 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
151 uint64_t Size
= (uint64_t)LoopSize
*Count
;
152 if (TripCount
!= 1 && Size
> CurrentThreshold
) {
153 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
154 << " because size: " << Size
<< ">" << CurrentThreshold
<< "\n");
155 if (!UnrollAllowPartial
) {
156 DEBUG(dbgs() << " will not try to unroll partially because "
157 << "-unroll-allow-partial not given\n");
160 // Reduce unroll count to be modulo of TripCount for partial unrolling
161 Count
= CurrentThreshold
/ LoopSize
;
162 while (Count
!= 0 && TripCount
%Count
!= 0) {
166 DEBUG(dbgs() << " could not unroll partially\n");
169 DEBUG(dbgs() << " partially unrolling with count: " << Count
<< "\n");
174 Function
*F
= L
->getHeader()->getParent();
175 if (!UnrollLoop(L
, Count
, LI
, &LPM
))
178 // FIXME: Reconstruct dom info, because it is not preserved properly.
179 if (DominatorTree
*DT
= getAnalysisIfAvailable
<DominatorTree
>())
180 DT
->runOnFunction(*F
);