blob: 01a8ad8a1445a863b966678ae8ac8f551ada79a0 [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"
James Molloyefbba722015-09-10 10:22:12 +000017#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000019#include "llvm/Analysis/CodeMetrics.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/LoopPass.h"
Michael Zolotukhin1da4afd2016-02-08 23:03:59 +000022#include "llvm/Analysis/LoopUnrollAnalyzer.h"
Dan Gohman0141c132010-07-26 18:11:16 +000023#include "llvm/Analysis/ScalarEvolution.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000024#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
Eli Benderskyff903242014-06-16 23:53:02 +000027#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000031#include "llvm/IR/Metadata.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000035#include "llvm/Transforms/Utils/LoopUtils.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000036#include "llvm/Transforms/Utils/UnrollLoop.h"
Duncan Sands67933e62008-05-16 09:30:00 +000037#include <climits>
Chris Lattner946b2552004-04-18 05:20:17 +000038
Dan Gohman3dc2d922008-05-14 00:24:14 +000039using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000040
Chandler Carruth964daaa2014-04-22 02:55:47 +000041#define DEBUG_TYPE "loop-unroll"
42
Dan Gohmand78c4002008-05-13 00:00:25 +000043static cl::opt<unsigned>
Justin Bognera1dd4932016-01-12 00:55:26 +000044 UnrollThreshold("unroll-threshold", cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000045 cl::desc("The baseline cost threshold for loop unrolling"));
46
47static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
Justin Bognera1dd4932016-01-12 00:55:26 +000048 "unroll-percent-dynamic-cost-saved-threshold", cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000049 cl::desc("The percentage of estimated dynamic cost which must be saved by "
50 "unrolling to allow unrolling up to the max threshold."));
51
52static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
Justin Bognera1dd4932016-01-12 00:55:26 +000053 "unroll-dynamic-cost-savings-discount", cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000054 cl::desc("This is the amount discounted from the total unroll cost when "
55 "the unrolled form has a high dynamic cost savings (triggered by "
56 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
Dan Gohmand78c4002008-05-13 00:00:25 +000057
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000058static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
Chandler Carruth1fbc3162015-02-13 05:31:46 +000059 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000060 cl::desc("Don't allow loop unrolling to simulate more than this number of"
61 "iterations when checking full unroll profitability"));
62
Dan Gohmand78c4002008-05-13 00:00:25 +000063static cl::opt<unsigned>
Justin Bognera1dd4932016-01-12 00:55:26 +000064UnrollCount("unroll-count", cl::Hidden,
Eli Benderskyff903242014-06-16 23:53:02 +000065 cl::desc("Use this unroll count for all loops including those with "
66 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +000067
Fiona Glaser045afc42016-04-06 16:57:25 +000068static cl::opt<unsigned>
69UnrollMaxCount("unroll-max-count", cl::Hidden,
70 cl::desc("Set the max unroll count for partial and runtime unrolling, for"
71 "testing purposes"));
72
73static cl::opt<unsigned>
74UnrollFullMaxCount("unroll-full-max-count", cl::Hidden,
75 cl::desc("Set the max unroll count for full unrolling, for testing purposes"));
76
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000077static cl::opt<bool>
Justin Bognera1dd4932016-01-12 00:55:26 +000078UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000079 cl::desc("Allows loops to be partially unrolled until "
80 "-unroll-threshold loop size is reached."));
81
Andrew Trickd04d15292011-12-09 06:19:40 +000082static cl::opt<bool>
Justin Bognera1dd4932016-01-12 00:55:26 +000083UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
Andrew Trickd04d15292011-12-09 06:19:40 +000084 cl::desc("Unroll loops with run-time trip counts"));
85
Eli Benderskyff903242014-06-16 23:53:02 +000086static cl::opt<unsigned>
87PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
Mark Heffernane6b4ba12014-07-23 17:31:37 +000088 cl::desc("Unrolled size limit for loops with an unroll(full) or "
Eli Benderskyff903242014-06-16 23:53:02 +000089 "unroll_count pragma."));
90
Justin Bognera1dd4932016-01-12 00:55:26 +000091
92/// A magic value for use with the Threshold parameter to indicate
93/// that the loop unroll should be performed regardless of how much
94/// code expansion would result.
95static const unsigned NoThreshold = UINT_MAX;
96
97/// Default unroll count for loops with run-time trip count if
98/// -unroll-count is not set
99static const unsigned DefaultUnrollRuntimeCount = 8;
100
101/// Gather the various unrolling parameters based on the defaults, compiler
102/// flags, TTI overrides, pragmas, and user specified parameters.
103static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(
104 Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold,
105 Optional<unsigned> UserCount, Optional<bool> UserAllowPartial,
106 Optional<bool> UserRuntime, unsigned PragmaCount, bool PragmaFullUnroll,
107 bool PragmaEnableUnroll, unsigned TripCount) {
108 TargetTransformInfo::UnrollingPreferences UP;
109
110 // Set up the defaults
111 UP.Threshold = 150;
112 UP.PercentDynamicCostSavedThreshold = 20;
113 UP.DynamicCostSavingsDiscount = 2000;
114 UP.OptSizeThreshold = 50;
115 UP.PartialThreshold = UP.Threshold;
116 UP.PartialOptSizeThreshold = UP.OptSizeThreshold;
117 UP.Count = 0;
118 UP.MaxCount = UINT_MAX;
Fiona Glaser045afc42016-04-06 16:57:25 +0000119 UP.FullUnrollMaxCount = UINT_MAX;
Justin Bognera1dd4932016-01-12 00:55:26 +0000120 UP.Partial = false;
121 UP.Runtime = false;
122 UP.AllowExpensiveTripCount = false;
123
124 // Override with any target specific settings
125 TTI.getUnrollingPreferences(L, UP);
126
127 // Apply size attributes
128 if (L->getHeader()->getParent()->optForSize()) {
129 UP.Threshold = UP.OptSizeThreshold;
130 UP.PartialThreshold = UP.PartialOptSizeThreshold;
131 }
132
133 // Apply unroll count pragmas
134 if (PragmaCount)
135 UP.Count = PragmaCount;
136 else if (PragmaFullUnroll)
137 UP.Count = TripCount;
138
139 // Apply any user values specified by cl::opt
140 if (UnrollThreshold.getNumOccurrences() > 0) {
141 UP.Threshold = UnrollThreshold;
142 UP.PartialThreshold = UnrollThreshold;
143 }
144 if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0)
145 UP.PercentDynamicCostSavedThreshold =
146 UnrollPercentDynamicCostSavedThreshold;
147 if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0)
148 UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
149 if (UnrollCount.getNumOccurrences() > 0)
150 UP.Count = UnrollCount;
Fiona Glaser045afc42016-04-06 16:57:25 +0000151 if (UnrollMaxCount.getNumOccurrences() > 0)
152 UP.MaxCount = UnrollMaxCount;
153 if (UnrollFullMaxCount.getNumOccurrences() > 0)
154 UP.FullUnrollMaxCount = UnrollFullMaxCount;
Justin Bognera1dd4932016-01-12 00:55:26 +0000155 if (UnrollAllowPartial.getNumOccurrences() > 0)
156 UP.Partial = UnrollAllowPartial;
157 if (UnrollRuntime.getNumOccurrences() > 0)
158 UP.Runtime = UnrollRuntime;
159
160 // Apply user values provided by argument
161 if (UserThreshold.hasValue()) {
162 UP.Threshold = *UserThreshold;
163 UP.PartialThreshold = *UserThreshold;
164 }
165 if (UserCount.hasValue())
166 UP.Count = *UserCount;
167 if (UserAllowPartial.hasValue())
168 UP.Partial = *UserAllowPartial;
169 if (UserRuntime.hasValue())
170 UP.Runtime = *UserRuntime;
171
172 if (PragmaCount > 0 ||
173 ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount != 0)) {
174 // If the loop has an unrolling pragma, we want to be more aggressive with
175 // unrolling limits. Set thresholds to at least the PragmaTheshold value
176 // which is larger than the default limits.
177 if (UP.Threshold != NoThreshold)
178 UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
179 if (UP.PartialThreshold != NoThreshold)
180 UP.PartialThreshold =
181 std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
182 }
183
184 return UP;
185}
186
Chris Lattner79a42ac2006-12-19 21:40:18 +0000187namespace {
Chandler Carruth02156082015-05-22 17:41:35 +0000188struct EstimatedUnrollCost {
Chandler Carruth9dabd142015-06-05 17:01:43 +0000189 /// \brief The estimated cost after unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000190 int UnrolledCost;
Chandler Carruth302a1332015-02-13 02:10:56 +0000191
Chandler Carruth9dabd142015-06-05 17:01:43 +0000192 /// \brief The estimated dynamic cost of executing the instructions in the
193 /// rolled form.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000194 int RolledDynamicCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000195};
196}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000197
Chandler Carruth02156082015-05-22 17:41:35 +0000198/// \brief Figure out if the loop is worth full unrolling.
199///
200/// Complete loop unrolling can make some loads constant, and we need to know
201/// if that would expose any further optimization opportunities. This routine
Michael Zolotukhinc4e4f332015-06-11 22:17:39 +0000202/// estimates this optimization. It computes cost of unrolled loop
203/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
204/// dynamic cost we mean that we won't count costs of blocks that are known not
205/// to be executed (i.e. if we have a branch in the loop and we know that at the
206/// given iteration its condition would be resolved to true, we won't add up the
207/// cost of the 'false'-block).
208/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
209/// the analysis failed (no benefits expected from the unrolling, or the loop is
210/// too big to analyze), the returned value is None.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000211static Optional<EstimatedUnrollCost>
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000212analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
213 ScalarEvolution &SE, const TargetTransformInfo &TTI,
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000214 int MaxUnrolledLoopSize) {
Chandler Carruth02156082015-05-22 17:41:35 +0000215 // We want to be able to scale offsets by the trip count and add more offsets
216 // to them without checking for overflows, and we already don't want to
217 // analyze *massive* trip counts, so we force the max to be reasonably small.
218 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
219 "The unroll iterations max is too large!");
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000220
Chandler Carruth02156082015-05-22 17:41:35 +0000221 // Don't simulate loops with a big or unknown tripcount
222 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
223 TripCount > UnrollMaxIterationsCountToAnalyze)
224 return None;
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000225
Chandler Carruth02156082015-05-22 17:41:35 +0000226 SmallSetVector<BasicBlock *, 16> BBWorklist;
227 DenseMap<Value *, Constant *> SimplifiedValues;
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000228 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
Chandler Carruth3b057b32015-02-13 03:57:40 +0000229
Chandler Carruth9dabd142015-06-05 17:01:43 +0000230 // The estimated cost of the unrolled form of the loop. We try to estimate
231 // this by simplifying as much as we can while computing the estimate.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000232 int UnrolledCost = 0;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000233 // We also track the estimated dynamic (that is, actually executed) cost in
234 // the rolled form. This helps identify cases when the savings from unrolling
235 // aren't just exposing dead control flows, but actual reduced dynamic
236 // instructions due to the simplifications which we expect to occur after
237 // unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000238 int RolledDynamicCost = 0;
Chandler Carruth8c863752015-02-13 03:48:38 +0000239
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000240 // Ensure that we don't violate the loop structure invariants relied on by
241 // this analysis.
242 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
243 assert(L->isLCSSAForm(DT) &&
244 "Must have loops in LCSSA form to track live-out values.");
245
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000246 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
247
Chandler Carruth02156082015-05-22 17:41:35 +0000248 // Simulate execution of each iteration of the loop counting instructions,
249 // which would be simplified.
250 // Since the same load will take different values on different iterations,
251 // we literally have to go through all loop's iterations.
252 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000253 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000254
255 // Prepare for the iteration by collecting any simplified entry or backedge
256 // inputs.
257 for (Instruction &I : *L->getHeader()) {
258 auto *PHI = dyn_cast<PHINode>(&I);
259 if (!PHI)
260 break;
261
262 // The loop header PHI nodes must have exactly two input: one from the
263 // loop preheader and one from the loop latch.
264 assert(
265 PHI->getNumIncomingValues() == 2 &&
266 "Must have an incoming value only for the preheader and the latch.");
267
268 Value *V = PHI->getIncomingValueForBlock(
269 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
270 Constant *C = dyn_cast<Constant>(V);
271 if (Iteration != 0 && !C)
272 C = SimplifiedValues.lookup(V);
273 if (C)
274 SimplifiedInputValues.push_back({PHI, C});
275 }
276
277 // Now clear and re-populate the map for the next iteration.
Chandler Carruth02156082015-05-22 17:41:35 +0000278 SimplifiedValues.clear();
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000279 while (!SimplifiedInputValues.empty())
280 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
281
Michael Zolotukhin9f520eb2016-02-26 02:57:05 +0000282 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
Chandler Carruthf174a152015-05-22 02:47:29 +0000283
Chandler Carruth02156082015-05-22 17:41:35 +0000284 BBWorklist.clear();
285 BBWorklist.insert(L->getHeader());
286 // Note that we *must not* cache the size, this loop grows the worklist.
287 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
288 BasicBlock *BB = BBWorklist[Idx];
Chandler Carruthf174a152015-05-22 02:47:29 +0000289
Chandler Carruth02156082015-05-22 17:41:35 +0000290 // Visit all instructions in the given basic block and try to simplify
291 // it. We don't change the actual IR, just count optimization
292 // opportunities.
293 for (Instruction &I : *BB) {
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000294 int InstCost = TTI.getUserCost(&I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000295
Chandler Carruth02156082015-05-22 17:41:35 +0000296 // Visit the instruction to analyze its loop cost after unrolling,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000297 // and if the visitor returns false, include this instruction in the
298 // unrolled cost.
299 if (!Analyzer.visit(I))
300 UnrolledCost += InstCost;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000301 else {
302 DEBUG(dbgs() << " " << I
303 << " would be simplified if loop is unrolled.\n");
304 (void)0;
305 }
Chandler Carruth9dabd142015-06-05 17:01:43 +0000306
307 // Also track this instructions expected cost when executing the rolled
308 // loop form.
309 RolledDynamicCost += InstCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000310
311 // If unrolled body turns out to be too big, bail out.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000312 if (UnrolledCost > MaxUnrolledLoopSize) {
313 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n"
314 << " UnrolledCost: " << UnrolledCost
315 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
316 << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000317 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000318 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000319 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000320
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000321 TerminatorInst *TI = BB->getTerminator();
322
323 // Add in the live successors by first checking whether we have terminator
324 // that may be simplified based on the values simplified by this call.
325 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
326 if (BI->isConditional()) {
327 if (Constant *SimpleCond =
328 SimplifiedValues.lookup(BI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000329 BasicBlock *Succ = nullptr;
330 // Just take the first successor if condition is undef
331 if (isa<UndefValue>(SimpleCond))
332 Succ = BI->getSuccessor(0);
333 else
334 Succ = BI->getSuccessor(
335 cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0);
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000336 if (L->contains(Succ))
337 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000338 continue;
339 }
340 }
341 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
342 if (Constant *SimpleCond =
343 SimplifiedValues.lookup(SI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000344 BasicBlock *Succ = nullptr;
345 // Just take the first successor if condition is undef
346 if (isa<UndefValue>(SimpleCond))
347 Succ = SI->getSuccessor(0);
348 else
Michael Zolotukhin9f06ef72015-07-29 18:10:33 +0000349 Succ = SI->findCaseValue(cast<ConstantInt>(SimpleCond))
350 .getCaseSuccessor();
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000351 if (L->contains(Succ))
352 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000353 continue;
354 }
355 }
356
Chandler Carruth02156082015-05-22 17:41:35 +0000357 // Add BB's successors to the worklist.
358 for (BasicBlock *Succ : successors(BB))
359 if (L->contains(Succ))
360 BBWorklist.insert(Succ);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000361 }
Chandler Carruth02156082015-05-22 17:41:35 +0000362
363 // If we found no optimization opportunities on the first iteration, we
364 // won't find them on later ones too.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000365 if (UnrolledCost == RolledDynamicCost) {
366 DEBUG(dbgs() << " No opportunities found.. exiting.\n"
367 << " UnrolledCost: " << UnrolledCost << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000368 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000369 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000370 }
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000371 DEBUG(dbgs() << "Analysis finished:\n"
372 << "UnrolledCost: " << UnrolledCost << ", "
373 << "RolledDynamicCost: " << RolledDynamicCost << "\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000374 return {{UnrolledCost, RolledDynamicCost}};
Chandler Carruth02156082015-05-22 17:41:35 +0000375}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000376
Dan Gohman49d08a52007-05-08 15:14:19 +0000377/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000378static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Justin Lebar6827de12016-03-14 23:15:34 +0000379 bool &NotDuplicatable, bool &Convergent,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000380 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000381 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000382 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000383 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000384
Dan Gohman969e83a2009-10-31 14:54:17 +0000385 CodeMetrics Metrics;
Sanjay Patel5c967232016-03-08 19:06:12 +0000386 for (BasicBlock *BB : L->blocks())
387 Metrics.analyzeBasicBlock(BB, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000388 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000389 NotDuplicatable = Metrics.notDuplicatable;
Justin Lebar6827de12016-03-14 23:15:34 +0000390 Convergent = Metrics.convergent;
Andrew Trick279e7a62011-07-23 00:29:16 +0000391
Owen Anderson62ea1b72010-09-09 19:07:31 +0000392 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000393
Owen Anderson62ea1b72010-09-09 19:07:31 +0000394 // Don't allow an estimate of size zero. This would allows unrolling of loops
395 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000396 // not a problem for code quality. Also, the code using this size may assume
397 // that each loop has at least three instructions (likely a conditional
398 // branch, a comparison feeding that branch, and some kind of loop increment
399 // feeding that comparison instruction).
400 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000401
Owen Anderson62ea1b72010-09-09 19:07:31 +0000402 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000403}
404
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000405// Returns the loop hint metadata node with the given name (for example,
406// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
407// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000408static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
409 if (MDNode *LoopID = L->getLoopID())
410 return GetUnrollMetadata(LoopID, Name);
411 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000412}
413
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000414// Returns true if the loop has an unroll(full) pragma.
415static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000416 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000417}
418
Mark Heffernan89391542015-08-10 17:28:08 +0000419// Returns true if the loop has an unroll(enable) pragma. This metadata is used
420// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
421static bool HasUnrollEnablePragma(const Loop *L) {
422 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
423}
424
Eli Benderskyff903242014-06-16 23:53:02 +0000425// Returns true if the loop has an unroll(disable) pragma.
426static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000427 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000428}
429
Kevin Qin715b01e2015-03-09 06:14:18 +0000430// Returns true if the loop has an runtime unroll(disable) pragma.
431static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
432 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
433}
434
Eli Benderskyff903242014-06-16 23:53:02 +0000435// If loop has an unroll_count pragma return the (necessarily
436// positive) value from the pragma. Otherwise return 0.
437static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000438 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000439 if (MD) {
440 assert(MD->getNumOperands() == 2 &&
441 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000442 unsigned Count =
443 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000444 assert(Count >= 1 && "Unroll count must be positive.");
445 return Count;
446 }
447 return 0;
448}
449
Mark Heffernan053a6862014-07-18 21:04:33 +0000450// Remove existing unroll metadata and add unroll disable metadata to
451// indicate the loop has already been unrolled. This prevents a loop
452// from being unrolled more than is directed by a pragma if the loop
453// unrolling pass is run more than once (which it generally is).
454static void SetLoopAlreadyUnrolled(Loop *L) {
455 MDNode *LoopID = L->getLoopID();
456 if (!LoopID) return;
457
458 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000459 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000460 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000461 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000462 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
463 bool IsUnrollMetadata = false;
464 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
465 if (MD) {
466 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
467 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
468 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000469 if (!IsUnrollMetadata)
470 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000471 }
472
473 // Add unroll(disable) metadata to disable future unrolling.
474 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000475 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000476 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000477 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000478 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000479
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000480 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000481 // Set operand 0 to refer to the loop id itself.
482 NewLoopID->replaceOperandWith(0, NewLoopID);
483 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000484}
485
Justin Bogner921b04e2016-01-12 01:06:32 +0000486static bool canUnrollCompletely(Loop *L, unsigned Threshold,
487 unsigned PercentDynamicCostSavedThreshold,
488 unsigned DynamicCostSavingsDiscount,
489 uint64_t UnrolledCost,
490 uint64_t RolledDynamicCost) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000491 if (Threshold == NoThreshold) {
492 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
493 return true;
494 }
495
Chandler Carruth9dabd142015-06-05 17:01:43 +0000496 if (UnrolledCost <= Threshold) {
497 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
498 << UnrolledCost << "<" << Threshold << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000499 return true;
500 }
501
Chandler Carruth9dabd142015-06-05 17:01:43 +0000502 assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
503 assert(RolledDynamicCost >= UnrolledCost &&
504 "Cannot have a higher unrolled cost than a rolled cost!");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000505
Chandler Carruth9dabd142015-06-05 17:01:43 +0000506 // Compute the percentage of the dynamic cost in the rolled form that is
507 // saved when unrolled. If unrolling dramatically reduces the estimated
508 // dynamic cost of the loop, we use a higher threshold to allow more
509 // unrolling.
510 unsigned PercentDynamicCostSaved =
511 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
512
513 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
514 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
515 (int64_t)Threshold) {
516 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
517 "expected dynamic cost by " << PercentDynamicCostSaved
518 << "% (threshold: " << PercentDynamicCostSavedThreshold
519 << "%)\n"
520 << " and the unrolled cost (" << UnrolledCost
521 << ") is less than the max threshold ("
522 << DynamicCostSavingsDiscount << ").\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000523 return true;
524 }
525
526 DEBUG(dbgs() << " Too large to fully unroll:\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000527 DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
528 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
529 DEBUG(dbgs() << " Percent cost saved threshold: "
530 << PercentDynamicCostSavedThreshold << "%\n");
531 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
532 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
533 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
534 << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000535 return false;
536}
537
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000538static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
539 ScalarEvolution *SE, const TargetTransformInfo &TTI,
540 AssumptionCache &AC, bool PreserveLCSSA,
541 Optional<unsigned> ProvidedCount,
542 Optional<unsigned> ProvidedThreshold,
543 Optional<bool> ProvidedAllowPartial,
544 Optional<bool> ProvidedRuntime) {
Dan Gohman2e1f8042007-05-08 15:19:19 +0000545 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000546 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000547 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000548
549 if (HasUnrollDisablePragma(L)) {
550 return false;
551 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000552 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Mark Heffernan89391542015-08-10 17:28:08 +0000553 bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000554 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernan89391542015-08-10 17:28:08 +0000555 bool HasPragma = PragmaFullUnroll || PragmaEnableUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000556
Andrew Trick2b6860f2011-08-11 23:36:16 +0000557 // Find trip count and trip multiple if count is not available
558 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000559 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000560 // If there are multiple exiting blocks but one of them is the latch, use the
561 // latch for the trip count estimation. Otherwise insist on a single exiting
562 // block for the trip count estimation.
563 BasicBlock *ExitingBlock = L->getLoopLatch();
564 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
565 ExitingBlock = L->getExitingBlock();
566 if (ExitingBlock) {
567 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
568 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000569 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000570
Justin Bognera1dd4932016-01-12 00:55:26 +0000571 TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
572 L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial,
573 ProvidedRuntime, PragmaCount, PragmaFullUnroll, PragmaEnableUnroll,
574 TripCount);
575
576 unsigned Count = UP.Count;
577 bool CountSetExplicitly = Count != 0;
578 // Use a heuristic count if we didn't set anything explicitly.
579 if (!CountSetExplicitly)
580 Count = TripCount == 0 ? DefaultUnrollRuntimeCount : TripCount;
581 if (TripCount && Count > TripCount)
582 Count = TripCount;
Fiona Glaser045afc42016-04-06 16:57:25 +0000583 Count = std::min(Count, UP.FullUnrollMaxCount);
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000584
Eli Benderskyff903242014-06-16 23:53:02 +0000585 unsigned NumInlineCandidates;
Sanjay Patelf831fdb2016-03-08 19:07:42 +0000586 bool NotDuplicatable;
Justin Lebar6827de12016-03-14 23:15:34 +0000587 bool Convergent;
588 unsigned LoopSize = ApproximateLoopSize(
589 L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000590 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Hal Finkel38dd5902015-01-10 00:30:55 +0000591
592 // When computing the unrolled size, note that the conditional branch on the
593 // backedge and the comparison feeding it are not replicated like the rest of
594 // the loop body (which is why 2 is subtracted).
595 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
Sanjay Patelf831fdb2016-03-08 19:07:42 +0000596 if (NotDuplicatable) {
Eli Benderskyff903242014-06-16 23:53:02 +0000597 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
598 << " instructions.\n");
599 return false;
600 }
601 if (NumInlineCandidates != 0) {
602 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
603 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000604 }
605
Eli Benderskyff903242014-06-16 23:53:02 +0000606 // Given Count, TripCount and thresholds determine the type of
607 // unrolling which is to be performed.
608 enum { Full = 0, Partial = 1, Runtime = 2 };
609 int Unrolling;
610 if (TripCount && Count == TripCount) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000611 Unrolling = Partial;
612 // If the loop is really small, we don't need to run an expensive analysis.
Justin Bognera1dd4932016-01-12 00:55:26 +0000613 if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000614 UnrolledSize, UnrolledSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000615 Unrolling = Full;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000616 } else {
617 // The loop isn't that small, but we still can fully unroll it if that
618 // helps to remove a significant number of instructions.
619 // To check that, run additional analysis on the loop.
Justin Bognera1dd4932016-01-12 00:55:26 +0000620 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
621 L, TripCount, DT, *SE, TTI,
622 UP.Threshold + UP.DynamicCostSavingsDiscount))
623 if (canUnrollCompletely(L, UP.Threshold,
624 UP.PercentDynamicCostSavedThreshold,
625 UP.DynamicCostSavingsDiscount,
626 Cost->UnrolledCost, Cost->RolledDynamicCost)) {
Chandler Carruth02156082015-05-22 17:41:35 +0000627 Unrolling = Full;
628 }
Dan Gohman2980d9d2007-05-11 20:53:41 +0000629 }
Eli Benderskyff903242014-06-16 23:53:02 +0000630 } else if (TripCount && Count < TripCount) {
631 Unrolling = Partial;
632 } else {
633 Unrolling = Runtime;
634 }
635
636 // Reduce count based on the type of unrolling and the threshold values.
637 unsigned OriginalCount = Count;
Justin Bognera1dd4932016-01-12 00:55:26 +0000638 bool AllowRuntime = PragmaEnableUnroll || (PragmaCount > 0) || UP.Runtime;
Mark Heffernand7ebc242015-07-13 18:26:27 +0000639 // Don't unroll a runtime trip count loop with unroll full pragma.
640 if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
Kevin Qin715b01e2015-03-09 06:14:18 +0000641 AllowRuntime = false;
642 }
Justin Lebar6827de12016-03-14 23:15:34 +0000643 bool DecreasedCountDueToConvergence = false;
Eli Benderskyff903242014-06-16 23:53:02 +0000644 if (Unrolling == Partial) {
Justin Bognera1dd4932016-01-12 00:55:26 +0000645 bool AllowPartial = PragmaEnableUnroll || UP.Partial;
Eli Benderskyff903242014-06-16 23:53:02 +0000646 if (!AllowPartial && !CountSetExplicitly) {
647 DEBUG(dbgs() << " will not try to unroll partially because "
648 << "-unroll-allow-partial not given\n");
649 return false;
650 }
Fiona Glaser045afc42016-04-06 16:57:25 +0000651 if (UP.PartialThreshold != NoThreshold && Count > 1) {
Eli Benderskyff903242014-06-16 23:53:02 +0000652 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Fiona Glaser045afc42016-04-06 16:57:25 +0000653 if (UnrolledSize > UP.PartialThreshold)
654 Count = (std::max(UP.PartialThreshold, 3u) - 2) / (LoopSize - 2);
655 if (Count > UP.MaxCount)
656 Count = UP.MaxCount;
Eli Benderskyff903242014-06-16 23:53:02 +0000657 while (Count != 0 && TripCount % Count != 0)
658 Count--;
Fiona Glaser16332ba2016-04-06 16:43:45 +0000659 if (AllowRuntime && Count <= 1) {
Zia Ansaria82a58a42016-04-04 19:24:46 +0000660 // If there is no Count that is modulo of TripCount, set Count to
661 // largest power-of-two factor that satisfies the threshold limit.
Fiona Glaser16332ba2016-04-06 16:43:45 +0000662 // As we'll create fixup loop, do the type of unrolling only if
663 // runtime unrolling is allowed.
664 Count = DefaultUnrollRuntimeCount;
Zia Ansaria82a58a42016-04-04 19:24:46 +0000665 UnrolledSize = (LoopSize - 2) * Count + 2;
666 while (Count != 0 && UnrolledSize > UP.PartialThreshold) {
667 Count >>= 1;
668 UnrolledSize = (LoopSize - 2) * Count + 2;
669 }
670 }
Eli Benderskyff903242014-06-16 23:53:02 +0000671 }
672 } else if (Unrolling == Runtime) {
673 if (!AllowRuntime && !CountSetExplicitly) {
674 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
675 << "-unroll-runtime not given\n");
676 return false;
677 }
Justin Lebar6827de12016-03-14 23:15:34 +0000678
Eli Benderskyff903242014-06-16 23:53:02 +0000679 // Reduce unroll count to be the largest power-of-two factor of
680 // the original count which satisfies the threshold limit.
Justin Bognera1dd4932016-01-12 00:55:26 +0000681 while (Count != 0 && UnrolledSize > UP.PartialThreshold) {
Eli Benderskyff903242014-06-16 23:53:02 +0000682 Count >>= 1;
Hal Finkel38dd5902015-01-10 00:30:55 +0000683 UnrolledSize = (LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000684 }
Justin Lebar6827de12016-03-14 23:15:34 +0000685
Eli Benderskyff903242014-06-16 23:53:02 +0000686 if (Count > UP.MaxCount)
687 Count = UP.MaxCount;
Justin Lebar6827de12016-03-14 23:15:34 +0000688
689 // If the loop contains a convergent operation, the prelude we'd add
690 // to do the first few instructions before we hit the unrolled loop
691 // is unsafe -- it adds a control-flow dependency to the convergent
692 // operation. Therefore Count must divide TripMultiple.
693 //
694 // TODO: This is quite conservative. In practice, convergent_op()
695 // is likely to be called unconditionally in the loop. In this
696 // case, the program would be ill-formed (on most architectures)
697 // unless n were the same on all threads in a thread group.
698 // Assuming n is the same on all threads, any kind of unrolling is
699 // safe. But currently llvm's notion of convergence isn't powerful
700 // enough to express this.
701 unsigned OrigCount = Count;
702 while (Convergent && Count != 0 && TripMultiple % Count != 0) {
703 DecreasedCountDueToConvergence = true;
704 Count >>= 1;
705 }
706 if (OrigCount > Count) {
707 DEBUG(dbgs() << " loop contains a convergent instruction, so unroll "
708 "count must divide the trip multiple, "
709 << TripMultiple << ". Reducing unroll count from "
710 << OrigCount << " to " << Count << ".\n");
711 }
Eli Benderskyff903242014-06-16 23:53:02 +0000712 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
713 }
714
715 if (HasPragma) {
716 // Emit optimization remarks if we are unable to unroll the loop
717 // as directed by a pragma.
718 DebugLoc LoopLoc = L->getStartLoc();
719 Function *F = Header->getParent();
720 LLVMContext &Ctx = F->getContext();
Justin Lebar6827de12016-03-14 23:15:34 +0000721 if (PragmaCount > 0 && DecreasedCountDueToConvergence) {
722 emitOptimizationRemarkMissed(
723 Ctx, DEBUG_TYPE, *F, LoopLoc,
724 Twine("Unable to unroll loop the number of times directed by "
725 "unroll_count pragma because the loop contains a convergent "
726 "instruction, and so must have an unroll count that divides "
727 "the loop trip multiple of ") +
728 Twine(TripMultiple) + ". Unrolling instead " + Twine(Count) +
729 " time(s).");
730 } else if ((PragmaCount > 0) && Count != OriginalCount) {
Eli Benderskyff903242014-06-16 23:53:02 +0000731 emitOptimizationRemarkMissed(
732 Ctx, DEBUG_TYPE, *F, LoopLoc,
733 "Unable to unroll loop the number of times directed by "
734 "unroll_count pragma because unrolled size is too large.");
Mark Heffernan89391542015-08-10 17:28:08 +0000735 } else if (PragmaFullUnroll && !TripCount) {
736 emitOptimizationRemarkMissed(
737 Ctx, DEBUG_TYPE, *F, LoopLoc,
738 "Unable to fully unroll loop as directed by unroll(full) pragma "
739 "because loop has a runtime trip count.");
740 } else if (PragmaEnableUnroll && Count != TripCount && Count < 2) {
741 emitOptimizationRemarkMissed(
742 Ctx, DEBUG_TYPE, *F, LoopLoc,
743 "Unable to unroll loop as directed by unroll(enable) pragma because "
744 "unrolled size is too large.");
745 } else if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
746 Count != TripCount) {
747 emitOptimizationRemarkMissed(
748 Ctx, DEBUG_TYPE, *F, LoopLoc,
749 "Unable to fully unroll loop as directed by unroll pragma because "
750 "unrolled size is too large.");
Eli Benderskyff903242014-06-16 23:53:02 +0000751 }
752 }
753
754 if (Unrolling != Full && Count < 2) {
755 // Partial unrolling by 1 is a nop. For full unrolling, a factor
756 // of 1 makes sense because loop control can be eliminated.
757 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000758 }
759
Dan Gohman3dc2d922008-05-14 00:24:14 +0000760 // Unroll the loop.
Sanjoy Dase178f462015-04-14 03:20:38 +0000761 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
Justin Bogner883a3ea2015-12-16 18:40:20 +0000762 TripMultiple, LI, SE, &DT, &AC, PreserveLCSSA))
Dan Gohman3dc2d922008-05-14 00:24:14 +0000763 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000764
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000765 // If loop has an unroll count pragma mark loop as unrolled to prevent
766 // unrolling beyond that requested by the pragma.
767 if (HasPragma && PragmaCount != 0)
768 SetLoopAlreadyUnrolled(L);
Chris Lattner946b2552004-04-18 05:20:17 +0000769 return true;
770}
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000771
772namespace {
773class LoopUnroll : public LoopPass {
774public:
775 static char ID; // Pass ID, replacement for typeid
776 LoopUnroll(Optional<unsigned> Threshold = None,
777 Optional<unsigned> Count = None,
778 Optional<bool> AllowPartial = None, Optional<bool> Runtime = None)
779 : LoopPass(ID), ProvidedCount(Count), ProvidedThreshold(Threshold),
780 ProvidedAllowPartial(AllowPartial), ProvidedRuntime(Runtime) {
781 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
782 }
783
784 Optional<unsigned> ProvidedCount;
785 Optional<unsigned> ProvidedThreshold;
786 Optional<bool> ProvidedAllowPartial;
787 Optional<bool> ProvidedRuntime;
788
789 bool runOnLoop(Loop *L, LPPassManager &) override {
790 if (skipOptnoneFunction(L))
791 return false;
792
793 Function &F = *L->getHeader()->getParent();
794
795 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
796 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
797 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
798 const TargetTransformInfo &TTI =
799 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
800 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
801 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
802
803 return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, PreserveLCSSA, ProvidedCount,
804 ProvidedThreshold, ProvidedAllowPartial,
805 ProvidedRuntime);
806 }
807
808 /// This transformation requires natural loop information & requires that
809 /// loop preheaders be inserted into the CFG...
810 ///
811 void getAnalysisUsage(AnalysisUsage &AU) const override {
812 AU.addRequired<AssumptionCacheTracker>();
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000813 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000814 // FIXME: Loop passes are required to preserve domtree, and for now we just
815 // recreate dom info if anything gets unrolled.
816 getLoopAnalysisUsage(AU);
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000817 }
818};
819}
820
821char LoopUnroll::ID = 0;
822INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000823INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000824INITIALIZE_PASS_DEPENDENCY(LoopPass)
825INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000826INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
827
828Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
829 int Runtime) {
830 // TODO: It would make more sense for this function to take the optionals
831 // directly, but that's dangerous since it would silently break out of tree
832 // callers.
833 return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold),
834 Count == -1 ? None : Optional<unsigned>(Count),
835 AllowPartial == -1 ? None
836 : Optional<bool>(AllowPartial),
837 Runtime == -1 ? None : Optional<bool>(Runtime));
838}
839
840Pass *llvm::createSimpleLoopUnrollPass() {
841 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
842}