LLVM 23.0.0git
LoopUnroll.cpp
Go to the documentation of this file.
1//===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
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 file implements some loop unrolling utilities. It does not define any
10// actual pass or policy, but provides a single function to perform loop
11// unrolling.
12//
13// The process of unrolling can produce extraneous basic blocks linked with
14// unconditional branches. This will be corrected in the future.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/Twine.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constants.h"
41#include "llvm/IR/DebugLoc.h"
43#include "llvm/IR/Dominators.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/IRBuilder.h"
46#include "llvm/IR/Instruction.h"
49#include "llvm/IR/Metadata.h"
51#include "llvm/IR/Use.h"
52#include "llvm/IR/User.h"
53#include "llvm/IR/ValueHandle.h"
54#include "llvm/IR/ValueMap.h"
57#include "llvm/Support/Debug.h"
68#include <assert.h>
69#include <cmath>
70#include <numeric>
71#include <vector>
72
73namespace llvm {
74class DataLayout;
75class Value;
76} // namespace llvm
77
78using namespace llvm;
79
80#define DEBUG_TYPE "loop-unroll"
81
82// TODO: Should these be here or in LoopUnroll?
83STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
84STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
85STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
86 "latch (completely or otherwise)");
87
88static cl::opt<bool>
89UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
90 cl::desc("Allow runtime unrolled loops to be unrolled "
91 "with epilog instead of prolog."));
92
93static cl::opt<bool>
94UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
95 cl::desc("Verify domtree after unrolling"),
96#ifdef EXPENSIVE_CHECKS
97 cl::init(true)
98#else
99 cl::init(false)
100#endif
101 );
102
103static cl::opt<bool>
104UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
105 cl::desc("Verify loopinfo after unrolling"),
106#ifdef EXPENSIVE_CHECKS
107 cl::init(true)
108#else
109 cl::init(false)
110#endif
111 );
112
114 "unroll-add-parallel-reductions", cl::init(false), cl::Hidden,
115 cl::desc("Allow unrolling to add parallel reduction phis."));
116
117/// Check if unrolling created a situation where we need to insert phi nodes to
118/// preserve LCSSA form.
119/// \param Blocks is a vector of basic blocks representing unrolled loop.
120/// \param L is the outer loop.
121/// It's possible that some of the blocks are in L, and some are not. In this
122/// case, if there is a use is outside L, and definition is inside L, we need to
123/// insert a phi-node, otherwise LCSSA will be broken.
124/// The function is just a helper function for llvm::UnrollLoop that returns
125/// true if this situation occurs, indicating that LCSSA needs to be fixed.
127 const std::vector<BasicBlock *> &Blocks,
128 LoopInfo *LI) {
129 for (BasicBlock *BB : Blocks) {
130 if (LI->getLoopFor(BB) == L)
131 continue;
132 for (Instruction &I : *BB) {
133 for (Use &U : I.operands()) {
134 if (const auto *Def = dyn_cast<Instruction>(U)) {
135 Loop *DefLoop = LI->getLoopFor(Def->getParent());
136 if (!DefLoop)
137 continue;
138 if (DefLoop->contains(L))
139 return true;
140 }
141 }
142 }
143 }
144 return false;
145}
146
147/// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
148/// and adds a mapping from the original loop to the new loop to NewLoops.
149/// Returns nullptr if no new loop was created and a pointer to the
150/// original loop OriginalBB was part of otherwise.
152 BasicBlock *ClonedBB, LoopInfo *LI,
153 NewLoopsMap &NewLoops) {
154 // Figure out which loop New is in.
155 const Loop *OldLoop = LI->getLoopFor(OriginalBB);
156 assert(OldLoop && "Should (at least) be in the loop being unrolled!");
157
158 Loop *&NewLoop = NewLoops[OldLoop];
159 if (!NewLoop) {
160 // Found a new sub-loop.
161 assert(OriginalBB == OldLoop->getHeader() &&
162 "Header should be first in RPO");
163
164 NewLoop = LI->AllocateLoop();
165 Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
166
167 if (NewLoopParent)
168 NewLoopParent->addChildLoop(NewLoop);
169 else
170 LI->addTopLevelLoop(NewLoop);
171
172 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
173 return OldLoop;
174 } else {
175 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
176 return nullptr;
177 }
178}
179
180/// The function chooses which type of unroll (epilog or prolog) is more
181/// profitabale.
182/// Epilog unroll is more profitable when there is PHI that starts from
183/// constant. In this case epilog will leave PHI start from constant,
184/// but prolog will convert it to non-constant.
185///
186/// loop:
187/// PN = PHI [I, Latch], [CI, PreHeader]
188/// I = foo(PN)
189/// ...
190///
191/// Epilog unroll case.
192/// loop:
193/// PN = PHI [I2, Latch], [CI, PreHeader]
194/// I1 = foo(PN)
195/// I2 = foo(I1)
196/// ...
197/// Prolog unroll case.
198/// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
199/// loop:
200/// PN = PHI [I2, Latch], [NewPN, PreHeader]
201/// I1 = foo(PN)
202/// I2 = foo(I1)
203/// ...
204///
205static bool isEpilogProfitable(Loop *L) {
206 BasicBlock *PreHeader = L->getLoopPreheader();
207 BasicBlock *Header = L->getHeader();
208 assert(PreHeader && Header);
209 for (const PHINode &PN : Header->phis()) {
210 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
211 return true;
212 }
213 return false;
214}
215
216struct LoadValue {
217 Instruction *DefI = nullptr;
218 unsigned Generation = 0;
219 LoadValue() = default;
221 : DefI(Inst), Generation(Generation) {}
222};
223
226 unsigned CurrentGeneration;
227 unsigned ChildGeneration;
228 DomTreeNode *Node;
229 DomTreeNode::const_iterator ChildIter;
230 DomTreeNode::const_iterator EndIter;
231 bool Processed = false;
232
233public:
235 unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child,
236 DomTreeNode::const_iterator End)
237 : LoadScope(AvailableLoads), CurrentGeneration(cg), ChildGeneration(cg),
238 Node(N), ChildIter(Child), EndIter(End) {}
239 // Accessors.
240 unsigned currentGeneration() const { return CurrentGeneration; }
241 unsigned childGeneration() const { return ChildGeneration; }
242 void childGeneration(unsigned generation) { ChildGeneration = generation; }
243 DomTreeNode *node() { return Node; }
244 DomTreeNode::const_iterator childIter() const { return ChildIter; }
245
247 DomTreeNode *Child = *ChildIter;
248 ++ChildIter;
249 return Child;
250 }
251
252 DomTreeNode::const_iterator end() const { return EndIter; }
253 bool isProcessed() const { return Processed; }
254 void process() { Processed = true; }
255};
256
257Value *getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration,
258 BatchAAResults &BAA,
259 function_ref<MemorySSA *()> GetMSSA) {
260 if (!LV.DefI)
261 return nullptr;
262 if (LV.DefI->getType() != LI->getType())
263 return nullptr;
264 if (LV.Generation != CurrentGeneration) {
265 MemorySSA *MSSA = GetMSSA();
266 if (!MSSA)
267 return nullptr;
268 auto *EarlierMA = MSSA->getMemoryAccess(LV.DefI);
269 MemoryAccess *LaterDef =
270 MSSA->getWalker()->getClobberingMemoryAccess(LI, BAA);
271 if (!MSSA->dominates(LaterDef, EarlierMA))
272 return nullptr;
273 }
274 return LV.DefI;
275}
276
278 BatchAAResults &BAA, function_ref<MemorySSA *()> GetMSSA) {
281 DomTreeNode *HeaderD = DT.getNode(L->getHeader());
282 NodesToProcess.emplace_back(new StackNode(AvailableLoads, 0, HeaderD,
283 HeaderD->begin(), HeaderD->end()));
284
285 unsigned CurrentGeneration = 0;
286 while (!NodesToProcess.empty()) {
287 StackNode *NodeToProcess = &*NodesToProcess.back();
288
289 CurrentGeneration = NodeToProcess->currentGeneration();
290
291 if (!NodeToProcess->isProcessed()) {
292 // Process the node.
293
294 // If this block has a single predecessor, then the predecessor is the
295 // parent
296 // of the domtree node and all of the live out memory values are still
297 // current in this block. If this block has multiple predecessors, then
298 // they could have invalidated the live-out memory values of our parent
299 // value. For now, just be conservative and invalidate memory if this
300 // block has multiple predecessors.
301 if (!NodeToProcess->node()->getBlock()->getSinglePredecessor())
302 ++CurrentGeneration;
303 for (auto &I : make_early_inc_range(*NodeToProcess->node()->getBlock())) {
304
305 auto *Load = dyn_cast<LoadInst>(&I);
306 if (!Load || !Load->isSimple()) {
307 if (I.mayWriteToMemory())
308 CurrentGeneration++;
309 continue;
310 }
311
312 const SCEV *PtrSCEV = SE.getSCEV(Load->getPointerOperand());
313 LoadValue LV = AvailableLoads.lookup(PtrSCEV);
314 if (Value *M =
315 getMatchingValue(LV, Load, CurrentGeneration, BAA, GetMSSA)) {
316 if (LI.replacementPreservesLCSSAForm(Load, M)) {
317 Load->replaceAllUsesWith(M);
318 Load->eraseFromParent();
319 }
320 } else {
321 AvailableLoads.insert(PtrSCEV, LoadValue(Load, CurrentGeneration));
322 }
323 }
324 NodeToProcess->childGeneration(CurrentGeneration);
325 NodeToProcess->process();
326 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
327 // Push the next child onto the stack.
328 DomTreeNode *Child = NodeToProcess->nextChild();
329 if (!L->contains(Child->getBlock()))
330 continue;
331 NodesToProcess.emplace_back(
332 new StackNode(AvailableLoads, NodeToProcess->childGeneration(), Child,
333 Child->begin(), Child->end()));
334 } else {
335 // It has been processed, and there are no more children to process,
336 // so delete it and pop it off the stack.
337 NodesToProcess.pop_back();
338 }
339 }
340}
341
342/// Perform some cleanup and simplifications on loops after unrolling. It is
343/// useful to simplify the IV's in the new loop, as well as do a quick
344/// simplify/dce pass of the instructions.
345void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
347 AssumptionCache *AC,
350 AAResults *AA) {
351 using namespace llvm::PatternMatch;
352
353 // Simplify any new induction variables in the partially unrolled loop.
354 if (SE && SimplifyIVs) {
356 simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
357
358 // Aggressively clean up dead instructions that simplifyLoopIVs already
359 // identified. Any remaining should be cleaned up below.
360 while (!DeadInsts.empty()) {
361 Value *V = DeadInsts.pop_back_val();
364 }
365
366 if (AA) {
367 std::unique_ptr<MemorySSA> MSSA = nullptr;
368 BatchAAResults BAA(*AA);
369 loadCSE(L, *DT, *SE, *LI, BAA, [L, AA, DT, &MSSA]() -> MemorySSA * {
370 if (!MSSA)
371 MSSA.reset(new MemorySSA(*L, AA, DT));
372 return &*MSSA;
373 });
374 }
375 }
376
377 // At this point, the code is well formed. Perform constprop, instsimplify,
378 // and dce.
380 for (BasicBlock *BB : Blocks) {
381 // Remove repeated debug instructions after loop unrolling.
382 if (BB->getParent()->getSubprogram())
384
385 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
386 if (Value *V = simplifyInstruction(
387 &Inst, {BB->getDataLayout(), nullptr, DT, AC}))
388 if (LI->replacementPreservesLCSSAForm(&Inst, V))
389 Inst.replaceAllUsesWith(V);
391 DeadInsts.emplace_back(&Inst);
392
393 // Fold ((add X, C1), C2) to (add X, C1+C2). This is very common in
394 // unrolled loops, and handling this early allows following code to
395 // identify the IV as a "simple recurrence" without first folding away
396 // a long chain of adds.
397 {
398 Value *X;
399 const APInt *C1, *C2;
400 if (match(&Inst, m_Add(m_Add(m_Value(X), m_APInt(C1)), m_APInt(C2)))) {
401 auto *InnerI = dyn_cast<Instruction>(Inst.getOperand(0));
402 auto *InnerOBO = cast<OverflowingBinaryOperator>(Inst.getOperand(0));
403 bool SignedOverflow;
404 APInt NewC = C1->sadd_ov(*C2, SignedOverflow);
405 Inst.setOperand(0, X);
406 Inst.setOperand(1, ConstantInt::get(Inst.getType(), NewC));
407 Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() &&
408 InnerOBO->hasNoUnsignedWrap());
409 Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() &&
410 InnerOBO->hasNoSignedWrap() &&
411 !SignedOverflow);
412 if (InnerI && isInstructionTriviallyDead(InnerI))
413 DeadInsts.emplace_back(InnerI);
414 }
415 }
416 }
417 // We can't do recursive deletion until we're done iterating, as we might
418 // have a phi which (potentially indirectly) uses instructions later in
419 // the block we're iterating through.
421 }
422}
423
424// Loops containing convergent instructions that are uncontrolled or controlled
425// from outside the loop must have a count that divides their TripMultiple.
427static bool canHaveUnrollRemainder(const Loop *L) {
429 return false;
430
431 // Check for uncontrolled convergent operations.
432 for (auto &BB : L->blocks()) {
433 for (auto &I : *BB) {
435 return true;
436 if (auto *CB = dyn_cast<CallBase>(&I))
437 if (CB->isConvergent())
438 return CB->getConvergenceControlToken();
439 }
440 }
441 return true;
442}
443
444// If LoopUnroll has proven OriginalLoopProb is incorrect for some iterations
445// of the original loop, adjust latch probabilities in the unrolled loop to
446// maintain the original total frequency of the original loop body.
447//
448// OriginalLoopProb is practical but imprecise
449// -------------------------------------------
450//
451// The latch branch weights that LLVM originally adds to a loop encode one latch
452// probability, OriginalLoopProb, applied uniformly across the loop's infinite
453// set of theoretically possible iterations. While this uniform latch
454// probability serves as a practical statistic summarizing the trip counts
455// observed during profiling, it is imprecise. Specifically, unless it is zero,
456// it is impossible for it to be the actual probability observed at every
457// individual iteration. To see why, consider that the only way to actually
458// observe at run time that the latch probability remains non-zero is to profile
459// at least one loop execution that has an infinite number of iterations. I do
460// not know how to profile an infinite number of loop iterations, and most loops
461// I work with are always finite.
462//
463// LoopUnroll proves OriginalLoopProb is incorrect
464// ------------------------------------------------
465//
466// LoopUnroll reorganizes the original loop so that loop iterations are no
467// longer all implemented by the same code, and then it analyzes some of those
468// loop iteration implementations independently of others. In particular, it
469// converts some of their conditional latches to unconditional. That is, by
470// examining code structure without any profile data, LoopUnroll proves that the
471// actual latch probability at the end of such an iteration is either 1 or 0.
472// When an individual iteration's actual latch probability is 1 or 0, that means
473// it always behaves the same, so it is impossible to observe it as having any
474// other probability. The original uniform latch probability is rarely 1 or 0
475// because, when applied to all possible iterations, that would yield an
476// estimated trip count of infinity or 1, respectively.
477//
478// Thus, the new probabilities of 1 or 0 are proven corrections to
479// OriginalLoopProb for individual iterations in the original loop. However,
480// LoopUnroll often is able to perform these corrections for only some
481// iterations, leaving other iterations with OriginalLoopProb, and thus
482// corrupting the aggregate effect on the total frequency of the original loop
483// body.
484//
485// Adjusting latch probabilities
486// -----------------------------
487//
488// This function ensures that the total frequency of the original loop body,
489// summed across all its occurrences in the unrolled loop after the
490// aforementioned latch conversions, is the same as in the original loop. To do
491// so, it adjusts probabilities on the remaining conditional latches. However,
492// it cannot derive the new probabilities directly from the original uniform
493// latch probability because the latter has been proven incorrect for some
494// original loop iterations.
495//
496// There are often many sets of latch probabilities that can produce the
497// original total loop body frequency. For now, this function computes uniform
498// probabilities when the number of remaining conditional latches is <= 2 and
499// does not handle other cases.
501 BranchProbability OriginalLoopProb,
502 bool CompletelyUnroll,
503 std::vector<unsigned> &IterCounts,
504 const std::vector<BasicBlock *> &CondLatches,
505 std::vector<BasicBlock *> &CondLatchNexts) {
506 // Runtime unrolling is handled later in LoopUnroll not here.
507 //
508 // There are two scenarios in which LoopUnroll sets ProbUpdateRequired to true
509 // because it needs to update probabilities that were originally
510 // OriginalLoopProb, but only in one scenario has LoopUnroll proven
511 // OriginalLoopProb incorrect for iterations within the original loop:
512 // - If ULO.Runtime, LoopUnroll adds new guards that enforce new reaching
513 // conditions for new loop iteration implementations (e.g., one unrolled
514 // loop iteration executes only if at least ULO.Count original loop
515 // iterations remain). Those reaching conditions dictate how conditional
516 // latches can be converted to unconditional (e.g., within an unrolled loop
517 // iteration, there is no need to recheck the number of remaining original
518 // loop iterations). None of this reorganization alters the set of possible
519 // original loop iteration counts or proves OriginalLoopProb incorrect for
520 // any of the original loop iterations. Thus, LoopUnroll derives
521 // probabilities for the new guards and latches directly from
522 // OriginalLoopProb based on the probabilities that their reaching
523 // conditions would occur in the original loop. Doing so maintains the
524 // total frequency of the original loop body.
525 // - If !ULO.Runtime, LoopUnroll initially adds new loop iteration
526 // implementations, which have the same latch probabilities as in the
527 // original loop because there are no new guards that change their reaching
528 // conditions. Sometimes, LoopUnroll is then done, and so does not set
529 // ProbUpdateRequired to true. Other times, LoopUnroll then proves that
530 // some latches are unconditional, directly contradicting OriginalLoopProb
531 // for the corresponding original loop iterations. That reduces the set of
532 // possible original loop iteration counts, possibly producing a finite set
533 // if it manages to eliminate the backedge. LoopUnroll has to choose a new
534 // set of latch probabilities that produce the same total loop body
535 // frequency.
536 //
537 // This function addresses the second scenario only.
538 if (ULO.Runtime)
539 return;
540
541 // If CondLatches.empty(), there are no latch branches with probabilities we
542 // can adjust. That should mean that the actual trip count is always exactly
543 // the number of remaining unrolled iterations, and so OriginalLoopProb should
544 // have yielded that trip count as the original loop body frequency. Of
545 // course, OriginalLoopProb could be based on inaccurate profile data, but
546 // there is nothing we can do about that here.
547 if (CondLatches.empty())
548 return;
549
550 // If the original latch probability is 1, the original frequency is infinity.
551 // Leaving all remaining probabilities set to 1 might or might not get us
552 // there (e.g., a completely unrolled loop cannot be infinite), but it is the
553 // closest we can come.
554 assert(!OriginalLoopProb.isUnknown() &&
555 "Expected to have loop probability to fix");
556 if (OriginalLoopProb.isOne())
557 return;
558
559 // FreqDesired is the frequency implied by the original loop probability.
560 double FreqDesired = 1 / (1 - OriginalLoopProb.toDouble());
561
562 // Set the probability at CondLatches[I] to Prob.
563 auto SetProb = [&](unsigned I, double Prob) {
564 CondBrInst *B = cast<CondBrInst>(CondLatches[I]->getTerminator());
565 bool FirstTargetIsNext = B->getSuccessor(0) == CondLatchNexts[I];
567 FirstTargetIsNext);
568 };
569
570 // Set all probabilities in CondLatches to Prob.
571 auto SetAllProbs = [&](double Prob) {
572 for (unsigned I = 0, E = CondLatches.size(); I < E; ++I)
573 SetProb(I, Prob);
574 };
575
576 // If n <= 2, we choose the simplest probability model we can think of: every
577 // remaining conditional branch instruction has the same probability, Prob,
578 // of continuing to the next iteration. This model has several helpful
579 // properties:
580 // - We have no reason to think one latch branch's probability should be
581 // higher or lower than another, and so this model makes them all the same.
582 // In the worst cases, we thus avoid setting just some probabilities to 0 or
583 // 1, which can unrealistically make some code appear unreachable. There
584 // are cases where they *all* must become 0 or 1 to achieve the total
585 // frequency of original loop body, and our model does permit that.
586 // - The frequency, FreqOne, of the original loop body in a single iteration
587 // of the unrolled loop is computed by a simple polynomial, where p=Prob,
588 // n=CondLatches.size(), and c_i=IterCounts[i]:
589 //
590 // FreqOne = Sum(i=0..n)(c_i * p^i)
591 //
592 // - If the backedge has been eliminated, FreqOne is the total frequency of
593 // the original loop body in the unrolled loop.
594 // - If the backedge remains, Sum(i=0..inf)(FreqOne * p^(n*i)) =
595 // FreqOne / (1 - p^n) is the total frequency of the original loop body in
596 // the unrolled loop, regardless of whether the backedge is conditional or
597 // unconditional.
598 // - For n <= 2, we can use simple formulas to solve the above polynomial
599 // equations exactly for p without performing a search.
600
601 // Compute the probability that, used at CondLaches[0] where
602 // CondLatches.size() == 1, gets as close as possible to FreqDesired.
603 auto ComputeProbForLinear = [&]() {
604 // The polynomial is linear (0 = A*p + B), so just solve it.
605 double A = IterCounts[1] + (CompletelyUnroll ? 0 : FreqDesired);
606 double B = IterCounts[0] - FreqDesired;
607 assert(A > 0 && "Expected iterations after last conditional latch");
608 double Prob = -B / A;
609 Prob = std::max(Prob, 0.);
610 Prob = std::min(Prob, 1.);
611 return Prob;
612 };
613
614 // Compute the probability that, used throughout CondLatches where
615 // CondLatches.size() == 2, gets as close as possible to FreqDesired.
616 auto ComputeProbForQuadratic = [&]() {
617 // The polynomial is quadratic (0 = A*p^2 + B*p + C), so just solve it.
618 double A = IterCounts[2] + (CompletelyUnroll ? 0 : FreqDesired);
619 double B = IterCounts[1];
620 double C = IterCounts[0] - FreqDesired;
621 assert(A > 0 && "Expected iterations after last conditional latch");
622 double Prob = (-B + sqrt(B * B - 4 * A * C)) / (2 * A);
623 Prob = std::max(Prob, 0.);
624 Prob = std::min(Prob, 1.);
625 return Prob;
626 };
627
628 // Determine and set branch weights.
629 if (CondLatches.size() == 1) {
630 SetAllProbs(ComputeProbForLinear());
631 } else if (CondLatches.size() == 2) {
632 SetAllProbs(ComputeProbForQuadratic());
633 } else {
634 // FIXME: Handle CondLatches.size() > 2.
635 }
636
637 // FIXME: We have not considered non-latch loop exits:
638 // - Their original probabilities are not considered in our calculation of
639 // FreqDesired.
640 // - Their probabilities are not considered in our probability model used to
641 // determine new probabilities for remaining conditional branches.
642 // - If they are conditional and LoopUnroll converts them to unconditional,
643 // LoopUnroll has proven their original probabilities are incorrect for some
644 // original loop iterations, but that does not cause ProbUpdateRequired to
645 // be set to true.
646 //
647 // To adjust FreqDesired and our probability model correctly for a non-latch
648 // loop exit, we would need to compute the original probability that the exit
649 // is reached from the loop header (in contrast, we currently assume that
650 // probability is 1 in the case of a latch exit) and the probability that the
651 // exit is taken if it is conditional (use the branch's old or new weights for
652 // FreqDesired or the probability model, respectively). Does computing the
653 // reaching probability require a CFG traversal, or is there some existing
654 // library that can do it? Prior discussions suggest some such libraries are
655 // difficult to use within LoopUnroll:
656 // <https://github.com/llvm/llvm-project/pull/164799#issuecomment-3438681519>.
657 // For now, we just let our corrected probabilities be less accurate in that
658 // scenario. Alternatively, we could refuse to correct probabilities at all
659 // in that scenario, but that seems worse.
660}
661
662/// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
663/// can only fail when the loop's latch block is not terminated by a conditional
664/// branch instruction. However, if the trip count (and multiple) are not known,
665/// loop unrolling will mostly produce more code that is no faster.
666///
667/// If Runtime is true then UnrollLoop will try to insert a prologue or
668/// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
669/// will not runtime-unroll the loop if computing the run-time trip count will
670/// be expensive and AllowExpensiveTripCount is false.
671///
672/// The LoopInfo Analysis that is passed will be kept consistent.
673///
674/// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
675/// DominatorTree if they are non-null.
676///
677/// If RemainderLoop is non-null, it will receive the remainder loop (if
678/// required and not fully unrolled).
683 bool PreserveLCSSA, Loop **RemainderLoop, AAResults *AA) {
684 assert(DT && "DomTree is required");
685
686 if (!L->getLoopPreheader()) {
687 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
689 }
690
691 if (!L->getLoopLatch()) {
692 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
694 }
695
696 // Loops with indirectbr cannot be cloned.
697 if (!L->isSafeToClone()) {
698 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
700 }
701
702 if (L->getHeader()->hasAddressTaken()) {
703 // The loop-rotate pass can be helpful to avoid this in many cases.
705 dbgs() << " Won't unroll loop: address of header block is taken.\n");
707 }
708
709 assert(ULO.Count > 0);
710
711 // All these values should be taken only after peeling because they might have
712 // changed.
713 BasicBlock *Preheader = L->getLoopPreheader();
714 BasicBlock *Header = L->getHeader();
715 BasicBlock *LatchBlock = L->getLoopLatch();
717 L->getExitBlocks(ExitBlocks);
718 std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
719
720 const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
721 const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
722 std::optional<unsigned> OriginalTripCount =
724 BranchProbability OriginalLoopProb = llvm::getLoopProbability(L);
725
726 // Effectively "DCE" unrolled iterations that are beyond the max tripcount
727 // and will never be executed.
728 if (MaxTripCount && ULO.Count > MaxTripCount)
729 ULO.Count = MaxTripCount;
730
731 struct ExitInfo {
732 unsigned TripCount;
733 unsigned TripMultiple;
734 unsigned BreakoutTrip;
735 bool ExitOnTrue;
736 BasicBlock *FirstExitingBlock = nullptr;
737 SmallVector<BasicBlock *> ExitingBlocks;
738 };
740 SmallVector<BasicBlock *, 4> ExitingBlocks;
741 L->getExitingBlocks(ExitingBlocks);
742 for (auto *ExitingBlock : ExitingBlocks) {
743 // The folding code is not prepared to deal with non-branch instructions
744 // right now.
745 auto *BI = dyn_cast<CondBrInst>(ExitingBlock->getTerminator());
746 if (!BI)
747 continue;
748
749 ExitInfo &Info = ExitInfos[ExitingBlock];
750 Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
751 Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
752 if (Info.TripCount != 0) {
753 Info.BreakoutTrip = Info.TripCount % ULO.Count;
754 Info.TripMultiple = 0;
755 } else {
756 Info.BreakoutTrip = Info.TripMultiple =
757 (unsigned)std::gcd(ULO.Count, Info.TripMultiple);
758 }
759 Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
760 Info.ExitingBlocks.push_back(ExitingBlock);
761 LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName()
762 << ": TripCount=" << Info.TripCount
763 << ", TripMultiple=" << Info.TripMultiple
764 << ", BreakoutTrip=" << Info.BreakoutTrip << "\n");
765 }
766
767 // Are we eliminating the loop control altogether? Note that we can know
768 // we're eliminating the backedge without knowing exactly which iteration
769 // of the unrolled body exits.
770 const bool CompletelyUnroll = ULO.Count == MaxTripCount;
771
772 const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
773
774 // There's no point in performing runtime unrolling if this unroll count
775 // results in a full unroll.
776 if (CompletelyUnroll)
777 ULO.Runtime = false;
778
779 // Go through all exits of L and see if there are any phi-nodes there. We just
780 // conservatively assume that they're inserted to preserve LCSSA form, which
781 // means that complete unrolling might break this form. We need to either fix
782 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
783 // now we just recompute LCSSA for the outer loop, but it should be possible
784 // to fix it in-place.
785 bool NeedToFixLCSSA =
786 PreserveLCSSA && CompletelyUnroll &&
787 any_of(ExitBlocks,
788 [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
789
790 // The current loop unroll pass can unroll loops that have
791 // (1) single latch; and
792 // (2a) latch is unconditional; or
793 // (2b) latch is conditional and is an exiting block
794 // FIXME: The implementation can be extended to work with more complicated
795 // cases, e.g. loops with multiple latches.
796 Instruction *LatchTerm = LatchBlock->getTerminator();
797
798 // A conditional branch which exits the loop, which can be optimized to an
799 // unconditional branch in the unrolled loop in some cases.
800 bool LatchIsExiting = L->isLoopExiting(LatchBlock);
801 if (!isa<UncondBrInst>(LatchTerm) &&
802 !(isa<CondBrInst>(LatchTerm) && LatchIsExiting)) {
804 dbgs() << "Can't unroll; a conditional latch must exit the loop");
806 }
807
809 "Can't runtime unroll if loop contains a convergent operation.");
810
811 bool EpilogProfitability =
812 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
814
815 if (ULO.Runtime &&
817 L, ULO.Count, ULO.AllowExpensiveTripCount, EpilogProfitability,
818 ULO.UnrollRemainder, ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
819 PreserveLCSSA, ULO.SCEVExpansionBudget, ULO.RuntimeUnrollMultiExit,
820 RemainderLoop, OriginalTripCount, OriginalLoopProb)) {
821 if (ULO.Force)
822 ULO.Runtime = false;
823 else {
824 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
825 "generated when assuming runtime trip count\n");
827 }
828 }
829
830 using namespace ore;
831 // Report the unrolling decision.
832 if (CompletelyUnroll) {
833 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
834 << " with trip count " << ULO.Count << "!\n");
835 if (ORE)
836 ORE->emit([&]() {
837 return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
838 L->getHeader())
839 << "completely unrolled loop with "
840 << NV("UnrollCount", ULO.Count) << " iterations";
841 });
842 } else {
843 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
844 << ULO.Count);
845 if (ULO.Runtime)
846 LLVM_DEBUG(dbgs() << " with run-time trip count");
847 LLVM_DEBUG(dbgs() << "!\n");
848
849 if (ORE)
850 ORE->emit([&]() {
851 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
852 L->getHeader());
853 Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
854 if (ULO.Runtime)
855 Diag << " with run-time trip count";
856 return Diag;
857 });
858 }
859
860 // We are going to make changes to this loop. SCEV may be keeping cached info
861 // about it, in particular about backedge taken count. The changes we make
862 // are guaranteed to invalidate this information for our loop. It is tempting
863 // to only invalidate the loop being unrolled, but it is incorrect as long as
864 // all exiting branches from all inner loops have impact on the outer loops,
865 // and if something changes inside them then any of outer loops may also
866 // change. When we forget outermost loop, we also forget all contained loops
867 // and this is what we need here.
868 if (SE) {
869 if (ULO.ForgetAllSCEV)
870 SE->forgetAllLoops();
871 else {
872 SE->forgetTopmostLoop(L);
874 }
875 }
876
877 if (!LatchIsExiting)
878 ++NumUnrolledNotLatch;
879
880 // For the first iteration of the loop, we should use the precloned values for
881 // PHI nodes. Insert associations now.
882 ValueToValueMapTy LastValueMap;
883 std::vector<PHINode*> OrigPHINode;
884 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
885 OrigPHINode.push_back(cast<PHINode>(I));
886 }
887
888 // Collect phi nodes for reductions for which we can introduce multiple
889 // parallel reduction phis and compute the final reduction result after the
890 // loop. This requires a single exit block after unrolling. This is ensured by
891 // restricting to single-block loops where the unrolled iterations are known
892 // to not exit.
894 bool CanAddAdditionalAccumulators =
895 (UnrollAddParallelReductions.getNumOccurrences() > 0
898 !CompletelyUnroll && L->getNumBlocks() == 1 &&
899 (ULO.Runtime ||
900 (ExitInfos.contains(Header) && ((ExitInfos[Header].TripCount != 0 &&
901 ExitInfos[Header].BreakoutTrip == 0))));
902
903 // Limit parallelizing reductions to unroll counts of 4 or less for now.
904 // TODO: The number of parallel reductions should depend on the number of
905 // execution units. We also don't have to add a parallel reduction phi per
906 // unrolled iteration, but could for example add a parallel phi for every 2
907 // unrolled iterations.
908 if (CanAddAdditionalAccumulators && ULO.Count <= 4) {
909 for (PHINode &Phi : Header->phis()) {
910 auto RdxDesc = canParallelizeReductionWhenUnrolling(Phi, L, SE);
911 if (!RdxDesc)
912 continue;
913
914 // Only handle duplicate phis for a single reduction for now.
915 // TODO: Handle any number of reductions
916 if (!Reductions.empty())
917 continue;
918
919 Reductions[&Phi] = *RdxDesc;
920 }
921 }
922
923 std::vector<BasicBlock *> Headers;
924 std::vector<BasicBlock *> Latches;
925 Headers.push_back(Header);
926 Latches.push_back(LatchBlock);
927
928 // The current on-the-fly SSA update requires blocks to be processed in
929 // reverse postorder so that LastValueMap contains the correct value at each
930 // exit.
931 LoopBlocksDFS DFS(L);
932 DFS.perform(LI);
933
934 // Stash the DFS iterators before adding blocks to the loop.
935 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
936 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
937
938 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
939
940 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
941 // might break loop-simplified form for these loops (as they, e.g., would
942 // share the same exit blocks). We'll keep track of loops for which we can
943 // break this so that later we can re-simplify them.
944 SmallSetVector<Loop *, 4> LoopsToSimplify;
945 LoopsToSimplify.insert_range(*L);
946
947 // When a FSDiscriminator is enabled, we don't need to add the multiply
948 // factors to the discriminators.
949 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
951 for (BasicBlock *BB : L->getBlocks())
952 for (Instruction &I : *BB)
953 if (!I.isDebugOrPseudoInst())
954 if (const DILocation *DIL = I.getDebugLoc()) {
955 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
956 if (NewDIL)
957 I.setDebugLoc(*NewDIL);
958 else
960 << "Failed to create new discriminator: "
961 << DIL->getFilename() << " Line: " << DIL->getLine());
962 }
963
964 // Identify what noalias metadata is inside the loop: if it is inside the
965 // loop, the associated metadata must be cloned for each iteration.
966 SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
967 identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
968
969 // We place the unrolled iterations immediately after the original loop
970 // latch. This is a reasonable default placement if we don't have block
971 // frequencies, and if we do, well the layout will be adjusted later.
972 auto BlockInsertPt = std::next(LatchBlock->getIterator());
973 SmallVector<Instruction *> PartialReductions;
974 for (unsigned It = 1; It != ULO.Count; ++It) {
977 NewLoops[L] = L;
978
979 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
981 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
982 Header->getParent()->insert(BlockInsertPt, New);
983
984 assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
985 "Header should not be in a sub-loop");
986 // Tell LI about New.
987 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
988 if (OldLoop)
989 LoopsToSimplify.insert(NewLoops[OldLoop]);
990
991 if (*BB == Header) {
992 // Loop over all of the PHI nodes in the block, changing them to use
993 // the incoming values from the previous block.
994 for (PHINode *OrigPHI : OrigPHINode) {
995 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
996 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
997
998 // Use cloned phis as parallel phis for partial reductions, which will
999 // get combined to the final reduction result after the loop.
1000 if (Reductions.contains(OrigPHI)) {
1001 // Collect partial reduction results.
1002 if (PartialReductions.empty())
1003 PartialReductions.push_back(cast<Instruction>(InVal));
1004 PartialReductions.push_back(cast<Instruction>(VMap[InVal]));
1005
1006 // Update the start value for the cloned phis to use the identity
1007 // value for the reduction.
1008 const RecurrenceDescriptor &RdxDesc = Reductions[OrigPHI];
1010 L->getLoopPreheader(),
1012 OrigPHI->getType(),
1013 RdxDesc.getFastMathFlags()));
1014
1015 // Update NewPHI to use the cloned value for the iteration and move
1016 // to header.
1017 NewPHI->replaceUsesOfWith(InVal, VMap[InVal]);
1018 NewPHI->moveBefore(OrigPHI->getIterator());
1019 continue;
1020 }
1021
1022 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
1023 if (It > 1 && L->contains(InValI))
1024 InVal = LastValueMap[InValI];
1025 VMap[OrigPHI] = InVal;
1026 NewPHI->eraseFromParent();
1027 }
1028
1029 // Eliminate copies of the loop heart intrinsic, if any.
1030 if (ULO.Heart) {
1031 auto it = VMap.find(ULO.Heart);
1032 assert(it != VMap.end());
1033 Instruction *heartCopy = cast<Instruction>(it->second);
1034 heartCopy->eraseFromParent();
1035 VMap.erase(it);
1036 }
1037 }
1038
1039 // Remap source location atom instance. Do this now, rather than
1040 // when we remap instructions, because remap is called once we've
1041 // cloned all blocks (all the clones would get the same atom
1042 // number).
1043 if (!VMap.AtomMap.empty())
1044 for (Instruction &I : *New)
1045 RemapSourceAtom(&I, VMap);
1046
1047 // Update our running map of newest clones
1048 LastValueMap[*BB] = New;
1049 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
1050 VI != VE; ++VI)
1051 LastValueMap[VI->first] = VI->second;
1052
1053 // Add phi entries for newly created values to all exit blocks.
1054 for (BasicBlock *Succ : successors(*BB)) {
1055 if (L->contains(Succ))
1056 continue;
1057 for (PHINode &PHI : Succ->phis()) {
1058 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
1059 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
1060 if (It != LastValueMap.end())
1061 Incoming = It->second;
1062 PHI.addIncoming(Incoming, New);
1064 }
1065 }
1066 // Keep track of new headers and latches as we create them, so that
1067 // we can insert the proper branches later.
1068 if (*BB == Header)
1069 Headers.push_back(New);
1070 if (*BB == LatchBlock)
1071 Latches.push_back(New);
1072
1073 // Keep track of the exiting block and its successor block contained in
1074 // the loop for the current iteration.
1075 auto ExitInfoIt = ExitInfos.find(*BB);
1076 if (ExitInfoIt != ExitInfos.end())
1077 ExitInfoIt->second.ExitingBlocks.push_back(New);
1078
1079 NewBlocks.push_back(New);
1080 UnrolledLoopBlocks.push_back(New);
1081
1082 // Update DomTree: since we just copy the loop body, and each copy has a
1083 // dedicated entry block (copy of the header block), this header's copy
1084 // dominates all copied blocks. That means, dominance relations in the
1085 // copied body are the same as in the original body.
1086 if (*BB == Header)
1087 DT->addNewBlock(New, Latches[It - 1]);
1088 else {
1089 auto BBDomNode = DT->getNode(*BB);
1090 auto BBIDom = BBDomNode->getIDom();
1091 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
1092 DT->addNewBlock(
1093 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
1094 }
1095 }
1096
1097 // Remap all instructions in the most recent iteration.
1098 // Key Instructions: Nothing to do - we've already remapped the atoms.
1099 remapInstructionsInBlocks(NewBlocks, LastValueMap);
1100 for (BasicBlock *NewBlock : NewBlocks)
1101 for (Instruction &I : *NewBlock)
1102 if (auto *II = dyn_cast<AssumeInst>(&I))
1104
1105 {
1106 // Identify what other metadata depends on the cloned version. After
1107 // cloning, replace the metadata with the corrected version for both
1108 // memory instructions and noalias intrinsics.
1109 std::string ext = (Twine("It") + Twine(It)).str();
1110 cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
1111 Header->getContext(), ext);
1112 }
1113 }
1114
1115 // Loop over the PHI nodes in the original block, setting incoming values.
1116 for (PHINode *PN : OrigPHINode) {
1117 if (CompletelyUnroll) {
1118 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
1119 PN->eraseFromParent();
1120 } else if (ULO.Count > 1) {
1121 if (Reductions.contains(PN))
1122 continue;
1123
1124 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
1125 // If this value was defined in the loop, take the value defined by the
1126 // last iteration of the loop.
1127 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
1128 if (L->contains(InValI))
1129 InVal = LastValueMap[InVal];
1130 }
1131 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
1132 PN->addIncoming(InVal, Latches.back());
1133 }
1134 }
1135
1136 // Connect latches of the unrolled iterations to the headers of the next
1137 // iteration. Currently they point to the header of the same iteration.
1138 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
1139 unsigned j = (i + 1) % e;
1140 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
1141 }
1142
1143 // Remove loop metadata copied from the original loop latch to branches that
1144 // are no longer latches.
1145 for (unsigned I = 0, E = Latches.size() - (CompletelyUnroll ? 0 : 1); I < E;
1146 ++I)
1147 Latches[I]->getTerminator()->setMetadata(LLVMContext::MD_loop, nullptr);
1148
1149 // Update dominators of blocks we might reach through exits.
1150 // Immediate dominator of such block might change, because we add more
1151 // routes which can lead to the exit: we can now reach it from the copied
1152 // iterations too.
1153 if (ULO.Count > 1) {
1154 for (auto *BB : OriginalLoopBlocks) {
1155 auto *BBDomNode = DT->getNode(BB);
1156 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
1157 for (auto *ChildDomNode : BBDomNode->children()) {
1158 auto *ChildBB = ChildDomNode->getBlock();
1159 if (!L->contains(ChildBB))
1160 ChildrenToUpdate.push_back(ChildBB);
1161 }
1162 // The new idom of the block will be the nearest common dominator
1163 // of all copies of the previous idom. This is equivalent to the
1164 // nearest common dominator of the previous idom and the first latch,
1165 // which dominates all copies of the previous idom.
1166 BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
1167 for (auto *ChildBB : ChildrenToUpdate)
1168 DT->changeImmediateDominator(ChildBB, NewIDom);
1169 }
1170 }
1171
1173 DT->verify(DominatorTree::VerificationLevel::Fast));
1174
1176 auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
1177 auto *Term = cast<CondBrInst>(Src->getTerminator());
1178 const unsigned Idx = ExitOnTrue ^ WillExit;
1179 BasicBlock *Dest = Term->getSuccessor(Idx);
1180 BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
1181
1182 // Remove predecessors from all non-Dest successors.
1183 DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
1184
1185 // Replace the conditional branch with an unconditional one.
1186 auto *BI = UncondBrInst::Create(Dest, Term->getIterator());
1187 BI->setDebugLoc(Term->getDebugLoc());
1188 Term->eraseFromParent();
1189
1190 DTUpdates.emplace_back(DominatorTree::Delete, Src, DeadSucc);
1191 };
1192
1193 auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
1194 bool IsLatch) -> std::optional<bool> {
1195 if (CompletelyUnroll) {
1196 if (PreserveOnlyFirst) {
1197 if (i == 0)
1198 return std::nullopt;
1199 return j == 0;
1200 }
1201 // Complete (but possibly inexact) unrolling
1202 if (j == 0)
1203 return true;
1204 if (Info.TripCount && j != Info.TripCount)
1205 return false;
1206 return std::nullopt;
1207 }
1208
1209 if (ULO.Runtime) {
1210 // If runtime unrolling inserts a prologue, information about non-latch
1211 // exits may be stale.
1212 if (IsLatch && j != 0)
1213 return false;
1214 return std::nullopt;
1215 }
1216
1217 if (j != Info.BreakoutTrip &&
1218 (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
1219 // If we know the trip count or a multiple of it, we can safely use an
1220 // unconditional branch for some iterations.
1221 return false;
1222 }
1223 return std::nullopt;
1224 };
1225
1226 // Fold branches for iterations where we know that they will exit or not
1227 // exit. In the case of an iteration's latch, if we thus find
1228 // *OriginalLoopProb is incorrect, set ProbUpdateRequired to true.
1229 bool ProbUpdateRequired = false;
1230 for (auto &Pair : ExitInfos) {
1231 ExitInfo &Info = Pair.second;
1232 for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
1233 // The branch destination.
1234 unsigned j = (i + 1) % e;
1235 bool IsLatch = Pair.first == LatchBlock;
1236 std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
1237 if (!KnownWillExit) {
1238 if (!Info.FirstExitingBlock)
1239 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1240 continue;
1241 }
1242
1243 // We don't fold known-exiting branches for non-latch exits here,
1244 // because this ensures that both all loop blocks and all exit blocks
1245 // remain reachable in the CFG.
1246 // TODO: We could fold these branches, but it would require much more
1247 // sophisticated updates to LoopInfo.
1248 if (*KnownWillExit && !IsLatch) {
1249 if (!Info.FirstExitingBlock)
1250 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1251 continue;
1252 }
1253
1254 // For a latch, record any OriginalLoopProb contradiction.
1255 if (!OriginalLoopProb.isUnknown() && IsLatch) {
1256 BranchProbability ActualProb = *KnownWillExit
1259 ProbUpdateRequired |= OriginalLoopProb != ActualProb;
1260 }
1261
1262 SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
1263 }
1264 }
1265
1266 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1267 DomTreeUpdater *DTUToUse = &DTU;
1268 if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) {
1269 // Manually update the DT if there's a single exiting node. In that case
1270 // there's a single exit node and it is sufficient to update the nodes
1271 // immediately dominated by the original exiting block. They will become
1272 // dominated by the first exiting block that leaves the loop after
1273 // unrolling. Note that the CFG inside the loop does not change, so there's
1274 // no need to update the DT inside the unrolled loop.
1275 DTUToUse = nullptr;
1276 auto &[OriginalExit, Info] = *ExitInfos.begin();
1277 if (!Info.FirstExitingBlock)
1278 Info.FirstExitingBlock = Info.ExitingBlocks.back();
1279 for (auto *C : to_vector(DT->getNode(OriginalExit)->children())) {
1280 if (L->contains(C->getBlock()))
1281 continue;
1282 C->setIDom(DT->getNode(Info.FirstExitingBlock));
1283 }
1284 } else {
1285 DTU.applyUpdates(DTUpdates);
1286 }
1287
1288 // When completely unrolling, the last latch becomes unreachable.
1289 if (!LatchIsExiting && CompletelyUnroll) {
1290 // There is no need to update the DT here, because there must be a unique
1291 // latch. Hence if the latch is not exiting it must directly branch back to
1292 // the original loop header and does not dominate any nodes.
1293 assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?");
1294 changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA);
1295 }
1296
1297 // After merging adjacent blocks in Latches below:
1298 // - CondLatches will list the blocks from Latches that are still terminated
1299 // with conditional branches.
1300 // - For 1 <= I < CondLatches.size(), IterCounts[I] will store the number of
1301 // the original loop iterations through which control flows from
1302 // CondLatches[I-1] to CondLatches[I].
1303 // - For I == 0 or I == CondLatches.size(), IterCounts[I] will store the
1304 // number of the original loop iterations through which control can flow
1305 // before CondLatches.front() or after CondLatches.back(), respectively,
1306 // without taking the unrolled loop's backedge, if any.
1307 // - CondLatchNexts[I] will store the CondLatches[I] branch target for the
1308 // next of the original loop's iterations (as opposed to the exit target).
1309 assert(ULO.Count == Latches.size() &&
1310 "Expected one latch block per unrolled iteration");
1311 std::vector<unsigned> IterCounts(1, 0);
1312 std::vector<BasicBlock *> CondLatches;
1313 std::vector<BasicBlock *> CondLatchNexts;
1314 IterCounts.reserve(Latches.size() + 1);
1315 CondLatches.reserve(Latches.size());
1316 CondLatchNexts.reserve(Latches.size());
1317
1318 // Merge adjacent basic blocks, if possible.
1319 for (auto [I, Latch] : enumerate(Latches)) {
1320 ++IterCounts.back();
1321 assert((isa<UncondBrInst, CondBrInst>(Latch->getTerminator()) ||
1322 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
1323 "Need a branch as terminator, except when fully unrolling with "
1324 "unconditional latch");
1325 if (auto *Term = dyn_cast<UncondBrInst>(Latch->getTerminator())) {
1326 BasicBlock *Dest = Term->getSuccessor();
1327 BasicBlock *Fold = Dest->getUniquePredecessor();
1328 if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
1329 /*MSSAU=*/nullptr, /*MemDep=*/nullptr,
1330 /*PredecessorWithTwoSuccessors=*/false,
1331 DTUToUse ? nullptr : DT)) {
1332 // Dest has been folded into Fold. Update our worklists accordingly.
1333 llvm::replace(Latches, Dest, Fold);
1334 llvm::erase(UnrolledLoopBlocks, Dest);
1335 }
1336 } else if (isa<CondBrInst>(Latch->getTerminator())) {
1337 IterCounts.push_back(0);
1338 CondLatches.push_back(Latch);
1339 CondLatchNexts.push_back(Headers[(I + 1) % Latches.size()]);
1340 }
1341 }
1342
1343 // Fix probabilities we contradicted above.
1344 if (ProbUpdateRequired) {
1345 fixProbContradiction(ULO, OriginalLoopProb, CompletelyUnroll, IterCounts,
1346 CondLatches, CondLatchNexts);
1347 }
1348
1349 // If there are partial reductions, create code in the exit block to compute
1350 // the final result and update users of the final result.
1351 if (!PartialReductions.empty()) {
1352 BasicBlock *ExitBlock = L->getExitBlock();
1353 assert(ExitBlock &&
1354 "Can only introduce parallel reduction phis with single exit block");
1355 assert(Reductions.size() == 1 &&
1356 "currently only a single reduction is supported");
1357 Value *FinalRdxValue = PartialReductions.back();
1358 Value *RdxResult = nullptr;
1359 for (PHINode &Phi : ExitBlock->phis()) {
1360 if (Phi.getIncomingValueForBlock(L->getLoopLatch()) != FinalRdxValue)
1361 continue;
1362 if (!RdxResult) {
1363 RdxResult = PartialReductions.front();
1364 IRBuilder Builder(ExitBlock, ExitBlock->getFirstNonPHIIt());
1365 Builder.setFastMathFlags(Reductions.begin()->second.getFastMathFlags());
1366 RecurKind RK = Reductions.begin()->second.getRecurrenceKind();
1367 for (Instruction *RdxPart : drop_begin(PartialReductions)) {
1368 RdxResult = Builder.CreateBinOp(
1370 RdxPart, RdxResult, "bin.rdx");
1371 }
1372 NeedToFixLCSSA = true;
1373 for (Instruction *RdxPart : PartialReductions)
1374 RdxPart->dropPoisonGeneratingFlags();
1375 }
1376
1377 Phi.replaceAllUsesWith(RdxResult);
1378 }
1379 }
1380
1381 if (DTUToUse) {
1382 // Apply updates to the DomTree.
1383 DT = &DTU.getDomTree();
1384 }
1386 DT->verify(DominatorTree::VerificationLevel::Fast));
1387
1388 Loop *OuterL = L->getParentLoop();
1389 std::vector<BasicBlock *> Blocks;
1390 // Update LoopInfo if the loop is completely removed.
1391 if (CompletelyUnroll) {
1392 Blocks = L->getBlocks();
1393 LI->erase(L);
1394 // We shouldn't try to use `L` anymore.
1395 L = nullptr;
1396 }
1397
1398 // At this point, the code is well formed. We now simplify the unrolled loop,
1399 // doing constant propagation and dead code elimination as we go.
1401 L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC, TTI,
1402 CompletelyUnroll ? ArrayRef<BasicBlock *>(Blocks) : L->getBlocks(), AA);
1403
1404 NumCompletelyUnrolled += CompletelyUnroll;
1405 ++NumUnrolled;
1406
1407 if (!CompletelyUnroll) {
1408 // Update metadata for the loop's branch weights and estimated trip count:
1409 // - If ULO.Runtime, UnrollRuntimeLoopRemainder sets the guard branch
1410 // weights, latch branch weights, and estimated trip count of the
1411 // remainder loop it creates. It also sets the branch weights for the
1412 // unrolled loop guard it creates. The branch weights for the unrolled
1413 // loop latch are adjusted below. FIXME: Handle prologue loops.
1414 // - Otherwise, if unrolled loop iteration latches become unconditional,
1415 // branch weights are adjusted by the fixProbContradiction call above.
1416 // - Otherwise, the original loop's branch weights are correct for the
1417 // unrolled loop, so do not adjust them.
1418 // - In all cases, the unrolled loop's estimated trip count is set below.
1419 //
1420 // As an example of the last case, consider what happens if the unroll count
1421 // is 4 for a loop with an estimated trip count of 10 when we do not create
1422 // a remainder loop and all iterations' latches remain conditional. Each
1423 // unrolled iteration's latch still has the same probability of exiting the
1424 // loop as it did when in the original loop, and thus it should still have
1425 // the same branch weights. Each unrolled iteration's non-zero probability
1426 // of exiting already appropriately reduces the probability of reaching the
1427 // remaining iterations just as it did in the original loop. Trying to also
1428 // adjust the branch weights of the final unrolled iteration's latch (i.e.,
1429 // the backedge for the unrolled loop as a whole) to reflect its new trip
1430 // count of 3 will erroneously further reduce its block frequencies.
1431 // However, in case an analysis later needs to estimate the trip count of
1432 // the unrolled loop as a whole without considering the branch weights for
1433 // each unrolled iteration's latch within it, we store the new trip count as
1434 // separate metadata.
1435 if (!OriginalLoopProb.isUnknown() && ULO.Runtime && EpilogProfitability) {
1436 assert((CondLatches.size() == 1 &&
1437 (ProbUpdateRequired || OriginalLoopProb.isOne())) &&
1438 "Expected ULO.Runtime to give unrolled loop 1 conditional latch, "
1439 "the backedge, requiring a probability update unless infinite");
1440 // Where p is always the probability of executing at least 1 more
1441 // iteration, the probability for at least n more iterations is p^n.
1442 setLoopProbability(L, OriginalLoopProb.pow(ULO.Count));
1443 }
1444 if (OriginalTripCount) {
1445 unsigned NewTripCount = *OriginalTripCount / ULO.Count;
1446 if (!ULO.Runtime && *OriginalTripCount % ULO.Count)
1447 ++NewTripCount;
1448 setLoopEstimatedTripCount(L, NewTripCount);
1449 }
1450 }
1451
1452 // LoopInfo should not be valid, confirm that.
1454 LI->verify(*DT);
1455
1456 // After complete unrolling most of the blocks should be contained in OuterL.
1457 // However, some of them might happen to be out of OuterL (e.g. if they
1458 // precede a loop exit). In this case we might need to insert PHI nodes in
1459 // order to preserve LCSSA form.
1460 // We don't need to check this if we already know that we need to fix LCSSA
1461 // form.
1462 // TODO: For now we just recompute LCSSA for the outer loop in this case, but
1463 // it should be possible to fix it in-place.
1464 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
1465 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
1466
1467 // Make sure that loop-simplify form is preserved. We want to simplify
1468 // at least one layer outside of the loop that was unrolled so that any
1469 // changes to the parent loop exposed by the unrolling are considered.
1470 if (OuterL) {
1471 // OuterL includes all loops for which we can break loop-simplify, so
1472 // it's sufficient to simplify only it (it'll recursively simplify inner
1473 // loops too).
1474 if (NeedToFixLCSSA) {
1475 // LCSSA must be performed on the outermost affected loop. The unrolled
1476 // loop's last loop latch is guaranteed to be in the outermost loop
1477 // after LoopInfo's been updated by LoopInfo::erase.
1478 Loop *LatchLoop = LI->getLoopFor(Latches.back());
1479 Loop *FixLCSSALoop = OuterL;
1480 if (!FixLCSSALoop->contains(LatchLoop))
1481 while (FixLCSSALoop->getParentLoop() != LatchLoop)
1482 FixLCSSALoop = FixLCSSALoop->getParentLoop();
1483
1484 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
1485 } else if (PreserveLCSSA) {
1486 assert(OuterL->isLCSSAForm(*DT) &&
1487 "Loops should be in LCSSA form after loop-unroll.");
1488 }
1489
1490 // TODO: That potentially might be compile-time expensive. We should try
1491 // to fix the loop-simplified form incrementally.
1492 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1493 } else {
1494 // Simplify loops for which we might've broken loop-simplify form.
1495 for (Loop *SubLoop : LoopsToSimplify)
1496 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1497 }
1498
1499 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
1501}
1502
1503/// Given an llvm.loop loop id metadata node, returns the loop hint metadata
1504/// node with the given name (for example, "llvm.loop.unroll.count"). If no
1505/// such metadata node exists, then nullptr is returned.
1507 // First operand should refer to the loop id itself.
1508 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1509 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1510
1511 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1512 MDNode *MD = dyn_cast<MDNode>(MDO);
1513 if (!MD)
1514 continue;
1515
1517 if (!S)
1518 continue;
1519
1520 if (Name == S->getString())
1521 return MD;
1522 }
1523 return nullptr;
1524}
1525
1526// Returns the loop hint metadata node with the given name (for example,
1527// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
1528// returned.
1530 if (MDNode *LoopID = L->getLoopID())
1531 return GetUnrollMetadata(LoopID, Name);
1532 return nullptr;
1533}
1534
1535std::optional<RecurrenceDescriptor>
1537 ScalarEvolution *SE) {
1538 RecurrenceDescriptor RdxDesc;
1539 if (!RecurrenceDescriptor::isReductionPHI(&Phi, L, RdxDesc,
1540 /*DemandedBits=*/nullptr,
1541 /*AC=*/nullptr, /*DT=*/nullptr, SE))
1542 return std::nullopt;
1543 if (RdxDesc.hasUsesOutsideReductionChain())
1544 return std::nullopt;
1545 RecurKind RK = RdxDesc.getRecurrenceKind();
1546 // Skip unsupported reductions.
1547 // TODO: Handle additional reductions, including FP and min-max
1548 // reductions.
1552 return std::nullopt;
1553
1554 if (RdxDesc.hasExactFPMath())
1555 return std::nullopt;
1556
1557 if (RdxDesc.IntermediateStore)
1558 return std::nullopt;
1559
1560 // Don't unroll reductions with constant ops; those can be folded to a
1561 // single induction update.
1562 if (any_of(cast<Instruction>(Phi.getIncomingValueForBlock(L->getLoopLatch()))
1563 ->operands(),
1565 return std::nullopt;
1566
1567 BasicBlock *Latch = L->getLoopLatch();
1568 if (!Latch ||
1569 !is_contained(
1570 cast<Instruction>(Phi.getIncomingValueForBlock(Latch))->operands(),
1571 &Phi))
1572 return std::nullopt;
1573
1574 return RdxDesc;
1575}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Optimize for code generation
#define LLVM_ATTRIBUTE_USED
Definition Compiler.h:236
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
#define DEBUG_TYPE
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
static bool needToInsertPhisForLCSSA(Loop *L, const std::vector< BasicBlock * > &Blocks, LoopInfo *LI)
Check if unrolling created a situation where we need to insert phi nodes to preserve LCSSA form.
static bool isEpilogProfitable(Loop *L)
The function chooses which type of unroll (epilog or prolog) is more profitabale.
static void fixProbContradiction(UnrollLoopOptions ULO, BranchProbability OriginalLoopProb, bool CompletelyUnroll, std::vector< unsigned > &IterCounts, const std::vector< BasicBlock * > &CondLatches, std::vector< BasicBlock * > &CondLatchNexts)
void loadCSE(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
Value * getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
static cl::opt< bool > UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden, cl::desc("Allow runtime unrolled loops to be unrolled " "with epilog instead of prolog."))
static cl::opt< bool > UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden, cl::desc("Verify loopinfo after unrolling"), cl::init(false))
static cl::opt< bool > UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, cl::desc("Verify domtree after unrolling"), cl::init(false))
static LLVM_ATTRIBUTE_USED bool canHaveUnrollRemainder(const Loop *L)
static cl::opt< bool > UnrollAddParallelReductions("unroll-add-parallel-reductions", cl::init(false), cl::Hidden, cl::desc("Allow unrolling to add parallel reduction phis."))
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
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.
uint64_t IntrinsicInst * II
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 SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
void childGeneration(unsigned generation)
bool isProcessed() const
unsigned currentGeneration() const
unsigned childGeneration() const
StackNode(ScopedHashTable< const SCEV *, LoadValue > &AvailableLoads, unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child, DomTreeNode::const_iterator End)
DomTreeNode::const_iterator end() const
void process()
DomTreeNode * nextChild()
DomTreeNode::const_iterator childIter() const
DomTreeNode * node()
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
LLVM_ABI BranchProbability pow(unsigned N) const
Compute pow(Probability, N).
static BranchProbability getOne()
static BranchProbability getZero()
Conditional Branch instruction.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
iterator begin() const
NodeT * getBlock() const
iterator end() const
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2835
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
An instruction for reading from memory.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Store the result of a depth first search within basic blocks contained by a single loop.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * AllocateLoop(ArgsTy &&...Args)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:441
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:908
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
Definition LoopInfo.cpp:484
Metadata node.
Definition Metadata.h:1080
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1444
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1442
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1450
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
A single uniqued string.
Definition Metadata.h:722
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
iterator end()
Definition MapVector.h:67
iterator find(const KeyT &Key)
Definition MapVector.h:154
bool contains(const KeyT &Key) const
Definition MapVector.h:146
iterator begin()
Definition MapVector.h:65
size_type size() const
Definition MapVector.h:56
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1039
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
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 applied optimization remarks.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
FastMathFlags getFastMathFlags() const
bool hasExactFPMath() const
Returns true if the recurrence has floating-point math that requires precise (ordered) operations.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
RecurKind getRecurrenceKind() const
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isFindRecurrenceKind(RecurKind Kind)
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
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 const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
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 void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
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.
LLVM_ABI void forgetAllLoops()
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
ScopedHashTableScope< K, V, KInfo, AllocatorTy > ScopeTy
ScopeTy - A type alias for easy access to the name of the scope for this hash table.
void insert_range(Range &&R)
Definition SetVector.h:176
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator begin()
Definition ValueMap.h:138
iterator end()
Definition ValueMap.h:139
ValueMapIteratorImpl< MapT, const Value *, false > iterator
Definition ValueMap.h:135
bool erase(const KeyT &Val)
Definition ValueMap.h:192
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
Definition ValueMap.h:123
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
Abstract Attribute helper functions.
Definition Attributor.h:165
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
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.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:535
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
LLVM_ABI std::optional< RecurrenceDescriptor > canParallelizeReductionWhenUnrolling(PHINode &Phi, Loop *L, ScalarEvolution *SE)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
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)
SmallDenseMap< const Loop *, Loop *, 4 > NewLoopsMap
Definition UnrollLoop.h:41
LLVM_ABI cl::opt< bool > EnableFSDiscriminator
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:449
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
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.
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:94
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:403
void setBranchProbability(CondBrInst *B, BranchProbability P, bool ForFirstTarget)
Set branch weight metadata for B to indicate that P and 1 - P are the probabilities of control flowin...
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
BranchProbability getLoopProbability(Loop *L)
Based on branch weight metadata, return either:
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 unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition Local.cpp:2528
bool setLoopProbability(Loop *L, BranchProbability P)
Set branch weight metadata for the latch of L to indicate that, at the end of any iteration,...
TargetTransformInfo TTI
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1910
RecurKind
These are the kinds of recurrences that we support.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
LLVM_ABI MDNode * getUnrollMetadataForLoop(const Loop *L, StringRef Name)
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, std::optional< unsigned > EstimatedLoopInvocationWeight=std::nullopt)
Set llvm.loop.estimated_trip_count with the value EstimatedTripCount in the loop metadata of L.
LLVM_ABI const Loop * addClonedBlockToLoopInfo(BasicBlock *OriginalBB, BasicBlock *ClonedBB, LoopInfo *LI, NewLoopsMap &NewLoops)
Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary and adds a mapping from the o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
LLVM_ABI bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, bool PreserveLCSSA, unsigned SCEVExpansionBudget, bool RuntimeUnrollMultiExit, Loop **ResultLoop=nullptr, std::optional< unsigned > OriginalTripCount=std::nullopt, BranchProbability OriginalLoopProb=BranchProbability::getUnknown())
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
LLVM_ABI MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
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.
#define N
Instruction * DefI
LoadValue()=default
unsigned Generation
LoadValue(Instruction *Inst, unsigned Generation)
const Instruction * Heart
Definition UnrollLoop.h:79
std::conditional_t< IsConst, const ValueT &, ValueT & > second
Definition ValueMap.h:349