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({
844 dbgs() << "UNROLLING loop %" << Header->getName() << " by " << ULO.Count;
845 if (ULO.Runtime) {
846 dbgs() << " with run-time trip count";
847 if (ULO.UnrollRemainder)
848 dbgs() << " (remainder unrolled)";
849 }
850 dbgs() << "!\n";
851 });
852
853 if (ORE)
854 ORE->emit([&]() {
855 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
856 L->getHeader());
857 Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
858 if (ULO.Runtime)
859 Diag << " with run-time trip count"
860 << (ULO.UnrollRemainder ? " (remainder unrolled)" : "");
861 return Diag;
862 });
863 }
864
865 // We are going to make changes to this loop. SCEV may be keeping cached info
866 // about it, in particular about backedge taken count. The changes we make
867 // are guaranteed to invalidate this information for our loop. It is tempting
868 // to only invalidate the loop being unrolled, but it is incorrect as long as
869 // all exiting branches from all inner loops have impact on the outer loops,
870 // and if something changes inside them then any of outer loops may also
871 // change. When we forget outermost loop, we also forget all contained loops
872 // and this is what we need here.
873 if (SE) {
874 if (ULO.ForgetAllSCEV)
875 SE->forgetAllLoops();
876 else {
877 SE->forgetTopmostLoop(L);
879 }
880 }
881
882 if (!LatchIsExiting)
883 ++NumUnrolledNotLatch;
884
885 // For the first iteration of the loop, we should use the precloned values for
886 // PHI nodes. Insert associations now.
887 ValueToValueMapTy LastValueMap;
888 std::vector<PHINode*> OrigPHINode;
889 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
890 OrigPHINode.push_back(cast<PHINode>(I));
891 }
892
893 // Collect phi nodes for reductions for which we can introduce multiple
894 // parallel reduction phis and compute the final reduction result after the
895 // loop. This requires a single exit block after unrolling. This is ensured by
896 // restricting to single-block loops where the unrolled iterations are known
897 // to not exit.
899 bool CanAddAdditionalAccumulators =
900 (UnrollAddParallelReductions.getNumOccurrences() > 0
903 !CompletelyUnroll && L->getNumBlocks() == 1 &&
904 (ULO.Runtime ||
905 (ExitInfos.contains(Header) && ((ExitInfos[Header].TripCount != 0 &&
906 ExitInfos[Header].BreakoutTrip == 0))));
907
908 // Limit parallelizing reductions to unroll counts of 4 or less for now.
909 // TODO: The number of parallel reductions should depend on the number of
910 // execution units. We also don't have to add a parallel reduction phi per
911 // unrolled iteration, but could for example add a parallel phi for every 2
912 // unrolled iterations.
913 if (CanAddAdditionalAccumulators && ULO.Count <= 4) {
914 for (PHINode &Phi : Header->phis()) {
915 auto RdxDesc = canParallelizeReductionWhenUnrolling(Phi, L, SE);
916 if (!RdxDesc)
917 continue;
918
919 // Only handle duplicate phis for a single reduction for now.
920 // TODO: Handle any number of reductions
921 if (!Reductions.empty())
922 continue;
923
924 Reductions[&Phi] = *RdxDesc;
925 }
926 }
927
928 std::vector<BasicBlock *> Headers;
929 std::vector<BasicBlock *> Latches;
930 Headers.push_back(Header);
931 Latches.push_back(LatchBlock);
932
933 // The current on-the-fly SSA update requires blocks to be processed in
934 // reverse postorder so that LastValueMap contains the correct value at each
935 // exit.
936 LoopBlocksDFS DFS(L);
937 DFS.perform(LI);
938
939 // Stash the DFS iterators before adding blocks to the loop.
940 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
941 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
942
943 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
944
945 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
946 // might break loop-simplified form for these loops (as they, e.g., would
947 // share the same exit blocks). We'll keep track of loops for which we can
948 // break this so that later we can re-simplify them.
949 SmallSetVector<Loop *, 4> LoopsToSimplify;
950 LoopsToSimplify.insert_range(*L);
951
952 // When a FSDiscriminator is enabled, we don't need to add the multiply
953 // factors to the discriminators.
954 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
956 for (BasicBlock *BB : L->getBlocks())
957 for (Instruction &I : *BB)
958 if (!I.isDebugOrPseudoInst())
959 if (const DILocation *DIL = I.getDebugLoc()) {
960 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
961 if (NewDIL)
962 I.setDebugLoc(*NewDIL);
963 else
965 << "Failed to create new discriminator: "
966 << DIL->getFilename() << " Line: " << DIL->getLine());
967 }
968
969 // Identify what noalias metadata is inside the loop: if it is inside the
970 // loop, the associated metadata must be cloned for each iteration.
971 SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
972 identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
973
974 // We place the unrolled iterations immediately after the original loop
975 // latch. This is a reasonable default placement if we don't have block
976 // frequencies, and if we do, well the layout will be adjusted later.
977 auto BlockInsertPt = std::next(LatchBlock->getIterator());
978 SmallVector<Instruction *> PartialReductions;
979 for (unsigned It = 1; It != ULO.Count; ++It) {
982 NewLoops[L] = L;
983
984 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
986 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
987 Header->getParent()->insert(BlockInsertPt, New);
988
989 assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
990 "Header should not be in a sub-loop");
991 // Tell LI about New.
992 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
993 if (OldLoop)
994 LoopsToSimplify.insert(NewLoops[OldLoop]);
995
996 if (*BB == Header) {
997 // Loop over all of the PHI nodes in the block, changing them to use
998 // the incoming values from the previous block.
999 for (PHINode *OrigPHI : OrigPHINode) {
1000 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
1001 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
1002
1003 // Use cloned phis as parallel phis for partial reductions, which will
1004 // get combined to the final reduction result after the loop.
1005 if (Reductions.contains(OrigPHI)) {
1006 // Collect partial reduction results.
1007 if (PartialReductions.empty())
1008 PartialReductions.push_back(cast<Instruction>(InVal));
1009 PartialReductions.push_back(cast<Instruction>(VMap[InVal]));
1010
1011 // Update the start value for the cloned phis to use the identity
1012 // value for the reduction.
1013 const RecurrenceDescriptor &RdxDesc = Reductions[OrigPHI];
1015 L->getLoopPreheader(),
1017 OrigPHI->getType(),
1018 RdxDesc.getFastMathFlags()));
1019
1020 // Update NewPHI to use the cloned value for the iteration and move
1021 // to header.
1022 NewPHI->replaceUsesOfWith(InVal, VMap[InVal]);
1023 NewPHI->moveBefore(OrigPHI->getIterator());
1024 continue;
1025 }
1026
1027 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
1028 if (It > 1 && L->contains(InValI))
1029 InVal = LastValueMap[InValI];
1030 VMap[OrigPHI] = InVal;
1031 NewPHI->eraseFromParent();
1032 }
1033
1034 // Eliminate copies of the loop heart intrinsic, if any.
1035 if (ULO.Heart) {
1036 auto it = VMap.find(ULO.Heart);
1037 assert(it != VMap.end());
1038 Instruction *heartCopy = cast<Instruction>(it->second);
1039 heartCopy->eraseFromParent();
1040 VMap.erase(it);
1041 }
1042 }
1043
1044 // Remap source location atom instance. Do this now, rather than
1045 // when we remap instructions, because remap is called once we've
1046 // cloned all blocks (all the clones would get the same atom
1047 // number).
1048 if (!VMap.AtomMap.empty())
1049 for (Instruction &I : *New)
1050 RemapSourceAtom(&I, VMap);
1051
1052 // Update our running map of newest clones
1053 LastValueMap[*BB] = New;
1054 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
1055 VI != VE; ++VI)
1056 LastValueMap[VI->first] = VI->second;
1057
1058 // Add phi entries for newly created values to all exit blocks.
1059 for (BasicBlock *Succ : successors(*BB)) {
1060 if (L->contains(Succ))
1061 continue;
1062 for (PHINode &PHI : Succ->phis()) {
1063 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
1064 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
1065 if (It != LastValueMap.end())
1066 Incoming = It->second;
1067 PHI.addIncoming(Incoming, New);
1069 }
1070 }
1071 // Keep track of new headers and latches as we create them, so that
1072 // we can insert the proper branches later.
1073 if (*BB == Header)
1074 Headers.push_back(New);
1075 if (*BB == LatchBlock)
1076 Latches.push_back(New);
1077
1078 // Keep track of the exiting block and its successor block contained in
1079 // the loop for the current iteration.
1080 auto ExitInfoIt = ExitInfos.find(*BB);
1081 if (ExitInfoIt != ExitInfos.end())
1082 ExitInfoIt->second.ExitingBlocks.push_back(New);
1083
1084 NewBlocks.push_back(New);
1085 UnrolledLoopBlocks.push_back(New);
1086
1087 // Update DomTree: since we just copy the loop body, and each copy has a
1088 // dedicated entry block (copy of the header block), this header's copy
1089 // dominates all copied blocks. That means, dominance relations in the
1090 // copied body are the same as in the original body.
1091 if (*BB == Header)
1092 DT->addNewBlock(New, Latches[It - 1]);
1093 else {
1094 auto BBDomNode = DT->getNode(*BB);
1095 auto BBIDom = BBDomNode->getIDom();
1096 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
1097 DT->addNewBlock(
1098 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
1099 }
1100 }
1101
1102 // Remap all instructions in the most recent iteration.
1103 // Key Instructions: Nothing to do - we've already remapped the atoms.
1104 remapInstructionsInBlocks(NewBlocks, LastValueMap);
1105 for (BasicBlock *NewBlock : NewBlocks)
1106 for (Instruction &I : *NewBlock)
1107 if (auto *II = dyn_cast<AssumeInst>(&I))
1109
1110 {
1111 // Identify what other metadata depends on the cloned version. After
1112 // cloning, replace the metadata with the corrected version for both
1113 // memory instructions and noalias intrinsics.
1114 std::string ext = (Twine("It") + Twine(It)).str();
1115 cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
1116 Header->getContext(), ext);
1117 }
1118 }
1119
1120 // Loop over the PHI nodes in the original block, setting incoming values.
1121 for (PHINode *PN : OrigPHINode) {
1122 if (CompletelyUnroll) {
1123 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
1124 PN->eraseFromParent();
1125 } else if (ULO.Count > 1) {
1126 if (Reductions.contains(PN))
1127 continue;
1128
1129 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
1130 // If this value was defined in the loop, take the value defined by the
1131 // last iteration of the loop.
1132 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
1133 if (L->contains(InValI))
1134 InVal = LastValueMap[InVal];
1135 }
1136 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
1137 PN->addIncoming(InVal, Latches.back());
1138 }
1139 }
1140
1141 // Connect latches of the unrolled iterations to the headers of the next
1142 // iteration. Currently they point to the header of the same iteration.
1143 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
1144 unsigned j = (i + 1) % e;
1145 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
1146 }
1147
1148 // Remove loop metadata copied from the original loop latch to branches that
1149 // are no longer latches.
1150 for (unsigned I = 0, E = Latches.size() - (CompletelyUnroll ? 0 : 1); I < E;
1151 ++I)
1152 Latches[I]->getTerminator()->setMetadata(LLVMContext::MD_loop, nullptr);
1153
1154 // Update dominators of blocks we might reach through exits.
1155 // Immediate dominator of such block might change, because we add more
1156 // routes which can lead to the exit: we can now reach it from the copied
1157 // iterations too.
1158 if (ULO.Count > 1) {
1159 for (auto *BB : OriginalLoopBlocks) {
1160 auto *BBDomNode = DT->getNode(BB);
1161 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
1162 for (auto *ChildDomNode : BBDomNode->children()) {
1163 auto *ChildBB = ChildDomNode->getBlock();
1164 if (!L->contains(ChildBB))
1165 ChildrenToUpdate.push_back(ChildBB);
1166 }
1167 // The new idom of the block will be the nearest common dominator
1168 // of all copies of the previous idom. This is equivalent to the
1169 // nearest common dominator of the previous idom and the first latch,
1170 // which dominates all copies of the previous idom.
1171 BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
1172 for (auto *ChildBB : ChildrenToUpdate)
1173 DT->changeImmediateDominator(ChildBB, NewIDom);
1174 }
1175 }
1176
1178 DT->verify(DominatorTree::VerificationLevel::Fast));
1179
1181 auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
1182 auto *Term = cast<CondBrInst>(Src->getTerminator());
1183 const unsigned Idx = ExitOnTrue ^ WillExit;
1184 BasicBlock *Dest = Term->getSuccessor(Idx);
1185 BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
1186
1187 // Remove predecessors from all non-Dest successors.
1188 DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
1189
1190 // Replace the conditional branch with an unconditional one.
1191 auto *BI = UncondBrInst::Create(Dest, Term->getIterator());
1192 BI->setDebugLoc(Term->getDebugLoc());
1193 Term->eraseFromParent();
1194
1195 DTUpdates.emplace_back(DominatorTree::Delete, Src, DeadSucc);
1196 };
1197
1198 auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
1199 bool IsLatch) -> std::optional<bool> {
1200 if (CompletelyUnroll) {
1201 if (PreserveOnlyFirst) {
1202 if (i == 0)
1203 return std::nullopt;
1204 return j == 0;
1205 }
1206 // Complete (but possibly inexact) unrolling
1207 if (j == 0)
1208 return true;
1209 if (Info.TripCount && j != Info.TripCount)
1210 return false;
1211 return std::nullopt;
1212 }
1213
1214 if (ULO.Runtime) {
1215 // If runtime unrolling inserts a prologue, information about non-latch
1216 // exits may be stale.
1217 if (IsLatch && j != 0)
1218 return false;
1219 return std::nullopt;
1220 }
1221
1222 if (j != Info.BreakoutTrip &&
1223 (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
1224 // If we know the trip count or a multiple of it, we can safely use an
1225 // unconditional branch for some iterations.
1226 return false;
1227 }
1228 return std::nullopt;
1229 };
1230
1231 // Fold branches for iterations where we know that they will exit or not
1232 // exit. In the case of an iteration's latch, if we thus find
1233 // *OriginalLoopProb is incorrect, set ProbUpdateRequired to true.
1234 bool ProbUpdateRequired = false;
1235 for (auto &Pair : ExitInfos) {
1236 ExitInfo &Info = Pair.second;
1237 for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
1238 // The branch destination.
1239 unsigned j = (i + 1) % e;
1240 bool IsLatch = Pair.first == LatchBlock;
1241 std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
1242 if (!KnownWillExit) {
1243 if (!Info.FirstExitingBlock)
1244 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1245 continue;
1246 }
1247
1248 // We don't fold known-exiting branches for non-latch exits here,
1249 // because this ensures that both all loop blocks and all exit blocks
1250 // remain reachable in the CFG.
1251 // TODO: We could fold these branches, but it would require much more
1252 // sophisticated updates to LoopInfo.
1253 if (*KnownWillExit && !IsLatch) {
1254 if (!Info.FirstExitingBlock)
1255 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1256 continue;
1257 }
1258
1259 // For a latch, record any OriginalLoopProb contradiction.
1260 if (!OriginalLoopProb.isUnknown() && IsLatch) {
1261 BranchProbability ActualProb = *KnownWillExit
1264 ProbUpdateRequired |= OriginalLoopProb != ActualProb;
1265 }
1266
1267 SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
1268 }
1269 }
1270
1271 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1272 DomTreeUpdater *DTUToUse = &DTU;
1273 if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) {
1274 // Manually update the DT if there's a single exiting node. In that case
1275 // there's a single exit node and it is sufficient to update the nodes
1276 // immediately dominated by the original exiting block. They will become
1277 // dominated by the first exiting block that leaves the loop after
1278 // unrolling. Note that the CFG inside the loop does not change, so there's
1279 // no need to update the DT inside the unrolled loop.
1280 DTUToUse = nullptr;
1281 auto &[OriginalExit, Info] = *ExitInfos.begin();
1282 if (!Info.FirstExitingBlock)
1283 Info.FirstExitingBlock = Info.ExitingBlocks.back();
1284 for (auto *C : to_vector(DT->getNode(OriginalExit)->children())) {
1285 if (L->contains(C->getBlock()))
1286 continue;
1287 C->setIDom(DT->getNode(Info.FirstExitingBlock));
1288 }
1289 } else {
1290 DTU.applyUpdates(DTUpdates);
1291 }
1292
1293 // When completely unrolling, the last latch becomes unreachable.
1294 if (!LatchIsExiting && CompletelyUnroll) {
1295 // There is no need to update the DT here, because there must be a unique
1296 // latch. Hence if the latch is not exiting it must directly branch back to
1297 // the original loop header and does not dominate any nodes.
1298 assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?");
1299 changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA);
1300 }
1301
1302 // After merging adjacent blocks in Latches below:
1303 // - CondLatches will list the blocks from Latches that are still terminated
1304 // with conditional branches.
1305 // - For 1 <= I < CondLatches.size(), IterCounts[I] will store the number of
1306 // the original loop iterations through which control flows from
1307 // CondLatches[I-1] to CondLatches[I].
1308 // - For I == 0 or I == CondLatches.size(), IterCounts[I] will store the
1309 // number of the original loop iterations through which control can flow
1310 // before CondLatches.front() or after CondLatches.back(), respectively,
1311 // without taking the unrolled loop's backedge, if any.
1312 // - CondLatchNexts[I] will store the CondLatches[I] branch target for the
1313 // next of the original loop's iterations (as opposed to the exit target).
1314 assert(ULO.Count == Latches.size() &&
1315 "Expected one latch block per unrolled iteration");
1316 std::vector<unsigned> IterCounts(1, 0);
1317 std::vector<BasicBlock *> CondLatches;
1318 std::vector<BasicBlock *> CondLatchNexts;
1319 IterCounts.reserve(Latches.size() + 1);
1320 CondLatches.reserve(Latches.size());
1321 CondLatchNexts.reserve(Latches.size());
1322
1323 // Merge adjacent basic blocks, if possible.
1324 for (auto [I, Latch] : enumerate(Latches)) {
1325 ++IterCounts.back();
1326 assert((isa<UncondBrInst, CondBrInst>(Latch->getTerminator()) ||
1327 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
1328 "Need a branch as terminator, except when fully unrolling with "
1329 "unconditional latch");
1330 if (auto *Term = dyn_cast<UncondBrInst>(Latch->getTerminator())) {
1331 BasicBlock *Dest = Term->getSuccessor();
1332 BasicBlock *Fold = Dest->getUniquePredecessor();
1333 if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
1334 /*MSSAU=*/nullptr, /*MemDep=*/nullptr,
1335 /*PredecessorWithTwoSuccessors=*/false,
1336 DTUToUse ? nullptr : DT)) {
1337 // Dest has been folded into Fold. Update our worklists accordingly.
1338 llvm::replace(Latches, Dest, Fold);
1339 llvm::erase(UnrolledLoopBlocks, Dest);
1340 }
1341 } else if (isa<CondBrInst>(Latch->getTerminator())) {
1342 IterCounts.push_back(0);
1343 CondLatches.push_back(Latch);
1344 CondLatchNexts.push_back(Headers[(I + 1) % Latches.size()]);
1345 }
1346 }
1347
1348 // Fix probabilities we contradicted above.
1349 if (ProbUpdateRequired) {
1350 fixProbContradiction(ULO, OriginalLoopProb, CompletelyUnroll, IterCounts,
1351 CondLatches, CondLatchNexts);
1352 }
1353
1354 // If there are partial reductions, create code in the exit block to compute
1355 // the final result and update users of the final result.
1356 if (!PartialReductions.empty()) {
1357 BasicBlock *ExitBlock = L->getExitBlock();
1358 assert(ExitBlock &&
1359 "Can only introduce parallel reduction phis with single exit block");
1360 assert(Reductions.size() == 1 &&
1361 "currently only a single reduction is supported");
1362 Value *FinalRdxValue = PartialReductions.back();
1363 Value *RdxResult = nullptr;
1364 for (PHINode &Phi : ExitBlock->phis()) {
1365 if (Phi.getIncomingValueForBlock(L->getLoopLatch()) != FinalRdxValue)
1366 continue;
1367 if (!RdxResult) {
1368 RdxResult = PartialReductions.front();
1369 IRBuilder Builder(ExitBlock, ExitBlock->getFirstNonPHIIt());
1370 Builder.setFastMathFlags(Reductions.begin()->second.getFastMathFlags());
1371 RecurKind RK = Reductions.begin()->second.getRecurrenceKind();
1372 for (Instruction *RdxPart : drop_begin(PartialReductions)) {
1373 RdxResult = Builder.CreateBinOp(
1375 RdxPart, RdxResult, "bin.rdx");
1376 }
1377 NeedToFixLCSSA = true;
1378 for (Instruction *RdxPart : PartialReductions)
1379 RdxPart->dropPoisonGeneratingFlags();
1380 }
1381
1382 Phi.replaceAllUsesWith(RdxResult);
1383 }
1384 }
1385
1386 if (DTUToUse) {
1387 // Apply updates to the DomTree.
1388 DT = &DTU.getDomTree();
1389 }
1391 DT->verify(DominatorTree::VerificationLevel::Fast));
1392
1393 Loop *OuterL = L->getParentLoop();
1394 std::vector<BasicBlock *> Blocks;
1395 // Update LoopInfo if the loop is completely removed.
1396 if (CompletelyUnroll) {
1397 Blocks = L->getBlocks();
1398 LI->erase(L);
1399 // We shouldn't try to use `L` anymore.
1400 L = nullptr;
1401 }
1402
1403 // At this point, the code is well formed. We now simplify the unrolled loop,
1404 // doing constant propagation and dead code elimination as we go.
1406 L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC, TTI,
1407 CompletelyUnroll ? ArrayRef<BasicBlock *>(Blocks) : L->getBlocks(), AA);
1408
1409 NumCompletelyUnrolled += CompletelyUnroll;
1410 ++NumUnrolled;
1411
1412 if (!CompletelyUnroll) {
1413 // Update metadata for the loop's branch weights and estimated trip count:
1414 // - If ULO.Runtime, UnrollRuntimeLoopRemainder sets the guard branch
1415 // weights, latch branch weights, and estimated trip count of the
1416 // remainder loop it creates. It also sets the branch weights for the
1417 // unrolled loop guard it creates. The branch weights for the unrolled
1418 // loop latch are adjusted below. FIXME: Handle prologue loops.
1419 // - Otherwise, if unrolled loop iteration latches become unconditional,
1420 // branch weights are adjusted by the fixProbContradiction call above.
1421 // - Otherwise, the original loop's branch weights are correct for the
1422 // unrolled loop, so do not adjust them.
1423 // - In all cases, the unrolled loop's estimated trip count is set below.
1424 //
1425 // As an example of the last case, consider what happens if the unroll count
1426 // is 4 for a loop with an estimated trip count of 10 when we do not create
1427 // a remainder loop and all iterations' latches remain conditional. Each
1428 // unrolled iteration's latch still has the same probability of exiting the
1429 // loop as it did when in the original loop, and thus it should still have
1430 // the same branch weights. Each unrolled iteration's non-zero probability
1431 // of exiting already appropriately reduces the probability of reaching the
1432 // remaining iterations just as it did in the original loop. Trying to also
1433 // adjust the branch weights of the final unrolled iteration's latch (i.e.,
1434 // the backedge for the unrolled loop as a whole) to reflect its new trip
1435 // count of 3 will erroneously further reduce its block frequencies.
1436 // However, in case an analysis later needs to estimate the trip count of
1437 // the unrolled loop as a whole without considering the branch weights for
1438 // each unrolled iteration's latch within it, we store the new trip count as
1439 // separate metadata.
1440 if (!OriginalLoopProb.isUnknown() && ULO.Runtime && EpilogProfitability) {
1441 assert((CondLatches.size() == 1 &&
1442 (ProbUpdateRequired || OriginalLoopProb.isOne())) &&
1443 "Expected ULO.Runtime to give unrolled loop 1 conditional latch, "
1444 "the backedge, requiring a probability update unless infinite");
1445 // Where p is always the probability of executing at least 1 more
1446 // iteration, the probability for at least n more iterations is p^n.
1447 setLoopProbability(L, OriginalLoopProb.pow(ULO.Count));
1448 }
1449 if (OriginalTripCount) {
1450 unsigned NewTripCount = *OriginalTripCount / ULO.Count;
1451 if (!ULO.Runtime && *OriginalTripCount % ULO.Count)
1452 ++NewTripCount;
1453 setLoopEstimatedTripCount(L, NewTripCount);
1454 }
1455 }
1456
1457 // LoopInfo should not be valid, confirm that.
1459 LI->verify(*DT);
1460
1461 // After complete unrolling most of the blocks should be contained in OuterL.
1462 // However, some of them might happen to be out of OuterL (e.g. if they
1463 // precede a loop exit). In this case we might need to insert PHI nodes in
1464 // order to preserve LCSSA form.
1465 // We don't need to check this if we already know that we need to fix LCSSA
1466 // form.
1467 // TODO: For now we just recompute LCSSA for the outer loop in this case, but
1468 // it should be possible to fix it in-place.
1469 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
1470 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
1471
1472 // Make sure that loop-simplify form is preserved. We want to simplify
1473 // at least one layer outside of the loop that was unrolled so that any
1474 // changes to the parent loop exposed by the unrolling are considered.
1475 if (OuterL) {
1476 // OuterL includes all loops for which we can break loop-simplify, so
1477 // it's sufficient to simplify only it (it'll recursively simplify inner
1478 // loops too).
1479 if (NeedToFixLCSSA) {
1480 // LCSSA must be performed on the outermost affected loop. The unrolled
1481 // loop's last loop latch is guaranteed to be in the outermost loop
1482 // after LoopInfo's been updated by LoopInfo::erase.
1483 Loop *LatchLoop = LI->getLoopFor(Latches.back());
1484 Loop *FixLCSSALoop = OuterL;
1485 if (!FixLCSSALoop->contains(LatchLoop))
1486 while (FixLCSSALoop->getParentLoop() != LatchLoop)
1487 FixLCSSALoop = FixLCSSALoop->getParentLoop();
1488
1489 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
1490 } else if (PreserveLCSSA) {
1491 assert(OuterL->isLCSSAForm(*DT) &&
1492 "Loops should be in LCSSA form after loop-unroll.");
1493 }
1494
1495 // TODO: That potentially might be compile-time expensive. We should try
1496 // to fix the loop-simplified form incrementally.
1497 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1498 } else {
1499 // Simplify loops for which we might've broken loop-simplify form.
1500 for (Loop *SubLoop : LoopsToSimplify)
1501 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1502 }
1503
1504 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
1506}
1507
1508/// Given an llvm.loop loop id metadata node, returns the loop hint metadata
1509/// node with the given name (for example, "llvm.loop.unroll.count"). If no
1510/// such metadata node exists, then nullptr is returned.
1512 // First operand should refer to the loop id itself.
1513 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1514 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1515
1516 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1517 MDNode *MD = dyn_cast<MDNode>(MDO);
1518 if (!MD)
1519 continue;
1520
1522 if (!S)
1523 continue;
1524
1525 if (Name == S->getString())
1526 return MD;
1527 }
1528 return nullptr;
1529}
1530
1531// Returns the loop hint metadata node with the given name (for example,
1532// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
1533// returned.
1535 if (MDNode *LoopID = L->getLoopID())
1536 return GetUnrollMetadata(LoopID, Name);
1537 return nullptr;
1538}
1539
1540std::optional<RecurrenceDescriptor>
1542 ScalarEvolution *SE) {
1543 RecurrenceDescriptor RdxDesc;
1544 if (!RecurrenceDescriptor::isReductionPHI(&Phi, L, RdxDesc,
1545 /*DemandedBits=*/nullptr,
1546 /*AC=*/nullptr, /*DT=*/nullptr, SE))
1547 return std::nullopt;
1548 if (RdxDesc.hasUsesOutsideReductionChain())
1549 return std::nullopt;
1550 RecurKind RK = RdxDesc.getRecurrenceKind();
1551 // Skip unsupported reductions.
1552 // TODO: Handle additional reductions, including FP and min-max
1553 // reductions.
1557 return std::nullopt;
1558
1559 if (RdxDesc.hasExactFPMath())
1560 return std::nullopt;
1561
1562 if (RdxDesc.IntermediateStore)
1563 return std::nullopt;
1564
1565 // Don't unroll reductions with constant ops; those can be folded to a
1566 // single induction update.
1567 if (any_of(cast<Instruction>(Phi.getIncomingValueForBlock(L->getLoopLatch()))
1568 ->operands(),
1570 return std::nullopt;
1571
1572 BasicBlock *Latch = L->getLoopLatch();
1573 if (!Latch ||
1574 !is_contained(
1575 cast<Instruction>(Phi.getIncomingValueForBlock(Latch))->operands(),
1576 &Phi))
1577 return std::nullopt;
1578
1579 return RdxDesc;
1580}
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:2847
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