LLVM 19.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/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/ADT/Twine.h"
34#include "llvm/IR/BasicBlock.h"
35#include "llvm/IR/CFG.h"
36#include "llvm/IR/Constants.h"
38#include "llvm/IR/DebugLoc.h"
40#include "llvm/IR/Dominators.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Metadata.h"
46#include "llvm/IR/Module.h"
48#include "llvm/IR/Use.h"
49#include "llvm/IR/User.h"
50#include "llvm/IR/ValueHandle.h"
51#include "llvm/IR/ValueMap.h"
54#include "llvm/Support/Debug.h"
66#include <algorithm>
67#include <assert.h>
68#include <numeric>
69#include <type_traits>
70#include <vector>
71
72namespace llvm {
73class DataLayout;
74class Value;
75} // namespace llvm
76
77using namespace llvm;
78
79#define DEBUG_TYPE "loop-unroll"
80
81// TODO: Should these be here or in LoopUnroll?
82STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
83STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
84STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
85 "latch (completely or otherwise)");
86
87static cl::opt<bool>
88UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
89 cl::desc("Allow runtime unrolled loops to be unrolled "
90 "with epilog instead of prolog."));
91
92static cl::opt<bool>
93UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
94 cl::desc("Verify domtree after unrolling"),
95#ifdef EXPENSIVE_CHECKS
96 cl::init(true)
97#else
98 cl::init(false)
99#endif
100 );
101
102static cl::opt<bool>
103UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
104 cl::desc("Verify loopinfo after unrolling"),
105#ifdef EXPENSIVE_CHECKS
106 cl::init(true)
107#else
108 cl::init(false)
109#endif
110 );
111
112
113/// Check if unrolling created a situation where we need to insert phi nodes to
114/// preserve LCSSA form.
115/// \param Blocks is a vector of basic blocks representing unrolled loop.
116/// \param L is the outer loop.
117/// It's possible that some of the blocks are in L, and some are not. In this
118/// case, if there is a use is outside L, and definition is inside L, we need to
119/// insert a phi-node, otherwise LCSSA will be broken.
120/// The function is just a helper function for llvm::UnrollLoop that returns
121/// true if this situation occurs, indicating that LCSSA needs to be fixed.
123 const std::vector<BasicBlock *> &Blocks,
124 LoopInfo *LI) {
125 for (BasicBlock *BB : Blocks) {
126 if (LI->getLoopFor(BB) == L)
127 continue;
128 for (Instruction &I : *BB) {
129 for (Use &U : I.operands()) {
130 if (const auto *Def = dyn_cast<Instruction>(U)) {
131 Loop *DefLoop = LI->getLoopFor(Def->getParent());
132 if (!DefLoop)
133 continue;
134 if (DefLoop->contains(L))
135 return true;
136 }
137 }
138 }
139 }
140 return false;
141}
142
143/// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
144/// and adds a mapping from the original loop to the new loop to NewLoops.
145/// Returns nullptr if no new loop was created and a pointer to the
146/// original loop OriginalBB was part of otherwise.
148 BasicBlock *ClonedBB, LoopInfo *LI,
149 NewLoopsMap &NewLoops) {
150 // Figure out which loop New is in.
151 const Loop *OldLoop = LI->getLoopFor(OriginalBB);
152 assert(OldLoop && "Should (at least) be in the loop being unrolled!");
153
154 Loop *&NewLoop = NewLoops[OldLoop];
155 if (!NewLoop) {
156 // Found a new sub-loop.
157 assert(OriginalBB == OldLoop->getHeader() &&
158 "Header should be first in RPO");
159
160 NewLoop = LI->AllocateLoop();
161 Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
162
163 if (NewLoopParent)
164 NewLoopParent->addChildLoop(NewLoop);
165 else
166 LI->addTopLevelLoop(NewLoop);
167
168 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
169 return OldLoop;
170 } else {
171 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
172 return nullptr;
173 }
174}
175
176/// The function chooses which type of unroll (epilog or prolog) is more
177/// profitabale.
178/// Epilog unroll is more profitable when there is PHI that starts from
179/// constant. In this case epilog will leave PHI start from constant,
180/// but prolog will convert it to non-constant.
181///
182/// loop:
183/// PN = PHI [I, Latch], [CI, PreHeader]
184/// I = foo(PN)
185/// ...
186///
187/// Epilog unroll case.
188/// loop:
189/// PN = PHI [I2, Latch], [CI, PreHeader]
190/// I1 = foo(PN)
191/// I2 = foo(I1)
192/// ...
193/// Prolog unroll case.
194/// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
195/// loop:
196/// PN = PHI [I2, Latch], [NewPN, PreHeader]
197/// I1 = foo(PN)
198/// I2 = foo(I1)
199/// ...
200///
201static bool isEpilogProfitable(Loop *L) {
202 BasicBlock *PreHeader = L->getLoopPreheader();
203 BasicBlock *Header = L->getHeader();
204 assert(PreHeader && Header);
205 for (const PHINode &PN : Header->phis()) {
206 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
207 return true;
208 }
209 return false;
210}
211
212/// Perform some cleanup and simplifications on loops after unrolling. It is
213/// useful to simplify the IV's in the new loop, as well as do a quick
214/// simplify/dce pass of the instructions.
215void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
217 AssumptionCache *AC,
218 const TargetTransformInfo *TTI) {
219 using namespace llvm::PatternMatch;
220
221 // Simplify any new induction variables in the partially unrolled loop.
222 if (SE && SimplifyIVs) {
224 simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
225
226 // Aggressively clean up dead instructions that simplifyLoopIVs already
227 // identified. Any remaining should be cleaned up below.
228 while (!DeadInsts.empty()) {
229 Value *V = DeadInsts.pop_back_val();
230 if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
232 }
233 }
234
235 // At this point, the code is well formed. Perform constprop, instsimplify,
236 // and dce.
237 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
239 for (BasicBlock *BB : L->getBlocks()) {
240 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
241 if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
242 if (LI->replacementPreservesLCSSAForm(&Inst, V))
243 Inst.replaceAllUsesWith(V);
245 DeadInsts.emplace_back(&Inst);
246
247 // Fold ((add X, C1), C2) to (add X, C1+C2). This is very common in
248 // unrolled loops, and handling this early allows following code to
249 // identify the IV as a "simple recurrence" without first folding away
250 // a long chain of adds.
251 {
252 Value *X;
253 const APInt *C1, *C2;
254 if (match(&Inst, m_Add(m_Add(m_Value(X), m_APInt(C1)), m_APInt(C2)))) {
255 auto *InnerI = dyn_cast<Instruction>(Inst.getOperand(0));
256 auto *InnerOBO = cast<OverflowingBinaryOperator>(Inst.getOperand(0));
257 bool SignedOverflow;
258 APInt NewC = C1->sadd_ov(*C2, SignedOverflow);
259 Inst.setOperand(0, X);
260 Inst.setOperand(1, ConstantInt::get(Inst.getType(), NewC));
261 Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() &&
262 InnerOBO->hasNoUnsignedWrap());
263 Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() &&
264 InnerOBO->hasNoSignedWrap() &&
265 !SignedOverflow);
266 if (InnerI && isInstructionTriviallyDead(InnerI))
267 DeadInsts.emplace_back(InnerI);
268 }
269 }
270 }
271 // We can't do recursive deletion until we're done iterating, as we might
272 // have a phi which (potentially indirectly) uses instructions later in
273 // the block we're iterating through.
275 }
276}
277
278/// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
279/// can only fail when the loop's latch block is not terminated by a conditional
280/// branch instruction. However, if the trip count (and multiple) are not known,
281/// loop unrolling will mostly produce more code that is no faster.
282///
283/// If Runtime is true then UnrollLoop will try to insert a prologue or
284/// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
285/// will not runtime-unroll the loop if computing the run-time trip count will
286/// be expensive and AllowExpensiveTripCount is false.
287///
288/// The LoopInfo Analysis that is passed will be kept consistent.
289///
290/// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
291/// DominatorTree if they are non-null.
292///
293/// If RemainderLoop is non-null, it will receive the remainder loop (if
294/// required and not fully unrolled).
297 AssumptionCache *AC,
300 bool PreserveLCSSA, Loop **RemainderLoop) {
301 assert(DT && "DomTree is required");
302
303 if (!L->getLoopPreheader()) {
304 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
306 }
307
308 if (!L->getLoopLatch()) {
309 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
311 }
312
313 // Loops with indirectbr cannot be cloned.
314 if (!L->isSafeToClone()) {
315 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
317 }
318
319 if (L->getHeader()->hasAddressTaken()) {
320 // The loop-rotate pass can be helpful to avoid this in many cases.
322 dbgs() << " Won't unroll loop: address of header block is taken.\n");
324 }
325
326 assert(ULO.Count > 0);
327
328 // All these values should be taken only after peeling because they might have
329 // changed.
330 BasicBlock *Preheader = L->getLoopPreheader();
331 BasicBlock *Header = L->getHeader();
332 BasicBlock *LatchBlock = L->getLoopLatch();
334 L->getExitBlocks(ExitBlocks);
335 std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
336
337 const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
338 const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
339 unsigned EstimatedLoopInvocationWeight = 0;
340 std::optional<unsigned> OriginalTripCount =
341 llvm::getLoopEstimatedTripCount(L, &EstimatedLoopInvocationWeight);
342
343 // Effectively "DCE" unrolled iterations that are beyond the max tripcount
344 // and will never be executed.
345 if (MaxTripCount && ULO.Count > MaxTripCount)
346 ULO.Count = MaxTripCount;
347
348 struct ExitInfo {
349 unsigned TripCount;
350 unsigned TripMultiple;
351 unsigned BreakoutTrip;
352 bool ExitOnTrue;
353 BasicBlock *FirstExitingBlock = nullptr;
354 SmallVector<BasicBlock *> ExitingBlocks;
355 };
357 SmallVector<BasicBlock *, 4> ExitingBlocks;
358 L->getExitingBlocks(ExitingBlocks);
359 for (auto *ExitingBlock : ExitingBlocks) {
360 // The folding code is not prepared to deal with non-branch instructions
361 // right now.
362 auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
363 if (!BI)
364 continue;
365
366 ExitInfo &Info = ExitInfos.try_emplace(ExitingBlock).first->second;
367 Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
368 Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
369 if (Info.TripCount != 0) {
370 Info.BreakoutTrip = Info.TripCount % ULO.Count;
371 Info.TripMultiple = 0;
372 } else {
373 Info.BreakoutTrip = Info.TripMultiple =
374 (unsigned)std::gcd(ULO.Count, Info.TripMultiple);
375 }
376 Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
377 Info.ExitingBlocks.push_back(ExitingBlock);
378 LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName()
379 << ": TripCount=" << Info.TripCount
380 << ", TripMultiple=" << Info.TripMultiple
381 << ", BreakoutTrip=" << Info.BreakoutTrip << "\n");
382 }
383
384 // Are we eliminating the loop control altogether? Note that we can know
385 // we're eliminating the backedge without knowing exactly which iteration
386 // of the unrolled body exits.
387 const bool CompletelyUnroll = ULO.Count == MaxTripCount;
388
389 const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
390
391 // There's no point in performing runtime unrolling if this unroll count
392 // results in a full unroll.
393 if (CompletelyUnroll)
394 ULO.Runtime = false;
395
396 // Go through all exits of L and see if there are any phi-nodes there. We just
397 // conservatively assume that they're inserted to preserve LCSSA form, which
398 // means that complete unrolling might break this form. We need to either fix
399 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
400 // now we just recompute LCSSA for the outer loop, but it should be possible
401 // to fix it in-place.
402 bool NeedToFixLCSSA =
403 PreserveLCSSA && CompletelyUnroll &&
404 any_of(ExitBlocks,
405 [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
406
407 // The current loop unroll pass can unroll loops that have
408 // (1) single latch; and
409 // (2a) latch is unconditional; or
410 // (2b) latch is conditional and is an exiting block
411 // FIXME: The implementation can be extended to work with more complicated
412 // cases, e.g. loops with multiple latches.
413 BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
414
415 // A conditional branch which exits the loop, which can be optimized to an
416 // unconditional branch in the unrolled loop in some cases.
417 bool LatchIsExiting = L->isLoopExiting(LatchBlock);
418 if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
420 dbgs() << "Can't unroll; a conditional latch must exit the loop");
421 return LoopUnrollResult::Unmodified;
422 }
423
424 // Loops containing convergent instructions cannot use runtime unrolling,
425 // as the prologue/epilogue may add additional control-dependencies to
426 // convergent operations.
428 {
429 bool HasConvergent = false;
430 for (auto &BB : L->blocks())
431 for (auto &I : *BB)
432 if (auto *CB = dyn_cast<CallBase>(&I))
433 HasConvergent |= CB->isConvergent();
434 assert((!HasConvergent || !ULO.Runtime) &&
435 "Can't runtime unroll if loop contains a convergent operation.");
436 });
437
438 bool EpilogProfitability =
439 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
441
442 if (ULO.Runtime &&
444 EpilogProfitability, ULO.UnrollRemainder,
445 ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
446 PreserveLCSSA, RemainderLoop)) {
447 if (ULO.Force)
448 ULO.Runtime = false;
449 else {
450 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
451 "generated when assuming runtime trip count\n");
452 return LoopUnrollResult::Unmodified;
453 }
454 }
455
456 using namespace ore;
457 // Report the unrolling decision.
458 if (CompletelyUnroll) {
459 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
460 << " with trip count " << ULO.Count << "!\n");
461 if (ORE)
462 ORE->emit([&]() {
463 return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
464 L->getHeader())
465 << "completely unrolled loop with "
466 << NV("UnrollCount", ULO.Count) << " iterations";
467 });
468 } else {
469 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
470 << ULO.Count);
471 if (ULO.Runtime)
472 LLVM_DEBUG(dbgs() << " with run-time trip count");
473 LLVM_DEBUG(dbgs() << "!\n");
474
475 if (ORE)
476 ORE->emit([&]() {
477 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
478 L->getHeader());
479 Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
480 if (ULO.Runtime)
481 Diag << " with run-time trip count";
482 return Diag;
483 });
484 }
485
486 // We are going to make changes to this loop. SCEV may be keeping cached info
487 // about it, in particular about backedge taken count. The changes we make
488 // are guaranteed to invalidate this information for our loop. It is tempting
489 // to only invalidate the loop being unrolled, but it is incorrect as long as
490 // all exiting branches from all inner loops have impact on the outer loops,
491 // and if something changes inside them then any of outer loops may also
492 // change. When we forget outermost loop, we also forget all contained loops
493 // and this is what we need here.
494 if (SE) {
495 if (ULO.ForgetAllSCEV)
496 SE->forgetAllLoops();
497 else {
498 SE->forgetTopmostLoop(L);
500 }
501 }
502
503 if (!LatchIsExiting)
504 ++NumUnrolledNotLatch;
505
506 // For the first iteration of the loop, we should use the precloned values for
507 // PHI nodes. Insert associations now.
508 ValueToValueMapTy LastValueMap;
509 std::vector<PHINode*> OrigPHINode;
510 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
511 OrigPHINode.push_back(cast<PHINode>(I));
512 }
513
514 std::vector<BasicBlock *> Headers;
515 std::vector<BasicBlock *> Latches;
516 Headers.push_back(Header);
517 Latches.push_back(LatchBlock);
518
519 // The current on-the-fly SSA update requires blocks to be processed in
520 // reverse postorder so that LastValueMap contains the correct value at each
521 // exit.
522 LoopBlocksDFS DFS(L);
523 DFS.perform(LI);
524
525 // Stash the DFS iterators before adding blocks to the loop.
526 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
527 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
528
529 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
530
531 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
532 // might break loop-simplified form for these loops (as they, e.g., would
533 // share the same exit blocks). We'll keep track of loops for which we can
534 // break this so that later we can re-simplify them.
535 SmallSetVector<Loop *, 4> LoopsToSimplify;
536 for (Loop *SubLoop : *L)
537 LoopsToSimplify.insert(SubLoop);
538
539 // When a FSDiscriminator is enabled, we don't need to add the multiply
540 // factors to the discriminators.
541 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
543 for (BasicBlock *BB : L->getBlocks())
544 for (Instruction &I : *BB)
545 if (!I.isDebugOrPseudoInst())
546 if (const DILocation *DIL = I.getDebugLoc()) {
547 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
548 if (NewDIL)
549 I.setDebugLoc(*NewDIL);
550 else
552 << "Failed to create new discriminator: "
553 << DIL->getFilename() << " Line: " << DIL->getLine());
554 }
555
556 // Identify what noalias metadata is inside the loop: if it is inside the
557 // loop, the associated metadata must be cloned for each iteration.
558 SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
559 identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
560
561 // We place the unrolled iterations immediately after the original loop
562 // latch. This is a reasonable default placement if we don't have block
563 // frequencies, and if we do, well the layout will be adjusted later.
564 auto BlockInsertPt = std::next(LatchBlock->getIterator());
565 for (unsigned It = 1; It != ULO.Count; ++It) {
568 NewLoops[L] = L;
569
570 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
572 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
573 Header->getParent()->insert(BlockInsertPt, New);
574
575 assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
576 "Header should not be in a sub-loop");
577 // Tell LI about New.
578 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
579 if (OldLoop)
580 LoopsToSimplify.insert(NewLoops[OldLoop]);
581
582 if (*BB == Header)
583 // Loop over all of the PHI nodes in the block, changing them to use
584 // the incoming values from the previous block.
585 for (PHINode *OrigPHI : OrigPHINode) {
586 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
587 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
588 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
589 if (It > 1 && L->contains(InValI))
590 InVal = LastValueMap[InValI];
591 VMap[OrigPHI] = InVal;
592 NewPHI->eraseFromParent();
593 }
594
595 // Update our running map of newest clones
596 LastValueMap[*BB] = New;
597 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
598 VI != VE; ++VI)
599 LastValueMap[VI->first] = VI->second;
600
601 // Add phi entries for newly created values to all exit blocks.
602 for (BasicBlock *Succ : successors(*BB)) {
603 if (L->contains(Succ))
604 continue;
605 for (PHINode &PHI : Succ->phis()) {
606 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
607 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
608 if (It != LastValueMap.end())
609 Incoming = It->second;
610 PHI.addIncoming(Incoming, New);
611 SE->forgetValue(&PHI);
612 }
613 }
614 // Keep track of new headers and latches as we create them, so that
615 // we can insert the proper branches later.
616 if (*BB == Header)
617 Headers.push_back(New);
618 if (*BB == LatchBlock)
619 Latches.push_back(New);
620
621 // Keep track of the exiting block and its successor block contained in
622 // the loop for the current iteration.
623 auto ExitInfoIt = ExitInfos.find(*BB);
624 if (ExitInfoIt != ExitInfos.end())
625 ExitInfoIt->second.ExitingBlocks.push_back(New);
626
627 NewBlocks.push_back(New);
628 UnrolledLoopBlocks.push_back(New);
629
630 // Update DomTree: since we just copy the loop body, and each copy has a
631 // dedicated entry block (copy of the header block), this header's copy
632 // dominates all copied blocks. That means, dominance relations in the
633 // copied body are the same as in the original body.
634 if (*BB == Header)
635 DT->addNewBlock(New, Latches[It - 1]);
636 else {
637 auto BBDomNode = DT->getNode(*BB);
638 auto BBIDom = BBDomNode->getIDom();
639 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
640 DT->addNewBlock(
641 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
642 }
643 }
644
645 // Remap all instructions in the most recent iteration
646 remapInstructionsInBlocks(NewBlocks, LastValueMap);
647 for (BasicBlock *NewBlock : NewBlocks)
648 for (Instruction &I : *NewBlock)
649 if (auto *II = dyn_cast<AssumeInst>(&I))
650 AC->registerAssumption(II);
651
652 {
653 // Identify what other metadata depends on the cloned version. After
654 // cloning, replace the metadata with the corrected version for both
655 // memory instructions and noalias intrinsics.
656 std::string ext = (Twine("It") + Twine(It)).str();
657 cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
658 Header->getContext(), ext);
659 }
660 }
661
662 // Loop over the PHI nodes in the original block, setting incoming values.
663 for (PHINode *PN : OrigPHINode) {
664 if (CompletelyUnroll) {
665 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
666 PN->eraseFromParent();
667 } else if (ULO.Count > 1) {
668 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
669 // If this value was defined in the loop, take the value defined by the
670 // last iteration of the loop.
671 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
672 if (L->contains(InValI))
673 InVal = LastValueMap[InVal];
674 }
675 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
676 PN->addIncoming(InVal, Latches.back());
677 }
678 }
679
680 // Connect latches of the unrolled iterations to the headers of the next
681 // iteration. Currently they point to the header of the same iteration.
682 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
683 unsigned j = (i + 1) % e;
684 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
685 }
686
687 // Update dominators of blocks we might reach through exits.
688 // Immediate dominator of such block might change, because we add more
689 // routes which can lead to the exit: we can now reach it from the copied
690 // iterations too.
691 if (ULO.Count > 1) {
692 for (auto *BB : OriginalLoopBlocks) {
693 auto *BBDomNode = DT->getNode(BB);
694 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
695 for (auto *ChildDomNode : BBDomNode->children()) {
696 auto *ChildBB = ChildDomNode->getBlock();
697 if (!L->contains(ChildBB))
698 ChildrenToUpdate.push_back(ChildBB);
699 }
700 // The new idom of the block will be the nearest common dominator
701 // of all copies of the previous idom. This is equivalent to the
702 // nearest common dominator of the previous idom and the first latch,
703 // which dominates all copies of the previous idom.
704 BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
705 for (auto *ChildBB : ChildrenToUpdate)
706 DT->changeImmediateDominator(ChildBB, NewIDom);
707 }
708 }
709
711 DT->verify(DominatorTree::VerificationLevel::Fast));
712
714 auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
715 auto *Term = cast<BranchInst>(Src->getTerminator());
716 const unsigned Idx = ExitOnTrue ^ WillExit;
717 BasicBlock *Dest = Term->getSuccessor(Idx);
718 BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
719
720 // Remove predecessors from all non-Dest successors.
721 DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
722
723 // Replace the conditional branch with an unconditional one.
724 BranchInst::Create(Dest, Term->getIterator());
725 Term->eraseFromParent();
726
727 DTUpdates.emplace_back(DominatorTree::Delete, Src, DeadSucc);
728 };
729
730 auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
731 bool IsLatch) -> std::optional<bool> {
732 if (CompletelyUnroll) {
733 if (PreserveOnlyFirst) {
734 if (i == 0)
735 return std::nullopt;
736 return j == 0;
737 }
738 // Complete (but possibly inexact) unrolling
739 if (j == 0)
740 return true;
741 if (Info.TripCount && j != Info.TripCount)
742 return false;
743 return std::nullopt;
744 }
745
746 if (ULO.Runtime) {
747 // If runtime unrolling inserts a prologue, information about non-latch
748 // exits may be stale.
749 if (IsLatch && j != 0)
750 return false;
751 return std::nullopt;
752 }
753
754 if (j != Info.BreakoutTrip &&
755 (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
756 // If we know the trip count or a multiple of it, we can safely use an
757 // unconditional branch for some iterations.
758 return false;
759 }
760 return std::nullopt;
761 };
762
763 // Fold branches for iterations where we know that they will exit or not
764 // exit.
765 for (auto &Pair : ExitInfos) {
766 ExitInfo &Info = Pair.second;
767 for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
768 // The branch destination.
769 unsigned j = (i + 1) % e;
770 bool IsLatch = Pair.first == LatchBlock;
771 std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
772 if (!KnownWillExit) {
773 if (!Info.FirstExitingBlock)
774 Info.FirstExitingBlock = Info.ExitingBlocks[i];
775 continue;
776 }
777
778 // We don't fold known-exiting branches for non-latch exits here,
779 // because this ensures that both all loop blocks and all exit blocks
780 // remain reachable in the CFG.
781 // TODO: We could fold these branches, but it would require much more
782 // sophisticated updates to LoopInfo.
783 if (*KnownWillExit && !IsLatch) {
784 if (!Info.FirstExitingBlock)
785 Info.FirstExitingBlock = Info.ExitingBlocks[i];
786 continue;
787 }
788
789 SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
790 }
791 }
792
793 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
794 DomTreeUpdater *DTUToUse = &DTU;
795 if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) {
796 // Manually update the DT if there's a single exiting node. In that case
797 // there's a single exit node and it is sufficient to update the nodes
798 // immediately dominated by the original exiting block. They will become
799 // dominated by the first exiting block that leaves the loop after
800 // unrolling. Note that the CFG inside the loop does not change, so there's
801 // no need to update the DT inside the unrolled loop.
802 DTUToUse = nullptr;
803 auto &[OriginalExit, Info] = *ExitInfos.begin();
804 if (!Info.FirstExitingBlock)
805 Info.FirstExitingBlock = Info.ExitingBlocks.back();
806 for (auto *C : to_vector(DT->getNode(OriginalExit)->children())) {
807 if (L->contains(C->getBlock()))
808 continue;
809 C->setIDom(DT->getNode(Info.FirstExitingBlock));
810 }
811 } else {
812 DTU.applyUpdates(DTUpdates);
813 }
814
815 // When completely unrolling, the last latch becomes unreachable.
816 if (!LatchIsExiting && CompletelyUnroll) {
817 // There is no need to update the DT here, because there must be a unique
818 // latch. Hence if the latch is not exiting it must directly branch back to
819 // the original loop header and does not dominate any nodes.
820 assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?");
821 changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA);
822 }
823
824 // Merge adjacent basic blocks, if possible.
825 for (BasicBlock *Latch : Latches) {
826 BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
827 assert((Term ||
828 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
829 "Need a branch as terminator, except when fully unrolling with "
830 "unconditional latch");
831 if (Term && Term->isUnconditional()) {
832 BasicBlock *Dest = Term->getSuccessor(0);
833 BasicBlock *Fold = Dest->getUniquePredecessor();
834 if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
835 /*MSSAU=*/nullptr, /*MemDep=*/nullptr,
836 /*PredecessorWithTwoSuccessors=*/false,
837 DTUToUse ? nullptr : DT)) {
838 // Dest has been folded into Fold. Update our worklists accordingly.
839 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
840 llvm::erase(UnrolledLoopBlocks, Dest);
841 }
842 }
843 }
844
845 if (DTUToUse) {
846 // Apply updates to the DomTree.
847 DT = &DTU.getDomTree();
848 }
850 DT->verify(DominatorTree::VerificationLevel::Fast));
851
852 // At this point, the code is well formed. We now simplify the unrolled loop,
853 // doing constant propagation and dead code elimination as we go.
854 simplifyLoopAfterUnroll(L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC,
855 TTI);
856
857 NumCompletelyUnrolled += CompletelyUnroll;
858 ++NumUnrolled;
859
860 Loop *OuterL = L->getParentLoop();
861 // Update LoopInfo if the loop is completely removed.
862 if (CompletelyUnroll) {
863 LI->erase(L);
864 // We shouldn't try to use `L` anymore.
865 L = nullptr;
866 } else if (OriginalTripCount) {
867 // Update the trip count. Note that the remainder has already logic
868 // computing it in `UnrollRuntimeLoopRemainder`.
869 setLoopEstimatedTripCount(L, *OriginalTripCount / ULO.Count,
870 EstimatedLoopInvocationWeight);
871 }
872
873 // LoopInfo should not be valid, confirm that.
875 LI->verify(*DT);
876
877 // After complete unrolling most of the blocks should be contained in OuterL.
878 // However, some of them might happen to be out of OuterL (e.g. if they
879 // precede a loop exit). In this case we might need to insert PHI nodes in
880 // order to preserve LCSSA form.
881 // We don't need to check this if we already know that we need to fix LCSSA
882 // form.
883 // TODO: For now we just recompute LCSSA for the outer loop in this case, but
884 // it should be possible to fix it in-place.
885 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
886 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
887
888 // Make sure that loop-simplify form is preserved. We want to simplify
889 // at least one layer outside of the loop that was unrolled so that any
890 // changes to the parent loop exposed by the unrolling are considered.
891 if (OuterL) {
892 // OuterL includes all loops for which we can break loop-simplify, so
893 // it's sufficient to simplify only it (it'll recursively simplify inner
894 // loops too).
895 if (NeedToFixLCSSA) {
896 // LCSSA must be performed on the outermost affected loop. The unrolled
897 // loop's last loop latch is guaranteed to be in the outermost loop
898 // after LoopInfo's been updated by LoopInfo::erase.
899 Loop *LatchLoop = LI->getLoopFor(Latches.back());
900 Loop *FixLCSSALoop = OuterL;
901 if (!FixLCSSALoop->contains(LatchLoop))
902 while (FixLCSSALoop->getParentLoop() != LatchLoop)
903 FixLCSSALoop = FixLCSSALoop->getParentLoop();
904
905 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
906 } else if (PreserveLCSSA) {
907 assert(OuterL->isLCSSAForm(*DT) &&
908 "Loops should be in LCSSA form after loop-unroll.");
909 }
910
911 // TODO: That potentially might be compile-time expensive. We should try
912 // to fix the loop-simplified form incrementally.
913 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
914 } else {
915 // Simplify loops for which we might've broken loop-simplify form.
916 for (Loop *SubLoop : LoopsToSimplify)
917 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
918 }
919
920 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
921 : LoopUnrollResult::PartiallyUnrolled;
922}
923
924/// Given an llvm.loop loop id metadata node, returns the loop hint metadata
925/// node with the given name (for example, "llvm.loop.unroll.count"). If no
926/// such metadata node exists, then nullptr is returned.
928 // First operand should refer to the loop id itself.
929 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
930 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
931
932 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
933 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
934 if (!MD)
935 continue;
936
937 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
938 if (!S)
939 continue;
940
941 if (Name.equals(S->getString()))
942 return MD;
943 }
944 return nullptr;
945}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
std::string Name
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:507
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
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...
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.
Definition: LoopUnroll.cpp:122
static bool isEpilogProfitable(Loop *L)
The function chooses which type of unroll (epilog or prolog) is more profitabale.
Definition: LoopUnroll.cpp:201
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."))
#define DEBUG_TYPE
Definition: LoopUnroll.cpp:79
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))
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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:167
This defines the Use class.
Class for arbitrary precision integers.
Definition: APInt.h:76
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1898
A cache of @llvm.assume calls within a function.
void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:430
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:460
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:482
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:221
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:509
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
Debug location.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
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:202
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:235
unsigned size() const
Definition: DenseMap.h:99
iterator begin()
Definition: DenseMap.h:75
iterator end()
Definition: DenseMap.h:84
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
DominatorTree & getDomTree()
Flush DomTree updates and return DomTree.
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:162
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...
Definition: Dominators.cpp:344
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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.
Definition: LoopIterator.h:97
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
Definition: LoopIterator.h:136
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
Definition: LoopIterator.h:101
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Definition: LoopInfo.cpp:1222
RPOIterator endRPO() const
Definition: LoopIterator.h:140
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:439
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition: LoopInfo.cpp:875
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
Definition: LoopInfo.cpp:462
Metadata node.
Definition: Metadata.h:1067
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1428
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1434
A single uniqued string.
Definition: Metadata.h:720
StringRef getString() const
Definition: Metadata.cpp:610
The optimization diagnostic interface.
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
The main scalar evolution driver.
unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
unsigned getSmallConstantMaxTripCount(const Loop *L)
Returns the upper bound of the loop trip count as a normal unsigned value.
bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
void forgetTopmostLoop(const Loop *L)
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
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.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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:81
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
iterator find(const KeyT &Val)
Definition: ValueMap.h:155
iterator begin()
Definition: ValueMap.h:134
iterator end()
Definition: ValueMap.h:135
LLVM Value Representation.
Definition: Value.h:74
self_iterator getIterator()
Definition: ilist_node.h:109
@ 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)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:294
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
Definition: LoopUtils.cpp:849
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:539
auto successors(const MachineBasicBlock *BB)
bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:425
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:656
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition: STLExtras.h:2059
cl::opt< bool > EnableFSDiscriminator
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:1729
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:399
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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...
Definition: SmallVector.h:1312
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
Definition: UnrollLoop.h:54
@ Unmodified
The loop was not modified.
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:2832
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.
bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, unsigned EstimatedLoopInvocationWeight)
Set a loop's branch weight metadata to reflect that loop has EstimatedTripCount iterations and Estima...
Definition: LoopUtils.cpp:867
void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
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...
Definition: LoopUnroll.cpp:147
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)
Unroll the given loop by Count.
Definition: LoopUnroll.cpp:295
void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI)
Perform some cleanup and simplifications on loops after unrolling.
Definition: LoopUnroll.cpp:215
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...
Definition: LoopUnroll.cpp:927
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, Loop **ResultLoop=nullptr)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...