blob: 0851f436904e184a4c71a8144affe3dc4053ea76 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopPass.h"
Dan Gohman0141c132010-07-26 18:11:16 +000020#include "llvm/Analysis/ScalarEvolution.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000021#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Eli Benderskyff903242014-06-16 23:53:02 +000024#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000027#include "llvm/IR/Metadata.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000030#include "llvm/Support/raw_ostream.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000031#include "llvm/Transforms/Utils/UnrollLoop.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000032#include "llvm/IR/InstVisitor.h"
33#include "llvm/Analysis/InstructionSimplify.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(
45 "unroll-max-iteration-count-to-analyze", cl::init(1000), cl::Hidden,
46 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;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000168 TTI.getUnrollingPreferences(L, UP);
Eli Benderskyff903242014-06-16 23:53:02 +0000169 }
170
171 // Select and return an unroll count based on parameters from
172 // user, unroll preferences, unroll pragmas, or a heuristic.
173 // SetExplicitly is set to true if the unroll count is is set by
174 // the user or a pragma rather than selected heuristically.
175 unsigned
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000176 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000177 unsigned PragmaCount,
178 const TargetTransformInfo::UnrollingPreferences &UP,
179 bool &SetExplicitly);
180
Eli Benderskyff903242014-06-16 23:53:02 +0000181 // Select threshold values used to limit unrolling based on a
182 // total unrolled size. Parameters Threshold and PartialThreshold
183 // are set to the maximum unrolled size for fully and partially
184 // unrolled loops respectively.
185 void selectThresholds(const Loop *L, bool HasPragma,
186 const TargetTransformInfo::UnrollingPreferences &UP,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000187 unsigned &Threshold, unsigned &PartialThreshold,
Michael Zolotukhin7af83c12015-02-06 20:20:40 +0000188 unsigned NumberOfOptimizedInstructions) {
Eli Benderskyff903242014-06-16 23:53:02 +0000189 // Determine the current unrolling threshold. While this is
190 // normally set from UnrollThreshold, it is overridden to a
191 // smaller value if the current function is marked as
192 // optimize-for-size, and the unroll threshold was not user
193 // specified.
194 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
Michael Zolotukhin7af83c12015-02-06 20:20:40 +0000195
196 // If we are allowed to completely unroll if we can remove M% of
197 // instructions, and we know that with complete unrolling we'll be able
198 // to kill N instructions, then we can afford to completely unroll loops
199 // with unrolled size up to N*100/M.
200 // Adjust the threshold according to that:
201 unsigned PercentOfOptimizedForCompleteUnroll =
202 UserPercentOfOptimized ? CurrentMinPercentOfOptimized
203 : UP.MinPercentOfOptimized;
204 unsigned AbsoluteThreshold = UserAbsoluteThreshold
205 ? CurrentAbsoluteThreshold
206 : UP.AbsoluteThreshold;
207 if (PercentOfOptimizedForCompleteUnroll)
208 Threshold = std::max<unsigned>(Threshold,
209 NumberOfOptimizedInstructions * 100 /
210 PercentOfOptimizedForCompleteUnroll);
211 // But don't allow unrolling loops bigger than absolute threshold.
212 Threshold = std::min<unsigned>(Threshold, AbsoluteThreshold);
213
Eli Benderskyff903242014-06-16 23:53:02 +0000214 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
215 if (!UserThreshold &&
216 L->getHeader()->getParent()->getAttributes().
217 hasAttribute(AttributeSet::FunctionIndex,
218 Attribute::OptimizeForSize)) {
219 Threshold = UP.OptSizeThreshold;
220 PartialThreshold = UP.PartialOptSizeThreshold;
221 }
222 if (HasPragma) {
223 // If the loop has an unrolling pragma, we want to be more
224 // aggressive with unrolling limits. Set thresholds to at
225 // least the PragmaTheshold value which is larger than the
226 // default limits.
227 if (Threshold != NoThreshold)
228 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
229 if (PartialThreshold != NoThreshold)
230 PartialThreshold =
231 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
232 }
233 }
Chris Lattner946b2552004-04-18 05:20:17 +0000234 };
Chris Lattner946b2552004-04-18 05:20:17 +0000235}
236
Dan Gohmand78c4002008-05-13 00:00:25 +0000237char LoopUnroll::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000238INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000239INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000240INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000241INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000242INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
243INITIALIZE_PASS_DEPENDENCY(LCSSA)
Devang Patel88b4fa22011-10-19 23:56:07 +0000244INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000245INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000246
Hal Finkel081eaef2013-11-05 00:08:03 +0000247Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
248 int Runtime) {
249 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
Junjie Gu7c3b4592011-04-13 16:15:29 +0000250}
Chris Lattner946b2552004-04-18 05:20:17 +0000251
Hal Finkel86b30642014-03-31 23:23:51 +0000252Pass *llvm::createSimpleLoopUnrollPass() {
253 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
254}
255
Chandler Carruth186ad602015-02-13 00:00:24 +0000256static bool isLoadFromConstantInitializer(Value *V) {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000257 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
258 if (GV->isConstant() && GV->hasDefinitiveInitializer())
259 return GV->getInitializer();
260 return false;
261}
262
263struct FindConstantPointers {
264 bool LoadCanBeConstantFolded;
265 bool IndexIsConstant;
266 APInt Step;
267 APInt StartValue;
268 Value *BaseAddress;
269 const Loop *L;
270 ScalarEvolution &SE;
271 FindConstantPointers(const Loop *loop, ScalarEvolution &SE)
272 : LoadCanBeConstantFolded(true), IndexIsConstant(true), L(loop), SE(SE) {}
273
274 bool follow(const SCEV *S) {
275 if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) {
276 // We've reached the leaf node of SCEV, it's most probably just a
277 // variable. Now it's time to see if it corresponds to a global constant
278 // global (in which case we can eliminate the load), or not.
279 BaseAddress = SC->getValue();
280 LoadCanBeConstantFolded =
Chandler Carruth186ad602015-02-13 00:00:24 +0000281 IndexIsConstant && isLoadFromConstantInitializer(BaseAddress);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000282 return false;
283 }
284 if (isa<SCEVConstant>(S))
285 return true;
286 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
287 // If the current SCEV expression is AddRec, and its loop isn't the loop
288 // we are about to unroll, then we won't get a constant address after
289 // unrolling, and thus, won't be able to eliminate the load.
290 if (AR->getLoop() != L)
291 return IndexIsConstant = false;
292 // If the step isn't constant, we won't get constant addresses in unrolled
293 // version. Bail out.
294 if (const SCEVConstant *StepSE =
295 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
296 Step = StepSE->getValue()->getValue();
297 else
298 return IndexIsConstant = false;
299
300 return IndexIsConstant;
301 }
302 // If Result is true, continue traversal.
303 // Otherwise, we have found something that prevents us from (possible) load
304 // elimination.
305 return IndexIsConstant;
306 }
307 bool isDone() const { return !IndexIsConstant; }
308};
309
310// This class is used to get an estimate of the optimization effects that we
311// could get from complete loop unrolling. It comes from the fact that some
312// loads might be replaced with concrete constant values and that could trigger
313// a chain of instruction simplifications.
314//
315// E.g. we might have:
316// int a[] = {0, 1, 0};
317// v = 0;
318// for (i = 0; i < 3; i ++)
319// v += b[i]*a[i];
320// If we completely unroll the loop, we would get:
321// v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
322// Which then will be simplified to:
323// v = b[0]* 0 + b[1]* 1 + b[2]* 0
324// And finally:
325// v = b[1]
326class UnrollAnalyzer : public InstVisitor<UnrollAnalyzer, bool> {
327 typedef InstVisitor<UnrollAnalyzer, bool> Base;
328 friend class InstVisitor<UnrollAnalyzer, bool>;
329
330 const Loop *L;
331 unsigned TripCount;
332 ScalarEvolution &SE;
333 const TargetTransformInfo &TTI;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000334
335 DenseMap<Value *, Constant *> SimplifiedValues;
336 DenseMap<LoadInst *, Value *> LoadBaseAddresses;
Chandler Carruth415f4122015-02-13 02:17:39 +0000337 SmallPtrSet<Instruction *, 32> CountedInstructions;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000338
Chandler Carruth302a1332015-02-13 02:10:56 +0000339 /// \brief Count the number of optimized instructions.
340 unsigned NumberOfOptimizedInstructions;
341
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000342 // Provide base case for our instruction visit.
343 bool visitInstruction(Instruction &I) { return false; };
344 // TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt,
345 // FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select,
346 // ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue.
347 //
348 // Probaly it's worth to hoist the code for estimating the simplifications
349 // effects to a separate class, since we have a very similar code in
350 // InlineCost already.
351 bool visitBinaryOperator(BinaryOperator &I) {
352 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
353 if (!isa<Constant>(LHS))
354 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
355 LHS = SimpleLHS;
356 if (!isa<Constant>(RHS))
357 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
358 RHS = SimpleRHS;
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000359 Value *SimpleV = nullptr;
360 if (auto FI = dyn_cast<FPMathOperator>(&I))
361 SimpleV =
362 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags());
363 else
364 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000365
Chandler Carruth415f4122015-02-13 02:17:39 +0000366 if (SimpleV && CountedInstructions.insert(&I).second)
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000367 NumberOfOptimizedInstructions += TTI.getUserCost(&I);
368
369 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
370 SimplifiedValues[&I] = C;
371 return true;
372 }
373 return false;
374 }
375
376 Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) {
377 if (!LI)
378 return nullptr;
379 Value *BaseAddr = LoadBaseAddresses[LI];
380 if (!BaseAddr)
381 return nullptr;
382
383 auto GV = dyn_cast<GlobalVariable>(BaseAddr);
384 if (!GV)
385 return nullptr;
386
387 ConstantDataSequential *CDS =
388 dyn_cast<ConstantDataSequential>(GV->getInitializer());
389 if (!CDS)
390 return nullptr;
391
392 const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr);
393 const SCEV *S = SE.getSCEV(LI->getPointerOperand());
394 const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);
395
396 APInt StepC, StartC;
397 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);
398 if (!AR)
399 return nullptr;
400
401 if (const SCEVConstant *StepSE =
402 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
403 StepC = StepSE->getValue()->getValue();
404 else
405 return nullptr;
406
407 if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart()))
408 StartC = StartSE->getValue()->getValue();
409 else
410 return nullptr;
411
412 unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
413 unsigned Start = StartC.getLimitedValue();
414 unsigned Step = StepC.getLimitedValue();
415
416 unsigned Index = (Start + Step * Iteration) / ElemSize;
417 if (Index >= CDS->getNumElements())
418 return nullptr;
419
420 Constant *CV = CDS->getElementAsConstant(Index);
421
422 return CV;
423 }
424
425public:
426 UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
427 const TargetTransformInfo &TTI)
428 : L(L), TripCount(TripCount), SE(SE), TTI(TTI),
429 NumberOfOptimizedInstructions(0) {}
430
431 // Visit all loads the loop L, and for those that, after complete loop
432 // unrolling, would have a constant address and it will point to a known
433 // constant initializer, record its base address for future use. It is used
434 // when we estimate number of potentially simplified instructions.
Chandler Carruth186ad602015-02-13 00:00:24 +0000435 void findConstFoldableLoads() {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000436 for (auto BB : L->getBlocks()) {
437 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
438 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
439 if (!LI->isSimple())
440 continue;
441 Value *AddrOp = LI->getPointerOperand();
442 const SCEV *S = SE.getSCEV(AddrOp);
443 FindConstantPointers Visitor(L, SE);
444 SCEVTraversal<FindConstantPointers> T(Visitor);
445 T.visitAll(S);
446 if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) {
447 LoadBaseAddresses[LI] = Visitor.BaseAddress;
448 }
449 }
450 }
451 }
452 }
453
454 // Given a list of loads that could be constant-folded (LoadBaseAddresses),
455 // estimate number of optimized instructions after substituting the concrete
456 // values for the given Iteration.
Chandler Carruth415f4122015-02-13 02:17:39 +0000457 // Fill in SimplifiedValues map for future use in DCE-estimation.
458 unsigned estimateNumberOfSimplifiedInstructions(unsigned Iteration) {
Chandler Carruthe5c30e42015-02-13 04:27:50 +0000459 SmallSetVector<Instruction *, 8> Worklist;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000460 SimplifiedValues.clear();
Chandler Carruth415f4122015-02-13 02:17:39 +0000461 CountedInstructions.clear();
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000462 NumberOfOptimizedInstructions = 0;
Chandler Carruth302a1332015-02-13 02:10:56 +0000463
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000464 // We start by adding all loads to the worklist.
Chandler Carruthdd6029f2015-02-13 02:45:17 +0000465 for (auto &LoadDescr : LoadBaseAddresses) {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000466 LoadInst *LI = LoadDescr.first;
467 SimplifiedValues[LI] = computeLoadValue(LI, Iteration);
Chandler Carruth415f4122015-02-13 02:17:39 +0000468 if (CountedInstructions.insert(LI).second)
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000469 NumberOfOptimizedInstructions += TTI.getUserCost(LI);
470
Chandler Carruthdd6029f2015-02-13 02:45:17 +0000471 for (User *U : LI->users()) {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000472 Instruction *UI = dyn_cast<Instruction>(U);
473 if (!UI)
474 continue;
475 if (!L->contains(UI))
476 continue;
Chandler Carruthe5c30e42015-02-13 04:27:50 +0000477 Worklist.insert(UI);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000478 }
479 }
480
481 // And then we try to simplify every user of every instruction from the
482 // worklist. If we do simplify a user, add it to the worklist to process
483 // its users as well.
484 while (!Worklist.empty()) {
485 Instruction *I = Worklist.pop_back_val();
486 if (!visit(I))
487 continue;
Chandler Carruthdd6029f2015-02-13 02:45:17 +0000488 for (User *U : I->users()) {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000489 Instruction *UI = dyn_cast<Instruction>(U);
490 if (!UI)
491 continue;
492 if (!L->contains(UI))
493 continue;
Chandler Carruthe5c30e42015-02-13 04:27:50 +0000494 Worklist.insert(UI);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000495 }
496 }
497 return NumberOfOptimizedInstructions;
498 }
499
500 // Given a list of potentially simplifed instructions, estimate number of
501 // instructions that would become dead if we do perform the simplification.
Chandler Carruth415f4122015-02-13 02:17:39 +0000502 unsigned estimateNumberOfDeadInstructions() {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000503 NumberOfOptimizedInstructions = 0;
Chandler Carruth302a1332015-02-13 02:10:56 +0000504
Chandler Carruth3b057b32015-02-13 03:57:40 +0000505 // We keep a set vector for the worklist so that we don't wast space in the
506 // worklist queuing up the same instruction repeatedly. This can happen due
507 // to multiple operands being the same instruction or due to the same
508 // instruction being an operand of lots of things that end up dead or
509 // simplified.
510 SmallSetVector<Instruction *, 8> Worklist;
511
512 // The dead instructions are held in a separate set. This is used to
513 // prevent us from re-examining instructions and make sure we only count
514 // the benifit once. The worklist's internal set handles insertion
515 // deduplication.
516 SmallPtrSet<Instruction *, 16> DeadInstructions;
Chandler Carruth8c863752015-02-13 03:48:38 +0000517
Chandler Carruth17a04962015-02-13 03:49:41 +0000518 // Lambda to enque operands onto the worklist.
519 auto EnqueueOperands = [&](Instruction &I) {
Chandler Carruth17a04962015-02-13 03:49:41 +0000520 for (auto *Op : I.operand_values())
521 if (auto *OpI = dyn_cast<Instruction>(Op))
Chandler Carruth82cb30f2015-02-13 04:06:08 +0000522 if (!OpI->use_empty())
523 Worklist.insert(OpI);
Chandler Carruth17a04962015-02-13 03:49:41 +0000524 };
525
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000526 // Start by initializing worklist with simplified instructions.
Chandler Carruthdd6029f2015-02-13 02:45:17 +0000527 for (auto &FoldedKeyValue : SimplifiedValues)
528 if (auto *FoldedInst = dyn_cast<Instruction>(FoldedKeyValue.first)) {
Chandler Carruth415f4122015-02-13 02:17:39 +0000529 DeadInstructions.insert(FoldedInst);
Chandler Carruth93063e62015-02-13 03:40:58 +0000530
531 // Add each instruction operand of this dead instruction to the
532 // worklist.
Chandler Carruth17a04962015-02-13 03:49:41 +0000533 EnqueueOperands(*FoldedInst);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000534 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000535
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000536 // If a definition of an insn is only used by simplified or dead
537 // instructions, it's also dead. Check defs of all instructions from the
538 // worklist.
539 while (!Worklist.empty()) {
Chandler Carruth93063e62015-02-13 03:40:58 +0000540 Instruction *I = Worklist.pop_back_val();
541 if (!L->contains(I))
542 continue;
543 if (DeadInstructions.count(I))
544 continue;
Chandler Carruth06d537c2015-02-13 04:14:05 +0000545
Chandler Carruth7824bc92015-02-13 04:18:14 +0000546 if (std::all_of(I->user_begin(), I->user_end(), [&](User *U) {
547 return DeadInstructions.count(cast<Instruction>(U));
548 })) {
Chandler Carruth93063e62015-02-13 03:40:58 +0000549 NumberOfOptimizedInstructions += TTI.getUserCost(I);
550 DeadInstructions.insert(I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000551 EnqueueOperands(*I);
Chandler Carruth93063e62015-02-13 03:40:58 +0000552 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000553 }
554 return NumberOfOptimizedInstructions;
555 }
556};
557
558// Complete loop unrolling can make some loads constant, and we need to know if
559// that would expose any further optimization opportunities.
560// This routine estimates this optimization effect and returns the number of
561// instructions, that potentially might be optimized away.
562static unsigned
Chandler Carruth186ad602015-02-13 00:00:24 +0000563approximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000564 unsigned TripCount,
565 const TargetTransformInfo &TTI) {
Michael Zolotukhin1b480192015-02-13 00:17:03 +0000566 if (!TripCount || !UnrollMaxIterationsCountToAnalyze)
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000567 return 0;
568
569 UnrollAnalyzer UA(L, TripCount, SE, TTI);
Chandler Carruth186ad602015-02-13 00:00:24 +0000570 UA.findConstFoldableLoads();
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000571
572 // Estimate number of instructions, that could be simplified if we replace a
573 // load with the corresponding constant. Since the same load will take
574 // different values on different iterations, we have to go through all loop's
575 // iterations here. To limit ourselves here, we check only first N
576 // iterations, and then scale the found number, if necessary.
577 unsigned IterationsNumberForEstimate =
578 std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount);
579 unsigned NumberOfOptimizedInstructions = 0;
580 for (unsigned i = 0; i < IterationsNumberForEstimate; ++i) {
Chandler Carruth415f4122015-02-13 02:17:39 +0000581 NumberOfOptimizedInstructions +=
582 UA.estimateNumberOfSimplifiedInstructions(i);
583 NumberOfOptimizedInstructions += UA.estimateNumberOfDeadInstructions();
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000584 }
585 NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate;
586
587 return NumberOfOptimizedInstructions;
588}
589
Dan Gohman49d08a52007-05-08 15:14:19 +0000590/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000591static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000592 bool &NotDuplicatable,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000593 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000594 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000595 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000596 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000597
Dan Gohman969e83a2009-10-31 14:54:17 +0000598 CodeMetrics Metrics;
Dan Gohman90071072008-06-22 20:18:58 +0000599 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohman969e83a2009-10-31 14:54:17 +0000600 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000601 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000602 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000603 NotDuplicatable = Metrics.notDuplicatable;
Andrew Trick279e7a62011-07-23 00:29:16 +0000604
Owen Anderson62ea1b72010-09-09 19:07:31 +0000605 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000606
Owen Anderson62ea1b72010-09-09 19:07:31 +0000607 // Don't allow an estimate of size zero. This would allows unrolling of loops
608 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000609 // not a problem for code quality. Also, the code using this size may assume
610 // that each loop has at least three instructions (likely a conditional
611 // branch, a comparison feeding that branch, and some kind of loop increment
612 // feeding that comparison instruction).
613 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000614
Owen Anderson62ea1b72010-09-09 19:07:31 +0000615 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000616}
617
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000618// Returns the loop hint metadata node with the given name (for example,
619// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
620// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000621static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
622 if (MDNode *LoopID = L->getLoopID())
623 return GetUnrollMetadata(LoopID, Name);
624 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000625}
626
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000627// Returns true if the loop has an unroll(full) pragma.
628static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000629 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000630}
631
632// Returns true if the loop has an unroll(disable) pragma.
633static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000634 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000635}
636
637// If loop has an unroll_count pragma return the (necessarily
638// positive) value from the pragma. Otherwise return 0.
639static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000640 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000641 if (MD) {
642 assert(MD->getNumOperands() == 2 &&
643 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000644 unsigned Count =
645 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000646 assert(Count >= 1 && "Unroll count must be positive.");
647 return Count;
648 }
649 return 0;
650}
651
Mark Heffernan053a6862014-07-18 21:04:33 +0000652// Remove existing unroll metadata and add unroll disable metadata to
653// indicate the loop has already been unrolled. This prevents a loop
654// from being unrolled more than is directed by a pragma if the loop
655// unrolling pass is run more than once (which it generally is).
656static void SetLoopAlreadyUnrolled(Loop *L) {
657 MDNode *LoopID = L->getLoopID();
658 if (!LoopID) return;
659
660 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000661 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000662 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000663 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000664 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
665 bool IsUnrollMetadata = false;
666 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
667 if (MD) {
668 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
669 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
670 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000671 if (!IsUnrollMetadata)
672 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000673 }
674
675 // Add unroll(disable) metadata to disable future unrolling.
676 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000677 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000678 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000679 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000680 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000681
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000682 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000683 // Set operand 0 to refer to the loop id itself.
684 NewLoopID->replaceOperandWith(0, NewLoopID);
685 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000686}
687
Eli Benderskyff903242014-06-16 23:53:02 +0000688unsigned LoopUnroll::selectUnrollCount(
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000689 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000690 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
691 bool &SetExplicitly) {
692 SetExplicitly = true;
693
694 // User-specified count (either as a command-line option or
695 // constructor parameter) has highest precedence.
696 unsigned Count = UserCount ? CurrentCount : 0;
697
698 // If there is no user-specified count, unroll pragmas have the next
699 // highest precendence.
700 if (Count == 0) {
701 if (PragmaCount) {
702 Count = PragmaCount;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000703 } else if (PragmaFullUnroll) {
Eli Benderskyff903242014-06-16 23:53:02 +0000704 Count = TripCount;
705 }
706 }
707
708 if (Count == 0)
709 Count = UP.Count;
710
711 if (Count == 0) {
712 SetExplicitly = false;
713 if (TripCount == 0)
714 // Runtime trip count.
715 Count = UnrollRuntimeCount;
716 else
717 // Conservative heuristic: if we know the trip count, see if we can
718 // completely unroll (subject to the threshold, checked below); otherwise
719 // try to find greatest modulo of the trip count which is still under
720 // threshold value.
721 Count = TripCount;
722 }
723 if (TripCount && Count > TripCount)
724 return TripCount;
725 return Count;
726}
727
Devang Patel9779e562007-03-07 01:38:05 +0000728bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000729 if (skipOptnoneFunction(L))
730 return false;
731
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000732 Function &F = *L->getHeader()->getParent();
733
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000734 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Andrew Trick2b6860f2011-08-11 23:36:16 +0000735 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000736 const TargetTransformInfo &TTI =
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000737 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000738 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000739
Dan Gohman2e1f8042007-05-08 15:19:19 +0000740 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000741 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000742 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000743
744 if (HasUnrollDisablePragma(L)) {
745 return false;
746 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000747 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000748 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000749 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000750
Hal Finkel8f2e7002013-09-11 19:25:43 +0000751 TargetTransformInfo::UnrollingPreferences UP;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000752 getUnrollingPreferences(L, TTI, UP);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000753
Andrew Trick2b6860f2011-08-11 23:36:16 +0000754 // Find trip count and trip multiple if count is not available
755 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000756 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000757 // If there are multiple exiting blocks but one of them is the latch, use the
758 // latch for the trip count estimation. Otherwise insist on a single exiting
759 // block for the trip count estimation.
760 BasicBlock *ExitingBlock = L->getLoopLatch();
761 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
762 ExitingBlock = L->getExitingBlock();
763 if (ExitingBlock) {
764 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
765 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000766 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000767
Eli Benderskyff903242014-06-16 23:53:02 +0000768 // Select an initial unroll count. This may be reduced later based
769 // on size thresholds.
770 bool CountSetExplicitly;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000771 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
772 PragmaCount, UP, CountSetExplicitly);
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000773
Eli Benderskyff903242014-06-16 23:53:02 +0000774 unsigned NumInlineCandidates;
775 bool notDuplicatable;
776 unsigned LoopSize =
Chandler Carruth66b31302015-01-04 12:03:27 +0000777 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000778 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Hal Finkel38dd5902015-01-10 00:30:55 +0000779
780 // When computing the unrolled size, note that the conditional branch on the
781 // backedge and the comparison feeding it are not replicated like the rest of
782 // the loop body (which is why 2 is subtracted).
783 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000784 if (notDuplicatable) {
785 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
786 << " instructions.\n");
787 return false;
788 }
789 if (NumInlineCandidates != 0) {
790 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
791 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000792 }
793
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000794 unsigned NumberOfOptimizedInstructions =
Chandler Carruth186ad602015-02-13 00:00:24 +0000795 approximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000796 DEBUG(dbgs() << " Complete unrolling could save: "
797 << NumberOfOptimizedInstructions << "\n");
798
Eli Benderskyff903242014-06-16 23:53:02 +0000799 unsigned Threshold, PartialThreshold;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000800 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
801 NumberOfOptimizedInstructions);
Benjamin Kramer9130cb82014-05-04 19:12:38 +0000802
Eli Benderskyff903242014-06-16 23:53:02 +0000803 // Given Count, TripCount and thresholds determine the type of
804 // unrolling which is to be performed.
805 enum { Full = 0, Partial = 1, Runtime = 2 };
806 int Unrolling;
807 if (TripCount && Count == TripCount) {
808 if (Threshold != NoThreshold && UnrolledSize > Threshold) {
809 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
810 << " because size: " << UnrolledSize << ">" << Threshold
811 << "\n");
812 Unrolling = Partial;
813 } else {
814 Unrolling = Full;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000815 }
Eli Benderskyff903242014-06-16 23:53:02 +0000816 } else if (TripCount && Count < TripCount) {
817 Unrolling = Partial;
818 } else {
819 Unrolling = Runtime;
820 }
821
822 // Reduce count based on the type of unrolling and the threshold values.
823 unsigned OriginalCount = Count;
824 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
825 if (Unrolling == Partial) {
826 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
827 if (!AllowPartial && !CountSetExplicitly) {
828 DEBUG(dbgs() << " will not try to unroll partially because "
829 << "-unroll-allow-partial not given\n");
830 return false;
831 }
832 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
833 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Hal Finkel38dd5902015-01-10 00:30:55 +0000834 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
Eli Benderskyff903242014-06-16 23:53:02 +0000835 while (Count != 0 && TripCount % Count != 0)
836 Count--;
837 }
838 } else if (Unrolling == Runtime) {
839 if (!AllowRuntime && !CountSetExplicitly) {
840 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
841 << "-unroll-runtime not given\n");
842 return false;
843 }
844 // Reduce unroll count to be the largest power-of-two factor of
845 // the original count which satisfies the threshold limit.
846 while (Count != 0 && UnrolledSize > PartialThreshold) {
847 Count >>= 1;
Hal Finkel38dd5902015-01-10 00:30:55 +0000848 UnrolledSize = (LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000849 }
850 if (Count > UP.MaxCount)
851 Count = UP.MaxCount;
852 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
853 }
854
855 if (HasPragma) {
Mark Heffernan9e112442014-07-23 20:05:44 +0000856 if (PragmaCount != 0)
857 // If loop has an unroll count pragma mark loop as unrolled to prevent
858 // unrolling beyond that requested by the pragma.
859 SetLoopAlreadyUnrolled(L);
Mark Heffernan053a6862014-07-18 21:04:33 +0000860
Eli Benderskyff903242014-06-16 23:53:02 +0000861 // Emit optimization remarks if we are unable to unroll the loop
862 // as directed by a pragma.
863 DebugLoc LoopLoc = L->getStartLoc();
864 Function *F = Header->getParent();
865 LLVMContext &Ctx = F->getContext();
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000866 if (PragmaFullUnroll && PragmaCount == 0) {
Eli Benderskyff903242014-06-16 23:53:02 +0000867 if (TripCount && Count != TripCount) {
868 emitOptimizationRemarkMissed(
869 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000870 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +0000871 "because unrolled size is too large.");
872 } else if (!TripCount) {
873 emitOptimizationRemarkMissed(
874 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000875 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +0000876 "because loop has a runtime trip count.");
877 }
878 } else if (PragmaCount > 0 && Count != OriginalCount) {
879 emitOptimizationRemarkMissed(
880 Ctx, DEBUG_TYPE, *F, LoopLoc,
881 "Unable to unroll loop the number of times directed by "
882 "unroll_count pragma because unrolled size is too large.");
883 }
884 }
885
886 if (Unrolling != Full && Count < 2) {
887 // Partial unrolling by 1 is a nop. For full unrolling, a factor
888 // of 1 makes sense because loop control can be eliminated.
889 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000890 }
891
Dan Gohman3dc2d922008-05-14 00:24:14 +0000892 // Unroll the loop.
Hal Finkel74c2f352014-09-07 12:44:26 +0000893 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,
Chandler Carruth66b31302015-01-04 12:03:27 +0000894 &LPM, &AC))
Dan Gohman3dc2d922008-05-14 00:24:14 +0000895 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000896
Chris Lattner946b2552004-04-18 05:20:17 +0000897 return true;
898}