blob: ccafd100ef0f4d036a9da98c5c3718eee14e1e0c [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>
Owen Andersond85c9cc2010-09-10 17:57:00 +000041UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
Dan Gohmand78c4002008-05-13 00:00:25 +000042 cl::desc("The cut-off point for automatic loop unrolling"));
43
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000044static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
Chandler Carruth1fbc3162015-02-13 05:31:46 +000045 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000046 cl::desc("Don't allow loop unrolling to simulate more than this number of"
47 "iterations when checking full unroll profitability"));
48
Michael Zolotukhin7af83c12015-02-06 20:20:40 +000049static cl::opt<unsigned> UnrollMinPercentOfOptimized(
50 "unroll-percent-of-optimized-for-complete-unroll", cl::init(20), cl::Hidden,
51 cl::desc("If complete unrolling could trigger further optimizations, and, "
52 "by that, remove the given percent of instructions, perform the "
53 "complete unroll even if it's beyond the threshold"));
54
55static cl::opt<unsigned> UnrollAbsoluteThreshold(
56 "unroll-absolute-threshold", cl::init(2000), cl::Hidden,
57 cl::desc("Don't unroll if the unrolled size is bigger than this threshold,"
58 " even if we can remove big portion of instructions later."));
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);
Michael Zolotukhin7af83c12015-02-06 20:20:40 +000085 CurrentAbsoluteThreshold = UnrollAbsoluteThreshold;
86 CurrentMinPercentOfOptimized = UnrollMinPercentOfOptimized;
Chris Lattner35a65b22011-04-14 02:27:25 +000087 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
Junjie Gu7c3b4592011-04-13 16:15:29 +000088 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
Hal Finkel081eaef2013-11-05 00:08:03 +000089 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
Junjie Gu7c3b4592011-04-13 16:15:29 +000090
91 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
Michael Zolotukhin7af83c12015-02-06 20:20:40 +000092 UserAbsoluteThreshold = (UnrollAbsoluteThreshold.getNumOccurrences() > 0);
93 UserPercentOfOptimized =
94 (UnrollMinPercentOfOptimized.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000095 UserAllowPartial = (P != -1) ||
96 (UnrollAllowPartial.getNumOccurrences() > 0);
Hal Finkel081eaef2013-11-05 00:08:03 +000097 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000098 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
Andrew Trick279e7a62011-07-23 00:29:16 +000099
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000100 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
101 }
Devang Patel09f162c2007-05-01 21:15:47 +0000102
Dan Gohman2980d9d2007-05-11 20:53:41 +0000103 /// A magic value for use with the Threshold parameter to indicate
104 /// that the loop unroll should be performed regardless of how much
105 /// code expansion would result.
106 static const unsigned NoThreshold = UINT_MAX;
Andrew Trick279e7a62011-07-23 00:29:16 +0000107
Owen Andersona4d9c782010-09-07 23:15:30 +0000108 // Threshold to use when optsize is specified (and there is no
109 // explicit -unroll-threshold).
110 static const unsigned OptSizeUnrollThreshold = 50;
Andrew Trick279e7a62011-07-23 00:29:16 +0000111
Andrew Trickd04d15292011-12-09 06:19:40 +0000112 // Default unroll count for loops with run-time trip count if
113 // -unroll-count is not set
114 static const unsigned UnrollRuntimeCount = 8;
115
Junjie Gu7c3b4592011-04-13 16:15:29 +0000116 unsigned CurrentCount;
Owen Andersona4d9c782010-09-07 23:15:30 +0000117 unsigned CurrentThreshold;
Michael Zolotukhin7af83c12015-02-06 20:20:40 +0000118 unsigned CurrentAbsoluteThreshold;
119 unsigned CurrentMinPercentOfOptimized;
Junjie Gu7c3b4592011-04-13 16:15:29 +0000120 bool CurrentAllowPartial;
Hal Finkel081eaef2013-11-05 00:08:03 +0000121 bool CurrentRuntime;
Hal Finkel8f2e7002013-09-11 19:25:43 +0000122 bool UserCount; // CurrentCount is user-specified.
Junjie Gu7c3b4592011-04-13 16:15:29 +0000123 bool UserThreshold; // CurrentThreshold is user-specified.
Michael Zolotukhin7af83c12015-02-06 20:20:40 +0000124 bool UserAbsoluteThreshold; // CurrentAbsoluteThreshold is
125 // user-specified.
126 bool UserPercentOfOptimized; // CurrentMinPercentOfOptimized is
127 // user-specified.
Hal Finkel8f2e7002013-09-11 19:25:43 +0000128 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
Hal Finkel081eaef2013-11-05 00:08:03 +0000129 bool UserRuntime; // CurrentRuntime is user-specified.
Dan Gohman2980d9d2007-05-11 20:53:41 +0000130
Craig Topper3e4c6972014-03-05 09:10:37 +0000131 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner946b2552004-04-18 05:20:17 +0000132
133 /// This transformation requires natural loop information & requires that
134 /// loop preheaders be inserted into the CFG...
135 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000136 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000137 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000138 AU.addRequired<LoopInfoWrapperPass>();
139 AU.addPreserved<LoopInfoWrapperPass>();
Dan Gohman0141c132010-07-26 18:11:16 +0000140 AU.addRequiredID(LoopSimplifyID);
141 AU.addPreservedID(LoopSimplifyID);
142 AU.addRequiredID(LCSSAID);
143 AU.addPreservedID(LCSSAID);
Andrew Trick4d0040b2011-08-10 04:29:49 +0000144 AU.addRequired<ScalarEvolution>();
Chris Lattnerd6f46b82010-08-29 17:21:35 +0000145 AU.addPreserved<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000146 AU.addRequired<TargetTransformInfoWrapperPass>();
Devang Patelf94b9822008-07-03 07:04:22 +0000147 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
148 // If loop unroll does not preserve dom info then LCSSA pass on next
149 // loop will receive invalid dom info.
150 // For now, recreate dom info, if loop is unrolled.
Chandler Carruth73523022014-01-13 13:07:17 +0000151 AU.addPreserved<DominatorTreeWrapperPass>();
Chris Lattner946b2552004-04-18 05:20:17 +0000152 }
Eli Benderskyff903242014-06-16 23:53:02 +0000153
154 // Fill in the UnrollingPreferences parameter with values from the
155 // TargetTransformationInfo.
Chandler Carruth21fc1952015-02-01 14:37:03 +0000156 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
Eli Benderskyff903242014-06-16 23:53:02 +0000157 TargetTransformInfo::UnrollingPreferences &UP) {
158 UP.Threshold = CurrentThreshold;
Michael Zolotukhin7af83c12015-02-06 20:20:40 +0000159 UP.AbsoluteThreshold = CurrentAbsoluteThreshold;
160 UP.MinPercentOfOptimized = CurrentMinPercentOfOptimized;
Eli Benderskyff903242014-06-16 23:53:02 +0000161 UP.OptSizeThreshold = OptSizeUnrollThreshold;
162 UP.PartialThreshold = CurrentThreshold;
163 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
164 UP.Count = CurrentCount;
165 UP.MaxCount = UINT_MAX;
166 UP.Partial = CurrentAllowPartial;
167 UP.Runtime = CurrentRuntime;
Sanjoy Dase178f462015-04-14 03:20:38 +0000168 UP.AllowExpensiveTripCount = false;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000169 TTI.getUnrollingPreferences(L, UP);
Eli Benderskyff903242014-06-16 23:53:02 +0000170 }
171
172 // Select and return an unroll count based on parameters from
173 // user, unroll preferences, unroll pragmas, or a heuristic.
174 // SetExplicitly is set to true if the unroll count is is set by
175 // the user or a pragma rather than selected heuristically.
176 unsigned
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000177 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000178 unsigned PragmaCount,
179 const TargetTransformInfo::UnrollingPreferences &UP,
180 bool &SetExplicitly);
181
Eli Benderskyff903242014-06-16 23:53:02 +0000182 // Select threshold values used to limit unrolling based on a
183 // total unrolled size. Parameters Threshold and PartialThreshold
184 // are set to the maximum unrolled size for fully and partially
185 // unrolled loops respectively.
186 void selectThresholds(const Loop *L, bool HasPragma,
187 const TargetTransformInfo::UnrollingPreferences &UP,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000188 unsigned &Threshold, unsigned &PartialThreshold,
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000189 unsigned &AbsoluteThreshold,
190 unsigned &PercentOfOptimizedForCompleteUnroll) {
Eli Benderskyff903242014-06-16 23:53:02 +0000191 // Determine the current unrolling threshold. While this is
192 // normally set from UnrollThreshold, it is overridden to a
193 // smaller value if the current function is marked as
194 // optimize-for-size, and the unroll threshold was not user
195 // specified.
196 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
197 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000198 AbsoluteThreshold = UserAbsoluteThreshold ? CurrentAbsoluteThreshold
199 : UP.AbsoluteThreshold;
200 PercentOfOptimizedForCompleteUnroll = UserPercentOfOptimized
201 ? CurrentMinPercentOfOptimized
202 : UP.MinPercentOfOptimized;
203
Eli Benderskyff903242014-06-16 23:53:02 +0000204 if (!UserThreshold &&
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000205 L->getHeader()->getParent()->hasFnAttribute(
206 Attribute::OptimizeForSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000207 Threshold = UP.OptSizeThreshold;
208 PartialThreshold = UP.PartialOptSizeThreshold;
209 }
210 if (HasPragma) {
211 // If the loop has an unrolling pragma, we want to be more
212 // aggressive with unrolling limits. Set thresholds to at
213 // least the PragmaTheshold value which is larger than the
214 // default limits.
215 if (Threshold != NoThreshold)
216 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
217 if (PartialThreshold != NoThreshold)
218 PartialThreshold =
219 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
220 }
221 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000222 bool canUnrollCompletely(Loop *L, unsigned Threshold,
223 unsigned AbsoluteThreshold, uint64_t UnrolledSize,
224 unsigned NumberOfOptimizedInstructions,
225 unsigned PercentOfOptimizedForCompleteUnroll);
Chris Lattner946b2552004-04-18 05:20:17 +0000226 };
Chris Lattner946b2552004-04-18 05:20:17 +0000227}
228
Dan Gohmand78c4002008-05-13 00:00:25 +0000229char LoopUnroll::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000230INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000231INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000232INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000233INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000234INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
235INITIALIZE_PASS_DEPENDENCY(LCSSA)
Devang Patel88b4fa22011-10-19 23:56:07 +0000236INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000237INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000238
Hal Finkel081eaef2013-11-05 00:08:03 +0000239Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
240 int Runtime) {
241 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
Junjie Gu7c3b4592011-04-13 16:15:29 +0000242}
Chris Lattner946b2552004-04-18 05:20:17 +0000243
Hal Finkel86b30642014-03-31 23:23:51 +0000244Pass *llvm::createSimpleLoopUnrollPass() {
245 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
246}
247
Benjamin Kramer51f6096c2015-03-23 12:30:58 +0000248namespace {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000249/// \brief SCEV expressions visitor used for finding expressions that would
250/// become constants if the loop L is unrolled.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000251struct FindConstantPointers {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000252 /// \brief Shows whether the expression is ConstAddress+Constant or not.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000253 bool IndexIsConstant;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000254
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000255 /// \brief Used for filtering out SCEV expressions with two or more AddRec
256 /// subexpressions.
257 ///
258 /// Used to filter out complicated SCEV expressions, having several AddRec
259 /// sub-expressions. We don't handle them, because unrolling one loop
260 /// would help to replace only one of these inductions with a constant, and
261 /// consequently, the expression would remain non-constant.
262 bool HaveSeenAR;
263
264 /// \brief If the SCEV expression becomes ConstAddress+Constant, this value
265 /// holds ConstAddress. Otherwise, it's nullptr.
266 Value *BaseAddress;
267
268 /// \brief The loop, which we try to completely unroll.
269 const Loop *L;
270
271 ScalarEvolution &SE;
272
273 FindConstantPointers(const Loop *L, ScalarEvolution &SE)
274 : IndexIsConstant(true), HaveSeenAR(false), BaseAddress(nullptr),
275 L(L), SE(SE) {}
276
277 /// Examine the given expression S and figure out, if it can be a part of an
278 /// expression, that could become a constant after the loop is unrolled.
279 /// The routine sets IndexIsConstant and HaveSeenAR according to the analysis
280 /// results.
281 /// \returns true if we need to examine subexpressions, and false otherwise.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000282 bool follow(const SCEV *S) {
283 if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) {
284 // We've reached the leaf node of SCEV, it's most probably just a
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000285 // variable.
286 // If it's the only one SCEV-subexpression, then it might be a base
287 // address of an index expression.
288 // If we've already recorded base address, then just give up on this SCEV
289 // - it's too complicated.
290 if (BaseAddress) {
291 IndexIsConstant = false;
292 return false;
293 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000294 BaseAddress = SC->getValue();
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000295 return false;
296 }
297 if (isa<SCEVConstant>(S))
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000298 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000299 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
300 // If the current SCEV expression is AddRec, and its loop isn't the loop
301 // we are about to unroll, then we won't get a constant address after
302 // unrolling, and thus, won't be able to eliminate the load.
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000303 if (AR->getLoop() != L) {
304 IndexIsConstant = false;
305 return false;
306 }
307 // We don't handle multiple AddRecs here, so give up in this case.
308 if (HaveSeenAR) {
309 IndexIsConstant = false;
310 return false;
311 }
312 HaveSeenAR = true;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000313 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000314
315 // Continue traversal.
316 return true;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000317 }
318 bool isDone() const { return !IndexIsConstant; }
319};
Chandler Carruthe1a04622015-05-22 03:02:22 +0000320} // End anonymous namespace.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000321
Chandler Carruthe1a04622015-05-22 03:02:22 +0000322namespace {
Chandler Carruth04cc6652015-05-25 01:00:46 +0000323/// \brief A cache of SCEV results used to optimize repeated queries to SCEV on
324/// the same set of instructions.
325///
326/// The primary cost this saves is the cost of checking the validity of a SCEV
327/// every time it is looked up. However, in some cases we can provide a reduced
328/// and especially useful model for an instruction based upon SCEV that is
329/// non-trivial to compute but more useful to clients.
330class SCEVCache {
331public:
332 /// \brief Struct to represent a GEP whose start and step are known fixed
333 /// offsets from a base address due to SCEV's analysis.
334 struct GEPDescriptor {
335 Value *BaseAddr = nullptr;
336 unsigned Start = 0;
337 unsigned Step = 0;
338 };
339
340 Optional<GEPDescriptor> getGEPDescriptor(GetElementPtrInst *GEP);
341
342 SCEVCache(const Loop &L, ScalarEvolution &SE) : L(L), SE(SE) {}
343
344private:
345 const Loop &L;
346 ScalarEvolution &SE;
347
348 SmallDenseMap<GetElementPtrInst *, GEPDescriptor> GEPDescriptors;
Chandler Carruthe1a04622015-05-22 03:02:22 +0000349};
350} // End anonymous namespace.
351
Chandler Carruth04cc6652015-05-25 01:00:46 +0000352/// \brief Get a simplified descriptor for a GEP instruction.
Chandler Carruthe1a04622015-05-22 03:02:22 +0000353///
Chandler Carruth04cc6652015-05-25 01:00:46 +0000354/// Where possible, this produces a simplified descriptor for a GEP instruction
355/// using SCEV analysis of the containing loop. If this isn't possible, it
356/// returns an empty optional.
357///
358/// The model is a base address, an initial offset, and a per-iteration step.
359/// This fits very common patterns of GEPs inside loops and is something we can
360/// use to simulate the behavior of a particular iteration of a loop.
361///
362/// This is a cached interface. The first call may do non-trivial work to
363/// compute the result, but all subsequent calls will return a fast answer
364/// based on a cached result. This includes caching negative results.
365Optional<SCEVCache::GEPDescriptor>
366SCEVCache::getGEPDescriptor(GetElementPtrInst *GEP) {
367 decltype(GEPDescriptors)::iterator It;
368 bool Inserted;
Chandler Carruthe1a04622015-05-22 03:02:22 +0000369
Chandler Carruth04cc6652015-05-25 01:00:46 +0000370 std::tie(It, Inserted) = GEPDescriptors.insert({GEP, {}});
Chandler Carruth51895592015-05-22 03:07:28 +0000371
Chandler Carruth04cc6652015-05-25 01:00:46 +0000372 if (!Inserted) {
373 if (!It->second.BaseAddr)
374 return None;
Chandler Carruth51895592015-05-22 03:07:28 +0000375
Chandler Carruth04cc6652015-05-25 01:00:46 +0000376 return It->second;
Chandler Carruthe1a04622015-05-22 03:02:22 +0000377 }
378
Chandler Carruth04cc6652015-05-25 01:00:46 +0000379 // We've inserted a new record into the cache, so compute the GEP descriptor
380 // if possible.
381 Value *V = cast<Value>(GEP);
382 if (!SE.isSCEVable(V->getType()))
383 return None;
384 const SCEV *S = SE.getSCEV(V);
385
386 // FIXME: It'd be nice if the worklist and set used by the
387 // SCEVTraversal could be re-used between loop iterations, but the
388 // interface doesn't support that. There is no way to clear the visited
389 // sets between uses.
390 FindConstantPointers Visitor(&L, SE);
391 SCEVTraversal<FindConstantPointers> T(Visitor);
392
393 // Try to find (BaseAddress+Step+Offset) tuple.
394 // If succeeded, save it to the cache - it might help in folding
395 // loads.
396 T.visitAll(S);
397 if (!Visitor.IndexIsConstant || !Visitor.BaseAddress)
398 return None;
399
400 const SCEV *BaseAddrSE = SE.getSCEV(Visitor.BaseAddress);
401 if (BaseAddrSE->getType() != S->getType())
402 return None;
403 const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);
404 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);
405
406 if (!AR)
407 return None;
408
409 const SCEVConstant *StepSE =
410 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE));
411 const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart());
412 if (!StepSE || !StartSE)
413 return None;
414
415 // Check and skip caching if doing so would require lots of bits to
416 // avoid overflow.
417 APInt Start = StartSE->getValue()->getValue();
418 APInt Step = StepSE->getValue()->getValue();
419 if (Start.getActiveBits() > 32 || Step.getActiveBits() > 32)
420 return None;
421
422 // We found a cacheable SCEV model for the GEP.
423 It->second.BaseAddr = Visitor.BaseAddress;
424 It->second.Start = Start.getLimitedValue();
425 It->second.Step = Step.getLimitedValue();
426 return It->second;
Chandler Carruthe1a04622015-05-22 03:02:22 +0000427}
428
429namespace {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000430// This class is used to get an estimate of the optimization effects that we
431// could get from complete loop unrolling. It comes from the fact that some
432// loads might be replaced with concrete constant values and that could trigger
433// a chain of instruction simplifications.
434//
435// E.g. we might have:
436// int a[] = {0, 1, 0};
437// v = 0;
438// for (i = 0; i < 3; i ++)
439// v += b[i]*a[i];
440// If we completely unroll the loop, we would get:
441// v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
442// Which then will be simplified to:
443// v = b[0]* 0 + b[1]* 1 + b[2]* 0
444// And finally:
445// v = b[1]
Chandler Carruth02156082015-05-22 17:41:35 +0000446class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> {
447 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base;
448 friend class InstVisitor<UnrolledInstAnalyzer, bool>;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000449
Chandler Carruth02156082015-05-22 17:41:35 +0000450public:
451 UnrolledInstAnalyzer(unsigned Iteration,
452 DenseMap<Value *, Constant *> &SimplifiedValues,
Chandler Carruth04cc6652015-05-25 01:00:46 +0000453 SCEVCache &SC)
454 : Iteration(Iteration), SimplifiedValues(SimplifiedValues), SC(SC) {}
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000455
Chandler Carruth02156082015-05-22 17:41:35 +0000456 // Allow access to the initial visit method.
457 using Base::visit;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000458
Chandler Carruth02156082015-05-22 17:41:35 +0000459private:
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000460 /// \brief Number of currently simulated iteration.
461 ///
462 /// If an expression is ConstAddress+Constant, then the Constant is
463 /// Start + Iteration*Step, where Start and Step could be obtained from
Chandler Carruthe1a04622015-05-22 03:02:22 +0000464 /// SCEVGEPCache.
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000465 unsigned Iteration;
466
Chandler Carruth02156082015-05-22 17:41:35 +0000467 // While we walk the loop instructions, we we build up and maintain a mapping
468 // of simplified values specific to this iteration. The idea is to propagate
469 // any special information we have about loads that can be replaced with
470 // constants after complete unrolling, and account for likely simplifications
471 // post-unrolling.
472 DenseMap<Value *, Constant *> &SimplifiedValues;
473
Chandler Carruth04cc6652015-05-25 01:00:46 +0000474 // We use a cache to wrap all our SCEV queries.
475 SCEVCache &SC;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000476
477 /// Base case for the instruction visitor.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000478 bool visitInstruction(Instruction &I) { return false; };
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000479
480 /// TODO: Add visitors for other instruction types, e.g. ZExt, SExt.
481
482 /// Try to simplify binary operator I.
483 ///
484 /// TODO: Probaly it's worth to hoist the code for estimating the
485 /// simplifications effects to a separate class, since we have a very similar
486 /// code in InlineCost already.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000487 bool visitBinaryOperator(BinaryOperator &I) {
488 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
489 if (!isa<Constant>(LHS))
490 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
491 LHS = SimpleLHS;
492 if (!isa<Constant>(RHS))
493 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
494 RHS = SimpleRHS;
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000495 Value *SimpleV = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000496 const DataLayout &DL = I.getModule()->getDataLayout();
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000497 if (auto FI = dyn_cast<FPMathOperator>(&I))
498 SimpleV =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000499 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000500 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000501 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000502
Chandler Carruthf174a152015-05-22 02:47:29 +0000503 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000504 SimplifiedValues[&I] = C;
Chandler Carruthf174a152015-05-22 02:47:29 +0000505
506 return SimpleV;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000507 }
508
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000509 /// Try to fold load I.
510 bool visitLoad(LoadInst &I) {
511 Value *AddrOp = I.getPointerOperand();
512 if (!isa<Constant>(AddrOp))
513 if (Constant *SimplifiedAddrOp = SimplifiedValues.lookup(AddrOp))
514 AddrOp = SimplifiedAddrOp;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000515
Chandler Carruth04cc6652015-05-25 01:00:46 +0000516 auto *GEP = dyn_cast<GetElementPtrInst>(AddrOp);
517 if (!GEP)
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000518 return false;
Chandler Carruth04cc6652015-05-25 01:00:46 +0000519 auto OptionalGEPDesc = SC.getGEPDescriptor(GEP);
520 if (!OptionalGEPDesc)
521 return false;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000522
Chandler Carruth04cc6652015-05-25 01:00:46 +0000523 auto GV = dyn_cast<GlobalVariable>(OptionalGEPDesc->BaseAddr);
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000524 // We're only interested in loads that can be completely folded to a
525 // constant.
526 if (!GV || !GV->hasInitializer())
527 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000528
529 ConstantDataSequential *CDS =
530 dyn_cast<ConstantDataSequential>(GV->getInitializer());
531 if (!CDS)
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000532 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000533
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000534 // This calculation should never overflow because we bound Iteration quite
535 // low and both the start and step are 32-bit integers. We use signed
536 // integers so that UBSan will catch if a bug sneaks into the code.
537 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
Chandler Carruth04cc6652015-05-25 01:00:46 +0000538 int64_t Index = ((int64_t)OptionalGEPDesc->Start +
539 (int64_t)OptionalGEPDesc->Step * (int64_t)Iteration) /
540 ElemSize;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000541 if (Index >= CDS->getNumElements()) {
542 // FIXME: For now we conservatively ignore out of bound accesses, but
543 // we're allowed to perform the optimization in this case.
544 return false;
545 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000546
547 Constant *CV = CDS->getElementAsConstant(Index);
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000548 assert(CV && "Constant expected.");
549 SimplifiedValues[&I] = CV;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000550
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000551 return true;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000552 }
Chandler Carruth02156082015-05-22 17:41:35 +0000553};
554} // namespace
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000555
Chandler Carruth6c03dff2015-02-13 04:39:05 +0000556
Chandler Carruth02156082015-05-22 17:41:35 +0000557namespace {
558struct EstimatedUnrollCost {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000559 /// \brief Count the number of optimized instructions.
560 unsigned NumberOfOptimizedInstructions;
Chandler Carruth302a1332015-02-13 02:10:56 +0000561
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000562 /// \brief Count the total number of instructions.
563 unsigned UnrolledLoopSize;
Chandler Carruth02156082015-05-22 17:41:35 +0000564};
565}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000566
Chandler Carruth02156082015-05-22 17:41:35 +0000567/// \brief Figure out if the loop is worth full unrolling.
568///
569/// Complete loop unrolling can make some loads constant, and we need to know
570/// if that would expose any further optimization opportunities. This routine
571/// estimates this optimization. It assigns computed number of instructions,
572/// that potentially might be optimized away, to
573/// NumberOfOptimizedInstructions, and total number of instructions to
574/// UnrolledLoopSize (not counting blocks that won't be reached, if we were
575/// able to compute the condition).
576/// \returns false if we can't analyze the loop, or if we discovered that
577/// unrolling won't give anything. Otherwise, returns true.
578Optional<EstimatedUnrollCost>
579analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
580 const TargetTransformInfo &TTI,
581 unsigned MaxUnrolledLoopSize) {
582 // We want to be able to scale offsets by the trip count and add more offsets
583 // to them without checking for overflows, and we already don't want to
584 // analyze *massive* trip counts, so we force the max to be reasonably small.
585 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
586 "The unroll iterations max is too large!");
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000587
Chandler Carruth02156082015-05-22 17:41:35 +0000588 // Don't simulate loops with a big or unknown tripcount
589 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
590 TripCount > UnrollMaxIterationsCountToAnalyze)
591 return None;
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000592
Chandler Carruth02156082015-05-22 17:41:35 +0000593 SmallSetVector<BasicBlock *, 16> BBWorklist;
594 DenseMap<Value *, Constant *> SimplifiedValues;
Chandler Carruth3b057b32015-02-13 03:57:40 +0000595
Chandler Carruth04cc6652015-05-25 01:00:46 +0000596 // Use a cache to access SCEV expressions so that we don't pay the cost on
597 // each iteration. This cache is lazily self-populating.
598 SCEVCache SC(*L, SE);
599
Chandler Carruth02156082015-05-22 17:41:35 +0000600 unsigned NumberOfOptimizedInstructions = 0;
601 unsigned UnrolledLoopSize = 0;
Chandler Carruth8c863752015-02-13 03:48:38 +0000602
Chandler Carruth02156082015-05-22 17:41:35 +0000603 // Simulate execution of each iteration of the loop counting instructions,
604 // which would be simplified.
605 // Since the same load will take different values on different iterations,
606 // we literally have to go through all loop's iterations.
607 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
608 SimplifiedValues.clear();
Chandler Carruth04cc6652015-05-25 01:00:46 +0000609 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SC);
Chandler Carruthf174a152015-05-22 02:47:29 +0000610
Chandler Carruth02156082015-05-22 17:41:35 +0000611 BBWorklist.clear();
612 BBWorklist.insert(L->getHeader());
613 // Note that we *must not* cache the size, this loop grows the worklist.
614 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
615 BasicBlock *BB = BBWorklist[Idx];
Chandler Carruthf174a152015-05-22 02:47:29 +0000616
Chandler Carruth02156082015-05-22 17:41:35 +0000617 // Visit all instructions in the given basic block and try to simplify
618 // it. We don't change the actual IR, just count optimization
619 // opportunities.
620 for (Instruction &I : *BB) {
621 UnrolledLoopSize += TTI.getUserCost(&I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000622
Chandler Carruth02156082015-05-22 17:41:35 +0000623 // Visit the instruction to analyze its loop cost after unrolling,
624 // and if the visitor returns true, then we can optimize this
625 // instruction away.
626 if (Analyzer.visit(I))
627 NumberOfOptimizedInstructions += TTI.getUserCost(&I);
628
629 // If unrolled body turns out to be too big, bail out.
630 if (UnrolledLoopSize - NumberOfOptimizedInstructions >
631 MaxUnrolledLoopSize)
632 return None;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000633 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000634
Chandler Carruth02156082015-05-22 17:41:35 +0000635 // Add BB's successors to the worklist.
636 for (BasicBlock *Succ : successors(BB))
637 if (L->contains(Succ))
638 BBWorklist.insert(Succ);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000639 }
Chandler Carruth02156082015-05-22 17:41:35 +0000640
641 // If we found no optimization opportunities on the first iteration, we
642 // won't find them on later ones too.
643 if (!NumberOfOptimizedInstructions)
644 return None;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000645 }
Chandler Carruth02156082015-05-22 17:41:35 +0000646 return {{NumberOfOptimizedInstructions, UnrolledLoopSize}};
647}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000648
Dan Gohman49d08a52007-05-08 15:14:19 +0000649/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000650static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000651 bool &NotDuplicatable,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000652 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000653 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000654 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000655 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000656
Dan Gohman969e83a2009-10-31 14:54:17 +0000657 CodeMetrics Metrics;
Dan Gohman90071072008-06-22 20:18:58 +0000658 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohman969e83a2009-10-31 14:54:17 +0000659 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000660 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000661 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000662 NotDuplicatable = Metrics.notDuplicatable;
Andrew Trick279e7a62011-07-23 00:29:16 +0000663
Owen Anderson62ea1b72010-09-09 19:07:31 +0000664 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000665
Owen Anderson62ea1b72010-09-09 19:07:31 +0000666 // Don't allow an estimate of size zero. This would allows unrolling of loops
667 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000668 // not a problem for code quality. Also, the code using this size may assume
669 // that each loop has at least three instructions (likely a conditional
670 // branch, a comparison feeding that branch, and some kind of loop increment
671 // feeding that comparison instruction).
672 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000673
Owen Anderson62ea1b72010-09-09 19:07:31 +0000674 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000675}
676
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000677// Returns the loop hint metadata node with the given name (for example,
678// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
679// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000680static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
681 if (MDNode *LoopID = L->getLoopID())
682 return GetUnrollMetadata(LoopID, Name);
683 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000684}
685
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000686// Returns true if the loop has an unroll(full) pragma.
687static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000688 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000689}
690
691// Returns true if the loop has an unroll(disable) pragma.
692static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000693 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000694}
695
Kevin Qin715b01e2015-03-09 06:14:18 +0000696// Returns true if the loop has an runtime unroll(disable) pragma.
697static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
698 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
699}
700
Eli Benderskyff903242014-06-16 23:53:02 +0000701// If loop has an unroll_count pragma return the (necessarily
702// positive) value from the pragma. Otherwise return 0.
703static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000704 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000705 if (MD) {
706 assert(MD->getNumOperands() == 2 &&
707 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000708 unsigned Count =
709 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000710 assert(Count >= 1 && "Unroll count must be positive.");
711 return Count;
712 }
713 return 0;
714}
715
Mark Heffernan053a6862014-07-18 21:04:33 +0000716// Remove existing unroll metadata and add unroll disable metadata to
717// indicate the loop has already been unrolled. This prevents a loop
718// from being unrolled more than is directed by a pragma if the loop
719// unrolling pass is run more than once (which it generally is).
720static void SetLoopAlreadyUnrolled(Loop *L) {
721 MDNode *LoopID = L->getLoopID();
722 if (!LoopID) return;
723
724 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000725 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000726 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000727 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000728 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
729 bool IsUnrollMetadata = false;
730 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
731 if (MD) {
732 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
733 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
734 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000735 if (!IsUnrollMetadata)
736 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000737 }
738
739 // Add unroll(disable) metadata to disable future unrolling.
740 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000741 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000742 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000743 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000744 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000745
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000746 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000747 // Set operand 0 to refer to the loop id itself.
748 NewLoopID->replaceOperandWith(0, NewLoopID);
749 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000750}
751
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000752bool LoopUnroll::canUnrollCompletely(
753 Loop *L, unsigned Threshold, unsigned AbsoluteThreshold,
754 uint64_t UnrolledSize, unsigned NumberOfOptimizedInstructions,
755 unsigned PercentOfOptimizedForCompleteUnroll) {
756
757 if (Threshold == NoThreshold) {
758 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
759 return true;
760 }
761
762 if (UnrolledSize <= Threshold) {
763 DEBUG(dbgs() << " Can fully unroll, because unrolled size: "
764 << UnrolledSize << "<" << Threshold << "\n");
765 return true;
766 }
767
768 assert(UnrolledSize && "UnrolledSize can't be 0 at this point.");
769 unsigned PercentOfOptimizedInstructions =
770 (uint64_t)NumberOfOptimizedInstructions * 100ull / UnrolledSize;
771
772 if (UnrolledSize <= AbsoluteThreshold &&
773 PercentOfOptimizedInstructions >= PercentOfOptimizedForCompleteUnroll) {
774 DEBUG(dbgs() << " Can fully unroll, because unrolling will help removing "
775 << PercentOfOptimizedInstructions
776 << "% instructions (threshold: "
777 << PercentOfOptimizedForCompleteUnroll << "%)\n");
778 DEBUG(dbgs() << " Unrolled size (" << UnrolledSize
779 << ") is less than the threshold (" << AbsoluteThreshold
780 << ").\n");
781 return true;
782 }
783
784 DEBUG(dbgs() << " Too large to fully unroll:\n");
785 DEBUG(dbgs() << " Unrolled size: " << UnrolledSize << "\n");
786 DEBUG(dbgs() << " Estimated number of optimized instructions: "
787 << NumberOfOptimizedInstructions << "\n");
788 DEBUG(dbgs() << " Absolute threshold: " << AbsoluteThreshold << "\n");
789 DEBUG(dbgs() << " Minimum percent of removed instructions: "
790 << PercentOfOptimizedForCompleteUnroll << "\n");
791 DEBUG(dbgs() << " Threshold for small loops: " << Threshold << "\n");
792 return false;
793}
794
Eli Benderskyff903242014-06-16 23:53:02 +0000795unsigned LoopUnroll::selectUnrollCount(
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000796 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000797 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
798 bool &SetExplicitly) {
799 SetExplicitly = true;
800
801 // User-specified count (either as a command-line option or
802 // constructor parameter) has highest precedence.
803 unsigned Count = UserCount ? CurrentCount : 0;
804
805 // If there is no user-specified count, unroll pragmas have the next
806 // highest precendence.
807 if (Count == 0) {
808 if (PragmaCount) {
809 Count = PragmaCount;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000810 } else if (PragmaFullUnroll) {
Eli Benderskyff903242014-06-16 23:53:02 +0000811 Count = TripCount;
812 }
813 }
814
815 if (Count == 0)
816 Count = UP.Count;
817
818 if (Count == 0) {
819 SetExplicitly = false;
820 if (TripCount == 0)
821 // Runtime trip count.
822 Count = UnrollRuntimeCount;
823 else
824 // Conservative heuristic: if we know the trip count, see if we can
825 // completely unroll (subject to the threshold, checked below); otherwise
826 // try to find greatest modulo of the trip count which is still under
827 // threshold value.
828 Count = TripCount;
829 }
830 if (TripCount && Count > TripCount)
831 return TripCount;
832 return Count;
833}
834
Devang Patel9779e562007-03-07 01:38:05 +0000835bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000836 if (skipOptnoneFunction(L))
837 return false;
838
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000839 Function &F = *L->getHeader()->getParent();
840
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000841 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Andrew Trick2b6860f2011-08-11 23:36:16 +0000842 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000843 const TargetTransformInfo &TTI =
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000844 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000845 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000846
Dan Gohman2e1f8042007-05-08 15:19:19 +0000847 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000848 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000849 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000850
851 if (HasUnrollDisablePragma(L)) {
852 return false;
853 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000854 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000855 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000856 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000857
Hal Finkel8f2e7002013-09-11 19:25:43 +0000858 TargetTransformInfo::UnrollingPreferences UP;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000859 getUnrollingPreferences(L, TTI, UP);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000860
Andrew Trick2b6860f2011-08-11 23:36:16 +0000861 // Find trip count and trip multiple if count is not available
862 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000863 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000864 // If there are multiple exiting blocks but one of them is the latch, use the
865 // latch for the trip count estimation. Otherwise insist on a single exiting
866 // block for the trip count estimation.
867 BasicBlock *ExitingBlock = L->getLoopLatch();
868 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
869 ExitingBlock = L->getExitingBlock();
870 if (ExitingBlock) {
871 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
872 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000873 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000874
Eli Benderskyff903242014-06-16 23:53:02 +0000875 // Select an initial unroll count. This may be reduced later based
876 // on size thresholds.
877 bool CountSetExplicitly;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000878 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
879 PragmaCount, UP, CountSetExplicitly);
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000880
Eli Benderskyff903242014-06-16 23:53:02 +0000881 unsigned NumInlineCandidates;
882 bool notDuplicatable;
883 unsigned LoopSize =
Chandler Carruth66b31302015-01-04 12:03:27 +0000884 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000885 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Hal Finkel38dd5902015-01-10 00:30:55 +0000886
887 // When computing the unrolled size, note that the conditional branch on the
888 // backedge and the comparison feeding it are not replicated like the rest of
889 // the loop body (which is why 2 is subtracted).
890 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000891 if (notDuplicatable) {
892 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
893 << " instructions.\n");
894 return false;
895 }
896 if (NumInlineCandidates != 0) {
897 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
898 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000899 }
900
Eli Benderskyff903242014-06-16 23:53:02 +0000901 unsigned Threshold, PartialThreshold;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000902 unsigned AbsoluteThreshold, PercentOfOptimizedForCompleteUnroll;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000903 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000904 AbsoluteThreshold, PercentOfOptimizedForCompleteUnroll);
Benjamin Kramer9130cb82014-05-04 19:12:38 +0000905
Eli Benderskyff903242014-06-16 23:53:02 +0000906 // Given Count, TripCount and thresholds determine the type of
907 // unrolling which is to be performed.
908 enum { Full = 0, Partial = 1, Runtime = 2 };
909 int Unrolling;
910 if (TripCount && Count == TripCount) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000911 Unrolling = Partial;
912 // If the loop is really small, we don't need to run an expensive analysis.
913 if (canUnrollCompletely(
914 L, Threshold, AbsoluteThreshold,
915 UnrolledSize, 0, 100)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000916 Unrolling = Full;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000917 } else {
918 // The loop isn't that small, but we still can fully unroll it if that
919 // helps to remove a significant number of instructions.
920 // To check that, run additional analysis on the loop.
Chandler Carruth02156082015-05-22 17:41:35 +0000921 if (Optional<EstimatedUnrollCost> Cost =
922 analyzeLoopUnrollCost(L, TripCount, *SE, TTI, AbsoluteThreshold))
923 if (canUnrollCompletely(L, Threshold, AbsoluteThreshold,
924 Cost->UnrolledLoopSize,
925 Cost->NumberOfOptimizedInstructions,
926 PercentOfOptimizedForCompleteUnroll)) {
927 Unrolling = Full;
928 }
Dan Gohman2980d9d2007-05-11 20:53:41 +0000929 }
Eli Benderskyff903242014-06-16 23:53:02 +0000930 } else if (TripCount && Count < TripCount) {
931 Unrolling = Partial;
932 } else {
933 Unrolling = Runtime;
934 }
935
936 // Reduce count based on the type of unrolling and the threshold values.
937 unsigned OriginalCount = Count;
938 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
Kevin Qin715b01e2015-03-09 06:14:18 +0000939 if (HasRuntimeUnrollDisablePragma(L)) {
940 AllowRuntime = false;
941 }
Eli Benderskyff903242014-06-16 23:53:02 +0000942 if (Unrolling == Partial) {
943 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
944 if (!AllowPartial && !CountSetExplicitly) {
945 DEBUG(dbgs() << " will not try to unroll partially because "
946 << "-unroll-allow-partial not given\n");
947 return false;
948 }
949 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
950 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Hal Finkel38dd5902015-01-10 00:30:55 +0000951 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
Eli Benderskyff903242014-06-16 23:53:02 +0000952 while (Count != 0 && TripCount % Count != 0)
953 Count--;
954 }
955 } else if (Unrolling == Runtime) {
956 if (!AllowRuntime && !CountSetExplicitly) {
957 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
958 << "-unroll-runtime not given\n");
959 return false;
960 }
961 // Reduce unroll count to be the largest power-of-two factor of
962 // the original count which satisfies the threshold limit.
963 while (Count != 0 && UnrolledSize > PartialThreshold) {
964 Count >>= 1;
Hal Finkel38dd5902015-01-10 00:30:55 +0000965 UnrolledSize = (LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000966 }
967 if (Count > UP.MaxCount)
968 Count = UP.MaxCount;
969 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
970 }
971
972 if (HasPragma) {
Mark Heffernan9e112442014-07-23 20:05:44 +0000973 if (PragmaCount != 0)
974 // If loop has an unroll count pragma mark loop as unrolled to prevent
975 // unrolling beyond that requested by the pragma.
976 SetLoopAlreadyUnrolled(L);
Mark Heffernan053a6862014-07-18 21:04:33 +0000977
Eli Benderskyff903242014-06-16 23:53:02 +0000978 // Emit optimization remarks if we are unable to unroll the loop
979 // as directed by a pragma.
980 DebugLoc LoopLoc = L->getStartLoc();
981 Function *F = Header->getParent();
982 LLVMContext &Ctx = F->getContext();
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000983 if (PragmaFullUnroll && PragmaCount == 0) {
Eli Benderskyff903242014-06-16 23:53:02 +0000984 if (TripCount && Count != TripCount) {
985 emitOptimizationRemarkMissed(
986 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000987 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +0000988 "because unrolled size is too large.");
989 } else if (!TripCount) {
990 emitOptimizationRemarkMissed(
991 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000992 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +0000993 "because loop has a runtime trip count.");
994 }
995 } else if (PragmaCount > 0 && Count != OriginalCount) {
996 emitOptimizationRemarkMissed(
997 Ctx, DEBUG_TYPE, *F, LoopLoc,
998 "Unable to unroll loop the number of times directed by "
999 "unroll_count pragma because unrolled size is too large.");
1000 }
1001 }
1002
1003 if (Unrolling != Full && Count < 2) {
1004 // Partial unrolling by 1 is a nop. For full unrolling, a factor
1005 // of 1 makes sense because loop control can be eliminated.
1006 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001007 }
1008
Dan Gohman3dc2d922008-05-14 00:24:14 +00001009 // Unroll the loop.
Sanjoy Dase178f462015-04-14 03:20:38 +00001010 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
1011 TripMultiple, LI, this, &LPM, &AC))
Dan Gohman3dc2d922008-05-14 00:24:14 +00001012 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001013
Chris Lattner946b2552004-04-18 05:20:17 +00001014 return true;
1015}