blob: 0c047e78eab3b39b5e7a5d822a7758f5d128090b [file] [log] [blame]
Chris Lattner946b2552004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner946b2552004-04-18 05:20:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner946b2552004-04-18 05:20:17 +00008//===----------------------------------------------------------------------===//
9//
10// This pass implements a simple loop unroller. It works best when loops have
11// been canonicalized by the -indvars pass, allowing it to determine the trip
12// counts of loops easily.
Chris Lattner946b2552004-04-18 05:20:17 +000013//===----------------------------------------------------------------------===//
14
Chris Lattner946b2552004-04-18 05:20:17 +000015#include "llvm/Transforms/Scalar.h"
Chandler Carruth3b057b32015-02-13 03:57:40 +000016#include "llvm/ADT/SetVector.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000017#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000018#include "llvm/Analysis/CodeMetrics.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000019#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/LoopPass.h"
Dan Gohman0141c132010-07-26 18:11:16 +000021#include "llvm/Analysis/ScalarEvolution.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000022#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Eli Benderskyff903242014-06-16 23:53:02 +000025#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000027#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000029#include "llvm/IR/Metadata.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000032#include "llvm/Support/raw_ostream.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000033#include "llvm/Transforms/Utils/UnrollLoop.h"
Duncan Sands67933e62008-05-16 09:30:00 +000034#include <climits>
Chris Lattner946b2552004-04-18 05:20:17 +000035
Dan Gohman3dc2d922008-05-14 00:24:14 +000036using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000037
Chandler Carruth964daaa2014-04-22 02:55:47 +000038#define DEBUG_TYPE "loop-unroll"
39
Dan Gohmand78c4002008-05-13 00:00:25 +000040static cl::opt<unsigned>
Chandler Carruth9dabd142015-06-05 17:01:43 +000041 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
42 cl::desc("The baseline cost threshold for loop unrolling"));
43
44static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
45 "unroll-percent-dynamic-cost-saved-threshold", cl::init(20), cl::Hidden,
46 cl::desc("The percentage of estimated dynamic cost which must be saved by "
47 "unrolling to allow unrolling up to the max threshold."));
48
49static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
50 "unroll-dynamic-cost-savings-discount", cl::init(2000), cl::Hidden,
51 cl::desc("This is the amount discounted from the total unroll cost when "
52 "the unrolled form has a high dynamic cost savings (triggered by "
53 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
Dan Gohmand78c4002008-05-13 00:00:25 +000054
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000055static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
Chandler Carruth1fbc3162015-02-13 05:31:46 +000056 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000057 cl::desc("Don't allow loop unrolling to simulate more than this number of"
58 "iterations when checking full unroll profitability"));
59
Dan Gohmand78c4002008-05-13 00:00:25 +000060static cl::opt<unsigned>
61UnrollCount("unroll-count", cl::init(0), cl::Hidden,
Eli Benderskyff903242014-06-16 23:53:02 +000062 cl::desc("Use this unroll count for all loops including those with "
63 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +000064
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000065static cl::opt<bool>
66UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
67 cl::desc("Allows loops to be partially unrolled until "
68 "-unroll-threshold loop size is reached."));
69
Andrew Trickd04d15292011-12-09 06:19:40 +000070static cl::opt<bool>
71UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
72 cl::desc("Unroll loops with run-time trip counts"));
73
Eli Benderskyff903242014-06-16 23:53:02 +000074static cl::opt<unsigned>
75PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
Mark Heffernane6b4ba12014-07-23 17:31:37 +000076 cl::desc("Unrolled size limit for loops with an unroll(full) or "
Eli Benderskyff903242014-06-16 23:53:02 +000077 "unroll_count pragma."));
78
Chris Lattner79a42ac2006-12-19 21:40:18 +000079namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000080 class LoopUnroll : public LoopPass {
Chris Lattner946b2552004-04-18 05:20:17 +000081 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000082 static char ID; // Pass ID, replacement for typeid
Hal Finkel081eaef2013-11-05 00:08:03 +000083 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
Chris Lattner35a65b22011-04-14 02:27:25 +000084 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
Chandler Carruth9dabd142015-06-05 17:01:43 +000085 CurrentPercentDynamicCostSavedThreshold =
86 UnrollPercentDynamicCostSavedThreshold;
87 CurrentDynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
Chris Lattner35a65b22011-04-14 02:27:25 +000088 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
Junjie Gu7c3b4592011-04-13 16:15:29 +000089 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
Hal Finkel081eaef2013-11-05 00:08:03 +000090 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
Junjie Gu7c3b4592011-04-13 16:15:29 +000091
92 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
Chandler Carruth9dabd142015-06-05 17:01:43 +000093 UserPercentDynamicCostSavedThreshold =
94 (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0);
95 UserDynamicCostSavingsDiscount =
96 (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000097 UserAllowPartial = (P != -1) ||
98 (UnrollAllowPartial.getNumOccurrences() > 0);
Hal Finkel081eaef2013-11-05 00:08:03 +000099 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +0000100 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
Andrew Trick279e7a62011-07-23 00:29:16 +0000101
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000102 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
103 }
Devang Patel09f162c2007-05-01 21:15:47 +0000104
Dan Gohman2980d9d2007-05-11 20:53:41 +0000105 /// A magic value for use with the Threshold parameter to indicate
106 /// that the loop unroll should be performed regardless of how much
107 /// code expansion would result.
108 static const unsigned NoThreshold = UINT_MAX;
Andrew Trick279e7a62011-07-23 00:29:16 +0000109
Owen Andersona4d9c782010-09-07 23:15:30 +0000110 // Threshold to use when optsize is specified (and there is no
111 // explicit -unroll-threshold).
112 static const unsigned OptSizeUnrollThreshold = 50;
Andrew Trick279e7a62011-07-23 00:29:16 +0000113
Andrew Trickd04d15292011-12-09 06:19:40 +0000114 // Default unroll count for loops with run-time trip count if
115 // -unroll-count is not set
116 static const unsigned UnrollRuntimeCount = 8;
117
Junjie Gu7c3b4592011-04-13 16:15:29 +0000118 unsigned CurrentCount;
Owen Andersona4d9c782010-09-07 23:15:30 +0000119 unsigned CurrentThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000120 unsigned CurrentPercentDynamicCostSavedThreshold;
121 unsigned CurrentDynamicCostSavingsDiscount;
122 bool CurrentAllowPartial;
123 bool CurrentRuntime;
124
125 // Flags for whether the 'current' settings are user-specified.
126 bool UserCount;
127 bool UserThreshold;
128 bool UserPercentDynamicCostSavedThreshold;
129 bool UserDynamicCostSavingsDiscount;
130 bool UserAllowPartial;
131 bool UserRuntime;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000132
Craig Topper3e4c6972014-03-05 09:10:37 +0000133 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner946b2552004-04-18 05:20:17 +0000134
135 /// This transformation requires natural loop information & requires that
136 /// loop preheaders be inserted into the CFG...
137 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000138 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000139 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000140 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000141 AU.addRequired<LoopInfoWrapperPass>();
142 AU.addPreserved<LoopInfoWrapperPass>();
Dan Gohman0141c132010-07-26 18:11:16 +0000143 AU.addRequiredID(LoopSimplifyID);
144 AU.addPreservedID(LoopSimplifyID);
145 AU.addRequiredID(LCSSAID);
146 AU.addPreservedID(LCSSAID);
Andrew Trick4d0040b2011-08-10 04:29:49 +0000147 AU.addRequired<ScalarEvolution>();
Chris Lattnerd6f46b82010-08-29 17:21:35 +0000148 AU.addPreserved<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000149 AU.addRequired<TargetTransformInfoWrapperPass>();
Devang Patelf94b9822008-07-03 07:04:22 +0000150 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
151 // If loop unroll does not preserve dom info then LCSSA pass on next
152 // loop will receive invalid dom info.
153 // For now, recreate dom info, if loop is unrolled.
Chandler Carruth73523022014-01-13 13:07:17 +0000154 AU.addPreserved<DominatorTreeWrapperPass>();
Chris Lattner946b2552004-04-18 05:20:17 +0000155 }
Eli Benderskyff903242014-06-16 23:53:02 +0000156
157 // Fill in the UnrollingPreferences parameter with values from the
158 // TargetTransformationInfo.
Chandler Carruth21fc1952015-02-01 14:37:03 +0000159 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
Eli Benderskyff903242014-06-16 23:53:02 +0000160 TargetTransformInfo::UnrollingPreferences &UP) {
161 UP.Threshold = CurrentThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000162 UP.PercentDynamicCostSavedThreshold =
163 CurrentPercentDynamicCostSavedThreshold;
164 UP.DynamicCostSavingsDiscount = CurrentDynamicCostSavingsDiscount;
Eli Benderskyff903242014-06-16 23:53:02 +0000165 UP.OptSizeThreshold = OptSizeUnrollThreshold;
166 UP.PartialThreshold = CurrentThreshold;
167 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
168 UP.Count = CurrentCount;
169 UP.MaxCount = UINT_MAX;
170 UP.Partial = CurrentAllowPartial;
171 UP.Runtime = CurrentRuntime;
Sanjoy Dase178f462015-04-14 03:20:38 +0000172 UP.AllowExpensiveTripCount = false;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000173 TTI.getUnrollingPreferences(L, UP);
Eli Benderskyff903242014-06-16 23:53:02 +0000174 }
175
176 // Select and return an unroll count based on parameters from
177 // user, unroll preferences, unroll pragmas, or a heuristic.
178 // SetExplicitly is set to true if the unroll count is is set by
179 // the user or a pragma rather than selected heuristically.
180 unsigned
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000181 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000182 unsigned PragmaCount,
183 const TargetTransformInfo::UnrollingPreferences &UP,
184 bool &SetExplicitly);
185
Eli Benderskyff903242014-06-16 23:53:02 +0000186 // Select threshold values used to limit unrolling based on a
187 // total unrolled size. Parameters Threshold and PartialThreshold
188 // are set to the maximum unrolled size for fully and partially
189 // unrolled loops respectively.
Mark Heffernan89391542015-08-10 17:28:08 +0000190 void selectThresholds(const Loop *L, bool UsePragmaThreshold,
Eli Benderskyff903242014-06-16 23:53:02 +0000191 const TargetTransformInfo::UnrollingPreferences &UP,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000192 unsigned &Threshold, unsigned &PartialThreshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000193 unsigned &PercentDynamicCostSavedThreshold,
194 unsigned &DynamicCostSavingsDiscount) {
Eli Benderskyff903242014-06-16 23:53:02 +0000195 // Determine the current unrolling threshold. While this is
196 // normally set from UnrollThreshold, it is overridden to a
197 // smaller value if the current function is marked as
198 // optimize-for-size, and the unroll threshold was not user
199 // specified.
200 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
201 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000202 PercentDynamicCostSavedThreshold =
203 UserPercentDynamicCostSavedThreshold
204 ? CurrentPercentDynamicCostSavedThreshold
205 : UP.PercentDynamicCostSavedThreshold;
206 DynamicCostSavingsDiscount = UserDynamicCostSavingsDiscount
207 ? CurrentDynamicCostSavingsDiscount
208 : UP.DynamicCostSavingsDiscount;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000209
Eli Benderskyff903242014-06-16 23:53:02 +0000210 if (!UserThreshold &&
Sanjay Patel924879a2015-08-04 15:49:57 +0000211 // FIXME: Use Function::optForSize().
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000212 L->getHeader()->getParent()->hasFnAttribute(
213 Attribute::OptimizeForSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000214 Threshold = UP.OptSizeThreshold;
215 PartialThreshold = UP.PartialOptSizeThreshold;
216 }
Mark Heffernan89391542015-08-10 17:28:08 +0000217 if (UsePragmaThreshold) {
Eli Benderskyff903242014-06-16 23:53:02 +0000218 // If the loop has an unrolling pragma, we want to be more
219 // aggressive with unrolling limits. Set thresholds to at
220 // least the PragmaTheshold value which is larger than the
221 // default limits.
222 if (Threshold != NoThreshold)
223 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
224 if (PartialThreshold != NoThreshold)
225 PartialThreshold =
226 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
227 }
228 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000229 bool canUnrollCompletely(Loop *L, unsigned Threshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000230 unsigned PercentDynamicCostSavedThreshold,
231 unsigned DynamicCostSavingsDiscount,
Sanjoy Dasad714b12015-06-06 05:24:10 +0000232 uint64_t UnrolledCost, uint64_t RolledDynamicCost);
Chris Lattner946b2552004-04-18 05:20:17 +0000233 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000234}
Chris Lattner946b2552004-04-18 05:20:17 +0000235
Dan Gohmand78c4002008-05-13 00:00:25 +0000236char LoopUnroll::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000237INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000238INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000239INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000240INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
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
Benjamin Kramer51f6096c2015-03-23 12:30:58 +0000256namespace {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000257// This class is used to get an estimate of the optimization effects that we
258// could get from complete loop unrolling. It comes from the fact that some
259// loads might be replaced with concrete constant values and that could trigger
260// a chain of instruction simplifications.
261//
262// E.g. we might have:
263// int a[] = {0, 1, 0};
264// v = 0;
265// for (i = 0; i < 3; i ++)
266// v += b[i]*a[i];
267// If we completely unroll the loop, we would get:
268// v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
269// Which then will be simplified to:
270// v = b[0]* 0 + b[1]* 1 + b[2]* 0
271// And finally:
272// v = b[1]
Chandler Carruth02156082015-05-22 17:41:35 +0000273class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> {
274 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base;
275 friend class InstVisitor<UnrolledInstAnalyzer, bool>;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000276 struct SimplifiedAddress {
277 Value *Base = nullptr;
278 ConstantInt *Offset = nullptr;
279 };
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000280
Chandler Carruth02156082015-05-22 17:41:35 +0000281public:
282 UnrolledInstAnalyzer(unsigned Iteration,
283 DenseMap<Value *, Constant *> &SimplifiedValues,
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000284 const Loop *L, ScalarEvolution &SE)
285 : Iteration(Iteration), SimplifiedValues(SimplifiedValues), L(L), SE(SE) {
286 IterationNumber = SE.getConstant(APInt(64, Iteration));
287 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000288
Chandler Carruth02156082015-05-22 17:41:35 +0000289 // Allow access to the initial visit method.
290 using Base::visit;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000291
Chandler Carruth02156082015-05-22 17:41:35 +0000292private:
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000293 /// \brief A cache of pointer bases and constant-folded offsets corresponding
294 /// to GEP (or derived from GEP) instructions.
295 ///
296 /// In order to find the base pointer one needs to perform non-trivial
297 /// traversal of the corresponding SCEV expression, so it's good to have the
298 /// results saved.
299 DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses;
300
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000301 /// \brief Number of currently simulated iteration.
302 ///
303 /// If an expression is ConstAddress+Constant, then the Constant is
304 /// Start + Iteration*Step, where Start and Step could be obtained from
Chandler Carruthe1a04622015-05-22 03:02:22 +0000305 /// SCEVGEPCache.
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000306 unsigned Iteration;
307
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000308 /// \brief SCEV expression corresponding to number of currently simulated
309 /// iteration.
310 const SCEV *IterationNumber;
311
312 /// \brief A Value->Constant map for keeping values that we managed to
313 /// constant-fold on the given iteration.
314 ///
315 /// While we walk the loop instructions, we build up and maintain a mapping
316 /// of simplified values specific to this iteration. The idea is to propagate
317 /// any special information we have about loads that can be replaced with
318 /// constants after complete unrolling, and account for likely simplifications
319 /// post-unrolling.
Chandler Carruth02156082015-05-22 17:41:35 +0000320 DenseMap<Value *, Constant *> &SimplifiedValues;
321
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000322 const Loop *L;
323 ScalarEvolution &SE;
324
325 /// \brief Try to simplify instruction \param I using its SCEV expression.
326 ///
327 /// The idea is that some AddRec expressions become constants, which then
328 /// could trigger folding of other instructions. However, that only happens
329 /// for expressions whose start value is also constant, which isn't always the
330 /// case. In another common and important case the start value is just some
331 /// address (i.e. SCEVUnknown) - in this case we compute the offset and save
332 /// it along with the base address instead.
333 bool simplifyInstWithSCEV(Instruction *I) {
334 if (!SE.isSCEVable(I->getType()))
335 return false;
336
337 const SCEV *S = SE.getSCEV(I);
338 if (auto *SC = dyn_cast<SCEVConstant>(S)) {
339 SimplifiedValues[I] = SC->getValue();
340 return true;
341 }
342
343 auto *AR = dyn_cast<SCEVAddRecExpr>(S);
344 if (!AR)
345 return false;
346
347 const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE);
348 // Check if the AddRec expression becomes a constant.
349 if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) {
350 SimplifiedValues[I] = SC->getValue();
351 return true;
352 }
353
354 // Check if the offset from the base address becomes a constant.
355 auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S));
356 if (!Base)
357 return false;
358 auto *Offset =
359 dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base));
360 if (!Offset)
361 return false;
362 SimplifiedAddress Address;
363 Address.Base = Base->getValue();
364 Address.Offset = Offset->getValue();
365 SimplifiedAddresses[I] = Address;
366 return true;
367 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000368
369 /// Base case for the instruction visitor.
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000370 bool visitInstruction(Instruction &I) {
371 return simplifyInstWithSCEV(&I);
372 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000373
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000374 /// Try to simplify binary operator I.
375 ///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000376 /// TODO: Probably it's worth to hoist the code for estimating the
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000377 /// simplifications effects to a separate class, since we have a very similar
378 /// code in InlineCost already.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000379 bool visitBinaryOperator(BinaryOperator &I) {
380 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
381 if (!isa<Constant>(LHS))
382 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
383 LHS = SimpleLHS;
384 if (!isa<Constant>(RHS))
385 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
386 RHS = SimpleRHS;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000387
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000388 Value *SimpleV = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000389 const DataLayout &DL = I.getModule()->getDataLayout();
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000390 if (auto FI = dyn_cast<FPMathOperator>(&I))
391 SimpleV =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000392 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000393 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000394 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000395
Chandler Carruthf174a152015-05-22 02:47:29 +0000396 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000397 SimplifiedValues[&I] = C;
Chandler Carruthf174a152015-05-22 02:47:29 +0000398
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000399 if (SimpleV)
400 return true;
401 return Base::visitBinaryOperator(I);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000402 }
403
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000404 /// Try to fold load I.
405 bool visitLoad(LoadInst &I) {
406 Value *AddrOp = I.getPointerOperand();
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000407
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000408 auto AddressIt = SimplifiedAddresses.find(AddrOp);
409 if (AddressIt == SimplifiedAddresses.end())
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000410 return false;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000411 ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000412
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000413 auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base);
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000414 // We're only interested in loads that can be completely folded to a
415 // constant.
416 if (!GV || !GV->hasInitializer())
417 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000418
419 ConstantDataSequential *CDS =
420 dyn_cast<ConstantDataSequential>(GV->getInitializer());
421 if (!CDS)
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000422 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000423
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000424 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000425 assert(SimplifiedAddrOp->getValue().getActiveBits() < 64 &&
426 "Unexpectedly large index value.");
427 int64_t Index = SimplifiedAddrOp->getSExtValue() / ElemSize;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000428 if (Index >= CDS->getNumElements()) {
429 // FIXME: For now we conservatively ignore out of bound accesses, but
430 // we're allowed to perform the optimization in this case.
431 return false;
432 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000433
434 Constant *CV = CDS->getElementAsConstant(Index);
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000435 assert(CV && "Constant expected.");
436 SimplifiedValues[&I] = CV;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000437
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000438 return true;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000439 }
Michael Zolotukhin31b3eaa2015-07-15 00:19:51 +0000440
441 bool visitCastInst(CastInst &I) {
442 // Propagate constants through casts.
443 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
444 if (!COp)
445 COp = SimplifiedValues.lookup(I.getOperand(0));
446 if (COp)
447 if (Constant *C =
448 ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
449 SimplifiedValues[&I] = C;
450 return true;
451 }
452
453 return Base::visitCastInst(I);
454 }
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000455
456 bool visitCmpInst(CmpInst &I) {
457 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
458
459 // First try to handle simplified comparisons.
460 if (!isa<Constant>(LHS))
461 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
462 LHS = SimpleLHS;
463 if (!isa<Constant>(RHS))
464 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
465 RHS = SimpleRHS;
466
467 if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) {
468 auto SimplifiedLHS = SimplifiedAddresses.find(LHS);
469 if (SimplifiedLHS != SimplifiedAddresses.end()) {
470 auto SimplifiedRHS = SimplifiedAddresses.find(RHS);
471 if (SimplifiedRHS != SimplifiedAddresses.end()) {
472 SimplifiedAddress &LHSAddr = SimplifiedLHS->second;
473 SimplifiedAddress &RHSAddr = SimplifiedRHS->second;
474 if (LHSAddr.Base == RHSAddr.Base) {
475 LHS = LHSAddr.Offset;
476 RHS = RHSAddr.Offset;
477 }
478 }
479 }
480 }
481
482 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
483 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
484 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
485 SimplifiedValues[&I] = C;
486 return true;
487 }
488 }
489 }
490
491 return Base::visitCmpInst(I);
492 }
Chandler Carruth02156082015-05-22 17:41:35 +0000493};
494} // namespace
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000495
Chandler Carruth6c03dff2015-02-13 04:39:05 +0000496
Chandler Carruth02156082015-05-22 17:41:35 +0000497namespace {
498struct EstimatedUnrollCost {
Chandler Carruth9dabd142015-06-05 17:01:43 +0000499 /// \brief The estimated cost after unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000500 int UnrolledCost;
Chandler Carruth302a1332015-02-13 02:10:56 +0000501
Chandler Carruth9dabd142015-06-05 17:01:43 +0000502 /// \brief The estimated dynamic cost of executing the instructions in the
503 /// rolled form.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000504 int RolledDynamicCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000505};
506}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000507
Chandler Carruth02156082015-05-22 17:41:35 +0000508/// \brief Figure out if the loop is worth full unrolling.
509///
510/// Complete loop unrolling can make some loads constant, and we need to know
511/// if that would expose any further optimization opportunities. This routine
Michael Zolotukhinc4e4f332015-06-11 22:17:39 +0000512/// estimates this optimization. It computes cost of unrolled loop
513/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
514/// dynamic cost we mean that we won't count costs of blocks that are known not
515/// to be executed (i.e. if we have a branch in the loop and we know that at the
516/// given iteration its condition would be resolved to true, we won't add up the
517/// cost of the 'false'-block).
518/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
519/// the analysis failed (no benefits expected from the unrolling, or the loop is
520/// too big to analyze), the returned value is None.
Chandler Carruth02156082015-05-22 17:41:35 +0000521Optional<EstimatedUnrollCost>
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000522analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
523 ScalarEvolution &SE, const TargetTransformInfo &TTI,
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000524 int MaxUnrolledLoopSize) {
Chandler Carruth02156082015-05-22 17:41:35 +0000525 // We want to be able to scale offsets by the trip count and add more offsets
526 // to them without checking for overflows, and we already don't want to
527 // analyze *massive* trip counts, so we force the max to be reasonably small.
528 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
529 "The unroll iterations max is too large!");
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000530
Chandler Carruth02156082015-05-22 17:41:35 +0000531 // Don't simulate loops with a big or unknown tripcount
532 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
533 TripCount > UnrollMaxIterationsCountToAnalyze)
534 return None;
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000535
Chandler Carruth02156082015-05-22 17:41:35 +0000536 SmallSetVector<BasicBlock *, 16> BBWorklist;
537 DenseMap<Value *, Constant *> SimplifiedValues;
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000538 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
Chandler Carruth3b057b32015-02-13 03:57:40 +0000539
Chandler Carruth9dabd142015-06-05 17:01:43 +0000540 // The estimated cost of the unrolled form of the loop. We try to estimate
541 // this by simplifying as much as we can while computing the estimate.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000542 int UnrolledCost = 0;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000543 // We also track the estimated dynamic (that is, actually executed) cost in
544 // the rolled form. This helps identify cases when the savings from unrolling
545 // aren't just exposing dead control flows, but actual reduced dynamic
546 // instructions due to the simplifications which we expect to occur after
547 // unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000548 int RolledDynamicCost = 0;
Chandler Carruth8c863752015-02-13 03:48:38 +0000549
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000550 // Ensure that we don't violate the loop structure invariants relied on by
551 // this analysis.
552 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
553 assert(L->isLCSSAForm(DT) &&
554 "Must have loops in LCSSA form to track live-out values.");
555
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000556 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
557
Chandler Carruth02156082015-05-22 17:41:35 +0000558 // Simulate execution of each iteration of the loop counting instructions,
559 // which would be simplified.
560 // Since the same load will take different values on different iterations,
561 // we literally have to go through all loop's iterations.
562 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000563 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000564
565 // Prepare for the iteration by collecting any simplified entry or backedge
566 // inputs.
567 for (Instruction &I : *L->getHeader()) {
568 auto *PHI = dyn_cast<PHINode>(&I);
569 if (!PHI)
570 break;
571
572 // The loop header PHI nodes must have exactly two input: one from the
573 // loop preheader and one from the loop latch.
574 assert(
575 PHI->getNumIncomingValues() == 2 &&
576 "Must have an incoming value only for the preheader and the latch.");
577
578 Value *V = PHI->getIncomingValueForBlock(
579 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
580 Constant *C = dyn_cast<Constant>(V);
581 if (Iteration != 0 && !C)
582 C = SimplifiedValues.lookup(V);
583 if (C)
584 SimplifiedInputValues.push_back({PHI, C});
585 }
586
587 // Now clear and re-populate the map for the next iteration.
Chandler Carruth02156082015-05-22 17:41:35 +0000588 SimplifiedValues.clear();
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000589 while (!SimplifiedInputValues.empty())
590 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
591
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000592 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, L, SE);
Chandler Carruthf174a152015-05-22 02:47:29 +0000593
Chandler Carruth02156082015-05-22 17:41:35 +0000594 BBWorklist.clear();
595 BBWorklist.insert(L->getHeader());
596 // Note that we *must not* cache the size, this loop grows the worklist.
597 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
598 BasicBlock *BB = BBWorklist[Idx];
Chandler Carruthf174a152015-05-22 02:47:29 +0000599
Chandler Carruth02156082015-05-22 17:41:35 +0000600 // Visit all instructions in the given basic block and try to simplify
601 // it. We don't change the actual IR, just count optimization
602 // opportunities.
603 for (Instruction &I : *BB) {
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000604 int InstCost = TTI.getUserCost(&I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000605
Chandler Carruth02156082015-05-22 17:41:35 +0000606 // Visit the instruction to analyze its loop cost after unrolling,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000607 // and if the visitor returns false, include this instruction in the
608 // unrolled cost.
609 if (!Analyzer.visit(I))
610 UnrolledCost += InstCost;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000611 else {
612 DEBUG(dbgs() << " " << I
613 << " would be simplified if loop is unrolled.\n");
614 (void)0;
615 }
Chandler Carruth9dabd142015-06-05 17:01:43 +0000616
617 // Also track this instructions expected cost when executing the rolled
618 // loop form.
619 RolledDynamicCost += InstCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000620
621 // If unrolled body turns out to be too big, bail out.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000622 if (UnrolledCost > MaxUnrolledLoopSize) {
623 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n"
624 << " UnrolledCost: " << UnrolledCost
625 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
626 << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000627 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000628 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000629 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000630
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000631 TerminatorInst *TI = BB->getTerminator();
632
633 // Add in the live successors by first checking whether we have terminator
634 // that may be simplified based on the values simplified by this call.
635 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
636 if (BI->isConditional()) {
637 if (Constant *SimpleCond =
638 SimplifiedValues.lookup(BI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000639 BasicBlock *Succ = nullptr;
640 // Just take the first successor if condition is undef
641 if (isa<UndefValue>(SimpleCond))
642 Succ = BI->getSuccessor(0);
643 else
644 Succ = BI->getSuccessor(
645 cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0);
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000646 if (L->contains(Succ))
647 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000648 continue;
649 }
650 }
651 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
652 if (Constant *SimpleCond =
653 SimplifiedValues.lookup(SI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000654 BasicBlock *Succ = nullptr;
655 // Just take the first successor if condition is undef
656 if (isa<UndefValue>(SimpleCond))
657 Succ = SI->getSuccessor(0);
658 else
Michael Zolotukhin9f06ef72015-07-29 18:10:33 +0000659 Succ = SI->findCaseValue(cast<ConstantInt>(SimpleCond))
660 .getCaseSuccessor();
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000661 if (L->contains(Succ))
662 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000663 continue;
664 }
665 }
666
Chandler Carruth02156082015-05-22 17:41:35 +0000667 // Add BB's successors to the worklist.
668 for (BasicBlock *Succ : successors(BB))
669 if (L->contains(Succ))
670 BBWorklist.insert(Succ);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000671 }
Chandler Carruth02156082015-05-22 17:41:35 +0000672
673 // If we found no optimization opportunities on the first iteration, we
674 // won't find them on later ones too.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000675 if (UnrolledCost == RolledDynamicCost) {
676 DEBUG(dbgs() << " No opportunities found.. exiting.\n"
677 << " UnrolledCost: " << UnrolledCost << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000678 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000679 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000680 }
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000681 DEBUG(dbgs() << "Analysis finished:\n"
682 << "UnrolledCost: " << UnrolledCost << ", "
683 << "RolledDynamicCost: " << RolledDynamicCost << "\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000684 return {{UnrolledCost, RolledDynamicCost}};
Chandler Carruth02156082015-05-22 17:41:35 +0000685}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000686
Dan Gohman49d08a52007-05-08 15:14:19 +0000687/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000688static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000689 bool &NotDuplicatable,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000690 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000691 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000692 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000693 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000694
Dan Gohman969e83a2009-10-31 14:54:17 +0000695 CodeMetrics Metrics;
Dan Gohman90071072008-06-22 20:18:58 +0000696 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohman969e83a2009-10-31 14:54:17 +0000697 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000698 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000699 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000700 NotDuplicatable = Metrics.notDuplicatable;
Andrew Trick279e7a62011-07-23 00:29:16 +0000701
Owen Anderson62ea1b72010-09-09 19:07:31 +0000702 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000703
Owen Anderson62ea1b72010-09-09 19:07:31 +0000704 // Don't allow an estimate of size zero. This would allows unrolling of loops
705 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000706 // not a problem for code quality. Also, the code using this size may assume
707 // that each loop has at least three instructions (likely a conditional
708 // branch, a comparison feeding that branch, and some kind of loop increment
709 // feeding that comparison instruction).
710 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000711
Owen Anderson62ea1b72010-09-09 19:07:31 +0000712 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000713}
714
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000715// Returns the loop hint metadata node with the given name (for example,
716// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
717// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000718static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
719 if (MDNode *LoopID = L->getLoopID())
720 return GetUnrollMetadata(LoopID, Name);
721 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000722}
723
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000724// Returns true if the loop has an unroll(full) pragma.
725static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000726 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000727}
728
Mark Heffernan89391542015-08-10 17:28:08 +0000729// Returns true if the loop has an unroll(enable) pragma. This metadata is used
730// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
731static bool HasUnrollEnablePragma(const Loop *L) {
732 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
733}
734
Eli Benderskyff903242014-06-16 23:53:02 +0000735// Returns true if the loop has an unroll(disable) pragma.
736static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000737 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000738}
739
Kevin Qin715b01e2015-03-09 06:14:18 +0000740// Returns true if the loop has an runtime unroll(disable) pragma.
741static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
742 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
743}
744
Eli Benderskyff903242014-06-16 23:53:02 +0000745// If loop has an unroll_count pragma return the (necessarily
746// positive) value from the pragma. Otherwise return 0.
747static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000748 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000749 if (MD) {
750 assert(MD->getNumOperands() == 2 &&
751 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000752 unsigned Count =
753 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000754 assert(Count >= 1 && "Unroll count must be positive.");
755 return Count;
756 }
757 return 0;
758}
759
Mark Heffernan053a6862014-07-18 21:04:33 +0000760// Remove existing unroll metadata and add unroll disable metadata to
761// indicate the loop has already been unrolled. This prevents a loop
762// from being unrolled more than is directed by a pragma if the loop
763// unrolling pass is run more than once (which it generally is).
764static void SetLoopAlreadyUnrolled(Loop *L) {
765 MDNode *LoopID = L->getLoopID();
766 if (!LoopID) return;
767
768 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000769 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000770 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000771 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000772 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
773 bool IsUnrollMetadata = false;
774 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
775 if (MD) {
776 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
777 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
778 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000779 if (!IsUnrollMetadata)
780 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000781 }
782
783 // Add unroll(disable) metadata to disable future unrolling.
784 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000785 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000786 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000787 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000788 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000789
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000790 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000791 // Set operand 0 to refer to the loop id itself.
792 NewLoopID->replaceOperandWith(0, NewLoopID);
793 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000794}
795
Chandler Carruth9dabd142015-06-05 17:01:43 +0000796bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold,
797 unsigned PercentDynamicCostSavedThreshold,
798 unsigned DynamicCostSavingsDiscount,
Sanjoy Dasad714b12015-06-06 05:24:10 +0000799 uint64_t UnrolledCost,
800 uint64_t RolledDynamicCost) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000801
802 if (Threshold == NoThreshold) {
803 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
804 return true;
805 }
806
Chandler Carruth9dabd142015-06-05 17:01:43 +0000807 if (UnrolledCost <= Threshold) {
808 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
809 << UnrolledCost << "<" << Threshold << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000810 return true;
811 }
812
Chandler Carruth9dabd142015-06-05 17:01:43 +0000813 assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
814 assert(RolledDynamicCost >= UnrolledCost &&
815 "Cannot have a higher unrolled cost than a rolled cost!");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000816
Chandler Carruth9dabd142015-06-05 17:01:43 +0000817 // Compute the percentage of the dynamic cost in the rolled form that is
818 // saved when unrolled. If unrolling dramatically reduces the estimated
819 // dynamic cost of the loop, we use a higher threshold to allow more
820 // unrolling.
821 unsigned PercentDynamicCostSaved =
822 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
823
824 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
825 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
826 (int64_t)Threshold) {
827 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
828 "expected dynamic cost by " << PercentDynamicCostSaved
829 << "% (threshold: " << PercentDynamicCostSavedThreshold
830 << "%)\n"
831 << " and the unrolled cost (" << UnrolledCost
832 << ") is less than the max threshold ("
833 << DynamicCostSavingsDiscount << ").\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000834 return true;
835 }
836
837 DEBUG(dbgs() << " Too large to fully unroll:\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000838 DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
839 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
840 DEBUG(dbgs() << " Percent cost saved threshold: "
841 << PercentDynamicCostSavedThreshold << "%\n");
842 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
843 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
844 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
845 << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000846 return false;
847}
848
Eli Benderskyff903242014-06-16 23:53:02 +0000849unsigned LoopUnroll::selectUnrollCount(
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000850 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000851 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
852 bool &SetExplicitly) {
853 SetExplicitly = true;
854
855 // User-specified count (either as a command-line option or
856 // constructor parameter) has highest precedence.
857 unsigned Count = UserCount ? CurrentCount : 0;
858
859 // If there is no user-specified count, unroll pragmas have the next
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000860 // highest precedence.
Eli Benderskyff903242014-06-16 23:53:02 +0000861 if (Count == 0) {
862 if (PragmaCount) {
863 Count = PragmaCount;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000864 } else if (PragmaFullUnroll) {
Eli Benderskyff903242014-06-16 23:53:02 +0000865 Count = TripCount;
866 }
867 }
868
869 if (Count == 0)
870 Count = UP.Count;
871
872 if (Count == 0) {
873 SetExplicitly = false;
874 if (TripCount == 0)
875 // Runtime trip count.
876 Count = UnrollRuntimeCount;
877 else
878 // Conservative heuristic: if we know the trip count, see if we can
879 // completely unroll (subject to the threshold, checked below); otherwise
880 // try to find greatest modulo of the trip count which is still under
881 // threshold value.
882 Count = TripCount;
883 }
884 if (TripCount && Count > TripCount)
885 return TripCount;
886 return Count;
887}
888
Devang Patel9779e562007-03-07 01:38:05 +0000889bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000890 if (skipOptnoneFunction(L))
891 return false;
892
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000893 Function &F = *L->getHeader()->getParent();
894
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000895 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000896 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Andrew Trick2b6860f2011-08-11 23:36:16 +0000897 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000898 const TargetTransformInfo &TTI =
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000899 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000900 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000901
Dan Gohman2e1f8042007-05-08 15:19:19 +0000902 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000903 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000904 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000905
906 if (HasUnrollDisablePragma(L)) {
907 return false;
908 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000909 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Mark Heffernan89391542015-08-10 17:28:08 +0000910 bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000911 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernan89391542015-08-10 17:28:08 +0000912 bool HasPragma = PragmaFullUnroll || PragmaEnableUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000913
Hal Finkel8f2e7002013-09-11 19:25:43 +0000914 TargetTransformInfo::UnrollingPreferences UP;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000915 getUnrollingPreferences(L, TTI, UP);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000916
Andrew Trick2b6860f2011-08-11 23:36:16 +0000917 // Find trip count and trip multiple if count is not available
918 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000919 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000920 // If there are multiple exiting blocks but one of them is the latch, use the
921 // latch for the trip count estimation. Otherwise insist on a single exiting
922 // block for the trip count estimation.
923 BasicBlock *ExitingBlock = L->getLoopLatch();
924 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
925 ExitingBlock = L->getExitingBlock();
926 if (ExitingBlock) {
927 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
928 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000929 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000930
Eli Benderskyff903242014-06-16 23:53:02 +0000931 // Select an initial unroll count. This may be reduced later based
932 // on size thresholds.
933 bool CountSetExplicitly;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000934 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
935 PragmaCount, UP, CountSetExplicitly);
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000936
Eli Benderskyff903242014-06-16 23:53:02 +0000937 unsigned NumInlineCandidates;
938 bool notDuplicatable;
939 unsigned LoopSize =
Chandler Carruth66b31302015-01-04 12:03:27 +0000940 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000941 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Hal Finkel38dd5902015-01-10 00:30:55 +0000942
943 // When computing the unrolled size, note that the conditional branch on the
944 // backedge and the comparison feeding it are not replicated like the rest of
945 // the loop body (which is why 2 is subtracted).
946 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000947 if (notDuplicatable) {
948 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
949 << " instructions.\n");
950 return false;
951 }
952 if (NumInlineCandidates != 0) {
953 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
954 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000955 }
956
Eli Benderskyff903242014-06-16 23:53:02 +0000957 unsigned Threshold, PartialThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000958 unsigned PercentDynamicCostSavedThreshold;
959 unsigned DynamicCostSavingsDiscount;
Mark Heffernan89391542015-08-10 17:28:08 +0000960 // Only use the high pragma threshold when we have a target unroll factor such
961 // as with "#pragma unroll N" or a pragma indicating full unrolling and the
962 // trip count is known. Otherwise we rely on the standard threshold to
963 // heuristically select a reasonable unroll count.
964 bool UsePragmaThreshold =
965 PragmaCount > 0 ||
966 ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount != 0);
967
968 selectThresholds(L, UsePragmaThreshold, UP, Threshold, PartialThreshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000969 PercentDynamicCostSavedThreshold,
970 DynamicCostSavingsDiscount);
Benjamin Kramer9130cb82014-05-04 19:12:38 +0000971
Eli Benderskyff903242014-06-16 23:53:02 +0000972 // Given Count, TripCount and thresholds determine the type of
973 // unrolling which is to be performed.
974 enum { Full = 0, Partial = 1, Runtime = 2 };
975 int Unrolling;
976 if (TripCount && Count == TripCount) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000977 Unrolling = Partial;
978 // If the loop is really small, we don't need to run an expensive analysis.
Chandler Carruth9dabd142015-06-05 17:01:43 +0000979 if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount,
980 UnrolledSize, UnrolledSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000981 Unrolling = Full;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000982 } else {
983 // The loop isn't that small, but we still can fully unroll it if that
984 // helps to remove a significant number of instructions.
985 // To check that, run additional analysis on the loop.
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000986 if (Optional<EstimatedUnrollCost> Cost =
987 analyzeLoopUnrollCost(L, TripCount, DT, *SE, TTI,
988 Threshold + DynamicCostSavingsDiscount))
Chandler Carruth9dabd142015-06-05 17:01:43 +0000989 if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold,
990 DynamicCostSavingsDiscount, Cost->UnrolledCost,
991 Cost->RolledDynamicCost)) {
Chandler Carruth02156082015-05-22 17:41:35 +0000992 Unrolling = Full;
993 }
Dan Gohman2980d9d2007-05-11 20:53:41 +0000994 }
Eli Benderskyff903242014-06-16 23:53:02 +0000995 } else if (TripCount && Count < TripCount) {
996 Unrolling = Partial;
997 } else {
998 Unrolling = Runtime;
999 }
1000
1001 // Reduce count based on the type of unrolling and the threshold values.
1002 unsigned OriginalCount = Count;
Mark Heffernan89391542015-08-10 17:28:08 +00001003 bool AllowRuntime = PragmaEnableUnroll || (PragmaCount > 0) ||
1004 (UserRuntime ? CurrentRuntime : UP.Runtime);
Mark Heffernand7ebc242015-07-13 18:26:27 +00001005 // Don't unroll a runtime trip count loop with unroll full pragma.
1006 if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
Kevin Qin715b01e2015-03-09 06:14:18 +00001007 AllowRuntime = false;
1008 }
Eli Benderskyff903242014-06-16 23:53:02 +00001009 if (Unrolling == Partial) {
Mark Heffernan89391542015-08-10 17:28:08 +00001010 bool AllowPartial = PragmaEnableUnroll ||
1011 (UserAllowPartial ? CurrentAllowPartial : UP.Partial);
Eli Benderskyff903242014-06-16 23:53:02 +00001012 if (!AllowPartial && !CountSetExplicitly) {
1013 DEBUG(dbgs() << " will not try to unroll partially because "
1014 << "-unroll-allow-partial not given\n");
1015 return false;
1016 }
1017 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
1018 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Hal Finkel38dd5902015-01-10 00:30:55 +00001019 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
Eli Benderskyff903242014-06-16 23:53:02 +00001020 while (Count != 0 && TripCount % Count != 0)
1021 Count--;
1022 }
1023 } else if (Unrolling == Runtime) {
1024 if (!AllowRuntime && !CountSetExplicitly) {
1025 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
1026 << "-unroll-runtime not given\n");
1027 return false;
1028 }
1029 // Reduce unroll count to be the largest power-of-two factor of
1030 // the original count which satisfies the threshold limit.
1031 while (Count != 0 && UnrolledSize > PartialThreshold) {
1032 Count >>= 1;
Hal Finkel38dd5902015-01-10 00:30:55 +00001033 UnrolledSize = (LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +00001034 }
1035 if (Count > UP.MaxCount)
1036 Count = UP.MaxCount;
1037 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
1038 }
1039
1040 if (HasPragma) {
Mark Heffernan9e112442014-07-23 20:05:44 +00001041 if (PragmaCount != 0)
1042 // If loop has an unroll count pragma mark loop as unrolled to prevent
1043 // unrolling beyond that requested by the pragma.
1044 SetLoopAlreadyUnrolled(L);
Mark Heffernan053a6862014-07-18 21:04:33 +00001045
Eli Benderskyff903242014-06-16 23:53:02 +00001046 // Emit optimization remarks if we are unable to unroll the loop
1047 // as directed by a pragma.
1048 DebugLoc LoopLoc = L->getStartLoc();
1049 Function *F = Header->getParent();
1050 LLVMContext &Ctx = F->getContext();
Mark Heffernan89391542015-08-10 17:28:08 +00001051 if ((PragmaCount > 0) && Count != OriginalCount) {
Eli Benderskyff903242014-06-16 23:53:02 +00001052 emitOptimizationRemarkMissed(
1053 Ctx, DEBUG_TYPE, *F, LoopLoc,
1054 "Unable to unroll loop the number of times directed by "
1055 "unroll_count pragma because unrolled size is too large.");
Mark Heffernan89391542015-08-10 17:28:08 +00001056 } else if (PragmaFullUnroll && !TripCount) {
1057 emitOptimizationRemarkMissed(
1058 Ctx, DEBUG_TYPE, *F, LoopLoc,
1059 "Unable to fully unroll loop as directed by unroll(full) pragma "
1060 "because loop has a runtime trip count.");
1061 } else if (PragmaEnableUnroll && Count != TripCount && Count < 2) {
1062 emitOptimizationRemarkMissed(
1063 Ctx, DEBUG_TYPE, *F, LoopLoc,
1064 "Unable to unroll loop as directed by unroll(enable) pragma because "
1065 "unrolled size is too large.");
1066 } else if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
1067 Count != TripCount) {
1068 emitOptimizationRemarkMissed(
1069 Ctx, DEBUG_TYPE, *F, LoopLoc,
1070 "Unable to fully unroll loop as directed by unroll pragma because "
1071 "unrolled size is too large.");
Eli Benderskyff903242014-06-16 23:53:02 +00001072 }
1073 }
1074
1075 if (Unrolling != Full && Count < 2) {
1076 // Partial unrolling by 1 is a nop. For full unrolling, a factor
1077 // of 1 makes sense because loop control can be eliminated.
1078 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001079 }
1080
Dan Gohman3dc2d922008-05-14 00:24:14 +00001081 // Unroll the loop.
Sanjoy Dase178f462015-04-14 03:20:38 +00001082 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
1083 TripMultiple, LI, this, &LPM, &AC))
Dan Gohman3dc2d922008-05-14 00:24:14 +00001084 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001085
Chris Lattner946b2552004-04-18 05:20:17 +00001086 return true;
1087}