blob: 4d23178174bef24705133798e3b436b154202f9e [file] [log] [blame]
Chris Lattner83bf2882004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner83bf2882004-04-18 05:20:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner83bf2882004-04-18 05:20:17 +00008//===----------------------------------------------------------------------===//
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.
Chris Lattner83bf2882004-04-18 05:20:17 +000013//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "loop-unroll"
Dan Gohman45b31972008-05-14 00:24:14 +000016#include "llvm/IntrinsicInst.h"
Chris Lattner83bf2882004-04-18 05:20:17 +000017#include "llvm/Transforms/Scalar.h"
Devang Patel3f1a1e02007-03-07 01:38:05 +000018#include "llvm/Analysis/LoopPass.h"
Dan Gohmana2aabe32009-10-31 14:54:17 +000019#include "llvm/Analysis/InlineCost.h"
Dan Gohman052f0002010-07-26 18:11:16 +000020#include "llvm/Analysis/ScalarEvolution.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000023#include "llvm/Support/raw_ostream.h"
Dan Gohman45b31972008-05-14 00:24:14 +000024#include "llvm/Transforms/Utils/UnrollLoop.h"
Duncan Sands1a2d6672008-05-16 09:30:00 +000025#include <climits>
Chris Lattner83bf2882004-04-18 05:20:17 +000026
Dan Gohman45b31972008-05-14 00:24:14 +000027using namespace llvm;
Chris Lattner83bf2882004-04-18 05:20:17 +000028
Dan Gohman844731a2008-05-13 00:00:25 +000029static cl::opt<unsigned>
Owen Andersoncc443c32010-09-09 19:11:57 +000030UnrollThreshold("unroll-threshold", cl::init(200), cl::Hidden,
Dan Gohman844731a2008-05-13 00:00:25 +000031 cl::desc("The cut-off point for automatic loop unrolling"));
32
33static cl::opt<unsigned>
34UnrollCount("unroll-count", cl::init(0), cl::Hidden,
35 cl::desc("Use this unroll count for all loops, for testing purposes"));
36
Matthijs Kooijman75cf9cc2008-07-29 13:21:23 +000037static cl::opt<bool>
38UnrollAllowPartial("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."));
41
Chris Lattner0e5f4992006-12-19 21:40:18 +000042namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000043 class LoopUnroll : public LoopPass {
Chris Lattner83bf2882004-04-18 05:20:17 +000044 public:
Devang Patel19974732007-05-03 01:11:54 +000045 static char ID; // Pass ID, replacement for typeid
Owen Anderson90c579d2010-08-06 18:33:48 +000046 LoopUnroll() : LoopPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000047
Dan Gohmanc7678442007-05-11 20:53:41 +000048 /// A magic value for use with the Threshold parameter to indicate
49 /// that the loop unroll should be performed regardless of how much
50 /// code expansion would result.
51 static const unsigned NoThreshold = UINT_MAX;
Owen Andersone9f18822010-09-07 23:15:30 +000052
53 // Threshold to use when optsize is specified (and there is no
54 // explicit -unroll-threshold).
55 static const unsigned OptSizeUnrollThreshold = 50;
56
57 unsigned CurrentThreshold;
Dan Gohmanc7678442007-05-11 20:53:41 +000058
Devang Patel3f1a1e02007-03-07 01:38:05 +000059 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner83bf2882004-04-18 05:20:17 +000060
61 /// This transformation requires natural loop information & requires that
62 /// loop preheaders be inserted into the CFG...
63 ///
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner83bf2882004-04-18 05:20:17 +000065 AU.addRequired<LoopInfo>();
Chris Lattner9c2cc462004-04-18 05:38:37 +000066 AU.addPreserved<LoopInfo>();
Dan Gohman052f0002010-07-26 18:11:16 +000067 AU.addRequiredID(LoopSimplifyID);
68 AU.addPreservedID(LoopSimplifyID);
69 AU.addRequiredID(LCSSAID);
70 AU.addPreservedID(LCSSAID);
Chris Lattner93779012010-08-29 17:21:35 +000071 AU.addPreserved<ScalarEvolution>();
Devang Patel98260a42008-07-03 07:04:22 +000072 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
73 // If loop unroll does not preserve dom info then LCSSA pass on next
74 // loop will receive invalid dom info.
75 // For now, recreate dom info, if loop is unrolled.
76 AU.addPreserved<DominatorTree>();
Chris Lattner83bf2882004-04-18 05:20:17 +000077 }
78 };
Chris Lattner83bf2882004-04-18 05:20:17 +000079}
80
Dan Gohman844731a2008-05-13 00:00:25 +000081char LoopUnroll::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000082INITIALIZE_PASS(LoopUnroll, "loop-unroll", "Unroll loops", false, false);
Dan Gohman844731a2008-05-13 00:00:25 +000083
Daniel Dunbar394f0442008-10-22 23:32:42 +000084Pass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
Chris Lattner83bf2882004-04-18 05:20:17 +000085
Dan Gohmanf742c232007-05-08 15:14:19 +000086/// ApproximateLoopSize - Approximate the size of the loop.
Jakob Stoklund Olesend450e5b2010-02-05 23:21:31 +000087static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {
Dan Gohmana2aabe32009-10-31 14:54:17 +000088 CodeMetrics Metrics;
Dan Gohman9b787632008-06-22 20:18:58 +000089 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohmana2aabe32009-10-31 14:54:17 +000090 I != E; ++I)
91 Metrics.analyzeBasicBlock(*I);
Jakob Stoklund Olesend450e5b2010-02-05 23:21:31 +000092 NumCalls = Metrics.NumCalls;
Owen Anderson6add2fb2010-09-09 19:07:31 +000093
94 unsigned LoopSize = Metrics.NumInsts;
95
96 // If we can identify the induction variable, we know that it will become
97 // constant when we unroll the loop, so factor that into our loop size
98 // estimate.
99 // FIXME: We have to divide by InlineConstants::InstrCost because the
100 // measure returned by CountCodeReductionForConstant is not an instruction
101 // count, but rather a weight as defined by InlineConstants. It would
102 // probably be a good idea to standardize on a single weighting scheme by
103 // pushing more of the logic for weighting into CodeMetrics.
104 if (PHINode *IndVar = L->getCanonicalInductionVariable()) {
105 unsigned SizeDecrease = Metrics.CountCodeReductionForConstant(IndVar);
106 // NOTE: Because SizeDecrease is a fuzzy estimate, we don't want to allow
107 // it to totally negate the cost of unrolling a loop.
Owen Anderson20672e42010-09-09 19:08:59 +0000108 SizeDecrease = SizeDecrease > LoopSize / 2 ? LoopSize / 2 : SizeDecrease;
Owen Anderson6add2fb2010-09-09 19:07:31 +0000109 }
110
111 // Don't allow an estimate of size zero. This would allows unrolling of loops
112 // with huge iteration counts, which is a compile time problem even if it's
113 // not a problem for code quality.
114 if (LoopSize == 0) LoopSize = 1;
115
116 return LoopSize;
Chris Lattner83bf2882004-04-18 05:20:17 +0000117}
118
Devang Patel3f1a1e02007-03-07 01:38:05 +0000119bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Owen Andersone9f18822010-09-07 23:15:30 +0000120
Dan Gohman45b31972008-05-14 00:24:14 +0000121 LoopInfo *LI = &getAnalysis<LoopInfo>();
Dan Gohmanc7678442007-05-11 20:53:41 +0000122
Dan Gohman1cc00962007-05-08 15:19:19 +0000123 BasicBlock *Header = L->getHeader();
David Greened241e382010-01-05 01:27:44 +0000124 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000125 << "] Loop %" << Header->getName() << "\n");
Mike Stump02efa782009-07-27 23:14:11 +0000126 (void)Header;
Owen Andersone9f18822010-09-07 23:15:30 +0000127
128 // Determine the current unrolling threshold. While this is normally set
129 // from UnrollThreshold, it is overridden to a smaller value if the current
130 // function is marked as optimize-for-size, and the unroll threshold was
131 // not user specified.
132 CurrentThreshold = UnrollThreshold;
133 if (Header->getParent()->hasFnAttr(Attribute::OptimizeForSize) &&
134 UnrollThreshold.getNumOccurrences() == 0)
135 CurrentThreshold = OptSizeUnrollThreshold;
Dan Gohmanc7678442007-05-11 20:53:41 +0000136
Dan Gohman45b31972008-05-14 00:24:14 +0000137 // Find trip count
138 unsigned TripCount = L->getSmallConstantTripCount();
139 unsigned Count = UnrollCount;
Andreas Bolkaf1f2dc22009-08-13 02:40:50 +0000140
Dan Gohmanc7678442007-05-11 20:53:41 +0000141 // Automatically select an unroll count.
142 if (Count == 0) {
143 // Conservative heuristic: if we know the trip count, see if we can
144 // completely unroll (subject to the threshold, checked below); otherwise
Andreas Bolkaf1f2dc22009-08-13 02:40:50 +0000145 // try to find greatest modulo of the trip count which is still under
Matthijs Kooijman75cf9cc2008-07-29 13:21:23 +0000146 // threshold value.
Andreas Bolkaec40eb42009-08-13 03:00:57 +0000147 if (TripCount == 0)
Dan Gohmanc7678442007-05-11 20:53:41 +0000148 return false;
Andreas Bolkaec40eb42009-08-13 03:00:57 +0000149 Count = TripCount;
Dan Gohmanc7678442007-05-11 20:53:41 +0000150 }
151
Dan Gohmanc7678442007-05-11 20:53:41 +0000152 // Enforce the threshold.
Owen Andersone9f18822010-09-07 23:15:30 +0000153 if (CurrentThreshold != NoThreshold) {
Jakob Stoklund Olesend450e5b2010-02-05 23:21:31 +0000154 unsigned NumCalls;
155 unsigned LoopSize = ApproximateLoopSize(L, NumCalls);
David Greened241e382010-01-05 01:27:44 +0000156 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Jakob Stoklund Olesend450e5b2010-02-05 23:21:31 +0000157 if (NumCalls != 0) {
Owen Anderson49754472010-09-08 23:10:07 +0000158 // Even for a loop that contains calls, it can still be profitable to
159 // unroll if the loop is really, REALLY small.
160 DEBUG(dbgs() <<" Using lower threshold for loop with function calls.\n");
161 CurrentThreshold = OptSizeUnrollThreshold;
Jakob Stoklund Olesend450e5b2010-02-05 23:21:31 +0000162 }
Dan Gohmanc7678442007-05-11 20:53:41 +0000163 uint64_t Size = (uint64_t)LoopSize*Count;
Owen Andersone9f18822010-09-07 23:15:30 +0000164 if (TripCount != 1 && Size > CurrentThreshold) {
David Greened241e382010-01-05 01:27:44 +0000165 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
Owen Andersone9f18822010-09-07 23:15:30 +0000166 << " because size: " << Size << ">" << CurrentThreshold << "\n");
Andreas Bolkaec40eb42009-08-13 03:00:57 +0000167 if (!UnrollAllowPartial) {
David Greened241e382010-01-05 01:27:44 +0000168 DEBUG(dbgs() << " will not try to unroll partially because "
Andreas Bolka52e539c2009-08-13 02:45:03 +0000169 << "-unroll-allow-partial not given\n");
Matthijs Kooijman75cf9cc2008-07-29 13:21:23 +0000170 return false;
171 }
Andreas Bolkaec40eb42009-08-13 03:00:57 +0000172 // Reduce unroll count to be modulo of TripCount for partial unrolling
Owen Andersone9f18822010-09-07 23:15:30 +0000173 Count = CurrentThreshold / LoopSize;
Andreas Bolkaec40eb42009-08-13 03:00:57 +0000174 while (Count != 0 && TripCount%Count != 0) {
175 Count--;
176 }
177 if (Count < 2) {
David Greened241e382010-01-05 01:27:44 +0000178 DEBUG(dbgs() << " could not unroll partially\n");
Andreas Bolkaec40eb42009-08-13 03:00:57 +0000179 return false;
180 }
David Greened241e382010-01-05 01:27:44 +0000181 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
Dan Gohmanc7678442007-05-11 20:53:41 +0000182 }
183 }
184
Dan Gohman45b31972008-05-14 00:24:14 +0000185 // Unroll the loop.
Devang Patel98260a42008-07-03 07:04:22 +0000186 Function *F = L->getHeader()->getParent();
Dan Gohman45b31972008-05-14 00:24:14 +0000187 if (!UnrollLoop(L, Count, LI, &LPM))
188 return false;
Dan Gohmanc7678442007-05-11 20:53:41 +0000189
Devang Patel98260a42008-07-03 07:04:22 +0000190 // FIXME: Reconstruct dom info, because it is not preserved properly.
Chris Lattner93779012010-08-29 17:21:35 +0000191 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
Devang Patel98260a42008-07-03 07:04:22 +0000192 DT->runOnFunction(*F);
Chris Lattner83bf2882004-04-18 05:20:17 +0000193 return true;
194}