LLVM 24.0.0git
LoopUnrollPass.cpp
Go to the documentation of this file.
1//===- LoopUnroll.cpp - Loop unroller pass --------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements a simple loop unroller. It works best when loops have
10// been canonicalized by the -indvars pass, allowing it to determine the trip
11// counts of loops easily.
12//===----------------------------------------------------------------------===//
13
15#include "ScalarOptions.h"
16#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/StringRef.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
42#include "llvm/IR/Dominators.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Metadata.h"
47#include "llvm/IR/PassManager.h"
49#include "llvm/Pass.h"
52#include "llvm/Support/Debug.h"
64#include <algorithm>
65#include <cassert>
66#include <cstdint>
67#include <limits>
68#include <optional>
69#include <string>
70#include <tuple>
71#include <utility>
72
73using namespace llvm;
74
75#define DEBUG_TYPE "loop-unroll"
76
78 const cl::LibraryOptionsContext *LibraryOptions) {
80 .forget_scev_loop_unroll;
81}
82
83/// A magic value for use with the Threshold parameter to indicate
84/// that the loop unroll should be performed regardless of how much
85/// code expansion would result.
86static const unsigned NoThreshold = std::numeric_limits<unsigned>::max();
87
88/// Gather the various unrolling parameters based on the defaults, compiler
89/// flags, TTI overrides and user specified parameters.
93 OptimizationRemarkEmitter &ORE, int OptLevel,
94 std::optional<unsigned> UserThreshold, std::optional<bool> UserAllowPartial,
95 std::optional<bool> UserRuntime, std::optional<bool> UserUpperBound,
96 std::optional<unsigned> UserFullUnrollMaxCount) {
97 const ScalarOptions &Opts = getScalarOptions(*L);
99
100 // Set up the defaults
101 UP.Threshold = OptLevel > 2 ? Opts.unroll_threshold_aggressive
102 : Opts.unroll_threshold_default;
104 UP.OptSizeThreshold = Opts.unroll_optsize_threshold;
105 UP.PartialThreshold = 150;
106 UP.PartialOptSizeThreshold = Opts.unroll_optsize_threshold;
108 UP.MaxCount = std::numeric_limits<unsigned>::max();
109 UP.MaxUpperBound = 8;
110 UP.FullUnrollMaxCount = std::numeric_limits<unsigned>::max();
111 UP.BEInsns = 2;
112 UP.Partial = false;
113 UP.Runtime = false;
114 UP.AllowRemainder = true;
115 UP.UnrollRemainder = false;
116 UP.AllowExpensiveTripCount = false;
117 UP.Force = false;
118 UP.UpperBound = false;
119 UP.UnrollAndJam = false;
123 UP.RuntimeUnrollMultiExit = false;
124 UP.AddAdditionalAccumulators = false;
125
126 // Override with any target specific settings
127 TTI.getUnrollingPreferences(L, SE, UP, &ORE);
128
129 // Apply size attributes
130 bool OptForSize = L->getHeader()->getParent()->hasOptSize() ||
131 // Let unroll hints / pragmas take precedence over PGSO.
133 llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
135 if (OptForSize) {
139 }
140
141 // Apply any user values specified by cl::opt
142 if (Opts.unroll_threshold)
143 UP.Threshold = *Opts.unroll_threshold;
144 if (Opts.unroll_partial_threshold)
145 UP.PartialThreshold = *Opts.unroll_partial_threshold;
146 if (Opts.unroll_max_percent_threshold_boost)
147 UP.MaxPercentThresholdBoost = *Opts.unroll_max_percent_threshold_boost;
148 if (Opts.unroll_max_count)
149 UP.MaxCount = *Opts.unroll_max_count;
150 if (Opts.unroll_max_upperbound)
151 UP.MaxUpperBound = *Opts.unroll_max_upperbound;
152 if (Opts.unroll_full_max_count)
153 UP.FullUnrollMaxCount = *Opts.unroll_full_max_count;
154 UP.Partial = valueOr(Opts.unroll_allow_partial, UP.Partial);
155 UP.AllowRemainder = valueOr(Opts.unroll_allow_remainder, UP.AllowRemainder);
156 UP.Runtime = valueOr(Opts.unroll_runtime, UP.Runtime);
157 if (Opts.unroll_max_upperbound == 0)
158 UP.UpperBound = false;
159 UP.UnrollRemainder = valueOr(Opts.unroll_remainder, UP.UnrollRemainder);
160 if (Opts.unroll_max_iteration_count_to_analyze)
162 *Opts.unroll_max_iteration_count_to_analyze;
163
164 // Apply user values provided by argument
165 if (UserThreshold) {
166 UP.Threshold = *UserThreshold;
167 UP.PartialThreshold = *UserThreshold;
168 }
169 if (UserAllowPartial)
170 UP.Partial = *UserAllowPartial;
171 if (UserRuntime)
172 UP.Runtime = *UserRuntime;
173 if (UserUpperBound)
174 UP.UpperBound = *UserUpperBound;
175 if (UserFullUnrollMaxCount)
176 UP.FullUnrollMaxCount = *UserFullUnrollMaxCount;
177
178 return UP;
179}
180
181namespace {
182
183/// A struct to densely store the state of an instruction after unrolling at
184/// each iteration.
185///
186/// This is designed to work like a tuple of <Instruction *, int> for the
187/// purposes of hashing and lookup, but to be able to associate two boolean
188/// states with each key.
189struct UnrolledInstState {
190 Instruction *I;
191 int Iteration : 30;
192 unsigned IsFree : 1;
193 unsigned IsCounted : 1;
194};
195
196/// Hashing and equality testing for a set of the instruction states.
197struct UnrolledInstStateKeyInfo {
198 using PairInfo = DenseMapInfo<std::pair<Instruction *, int>>;
199
200 static inline unsigned getHashValue(const UnrolledInstState &S) {
201 return PairInfo::getHashValue({S.I, S.Iteration});
202 }
203
204 static inline bool isEqual(const UnrolledInstState &LHS,
205 const UnrolledInstState &RHS) {
206 return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
207 }
208};
209
210struct EstimatedUnrollCost {
211 /// The estimated cost after unrolling.
212 unsigned UnrolledCost;
213
214 /// The estimated dynamic cost of executing the instructions in the
215 /// rolled form.
216 unsigned RolledDynamicCost;
217};
218
219} // end anonymous namespace
220
221/// Figure out if the loop is worth full unrolling.
222///
223/// Complete loop unrolling can make some loads constant, and we need to know
224/// if that would expose any further optimization opportunities. This routine
225/// estimates this optimization. It computes cost of unrolled loop
226/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
227/// dynamic cost we mean that we won't count costs of blocks that are known not
228/// to be executed (i.e. if we have a branch in the loop and we know that at the
229/// given iteration its condition would be resolved to true, we won't add up the
230/// cost of the 'false'-block).
231/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
232/// the analysis failed (no benefits expected from the unrolling, or the loop is
233/// too big to analyze), the returned value is std::nullopt.
234static std::optional<EstimatedUnrollCost> analyzeLoopUnrollCost(
235 const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE,
236 const SmallPtrSetImpl<const Value *> &EphValues,
237 const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize,
238 unsigned MaxIterationsCountToAnalyze) {
239 // We want to be able to scale offsets by the trip count and add more offsets
240 // to them without checking for overflows, and we already don't want to
241 // analyze *massive* trip counts, so we force the max to be reasonably small.
242 assert(MaxIterationsCountToAnalyze <
243 (unsigned)(std::numeric_limits<int>::max() / 2) &&
244 "The unroll iterations max is too large!");
245
246 // Only analyze inner loops. We can't properly estimate cost of nested loops
247 // and we won't visit inner loops again anyway.
248 if (!L->isInnermost()) {
250 << "Not analyzing loop cost: not an innermost loop.\n");
251 return std::nullopt;
252 }
253
254 // Don't simulate loops with a big or unknown tripcount
255 if (!TripCount || TripCount > MaxIterationsCountToAnalyze) {
257 << "Not analyzing loop cost: trip count "
258 << (TripCount ? "too large" : "unknown") << ".\n");
259 return std::nullopt;
260 }
261
264 DenseMap<Value *, Value *> SimplifiedValues;
265 SmallVector<std::pair<Value *, Value *>, 4> SimplifiedInputValues;
266
267 // The estimated cost of the unrolled form of the loop. We try to estimate
268 // this by simplifying as much as we can while computing the estimate.
269 InstructionCost UnrolledCost = 0;
270
271 // We also track the estimated dynamic (that is, actually executed) cost in
272 // the rolled form. This helps identify cases when the savings from unrolling
273 // aren't just exposing dead control flows, but actual reduced dynamic
274 // instructions due to the simplifications which we expect to occur after
275 // unrolling.
276 InstructionCost RolledDynamicCost = 0;
277
278 // We track the simplification of each instruction in each iteration. We use
279 // this to recursively merge costs into the unrolled cost on-demand so that
280 // we don't count the cost of any dead code. This is essentially a map from
281 // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
283
284 // A small worklist used to accumulate cost of instructions from each
285 // observable and reached root in the loop.
287
288 // PHI-used worklist used between iterations while accumulating cost.
290
291 // Helper function to accumulate cost for instructions in the loop.
292 auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
293 assert(Iteration >= 0 && "Cannot have a negative iteration!");
294 assert(CostWorklist.empty() && "Must start with an empty cost list");
295 assert(PHIUsedList.empty() && "Must start with an empty phi used list");
296 CostWorklist.push_back(&RootI);
298 RootI.getFunction()->hasMinSize() ?
301 for (;; --Iteration) {
302 do {
303 Instruction *I = CostWorklist.pop_back_val();
304
305 // InstCostMap only uses I and Iteration as a key, the other two values
306 // don't matter here.
307 auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
308 if (CostIter == InstCostMap.end())
309 // If an input to a PHI node comes from a dead path through the loop
310 // we may have no cost data for it here. What that actually means is
311 // that it is free.
312 continue;
313 auto &Cost = *CostIter;
314 if (Cost.IsCounted)
315 // Already counted this instruction.
316 continue;
317
318 // Mark that we are counting the cost of this instruction now.
319 Cost.IsCounted = true;
320
321 // If this is a PHI node in the loop header, just add it to the PHI set.
322 if (auto *PhiI = dyn_cast<PHINode>(I))
323 if (PhiI->getParent() == L->getHeader()) {
324 assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
325 "inherently simplify during unrolling.");
326 if (Iteration == 0)
327 continue;
328
329 // Push the incoming value from the backedge into the PHI used list
330 // if it is an in-loop instruction. We'll use this to populate the
331 // cost worklist for the next iteration (as we count backwards).
332 if (auto *OpI = dyn_cast<Instruction>(
333 PhiI->getIncomingValueForBlock(L->getLoopLatch())))
334 if (L->contains(OpI))
335 PHIUsedList.push_back(OpI);
336 continue;
337 }
338
339 // First accumulate the cost of this instruction.
340 if (!Cost.IsFree) {
341 // Consider simplified operands in instruction cost.
343 transform(I->operands(), std::back_inserter(Operands),
344 [&](Value *Op) {
345 if (auto Res = SimplifiedValues.lookup(Op))
346 return Res;
347 return Op;
348 });
349 UnrolledCost += TTI.getInstructionCost(I, Operands, CostKind);
351 << "Adding cost of instruction (iteration " << Iteration
352 << "): ");
353 LLVM_DEBUG(I->dump());
354 }
355
356 // We must count the cost of every operand which is not free,
357 // recursively. If we reach a loop PHI node, simply add it to the set
358 // to be considered on the next iteration (backwards!).
359 for (Value *Op : I->operands()) {
360 // Check whether this operand is free due to being a constant or
361 // outside the loop.
362 auto *OpI = dyn_cast<Instruction>(Op);
363 if (!OpI || !L->contains(OpI))
364 continue;
365
366 // Otherwise accumulate its cost.
367 CostWorklist.push_back(OpI);
368 }
369 } while (!CostWorklist.empty());
370
371 if (PHIUsedList.empty())
372 // We've exhausted the search.
373 break;
374
375 assert(Iteration > 0 &&
376 "Cannot track PHI-used values past the first iteration!");
377 CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
378 PHIUsedList.clear();
379 }
380 };
381
382 // Ensure that we don't violate the loop structure invariants relied on by
383 // this analysis.
384 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
385 assert(L->isLCSSAForm(DT) &&
386 "Must have loops in LCSSA form to track live-out values.");
387
389 << "Starting LoopUnroll profitability analysis...\n");
390
392 L->getHeader()->getParent()->hasMinSize() ?
394 // Simulate execution of each iteration of the loop counting instructions,
395 // which would be simplified.
396 // Since the same load will take different values on different iterations,
397 // we literally have to go through all loop's iterations.
398 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
399 LLVM_DEBUG(dbgs().indent(3) << "Analyzing iteration " << Iteration << "\n");
400
401 // Prepare for the iteration by collecting any simplified entry or backedge
402 // inputs.
403 for (Instruction &I : *L->getHeader()) {
404 auto *PHI = dyn_cast<PHINode>(&I);
405 if (!PHI)
406 break;
407
408 // The loop header PHI nodes must have exactly two input: one from the
409 // loop preheader and one from the loop latch.
410 assert(
411 PHI->getNumIncomingValues() == 2 &&
412 "Must have an incoming value only for the preheader and the latch.");
413
414 Value *V = PHI->getIncomingValueForBlock(
415 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
416 if (Iteration != 0 && SimplifiedValues.contains(V))
417 V = SimplifiedValues.lookup(V);
418 SimplifiedInputValues.push_back({PHI, V});
419 }
420
421 // Now clear and re-populate the map for the next iteration.
422 SimplifiedValues.clear();
423 while (!SimplifiedInputValues.empty())
424 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
425
426 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
427
428 BBWorklist.clear();
429 BBWorklist.insert(L->getHeader());
430 // Note that we *must not* cache the size, this loop grows the worklist.
431 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
432 BasicBlock *BB = BBWorklist[Idx];
433
434 // Visit all instructions in the given basic block and try to simplify
435 // it. We don't change the actual IR, just count optimization
436 // opportunities.
437 for (Instruction &I : *BB) {
438 // These won't get into the final code - don't even try calculating the
439 // cost for them.
440 if (EphValues.contains(&I))
441 continue;
442
443 // Track this instruction's expected baseline cost when executing the
444 // rolled loop form.
445 RolledDynamicCost += TTI.getInstructionCost(&I, CostKind);
446
447 // Visit the instruction to analyze its loop cost after unrolling,
448 // and if the visitor returns true, mark the instruction as free after
449 // unrolling and continue.
450 bool IsFree = Analyzer.visit(I);
451 bool Inserted = InstCostMap.insert({&I, (int)Iteration,
452 (unsigned)IsFree,
453 /*IsCounted*/ false}).second;
454 (void)Inserted;
455 assert(Inserted && "Cannot have a state for an unvisited instruction!");
456
457 if (IsFree)
458 continue;
459
460 // Can't properly model a cost of a call.
461 // FIXME: With a proper cost model we should be able to do it.
462 if (auto *CI = dyn_cast<CallInst>(&I)) {
463 const Function *Callee = CI->getCalledFunction();
464 if (!Callee || TTI.isLoweredToCall(Callee)) {
466 << "Can't analyze cost of loop with call\n");
467 return std::nullopt;
468 }
469 }
470
471 // If the instruction might have a side-effect recursively account for
472 // the cost of it and all the instructions leading up to it.
473 if (I.mayHaveSideEffects())
474 AddCostRecursively(I, Iteration);
475
476 // If unrolled body turns out to be too big, bail out.
477 if (UnrolledCost > MaxUnrolledLoopSize) {
478 LLVM_DEBUG({
479 dbgs().indent(3) << "Exceeded threshold.. exiting.\n";
480 dbgs().indent(3)
481 << "UnrolledCost: " << UnrolledCost
482 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize << "\n";
483 });
484 return std::nullopt;
485 }
486 }
487
488 Instruction *TI = BB->getTerminator();
489
490 auto getSimplifiedConstant = [&](Value *V) -> Constant * {
491 if (SimplifiedValues.contains(V))
492 V = SimplifiedValues.lookup(V);
493 return dyn_cast<Constant>(V);
494 };
495
496 // Add in the live successors by first checking whether we have terminator
497 // that may be simplified based on the values simplified by this call.
498 BasicBlock *KnownSucc = nullptr;
499 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
500 if (auto *SimpleCond = getSimplifiedConstant(BI->getCondition())) {
501 // Just take the first successor if condition is undef
502 if (isa<UndefValue>(SimpleCond))
503 KnownSucc = BI->getSuccessor(0);
504 else if (ConstantInt *SimpleCondVal =
505 dyn_cast<ConstantInt>(SimpleCond))
506 KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
507 }
508 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
509 if (auto *SimpleCond = getSimplifiedConstant(SI->getCondition())) {
510 // Just take the first successor if condition is undef
511 if (isa<UndefValue>(SimpleCond))
512 KnownSucc = SI->getSuccessor(0);
513 else if (ConstantInt *SimpleCondVal =
514 dyn_cast<ConstantInt>(SimpleCond))
515 KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
516 }
517 }
518 if (KnownSucc) {
519 if (L->contains(KnownSucc))
520 BBWorklist.insert(KnownSucc);
521 else
522 ExitWorklist.insert({BB, KnownSucc});
523 continue;
524 }
525
526 // Add BB's successors to the worklist.
527 for (BasicBlock *Succ : successors(BB))
528 if (L->contains(Succ))
529 BBWorklist.insert(Succ);
530 else
531 ExitWorklist.insert({BB, Succ});
532 AddCostRecursively(*TI, Iteration);
533 }
534
535 // If we found no optimization opportunities on the first iteration, we
536 // won't find them on later ones too.
537 if (UnrolledCost == RolledDynamicCost) {
538 LLVM_DEBUG({
539 dbgs().indent(3) << "No opportunities found.. exiting.\n";
540 dbgs().indent(3) << "UnrolledCost: " << UnrolledCost << "\n";
541 });
542 return std::nullopt;
543 }
544 }
545
546 while (!ExitWorklist.empty()) {
547 BasicBlock *ExitingBB, *ExitBB;
548 std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
549
550 for (Instruction &I : *ExitBB) {
551 auto *PN = dyn_cast<PHINode>(&I);
552 if (!PN)
553 break;
554
555 Value *Op = PN->getIncomingValueForBlock(ExitingBB);
556 if (auto *OpI = dyn_cast<Instruction>(Op))
557 if (L->contains(OpI))
558 AddCostRecursively(*OpI, TripCount - 1);
559 }
560 }
561
562 assert(UnrolledCost.isValid() && RolledDynamicCost.isValid() &&
563 "All instructions must have a valid cost, whether the "
564 "loop is rolled or unrolled.");
565
566 LLVM_DEBUG({
567 dbgs().indent(3) << "Analysis finished:\n";
568 dbgs().indent(3) << "UnrolledCost: " << UnrolledCost
569 << ", RolledDynamicCost: " << RolledDynamicCost << "\n";
570 });
571 return {{unsigned(UnrolledCost.getValue()),
572 unsigned(RolledDynamicCost.getValue())}};
573}
574
576 const Loop *L, const TargetTransformInfo &TTI,
577 const SmallPtrSetImpl<const Value *> &EphValues, unsigned BEInsns,
578 bool PrepareForLTO, bool TripCountIsUniform) {
580 for (BasicBlock *BB : L->blocks())
581 Metrics.analyzeBasicBlock(BB, TTI, EphValues, PrepareForLTO, L);
582 NumInlineCandidates = Metrics.NumInlineCandidates;
583 NotDuplicatable = Metrics.notDuplicatable;
584 Convergence = Metrics.Convergence;
585 LoopSize = Metrics.NumInsts;
586 // Convergent operations make the remainder prelude unsafe by adding a
587 // control-flow dependency, unless the trip count is uniform per
588 // UniformityInfo, in which case all paths agree and the remainder is safe.
590 (Metrics.Convergence != ConvergenceKind::Uncontrolled &&
592 TripCountIsUniform;
593
594 // Don't allow an estimate of size zero. This would allows unrolling of loops
595 // with huge iteration counts, which is a compile time problem even if it's
596 // not a problem for code quality. Also, the code using this size may assume
597 // that each loop has at least three instructions (likely a conditional
598 // branch, a comparison feeding that branch, and some kind of loop increment
599 // feeding that comparison instruction).
600 if (LoopSize.isValid() && LoopSize < BEInsns + 1)
601 // This is an open coded max() on InstructionCost
602 LoopSize = BEInsns + 1;
603}
604
606 const Loop *L) const {
607 auto ReportCannotUnroll = [&](StringRef Reason) {
608 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling: " << Reason << ".\n");
609 if (ORE && L)
610 ORE->emit([&]() {
611 return OptimizationRemarkMissed(DEBUG_TYPE, "CannotUnrollLoop",
612 L->getStartLoc(), L->getHeader())
613 << "unable to unroll loop: " << Reason;
614 });
615 };
616
618 ReportCannotUnroll("contains convergent operations");
619 return false;
620 }
621 if (!LoopSize.isValid()) {
622 ReportCannotUnroll("loop size could not be computed");
623 return false;
624 }
625 if (NotDuplicatable) {
626 ReportCannotUnroll("contains non-duplicatable instructions");
627 return false;
628 }
629 return true;
630}
631
633 const TargetTransformInfo::UnrollingPreferences &UP, unsigned Count) const {
634 unsigned LS = LoopSize.getValue();
635 assert(LS >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
636 return static_cast<uint64_t>(LS - UP.BEInsns) * Count + UP.BEInsns;
637}
638
639// Returns true if the loop has an unroll(full) pragma.
640static bool hasUnrollFullPragma(const Loop *L) {
641 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
642}
643
644// Returns true if the loop has an unroll(enable) pragma. This metadata is used
645// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
646static bool hasUnrollEnablePragma(const Loop *L) {
647 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
648}
649
650// Returns true if the loop has a runtime unroll(disable) pragma.
651static bool hasRuntimeUnrollDisablePragma(const Loop *L) {
652 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
653}
654
655/// Returns true if the SCEV expression is uniform, i.e., all threads in a
656/// convergent execution agree on its value. Recursively checks operands.
657/// Returns false if the SCEV could not be computed.
658static bool isSCEVUniform(const SCEV *S, UniformityInfo &UI) {
660 return false;
661 if (isa<SCEVConstant>(S))
662 return true;
663 if (auto *U = dyn_cast<SCEVUnknown>(S))
664 return UI.isUniformAtDef(U->getValue());
665 for (const SCEV *Op : S->operands()) {
666 if (!isSCEVUniform(Op, UI))
667 return false;
668 }
669 return true;
670}
671
672// If loop has an unroll_count pragma return the (necessarily
673// positive) value from the pragma. Otherwise return 0.
674static unsigned unrollCountPragmaValue(const Loop *L) {
675 MDNode *MD = getUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
676 if (MD) {
677 assert(MD->getNumOperands() == 2 &&
678 "Unroll count hint metadata should have two operands.");
679 unsigned Count =
680 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
681 assert(Count >= 1 && "Unroll count must be positive.");
682 return Count;
683 }
684 return 0;
685}
686
695
696// Computes the boosting factor for complete unrolling.
697// If fully unrolling the loop would save a lot of RolledDynamicCost, it would
698// be beneficial to fully unroll the loop even if unrolledcost is large. We
699// use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust
700// the unroll threshold.
701static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost,
702 unsigned MaxPercentThresholdBoost) {
703 if (Cost.RolledDynamicCost >= std::numeric_limits<unsigned>::max() / 100)
704 return 100;
705 else if (Cost.UnrolledCost != 0)
706 // The boosting factor is RolledDynamicCost / UnrolledCost
707 return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
708 MaxPercentThresholdBoost);
709 else
710 return MaxPercentThresholdBoost;
711}
712
713static std::optional<unsigned>
714shouldPragmaUnroll(const ScalarOptions &Opts, Loop *L,
715 const UnrollPragmaInfo &PInfo, const unsigned TripMultiple,
716 const unsigned TripCount, unsigned MaxTripCount,
717 const UnrollCostEstimator UCE,
720
721 // Using unroll pragma
722 // 1st priority is unroll count set by "unroll-count" option.
723
724 if (PInfo.UserUnrollCount) {
725 if (UP.AllowRemainder &&
726 UCE.getUnrolledLoopSize(UP, *Opts.unroll_count) < UP.Threshold) {
727 LLVM_DEBUG(dbgs().indent(2) << "Unrolling with user-specified count: "
728 << *Opts.unroll_count << ".\n");
729 return *Opts.unroll_count;
730 }
732 << "Not unrolling with user count " << *Opts.unroll_count << ": "
733 << (UP.AllowRemainder ? "exceeds threshold"
734 : "remainder not allowed")
735 << ".\n");
736 }
737
738 // 2nd priority is unroll count set by pragma.
739 if (PInfo.PragmaCount > 0) {
740 if ((UP.AllowRemainder || (TripMultiple % PInfo.PragmaCount == 0))) {
741 LLVM_DEBUG(dbgs().indent(2) << "Unrolling with pragma count: "
742 << PInfo.PragmaCount << ".\n");
743 return PInfo.PragmaCount;
744 }
746 << "Not unrolling with pragma count " << PInfo.PragmaCount
747 << ": remainder not allowed, count does not divide trip "
748 << "multiple " << TripMultiple << ".\n");
749 ORE->emit([&]() {
750 return OptimizationRemarkAnalysis(DEBUG_TYPE, "PragmaUnrollCountRejected",
751 L->getStartLoc(), L->getHeader())
752 << "may be unable to unroll loop with count "
753 << ore::NV("PragmaCount", PInfo.PragmaCount)
754 << ": remainder loop is not allowed and count does not divide "
755 "trip multiple "
756 << ore::NV("TripMultiple", TripMultiple);
757 });
758 }
759
760 if (PInfo.PragmaFullUnroll) {
761 if (TripCount != 0) {
762 // Certain cases with UBSAN can cause trip count to be calculated as
763 // INT_MAX, Block full unrolling at a reasonable limit so that the
764 // compiler doesn't hang trying to unroll the loop. See PR77842
765 if (TripCount > Opts.pragma_unroll_full_max_iterations) {
767 << "Won't unroll; trip count is too large.\n");
768 ORE->emit([&]() {
770 "PragmaFullUnrollTripCountTooLarge",
771 L->getStartLoc(), L->getHeader())
772 << "may be unable to fully unroll loop: trip count "
773 << ore::NV("TripCount", TripCount) << " exceeds limit "
774 << ore::NV("Limit", Opts.pragma_unroll_full_max_iterations);
775 });
776 return std::nullopt;
777 }
778
780 << "Fully unrolling with trip count: " << TripCount << ".\n");
781 return TripCount;
782 }
784 << "Not fully unrolling: unknown trip count.\n");
785 ORE->emit([&]() {
787 "PragmaFullUnrollUnknownTripCount",
788 L->getStartLoc(), L->getHeader())
789 << "may be unable to fully unroll loop: trip count is unknown";
790 });
791 }
792
793 if (PInfo.PragmaEnableUnroll && !TripCount && MaxTripCount &&
794 MaxTripCount <= UP.MaxUpperBound) {
796 << "Unrolling with max trip count: " << MaxTripCount << ".\n");
797 return MaxTripCount;
798 }
799
800 return std::nullopt;
801}
802
803static std::optional<unsigned> shouldFullUnroll(
806 const unsigned FullUnrollTripCount, const UnrollCostEstimator UCE,
808 assert(FullUnrollTripCount && "should be non-zero!");
809
810 if (FullUnrollTripCount > UP.FullUnrollMaxCount) {
812 << "Not unrolling: trip count " << FullUnrollTripCount
813 << " exceeds max count " << UP.FullUnrollMaxCount << ".\n");
814 return std::nullopt;
815 }
816
817 // When computing the unrolled size, note that BEInsns are not replicated
818 // like the rest of the loop body.
819 uint64_t UnrolledSize = UCE.getUnrolledLoopSize(UP, FullUnrollTripCount);
820 if (UnrolledSize < UP.Threshold) {
821 LLVM_DEBUG(dbgs().indent(2) << "Unrolling: size " << UnrolledSize
822 << " < threshold " << UP.Threshold << ".\n");
823 return FullUnrollTripCount;
824 }
825
827 << "Unrolled size " << UnrolledSize << " exceeds threshold "
828 << UP.Threshold << "; checking for cost benefit.\n");
829
830 // The loop isn't that small, but we still can fully unroll it if that
831 // helps to remove a significant number of instructions.
832 // To check that, run additional analysis on the loop.
833 if (std::optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
834 L, FullUnrollTripCount, DT, SE, EphValues, TTI,
837 unsigned Boost =
839 unsigned BoostedThreshold = UP.Threshold * Boost / 100;
840 if (Cost->UnrolledCost < BoostedThreshold) {
841 LLVM_DEBUG(dbgs().indent(2) << "Profitable after cost analysis.\n");
842 return FullUnrollTripCount;
843 }
845 << "Not unrolling: cost " << Cost->UnrolledCost
846 << " >= boosted threshold " << BoostedThreshold << ".\n");
847 }
848
849 return std::nullopt;
850}
851
852static std::optional<unsigned>
853shouldPartialUnroll(const unsigned LoopSize, const unsigned TripCount,
854 const UnrollCostEstimator UCE,
856
857 if (!TripCount)
858 return std::nullopt;
859
860 if (!UP.Partial) {
861 LLVM_DEBUG(dbgs().indent(2) << "Will not try to unroll partially because "
862 << "-unroll-allow-partial not given\n");
863 return 0;
864 }
865 unsigned Count = TripCount;
866 if (UP.PartialThreshold != NoThreshold) {
867 // Reduce unroll count to be modulo of TripCount for partial unrolling.
868 if (UCE.getUnrolledLoopSize(UP, Count) > UP.PartialThreshold) {
869 unsigned NewCount =
870 (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) /
871 (LoopSize - UP.BEInsns);
873 << "Unrolled size exceeds threshold; reducing count "
874 << "from " << Count << " to " << NewCount << ".\n");
875 Count = NewCount;
876 }
877 if (Count > UP.MaxCount)
878 Count = UP.MaxCount;
879 while (Count != 0 && TripCount % Count != 0)
880 Count--;
881 if (UP.AllowRemainder && Count <= 1) {
882 // If there is no Count that is modulo of TripCount, set Count to
883 // largest power-of-two factor that satisfies the threshold limit.
884 // As we'll create fixup loop, do the type of unrolling only if
885 // remainder loop is allowed.
886 // Note: DefaultUnrollRuntimeCount is used as a reasonable starting point
887 // even though this is partial unrolling (not runtime unrolling).
889 while (Count != 0 &&
891 Count >>= 1;
892 }
893 if (Count < 2) {
895 << "Will not partially unroll: no profitable count.\n");
896 Count = 0;
897 }
898 } else {
899 Count = TripCount;
900 }
901 if (Count > UP.MaxCount)
902 Count = UP.MaxCount;
903
905 << "Partially unrolling with count: " << Count << "\n");
906
907 return Count;
908}
909
910static unsigned
911shouldRuntimeUnroll(Loop *L, unsigned MaxTripCount, unsigned TripMultiple,
912 const UnrollCostEstimator &UCE,
913 const UnrollPragmaInfo &PInfo, const ScalarOptions &Opts,
915 // Don't unroll a runtime trip count loop when it is disabled.
916 if (PInfo.PragmaRuntimeUnrollDisable) {
918 << "Not runtime unrolling: disabled by pragma.\n");
919 return 0;
920 }
921
922 // Don't unroll a small upper bound loop unless user or TTI asked to do so.
923 if (MaxTripCount && !UP.Force && MaxTripCount <= UP.MaxUpperBound) {
924 LLVM_DEBUG(dbgs().indent(2) << "Not runtime unrolling: max trip count "
925 << MaxTripCount << " is small (<= "
926 << UP.MaxUpperBound << ") and not forced.\n");
927 return 0;
928 }
929
930 // Check if the runtime trip count is too small when profile is available.
931 if (L->getHeader()->getParent()->hasProfileData()) {
932 if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) {
933 if (*ProfileTripCount < Opts.flat_loop_tripcount_threshold)
934 return 0;
935 else
936 UP.AllowExpensiveTripCount = true;
937 }
938 }
939 if (!UP.Runtime) {
941 << "Will not try to unroll loop with runtime trip count "
942 << "because -unroll-runtime not given\n");
943 return 0;
944 }
945
946 unsigned Count = UP.DefaultUnrollRuntimeCount;
947
948 // Reduce unroll count to be the largest power-of-two factor of
949 // the original count which satisfies the threshold limit.
950 while (Count != 0 && UCE.getUnrolledLoopSize(UP, Count) > UP.PartialThreshold)
951 Count >>= 1;
952
953#ifndef NDEBUG
954 unsigned OrigCount = Count;
955#endif
956
957 if (!UP.AllowRemainder && Count != 0 && (TripMultiple % Count) != 0) {
958 while (Count != 0 && TripMultiple % Count != 0)
959 Count >>= 1;
961 << "Remainder loop is restricted (that could be architecture "
962 "specific or because the loop contains a convergent "
963 "instruction), so unroll count must divide the trip "
964 "multiple, "
965 << TripMultiple << ". Reducing unroll count from " << OrigCount
966 << " to " << Count << ".\n");
967 }
968
969 if (Count > UP.MaxCount)
970 Count = UP.MaxCount;
971
972 if (MaxTripCount && Count > MaxTripCount)
973 Count = MaxTripCount;
974
975 if (Count < 2)
976 Count = 0;
977 else
979 << "Runtime unrolling with count: " << Count << "\n");
980 return Count;
981}
982
983// Calculates and returns the unroll count, using metadata and command-line
984// options that are specific to the LoopUnroll pass (which, for instance, are
985// irrelevant for the LoopUnrollAndJam pass).
986// FIXME: This function is used by LoopUnroll and LoopUnrollAndJam, but consumes
987// many LoopUnroll-specific options. The shared functionality should be
988// refactored into it own function.
992 const SmallPtrSetImpl<const Value *> &EphValues,
993 OptimizationRemarkEmitter *ORE, const unsigned TripCount,
994 const unsigned MaxTripCount, const bool MaxOrZero,
995 const unsigned TripMultiple, const UnrollCostEstimator &UCE,
998 const ScalarOptions &Opts = getScalarOptions(*L);
999
1000 unsigned LoopSize = UCE.getRolledLoopSize();
1001
1002 LLVM_DEBUG(dbgs().indent(1) << "Computing unroll count: TripCount="
1003 << TripCount << ", MaxTripCount=" << MaxTripCount
1004 << (MaxOrZero ? " (MaxOrZero)" : "")
1005 << ", TripMultiple=" << TripMultiple << "\n");
1006
1007 UnrollPragmaInfo PInfo(L);
1008 LLVM_DEBUG({
1009 if (PInfo.ExplicitUnroll) {
1010 dbgs().indent(1) << "Explicit unroll requested:";
1011 if (PInfo.UserUnrollCount)
1012 dbgs() << " user-count";
1013 if (PInfo.PragmaFullUnroll)
1014 dbgs() << " pragma-full";
1015 if (PInfo.PragmaCount > 0)
1016 dbgs() << " pragma-count(" << PInfo.PragmaCount << ")";
1017 if (PInfo.PragmaEnableUnroll)
1018 dbgs() << " pragma-enable";
1019 dbgs() << "\n";
1020 }
1021 });
1022
1023 // Use an explicit peel count that has been specified for testing. In this
1024 // case it's not permitted to also specify an explicit unroll count.
1025 if (PP.PeelCount) {
1026 if (Opts.unroll_count) {
1027 reportFatalUsageError("Cannot specify both explicit peel count and "
1028 "explicit unroll count");
1029 }
1031 << "Using explicit peel count: " << PP.PeelCount << ".\n");
1032 UP.Runtime = false;
1033 return 1;
1034 }
1035
1036 // If a user provided an explicit unroll pragma (with or without count),
1037 // enable runtime unrolling and override expensive trip count checks.
1038 if (PInfo.PragmaEnableUnroll || PInfo.PragmaCount > 0) {
1039 UP.AllowExpensiveTripCount = true;
1040 UP.Runtime = true;
1041 }
1042
1043 // Check for an explicit unroll count.
1044 // 1st priority is unroll count set by "unroll-count" option.
1045 // 2nd priority is unroll count set by pragma.
1046 LLVM_DEBUG(dbgs().indent(1) << "Trying pragma unroll...\n");
1047 if (auto UnrollFactor =
1048 shouldPragmaUnroll(Opts, L, PInfo, TripMultiple, TripCount,
1049 MaxTripCount, UCE, UP, ORE)) {
1050 if (PInfo.UserUnrollCount || (PInfo.PragmaCount > 0)) {
1051 UP.AllowExpensiveTripCount = true;
1052 UP.Force = true;
1053 }
1054 return *UnrollFactor;
1055 } else {
1056 if (PInfo.ExplicitUnroll && TripCount != 0) {
1057 // If the loop has an unrolling pragma, we want to be more aggressive with
1058 // unrolling limits. Set thresholds to at least the PragmaUnrollThreshold
1059 // value which is larger than the default limits.
1060 UP.Threshold = std::max(UP.Threshold, Opts.pragma_unroll_threshold);
1061 UP.PartialThreshold =
1062 std::max(UP.PartialThreshold, Opts.pragma_unroll_threshold);
1063 }
1064 }
1065
1066 // 3rd priority is exact full unrolling. This will eliminate all copies
1067 // of some exit test.
1068 LLVM_DEBUG(dbgs().indent(1) << "Trying full unroll...\n");
1069 if (TripCount) {
1070 if (auto UnrollFactor =
1071 shouldFullUnroll(L, TTI, DT, SE, EphValues, TripCount, UCE, UP))
1072 return *UnrollFactor;
1073 }
1074
1075 // 4th priority is bounded unrolling.
1076 // We can unroll by the upper bound amount if it's generally allowed or if
1077 // we know that the loop is executed either the upper bound or zero times.
1078 // (MaxOrZero unrolling keeps only the first loop test, so the number of
1079 // loop tests remains the same compared to the non-unrolled version, whereas
1080 // the generic upper bound unrolling keeps all but the last loop test so the
1081 // number of loop tests goes up which may end up being worse on targets with
1082 // constrained branch predictor resources so is controlled by an option.)
1083 // In addition we only unroll small upper bounds.
1084 // Note that the cost of bounded unrolling is always strictly greater than
1085 // cost of exact full unrolling. As such, if we have an exact count and
1086 // found it unprofitable, we'll never chose to bounded unroll.
1087 LLVM_DEBUG(dbgs().indent(1) << "Trying upper-bound unroll...\n");
1088 if (!TripCount && MaxTripCount && (UP.UpperBound || MaxOrZero) &&
1089 MaxTripCount <= UP.MaxUpperBound) {
1090 if (auto UnrollFactor =
1091 shouldFullUnroll(L, TTI, DT, SE, EphValues, MaxTripCount, UCE, UP))
1092 return *UnrollFactor;
1093 }
1094
1095 // 5th priority is loop peeling.
1096 LLVM_DEBUG(dbgs().indent(1) << "Trying loop peeling...\n");
1097 computePeelCount(L, LoopSize, PP, TripCount, DT, SE, TTI, AC, UP.Threshold);
1098 if (PP.PeelCount) {
1100 << "Peeling with count: " << PP.PeelCount << ".\n");
1101 UP.Runtime = false;
1102 return 1;
1103 }
1104
1105 // Before starting partial unrolling, set UP.Partial to true,
1106 // if user explicitly asked for unrolling.
1107 if (TripCount)
1108 UP.Partial |= PInfo.ExplicitUnroll;
1109
1110 // 6th priority is partial unrolling.
1111 // Try partial unroll only when TripCount could be statically calculated.
1112 LLVM_DEBUG(dbgs().indent(1) << "Trying partial unroll...\n");
1113 if (auto UnrollFactor = shouldPartialUnroll(LoopSize, TripCount, UCE, UP))
1114 return *UnrollFactor;
1115 assert(TripCount == 0 &&
1116 "All cases when TripCount is constant should be covered here.");
1117
1118 // 7th priority is runtime unrolling.
1119 LLVM_DEBUG(dbgs().indent(1) << "Trying runtime unroll...\n");
1120 return shouldRuntimeUnroll(L, MaxTripCount, TripMultiple, UCE, PInfo, Opts,
1121 UP);
1122}
1123
1124static LoopUnrollResult
1128 ProfileSummaryInfo *PSI, bool PreserveLCSSA, int OptLevel,
1129 bool OnlyFullUnroll, bool OnlyWhenForced, bool ForgetAllSCEV,
1130 bool PrepareForLTO, std::optional<unsigned> ProvidedThreshold,
1131 std::optional<bool> ProvidedAllowPartial,
1132 std::optional<bool> ProvidedRuntime,
1133 std::optional<bool> ProvidedUpperBound,
1134 std::optional<bool> ProvidedAllowPeeling,
1135 std::optional<bool> ProvidedAllowProfileBasedPeeling,
1136 std::optional<unsigned> ProvidedFullUnrollMaxCount,
1137 UniformityInfo *UI = nullptr, AAResults *AA = nullptr) {
1138
1139 LLVM_DEBUG(dbgs() << "Loop Unroll: F["
1140 << L->getHeader()->getParent()->getName() << "] Loop %"
1141 << L->getHeader()->getName()
1142 << " (depth=" << L->getLoopDepth() << ")\n");
1144 if (TM & TM_Disable) {
1145 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling: transformation disabled by "
1146 << "metadata.\n");
1148 }
1149
1150 // If this loop isn't forced to be unrolled, avoid unrolling it when the
1151 // parent loop has an explicit unroll-and-jam pragma. This is to prevent
1152 // automatic unrolling from interfering with the user requested
1153 // transformation.
1154 Loop *ParentL = L->getParentLoop();
1155 if (ParentL != nullptr &&
1158 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling loop since parent loop has"
1159 << " llvm.loop.unroll_and_jam.\n");
1161 }
1162
1163 // If this loop isn't forced to be unrolled, avoid unrolling it when the
1164 // loop has an explicit unroll-and-jam pragma. This is to prevent automatic
1165 // unrolling from interfering with the user requested transformation.
1168 LLVM_DEBUG(
1169 dbgs().indent(1)
1170 << "Not unrolling loop since it has llvm.loop.unroll_and_jam.\n");
1172 }
1173
1174 if (!L->isLoopSimplifyForm()) {
1176 << "Not unrolling loop which is not in loop-simplify form.\n");
1177 if (TM & TM_ForcedByUser) {
1178 ORE.emit([&]() {
1179 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInLoopSimplifyForm",
1180 L->getStartLoc(), L->getHeader())
1181 << "unable to unroll loop: not in loop-simplify form";
1182 });
1183 }
1185 }
1186
1187 // When automatic unrolling is disabled, do not unroll unless overridden for
1188 // this loop.
1189 if (OnlyWhenForced && !(TM & TM_Enable)) {
1190 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling: automatic unrolling "
1191 << "disabled and loop not explicitly "
1192 << "enabled.\n");
1194 }
1195
1196 bool OptForSize = L->getHeader()->getParent()->hasOptSize();
1198 L, SE, TTI, BFI, PSI, ORE, OptLevel, ProvidedThreshold,
1199 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
1200 ProvidedFullUnrollMaxCount);
1202 L, SE, TTI, ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling, true);
1203
1204 // Exit early if unrolling is disabled. For OptForSize, we pick the loop size
1205 // as threshold later on.
1206 if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0) &&
1207 !OptForSize) {
1208 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling: all thresholds are zero.\n");
1209 if (TM & TM_ForcedByUser) {
1210 ORE.emit([&]() {
1211 return OptimizationRemarkMissed(DEBUG_TYPE, "UnrollThresholdsZero",
1212 L->getStartLoc(), L->getHeader())
1213 << "unable to unroll loop: unroll threshold is zero";
1214 });
1215 }
1217 }
1218
1220 CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
1221
1222 // Check if the backedge-taken count is uniform before constructing UCE.
1223 // This is used to allow runtime unrolling with a remainder for convergent
1224 // loops when all threads agree on the trip count.
1225 const SCEV *BTC = SE.getBackedgeTakenCount(L);
1226 bool TripCountIsUniform = UI && isSCEVUniform(BTC, *UI);
1227 UnrollCostEstimator UCE(L, TTI, EphValues, UP.BEInsns, PrepareForLTO,
1228 TripCountIsUniform);
1229 if (!UCE.canUnroll((TM & TM_ForcedByUser) ? &ORE : nullptr, L))
1231
1232 unsigned LoopSize = UCE.getRolledLoopSize();
1233 LLVM_DEBUG(dbgs() << "Loop Size = " << LoopSize << "\n");
1234
1235 // When optimizing for size, use LoopSize + 1 as threshold (we use < Threshold
1236 // later), to (fully) unroll loops, if it does not increase code size.
1237 if (OptForSize)
1238 UP.Threshold = std::max(UP.Threshold, LoopSize + 1);
1239
1240 if (UCE.NumInlineCandidates != 0) {
1242 << "Not unrolling loop with inlinable calls.\n");
1243 if (TM & TM_ForcedByUser) {
1244 ORE.emit([&]() {
1246 "InlineCandidatesPreventUnroll",
1247 L->getStartLoc(), L->getHeader())
1248 << "unable to unroll loop: contains inlinable calls";
1249 });
1250 }
1252 }
1253
1254 // Find the smallest exact trip count for any exit. This is an upper bound
1255 // on the loop trip count, but an exit at an earlier iteration is still
1256 // possible. An unroll by the smallest exact trip count guarantees that all
1257 // branches relating to at least one exit can be eliminated. This is unlike
1258 // the max trip count, which only guarantees that the backedge can be broken.
1259 unsigned TripCount = 0;
1260 unsigned TripMultiple = 1;
1261 SmallVector<BasicBlock *, 8> ExitingBlocks;
1262 L->getExitingBlocks(ExitingBlocks);
1263 for (BasicBlock *ExitingBlock : ExitingBlocks)
1264 if (unsigned TC = SE.getSmallConstantTripCount(L, ExitingBlock))
1265 if (!TripCount || TC < TripCount)
1266 TripCount = TripMultiple = TC;
1267
1268 if (!TripCount) {
1269 // If no exact trip count is known, determine the trip multiple of either
1270 // the loop latch or the single exiting block.
1271 // TODO: Relax for multiple exits.
1272 BasicBlock *ExitingBlock = L->getLoopLatch();
1273 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
1274 ExitingBlock = L->getExitingBlock();
1275 if (ExitingBlock)
1276 TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock);
1277 }
1278
1279 // If the loop contains a convergent operation, the prelude we'd add
1280 // to do the first few instructions before we hit the unrolled loop
1281 // is unsafe -- it adds a control-flow dependency to the convergent
1282 // operation. Therefore restrict remainder loop (try unrolling without).
1284
1285 // Try to find the trip count upper bound if we cannot find the exact trip
1286 // count.
1287 unsigned MaxTripCount = 0;
1288 bool MaxOrZero = false;
1289 if (!TripCount) {
1290 MaxTripCount = SE.getSmallConstantMaxTripCount(L);
1291 MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L);
1292 }
1293
1294 // computeUnrollCount() decides whether it is beneficial to use upper bound to
1295 // fully unroll the loop.
1296 unsigned Count =
1297 computeUnrollCount(L, TTI, DT, LI, &AC, SE, EphValues, &ORE, TripCount,
1298 MaxTripCount, MaxOrZero, TripMultiple, UCE, UP, PP);
1299 if (!Count) {
1301 << "Not unrolling: no viable strategy found.\n");
1302 if (TM & TM_ForcedByUser) {
1303 ORE.emit([&]() {
1304 return OptimizationRemarkMissed(DEBUG_TYPE, "NoUnrollStrategy",
1305 L->getStartLoc(), L->getHeader())
1306 << "unable to unroll loop: no viable unroll count found";
1307 });
1308 }
1310 }
1311
1313
1314 if (PP.PeelCount) {
1315 assert(Count == 1 && "Cannot perform peel and unroll in the same step");
1316 LLVM_DEBUG(dbgs() << "PEELING loop %" << L->getHeader()->getName()
1317 << " with iteration count " << PP.PeelCount << "!\n");
1318 ORE.emit([&]() {
1319 return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
1320 L->getHeader())
1321 << "peeled loop by " << ore::NV("PeelCount", PP.PeelCount)
1322 << " iterations";
1323 });
1324
1325 ValueToValueMapTy VMap;
1326 peelLoop(L, PP.PeelCount, PP.PeelLast, LI, &SE, DT, &AC, PreserveLCSSA,
1327 VMap);
1328 simplifyLoopAfterUnroll(L, true, LI, &SE, &DT, &AC, &TTI, L->getBlocks(),
1329 nullptr);
1330 // If the loop was peeled, we already "used up" the profile information
1331 // we had, so we don't want to unroll or peel again.
1333 L->setLoopAlreadyUnrolled();
1335 }
1336
1337 // Do not attempt partial/runtime unrolling in FullLoopUnrolling
1338 if (OnlyFullUnroll && ((!TripCount && !MaxTripCount) || Count < TripCount ||
1339 Count < MaxTripCount)) {
1341 << "Not attempting partial/runtime unroll in FullLoopUnroll.\n");
1343 }
1344
1345 // At this point, UP.Runtime indicates that run-time unrolling is allowed.
1346 // However, we only want to actually perform it if we don't know the trip
1347 // count and the unroll count doesn't divide the known trip multiple.
1348 // TODO: This decision should probably be pushed up into
1349 // computeUnrollCount().
1350 UP.Runtime &= TripCount == 0 && TripMultiple % Count != 0;
1351
1352 // Save loop properties before it is transformed.
1353 MDNode *OrigLoopID = L->getLoopID();
1354 UnrollPragmaInfo PInfo(L);
1355 DebugLoc LoopStartLoc = L->getStartLoc();
1356 BasicBlock *LoopHeader = L->getHeader();
1357
1358 // Unroll the loop.
1359 Loop *RemainderLoop = nullptr;
1361 ULO.Count = Count;
1362 ULO.Force = UP.Force;
1365 ULO.Runtime = UP.Runtime;
1366 ULO.ForgetAllSCEV = ForgetAllSCEV;
1371 LoopUnrollResult UnrollResult = UnrollLoop(
1372 L, ULO, LI, &SE, &DT, &AC, &TTI, &ORE, PreserveLCSSA, &RemainderLoop, AA);
1373 if (UnrollResult == LoopUnrollResult::Unmodified) {
1374 if (PInfo.ExplicitUnroll) {
1376 << "Failed to unroll loop as explicitly requested.\n");
1377 ORE.emit([&]() {
1378 return OptimizationRemarkMissed(DEBUG_TYPE, "FailedToUnrollAsRequested",
1379 LoopStartLoc, LoopHeader)
1380 << "failed to unroll loop as explicitly requested";
1381 });
1382 }
1384 }
1385
1386 if (PInfo.PragmaFullUnroll && ULO.Count != TripCount) {
1387 ORE.emit([&]() {
1388 return OptimizationRemarkMissed(DEBUG_TYPE, "FullUnrollAsDirectedFailed",
1389 LoopStartLoc, LoopHeader)
1390 << "unable to fully unroll loop as directed; "
1391 << "unrolled by factor " << ore::NV("UnrollCount", ULO.Count);
1392 });
1393 }
1394 if (PInfo.PragmaCount > 0 && ULO.Count != PInfo.PragmaCount) {
1395 ORE.emit([&]() {
1396 return OptimizationRemarkMissed(DEBUG_TYPE, "UnrollCountDiffers",
1397 LoopStartLoc, LoopHeader)
1398 << "unable to unroll loop with requested count "
1399 << ore::NV("RequestedCount", PInfo.PragmaCount)
1400 << "; unrolled by factor " << ore::NV("UnrollCount", ULO.Count);
1401 });
1402 }
1403
1404 if (RemainderLoop) {
1405 std::optional<MDNode *> RemainderLoopID =
1408 if (RemainderLoopID)
1409 RemainderLoop->setLoopID(*RemainderLoopID);
1410 }
1411
1412 if (UnrollResult != LoopUnrollResult::FullyUnrolled) {
1413 std::optional<MDNode *> NewLoopID =
1416 if (NewLoopID) {
1417 L->setLoopID(*NewLoopID);
1418
1419 // Do not setLoopAlreadyUnrolled if loop attributes have been specified
1420 // explicitly.
1421 return UnrollResult;
1422 }
1423 }
1424
1425 // If loop has an unroll count pragma or unrolled by explicitly set count
1426 // mark loop as unrolled to prevent unrolling beyond that requested.
1427 if (UnrollResult != LoopUnrollResult::FullyUnrolled && PInfo.ExplicitUnroll)
1428 L->setLoopAlreadyUnrolled();
1429
1430 return UnrollResult;
1431}
1432
1433namespace {
1434
1435class LoopUnroll : public LoopPass {
1436public:
1437 static char ID; // Pass ID, replacement for typeid
1438
1439 int OptLevel;
1440
1441 /// If false, use a cost model to determine whether unrolling of a loop is
1442 /// profitable. If true, only loops that explicitly request unrolling via
1443 /// metadata are considered. All other loops are skipped.
1444 bool OnlyWhenForced;
1445
1446 /// If false, when SCEV is invalidated, only forget everything in the
1447 /// top-most loop (call forgetTopMostLoop), of the loop being processed.
1448 /// Otherwise, forgetAllLoops and rebuild when needed next.
1449 bool ForgetAllSCEV;
1450
1451 std::optional<unsigned> ProvidedThreshold;
1452 std::optional<bool> ProvidedAllowPartial;
1453 std::optional<bool> ProvidedRuntime;
1454 std::optional<bool> ProvidedUpperBound;
1455 std::optional<bool> ProvidedAllowPeeling;
1456 std::optional<bool> ProvidedAllowProfileBasedPeeling;
1457 std::optional<unsigned> ProvidedFullUnrollMaxCount;
1458
1459 LoopUnroll(int OptLevel = 2, bool OnlyWhenForced = false,
1460 bool ForgetAllSCEV = false,
1461 std::optional<unsigned> Threshold = std::nullopt,
1462 std::optional<bool> AllowPartial = std::nullopt,
1463 std::optional<bool> Runtime = std::nullopt,
1464 std::optional<bool> UpperBound = std::nullopt,
1465 std::optional<bool> AllowPeeling = std::nullopt,
1466 std::optional<bool> AllowProfileBasedPeeling = std::nullopt,
1467 std::optional<unsigned> ProvidedFullUnrollMaxCount = std::nullopt)
1468 : LoopPass(ID), OptLevel(OptLevel), OnlyWhenForced(OnlyWhenForced),
1469 ForgetAllSCEV(ForgetAllSCEV), ProvidedThreshold(Threshold),
1470 ProvidedAllowPartial(AllowPartial), ProvidedRuntime(Runtime),
1471 ProvidedUpperBound(UpperBound), ProvidedAllowPeeling(AllowPeeling),
1472 ProvidedAllowProfileBasedPeeling(AllowProfileBasedPeeling),
1473 ProvidedFullUnrollMaxCount(ProvidedFullUnrollMaxCount) {
1475 }
1476
1477 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
1478 if (skipLoop(L))
1479 return false;
1480
1481 Function &F = *L->getHeader()->getParent();
1482
1483 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1484 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1485 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1486 const TargetTransformInfo &TTI =
1487 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1488 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1489 UniformityInfo *UI =
1491 ? &getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo()
1492 : nullptr;
1493 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
1494 // pass. Function analyses need to be preserved across loop transformations
1495 // but ORE cannot be preserved (see comment before the pass definition).
1496 OptimizationRemarkEmitter ORE(&F);
1497 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1498
1500 L, DT, LI, SE, TTI, AC, ORE, nullptr, nullptr, PreserveLCSSA, OptLevel,
1501 /*OnlyFullUnroll*/ false, OnlyWhenForced, ForgetAllSCEV,
1502 /*PrepareForLTO*/ false, ProvidedThreshold, ProvidedAllowPartial,
1503 ProvidedRuntime, ProvidedUpperBound, ProvidedAllowPeeling,
1504 ProvidedAllowProfileBasedPeeling, ProvidedFullUnrollMaxCount, UI);
1505
1506 if (Result == LoopUnrollResult::FullyUnrolled)
1507 LPM.markLoopAsDeleted(*L);
1508
1509 return Result != LoopUnrollResult::Unmodified;
1510 }
1511
1512 /// This transformation requires natural loop information & requires that
1513 /// loop preheaders be inserted into the CFG...
1514 void getAnalysisUsage(AnalysisUsage &AU) const override {
1515 AU.addRequired<AssumptionCacheTracker>();
1516 AU.addRequired<TargetTransformInfoWrapperPass>();
1517 AU.addRequired<UniformityInfoWrapperPass>();
1518 // FIXME: Loop passes are required to preserve domtree, and for now we just
1519 // recreate dom info if anything gets unrolled.
1521 }
1522};
1523
1524} // end anonymous namespace
1525
1526char LoopUnroll::ID = 0;
1527
1528INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1533INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1534
1535Pass *llvm::createLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1536 bool ForgetAllSCEV, int Threshold,
1537 int AllowPartial, int Runtime, int UpperBound,
1538 int AllowPeeling) {
1539 // TODO: It would make more sense for this function to take the optionals
1540 // directly, but that's dangerous since it would silently break out of tree
1541 // callers.
1542 return new LoopUnroll(
1543 OptLevel, OnlyWhenForced, ForgetAllSCEV,
1544 Threshold == -1 ? std::nullopt : std::optional<unsigned>(Threshold),
1545 AllowPartial == -1 ? std::nullopt : std::optional<bool>(AllowPartial),
1546 Runtime == -1 ? std::nullopt : std::optional<bool>(Runtime),
1547 UpperBound == -1 ? std::nullopt : std::optional<bool>(UpperBound),
1548 AllowPeeling == -1 ? std::nullopt : std::optional<bool>(AllowPeeling));
1549}
1550
1553 LPMUpdater &Updater) {
1554 // For the new PM, we can't use OptimizationRemarkEmitter as an analysis
1555 // pass. Function analyses need to be preserved across loop transformations
1556 // but ORE cannot be preserved (see comment before the pass definition).
1557 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
1558 const ScalarOptions &Opts = getScalarOptions(L);
1559
1560 // Keep track of the previous loop structure so we can identify new loops
1561 // created by unrolling.
1562 Loop *ParentL = L.getParentLoop();
1563 SmallPtrSet<Loop *, 4> OldLoops;
1564 if (ParentL)
1565 OldLoops.insert_range(*ParentL);
1566 else
1567 OldLoops.insert_range(AR.LI);
1568
1569 std::string LoopName = std::string(L.getName());
1570
1571 bool Changed =
1572 tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, ORE,
1573 /*BFI*/ nullptr, /*PSI*/ nullptr,
1574 /*PreserveLCSSA*/ true, OptLevel, /*OnlyFullUnroll*/ true,
1575 OnlyWhenForced, ForgetSCEV, PrepareForLTO,
1576 /*Threshold*/ std::nullopt, /*AllowPartial*/ false,
1577 /*Runtime*/ false, /*UpperBound*/ false,
1578 /*AllowPeeling*/ true,
1579 /*AllowProfileBasedPeeling*/ false,
1580 /*FullUnrollMaxCount*/ std::nullopt) !=
1582 if (!Changed)
1583 return PreservedAnalyses::all();
1584
1585 // The parent must not be damaged by unrolling!
1586#ifndef NDEBUG
1587 if (ParentL)
1588 ParentL->verifyLoop();
1589#endif
1590
1591 // Unrolling can do several things to introduce new loops into a loop nest:
1592 // - Full unrolling clones child loops within the current loop but then
1593 // removes the current loop making all of the children appear to be new
1594 // sibling loops.
1595 //
1596 // When a new loop appears as a sibling loop after fully unrolling,
1597 // its nesting structure has fundamentally changed and we want to revisit
1598 // it to reflect that.
1599 //
1600 // When unrolling has removed the current loop, we need to tell the
1601 // infrastructure that it is gone.
1602 //
1603 // Finally, we support a debugging/testing mode where we revisit child loops
1604 // as well. These are not expected to require further optimizations as either
1605 // they or the loop they were cloned from have been directly visited already.
1606 // But the debugging mode allows us to check this assumption.
1607 bool IsCurrentLoopValid = false;
1608 SmallVector<Loop *, 4> SibLoops;
1609 if (ParentL)
1610 SibLoops.append(ParentL->begin(), ParentL->end());
1611 else
1612 SibLoops.append(AR.LI.begin(), AR.LI.end());
1613 erase_if(SibLoops, [&](Loop *SibLoop) {
1614 if (SibLoop == &L) {
1615 IsCurrentLoopValid = true;
1616 return true;
1617 }
1618
1619 // Otherwise erase the loop from the list if it was in the old loops.
1620 return OldLoops.contains(SibLoop);
1621 });
1622 Updater.addSiblingLoops(SibLoops);
1623
1624 if (!IsCurrentLoopValid) {
1625 Updater.markLoopAsDeleted(L, LoopName);
1626 } else {
1627 // We can only walk child loops if the current loop remained valid.
1628 if (Opts.unroll_revisit_child_loops) {
1629 // Walk *all* of the child loops.
1630 SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end());
1631 Updater.addChildLoops(ChildLoops);
1632 }
1633 }
1634
1636}
1637
1640 auto &LI = AM.getResult<LoopAnalysis>(F);
1641 // There are no loops in the function. Return before computing other expensive
1642 // analyses.
1643 if (LI.empty())
1644 return PreservedAnalyses::all();
1645 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1646 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1647 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1648 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1651
1652 UniformityInfo *UI = TTI.hasBranchDivergence(&F)
1654 : nullptr;
1655
1656 LoopAnalysisManager *LAM = nullptr;
1657 if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F))
1658 LAM = &LAMProxy->getManager();
1659
1660 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1661 ProfileSummaryInfo *PSI =
1662 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1663 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
1664 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
1665
1666 bool Changed = false;
1667
1668 // The unroller requires loops to be in simplified form, and also needs LCSSA.
1669 // Since simplification may add new inner loops, it has to run before the
1670 // legality and profitability checks. This means running the loop unroller
1671 // will simplify all loops, regardless of whether anything end up being
1672 // unrolled.
1673 for (const auto &L : LI) {
1674 Changed |=
1675 simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
1676 Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
1677 }
1678
1679 // Add the loop nests in the reverse order of LoopInfo. See method
1680 // declaration.
1682 appendLoopsToWorklist(LI, Worklist);
1683
1684 while (!Worklist.empty()) {
1685 // Because the LoopInfo stores the loops in RPO, we walk the worklist
1686 // from back to front so that we work forward across the CFG, which
1687 // for unrolling is only needed to get optimization remarks emitted in
1688 // a forward order.
1689 Loop &L = *Worklist.pop_back_val();
1690#ifndef NDEBUG
1691 Loop *ParentL = L.getParentLoop();
1692#endif
1693
1694 // Check if the profile summary indicates that the profiled application
1695 // has a huge working set size, in which case we disable peeling to avoid
1696 // bloating it further.
1697 std::optional<bool> LocalAllowPeeling = UnrollOpts.AllowPeeling;
1698 if (PSI && PSI->hasHugeWorkingSetSize())
1699 LocalAllowPeeling = false;
1700 std::string LoopName = std::string(L.getName());
1701 // The API here is quite complex to call and we allow to select some
1702 // flavors of unrolling during construction time (by setting UnrollOpts).
1703 LoopUnrollResult Result =
1704 tryToUnrollLoop(&L, DT, &LI, SE, TTI, AC, ORE, BFI, PSI,
1705 /*PreserveLCSSA*/ true, UnrollOpts.OptLevel,
1706 /*OnlyFullUnroll*/ false, UnrollOpts.OnlyWhenForced,
1707 UnrollOpts.ForgetSCEV, UnrollOpts.PrepareForLTO,
1708 /*Threshold*/ std::nullopt, UnrollOpts.AllowPartial,
1709 UnrollOpts.AllowRuntime, UnrollOpts.AllowUpperBound,
1710 LocalAllowPeeling, UnrollOpts.AllowProfileBasedPeeling,
1711 UnrollOpts.FullUnrollMaxCount, UI, &AA);
1713
1714 // The parent must not be damaged by unrolling!
1715#ifndef NDEBUG
1716 if (Result != LoopUnrollResult::Unmodified && ParentL)
1717 ParentL->verifyLoop();
1718#endif
1719
1720 // Clear any cached analysis results for L if we removed it completely.
1721 if (LAM && Result == LoopUnrollResult::FullyUnrolled)
1722 LAM->clear(L, LoopName);
1723 }
1724
1725 if (!Changed)
1726 return PreservedAnalyses::all();
1727
1729}
1730
1732 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1733 static_cast<PassInfoMixin<LoopUnrollPass> *>(this)->printPipeline(
1734 OS, MapClassName2PassName);
1735 OS << '<';
1736 if (UnrollOpts.AllowPartial != std::nullopt)
1737 OS << (*UnrollOpts.AllowPartial ? "" : "no-") << "partial;";
1738 if (UnrollOpts.AllowPeeling != std::nullopt)
1739 OS << (*UnrollOpts.AllowPeeling ? "" : "no-") << "peeling;";
1740 if (UnrollOpts.AllowRuntime != std::nullopt)
1741 OS << (*UnrollOpts.AllowRuntime ? "" : "no-") << "runtime;";
1742 if (UnrollOpts.AllowUpperBound != std::nullopt)
1743 OS << (*UnrollOpts.AllowUpperBound ? "" : "no-") << "upperbound;";
1744 if (UnrollOpts.AllowProfileBasedPeeling != std::nullopt)
1745 OS << (*UnrollOpts.AllowProfileBasedPeeling ? "" : "no-")
1746 << "profile-peeling;";
1747 if (UnrollOpts.FullUnrollMaxCount != std::nullopt)
1748 OS << "full-unroll-max=" << UnrollOpts.FullUnrollMaxCount << ';';
1749 if (UnrollOpts.PrepareForLTO)
1750 OS << "prepare-for-lto;";
1751 OS << 'O' << UnrollOpts.OptLevel;
1752 OS << '>';
1753}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
#define DEBUG_TYPE
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
This header provides classes for managing per-loop analyses.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
static LoopUnrollResult tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE, const TargetTransformInfo &TTI, AssumptionCache &AC, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, bool PreserveLCSSA, int OptLevel, bool OnlyFullUnroll, bool OnlyWhenForced, bool ForgetAllSCEV, bool PrepareForLTO, std::optional< unsigned > ProvidedThreshold, std::optional< bool > ProvidedAllowPartial, std::optional< bool > ProvidedRuntime, std::optional< bool > ProvidedUpperBound, std::optional< bool > ProvidedAllowPeeling, std::optional< bool > ProvidedAllowProfileBasedPeeling, std::optional< unsigned > ProvidedFullUnrollMaxCount, UniformityInfo *UI=nullptr, AAResults *AA=nullptr)
static bool hasUnrollFullPragma(const Loop *L)
static bool isSCEVUniform(const SCEV *S, UniformityInfo &UI)
Returns true if the SCEV expression is uniform, i.e., all threads in a convergent execution agree on ...
static unsigned unrollCountPragmaValue(const Loop *L)
static bool hasUnrollEnablePragma(const Loop *L)
static std::optional< unsigned > shouldFullUnroll(Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, ScalarEvolution &SE, const SmallPtrSetImpl< const Value * > &EphValues, const unsigned FullUnrollTripCount, const UnrollCostEstimator UCE, const TargetTransformInfo::UnrollingPreferences &UP)
static std::optional< EstimatedUnrollCost > analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, const SmallPtrSetImpl< const Value * > &EphValues, const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize, unsigned MaxIterationsCountToAnalyze)
Figure out if the loop is worth full unrolling.
static std::optional< unsigned > shouldPragmaUnroll(const ScalarOptions &Opts, Loop *L, const UnrollPragmaInfo &PInfo, const unsigned TripMultiple, const unsigned TripCount, unsigned MaxTripCount, const UnrollCostEstimator UCE, const TargetTransformInfo::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE)
static std::optional< unsigned > shouldPartialUnroll(const unsigned LoopSize, const unsigned TripCount, const UnrollCostEstimator UCE, const TargetTransformInfo::UnrollingPreferences &UP)
static const unsigned NoThreshold
A magic value for use with the Threshold parameter to indicate that the loop unroll should be perform...
static unsigned shouldRuntimeUnroll(Loop *L, unsigned MaxTripCount, unsigned TripMultiple, const UnrollCostEstimator &UCE, const UnrollPragmaInfo &PInfo, const ScalarOptions &Opts, TargetTransformInfo::UnrollingPreferences &UP)
static bool hasRuntimeUnrollDisablePragma(const Loop *L)
static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost, unsigned MaxPercentThresholdBoost)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Trace Metrics
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
LoopAnalysisManager LAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
LLVM IR instance of the generic uniformity analysis.
Value * RHS
Value * LHS
A manager for alias analyses.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional Branch instruction.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:44
A debug info location.
Definition DebugLoc.h:126
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
bool isUniformAtDef(ConstValueRefT V) const
Whether V is uniform/non-divergent at its definition.
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
void addChildLoops(ArrayRef< Loop * > NewChildLoops)
Loop passes should use this method to indicate they have added new child loops of the current loop.
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
void addSiblingLoops(ArrayRef< Loop * > NewSibLoops)
Loop passes should use this method to indicate they have added new sibling loops to the current loop.
void markLoopAsDeleted(Loop &L)
Definition LoopPass.cpp:124
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
void verifyLoop() const
Verify loop structure.
iterator end() const
iterator begin() const
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
iterator end() const
iterator begin() const
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:582
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
bool empty() const
Determine if the PriorityWorklist is empty or not.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
This class represents an analyzed expression in the program.
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
void insert_range(Range &&R)
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
TargetCostKind
The kind of cost model.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
Produce an estimate of the unrolled cost of the specified loop.
Definition UnrollLoop.h:150
ConvergenceKind Convergence
Definition UnrollLoop.h:156
LLVM_ABI bool canUnroll(OptimizationRemarkEmitter *ORE=nullptr, const Loop *L=nullptr) const
Whether it is legal to unroll this loop.
LLVM_ABI uint64_t getUnrolledLoopSize(const TargetTransformInfo::UnrollingPreferences &UP, unsigned Count) const
Returns loop size estimation for an unrolled loop with the given unroll count and the unrolling confi...
LLVM_ABI UnrollCostEstimator(const Loop *L, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value * > &EphValues, unsigned BEInsns, bool PrepareForLTO=false, bool TripCountIsUniform=false)
uint64_t getRolledLoopSize() const
Definition UnrollLoop.h:174
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
iterator find(const_arg_type_t< ValueT > V)
Definition DenseSet.h:174
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Abstract Attribute helper functions.
Definition Attributor.h:164
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
GenericUniformityInfo< SSAContext > UniformityInfo
LLVM_ABI Pass * createLoopUnrollPass(int OptLevel=2, bool OnlyWhenForced=false, bool ForgetAllSCEV=false, int Threshold=-1, int AllowPartial=-1, int Runtime=-1, int UpperBound=-1, int AllowPeeling=-1)
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
LLVM_ABI unsigned computeUnrollCount(Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI, AssumptionCache *AC, ScalarEvolution &SE, const SmallPtrSetImpl< const Value * > &EphValues, OptimizationRemarkEmitter *ORE, unsigned TripCount, unsigned MaxTripCount, bool MaxOrZero, unsigned TripMultiple, const UnrollCostEstimator &UCE, TargetTransformInfo::UnrollingPreferences &UP, TargetTransformInfo::PeelingPreferences &PP)
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Runtime
Detect stack use after return if not disabled runtime with (ASAN_OPTIONS=detect_stack_use_after_retur...
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI bool getForgetSCEVInLoopUnroll(const cl::LibraryOptionsContext *LibraryOptions)
Returns -forget-scev-loop-unroll of LibraryOptions, or its global value if null.
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
LLVM_ABI std::optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
LLVM_ABI TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, llvm::OptimizationRemarkEmitter &ORE, int OptLevel, std::optional< unsigned > UserThreshold, std::optional< bool > UserAllowPartial, std::optional< bool > UserRuntime, std::optional< bool > UserUpperBound, std::optional< unsigned > UserFullUnrollMaxCount)
Gather the various unrolling parameters based on the defaults, compiler flags, TTI overrides and user...
LLVM_ABI char & LCSSAID
Definition LCSSA.cpp:545
LLVM_ABI void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, ArrayRef< BasicBlock * > Blocks, AAResults *AA=nullptr)
Perform some cleanup and simplifications on loops after unrolling.
const ScalarOptions & getScalarOptions(const LLVMContext &C)
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
LLVM_ABI void initializeLoopUnrollPass(PassRegistry &)
LLVM_ABI TargetTransformInfo::PeelingPreferences gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, std::optional< bool > UserAllowPeeling, std::optional< bool > UserAllowProfileBasedPeeling, bool UnrollingSpecficValues=false)
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI TransformationMode hasUnrollAndJamTransformation(const Loop *L)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void computePeelCount(Loop *L, unsigned LoopSize, TargetTransformInfo::PeelingPreferences &PP, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, const TargetTransformInfo &TTI, AssumptionCache *AC=nullptr, unsigned Threshold=UINT_MAX)
Definition LoopPeel.cpp:749
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
LLVM_ABI TransformationMode hasUnrollTransformation(const Loop *L)
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
Definition UnrollLoop.h:58
@ PartiallyUnrolled
The loop was partially unrolled – we still have a loop, but with a smaller trip count.
Definition UnrollLoop.h:65
@ Unmodified
The loop was not modified.
Definition UnrollLoop.h:60
@ FullyUnrolled
The loop was fully unrolled into straight-line code.
Definition UnrollLoop.h:69
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_ABI void peelLoop(Loop *L, unsigned PeelCount, bool PeelLast, LoopInfo *LI, ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, bool PreserveLCSSA, ValueToValueMapTy &VMap)
VMap is the value-map that maps instructions from the original loop to instructions in the last peele...
const char *const LLVMLoopUnrollFollowupAll
Definition UnrollLoop.h:45
TargetTransformInfo TTI
TransformationMode
The mode sets how eager a transformation should be applied.
Definition LoopUtils.h:292
@ TM_ForcedByUser
The transformation was directed by the user, e.g.
Definition LoopUtils.h:309
@ TM_Disable
The transformation should not be applied.
Definition LoopUtils.h:301
@ TM_Enable
The transformation should be applied without considering a cost model.
Definition LoopUtils.h:298
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI MDNode * getUnrollMetadataForLoop(const Loop *L, StringRef Name)
DWARFExpression::Operation Op
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
const char *const LLVMLoopUnrollFollowupRemainder
Definition UnrollLoop.h:48
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
const char *const LLVMLoopUnrollFollowupUnrolled
Definition UnrollLoop.h:46
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool valueOr(BoolOrDefault X, bool Default)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI LoopUnrollResult UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const llvm::TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop=nullptr, AAResults *AA=nullptr)
Unroll the given loop by Count.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition CodeMetrics.h:34
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
bool PeelLast
Peel off the last PeelCount loop iterations.
bool PeelProfiledIterations
Allow peeling basing on profile.
unsigned PeelCount
A forced peeling factor (the number of bodied of the original loop that should be peeled off before t...
Parameters that control the generic loop unrolling transformation.
bool UpperBound
Allow using trip count upper bound to unroll loops.
unsigned Threshold
The cost threshold for the unrolled loop.
bool Force
Apply loop unroll on any kind of loop (mainly to loops that fail runtime unrolling).
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
unsigned DefaultUnrollRuntimeCount
Default unroll count for loops with run-time trip count.
unsigned MaxPercentThresholdBoost
If complete unrolling will reduce the cost of the loop, we will boost the Threshold by a certain perc...
bool RuntimeUnrollMultiExit
Allow runtime unrolling multi-exit loops.
unsigned SCEVExpansionBudget
Don't allow runtime unrolling if expanding the trip count takes more than SCEVExpansionBudget.
bool AddAdditionalAccumulators
Allow unrolling to add parallel reduction phis.
unsigned UnrollAndJamInnerLoopThreshold
Threshold for unroll and jam, for inner loop size.
unsigned MaxIterationsCountToAnalyze
Don't allow loop unrolling to simulate more than this number of iterations when checking full unroll ...
bool AllowRemainder
Allow generation of a loop remainder (extra iterations after unroll).
bool UnrollAndJam
Allow unroll and jam. Used to enable unroll and jam for the target.
bool UnrollRemainder
Allow unrolling of all the iterations of the runtime loop remainder.
unsigned FullUnrollMaxCount
Set the maximum unrolling factor for full unrolling.
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
unsigned OptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size (set to UINT_MAX to disable).
bool AllowExpensiveTripCount
Allow emitting expensive instructions (such as divisions) when computing the trip count of a loop for...
unsigned MaxUpperBound
Set the maximum upper bound of trip count.
const Instruction * Heart
Definition UnrollLoop.h:79
const bool PragmaFullUnroll
Definition UnrollLoop.h:131
LLVM_ABI UnrollPragmaInfo(const Loop *L)
const unsigned PragmaCount
Definition UnrollLoop.h:132
const bool ExplicitUnroll
Definition UnrollLoop.h:135
const bool PragmaRuntimeUnrollDisable
Definition UnrollLoop.h:134
const bool UserUnrollCount
Definition UnrollLoop.h:130
const bool PragmaEnableUnroll
Definition UnrollLoop.h:133