blob: bd9da14f66931e4835c0f18a9c84a5fb3ed9b68a [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 Carruth66b31302015-01-04 12:03:27 +000016#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000017#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/Analysis/LoopPass.h"
Dan Gohman0141c132010-07-26 18:11:16 +000019#include "llvm/Analysis/ScalarEvolution.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000020#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Eli Benderskyff903242014-06-16 23:53:02 +000023#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000026#include "llvm/IR/Metadata.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000029#include "llvm/Support/raw_ostream.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000030#include "llvm/Transforms/Utils/UnrollLoop.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000031#include "llvm/IR/InstVisitor.h"
32#include "llvm/Analysis/InstructionSimplify.h"
Duncan Sands67933e62008-05-16 09:30:00 +000033#include <climits>
Chris Lattner946b2552004-04-18 05:20:17 +000034
Dan Gohman3dc2d922008-05-14 00:24:14 +000035using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000036
Chandler Carruth964daaa2014-04-22 02:55:47 +000037#define DEBUG_TYPE "loop-unroll"
38
Dan Gohmand78c4002008-05-13 00:00:25 +000039static cl::opt<unsigned>
Owen Andersond85c9cc2010-09-10 17:57:00 +000040UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
Dan Gohmand78c4002008-05-13 00:00:25 +000041 cl::desc("The cut-off point for automatic loop unrolling"));
42
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000043static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
44 "unroll-max-iteration-count-to-analyze", cl::init(1000), cl::Hidden,
45 cl::desc("Don't allow loop unrolling to simulate more than this number of"
46 "iterations when checking full unroll profitability"));
47
Dan Gohmand78c4002008-05-13 00:00:25 +000048static cl::opt<unsigned>
49UnrollCount("unroll-count", cl::init(0), cl::Hidden,
Eli Benderskyff903242014-06-16 23:53:02 +000050 cl::desc("Use this unroll count for all loops including those with "
51 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +000052
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000053static cl::opt<bool>
54UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
55 cl::desc("Allows loops to be partially unrolled until "
56 "-unroll-threshold loop size is reached."));
57
Andrew Trickd04d15292011-12-09 06:19:40 +000058static cl::opt<bool>
59UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
60 cl::desc("Unroll loops with run-time trip counts"));
61
Eli Benderskyff903242014-06-16 23:53:02 +000062static cl::opt<unsigned>
63PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
Mark Heffernane6b4ba12014-07-23 17:31:37 +000064 cl::desc("Unrolled size limit for loops with an unroll(full) or "
Eli Benderskyff903242014-06-16 23:53:02 +000065 "unroll_count pragma."));
66
Chris Lattner79a42ac2006-12-19 21:40:18 +000067namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000068 class LoopUnroll : public LoopPass {
Chris Lattner946b2552004-04-18 05:20:17 +000069 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000070 static char ID; // Pass ID, replacement for typeid
Hal Finkel081eaef2013-11-05 00:08:03 +000071 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
Chris Lattner35a65b22011-04-14 02:27:25 +000072 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
73 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
Junjie Gu7c3b4592011-04-13 16:15:29 +000074 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
Hal Finkel081eaef2013-11-05 00:08:03 +000075 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
Junjie Gu7c3b4592011-04-13 16:15:29 +000076
77 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000078 UserAllowPartial = (P != -1) ||
79 (UnrollAllowPartial.getNumOccurrences() > 0);
Hal Finkel081eaef2013-11-05 00:08:03 +000080 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000081 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
Andrew Trick279e7a62011-07-23 00:29:16 +000082
Owen Anderson6c18d1a2010-10-19 17:21:58 +000083 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
84 }
Devang Patel09f162c2007-05-01 21:15:47 +000085
Dan Gohman2980d9d2007-05-11 20:53:41 +000086 /// A magic value for use with the Threshold parameter to indicate
87 /// that the loop unroll should be performed regardless of how much
88 /// code expansion would result.
89 static const unsigned NoThreshold = UINT_MAX;
Andrew Trick279e7a62011-07-23 00:29:16 +000090
Owen Andersona4d9c782010-09-07 23:15:30 +000091 // Threshold to use when optsize is specified (and there is no
92 // explicit -unroll-threshold).
93 static const unsigned OptSizeUnrollThreshold = 50;
Andrew Trick279e7a62011-07-23 00:29:16 +000094
Andrew Trickd04d15292011-12-09 06:19:40 +000095 // Default unroll count for loops with run-time trip count if
96 // -unroll-count is not set
97 static const unsigned UnrollRuntimeCount = 8;
98
Junjie Gu7c3b4592011-04-13 16:15:29 +000099 unsigned CurrentCount;
Owen Andersona4d9c782010-09-07 23:15:30 +0000100 unsigned CurrentThreshold;
Junjie Gu7c3b4592011-04-13 16:15:29 +0000101 bool CurrentAllowPartial;
Hal Finkel081eaef2013-11-05 00:08:03 +0000102 bool CurrentRuntime;
Hal Finkel8f2e7002013-09-11 19:25:43 +0000103 bool UserCount; // CurrentCount is user-specified.
Junjie Gu7c3b4592011-04-13 16:15:29 +0000104 bool UserThreshold; // CurrentThreshold is user-specified.
Hal Finkel8f2e7002013-09-11 19:25:43 +0000105 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
Hal Finkel081eaef2013-11-05 00:08:03 +0000106 bool UserRuntime; // CurrentRuntime is user-specified.
Dan Gohman2980d9d2007-05-11 20:53:41 +0000107
Craig Topper3e4c6972014-03-05 09:10:37 +0000108 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner946b2552004-04-18 05:20:17 +0000109
110 /// This transformation requires natural loop information & requires that
111 /// loop preheaders be inserted into the CFG...
112 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000113 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000114 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000115 AU.addRequired<LoopInfoWrapperPass>();
116 AU.addPreserved<LoopInfoWrapperPass>();
Dan Gohman0141c132010-07-26 18:11:16 +0000117 AU.addRequiredID(LoopSimplifyID);
118 AU.addPreservedID(LoopSimplifyID);
119 AU.addRequiredID(LCSSAID);
120 AU.addPreservedID(LCSSAID);
Andrew Trick4d0040b2011-08-10 04:29:49 +0000121 AU.addRequired<ScalarEvolution>();
Chris Lattnerd6f46b82010-08-29 17:21:35 +0000122 AU.addPreserved<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000123 AU.addRequired<TargetTransformInfoWrapperPass>();
Devang Patelf94b9822008-07-03 07:04:22 +0000124 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
125 // If loop unroll does not preserve dom info then LCSSA pass on next
126 // loop will receive invalid dom info.
127 // For now, recreate dom info, if loop is unrolled.
Chandler Carruth73523022014-01-13 13:07:17 +0000128 AU.addPreserved<DominatorTreeWrapperPass>();
Chris Lattner946b2552004-04-18 05:20:17 +0000129 }
Eli Benderskyff903242014-06-16 23:53:02 +0000130
131 // Fill in the UnrollingPreferences parameter with values from the
132 // TargetTransformationInfo.
Chandler Carruth21fc1952015-02-01 14:37:03 +0000133 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
Eli Benderskyff903242014-06-16 23:53:02 +0000134 TargetTransformInfo::UnrollingPreferences &UP) {
135 UP.Threshold = CurrentThreshold;
136 UP.OptSizeThreshold = OptSizeUnrollThreshold;
137 UP.PartialThreshold = CurrentThreshold;
138 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
139 UP.Count = CurrentCount;
140 UP.MaxCount = UINT_MAX;
141 UP.Partial = CurrentAllowPartial;
142 UP.Runtime = CurrentRuntime;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000143 TTI.getUnrollingPreferences(L, UP);
Eli Benderskyff903242014-06-16 23:53:02 +0000144 }
145
146 // Select and return an unroll count based on parameters from
147 // user, unroll preferences, unroll pragmas, or a heuristic.
148 // SetExplicitly is set to true if the unroll count is is set by
149 // the user or a pragma rather than selected heuristically.
150 unsigned
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000151 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000152 unsigned PragmaCount,
153 const TargetTransformInfo::UnrollingPreferences &UP,
154 bool &SetExplicitly);
155
Eli Benderskyff903242014-06-16 23:53:02 +0000156 // Select threshold values used to limit unrolling based on a
157 // total unrolled size. Parameters Threshold and PartialThreshold
158 // are set to the maximum unrolled size for fully and partially
159 // unrolled loops respectively.
160 void selectThresholds(const Loop *L, bool HasPragma,
161 const TargetTransformInfo::UnrollingPreferences &UP,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000162 unsigned &Threshold, unsigned &PartialThreshold,
163 unsigned NumberOfSimplifiedInstructions) {
Eli Benderskyff903242014-06-16 23:53:02 +0000164 // Determine the current unrolling threshold. While this is
165 // normally set from UnrollThreshold, it is overridden to a
166 // smaller value if the current function is marked as
167 // optimize-for-size, and the unroll threshold was not user
168 // specified.
169 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
170 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
171 if (!UserThreshold &&
172 L->getHeader()->getParent()->getAttributes().
173 hasAttribute(AttributeSet::FunctionIndex,
174 Attribute::OptimizeForSize)) {
175 Threshold = UP.OptSizeThreshold;
176 PartialThreshold = UP.PartialOptSizeThreshold;
177 }
178 if (HasPragma) {
179 // If the loop has an unrolling pragma, we want to be more
180 // aggressive with unrolling limits. Set thresholds to at
181 // least the PragmaTheshold value which is larger than the
182 // default limits.
183 if (Threshold != NoThreshold)
184 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
185 if (PartialThreshold != NoThreshold)
186 PartialThreshold =
187 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
188 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000189 Threshold += NumberOfSimplifiedInstructions;
Eli Benderskyff903242014-06-16 23:53:02 +0000190 }
Chris Lattner946b2552004-04-18 05:20:17 +0000191 };
Chris Lattner946b2552004-04-18 05:20:17 +0000192}
193
Dan Gohmand78c4002008-05-13 00:00:25 +0000194char LoopUnroll::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000195INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000196INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000197INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000198INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000199INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
200INITIALIZE_PASS_DEPENDENCY(LCSSA)
Devang Patel88b4fa22011-10-19 23:56:07 +0000201INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000202INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000203
Hal Finkel081eaef2013-11-05 00:08:03 +0000204Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
205 int Runtime) {
206 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
Junjie Gu7c3b4592011-04-13 16:15:29 +0000207}
Chris Lattner946b2552004-04-18 05:20:17 +0000208
Hal Finkel86b30642014-03-31 23:23:51 +0000209Pass *llvm::createSimpleLoopUnrollPass() {
210 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
211}
212
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000213static bool IsLoadFromConstantInitializer(Value *V) {
214 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
215 if (GV->isConstant() && GV->hasDefinitiveInitializer())
216 return GV->getInitializer();
217 return false;
218}
219
220struct FindConstantPointers {
221 bool LoadCanBeConstantFolded;
222 bool IndexIsConstant;
223 APInt Step;
224 APInt StartValue;
225 Value *BaseAddress;
226 const Loop *L;
227 ScalarEvolution &SE;
228 FindConstantPointers(const Loop *loop, ScalarEvolution &SE)
229 : LoadCanBeConstantFolded(true), IndexIsConstant(true), L(loop), SE(SE) {}
230
231 bool follow(const SCEV *S) {
232 if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) {
233 // We've reached the leaf node of SCEV, it's most probably just a
234 // variable. Now it's time to see if it corresponds to a global constant
235 // global (in which case we can eliminate the load), or not.
236 BaseAddress = SC->getValue();
237 LoadCanBeConstantFolded =
238 IndexIsConstant && IsLoadFromConstantInitializer(BaseAddress);
239 return false;
240 }
241 if (isa<SCEVConstant>(S))
242 return true;
243 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
244 // If the current SCEV expression is AddRec, and its loop isn't the loop
245 // we are about to unroll, then we won't get a constant address after
246 // unrolling, and thus, won't be able to eliminate the load.
247 if (AR->getLoop() != L)
248 return IndexIsConstant = false;
249 // If the step isn't constant, we won't get constant addresses in unrolled
250 // version. Bail out.
251 if (const SCEVConstant *StepSE =
252 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
253 Step = StepSE->getValue()->getValue();
254 else
255 return IndexIsConstant = false;
256
257 return IndexIsConstant;
258 }
259 // If Result is true, continue traversal.
260 // Otherwise, we have found something that prevents us from (possible) load
261 // elimination.
262 return IndexIsConstant;
263 }
264 bool isDone() const { return !IndexIsConstant; }
265};
266
267// This class is used to get an estimate of the optimization effects that we
268// could get from complete loop unrolling. It comes from the fact that some
269// loads might be replaced with concrete constant values and that could trigger
270// a chain of instruction simplifications.
271//
272// E.g. we might have:
273// int a[] = {0, 1, 0};
274// v = 0;
275// for (i = 0; i < 3; i ++)
276// v += b[i]*a[i];
277// If we completely unroll the loop, we would get:
278// v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
279// Which then will be simplified to:
280// v = b[0]* 0 + b[1]* 1 + b[2]* 0
281// And finally:
282// v = b[1]
283class UnrollAnalyzer : public InstVisitor<UnrollAnalyzer, bool> {
284 typedef InstVisitor<UnrollAnalyzer, bool> Base;
285 friend class InstVisitor<UnrollAnalyzer, bool>;
286
287 const Loop *L;
288 unsigned TripCount;
289 ScalarEvolution &SE;
290 const TargetTransformInfo &TTI;
291 unsigned NumberOfOptimizedInstructions;
292
293 DenseMap<Value *, Constant *> SimplifiedValues;
294 DenseMap<LoadInst *, Value *> LoadBaseAddresses;
295 SmallPtrSet<Instruction *, 32> CountedInsns;
296
297 // Provide base case for our instruction visit.
298 bool visitInstruction(Instruction &I) { return false; };
299 // TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt,
300 // FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select,
301 // ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue.
302 //
303 // Probaly it's worth to hoist the code for estimating the simplifications
304 // effects to a separate class, since we have a very similar code in
305 // InlineCost already.
306 bool visitBinaryOperator(BinaryOperator &I) {
307 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
308 if (!isa<Constant>(LHS))
309 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
310 LHS = SimpleLHS;
311 if (!isa<Constant>(RHS))
312 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
313 RHS = SimpleRHS;
314 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS);
315
316 if (SimpleV && CountedInsns.insert(&I).second)
317 NumberOfOptimizedInstructions += TTI.getUserCost(&I);
318
319 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
320 SimplifiedValues[&I] = C;
321 return true;
322 }
323 return false;
324 }
325
326 Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) {
327 if (!LI)
328 return nullptr;
329 Value *BaseAddr = LoadBaseAddresses[LI];
330 if (!BaseAddr)
331 return nullptr;
332
333 auto GV = dyn_cast<GlobalVariable>(BaseAddr);
334 if (!GV)
335 return nullptr;
336
337 ConstantDataSequential *CDS =
338 dyn_cast<ConstantDataSequential>(GV->getInitializer());
339 if (!CDS)
340 return nullptr;
341
342 const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr);
343 const SCEV *S = SE.getSCEV(LI->getPointerOperand());
344 const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);
345
346 APInt StepC, StartC;
347 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);
348 if (!AR)
349 return nullptr;
350
351 if (const SCEVConstant *StepSE =
352 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
353 StepC = StepSE->getValue()->getValue();
354 else
355 return nullptr;
356
357 if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart()))
358 StartC = StartSE->getValue()->getValue();
359 else
360 return nullptr;
361
362 unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
363 unsigned Start = StartC.getLimitedValue();
364 unsigned Step = StepC.getLimitedValue();
365
366 unsigned Index = (Start + Step * Iteration) / ElemSize;
367 if (Index >= CDS->getNumElements())
368 return nullptr;
369
370 Constant *CV = CDS->getElementAsConstant(Index);
371
372 return CV;
373 }
374
375public:
376 UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
377 const TargetTransformInfo &TTI)
378 : L(L), TripCount(TripCount), SE(SE), TTI(TTI),
379 NumberOfOptimizedInstructions(0) {}
380
381 // Visit all loads the loop L, and for those that, after complete loop
382 // unrolling, would have a constant address and it will point to a known
383 // constant initializer, record its base address for future use. It is used
384 // when we estimate number of potentially simplified instructions.
385 void FindConstFoldableLoads() {
386 for (auto BB : L->getBlocks()) {
387 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
388 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
389 if (!LI->isSimple())
390 continue;
391 Value *AddrOp = LI->getPointerOperand();
392 const SCEV *S = SE.getSCEV(AddrOp);
393 FindConstantPointers Visitor(L, SE);
394 SCEVTraversal<FindConstantPointers> T(Visitor);
395 T.visitAll(S);
396 if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) {
397 LoadBaseAddresses[LI] = Visitor.BaseAddress;
398 }
399 }
400 }
401 }
402 }
403
404 // Given a list of loads that could be constant-folded (LoadBaseAddresses),
405 // estimate number of optimized instructions after substituting the concrete
406 // values for the given Iteration.
407 // Fill in SimplifiedInsns map for future use in DCE-estimation.
408 unsigned EstimateNumberOfSimplifiedInsns(unsigned Iteration) {
409 SmallVector<Instruction *, 8> Worklist;
410 SimplifiedValues.clear();
411 CountedInsns.clear();
412
413 NumberOfOptimizedInstructions = 0;
414 // We start by adding all loads to the worklist.
415 for (auto LoadDescr : LoadBaseAddresses) {
416 LoadInst *LI = LoadDescr.first;
417 SimplifiedValues[LI] = computeLoadValue(LI, Iteration);
418 if (CountedInsns.insert(LI).second)
419 NumberOfOptimizedInstructions += TTI.getUserCost(LI);
420
421 for (auto U : LI->users()) {
422 Instruction *UI = dyn_cast<Instruction>(U);
423 if (!UI)
424 continue;
425 if (!L->contains(UI))
426 continue;
427 Worklist.push_back(UI);
428 }
429 }
430
431 // And then we try to simplify every user of every instruction from the
432 // worklist. If we do simplify a user, add it to the worklist to process
433 // its users as well.
434 while (!Worklist.empty()) {
435 Instruction *I = Worklist.pop_back_val();
436 if (!visit(I))
437 continue;
438 for (auto U : I->users()) {
439 Instruction *UI = dyn_cast<Instruction>(U);
440 if (!UI)
441 continue;
442 if (!L->contains(UI))
443 continue;
444 Worklist.push_back(UI);
445 }
446 }
447 return NumberOfOptimizedInstructions;
448 }
449
450 // Given a list of potentially simplifed instructions, estimate number of
451 // instructions that would become dead if we do perform the simplification.
452 unsigned EstimateNumberOfDeadInsns() {
453 NumberOfOptimizedInstructions = 0;
454 SmallVector<Instruction *, 8> Worklist;
455 DenseMap<Instruction *, bool> DeadInstructions;
456 // Start by initializing worklist with simplified instructions.
457 for (auto Folded : SimplifiedValues) {
458 if (auto FoldedInsn = dyn_cast<Instruction>(Folded.first)) {
459 Worklist.push_back(FoldedInsn);
460 DeadInstructions[FoldedInsn] = true;
461 }
462 }
463 // If a definition of an insn is only used by simplified or dead
464 // instructions, it's also dead. Check defs of all instructions from the
465 // worklist.
466 while (!Worklist.empty()) {
467 Instruction *FoldedInsn = Worklist.pop_back_val();
468 for (Value *Op : FoldedInsn->operands()) {
469 if (auto I = dyn_cast<Instruction>(Op)) {
470 if (!L->contains(I))
471 continue;
472 if (SimplifiedValues[I])
473 continue; // This insn has been counted already.
474 if (I->getNumUses() == 0)
475 continue;
476 bool AllUsersFolded = true;
477 for (auto U : I->users()) {
478 Instruction *UI = dyn_cast<Instruction>(U);
479 if (!SimplifiedValues[UI] && !DeadInstructions[UI]) {
480 AllUsersFolded = false;
481 break;
482 }
483 }
484 if (AllUsersFolded) {
485 NumberOfOptimizedInstructions += TTI.getUserCost(I);
486 Worklist.push_back(I);
487 DeadInstructions[I] = true;
488 }
489 }
490 }
491 }
492 return NumberOfOptimizedInstructions;
493 }
494};
495
496// Complete loop unrolling can make some loads constant, and we need to know if
497// that would expose any further optimization opportunities.
498// This routine estimates this optimization effect and returns the number of
499// instructions, that potentially might be optimized away.
500static unsigned
501ApproximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE,
502 unsigned TripCount,
503 const TargetTransformInfo &TTI) {
504 if (!TripCount)
505 return 0;
506
507 UnrollAnalyzer UA(L, TripCount, SE, TTI);
508 UA.FindConstFoldableLoads();
509
510 // Estimate number of instructions, that could be simplified if we replace a
511 // load with the corresponding constant. Since the same load will take
512 // different values on different iterations, we have to go through all loop's
513 // iterations here. To limit ourselves here, we check only first N
514 // iterations, and then scale the found number, if necessary.
515 unsigned IterationsNumberForEstimate =
516 std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount);
517 unsigned NumberOfOptimizedInstructions = 0;
518 for (unsigned i = 0; i < IterationsNumberForEstimate; ++i) {
519 NumberOfOptimizedInstructions += UA.EstimateNumberOfSimplifiedInsns(i);
520 NumberOfOptimizedInstructions += UA.EstimateNumberOfDeadInsns();
521 }
522 NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate;
523
524 return NumberOfOptimizedInstructions;
525}
526
Dan Gohman49d08a52007-05-08 15:14:19 +0000527/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000528static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000529 bool &NotDuplicatable,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000530 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000531 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000532 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000533 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000534
Dan Gohman969e83a2009-10-31 14:54:17 +0000535 CodeMetrics Metrics;
Dan Gohman90071072008-06-22 20:18:58 +0000536 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohman969e83a2009-10-31 14:54:17 +0000537 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000538 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000539 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000540 NotDuplicatable = Metrics.notDuplicatable;
Andrew Trick279e7a62011-07-23 00:29:16 +0000541
Owen Anderson62ea1b72010-09-09 19:07:31 +0000542 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000543
Owen Anderson62ea1b72010-09-09 19:07:31 +0000544 // Don't allow an estimate of size zero. This would allows unrolling of loops
545 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000546 // not a problem for code quality. Also, the code using this size may assume
547 // that each loop has at least three instructions (likely a conditional
548 // branch, a comparison feeding that branch, and some kind of loop increment
549 // feeding that comparison instruction).
550 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000551
Owen Anderson62ea1b72010-09-09 19:07:31 +0000552 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000553}
554
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000555// Returns the loop hint metadata node with the given name (for example,
556// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
557// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000558static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
559 if (MDNode *LoopID = L->getLoopID())
560 return GetUnrollMetadata(LoopID, Name);
561 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000562}
563
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000564// Returns true if the loop has an unroll(full) pragma.
565static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000566 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000567}
568
569// Returns true if the loop has an unroll(disable) pragma.
570static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000571 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000572}
573
574// If loop has an unroll_count pragma return the (necessarily
575// positive) value from the pragma. Otherwise return 0.
576static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000577 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000578 if (MD) {
579 assert(MD->getNumOperands() == 2 &&
580 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000581 unsigned Count =
582 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000583 assert(Count >= 1 && "Unroll count must be positive.");
584 return Count;
585 }
586 return 0;
587}
588
Mark Heffernan053a6862014-07-18 21:04:33 +0000589// Remove existing unroll metadata and add unroll disable metadata to
590// indicate the loop has already been unrolled. This prevents a loop
591// from being unrolled more than is directed by a pragma if the loop
592// unrolling pass is run more than once (which it generally is).
593static void SetLoopAlreadyUnrolled(Loop *L) {
594 MDNode *LoopID = L->getLoopID();
595 if (!LoopID) return;
596
597 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000598 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000599 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000600 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000601 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
602 bool IsUnrollMetadata = false;
603 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
604 if (MD) {
605 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
606 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
607 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000608 if (!IsUnrollMetadata)
609 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000610 }
611
612 // Add unroll(disable) metadata to disable future unrolling.
613 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000614 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000615 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000616 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000617 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000618
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000619 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000620 // Set operand 0 to refer to the loop id itself.
621 NewLoopID->replaceOperandWith(0, NewLoopID);
622 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000623}
624
Eli Benderskyff903242014-06-16 23:53:02 +0000625unsigned LoopUnroll::selectUnrollCount(
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000626 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000627 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
628 bool &SetExplicitly) {
629 SetExplicitly = true;
630
631 // User-specified count (either as a command-line option or
632 // constructor parameter) has highest precedence.
633 unsigned Count = UserCount ? CurrentCount : 0;
634
635 // If there is no user-specified count, unroll pragmas have the next
636 // highest precendence.
637 if (Count == 0) {
638 if (PragmaCount) {
639 Count = PragmaCount;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000640 } else if (PragmaFullUnroll) {
Eli Benderskyff903242014-06-16 23:53:02 +0000641 Count = TripCount;
642 }
643 }
644
645 if (Count == 0)
646 Count = UP.Count;
647
648 if (Count == 0) {
649 SetExplicitly = false;
650 if (TripCount == 0)
651 // Runtime trip count.
652 Count = UnrollRuntimeCount;
653 else
654 // Conservative heuristic: if we know the trip count, see if we can
655 // completely unroll (subject to the threshold, checked below); otherwise
656 // try to find greatest modulo of the trip count which is still under
657 // threshold value.
658 Count = TripCount;
659 }
660 if (TripCount && Count > TripCount)
661 return TripCount;
662 return Count;
663}
664
Devang Patel9779e562007-03-07 01:38:05 +0000665bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000666 if (skipOptnoneFunction(L))
667 return false;
668
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000669 Function &F = *L->getHeader()->getParent();
670
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000671 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Andrew Trick2b6860f2011-08-11 23:36:16 +0000672 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000673 const TargetTransformInfo &TTI =
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000674 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000675 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000676
Dan Gohman2e1f8042007-05-08 15:19:19 +0000677 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000678 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000679 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000680
681 if (HasUnrollDisablePragma(L)) {
682 return false;
683 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000684 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000685 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000686 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000687
Hal Finkel8f2e7002013-09-11 19:25:43 +0000688 TargetTransformInfo::UnrollingPreferences UP;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000689 getUnrollingPreferences(L, TTI, UP);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000690
Andrew Trick2b6860f2011-08-11 23:36:16 +0000691 // Find trip count and trip multiple if count is not available
692 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000693 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000694 // If there are multiple exiting blocks but one of them is the latch, use the
695 // latch for the trip count estimation. Otherwise insist on a single exiting
696 // block for the trip count estimation.
697 BasicBlock *ExitingBlock = L->getLoopLatch();
698 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
699 ExitingBlock = L->getExitingBlock();
700 if (ExitingBlock) {
701 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
702 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000703 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000704
Eli Benderskyff903242014-06-16 23:53:02 +0000705 // Select an initial unroll count. This may be reduced later based
706 // on size thresholds.
707 bool CountSetExplicitly;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000708 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
709 PragmaCount, UP, CountSetExplicitly);
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000710
Eli Benderskyff903242014-06-16 23:53:02 +0000711 unsigned NumInlineCandidates;
712 bool notDuplicatable;
713 unsigned LoopSize =
Chandler Carruth66b31302015-01-04 12:03:27 +0000714 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000715 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Hal Finkel38dd5902015-01-10 00:30:55 +0000716
717 // When computing the unrolled size, note that the conditional branch on the
718 // backedge and the comparison feeding it are not replicated like the rest of
719 // the loop body (which is why 2 is subtracted).
720 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000721 if (notDuplicatable) {
722 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
723 << " instructions.\n");
724 return false;
725 }
726 if (NumInlineCandidates != 0) {
727 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
728 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000729 }
730
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000731 unsigned NumberOfOptimizedInstructions =
732 ApproximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI);
733 DEBUG(dbgs() << " Complete unrolling could save: "
734 << NumberOfOptimizedInstructions << "\n");
735
Eli Benderskyff903242014-06-16 23:53:02 +0000736 unsigned Threshold, PartialThreshold;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000737 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
738 NumberOfOptimizedInstructions);
Benjamin Kramer9130cb82014-05-04 19:12:38 +0000739
Eli Benderskyff903242014-06-16 23:53:02 +0000740 // Given Count, TripCount and thresholds determine the type of
741 // unrolling which is to be performed.
742 enum { Full = 0, Partial = 1, Runtime = 2 };
743 int Unrolling;
744 if (TripCount && Count == TripCount) {
745 if (Threshold != NoThreshold && UnrolledSize > Threshold) {
746 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
747 << " because size: " << UnrolledSize << ">" << Threshold
748 << "\n");
749 Unrolling = Partial;
750 } else {
751 Unrolling = Full;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000752 }
Eli Benderskyff903242014-06-16 23:53:02 +0000753 } else if (TripCount && Count < TripCount) {
754 Unrolling = Partial;
755 } else {
756 Unrolling = Runtime;
757 }
758
759 // Reduce count based on the type of unrolling and the threshold values.
760 unsigned OriginalCount = Count;
761 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
762 if (Unrolling == Partial) {
763 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
764 if (!AllowPartial && !CountSetExplicitly) {
765 DEBUG(dbgs() << " will not try to unroll partially because "
766 << "-unroll-allow-partial not given\n");
767 return false;
768 }
769 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
770 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Hal Finkel38dd5902015-01-10 00:30:55 +0000771 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
Eli Benderskyff903242014-06-16 23:53:02 +0000772 while (Count != 0 && TripCount % Count != 0)
773 Count--;
774 }
775 } else if (Unrolling == Runtime) {
776 if (!AllowRuntime && !CountSetExplicitly) {
777 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
778 << "-unroll-runtime not given\n");
779 return false;
780 }
781 // Reduce unroll count to be the largest power-of-two factor of
782 // the original count which satisfies the threshold limit.
783 while (Count != 0 && UnrolledSize > PartialThreshold) {
784 Count >>= 1;
Hal Finkel38dd5902015-01-10 00:30:55 +0000785 UnrolledSize = (LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000786 }
787 if (Count > UP.MaxCount)
788 Count = UP.MaxCount;
789 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
790 }
791
792 if (HasPragma) {
Mark Heffernan9e112442014-07-23 20:05:44 +0000793 if (PragmaCount != 0)
794 // If loop has an unroll count pragma mark loop as unrolled to prevent
795 // unrolling beyond that requested by the pragma.
796 SetLoopAlreadyUnrolled(L);
Mark Heffernan053a6862014-07-18 21:04:33 +0000797
Eli Benderskyff903242014-06-16 23:53:02 +0000798 // Emit optimization remarks if we are unable to unroll the loop
799 // as directed by a pragma.
800 DebugLoc LoopLoc = L->getStartLoc();
801 Function *F = Header->getParent();
802 LLVMContext &Ctx = F->getContext();
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000803 if (PragmaFullUnroll && PragmaCount == 0) {
Eli Benderskyff903242014-06-16 23:53:02 +0000804 if (TripCount && Count != TripCount) {
805 emitOptimizationRemarkMissed(
806 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000807 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +0000808 "because unrolled size is too large.");
809 } else if (!TripCount) {
810 emitOptimizationRemarkMissed(
811 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000812 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +0000813 "because loop has a runtime trip count.");
814 }
815 } else if (PragmaCount > 0 && Count != OriginalCount) {
816 emitOptimizationRemarkMissed(
817 Ctx, DEBUG_TYPE, *F, LoopLoc,
818 "Unable to unroll loop the number of times directed by "
819 "unroll_count pragma because unrolled size is too large.");
820 }
821 }
822
823 if (Unrolling != Full && Count < 2) {
824 // Partial unrolling by 1 is a nop. For full unrolling, a factor
825 // of 1 makes sense because loop control can be eliminated.
826 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000827 }
828
Dan Gohman3dc2d922008-05-14 00:24:14 +0000829 // Unroll the loop.
Hal Finkel74c2f352014-09-07 12:44:26 +0000830 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,
Chandler Carruth66b31302015-01-04 12:03:27 +0000831 &LPM, &AC))
Dan Gohman3dc2d922008-05-14 00:24:14 +0000832 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000833
Chris Lattner946b2552004-04-18 05:20:17 +0000834 return true;
835}