blob: 25b0877a4f4ca0ffa899bc62dc246f87b4864383 [file] [log] [blame]
Chris Lattner946b2552004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner946b2552004-04-18 05:20:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner946b2552004-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 Lattner946b2552004-04-18 05:20:17 +000013//===----------------------------------------------------------------------===//
14
Chris Lattner946b2552004-04-18 05:20:17 +000015#include "llvm/Transforms/Scalar.h"
Chandler Carruth3b057b32015-02-13 03:57:40 +000016#include "llvm/ADT/SetVector.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000017#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000018#include "llvm/Analysis/CodeMetrics.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000019#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/LoopPass.h"
Dan Gohman0141c132010-07-26 18:11:16 +000021#include "llvm/Analysis/ScalarEvolution.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000022#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Eli Benderskyff903242014-06-16 23:53:02 +000025#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000027#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000029#include "llvm/IR/Metadata.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000032#include "llvm/Support/raw_ostream.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000033#include "llvm/Transforms/Utils/UnrollLoop.h"
Duncan Sands67933e62008-05-16 09:30:00 +000034#include <climits>
Chris Lattner946b2552004-04-18 05:20:17 +000035
Dan Gohman3dc2d922008-05-14 00:24:14 +000036using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000037
Chandler Carruth964daaa2014-04-22 02:55:47 +000038#define DEBUG_TYPE "loop-unroll"
39
Dan Gohmand78c4002008-05-13 00:00:25 +000040static cl::opt<unsigned>
Chandler Carruth9dabd142015-06-05 17:01:43 +000041 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
42 cl::desc("The baseline cost threshold for loop unrolling"));
43
44static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
45 "unroll-percent-dynamic-cost-saved-threshold", cl::init(20), cl::Hidden,
46 cl::desc("The percentage of estimated dynamic cost which must be saved by "
47 "unrolling to allow unrolling up to the max threshold."));
48
49static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
50 "unroll-dynamic-cost-savings-discount", cl::init(2000), cl::Hidden,
51 cl::desc("This is the amount discounted from the total unroll cost when "
52 "the unrolled form has a high dynamic cost savings (triggered by "
53 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
Dan Gohmand78c4002008-05-13 00:00:25 +000054
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000055static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
Chandler Carruth1fbc3162015-02-13 05:31:46 +000056 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000057 cl::desc("Don't allow loop unrolling to simulate more than this number of"
58 "iterations when checking full unroll profitability"));
59
Dan Gohmand78c4002008-05-13 00:00:25 +000060static cl::opt<unsigned>
61UnrollCount("unroll-count", cl::init(0), cl::Hidden,
Eli Benderskyff903242014-06-16 23:53:02 +000062 cl::desc("Use this unroll count for all loops including those with "
63 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +000064
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000065static cl::opt<bool>
66UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
67 cl::desc("Allows loops to be partially unrolled until "
68 "-unroll-threshold loop size is reached."));
69
Andrew Trickd04d15292011-12-09 06:19:40 +000070static cl::opt<bool>
71UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
72 cl::desc("Unroll loops with run-time trip counts"));
73
Eli Benderskyff903242014-06-16 23:53:02 +000074static cl::opt<unsigned>
75PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
Mark Heffernane6b4ba12014-07-23 17:31:37 +000076 cl::desc("Unrolled size limit for loops with an unroll(full) or "
Eli Benderskyff903242014-06-16 23:53:02 +000077 "unroll_count pragma."));
78
Chris Lattner79a42ac2006-12-19 21:40:18 +000079namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000080 class LoopUnroll : public LoopPass {
Chris Lattner946b2552004-04-18 05:20:17 +000081 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000082 static char ID; // Pass ID, replacement for typeid
Hal Finkel081eaef2013-11-05 00:08:03 +000083 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
Chris Lattner35a65b22011-04-14 02:27:25 +000084 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
Chandler Carruth9dabd142015-06-05 17:01:43 +000085 CurrentPercentDynamicCostSavedThreshold =
86 UnrollPercentDynamicCostSavedThreshold;
87 CurrentDynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
Chris Lattner35a65b22011-04-14 02:27:25 +000088 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
Junjie Gu7c3b4592011-04-13 16:15:29 +000089 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
Hal Finkel081eaef2013-11-05 00:08:03 +000090 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
Junjie Gu7c3b4592011-04-13 16:15:29 +000091
92 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
Chandler Carruth9dabd142015-06-05 17:01:43 +000093 UserPercentDynamicCostSavedThreshold =
94 (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0);
95 UserDynamicCostSavingsDiscount =
96 (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000097 UserAllowPartial = (P != -1) ||
98 (UnrollAllowPartial.getNumOccurrences() > 0);
Hal Finkel081eaef2013-11-05 00:08:03 +000099 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +0000100 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
Andrew Trick279e7a62011-07-23 00:29:16 +0000101
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000102 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
103 }
Devang Patel09f162c2007-05-01 21:15:47 +0000104
Dan Gohman2980d9d2007-05-11 20:53:41 +0000105 /// A magic value for use with the Threshold parameter to indicate
106 /// that the loop unroll should be performed regardless of how much
107 /// code expansion would result.
108 static const unsigned NoThreshold = UINT_MAX;
Andrew Trick279e7a62011-07-23 00:29:16 +0000109
Owen Andersona4d9c782010-09-07 23:15:30 +0000110 // Threshold to use when optsize is specified (and there is no
111 // explicit -unroll-threshold).
112 static const unsigned OptSizeUnrollThreshold = 50;
Andrew Trick279e7a62011-07-23 00:29:16 +0000113
Andrew Trickd04d15292011-12-09 06:19:40 +0000114 // Default unroll count for loops with run-time trip count if
115 // -unroll-count is not set
116 static const unsigned UnrollRuntimeCount = 8;
117
Junjie Gu7c3b4592011-04-13 16:15:29 +0000118 unsigned CurrentCount;
Owen Andersona4d9c782010-09-07 23:15:30 +0000119 unsigned CurrentThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000120 unsigned CurrentPercentDynamicCostSavedThreshold;
121 unsigned CurrentDynamicCostSavingsDiscount;
122 bool CurrentAllowPartial;
123 bool CurrentRuntime;
124
125 // Flags for whether the 'current' settings are user-specified.
126 bool UserCount;
127 bool UserThreshold;
128 bool UserPercentDynamicCostSavedThreshold;
129 bool UserDynamicCostSavingsDiscount;
130 bool UserAllowPartial;
131 bool UserRuntime;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000132
Craig Topper3e4c6972014-03-05 09:10:37 +0000133 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner946b2552004-04-18 05:20:17 +0000134
135 /// This transformation requires natural loop information & requires that
136 /// loop preheaders be inserted into the CFG...
137 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000138 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000139 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000140 AU.addRequired<LoopInfoWrapperPass>();
141 AU.addPreserved<LoopInfoWrapperPass>();
Dan Gohman0141c132010-07-26 18:11:16 +0000142 AU.addRequiredID(LoopSimplifyID);
143 AU.addPreservedID(LoopSimplifyID);
144 AU.addRequiredID(LCSSAID);
145 AU.addPreservedID(LCSSAID);
Andrew Trick4d0040b2011-08-10 04:29:49 +0000146 AU.addRequired<ScalarEvolution>();
Chris Lattnerd6f46b82010-08-29 17:21:35 +0000147 AU.addPreserved<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000148 AU.addRequired<TargetTransformInfoWrapperPass>();
Devang Patelf94b9822008-07-03 07:04:22 +0000149 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
150 // If loop unroll does not preserve dom info then LCSSA pass on next
151 // loop will receive invalid dom info.
152 // For now, recreate dom info, if loop is unrolled.
Chandler Carruth73523022014-01-13 13:07:17 +0000153 AU.addPreserved<DominatorTreeWrapperPass>();
Chris Lattner946b2552004-04-18 05:20:17 +0000154 }
Eli Benderskyff903242014-06-16 23:53:02 +0000155
156 // Fill in the UnrollingPreferences parameter with values from the
157 // TargetTransformationInfo.
Chandler Carruth21fc1952015-02-01 14:37:03 +0000158 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
Eli Benderskyff903242014-06-16 23:53:02 +0000159 TargetTransformInfo::UnrollingPreferences &UP) {
160 UP.Threshold = CurrentThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000161 UP.PercentDynamicCostSavedThreshold =
162 CurrentPercentDynamicCostSavedThreshold;
163 UP.DynamicCostSavingsDiscount = CurrentDynamicCostSavingsDiscount;
Eli Benderskyff903242014-06-16 23:53:02 +0000164 UP.OptSizeThreshold = OptSizeUnrollThreshold;
165 UP.PartialThreshold = CurrentThreshold;
166 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
167 UP.Count = CurrentCount;
168 UP.MaxCount = UINT_MAX;
169 UP.Partial = CurrentAllowPartial;
170 UP.Runtime = CurrentRuntime;
Sanjoy Dase178f462015-04-14 03:20:38 +0000171 UP.AllowExpensiveTripCount = false;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000172 TTI.getUnrollingPreferences(L, UP);
Eli Benderskyff903242014-06-16 23:53:02 +0000173 }
174
175 // Select and return an unroll count based on parameters from
176 // user, unroll preferences, unroll pragmas, or a heuristic.
177 // SetExplicitly is set to true if the unroll count is is set by
178 // the user or a pragma rather than selected heuristically.
179 unsigned
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000180 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000181 unsigned PragmaCount,
182 const TargetTransformInfo::UnrollingPreferences &UP,
183 bool &SetExplicitly);
184
Eli Benderskyff903242014-06-16 23:53:02 +0000185 // Select threshold values used to limit unrolling based on a
186 // total unrolled size. Parameters Threshold and PartialThreshold
187 // are set to the maximum unrolled size for fully and partially
188 // unrolled loops respectively.
189 void selectThresholds(const Loop *L, bool HasPragma,
190 const TargetTransformInfo::UnrollingPreferences &UP,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000191 unsigned &Threshold, unsigned &PartialThreshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000192 unsigned &PercentDynamicCostSavedThreshold,
193 unsigned &DynamicCostSavingsDiscount) {
Eli Benderskyff903242014-06-16 23:53:02 +0000194 // Determine the current unrolling threshold. While this is
195 // normally set from UnrollThreshold, it is overridden to a
196 // smaller value if the current function is marked as
197 // optimize-for-size, and the unroll threshold was not user
198 // specified.
199 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
200 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000201 PercentDynamicCostSavedThreshold =
202 UserPercentDynamicCostSavedThreshold
203 ? CurrentPercentDynamicCostSavedThreshold
204 : UP.PercentDynamicCostSavedThreshold;
205 DynamicCostSavingsDiscount = UserDynamicCostSavingsDiscount
206 ? CurrentDynamicCostSavingsDiscount
207 : UP.DynamicCostSavingsDiscount;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000208
Eli Benderskyff903242014-06-16 23:53:02 +0000209 if (!UserThreshold &&
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000210 L->getHeader()->getParent()->hasFnAttribute(
211 Attribute::OptimizeForSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000212 Threshold = UP.OptSizeThreshold;
213 PartialThreshold = UP.PartialOptSizeThreshold;
214 }
215 if (HasPragma) {
216 // If the loop has an unrolling pragma, we want to be more
217 // aggressive with unrolling limits. Set thresholds to at
218 // least the PragmaTheshold value which is larger than the
219 // default limits.
220 if (Threshold != NoThreshold)
221 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
222 if (PartialThreshold != NoThreshold)
223 PartialThreshold =
224 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
225 }
226 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000227 bool canUnrollCompletely(Loop *L, unsigned Threshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000228 unsigned PercentDynamicCostSavedThreshold,
229 unsigned DynamicCostSavingsDiscount,
Sanjoy Dasad714b12015-06-06 05:24:10 +0000230 uint64_t UnrolledCost, uint64_t RolledDynamicCost);
Chris Lattner946b2552004-04-18 05:20:17 +0000231 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000232}
Chris Lattner946b2552004-04-18 05:20:17 +0000233
Dan Gohmand78c4002008-05-13 00:00:25 +0000234char LoopUnroll::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000235INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000236INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000237INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000238INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000239INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
240INITIALIZE_PASS_DEPENDENCY(LCSSA)
Devang Patel88b4fa22011-10-19 23:56:07 +0000241INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000242INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000243
Hal Finkel081eaef2013-11-05 00:08:03 +0000244Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
245 int Runtime) {
246 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
Junjie Gu7c3b4592011-04-13 16:15:29 +0000247}
Chris Lattner946b2552004-04-18 05:20:17 +0000248
Hal Finkel86b30642014-03-31 23:23:51 +0000249Pass *llvm::createSimpleLoopUnrollPass() {
250 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
251}
252
Benjamin Kramer51f6096c2015-03-23 12:30:58 +0000253namespace {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000254// This class is used to get an estimate of the optimization effects that we
255// could get from complete loop unrolling. It comes from the fact that some
256// loads might be replaced with concrete constant values and that could trigger
257// a chain of instruction simplifications.
258//
259// E.g. we might have:
260// int a[] = {0, 1, 0};
261// v = 0;
262// for (i = 0; i < 3; i ++)
263// v += b[i]*a[i];
264// If we completely unroll the loop, we would get:
265// v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
266// Which then will be simplified to:
267// v = b[0]* 0 + b[1]* 1 + b[2]* 0
268// And finally:
269// v = b[1]
Chandler Carruth02156082015-05-22 17:41:35 +0000270class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> {
271 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base;
272 friend class InstVisitor<UnrolledInstAnalyzer, bool>;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000273 struct SimplifiedAddress {
274 Value *Base = nullptr;
275 ConstantInt *Offset = nullptr;
276 };
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000277
Chandler Carruth02156082015-05-22 17:41:35 +0000278public:
279 UnrolledInstAnalyzer(unsigned Iteration,
280 DenseMap<Value *, Constant *> &SimplifiedValues,
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000281 const Loop *L, ScalarEvolution &SE)
282 : Iteration(Iteration), SimplifiedValues(SimplifiedValues), L(L), SE(SE) {
283 IterationNumber = SE.getConstant(APInt(64, Iteration));
284 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000285
Chandler Carruth02156082015-05-22 17:41:35 +0000286 // Allow access to the initial visit method.
287 using Base::visit;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000288
Chandler Carruth02156082015-05-22 17:41:35 +0000289private:
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000290 /// \brief A cache of pointer bases and constant-folded offsets corresponding
291 /// to GEP (or derived from GEP) instructions.
292 ///
293 /// In order to find the base pointer one needs to perform non-trivial
294 /// traversal of the corresponding SCEV expression, so it's good to have the
295 /// results saved.
296 DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses;
297
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000298 /// \brief Number of currently simulated iteration.
299 ///
300 /// If an expression is ConstAddress+Constant, then the Constant is
301 /// Start + Iteration*Step, where Start and Step could be obtained from
Chandler Carruthe1a04622015-05-22 03:02:22 +0000302 /// SCEVGEPCache.
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000303 unsigned Iteration;
304
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000305 /// \brief SCEV expression corresponding to number of currently simulated
306 /// iteration.
307 const SCEV *IterationNumber;
308
309 /// \brief A Value->Constant map for keeping values that we managed to
310 /// constant-fold on the given iteration.
311 ///
312 /// While we walk the loop instructions, we build up and maintain a mapping
313 /// of simplified values specific to this iteration. The idea is to propagate
314 /// any special information we have about loads that can be replaced with
315 /// constants after complete unrolling, and account for likely simplifications
316 /// post-unrolling.
Chandler Carruth02156082015-05-22 17:41:35 +0000317 DenseMap<Value *, Constant *> &SimplifiedValues;
318
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000319 const Loop *L;
320 ScalarEvolution &SE;
321
322 /// \brief Try to simplify instruction \param I using its SCEV expression.
323 ///
324 /// The idea is that some AddRec expressions become constants, which then
325 /// could trigger folding of other instructions. However, that only happens
326 /// for expressions whose start value is also constant, which isn't always the
327 /// case. In another common and important case the start value is just some
328 /// address (i.e. SCEVUnknown) - in this case we compute the offset and save
329 /// it along with the base address instead.
330 bool simplifyInstWithSCEV(Instruction *I) {
331 if (!SE.isSCEVable(I->getType()))
332 return false;
333
334 const SCEV *S = SE.getSCEV(I);
335 if (auto *SC = dyn_cast<SCEVConstant>(S)) {
336 SimplifiedValues[I] = SC->getValue();
337 return true;
338 }
339
340 auto *AR = dyn_cast<SCEVAddRecExpr>(S);
341 if (!AR)
342 return false;
343
344 const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE);
345 // Check if the AddRec expression becomes a constant.
346 if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) {
347 SimplifiedValues[I] = SC->getValue();
348 return true;
349 }
350
351 // Check if the offset from the base address becomes a constant.
352 auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S));
353 if (!Base)
354 return false;
355 auto *Offset =
356 dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base));
357 if (!Offset)
358 return false;
359 SimplifiedAddress Address;
360 Address.Base = Base->getValue();
361 Address.Offset = Offset->getValue();
362 SimplifiedAddresses[I] = Address;
363 return true;
364 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000365
366 /// Base case for the instruction visitor.
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000367 bool visitInstruction(Instruction &I) {
368 return simplifyInstWithSCEV(&I);
369 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000370
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000371 /// Try to simplify binary operator I.
372 ///
373 /// TODO: Probaly it's worth to hoist the code for estimating the
374 /// simplifications effects to a separate class, since we have a very similar
375 /// code in InlineCost already.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000376 bool visitBinaryOperator(BinaryOperator &I) {
377 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
378 if (!isa<Constant>(LHS))
379 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
380 LHS = SimpleLHS;
381 if (!isa<Constant>(RHS))
382 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
383 RHS = SimpleRHS;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000384
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000385 Value *SimpleV = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000386 const DataLayout &DL = I.getModule()->getDataLayout();
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000387 if (auto FI = dyn_cast<FPMathOperator>(&I))
388 SimpleV =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000389 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000390 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000391 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000392
Chandler Carruthf174a152015-05-22 02:47:29 +0000393 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000394 SimplifiedValues[&I] = C;
Chandler Carruthf174a152015-05-22 02:47:29 +0000395
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000396 if (SimpleV)
397 return true;
398 return Base::visitBinaryOperator(I);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000399 }
400
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000401 /// Try to fold load I.
402 bool visitLoad(LoadInst &I) {
403 Value *AddrOp = I.getPointerOperand();
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000404
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000405 auto AddressIt = SimplifiedAddresses.find(AddrOp);
406 if (AddressIt == SimplifiedAddresses.end())
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000407 return false;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000408 ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000409
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000410 auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base);
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000411 // We're only interested in loads that can be completely folded to a
412 // constant.
413 if (!GV || !GV->hasInitializer())
414 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000415
416 ConstantDataSequential *CDS =
417 dyn_cast<ConstantDataSequential>(GV->getInitializer());
418 if (!CDS)
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000419 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000420
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000421 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000422 assert(SimplifiedAddrOp->getValue().getActiveBits() < 64 &&
423 "Unexpectedly large index value.");
424 int64_t Index = SimplifiedAddrOp->getSExtValue() / ElemSize;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000425 if (Index >= CDS->getNumElements()) {
426 // FIXME: For now we conservatively ignore out of bound accesses, but
427 // we're allowed to perform the optimization in this case.
428 return false;
429 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000430
431 Constant *CV = CDS->getElementAsConstant(Index);
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000432 assert(CV && "Constant expected.");
433 SimplifiedValues[&I] = CV;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000434
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000435 return true;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000436 }
Michael Zolotukhin31b3eaa2015-07-15 00:19:51 +0000437
438 bool visitCastInst(CastInst &I) {
439 // Propagate constants through casts.
440 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
441 if (!COp)
442 COp = SimplifiedValues.lookup(I.getOperand(0));
443 if (COp)
444 if (Constant *C =
445 ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
446 SimplifiedValues[&I] = C;
447 return true;
448 }
449
450 return Base::visitCastInst(I);
451 }
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000452
453 bool visitCmpInst(CmpInst &I) {
454 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
455
456 // First try to handle simplified comparisons.
457 if (!isa<Constant>(LHS))
458 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
459 LHS = SimpleLHS;
460 if (!isa<Constant>(RHS))
461 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
462 RHS = SimpleRHS;
463
464 if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) {
465 auto SimplifiedLHS = SimplifiedAddresses.find(LHS);
466 if (SimplifiedLHS != SimplifiedAddresses.end()) {
467 auto SimplifiedRHS = SimplifiedAddresses.find(RHS);
468 if (SimplifiedRHS != SimplifiedAddresses.end()) {
469 SimplifiedAddress &LHSAddr = SimplifiedLHS->second;
470 SimplifiedAddress &RHSAddr = SimplifiedRHS->second;
471 if (LHSAddr.Base == RHSAddr.Base) {
472 LHS = LHSAddr.Offset;
473 RHS = RHSAddr.Offset;
474 }
475 }
476 }
477 }
478
479 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
480 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
481 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
482 SimplifiedValues[&I] = C;
483 return true;
484 }
485 }
486 }
487
488 return Base::visitCmpInst(I);
489 }
Chandler Carruth02156082015-05-22 17:41:35 +0000490};
491} // namespace
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000492
Chandler Carruth6c03dff2015-02-13 04:39:05 +0000493
Chandler Carruth02156082015-05-22 17:41:35 +0000494namespace {
495struct EstimatedUnrollCost {
Chandler Carruth9dabd142015-06-05 17:01:43 +0000496 /// \brief The estimated cost after unrolling.
497 unsigned UnrolledCost;
Chandler Carruth302a1332015-02-13 02:10:56 +0000498
Chandler Carruth9dabd142015-06-05 17:01:43 +0000499 /// \brief The estimated dynamic cost of executing the instructions in the
500 /// rolled form.
501 unsigned RolledDynamicCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000502};
503}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000504
Chandler Carruth02156082015-05-22 17:41:35 +0000505/// \brief Figure out if the loop is worth full unrolling.
506///
507/// Complete loop unrolling can make some loads constant, and we need to know
508/// if that would expose any further optimization opportunities. This routine
Michael Zolotukhinc4e4f332015-06-11 22:17:39 +0000509/// estimates this optimization. It computes cost of unrolled loop
510/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
511/// dynamic cost we mean that we won't count costs of blocks that are known not
512/// to be executed (i.e. if we have a branch in the loop and we know that at the
513/// given iteration its condition would be resolved to true, we won't add up the
514/// cost of the 'false'-block).
515/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
516/// the analysis failed (no benefits expected from the unrolling, or the loop is
517/// too big to analyze), the returned value is None.
Chandler Carruth02156082015-05-22 17:41:35 +0000518Optional<EstimatedUnrollCost>
519analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
520 const TargetTransformInfo &TTI,
521 unsigned MaxUnrolledLoopSize) {
522 // We want to be able to scale offsets by the trip count and add more offsets
523 // to them without checking for overflows, and we already don't want to
524 // analyze *massive* trip counts, so we force the max to be reasonably small.
525 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
526 "The unroll iterations max is too large!");
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000527
Chandler Carruth02156082015-05-22 17:41:35 +0000528 // Don't simulate loops with a big or unknown tripcount
529 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
530 TripCount > UnrollMaxIterationsCountToAnalyze)
531 return None;
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000532
Chandler Carruth02156082015-05-22 17:41:35 +0000533 SmallSetVector<BasicBlock *, 16> BBWorklist;
534 DenseMap<Value *, Constant *> SimplifiedValues;
Chandler Carruth3b057b32015-02-13 03:57:40 +0000535
Chandler Carruth9dabd142015-06-05 17:01:43 +0000536 // The estimated cost of the unrolled form of the loop. We try to estimate
537 // this by simplifying as much as we can while computing the estimate.
538 unsigned UnrolledCost = 0;
539 // We also track the estimated dynamic (that is, actually executed) cost in
540 // the rolled form. This helps identify cases when the savings from unrolling
541 // aren't just exposing dead control flows, but actual reduced dynamic
542 // instructions due to the simplifications which we expect to occur after
543 // unrolling.
544 unsigned RolledDynamicCost = 0;
Chandler Carruth8c863752015-02-13 03:48:38 +0000545
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000546 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
547
Chandler Carruth02156082015-05-22 17:41:35 +0000548 // Simulate execution of each iteration of the loop counting instructions,
549 // which would be simplified.
550 // Since the same load will take different values on different iterations,
551 // we literally have to go through all loop's iterations.
552 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000553 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000554 SimplifiedValues.clear();
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000555 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, L, SE);
Chandler Carruthf174a152015-05-22 02:47:29 +0000556
Chandler Carruth02156082015-05-22 17:41:35 +0000557 BBWorklist.clear();
558 BBWorklist.insert(L->getHeader());
559 // Note that we *must not* cache the size, this loop grows the worklist.
560 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
561 BasicBlock *BB = BBWorklist[Idx];
Chandler Carruthf174a152015-05-22 02:47:29 +0000562
Chandler Carruth02156082015-05-22 17:41:35 +0000563 // Visit all instructions in the given basic block and try to simplify
564 // it. We don't change the actual IR, just count optimization
565 // opportunities.
566 for (Instruction &I : *BB) {
Chandler Carruth9dabd142015-06-05 17:01:43 +0000567 unsigned InstCost = TTI.getUserCost(&I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000568
Chandler Carruth02156082015-05-22 17:41:35 +0000569 // Visit the instruction to analyze its loop cost after unrolling,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000570 // and if the visitor returns false, include this instruction in the
571 // unrolled cost.
572 if (!Analyzer.visit(I))
573 UnrolledCost += InstCost;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000574 else {
575 DEBUG(dbgs() << " " << I
576 << " would be simplified if loop is unrolled.\n");
577 (void)0;
578 }
Chandler Carruth9dabd142015-06-05 17:01:43 +0000579
580 // Also track this instructions expected cost when executing the rolled
581 // loop form.
582 RolledDynamicCost += InstCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000583
584 // If unrolled body turns out to be too big, bail out.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000585 if (UnrolledCost > MaxUnrolledLoopSize) {
586 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n"
587 << " UnrolledCost: " << UnrolledCost
588 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
589 << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000590 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000591 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000592 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000593
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000594 TerminatorInst *TI = BB->getTerminator();
595
596 // Add in the live successors by first checking whether we have terminator
597 // that may be simplified based on the values simplified by this call.
598 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
599 if (BI->isConditional()) {
600 if (Constant *SimpleCond =
601 SimplifiedValues.lookup(BI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000602 BasicBlock *Succ = nullptr;
603 // Just take the first successor if condition is undef
604 if (isa<UndefValue>(SimpleCond))
605 Succ = BI->getSuccessor(0);
606 else
607 Succ = BI->getSuccessor(
608 cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0);
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000609 if (L->contains(Succ))
610 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000611 continue;
612 }
613 }
614 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
615 if (Constant *SimpleCond =
616 SimplifiedValues.lookup(SI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000617 BasicBlock *Succ = nullptr;
618 // Just take the first successor if condition is undef
619 if (isa<UndefValue>(SimpleCond))
620 Succ = SI->getSuccessor(0);
621 else
622 Succ =
623 SI->getSuccessor(cast<ConstantInt>(SimpleCond)->getSExtValue());
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000624 if (L->contains(Succ))
625 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000626 continue;
627 }
628 }
629
Chandler Carruth02156082015-05-22 17:41:35 +0000630 // Add BB's successors to the worklist.
631 for (BasicBlock *Succ : successors(BB))
632 if (L->contains(Succ))
633 BBWorklist.insert(Succ);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000634 }
Chandler Carruth02156082015-05-22 17:41:35 +0000635
636 // If we found no optimization opportunities on the first iteration, we
637 // won't find them on later ones too.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000638 if (UnrolledCost == RolledDynamicCost) {
639 DEBUG(dbgs() << " No opportunities found.. exiting.\n"
640 << " UnrolledCost: " << UnrolledCost << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000641 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000642 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000643 }
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000644 DEBUG(dbgs() << "Analysis finished:\n"
645 << "UnrolledCost: " << UnrolledCost << ", "
646 << "RolledDynamicCost: " << RolledDynamicCost << "\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000647 return {{UnrolledCost, RolledDynamicCost}};
Chandler Carruth02156082015-05-22 17:41:35 +0000648}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000649
Dan Gohman49d08a52007-05-08 15:14:19 +0000650/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000651static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000652 bool &NotDuplicatable,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000653 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000654 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000655 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000656 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000657
Dan Gohman969e83a2009-10-31 14:54:17 +0000658 CodeMetrics Metrics;
Dan Gohman90071072008-06-22 20:18:58 +0000659 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohman969e83a2009-10-31 14:54:17 +0000660 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000661 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000662 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000663 NotDuplicatable = Metrics.notDuplicatable;
Andrew Trick279e7a62011-07-23 00:29:16 +0000664
Owen Anderson62ea1b72010-09-09 19:07:31 +0000665 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000666
Owen Anderson62ea1b72010-09-09 19:07:31 +0000667 // Don't allow an estimate of size zero. This would allows unrolling of loops
668 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000669 // not a problem for code quality. Also, the code using this size may assume
670 // that each loop has at least three instructions (likely a conditional
671 // branch, a comparison feeding that branch, and some kind of loop increment
672 // feeding that comparison instruction).
673 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000674
Owen Anderson62ea1b72010-09-09 19:07:31 +0000675 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000676}
677
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000678// Returns the loop hint metadata node with the given name (for example,
679// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
680// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000681static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
682 if (MDNode *LoopID = L->getLoopID())
683 return GetUnrollMetadata(LoopID, Name);
684 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000685}
686
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000687// Returns true if the loop has an unroll(full) pragma.
688static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000689 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000690}
691
692// Returns true if the loop has an unroll(disable) pragma.
693static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000694 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000695}
696
Kevin Qin715b01e2015-03-09 06:14:18 +0000697// Returns true if the loop has an runtime unroll(disable) pragma.
698static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
699 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
700}
701
Eli Benderskyff903242014-06-16 23:53:02 +0000702// If loop has an unroll_count pragma return the (necessarily
703// positive) value from the pragma. Otherwise return 0.
704static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000705 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000706 if (MD) {
707 assert(MD->getNumOperands() == 2 &&
708 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000709 unsigned Count =
710 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000711 assert(Count >= 1 && "Unroll count must be positive.");
712 return Count;
713 }
714 return 0;
715}
716
Mark Heffernan053a6862014-07-18 21:04:33 +0000717// Remove existing unroll metadata and add unroll disable metadata to
718// indicate the loop has already been unrolled. This prevents a loop
719// from being unrolled more than is directed by a pragma if the loop
720// unrolling pass is run more than once (which it generally is).
721static void SetLoopAlreadyUnrolled(Loop *L) {
722 MDNode *LoopID = L->getLoopID();
723 if (!LoopID) return;
724
725 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000726 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000727 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000728 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000729 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
730 bool IsUnrollMetadata = false;
731 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
732 if (MD) {
733 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
734 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
735 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000736 if (!IsUnrollMetadata)
737 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000738 }
739
740 // Add unroll(disable) metadata to disable future unrolling.
741 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000742 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000743 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000744 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000745 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000746
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000747 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000748 // Set operand 0 to refer to the loop id itself.
749 NewLoopID->replaceOperandWith(0, NewLoopID);
750 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000751}
752
Chandler Carruth9dabd142015-06-05 17:01:43 +0000753bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold,
754 unsigned PercentDynamicCostSavedThreshold,
755 unsigned DynamicCostSavingsDiscount,
Sanjoy Dasad714b12015-06-06 05:24:10 +0000756 uint64_t UnrolledCost,
757 uint64_t RolledDynamicCost) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000758
759 if (Threshold == NoThreshold) {
760 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
761 return true;
762 }
763
Chandler Carruth9dabd142015-06-05 17:01:43 +0000764 if (UnrolledCost <= Threshold) {
765 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
766 << UnrolledCost << "<" << Threshold << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000767 return true;
768 }
769
Chandler Carruth9dabd142015-06-05 17:01:43 +0000770 assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
771 assert(RolledDynamicCost >= UnrolledCost &&
772 "Cannot have a higher unrolled cost than a rolled cost!");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000773
Chandler Carruth9dabd142015-06-05 17:01:43 +0000774 // Compute the percentage of the dynamic cost in the rolled form that is
775 // saved when unrolled. If unrolling dramatically reduces the estimated
776 // dynamic cost of the loop, we use a higher threshold to allow more
777 // unrolling.
778 unsigned PercentDynamicCostSaved =
779 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
780
781 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
782 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
783 (int64_t)Threshold) {
784 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
785 "expected dynamic cost by " << PercentDynamicCostSaved
786 << "% (threshold: " << PercentDynamicCostSavedThreshold
787 << "%)\n"
788 << " and the unrolled cost (" << UnrolledCost
789 << ") is less than the max threshold ("
790 << DynamicCostSavingsDiscount << ").\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000791 return true;
792 }
793
794 DEBUG(dbgs() << " Too large to fully unroll:\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000795 DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
796 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
797 DEBUG(dbgs() << " Percent cost saved threshold: "
798 << PercentDynamicCostSavedThreshold << "%\n");
799 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
800 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
801 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
802 << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000803 return false;
804}
805
Eli Benderskyff903242014-06-16 23:53:02 +0000806unsigned LoopUnroll::selectUnrollCount(
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000807 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000808 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
809 bool &SetExplicitly) {
810 SetExplicitly = true;
811
812 // User-specified count (either as a command-line option or
813 // constructor parameter) has highest precedence.
814 unsigned Count = UserCount ? CurrentCount : 0;
815
816 // If there is no user-specified count, unroll pragmas have the next
817 // highest precendence.
818 if (Count == 0) {
819 if (PragmaCount) {
820 Count = PragmaCount;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000821 } else if (PragmaFullUnroll) {
Eli Benderskyff903242014-06-16 23:53:02 +0000822 Count = TripCount;
823 }
824 }
825
826 if (Count == 0)
827 Count = UP.Count;
828
829 if (Count == 0) {
830 SetExplicitly = false;
831 if (TripCount == 0)
832 // Runtime trip count.
833 Count = UnrollRuntimeCount;
834 else
835 // Conservative heuristic: if we know the trip count, see if we can
836 // completely unroll (subject to the threshold, checked below); otherwise
837 // try to find greatest modulo of the trip count which is still under
838 // threshold value.
839 Count = TripCount;
840 }
841 if (TripCount && Count > TripCount)
842 return TripCount;
843 return Count;
844}
845
Devang Patel9779e562007-03-07 01:38:05 +0000846bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000847 if (skipOptnoneFunction(L))
848 return false;
849
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000850 Function &F = *L->getHeader()->getParent();
851
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000852 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Andrew Trick2b6860f2011-08-11 23:36:16 +0000853 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000854 const TargetTransformInfo &TTI =
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000855 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000856 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000857
Dan Gohman2e1f8042007-05-08 15:19:19 +0000858 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000859 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000860 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000861
862 if (HasUnrollDisablePragma(L)) {
863 return false;
864 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000865 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000866 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000867 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000868
Hal Finkel8f2e7002013-09-11 19:25:43 +0000869 TargetTransformInfo::UnrollingPreferences UP;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000870 getUnrollingPreferences(L, TTI, UP);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000871
Andrew Trick2b6860f2011-08-11 23:36:16 +0000872 // Find trip count and trip multiple if count is not available
873 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000874 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000875 // If there are multiple exiting blocks but one of them is the latch, use the
876 // latch for the trip count estimation. Otherwise insist on a single exiting
877 // block for the trip count estimation.
878 BasicBlock *ExitingBlock = L->getLoopLatch();
879 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
880 ExitingBlock = L->getExitingBlock();
881 if (ExitingBlock) {
882 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
883 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000884 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000885
Eli Benderskyff903242014-06-16 23:53:02 +0000886 // Select an initial unroll count. This may be reduced later based
887 // on size thresholds.
888 bool CountSetExplicitly;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000889 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
890 PragmaCount, UP, CountSetExplicitly);
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000891
Eli Benderskyff903242014-06-16 23:53:02 +0000892 unsigned NumInlineCandidates;
893 bool notDuplicatable;
894 unsigned LoopSize =
Chandler Carruth66b31302015-01-04 12:03:27 +0000895 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000896 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Hal Finkel38dd5902015-01-10 00:30:55 +0000897
898 // When computing the unrolled size, note that the conditional branch on the
899 // backedge and the comparison feeding it are not replicated like the rest of
900 // the loop body (which is why 2 is subtracted).
901 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000902 if (notDuplicatable) {
903 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
904 << " instructions.\n");
905 return false;
906 }
907 if (NumInlineCandidates != 0) {
908 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
909 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000910 }
911
Eli Benderskyff903242014-06-16 23:53:02 +0000912 unsigned Threshold, PartialThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000913 unsigned PercentDynamicCostSavedThreshold;
914 unsigned DynamicCostSavingsDiscount;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000915 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000916 PercentDynamicCostSavedThreshold,
917 DynamicCostSavingsDiscount);
Benjamin Kramer9130cb82014-05-04 19:12:38 +0000918
Eli Benderskyff903242014-06-16 23:53:02 +0000919 // Given Count, TripCount and thresholds determine the type of
920 // unrolling which is to be performed.
921 enum { Full = 0, Partial = 1, Runtime = 2 };
922 int Unrolling;
923 if (TripCount && Count == TripCount) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000924 Unrolling = Partial;
925 // If the loop is really small, we don't need to run an expensive analysis.
Chandler Carruth9dabd142015-06-05 17:01:43 +0000926 if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount,
927 UnrolledSize, UnrolledSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000928 Unrolling = Full;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000929 } else {
930 // The loop isn't that small, but we still can fully unroll it if that
931 // helps to remove a significant number of instructions.
932 // To check that, run additional analysis on the loop.
Chandler Carruth9dabd142015-06-05 17:01:43 +0000933 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
934 L, TripCount, *SE, TTI, Threshold + DynamicCostSavingsDiscount))
935 if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold,
936 DynamicCostSavingsDiscount, Cost->UnrolledCost,
937 Cost->RolledDynamicCost)) {
Chandler Carruth02156082015-05-22 17:41:35 +0000938 Unrolling = Full;
939 }
Dan Gohman2980d9d2007-05-11 20:53:41 +0000940 }
Eli Benderskyff903242014-06-16 23:53:02 +0000941 } else if (TripCount && Count < TripCount) {
942 Unrolling = Partial;
943 } else {
944 Unrolling = Runtime;
945 }
946
947 // Reduce count based on the type of unrolling and the threshold values.
948 unsigned OriginalCount = Count;
Mark Heffernand7ebc242015-07-13 18:26:27 +0000949 bool AllowRuntime =
950 (PragmaCount > 0) || (UserRuntime ? CurrentRuntime : UP.Runtime);
951 // Don't unroll a runtime trip count loop with unroll full pragma.
952 if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
Kevin Qin715b01e2015-03-09 06:14:18 +0000953 AllowRuntime = false;
954 }
Eli Benderskyff903242014-06-16 23:53:02 +0000955 if (Unrolling == Partial) {
956 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
957 if (!AllowPartial && !CountSetExplicitly) {
958 DEBUG(dbgs() << " will not try to unroll partially because "
959 << "-unroll-allow-partial not given\n");
960 return false;
961 }
962 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
963 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Hal Finkel38dd5902015-01-10 00:30:55 +0000964 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
Eli Benderskyff903242014-06-16 23:53:02 +0000965 while (Count != 0 && TripCount % Count != 0)
966 Count--;
967 }
968 } else if (Unrolling == Runtime) {
969 if (!AllowRuntime && !CountSetExplicitly) {
970 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
971 << "-unroll-runtime not given\n");
972 return false;
973 }
974 // Reduce unroll count to be the largest power-of-two factor of
975 // the original count which satisfies the threshold limit.
976 while (Count != 0 && UnrolledSize > PartialThreshold) {
977 Count >>= 1;
Hal Finkel38dd5902015-01-10 00:30:55 +0000978 UnrolledSize = (LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000979 }
980 if (Count > UP.MaxCount)
981 Count = UP.MaxCount;
982 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
983 }
984
985 if (HasPragma) {
Mark Heffernan9e112442014-07-23 20:05:44 +0000986 if (PragmaCount != 0)
987 // If loop has an unroll count pragma mark loop as unrolled to prevent
988 // unrolling beyond that requested by the pragma.
989 SetLoopAlreadyUnrolled(L);
Mark Heffernan053a6862014-07-18 21:04:33 +0000990
Eli Benderskyff903242014-06-16 23:53:02 +0000991 // Emit optimization remarks if we are unable to unroll the loop
992 // as directed by a pragma.
993 DebugLoc LoopLoc = L->getStartLoc();
994 Function *F = Header->getParent();
995 LLVMContext &Ctx = F->getContext();
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000996 if (PragmaFullUnroll && PragmaCount == 0) {
Eli Benderskyff903242014-06-16 23:53:02 +0000997 if (TripCount && Count != TripCount) {
998 emitOptimizationRemarkMissed(
999 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +00001000 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +00001001 "because unrolled size is too large.");
1002 } else if (!TripCount) {
1003 emitOptimizationRemarkMissed(
1004 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +00001005 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +00001006 "because loop has a runtime trip count.");
1007 }
1008 } else if (PragmaCount > 0 && Count != OriginalCount) {
1009 emitOptimizationRemarkMissed(
1010 Ctx, DEBUG_TYPE, *F, LoopLoc,
1011 "Unable to unroll loop the number of times directed by "
1012 "unroll_count pragma because unrolled size is too large.");
1013 }
1014 }
1015
1016 if (Unrolling != Full && Count < 2) {
1017 // Partial unrolling by 1 is a nop. For full unrolling, a factor
1018 // of 1 makes sense because loop control can be eliminated.
1019 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001020 }
1021
Dan Gohman3dc2d922008-05-14 00:24:14 +00001022 // Unroll the loop.
Sanjoy Dase178f462015-04-14 03:20:38 +00001023 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
1024 TripMultiple, LI, this, &LPM, &AC))
Dan Gohman3dc2d922008-05-14 00:24:14 +00001025 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001026
Chris Lattner946b2552004-04-18 05:20:17 +00001027 return true;
1028}