LLVM 24.0.0git
LoopUtils.cpp
Go to the documentation of this file.
1//===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
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 defines common loop utility functions.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/ScopeExit.h"
17#include "llvm/ADT/SetVector.h"
35#include "llvm/IR/Dominators.h"
38#include "llvm/IR/MDBuilder.h"
39#include "llvm/IR/Module.h"
42#include "llvm/IR/ValueHandle.h"
45#include "llvm/Pass.h"
47#include "llvm/Support/Debug.h"
51using namespace llvm;
52using namespace llvm::PatternMatch;
53
54#define DEBUG_TYPE "loop-utils"
55
56static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
57static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
58
60 MemorySSAUpdater *MSSAU,
61 bool PreserveLCSSA) {
62 bool Changed = false;
63
64 // We re-use a vector for the in-loop predecesosrs.
65 SmallVector<BasicBlock *, 4> InLoopPredecessors;
66
67 auto RewriteExit = [&](BasicBlock *BB) {
68 assert(InLoopPredecessors.empty() &&
69 "Must start with an empty predecessors list!");
70 llvm::scope_exit Cleanup([&] { InLoopPredecessors.clear(); });
71
72 // See if there are any non-loop predecessors of this exit block and
73 // keep track of the in-loop predecessors.
74 bool IsDedicatedExit = true;
75 for (auto *PredBB : predecessors(BB))
76 if (L->contains(PredBB)) {
77 if (isa<IndirectBrInst>(PredBB->getTerminator()))
78 // We cannot rewrite exiting edges from an indirectbr.
79 return false;
80
81 InLoopPredecessors.push_back(PredBB);
82 } else {
83 IsDedicatedExit = false;
84 }
85
86 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
87
88 // Nothing to do if this is already a dedicated exit.
89 if (IsDedicatedExit)
90 return false;
91
92 auto *NewExitBB = SplitBlockPredecessors(
93 BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
94
95 if (!NewExitBB)
97 dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
98 << *L << "\n");
99 else
100 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
101 << NewExitBB->getName() << "\n");
102 return true;
103 };
104
105 // Walk the exit blocks directly rather than building up a data structure for
106 // them, but only visit each one once.
108 for (auto *BB : L->blocks())
109 for (auto *SuccBB : successors(BB)) {
110 // We're looking for exit blocks so skip in-loop successors.
111 if (L->contains(SuccBB))
112 continue;
113
114 // Visit each exit block exactly once.
115 if (!Visited.insert(SuccBB).second)
116 continue;
117
118 Changed |= RewriteExit(SuccBB);
119 }
120
121 return Changed;
122}
123
124/// Returns the instructions that use values defined in the loop.
127
128 for (auto *Block : L->getBlocks())
129 // FIXME: I believe that this could use copy_if if the Inst reference could
130 // be adapted into a pointer.
131 for (auto &Inst : *Block) {
132 auto Users = Inst.users();
133 if (any_of(Users, [&](User *U) {
134 auto *Use = cast<Instruction>(U);
135 return !L->contains(Use->getParent());
136 }))
137 UsedOutside.push_back(&Inst);
138 }
139
140 return UsedOutside;
141}
142
144 // By definition, all loop passes need the LoopInfo analysis and the
145 // Dominator tree it depends on. Because they all participate in the loop
146 // pass manager, they must also preserve these.
151
152 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
153 // here because users shouldn't directly get them from this header.
154 extern char &LoopSimplifyID;
155 extern char &LCSSAID;
160 // This is used in the LPPassManager to perform LCSSA verification on passes
161 // which preserve lcssa form
164
165 // Loop passes are designed to run inside of a loop pass manager which means
166 // that any function analyses they require must be required by the first loop
167 // pass in the manager (so that it is computed before the loop pass manager
168 // runs) and preserved by all loop pasess in the manager. To make this
169 // reasonably robust, the set needed for most loop passes is maintained here.
170 // If your loop pass requires an analysis not listed here, you will need to
171 // carefully audit the loop pass manager nesting structure that results.
179 // FIXME: When all loop passes preserve MemorySSA, it can be required and
180 // preserved here instead of the individual handling in each pass.
181}
182
183/// Manually defined generic "LoopPass" dependency initialization. This is used
184/// to initialize the exact set of passes from above in \c
185/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
186/// with:
187///
188/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
189///
190/// As-if "LoopPass" were a pass.
203
204/// Create MDNode for input string.
205static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
206 LLVMContext &Context = TheLoop->getHeader()->getContext();
207 Metadata *MDs[] = {
208 MDString::get(Context, Name),
209 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
210 return MDNode::get(Context, MDs);
211}
212
213/// Set input string into loop metadata by keeping other values intact.
214/// If the string is already in loop metadata update value if it is
215/// different.
216void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
217 unsigned V) {
219 // If the loop already has metadata, retain it.
220 MDNode *LoopID = TheLoop->getLoopID();
221 if (LoopID) {
222 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
223 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
224 // If it is of form key = value, try to parse it.
225 if (Node->getNumOperands() == 2) {
226 MDString *S = dyn_cast<MDString>(Node->getOperand(0));
227 if (S && S->getString() == StringMD) {
228 ConstantInt *IntMD =
230 if (IntMD && IntMD->getSExtValue() == V)
231 // It is already in place. Do nothing.
232 return;
233 // We need to update the value, so just skip it here and it will
234 // be added after copying other existed nodes.
235 continue;
236 }
237 }
238 MDs.push_back(Node);
239 }
240 }
241 // Add new metadata.
242 MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
243 // Replace current metadata node with new one.
244 LLVMContext &Context = TheLoop->getHeader()->getContext();
245 MDNode *NewLoopID = MDNode::get(Context, MDs);
246 // Set operand 0 to refer to the loop id itself.
247 NewLoopID->replaceOperandWith(0, NewLoopID);
248 TheLoop->setLoopID(NewLoopID);
249}
250
252 LLVMContext &Context = TheLoop->getHeader()->getContext();
254 // Retain existing metadata, skipping a name-only node with the same string.
255 if (MDNode *LoopID = TheLoop->getLoopID())
256 for (const MDOperand &Op : drop_begin(LoopID->operands())) {
258 if (Node->getNumOperands() == 1)
259 if (auto *S = dyn_cast<MDString>(Node->getOperand(0)))
260 if (S->getString() == StringMD)
261 return;
262 MDs.push_back(Node);
263 }
264 MDs.push_back(MDNode::get(Context, {MDString::get(Context, StringMD)}));
265 MDNode *NewLoopID = MDNode::get(Context, MDs);
266 // Set operand 0 to refer to the loop id itself.
267 NewLoopID->replaceOperandWith(0, NewLoopID);
268 TheLoop->setLoopID(NewLoopID);
269}
270
271std::optional<ElementCount>
273 std::optional<int> Width =
274 getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
275
276 if (Width) {
277 // Presence of the scalable.enable unit node means a scalable ElementCount;
278 // disable or absence both mean fixed-width.
279 bool IsScalable =
280 getBooleanLoopAttribute(TheLoop, "llvm.loop.vectorize.scalable.enable");
281 return ElementCount::get(*Width, IsScalable);
282 }
283
284 return std::nullopt;
285}
286
287std::optional<MDNode *> llvm::makeFollowupLoopID(
288 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
289 const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
290 if (!OrigLoopID) {
291 if (AlwaysNew)
292 return nullptr;
293 return std::nullopt;
294 }
295
296 assert(OrigLoopID->getOperand(0) == OrigLoopID);
297
298 bool InheritAllAttrs = !InheritOptionsExceptPrefix;
299 bool InheritSomeAttrs =
300 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
302 MDs.push_back(nullptr);
303
304 bool Changed = false;
305 if (InheritAllAttrs || InheritSomeAttrs) {
306 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands())) {
307 MDNode *Op = cast<MDNode>(Existing.get());
308
309 auto InheritThisAttribute = [InheritSomeAttrs,
310 InheritOptionsExceptPrefix](MDNode *Op) {
311 if (!InheritSomeAttrs)
312 return false;
313
314 // Skip malformatted attribute metadata nodes.
315 if (Op->getNumOperands() == 0)
316 return true;
317 Metadata *NameMD = Op->getOperand(0).get();
318 if (!isa<MDString>(NameMD))
319 return true;
320 StringRef AttrName = cast<MDString>(NameMD)->getString();
321
322 // Do not inherit excluded attributes.
323 return !AttrName.starts_with(InheritOptionsExceptPrefix);
324 };
325
326 if (InheritThisAttribute(Op))
327 MDs.push_back(Op);
328 else
329 Changed = true;
330 }
331 } else {
332 // Modified if we dropped at least one attribute.
333 Changed = OrigLoopID->getNumOperands() > 1;
334 }
335
336 bool HasAnyFollowup = false;
337 for (StringRef OptionName : FollowupOptions) {
338 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
339 if (!FollowupNode)
340 continue;
341
342 HasAnyFollowup = true;
343 for (const MDOperand &Option : drop_begin(FollowupNode->operands())) {
344 MDs.push_back(Option.get());
345 Changed = true;
346 }
347 }
348
349 // Attributes of the followup loop not specified explicity, so signal to the
350 // transformation pass to add suitable attributes.
351 if (!AlwaysNew && !HasAnyFollowup)
352 return std::nullopt;
353
354 // If no attributes were added or remove, the previous loop Id can be reused.
355 if (!AlwaysNew && !Changed)
356 return OrigLoopID;
357
358 // No attributes is equivalent to having no !llvm.loop metadata at all.
359 if (MDs.size() == 1)
360 return nullptr;
361
362 // Build the new loop ID.
363 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
364 FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
365 return FollowupLoopID;
366}
367
371
375
377 bool IsVectorBody = getBooleanLoopAttribute(L, "llvm.loop.vectorize.body");
378 bool IsEpilogue = getBooleanLoopAttribute(L, "llvm.loop.vectorize.epilogue");
379 if (IsVectorBody && IsEpilogue)
380 return "vectorized epilogue ";
381 if (IsVectorBody)
382 return "vectorized ";
383 if (IsEpilogue)
384 return "epilogue ";
385 return "";
386}
387
389 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
390 return TM_SuppressedByUser;
391
392 std::optional<int> Count =
393 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
394 if (Count)
396
397 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
398 return TM_ForcedByUser;
399
400 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
401 return TM_ForcedByUser;
402
404 return TM_Disable;
405
406 return TM_Unspecified;
407}
408
410 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
411 return TM_SuppressedByUser;
412
413 std::optional<int> Count =
414 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
415 if (Count)
417
418 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
419 return TM_ForcedByUser;
420
422 return TM_Disable;
423
424 return TM_Unspecified;
425}
426
428 if (getBooleanLoopAttribute(L, "llvm.loop.vectorize.disable"))
429 return TM_SuppressedByUser;
430
431 bool Enable = getBooleanLoopAttribute(L, "llvm.loop.vectorize.enable");
432
433 std::optional<ElementCount> VectorizeWidth =
435 std::optional<int> InterleaveCount =
436 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
437
438 // 'Forcing' vector width and interleave count to one effectively disables
439 // this tranformation.
440 if (Enable && VectorizeWidth && VectorizeWidth->isScalar() &&
441 InterleaveCount == 1)
442 return TM_SuppressedByUser;
443
444 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
445 return TM_Disable;
446
447 if (Enable)
448 return TM_ForcedByUser;
449
450 if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
451 return TM_Disable;
452
453 if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
454 return TM_Enable;
455
457 return TM_Disable;
458
459 return TM_Unspecified;
460}
461
463 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.disable"))
464 return TM_SuppressedByUser;
465
466 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
467 return TM_ForcedByUser;
468
470 return TM_Disable;
471
472 return TM_Unspecified;
473}
474
476 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
477 return TM_SuppressedByUser;
478
480 return TM_Disable;
481
482 return TM_Unspecified;
483}
484
485/// Does a BFS from a given node to all of its children inside a given loop.
486/// The returned vector of basic blocks includes the starting point.
488 DomTreeNode *N,
489 const Loop *CurLoop) {
491 auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
492 // Only include subregions in the top level loop.
493 BasicBlock *BB = DTN->getBlock();
494 if (CurLoop->contains(BB))
495 Worklist.push_back(DTN->getBlock());
496 };
497
498 AddRegionToWorklist(N);
499
500 for (size_t I = 0; I < Worklist.size(); I++) {
501 for (DomTreeNode *Child : DT->getNode(Worklist[I])->children())
502 AddRegionToWorklist(Child);
503 }
504
505 return Worklist;
506}
507
509 int LatchIdx = PN->getBasicBlockIndex(LatchBlock);
510 assert(LatchIdx != -1 && "LatchBlock is not a case in this PHINode");
511 Value *IncV = PN->getIncomingValue(LatchIdx);
512
513 for (User *U : PN->users())
514 if (U != Cond && U != IncV) return false;
515
516 for (User *U : IncV->users())
517 if (U != Cond && U != PN) return false;
518 return true;
519}
520
521
523 LoopInfo *LI, MemorySSA *MSSA) {
524 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
525 auto *Preheader = L->getLoopPreheader();
526 assert(Preheader && "Preheader should exist!");
527
528 std::unique_ptr<MemorySSAUpdater> MSSAU;
529 if (MSSA)
530 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
531
532 // Now that we know the removal is safe, remove the loop by changing the
533 // branch from the preheader to go to the single exit block.
534 //
535 // Because we're deleting a large chunk of code at once, the sequence in which
536 // we remove things is very important to avoid invalidation issues.
537
538 // Tell ScalarEvolution that the loop is deleted. Do this before
539 // deleting the loop so that ScalarEvolution can look at the loop
540 // to determine what it needs to clean up.
541 if (SE) {
542 SE->forgetLoop(L);
544 }
545
546 Instruction *OldTerm = Preheader->getTerminator();
547 assert(!OldTerm->mayHaveSideEffects() &&
548 "Preheader must end with a side-effect-free terminator");
549 assert(OldTerm->getNumSuccessors() == 1 &&
550 "Preheader must have a single successor");
551 // Connect the preheader to the exit block. Keep the old edge to the header
552 // around to perform the dominator tree update in two separate steps
553 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
554 // preheader -> header.
555 //
556 //
557 // 0. Preheader 1. Preheader 2. Preheader
558 // | | | |
559 // V | V |
560 // Header <--\ | Header <--\ | Header <--\
561 // | | | | | | | | | | |
562 // | V | | | V | | | V |
563 // | Body --/ | | Body --/ | | Body --/
564 // V V V V V
565 // Exit Exit Exit
566 //
567 // By doing this is two separate steps we can perform the dominator tree
568 // update without using the batch update API.
569 //
570 // Even when the loop is never executed, we cannot remove the edge from the
571 // source block to the exit block. Consider the case where the unexecuted loop
572 // branches back to an outer loop. If we deleted the loop and removed the edge
573 // coming to this inner loop, this will break the outer loop structure (by
574 // deleting the backedge of the outer loop). If the outer loop is indeed a
575 // non-loop, it will be deleted in a future iteration of loop deletion pass.
576 IRBuilder<> Builder(OldTerm);
577
578 auto *ExitBlock = L->getUniqueExitBlock();
579 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
580 if (ExitBlock) {
581 assert(ExitBlock && "Should have a unique exit block!");
582 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
583
584 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
585 // Remove the old branch. The conditional branch becomes a new terminator.
586 OldTerm->eraseFromParent();
587
588 // Rewrite phis in the exit block to get their inputs from the Preheader
589 // instead of the exiting block.
590 for (PHINode &P : ExitBlock->phis()) {
591 // Set the zero'th element of Phi to be from the preheader and remove all
592 // other incoming values. Given the loop has dedicated exits, all other
593 // incoming values must be from the exiting blocks.
594 int PredIndex = 0;
595 P.setIncomingBlock(PredIndex, Preheader);
596 // Removes all incoming values from all other exiting blocks (including
597 // duplicate values from an exiting block).
598 // Nuke all entries except the zero'th entry which is the preheader entry.
599 P.removeIncomingValueIf([](unsigned Idx) { return Idx != 0; },
600 /* DeletePHIIfEmpty */ false);
601
602 assert((P.getNumIncomingValues() == 1 &&
603 P.getIncomingBlock(PredIndex) == Preheader) &&
604 "Should have exactly one value and that's from the preheader!");
605 }
606
607 if (DT) {
608 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
609 if (MSSA) {
610 MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
611 *DT);
612 if (VerifyMemorySSA)
613 MSSA->verifyMemorySSA();
614 }
615 }
616
617 // Disconnect the loop body by branching directly to its exit.
618 Builder.SetInsertPoint(Preheader->getTerminator());
619 Builder.CreateBr(ExitBlock);
620 // Remove the old branch.
621 Preheader->getTerminator()->eraseFromParent();
622 } else {
623 assert((!LI || LI->hasNoExitBlocks(*L)) &&
624 "Loop should have either zero or one exit blocks.");
625
626 Builder.SetInsertPoint(OldTerm);
627 Builder.CreateUnreachable();
628 Preheader->getTerminator()->eraseFromParent();
629 }
630
631 if (DT) {
632 DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
633 if (MSSA) {
634 MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
635 *DT);
636 SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
637 L->block_end());
638 MSSAU->removeBlocks(DeadBlockSet);
639 if (VerifyMemorySSA)
640 MSSA->verifyMemorySSA();
641 }
642 }
643
644 // Use a map to unique and a vector to guarantee deterministic ordering.
646 llvm::SmallVector<DbgVariableRecord *, 4> DeadDbgVariableRecords;
647
648 // Given LCSSA form is satisfied, we should not have users of instructions
649 // within the dead loop outside of the loop. However, LCSSA doesn't take
650 // unreachable uses into account. We handle them here.
651 // We could do it after drop all references (in this case all users in the
652 // loop will be already eliminated and we have less work to do but according
653 // to API doc of User::dropAllReferences only valid operation after dropping
654 // references, is deletion. So let's substitute all usages of
655 // instruction from the loop with poison value of corresponding type first.
656 for (auto *Block : L->blocks())
657 for (Instruction &I : *Block) {
658 auto *Poison = PoisonValue::get(I.getType());
659 for (Use &U : llvm::make_early_inc_range(I.uses())) {
660 if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
661 if (L->contains(Usr->getParent()))
662 continue;
663 // If we have a DT then we can check that uses outside a loop only in
664 // unreachable block.
665 if (DT)
667 "Unexpected user in reachable block");
668 U.set(Poison);
669 }
670
671 if (ExitBlock) {
672 // For one of each variable encountered, preserve a debug record (set
673 // to Poison) and transfer it to the loop exit. This terminates any
674 // variable locations that were set during the loop.
675 for (DbgVariableRecord &DVR :
676 llvm::make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
677 DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
678 DVR.getDebugLoc().get());
679 if (!DeadDebugSet.insert(Key).second)
680 continue;
681 // Unlinks the DVR from it's container, for later insertion.
682 DVR.removeFromParent();
683 DeadDbgVariableRecords.push_back(&DVR);
684 }
685 }
686 }
687
688 if (ExitBlock) {
689 // After the loop has been deleted all the values defined and modified
690 // inside the loop are going to be unavailable. Values computed in the
691 // loop will have been deleted, automatically causing their debug uses
692 // be be replaced with undef. Loop invariant values will still be available.
693 // Move dbg.values out the loop so that earlier location ranges are still
694 // terminated and loop invariant assignments are preserved.
695 BasicBlock::iterator InsertDbgValueBefore =
696 ExitBlock->getFirstInsertionPt();
697 assert(InsertDbgValueBefore != ExitBlock->end() &&
698 "There should be a non-PHI instruction in exit block, else these "
699 "instructions will have no parent.");
700
701 // Due to the "head" bit in BasicBlock::iterator, we're going to insert
702 // each DbgVariableRecord right at the start of the block, wheras dbg.values
703 // would be repeatedly inserted before the first instruction. To replicate
704 // this behaviour, do it backwards.
705 for (DbgVariableRecord *DVR : llvm::reverse(DeadDbgVariableRecords))
706 ExitBlock->insertDbgRecordBefore(DVR, InsertDbgValueBefore);
707 }
708
709 // Remove the block from the reference counting scheme, so that we can
710 // delete it freely later.
711 for (auto *Block : L->blocks())
712 Block->dropAllReferences();
713
714 if (MSSA && VerifyMemorySSA)
715 MSSA->verifyMemorySSA();
716
717 if (LI) {
719
720 // Erase the instructions and the blocks without having to worry
721 // about ordering because we already dropped the references.
722 // Remove blocks from loopinfo before erasing them, otherwise the loopinfo
723 // cannot find the loop using block numbers.
724 for (BasicBlock *BB : Blocks) {
725 LI->removeBlock(BB);
726 BB->eraseFromParent();
727 }
728
729 // The last step is to update LoopInfo now that we've eliminated this loop.
730 // Note: LoopInfo::erase remove the given loop and relink its subloops with
731 // its parent. While removeLoop/removeChildLoop remove the given loop but
732 // not relink its subloops, which is what we want.
733 if (Loop *ParentLoop = L->getParentLoop()) {
734 Loop::iterator I = find(*ParentLoop, L);
735 assert(I != ParentLoop->end() && "Couldn't find loop");
736 ParentLoop->removeChildLoop(I);
737 } else {
738 Loop::iterator I = find(*LI, L);
739 assert(I != LI->end() && "Couldn't find loop");
740 LI->removeLoop(I);
741 }
742 LI->destroy(L);
743 }
744}
745
747 LoopInfo &LI, MemorySSA *MSSA) {
748 auto *Latch = L->getLoopLatch();
749 assert(Latch && "multiple latches not yet supported");
750 auto *Header = L->getHeader();
751 Loop *OutermostLoop = L->getOutermostLoop();
752
753 SE.forgetLoop(L);
755
756 std::unique_ptr<MemorySSAUpdater> MSSAU;
757 if (MSSA)
758 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
759
760 // Update the CFG and domtree. We chose to special case a couple of
761 // of common cases for code quality and test readability reasons.
762 [&]() -> void {
763 if (auto *BI = dyn_cast<UncondBrInst>(Latch->getTerminator())) {
764 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
765 (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
766 return;
767 }
768 if (auto *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
769 // Conditional latch/exit - note that latch can be shared by inner
770 // and outer loop so the other target doesn't need to an exit
771 if (L->isLoopExiting(Latch)) {
772 // TODO: Generalize ConstantFoldTerminator so that it can be used
773 // here without invalidating LCSSA or MemorySSA. (Tricky case for
774 // LCSSA: header is an exit block of a preceeding sibling loop w/o
775 // dedicated exits.)
776 const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0;
777 BasicBlock *ExitBB = BI->getSuccessor(ExitIdx);
778
779 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
780 Header->removePredecessor(Latch, true);
781
782 IRBuilder<> Builder(BI);
783 auto *NewBI = Builder.CreateBr(ExitBB);
784 // Transfer the metadata to the new branch instruction (minus the
785 // loop info since this is no longer a loop)
786 NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg,
787 LLVMContext::MD_annotation});
788
789 BI->eraseFromParent();
790 DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}});
791 if (MSSA)
792 MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT);
793 return;
794 }
795 }
796
797 // General case. By splitting the backedge, and then explicitly making it
798 // unreachable we gracefully handle corner cases such as switch and invoke
799 // termiantors.
800 auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
801
802 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
803 (void)changeToUnreachable(BackedgeBB->getTerminator(),
804 /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
805 }();
806
807 // Erase (and destroy) this loop instance. Handles relinking sub-loops
808 // and blocks within the loop as needed.
809 LI.erase(L);
810
811 // If the loop we broke had a parent, then changeToUnreachable might have
812 // caused a block to be removed from the parent loop (see loop_nest_lcssa
813 // test case in zero-btc.ll for an example), thus changing the parent's
814 // exit blocks. If that happened, we need to rebuild LCSSA on the outermost
815 // loop which might have a had a block removed.
816 if (OutermostLoop != L)
817 formLCSSARecursively(*OutermostLoop, DT, &LI, &SE);
818}
819
820
821/// Checks if \p L has an exiting latch branch. There may also be other
822/// exiting blocks. Returns branch instruction terminating the loop
823/// latch if above check is successful, nullptr otherwise.
825 BasicBlock *Latch = L->getLoopLatch();
826 if (!Latch)
827 return nullptr;
828
829 CondBrInst *LatchBR = dyn_cast<CondBrInst>(Latch->getTerminator());
830 if (!LatchBR || !L->isLoopExiting(Latch))
831 return nullptr;
832
833 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
834 LatchBR->getSuccessor(1) == L->getHeader()) &&
835 "At least one edge out of the latch must go to the header");
836
837 return LatchBR;
838}
839
840struct DbgLoop {
841 const Loop *L;
842 explicit DbgLoop(const Loop *L) : L(L) {}
843};
844
845#ifndef NDEBUG
847 OS << "function ";
848 D.L->getHeader()->getParent()->printAsOperand(OS, /*PrintType=*/false);
849 return OS << " " << *D.L;
850}
851#endif // NDEBUG
852
853static std::optional<unsigned> estimateLoopTripCount(Loop *L) {
854 // Currently we take the estimate exit count only from the loop latch,
855 // ignoring other exiting blocks. This can overestimate the trip count
856 // if we exit through another exit, but can never underestimate it.
857 // TODO: incorporate information from other exits
858 CondBrInst *ExitingBranch = getExpectedExitLoopLatchBranch(L);
859 if (!ExitingBranch) {
860 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed to find exiting "
861 << "latch branch of required form in " << DbgLoop(L)
862 << "\n");
863 return std::nullopt;
864 }
865
866 // To estimate the number of times the loop body was executed, we want to
867 // know the number of times the backedge was taken, vs. the number of times
868 // we exited the loop.
869 uint64_t LoopWeight, ExitWeight;
870 if (!extractBranchWeights(*ExitingBranch, LoopWeight, ExitWeight)) {
871 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed to extract branch "
872 << "weights for " << DbgLoop(L) << "\n");
873 return std::nullopt;
874 }
875
876 if (L->contains(ExitingBranch->getSuccessor(1)))
877 std::swap(LoopWeight, ExitWeight);
878
879 if (!ExitWeight) {
880 // Don't have a way to return predicated infinite
881 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed because of zero exit "
882 << "probability for " << DbgLoop(L) << "\n");
883 return std::nullopt;
884 }
885
886 // Estimated exit count is a ratio of the loop weight by the weight of the
887 // edge exiting the loop, rounded to nearest.
888 uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight);
889
890 // When ExitCount + 1 would wrap in unsigned, saturate at UINT_MAX.
891 if (ExitCount >= std::numeric_limits<unsigned>::max())
892 return std::numeric_limits<unsigned>::max();
893
894 // Estimated trip count is one plus estimated exit count.
895 uint64_t TC = ExitCount + 1;
896 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Estimated trip count of " << TC
897 << " for " << DbgLoop(L) << "\n");
898 return TC;
899}
900
901std::optional<unsigned>
903 unsigned *EstimatedLoopInvocationWeight) {
904 // If EstimatedLoopInvocationWeight, we do not support this loop if
905 // getExpectedExitLoopLatchBranch returns nullptr.
906 //
907 // FIXME: Also, this is a stop-gap solution for nested loops. It avoids
908 // mistaking LLVMLoopEstimatedTripCount metadata to be for an outer loop when
909 // it was created for an inner loop. The problem is that loop metadata is
910 // attached to the branch instruction in the loop latch block, but that can be
911 // shared by the loops. A solution is to attach loop metadata to loop headers
912 // instead, but that would be a large change to LLVM.
913 //
914 // Until that happens, we work around the problem as follows.
915 // getExpectedExitLoopLatchBranch (which also guards
916 // setLoopEstimatedTripCount) returns nullptr for a loop unless the loop has
917 // one latch and that latch has exactly two successors one of which is an exit
918 // from the loop. If the latch is shared by nested loops, then that condition
919 // might hold for the inner loop but cannot hold for the outer loop:
920 // - Because the latch is shared, it must have at least two successors: the
921 // inner loop header and the outer loop header, which is also an exit for
922 // the inner loop. That satisifies the condition for the inner loop.
923 // - To satsify the condition for the outer loop, the latch must have a third
924 // successor that is an exit for the outer loop. But that violates the
925 // condition for both loops.
926 CondBrInst *ExitingBranch = getExpectedExitLoopLatchBranch(L);
927 if (!ExitingBranch)
928 return std::nullopt;
929
930 // If requested, either compute *EstimatedLoopInvocationWeight or return
931 // nullopt if cannot.
932 //
933 // TODO: Eventually, once all passes have migrated away from setting branch
934 // weights to indicate estimated trip counts, this function will drop the
935 // EstimatedLoopInvocationWeight parameter.
936 if (EstimatedLoopInvocationWeight) {
937 uint64_t LoopWeight = 0, ExitWeight = 0; // Inits expected to be unused.
938 if (!extractBranchWeights(*ExitingBranch, LoopWeight, ExitWeight))
939 return std::nullopt;
940 if (L->contains(ExitingBranch->getSuccessor(1)))
941 std::swap(LoopWeight, ExitWeight);
942 if (!ExitWeight)
943 return std::nullopt;
944 *EstimatedLoopInvocationWeight = ExitWeight;
945 }
946
947 // Return the estimated trip count from metadata unless the metadata is
948 // missing or has no value.
949 //
950 // Some passes set llvm.loop.estimated_trip_count to 0. For example, after
951 // peeling 10 or more iterations from a loop with an estimated trip count of
952 // 10, llvm.loop.estimated_trip_count becomes 0 on the remaining loop. It
953 // indicates that, each time execution reaches the peeled iterations,
954 // execution is estimated to exit them without reaching the remaining loop's
955 // header.
956 if (std::optional<unsigned> TC =
958 LLVM_DEBUG(dbgs() << "getLoopEstimatedTripCount: "
959 << LLVMLoopEstimatedTripCount << " metadata has trip "
960 << "count of " << *TC << " for " << DbgLoop(L) << "\n");
961 return TC;
962 }
963
964 // Estimate the trip count from latch branch weights.
965 return estimateLoopTripCount(L);
966}
967
969 Loop *L, unsigned EstimatedTripCount,
970 std::optional<unsigned> EstimatedloopInvocationWeight) {
971 // If EstimatedLoopInvocationWeight, we do not support this loop if
972 // getExpectedExitLoopLatchBranch returns nullptr.
973 //
974 // FIXME: See comments in getLoopEstimatedTripCount for why this is required
975 // here regardless of EstimatedLoopInvocationWeight.
977 if (!LatchBranch)
978 return false;
979
980 // Set the metadata.
982
983 // At the moment, we currently support changing the estimated trip count in
984 // the latch branch's branch weights only. We could extend this API to
985 // manipulate estimated trip counts for any exit.
986 //
987 // TODO: Eventually, once all passes have migrated away from setting branch
988 // weights to indicate estimated trip counts, we will not set branch weights
989 // here at all.
990 if (!EstimatedloopInvocationWeight)
991 return true;
992
993 // Calculate taken and exit weights.
994 unsigned LatchExitWeight = 1;
995 unsigned BackedgeTakenWeight = 0;
996
997 if (EstimatedTripCount != 0) {
998 LatchExitWeight = *EstimatedloopInvocationWeight;
999 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
1000 }
1001
1002 // Make a swap if back edge is taken when condition is "false".
1003 if (LatchBranch->getSuccessor(0) != L->getHeader())
1004 std::swap(BackedgeTakenWeight, LatchExitWeight);
1005
1006 // Set/Update profile metadata.
1007 setBranchWeights(*LatchBranch, {BackedgeTakenWeight, LatchExitWeight},
1008 /*IsExpected=*/false);
1009
1010 return true;
1011}
1012
1015 if (!LatchBranch)
1017 bool FirstTargetIsLoop = LatchBranch->getSuccessor(0) == L->getHeader();
1018 return getBranchProbability(LatchBranch, FirstTargetIsLoop);
1019}
1020
1023 if (!LatchBranch)
1024 return false;
1025 bool FirstTargetIsLoop = LatchBranch->getSuccessor(0) == L->getHeader();
1026 setBranchProbability(LatchBranch, P, FirstTargetIsLoop);
1027 return true;
1028}
1029
1031 bool ForFirstTarget) {
1032 uint64_t Weight0, Weight1;
1033 if (!extractBranchWeights(*B, Weight0, Weight1))
1035 uint64_t Denominator = Weight0 + Weight1;
1036 if (Denominator == 0)
1038 if (!ForFirstTarget)
1039 std::swap(Weight0, Weight1);
1040 return BranchProbability::getBranchProbability(Weight0, Denominator);
1041}
1042
1044 assert(Src != Dst && "Passed in same source as destination");
1045
1046 Instruction *TI = Src->getTerminator();
1047 if (TI->getNumSuccessors() == 0)
1049
1051
1052 if (!extractBranchWeights(*TI, Weights)) {
1053 // No metadata
1055 }
1056 assert(TI->getNumSuccessors() == Weights.size() &&
1057 "Missing weights in branch_weights");
1058
1059 uint64_t Total = 0;
1060 uint32_t Numerator = 0;
1061 for (auto [i, Weight] : llvm::enumerate(Weights)) {
1062 if (TI->getSuccessor(i) == Dst)
1063 Numerator += Weight;
1064 Total += Weight;
1065 }
1066
1067 // Total of edges might be 0 if the metadata is incorrect/set by hand
1068 // or missing. In such case return here to avoid division by 0 later on.
1069 // There might also be a case where the value of Total cannot fit into
1070 // uint32_t, in such case, just bail out.
1071 if (Total == 0 || Total > std::numeric_limits<uint32_t>::max())
1073
1074 return BranchProbability(Numerator, Total);
1075}
1076
1078 bool ForFirstTarget) {
1079 BranchProbability Prob0 = P;
1080 BranchProbability Prob1 = P.getCompl();
1081 if (!ForFirstTarget)
1082 std::swap(Prob0, Prob1);
1083 setBranchWeights(*B, {Prob0.getNumerator(), Prob1.getNumerator()},
1084 /*IsExpected=*/false);
1085}
1086
1088 ScalarEvolution &SE) {
1089 Loop *OuterL = InnerLoop->getParentLoop();
1090 if (!OuterL)
1091 return true;
1092
1093 // Get the backedge taken count for the inner loop
1094 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1095 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
1096 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
1097 !InnerLoopBECountSC->getType()->isIntegerTy())
1098 return false;
1099
1100 // Get whether count is invariant to the outer loop
1102 SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
1104 return false;
1105
1106 return true;
1107}
1108
1110 switch (RK) {
1111 default:
1112 llvm_unreachable("Unexpected recurrence kind");
1114 case RecurKind::Sub:
1115 case RecurKind::Add:
1116 return Intrinsic::vector_reduce_add;
1117 case RecurKind::Mul:
1118 return Intrinsic::vector_reduce_mul;
1119 case RecurKind::And:
1120 return Intrinsic::vector_reduce_and;
1121 case RecurKind::Or:
1122 return Intrinsic::vector_reduce_or;
1123 case RecurKind::Xor:
1124 return Intrinsic::vector_reduce_xor;
1125 case RecurKind::FMulAdd:
1127 case RecurKind::FSub:
1128 case RecurKind::FAdd:
1129 return Intrinsic::vector_reduce_fadd;
1130 case RecurKind::FMul:
1131 return Intrinsic::vector_reduce_fmul;
1132 case RecurKind::SMax:
1133 return Intrinsic::vector_reduce_smax;
1134 case RecurKind::SMin:
1135 return Intrinsic::vector_reduce_smin;
1136 case RecurKind::UMax:
1137 return Intrinsic::vector_reduce_umax;
1138 case RecurKind::UMin:
1139 return Intrinsic::vector_reduce_umin;
1140 case RecurKind::FMax:
1141 case RecurKind::FMaxNum:
1142 return Intrinsic::vector_reduce_fmax;
1143 case RecurKind::FMin:
1144 case RecurKind::FMinNum:
1145 return Intrinsic::vector_reduce_fmin;
1147 return Intrinsic::vector_reduce_fmaximum;
1149 return Intrinsic::vector_reduce_fminimum;
1151 return Intrinsic::vector_reduce_fmax;
1153 return Intrinsic::vector_reduce_fmin;
1154 }
1155}
1156
1158 switch (IID) {
1159 default:
1160 llvm_unreachable("Unexpected intrinsic id");
1161 case Intrinsic::umin:
1162 return Intrinsic::vector_reduce_umin;
1163 case Intrinsic::umax:
1164 return Intrinsic::vector_reduce_umax;
1165 case Intrinsic::smin:
1166 return Intrinsic::vector_reduce_smin;
1167 case Intrinsic::smax:
1168 return Intrinsic::vector_reduce_smax;
1169 }
1170}
1171
1172// This is the inverse to getReductionForBinop
1174 switch (RdxID) {
1175 case Intrinsic::vector_reduce_fadd:
1176 return Instruction::FAdd;
1177 case Intrinsic::vector_reduce_fmul:
1178 return Instruction::FMul;
1179 case Intrinsic::vector_reduce_add:
1180 return Instruction::Add;
1181 case Intrinsic::vector_reduce_mul:
1182 return Instruction::Mul;
1183 case Intrinsic::vector_reduce_and:
1184 return Instruction::And;
1185 case Intrinsic::vector_reduce_or:
1186 return Instruction::Or;
1187 case Intrinsic::vector_reduce_xor:
1188 return Instruction::Xor;
1189 case Intrinsic::vector_reduce_smax:
1190 case Intrinsic::vector_reduce_smin:
1191 case Intrinsic::vector_reduce_umax:
1192 case Intrinsic::vector_reduce_umin:
1193 return Instruction::ICmp;
1194 case Intrinsic::vector_reduce_fmax:
1195 case Intrinsic::vector_reduce_fmin:
1196 case Intrinsic::vector_reduce_fmaximum:
1197 case Intrinsic::vector_reduce_fminimum:
1198 case Intrinsic::vector_reduce_fmaximumnum:
1199 case Intrinsic::vector_reduce_fminimumnum:
1200 return Instruction::FCmp;
1201 default:
1202 llvm_unreachable("Unexpected ID");
1203 }
1204}
1205
1206// This is the inverse to getArithmeticReductionInstruction
1208 switch (Opc) {
1209 default:
1210 break;
1211 case Instruction::Add:
1212 return Intrinsic::vector_reduce_add;
1213 case Instruction::Mul:
1214 return Intrinsic::vector_reduce_mul;
1215 case Instruction::And:
1216 return Intrinsic::vector_reduce_and;
1217 case Instruction::Or:
1218 return Intrinsic::vector_reduce_or;
1219 case Instruction::Xor:
1220 return Intrinsic::vector_reduce_xor;
1221 case Instruction::FAdd:
1222 return Intrinsic::vector_reduce_fadd;
1223 case Instruction::FMul:
1224 return Intrinsic::vector_reduce_fmul;
1225 }
1227}
1228
1230 switch (RdxID) {
1231 default:
1232 llvm_unreachable("Unknown min/max recurrence kind");
1233 case Intrinsic::vector_reduce_umin:
1234 return Intrinsic::umin;
1235 case Intrinsic::vector_reduce_umax:
1236 return Intrinsic::umax;
1237 case Intrinsic::vector_reduce_smin:
1238 return Intrinsic::smin;
1239 case Intrinsic::vector_reduce_smax:
1240 return Intrinsic::smax;
1241 case Intrinsic::vector_reduce_fmin:
1242 return Intrinsic::minnum;
1243 case Intrinsic::vector_reduce_fmax:
1244 return Intrinsic::maxnum;
1245 case Intrinsic::vector_reduce_fminimum:
1246 return Intrinsic::minimum;
1247 case Intrinsic::vector_reduce_fmaximum:
1248 return Intrinsic::maximum;
1249 case Intrinsic::vector_reduce_fminimumnum:
1250 return Intrinsic::minimumnum;
1251 case Intrinsic::vector_reduce_fmaximumnum:
1252 return Intrinsic::maximumnum;
1253 }
1254}
1255
1257 switch (RK) {
1258 default:
1259 llvm_unreachable("Unknown min/max recurrence kind");
1260 case RecurKind::UMin:
1261 return Intrinsic::umin;
1262 case RecurKind::UMax:
1263 return Intrinsic::umax;
1264 case RecurKind::SMin:
1265 return Intrinsic::smin;
1266 case RecurKind::SMax:
1267 return Intrinsic::smax;
1268 case RecurKind::FMin:
1269 case RecurKind::FMinNum:
1270 return Intrinsic::minnum;
1271 case RecurKind::FMax:
1272 case RecurKind::FMaxNum:
1273 return Intrinsic::maxnum;
1275 return Intrinsic::minimum;
1277 return Intrinsic::maximum;
1279 return Intrinsic::minimumnum;
1281 return Intrinsic::maximumnum;
1282 }
1283}
1284
1286 switch (RdxID) {
1287 case Intrinsic::vector_reduce_smax:
1288 return RecurKind::SMax;
1289 case Intrinsic::vector_reduce_smin:
1290 return RecurKind::SMin;
1291 case Intrinsic::vector_reduce_umax:
1292 return RecurKind::UMax;
1293 case Intrinsic::vector_reduce_umin:
1294 return RecurKind::UMin;
1295 case Intrinsic::vector_reduce_fmax:
1296 return RecurKind::FMax;
1297 case Intrinsic::vector_reduce_fmin:
1298 return RecurKind::FMin;
1299 case Intrinsic::vector_reduce_fmaximum:
1300 return RecurKind::FMaximum;
1301 case Intrinsic::vector_reduce_fminimum:
1302 return RecurKind::FMinimum;
1303 case Intrinsic::vector_reduce_fmaximumnum:
1305 case Intrinsic::vector_reduce_fminimumnum:
1307 default:
1308 return RecurKind::None;
1309 }
1310}
1311
1313 switch (RK) {
1314 default:
1315 llvm_unreachable("Unknown min/max recurrence kind");
1316 case RecurKind::UMin:
1317 return CmpInst::ICMP_ULT;
1318 case RecurKind::UMax:
1319 return CmpInst::ICMP_UGT;
1320 case RecurKind::SMin:
1321 return CmpInst::ICMP_SLT;
1322 case RecurKind::SMax:
1323 return CmpInst::ICMP_SGT;
1324 case RecurKind::FMin:
1325 return CmpInst::FCMP_OLT;
1326 case RecurKind::FMax:
1327 return CmpInst::FCMP_OGT;
1328 // We do not add FMinimum/FMaximum recurrence kind here since there is no
1329 // equivalent predicate which compares signed zeroes according to the
1330 // semantics of the intrinsics (llvm.minimum/maximum).
1331 }
1332}
1333
1335 Value *Right) {
1336 Type *Ty = Left->getType();
1337 if (Ty->isIntOrIntVectorTy() ||
1338 (RK == RecurKind::FMinNum || RK == RecurKind::FMaxNum ||
1342 return Builder.CreateIntrinsic(Ty, Id, {Left, Right}, nullptr,
1343 "rdx.minmax");
1344 }
1346 Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp");
1347 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1348 // This select is synthesized fresh, not lowered from an existing branch, so
1349 // it carries no real profile. Mark its weights as explicitly unknown.
1350 if (auto *SI = dyn_cast<SelectInst>(Select))
1352 return Select;
1353}
1354
1355// Helper to generate an ordered reduction.
1357 unsigned Op, RecurKind RdxKind) {
1358 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
1359
1360 // Extract and apply reduction ops in ascending order:
1361 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
1362 Value *Result = Acc;
1363 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
1364 Value *Ext =
1365 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
1366
1367 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1368 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
1369 "bin.rdx");
1370 } else {
1372 "Invalid min/max");
1373 Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
1374 }
1375 }
1376
1377 return Result;
1378}
1379
1381 unsigned RdxOpcode, Value *Acc,
1382 DominatorTree *DT, LoopInfo *LI) {
1383 auto *VTy = cast<VectorType>(Vec->getType());
1384 Type *EltTy = VTy->getElementType();
1385 Function *F = Builder.GetInsertBlock()->getParent();
1386
1387 const DataLayout &DL = F->getDataLayout();
1388 Type *IdxTy = DL.getIndexType(EltTy->getContext(), 0);
1389 unsigned MinElts = VTy->getElementCount().getKnownMinValue();
1390 Value *NumElts = Builder.CreateVScale(IdxTy);
1391 NumElts = Builder.CreateMul(NumElts, ConstantInt::get(IdxTy, MinElts));
1392
1393 BasicBlock *EntryBB = Builder.GetInsertBlock();
1394 BasicBlock *LoopBB = BasicBlock::Create(F->getContext(), "rdx.loop", F);
1395 BasicBlock *ExitBB = SplitBlock(EntryBB, Builder.GetInsertPoint(), DT, LI,
1396 nullptr, "rdx.exit");
1397
1398 EntryBB->getTerminator()->eraseFromParent();
1399 Builder.SetInsertPoint(EntryBB);
1400 Builder.CreateBr(LoopBB);
1401
1402 Builder.SetInsertPoint(LoopBB);
1403 PHINode *IV = Builder.CreatePHI(IdxTy, 2, "rdx.iv");
1404 PHINode *AccPhi = Builder.CreatePHI(EltTy, 2, "rdx.acc");
1405 IV->addIncoming(ConstantInt::get(IdxTy, 0), EntryBB);
1406 AccPhi->addIncoming(Acc, EntryBB);
1407
1408 Value *Elt = Builder.CreateExtractElement(Vec, IV);
1409 Value *Res = Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, AccPhi,
1410 Elt, "rdx.op");
1411
1412 Value *NextIV =
1413 Builder.CreateNUWAdd(IV, ConstantInt::get(IdxTy, 1), "rdx.next");
1414 IV->addIncoming(NextIV, LoopBB);
1415 AccPhi->addIncoming(Res, LoopBB);
1416
1417 Value *Done = Builder.CreateICmpEQ(NextIV, NumElts, "rdx.done");
1418 Builder.CreateCondBr(Done, ExitBB, LoopBB);
1419
1420 // SplitBlock above updated DT/LI for EntryBB -> ExitBB. Now update
1421 // for replacing that edge with EntryBB -> LoopBB -> {ExitBB, LoopBB}.
1422 if (DT)
1423 DT->applyUpdates({{DominatorTree::Insert, EntryBB, LoopBB},
1424 {DominatorTree::Insert, LoopBB, LoopBB},
1425 {DominatorTree::Insert, LoopBB, ExitBB},
1426 {DominatorTree::Delete, EntryBB, ExitBB}});
1427
1428 if (LI) {
1429 Loop *NewLoop = LI->AllocateLoop();
1430 if (Loop *ParentLoop = LI->getLoopFor(EntryBB))
1431 ParentLoop->addChildLoop(NewLoop);
1432 else
1433 LI->addTopLevelLoop(NewLoop);
1434 NewLoop->addBasicBlockToLoop(LoopBB, *LI);
1435 }
1436
1437 Builder.SetInsertPoint(ExitBB->begin());
1438 return Res;
1439}
1440
1441// Helper to generate a log2 shuffle reduction.
1443 unsigned Op,
1445 RecurKind RdxKind) {
1446 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
1447 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1448 // and vector ops, reducing the set of values being computed by half each
1449 // round.
1450 assert(isPowerOf2_32(VF) &&
1451 "Reduction emission only supported for pow2 vectors!");
1452 // Note: fast-math-flags flags are controlled by the builder configuration
1453 // and are assumed to apply to all generated arithmetic instructions. Other
1454 // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
1455 // of the builder configuration, and since they're not passed explicitly,
1456 // will never be relevant here. Note that it would be generally unsound to
1457 // propagate these from an intrinsic call to the expansion anyways as we/
1458 // change the order of operations.
1459 auto BuildShuffledOp = [&Builder, &Op,
1460 &RdxKind](SmallVectorImpl<int> &ShuffleMask,
1461 Value *&TmpVec) -> void {
1462 Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
1463 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1464 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
1465 "bin.rdx");
1466 } else {
1468 "Invalid min/max");
1469 TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
1470 }
1471 };
1472
1473 Value *TmpVec = Src;
1475 SmallVector<int, 32> ShuffleMask(VF);
1476 for (unsigned stride = 1; stride < VF; stride <<= 1) {
1477 // Initialise the mask with undef.
1478 llvm::fill(ShuffleMask, -1);
1479 for (unsigned j = 0; j < VF; j += stride << 1) {
1480 ShuffleMask[j] = j + stride;
1481 }
1482 BuildShuffledOp(ShuffleMask, TmpVec);
1483 }
1484 } else {
1485 SmallVector<int, 32> ShuffleMask(VF);
1486 for (unsigned i = VF; i != 1; i >>= 1) {
1487 // Move the upper half of the vector to the lower half.
1488 for (unsigned j = 0; j != i / 2; ++j)
1489 ShuffleMask[j] = i / 2 + j;
1490
1491 // Fill the rest of the mask with undef.
1492 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
1493 BuildShuffledOp(ShuffleMask, TmpVec);
1494 }
1495 }
1496 // The result is in the first element of the vector.
1497 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1498}
1499
1501 FastMathFlags Flags) {
1502 bool Negative = false;
1503 switch (RdxID) {
1504 default:
1505 llvm_unreachable("Expecting a reduction intrinsic");
1506 case Intrinsic::vector_reduce_add:
1507 case Intrinsic::vector_reduce_mul:
1508 case Intrinsic::vector_reduce_or:
1509 case Intrinsic::vector_reduce_xor:
1510 case Intrinsic::vector_reduce_and:
1511 case Intrinsic::vector_reduce_fadd:
1512 case Intrinsic::vector_reduce_fmul: {
1513 unsigned Opc = getArithmeticReductionInstruction(RdxID);
1514 return ConstantExpr::getBinOpIdentity(Opc, Ty, false,
1515 Flags.noSignedZeros());
1516 }
1517 case Intrinsic::vector_reduce_umax:
1518 case Intrinsic::vector_reduce_umin:
1519 case Intrinsic::vector_reduce_smin:
1520 case Intrinsic::vector_reduce_smax: {
1522 return ConstantExpr::getIntrinsicIdentity(ScalarID, Ty);
1523 }
1524 case Intrinsic::vector_reduce_fmax:
1525 case Intrinsic::vector_reduce_fmaximum:
1526 Negative = true;
1527 [[fallthrough]];
1528 case Intrinsic::vector_reduce_fmin:
1529 case Intrinsic::vector_reduce_fminimum: {
1530 bool PropagatesNaN = RdxID == Intrinsic::vector_reduce_fminimum ||
1531 RdxID == Intrinsic::vector_reduce_fmaximum;
1532 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1533 return (!Flags.noNaNs() && !PropagatesNaN)
1534 ? ConstantFP::getQNaN(Ty, Negative)
1535 : !Flags.noInfs()
1536 ? ConstantFP::getInfinity(Ty, Negative)
1537 : ConstantFP::get(Ty, APFloat::getLargest(Semantics, Negative));
1538 }
1539 }
1540}
1541
1543 assert((!(K == RecurKind::FMin || K == RecurKind::FMax) ||
1544 (FMF.noNaNs() && FMF.noSignedZeros())) &&
1545 "nnan, nsz is expected to be set for FP min/max reduction.");
1547 return getReductionIdentity(RdxID, Tp, FMF);
1548}
1549
1551 RecurKind RdxKind) {
1552 auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
1553 auto getIdentity = [&]() {
1554 return getRecurrenceIdentity(RdxKind, SrcVecEltTy,
1555 Builder.getFastMathFlags());
1556 };
1557 switch (RdxKind) {
1559 case RecurKind::Sub:
1560 case RecurKind::Add:
1561 case RecurKind::Mul:
1562 case RecurKind::And:
1563 case RecurKind::Or:
1564 case RecurKind::Xor:
1565 case RecurKind::SMax:
1566 case RecurKind::SMin:
1567 case RecurKind::UMax:
1568 case RecurKind::UMin:
1569 case RecurKind::FMax:
1570 case RecurKind::FMin:
1571 case RecurKind::FMinNum:
1572 case RecurKind::FMaxNum:
1577 return Builder.CreateUnaryIntrinsic(getReductionIntrinsicID(RdxKind), Src);
1578 case RecurKind::FMulAdd:
1580 case RecurKind::FSub:
1581 case RecurKind::FAdd:
1582 return Builder.CreateFAddReduce(getIdentity(), Src);
1583 case RecurKind::FMul:
1584 return Builder.CreateFMulReduce(getIdentity(), Src);
1585 default:
1586 llvm_unreachable("Unhandled opcode");
1587 }
1588}
1589
1591 switch (Id) {
1592 default:
1593 llvm_unreachable("Unexpected reduction intrinsic");
1594 case Intrinsic::vector_reduce_add:
1595 return Intrinsic::vp_reduce_add;
1596 case Intrinsic::vector_reduce_mul:
1597 return Intrinsic::vp_reduce_mul;
1598 case Intrinsic::vector_reduce_and:
1599 return Intrinsic::vp_reduce_and;
1600 case Intrinsic::vector_reduce_or:
1601 return Intrinsic::vp_reduce_or;
1602 case Intrinsic::vector_reduce_xor:
1603 return Intrinsic::vp_reduce_xor;
1604 case Intrinsic::vector_reduce_smax:
1605 return Intrinsic::vp_reduce_smax;
1606 case Intrinsic::vector_reduce_smin:
1607 return Intrinsic::vp_reduce_smin;
1608 case Intrinsic::vector_reduce_umax:
1609 return Intrinsic::vp_reduce_umax;
1610 case Intrinsic::vector_reduce_umin:
1611 return Intrinsic::vp_reduce_umin;
1612 case Intrinsic::vector_reduce_fmax:
1613 return Intrinsic::vp_reduce_fmax;
1614 case Intrinsic::vector_reduce_fmin:
1615 return Intrinsic::vp_reduce_fmin;
1616 case Intrinsic::vector_reduce_fmaximum:
1617 return Intrinsic::vp_reduce_fmaximum;
1618 case Intrinsic::vector_reduce_fminimum:
1619 return Intrinsic::vp_reduce_fminimum;
1620 case Intrinsic::vector_reduce_fadd:
1621 return Intrinsic::vp_reduce_fadd;
1622 case Intrinsic::vector_reduce_fmul:
1623 return Intrinsic::vp_reduce_fmul;
1624 }
1625}
1626
1628 RecurKind Kind, Value *Mask, Value *EVL) {
1631 "AnyOf and FindIV reductions are not supported.");
1634 auto *EltTy = cast<VectorType>(Src->getType())->getElementType();
1635 Value *Iden = getRecurrenceIdentity(Kind, EltTy, Builder.getFastMathFlags());
1636 Value *Ops[] = {Iden, Src, Mask, EVL};
1637 return Builder.CreateIntrinsic(EltTy, VPID, Ops);
1638}
1639
1641 Value *Src, Value *Start) {
1642 assert((Kind == RecurKind::FAdd || Kind == RecurKind::FMulAdd) &&
1643 "Unexpected reduction kind");
1644 assert(Src->getType()->isVectorTy() && "Expected a vector type");
1645 assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1646
1647 return B.CreateFAddReduce(Start, Src);
1648}
1649
1651 Value *Src, Value *Start, Value *Mask,
1652 Value *EVL) {
1653 assert((Kind == RecurKind::FAdd || Kind == RecurKind::FMulAdd) &&
1654 "Unexpected reduction kind");
1655 assert(Src->getType()->isVectorTy() && "Expected a vector type");
1656 assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1657
1660 auto *EltTy = cast<VectorType>(Src->getType())->getElementType();
1661 Value *Ops[] = {Start, Src, Mask, EVL};
1662 return Builder.CreateIntrinsic(EltTy, VPID, Ops);
1663}
1664
1666 bool IncludeWrapFlags) {
1667 auto *VecOp = dyn_cast<Instruction>(I);
1668 if (!VecOp)
1669 return;
1670 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1671 : dyn_cast<Instruction>(OpValue);
1672 if (!Intersection)
1673 return;
1674 const unsigned Opcode = Intersection->getOpcode();
1675 VecOp->copyIRFlags(Intersection, IncludeWrapFlags);
1676 for (auto *V : VL) {
1677 auto *Instr = dyn_cast<Instruction>(V);
1678 if (!Instr)
1679 continue;
1680 if (OpValue == nullptr || Opcode == Instr->getOpcode())
1681 VecOp->andIRFlags(V);
1682 }
1683}
1684
1685bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1686 ScalarEvolution &SE) {
1687 const SCEV *Zero = SE.getZero(S->getType());
1688 return SE.isAvailableAtLoopEntry(S, L) &&
1690}
1691
1693 ScalarEvolution &SE) {
1694 const SCEV *Zero = SE.getZero(S->getType());
1695 return SE.isAvailableAtLoopEntry(S, L) &&
1697}
1698
1699bool llvm::isKnownPositiveInLoop(const SCEV *S, const Loop *L,
1700 ScalarEvolution &SE) {
1701 const SCEV *Zero = SE.getZero(S->getType());
1702 return SE.isAvailableAtLoopEntry(S, L) &&
1704}
1705
1707 ScalarEvolution &SE) {
1708 const SCEV *Zero = SE.getZero(S->getType());
1709 return SE.isAvailableAtLoopEntry(S, L) &&
1711}
1712
1714 bool Signed) {
1715 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1718 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1719 return SE.isAvailableAtLoopEntry(S, L) &&
1720 SE.isLoopEntryGuardedByCond(L, Predicate, S,
1721 SE.getConstant(Min));
1722}
1723
1725 bool Signed) {
1726 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1729 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1730 return SE.isAvailableAtLoopEntry(S, L) &&
1731 SE.isLoopEntryGuardedByCond(L, Predicate, S,
1732 SE.getConstant(Max));
1733}
1734
1735//===----------------------------------------------------------------------===//
1736// rewriteLoopExitValues - Optimize IV users outside the loop.
1737// As a side effect, reduces the amount of IV processing within the loop.
1738//===----------------------------------------------------------------------===//
1739
1740static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1743 Visited.insert(I);
1744 WorkList.push_back(I);
1745 while (!WorkList.empty()) {
1746 const Instruction *Curr = WorkList.pop_back_val();
1747 // This use is outside the loop, nothing to do.
1748 if (!L->contains(Curr))
1749 continue;
1750 // Do we assume it is a "hard" use which will not be eliminated easily?
1751 if (Curr->mayHaveSideEffects())
1752 return true;
1753 // Otherwise, add all its users to worklist.
1754 for (const auto *U : Curr->users()) {
1755 auto *UI = cast<Instruction>(U);
1756 if (Visited.insert(UI).second)
1757 WorkList.push_back(UI);
1758 }
1759 }
1760 return false;
1761}
1762
1763// Exit values of an instruction's loop-variant operands, indexed by operand
1764// number.
1766
1767// Collect information about PHI nodes which can be transformed in
1768// rewriteLoopExitValues.
1770 PHINode *PN; // For which PHI node is this replacement?
1771 unsigned Ith; // For which incoming value?
1772 SCEVUse ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1774 Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1775 bool HighCost; // Is this expansion a high-cost?
1776
1777 RewritePhi(PHINode *P, unsigned I, SCEVUse Val, Instruction *ExpansionPt,
1778 bool H, OperandExitValueList OpExitValues = {})
1779 : PN(P), Ith(I), ExpansionSCEV(Val),
1780 OperandExitValues(std::move(OpExitValues)), ExpansionPoint(ExpansionPt),
1781 HighCost(H) {}
1782};
1783
1784// Check whether it is possible to delete the loop after rewriting exit
1785// value. If it is possible, ignore ReplaceExitValue and do rewriting
1786// aggressively.
1787static bool canLoopBeDeleted(Loop *L,
1788 SmallVector<RewritePhi, 8> &RewritePhiSet) {
1789 BasicBlock *Preheader = L->getLoopPreheader();
1790 // If there is no preheader, the loop will not be deleted.
1791 if (!Preheader)
1792 return false;
1793
1794 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1795 // We obviate multiple ExitingBlocks case for simplicity.
1796 // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1797 // after exit value rewriting, we can enhance the logic here.
1798 SmallVector<BasicBlock *, 4> ExitingBlocks;
1799 L->getExitingBlocks(ExitingBlocks);
1801 L->getUniqueExitBlocks(ExitBlocks);
1802 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1803 return false;
1804
1805 BasicBlock *ExitBlock = ExitBlocks[0];
1806 BasicBlock::iterator BI = ExitBlock->begin();
1807 while (PHINode *P = dyn_cast<PHINode>(BI)) {
1808 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
1809
1810 // If the Incoming value of P is found in RewritePhiSet, we know it
1811 // could be rewritten to use a loop invariant value in transformation
1812 // phase later. Skip it in the loop invariant check below.
1813 bool found = false;
1814 for (const RewritePhi &Phi : RewritePhiSet) {
1815 unsigned i = Phi.Ith;
1816 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1817 found = true;
1818 break;
1819 }
1820 }
1821
1822 Instruction *I;
1823 if (!found && (I = dyn_cast<Instruction>(Incoming)))
1824 if (!L->hasLoopInvariantOperands(I))
1825 return false;
1826
1827 ++BI;
1828 }
1829
1830 for (auto *BB : L->blocks())
1831 if (llvm::any_of(*BB, [](Instruction &I) {
1832 return I.mayHaveSideEffects();
1833 }))
1834 return false;
1835
1836 return true;
1837}
1838
1839/// Checks if it is safe to call InductionDescriptor::isInductionPHI for \p Phi,
1840/// and returns true if this Phi is an induction phi in the loop. When
1841/// isInductionPHI returns true, \p ID will be also be set by isInductionPHI.
1842static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE,
1843 InductionDescriptor &ID) {
1844 if (!Phi)
1845 return false;
1846 if (!L->getLoopPreheader())
1847 return false;
1848 if (Phi->getParent() != L->getHeader())
1849 return false;
1850 return InductionDescriptor::isInductionPHI(Phi, L, SE, ID);
1851}
1852
1854 BasicBlock *ExitingBlock,
1855 ScalarEvolution *SE,
1856 SCEVExpander &Rewriter,
1857 OperandExitValueList &ExitValues) {
1858 BasicBlock *Preheader = L->getLoopPreheader();
1859 if (!Preheader || !isa<ICmpInst>(Inst))
1860 return false;
1861
1862 for (const auto &[Idx, Op] : enumerate(Inst->operands())) {
1863 // Operands defined outside the loop already dominate the preheader.
1864 if (L->isLoopInvariant(Op))
1865 continue;
1866 if (!SE->isSCEVable(Op->getType()))
1867 return false;
1868 SCEVUse ExitValue = SE->getSCEVAtExit(Op, L, ExitingBlock);
1869 if (isa<SCEVCouldNotCompute>(ExitValue) ||
1870 !SE->isLoopInvariant(ExitValue, L) ||
1871 !Rewriter.isSafeToExpandAt(ExitValue, Preheader->getTerminator()))
1872 return false;
1873 ExitValues.emplace_back(Idx, ExitValue);
1874 }
1875 return !ExitValues.empty();
1876}
1877
1879 ScalarEvolution *SE,
1880 const TargetTransformInfo *TTI,
1881 SCEVExpander &Rewriter, DominatorTree *DT,
1882 ReplaceExitVal ReplaceExitValue,
1884 // Check a pre-condition.
1885 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1886 "Caller did not preserve LCSSA!");
1887
1888 SmallVector<BasicBlock*, 8> ExitBlocks;
1889 L->getUniqueExitBlocks(ExitBlocks);
1890
1891 SmallVector<RewritePhi, 8> RewritePhiSet;
1892 // Find all values that are computed inside the loop, but used outside of it.
1893 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
1894 // the exit blocks of the loop to find them.
1895 for (BasicBlock *ExitBB : ExitBlocks) {
1896 // If there are no PHI nodes in this exit block, then no values defined
1897 // inside the loop are used on this path, skip it.
1898 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
1899 if (!PN) continue;
1900
1901 unsigned NumPreds = PN->getNumIncomingValues();
1902
1903 // Iterate over all of the PHI nodes.
1904 BasicBlock::iterator BBI = ExitBB->begin();
1905 while ((PN = dyn_cast<PHINode>(BBI++))) {
1906 if (PN->use_empty())
1907 continue; // dead use, don't replace it
1908
1909 if (!SE->isSCEVable(PN->getType()))
1910 continue;
1911
1912 // Iterate over all of the values in all the PHI nodes.
1913 for (unsigned i = 0; i != NumPreds; ++i) {
1914 // If the value being merged in is not integer or is not defined
1915 // in the loop, skip it.
1916 Value *InVal = PN->getIncomingValue(i);
1917 if (!isa<Instruction>(InVal))
1918 continue;
1919
1920 // If this pred is for a subloop, not L itself, skip it.
1921 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
1922 continue; // The Block is in a subloop, skip it.
1923
1924 // Check that InVal is defined in the loop.
1925 Instruction *Inst = cast<Instruction>(InVal);
1926 if (!L->contains(Inst))
1927 continue;
1928
1929 // Find exit values which are induction variables in the loop, and are
1930 // unused in the loop, with the only use being the exit block PhiNode,
1931 // and the induction variable update binary operator.
1932 // The exit value can be replaced with the final value when it is cheap
1933 // to do so.
1934 if (ReplaceExitValue == UnusedIndVarInLoop) {
1936 PHINode *IndPhi = dyn_cast<PHINode>(Inst);
1937 if (IndPhi) {
1938 if (!checkIsIndPhi(IndPhi, L, SE, ID))
1939 continue;
1940 // This is an induction PHI. Check that the only users are PHI
1941 // nodes, and induction variable update binary operators.
1942 if (llvm::any_of(Inst->users(), [&](User *U) {
1943 if (!isa<PHINode>(U) && !isa<BinaryOperator>(U))
1944 return true;
1945 BinaryOperator *B = dyn_cast<BinaryOperator>(U);
1946 if (B && B != ID.getInductionBinOp())
1947 return true;
1948 return false;
1949 }))
1950 continue;
1951 } else {
1952 // If it is not an induction phi, it must be an induction update
1953 // binary operator with an induction phi user.
1955 if (!B)
1956 continue;
1957 if (llvm::any_of(Inst->users(), [&](User *U) {
1958 PHINode *Phi = dyn_cast<PHINode>(U);
1959 if (Phi != PN && !checkIsIndPhi(Phi, L, SE, ID))
1960 return true;
1961 return false;
1962 }))
1963 continue;
1964 if (B != ID.getInductionBinOp())
1965 continue;
1966 }
1967 }
1968
1969 // Okay, this instruction has a user outside of the current loop
1970 // and varies predictably *inside* the loop. Evaluate the value it
1971 // contains when the loop exits, if possible. We prefer to start with
1972 // expressions which are true for all exits (so as to maximize
1973 // expression reuse by the SCEVExpander), but resort to per-exit
1974 // evaluation if that fails.
1975 BasicBlock *ExitingBlock = PN->getIncomingBlock(i);
1976 SCEVUse ExitValue = SE->getSCEVAtExit(Inst, L, ExitingBlock);
1977 OperandExitValueList OperandExitValues;
1978 if (!SE->isLoopInvariant(ExitValue, L) ||
1979 !Rewriter.isSafeToExpandAt(
1980 ExitValue, L->getLoopPreheader()->getTerminator())) {
1981 if (!collectOperandExitValues(Inst, L, ExitingBlock, SE, Rewriter,
1982 OperandExitValues))
1983 continue;
1984 }
1985
1986 // Computing the value outside of the loop brings no benefit if it is
1987 // definitely used inside the loop in a way which can not be optimized
1988 // away. Avoid doing so unless we know we have a value which computes
1989 // the ExitValue already. TODO: This should be merged into SCEV
1990 // expander to leverage its knowledge of existing expressions.
1991 if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
1992 !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
1993 continue;
1994
1995 // Check if expansions of this SCEV would count as being high cost.
1996 bool HighCost =
1997 !OperandExitValues.empty() ||
1998 Rewriter.isHighCostExpansion(ExitValue.getPointer(), L,
2000
2001 // Note that we must not perform expansions until after
2002 // we query *all* the costs, because if we perform temporary expansion
2003 // inbetween, one that we might not intend to keep, said expansion
2004 // *may* affect cost calculation of the next SCEV's we'll query,
2005 // and next SCEV may errneously get smaller cost.
2006
2007 // Collect all the candidate PHINodes to be rewritten.
2008 Instruction *InsertPt = L->getLoopPreheader()->getTerminator();
2009 RewritePhiSet.emplace_back(PN, i, ExitValue, InsertPt, HighCost,
2010 std::move(OperandExitValues));
2011 }
2012 }
2013 }
2014
2015 // TODO: evaluate whether it is beneficial to change how we calculate
2016 // high-cost: if we have SCEV 'A' which we know we will expand, should we
2017 // calculate the cost of other SCEV's after expanding SCEV 'A', thus
2018 // potentially giving cost bonus to those other SCEV's?
2019
2020 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
2021 int NumReplaced = 0;
2022
2023 // Transformation.
2024 for (const RewritePhi &Phi : RewritePhiSet) {
2025 PHINode *PN = Phi.PN;
2026
2027 // Only do the rewrite when the ExitValue can be expanded cheaply.
2028 // If LoopCanBeDel is true, rewrite exit value aggressively.
2029 if ((ReplaceExitValue == OnlyCheapRepl ||
2030 ReplaceExitValue == UnusedIndVarInLoop) &&
2031 !LoopCanBeDel && Phi.HighCost)
2032 continue;
2033
2034 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
2035 Value *ExitVal;
2036 if (Phi.OperandExitValues.empty()) {
2037 ExitVal = Rewriter.expandCodeFor(Phi.ExpansionSCEV, Phi.PN->getType(),
2038 Phi.ExpansionPoint);
2039 } else {
2040 Instruction *Clone = Inst->clone();
2041 Clone->setName(Inst->getName() + ".exit");
2042 for (auto [Idx, ExitSCEV] : Phi.OperandExitValues)
2043 Clone->setOperand(Idx, Rewriter.expandCodeFor(
2044 ExitSCEV, Inst->getOperand(Idx)->getType(),
2045 Phi.ExpansionPoint));
2046 Clone->insertBefore(Phi.ExpansionPoint->getIterator());
2047 ExitVal = Clone;
2048 }
2049
2050 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
2051 << '\n'
2052 << " LoopVal = " << *Inst << "\n");
2053
2054#ifndef NDEBUG
2055 // If we reuse an instruction from a loop which is neither L nor one of
2056 // its containing loops, we end up breaking LCSSA form for this loop by
2057 // creating a new use of its instruction.
2058 if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
2059 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
2060 if (EVL != L)
2061 assert(EVL->contains(L) && "LCSSA breach detected!");
2062#endif
2063
2064 NumReplaced++;
2065 PN->setIncomingValue(Phi.Ith, ExitVal);
2066 // It's necessary to tell ScalarEvolution about this explicitly so that
2067 // it can walk the def-use list and forget all SCEVs, as it may not be
2068 // watching the PHI itself. Once the new exit value is in place, there
2069 // may not be a def-use connection between the loop and every instruction
2070 // which got a SCEVAddRecExpr for that loop.
2071 SE->forgetValue(PN);
2072
2073 // If this instruction is dead now, delete it. Don't do it now to avoid
2074 // invalidating iterators.
2076 DeadInsts.push_back(Inst);
2077
2078 // Replace PN with ExitVal if that is legal and does not break LCSSA.
2079 if (PN->getNumIncomingValues() == 1 &&
2080 LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
2081 PN->replaceAllUsesWith(ExitVal);
2082 PN->eraseFromParent();
2083 }
2084 }
2085
2086 // The insertion point instruction may have been deleted; clear it out
2087 // so that the rewriter doesn't trip over it later.
2088 Rewriter.clearInsertPoint();
2089 return NumReplaced;
2090}
2091
2092/// Utility that implements appending of loops onto a worklist.
2093/// Loops are added in preorder (analogous for reverse postorder for trees),
2094/// and the worklist is processed LIFO.
2095template <typename RangeT>
2097 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
2098 // We use an internal worklist to build up the preorder traversal without
2099 // recursion.
2100 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
2101
2102 // We walk the initial sequence of loops in reverse because we generally want
2103 // to visit defs before uses and the worklist is LIFO.
2104 for (Loop *RootL : Loops) {
2105 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
2106 assert(PreOrderWorklist.empty() &&
2107 "Must start with an empty preorder walk worklist.");
2108 PreOrderWorklist.push_back(RootL);
2109 do {
2110 Loop *L = PreOrderWorklist.pop_back_val();
2111 PreOrderWorklist.append(L->begin(), L->end());
2112 PreOrderLoops.push_back(L);
2113 } while (!PreOrderWorklist.empty());
2114
2115 Worklist.insert(std::move(PreOrderLoops));
2116 PreOrderLoops.clear();
2117 }
2118}
2119
2120template <typename RangeT>
2124}
2125
2126template LLVM_EXPORT_TEMPLATE void
2129
2130template LLVM_EXPORT_TEMPLATE void
2133
2138
2140 LoopInfo *LI, LPPassManager *LPM) {
2141 Loop &New = *LI->AllocateLoop();
2142 if (PL)
2143 PL->addChildLoop(&New);
2144 else
2145 LI->addTopLevelLoop(&New);
2146
2147 if (LPM)
2148 LPM->addLoop(New);
2149
2150 // Add all of the blocks in L to the new loop.
2151 for (BasicBlock *BB : L->blocks())
2152 if (LI->getLoopFor(BB) == L)
2153 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI);
2154
2155 // Add all of the subloops to the new loop.
2156 for (Loop *I : *L)
2157 cloneLoop(I, &New, VM, LI, LPM);
2158
2159 return &New;
2160}
2161
2162/// IR Values for the lower and upper bounds of a pointer evolution. We
2163/// need to use value-handles because SCEV expansion can invalidate previously
2164/// expanded values. Thus expansion of a pointer can invalidate the bounds for
2165/// a previous one.
2171
2174 const Loop *TheLoop, ScalarEvolution &SE,
2175 bool HoistRuntimeChecks) {
2176 const SCEV *Low = CG->Low, *High = CG->High, *Stride = nullptr;
2177
2178 // If the Low and High values are themselves loop-variant, then we may want
2179 // to expand the range to include those covered by the outer loop as well.
2180 // There is a trade-off here with the advantage being that creating checks
2181 // using the expanded range permits the runtime memory checks to be hoisted
2182 // out of the outer loop. This reduces the cost of entering the inner loop,
2183 // which can be significant for low trip counts. The disadvantage is that
2184 // there is a chance we may now never enter the vectorized inner loop,
2185 // whereas using a restricted range check could have allowed us to enter at
2186 // least once. This is why the behaviour is not currently the default and is
2187 // controlled by the parameter 'HoistRuntimeChecks'.
2188 if (HoistRuntimeChecks && TheLoop->getParentLoop() &&
2190 auto *HighAR = cast<SCEVAddRecExpr>(High);
2191 auto *LowAR = cast<SCEVAddRecExpr>(Low);
2192 const Loop *OuterLoop = TheLoop->getParentLoop();
2193 const SCEV *Recur = LowAR->getStepRecurrence(SE);
2194 if (Recur == HighAR->getStepRecurrence(SE) &&
2195 HighAR->getLoop() == OuterLoop && LowAR->getLoop() == OuterLoop) {
2196 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2197 const SCEV *OuterExitCount = SE.getExitCount(OuterLoop, OuterLoopLatch);
2198 if (!isa<SCEVCouldNotCompute>(OuterExitCount) &&
2199 OuterExitCount->getType()->isIntegerTy()) {
2200 const SCEV *NewHigh =
2201 cast<SCEVAddRecExpr>(High)->evaluateAtIteration(OuterExitCount, SE);
2202 if (!isa<SCEVCouldNotCompute>(NewHigh)) {
2203 LLVM_DEBUG(dbgs() << "LAA: Expanded RT check for range to include "
2204 "outer loop in order to permit hoisting\n");
2205 High = NewHigh;
2206 Low = cast<SCEVAddRecExpr>(Low)->getStart();
2207 // If there is a possibility that the stride is negative then we have
2208 // to generate extra checks to ensure the stride is positive.
2209 if (!SE.isKnownNonNegative(
2210 SE.applyLoopGuards(Recur, HighAR->getLoop()))) {
2211 Stride = Recur;
2212 LLVM_DEBUG(dbgs() << "LAA: ... but need to check stride is "
2213 "positive: "
2214 << *Stride << '\n');
2215 }
2216 }
2217 }
2218 }
2219 }
2220 return {Low, High, Stride};
2221}
2222
2223/// Expand code for the lower and upper bound of the pointer group \p CG
2224/// in \p TheLoop. \return the values for the bounds.
2226 Loop *TheLoop, Instruction *Loc,
2227 SCEVExpander &Exp, bool HoistRuntimeChecks) {
2228 LLVMContext &Ctx = Loc->getContext();
2229 Type *PtrArithTy = PointerType::get(Ctx, CG->AddressSpace);
2230
2231 Value *Start = nullptr, *End = nullptr;
2232 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
2233 auto [Low, High, Stride] =
2234 getRuntimeCheckBounds(CG, TheLoop, *Exp.getSE(), HoistRuntimeChecks);
2235
2236 Start = Exp.expandCodeFor(Low, PtrArithTy, Loc);
2237 End = Exp.expandCodeFor(High, PtrArithTy, Loc);
2238 if (CG->NeedsFreeze) {
2239 IRBuilder<> Builder(Loc);
2240 Start = Builder.CreateFreeze(Start, Start->getName() + ".fr");
2241 End = Builder.CreateFreeze(End, End->getName() + ".fr");
2242 }
2243 Value *StrideVal =
2244 Stride ? Exp.expandCodeFor(Stride, Stride->getType(), Loc) : nullptr;
2245 LLVM_DEBUG(dbgs() << "Start: " << *Low << " End: " << *High << "\n");
2246 return {Start, End, StrideVal};
2247}
2248
2249/// Turns a collection of checks into a collection of expanded upper and
2250/// lower bounds for both pointers in the check.
2255
2256 // Here we're relying on the SCEV Expander's cache to only emit code for the
2257 // same bounds once.
2258 transform(PointerChecks, std::back_inserter(ChecksWithBounds),
2259 [&](const RuntimePointerCheck &Check) {
2260 PointerBounds First = expandBounds(Check.first, L, Loc, Exp,
2262 Second = expandBounds(Check.second, L, Loc, Exp,
2264 return std::make_pair(First, Second);
2265 });
2266
2267 return ChecksWithBounds;
2268}
2269
2271 Instruction *Loc, Loop *TheLoop,
2272 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
2273 SCEVExpander &Exp, bool HoistRuntimeChecks) {
2274 // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
2275 // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible
2276 auto ExpandedChecks =
2277 expandBounds(PointerChecks, TheLoop, Loc, Exp, HoistRuntimeChecks);
2278
2279 IRBuilder ChkBuilder(Loc->getIterator(),
2280 InstSimplifyFolder(Loc->getDataLayout()));
2281 // Our instructions might fold to a constant.
2282 Value *MemoryRuntimeCheck = nullptr;
2283 SmallPtrSet<Value *, 4> CheckedStrides;
2284
2285 for (const auto &[A, B] : ExpandedChecks) {
2286 // Check if two pointers (A and B) conflict where conflict is computed as:
2287 // start(A) <= end(B) && start(B) <= end(A)
2288
2289 assert((A.Start->getType()->getPointerAddressSpace() ==
2290 B.End->getType()->getPointerAddressSpace()) &&
2291 (B.Start->getType()->getPointerAddressSpace() ==
2292 A.End->getType()->getPointerAddressSpace()) &&
2293 "Trying to bounds check pointers with different address spaces");
2294
2295 // [A|B].Start points to the first accessed byte under base [A|B].
2296 // [A|B].End points to the last accessed byte, plus one.
2297 // There is no conflict when the intervals are disjoint:
2298 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
2299 //
2300 // bound0 = (B.Start < A.End)
2301 // bound1 = (A.Start < B.End)
2302 // IsConflict = bound0 & bound1
2303 Value *Cmp0 = ChkBuilder.CreateICmpULT(A.Start, B.End, "bound0");
2304 Value *Cmp1 = ChkBuilder.CreateICmpULT(B.Start, A.End, "bound1");
2305 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2306 if (A.StrideToCheck && CheckedStrides.insert(A.StrideToCheck).second) {
2307 Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
2308 A.StrideToCheck, ConstantInt::get(A.StrideToCheck->getType(), 0),
2309 "stride.check");
2310 IsConflict = ChkBuilder.CreateOr(IsConflict, IsNegativeStride);
2311 }
2312 if (B.StrideToCheck && CheckedStrides.insert(B.StrideToCheck).second) {
2313 Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
2314 B.StrideToCheck, ConstantInt::get(B.StrideToCheck->getType(), 0),
2315 "stride.check");
2316 IsConflict = ChkBuilder.CreateOr(IsConflict, IsNegativeStride);
2317 }
2318 if (MemoryRuntimeCheck) {
2319 IsConflict =
2320 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
2321 }
2322 MemoryRuntimeCheck = IsConflict;
2323 }
2324
2325 Exp.eraseDeadInstructions(MemoryRuntimeCheck);
2326 return MemoryRuntimeCheck;
2327}
2328
2331 SCEVExpander &Expander, ElementCount VF,
2332 unsigned IC) {
2333
2334 IRBuilder ChkBuilder(Loc->getIterator(),
2335 InstSimplifyFolder(Loc->getDataLayout()));
2336 // Our instructions might fold to a constant.
2337 Value *MemoryRuntimeCheck = nullptr;
2338
2339 auto &SE = *Expander.getSE();
2340 // Map to keep track of created compares, The key is the pair of operands for
2341 // the compare, to allow detecting and re-using redundant compares.
2343 for (const auto &[SrcStart, SinkStart, AccessSize, NeedsFreeze] : Checks) {
2344 assert(IC * AccessSize > 0 &&
2345 "Threshold must be non-zero to use diff-check");
2346 Type *Ty = SinkStart->getType();
2347 const SCEV *TotalAccessSize = SE.getElementCount(Ty, VF * IC * AccessSize);
2348 Value *ThresholdMinusOne = Expander.expandCodeFor(
2349 SE.getMinusSCEV(TotalAccessSize, SE.getConstant(Ty, 1)), Ty, Loc);
2350 Value *Diff =
2351 Expander.expandCodeFor(SE.getMinusSCEV(SinkStart, SrcStart), Ty, Loc);
2352
2353 // Check if the same compare has already been created earlier. In that case,
2354 // there is no need to check it again.
2355 Value *IsConflict = SeenCompares.lookup({Diff, ThresholdMinusOne});
2356 if (IsConflict)
2357 continue;
2358
2359 // Use (Diff - 1) <u (Threshold - 1), equivalent to 0 < Diff <u Threshold,
2360 // to exclude Diff == 0 (equal pointers are safe).
2361 IsConflict = ChkBuilder.CreateICmpULT(
2362 ChkBuilder.CreateSub(Diff, ConstantInt::get(Ty, 1)), ThresholdMinusOne,
2363 "diff.check");
2364 SeenCompares.insert({{Diff, ThresholdMinusOne}, IsConflict});
2365 if (NeedsFreeze)
2366 IsConflict =
2367 ChkBuilder.CreateFreeze(IsConflict, IsConflict->getName() + ".fr");
2368 if (MemoryRuntimeCheck) {
2369 IsConflict =
2370 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
2371 }
2372 MemoryRuntimeCheck = IsConflict;
2373 }
2374
2375 Expander.eraseDeadInstructions(MemoryRuntimeCheck);
2376 return MemoryRuntimeCheck;
2377}
2378
2379std::optional<IVConditionInfo>
2380llvm::hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold,
2381 const MemorySSA &MSSA, AAResults &AA) {
2382 auto *TI = dyn_cast<CondBrInst>(L.getHeader()->getTerminator());
2383 if (!TI)
2384 return {};
2385
2386 auto *CondI = dyn_cast<Instruction>(TI->getCondition());
2387 // The case with the condition outside the loop should already be handled
2388 // earlier.
2389 // Allow CmpInst and TruncInsts as they may be users of load instructions
2390 // and have potential for partial unswitching
2391 if (!CondI || !isa<CmpInst, TruncInst>(CondI) || !L.contains(CondI))
2392 return {};
2393
2394 SmallVector<Instruction *> InstToDuplicate;
2395 InstToDuplicate.push_back(CondI);
2396
2397 SmallVector<Value *, 4> WorkList;
2398 WorkList.append(CondI->op_begin(), CondI->op_end());
2399
2400 SmallVector<MemoryAccess *, 4> AccessesToCheck;
2401 SmallVector<MemoryLocation, 4> AccessedLocs;
2402 while (!WorkList.empty()) {
2404 if (!I || !L.contains(I))
2405 continue;
2406
2407 // TODO: support additional instructions.
2409 return {};
2410
2411 // Do not duplicate volatile and atomic loads.
2412 if (auto *LI = dyn_cast<LoadInst>(I))
2413 if (LI->isVolatile() || LI->isAtomic())
2414 return {};
2415
2416 InstToDuplicate.push_back(I);
2417 if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
2418 if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
2419 // Queue the defining access to check for alias checks.
2420 AccessesToCheck.push_back(MemUse->getDefiningAccess());
2421 AccessedLocs.push_back(MemoryLocation::get(I));
2422 } else {
2423 // MemoryDefs may clobber the location or may be atomic memory
2424 // operations. Bail out.
2425 return {};
2426 }
2427 }
2428 WorkList.append(I->op_begin(), I->op_end());
2429 }
2430
2431 if (InstToDuplicate.empty())
2432 return {};
2433
2434 SmallVector<BasicBlock *, 4> ExitingBlocks;
2435 L.getExitingBlocks(ExitingBlocks);
2436 auto HasNoClobbersOnPath =
2437 [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
2438 MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
2439 SmallVector<MemoryAccess *, 4> AccessesToCheck)
2440 -> std::optional<IVConditionInfo> {
2441 IVConditionInfo Info;
2442 // First, collect all blocks in the loop that are on a patch from Succ
2443 // to the header.
2445 WorkList.push_back(Succ);
2446 WorkList.push_back(Header);
2448 Seen.insert(Header);
2449 Info.PathIsNoop &=
2450 all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); });
2451
2452 while (!WorkList.empty()) {
2453 BasicBlock *Current = WorkList.pop_back_val();
2454 if (!L.contains(Current))
2455 continue;
2456 const auto &SeenIns = Seen.insert(Current);
2457 if (!SeenIns.second)
2458 continue;
2459
2460 Info.PathIsNoop &= all_of(
2461 *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); });
2462 WorkList.append(succ_begin(Current), succ_end(Current));
2463 }
2464
2465 // Require at least 2 blocks on a path through the loop. This skips
2466 // paths that directly exit the loop.
2467 if (Seen.size() < 2)
2468 return {};
2469
2470 // Next, check if there are any MemoryDefs that are on the path through
2471 // the loop (in the Seen set) and they may-alias any of the locations in
2472 // AccessedLocs. If that is the case, they may modify the condition and
2473 // partial unswitching is not possible.
2474 SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
2475 while (!AccessesToCheck.empty()) {
2476 MemoryAccess *Current = AccessesToCheck.pop_back_val();
2477 auto SeenI = SeenAccesses.insert(Current);
2478 if (!SeenI.second || !Seen.contains(Current->getBlock()))
2479 continue;
2480
2481 // Bail out if exceeded the threshold.
2482 if (SeenAccesses.size() >= MSSAThreshold)
2483 return {};
2484
2485 // MemoryUse are read-only accesses.
2486 if (isa<MemoryUse>(Current))
2487 continue;
2488
2489 // For a MemoryDef, check if is aliases any of the location feeding
2490 // the original condition.
2491 if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
2492 if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) {
2493 return isModSet(
2494 AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc));
2495 }))
2496 return {};
2497 }
2498
2499 for (Use &U : Current->uses())
2500 AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
2501 }
2502
2503 // We could also allow loops with known trip counts without mustprogress,
2504 // but ScalarEvolution may not be available.
2505 Info.PathIsNoop &= isMustProgress(&L);
2506
2507 // If the path is considered a no-op so far, check if it reaches a
2508 // single exit block without any phis. This ensures no values from the
2509 // loop are used outside of the loop.
2510 if (Info.PathIsNoop) {
2511 for (auto *Exiting : ExitingBlocks) {
2512 if (!Seen.contains(Exiting))
2513 continue;
2514 for (auto *Succ : successors(Exiting)) {
2515 if (L.contains(Succ))
2516 continue;
2517
2518 Info.PathIsNoop &= Succ->phis().empty() &&
2519 (!Info.ExitForPath || Info.ExitForPath == Succ);
2520 if (!Info.PathIsNoop)
2521 break;
2522 assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
2523 "cannot have multiple exit blocks");
2524 Info.ExitForPath = Succ;
2525 }
2526 }
2527 }
2528 if (!Info.ExitForPath)
2529 Info.PathIsNoop = false;
2530
2531 Info.InstToDuplicate = std::move(InstToDuplicate);
2532 return Info;
2533 };
2534
2535 // If we branch to the same successor, partial unswitching will not be
2536 // beneficial.
2537 if (TI->getSuccessor(0) == TI->getSuccessor(1))
2538 return {};
2539
2540 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(),
2541 AccessesToCheck)) {
2542 Info->KnownValue = ConstantInt::getTrue(TI->getContext());
2543 return Info;
2544 }
2545 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(),
2546 AccessesToCheck)) {
2547 Info->KnownValue = ConstantInt::getFalse(TI->getContext());
2548 return Info;
2549 }
2550
2551 return {};
2552}
2553
2555 DenseMap<Value *, const SCEVAddRecExpr *> &CompressedPtrs, const Loop &L,
2557 assert(L.isInnermost() && "Expected innermost loop!");
2558
2559 const DataLayout &DL = SE.getDataLayout();
2560 const SCEV *ApproximatePhiSCEV = CondID.getUnconditionalAddRec(SE, L);
2561 ValueToSCEVMapTy PhiMap{{CondID.getHeaderPHI(), ApproximatePhiSCEV}};
2562
2563 auto GetCompressedPtrSCEV = [&](Value *Ptr,
2564 Type *AccessTy) -> const SCEVAddRecExpr * {
2565 using namespace SCEVPatternMatch;
2566 // TODO: Take into account the non-wrap flags of the MD when rewriting the
2567 // SCEV expressions for pointers. This should allow folding away zext/sext
2568 // operations.
2569 const SCEV *PtrSCEV =
2571
2572 // Check the pointer is described by an add recurrence with a step matching
2573 // the access type size.
2574 unsigned AccessSize = DL.getTypeAllocSize(AccessTy).getFixedValue();
2575 if (!match(PtrSCEV,
2576 m_scev_AffineAddRec(m_SCEV(), m_scev_SpecificInt(AccessSize),
2577 m_SpecificLoop(&L))))
2578 return nullptr;
2579
2580 return cast<SCEVAddRecExpr>(PtrSCEV);
2581 };
2582
2584 SmallVector<Use *> Worklist(
2585 make_pointer_range(CondID.getHeaderPHI()->uses()));
2586 while (!Worklist.empty()) {
2587 Use *U = Worklist.pop_back_val();
2588 if (!Seen.insert(U).second)
2589 continue;
2590
2591 auto *UserI = cast<Instruction>(U->getUser());
2592 // Disallow out of loop users. TODO: This could be relaxed if the loop
2593 // vectorizer could handle liveout users of the conditional induction.
2594 if (!L.contains(UserI))
2595 return false;
2596
2597 // Always allow uses by the backedge update.
2598 if (UserI == CondID.getBackedgePHI())
2599 continue;
2600
2601 Value *CurrentVal = U->get();
2602 if (isa<LoadInst, StoreInst>(UserI)) {
2603 // Disallow any store that uses the monotonic value as the stored value.
2604 auto *SI = dyn_cast<StoreInst>(UserI);
2605 if (SI && SI->getValueOperand() == CurrentVal)
2606 return false;
2607
2608 Type *AccessTy = getLoadStoreType(UserI);
2609
2610 // Disallow loads/stores of scalable or irregular types (like i4).
2611 if (AccessTy->isScalableTy() || hasIrregularType(AccessTy, DL))
2612 return false;
2613
2614 Value *Ptr = getLoadStorePointerOperand(UserI);
2615 const SCEVAddRecExpr *PtrAddRec = GetCompressedPtrSCEV(Ptr, AccessTy);
2616 if (!PtrAddRec)
2617 return false;
2618 CompressedPtrs.try_emplace(Ptr, PtrAddRec);
2619 continue;
2620 }
2621
2622 auto LoopVariantOp = [&](Value *V, bool /*AllowRepeats*/) -> Value * {
2623 return L.isLoopInvariant(V) ? nullptr : V;
2624 };
2625
2626 // Non-memory users may use any opcode (select/and/or/etc.), but they must
2627 // only have CurrentVal as their only loop-varying input. That prevents
2628 // mixing in a second loop-varying term. GetCompressedPtrSCEV rewrites the
2629 // full leaf pointer SCEV and rejects it unless the entire address still
2630 // simplifies to the required affine AddRec.
2631 if (UserI->use_empty() ||
2632 find_singleton<Value>(UserI->operands(), LoopVariantOp) != CurrentVal)
2633 return false;
2634
2635 append_range(Worklist, make_pointer_range(UserI->uses()));
2636 }
2637
2638 return true;
2639}
bool IsScalable
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:213
This file defines the DenseSet and SmallDenseSet classes.
#define Check(C,...)
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
ManagedStatic< HTTPClientCleanup > Cleanup
Hexagon Hardware Loops
Module.h This file contains the declarations for the Module class.
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static cl::opt< bool, true > HoistRuntimeChecks("hoist-runtime-checks", cl::Hidden, cl::desc("Hoist inner loop runtime memory checks to outer loop if possible"), cl::location(VectorizerParams::HoistRuntimeChecks), cl::init(true))
static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I)
static CondBrInst * getExpectedExitLoopLatchBranch(Loop *L)
Checks if L has an exiting latch branch.
static const char * LLVMLoopDisableLICM
Definition LoopUtils.cpp:57
static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG, Loop *TheLoop, Instruction *Loc, SCEVExpander &Exp, bool HoistRuntimeChecks)
Expand code for the lower and upper bound of the pointer group CG in TheLoop.
static bool canLoopBeDeleted(Loop *L, SmallVector< RewritePhi, 8 > &RewritePhiSet)
static const char * LLVMLoopDisableNonforced
Definition LoopUtils.cpp:56
static bool collectOperandExitValues(Instruction *Inst, Loop *L, BasicBlock *ExitingBlock, ScalarEvolution *SE, SCEVExpander &Rewriter, OperandExitValueList &ExitValues)
static MDNode * createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V)
Create MDNode for input string.
static std::optional< unsigned > estimateLoopTripCount(Loop *L)
static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE, InductionDescriptor &ID)
Checks if it is safe to call InductionDescriptor::isInductionPHI for Phi, and returns true if this Ph...
SmallVector< std::pair< unsigned, SCEVUse >, 2 > OperandExitValueList
static Intrinsic::ID getVPReductionIntrinsicID(Intrinsic::ID Id)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t High
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
This file provides a priority worklist.
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
This is the interface for a SCEV-based alias analysis.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
SmallDenseMap< const PHINode *, PhiInfo, 16 > PhiMap
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const uint32_t IV[8]
Definition blake3_impl.h:83
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1271
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
Represent the analysis usage information of a pass.
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
Definition Pass.cpp:294
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Legacy wrapper pass to provide the BasicAAResult object.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static constexpr BranchProbability getUnknown()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
Conditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
Describes a conditional induction variable: an induction variable that is updated only on loop iterat...
PHINode * getHeaderPHI() const
Returns the header PHI described by this descriptor.
LLVM_ABI const SCEV * getUnconditionalAddRec(ScalarEvolution &SE, const Loop &L) const
Returns an over-approximation of the conditional induction as a SCEVAddRec assuming the condition is ...
PHINode * getBackedgePHI() const
Returns the backedge PHI that selects between StepInst and the HeaderPHI.
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
static LLVM_ABI Constant * getIntrinsicIdentity(Intrinsic::ID, Type *Ty)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Identifies a unique instance of a variable.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
iterator_range< iterator > children()
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noNaNs() const
Definition FMF.h:65
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Legacy wrapper pass to provide the GlobalsAAResult object.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2474
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2811
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1572
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2490
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2987
A struct for saving information about induction variables.
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
iterator_range< user_iterator > users()
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
void addLoop(Loop &L)
Definition LoopPass.cpp:90
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
typename std::vector< Loop * >::const_iterator iterator
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
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.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
bool hasNoExitBlocks(const LoopT &L) const
Return true if L does not have any exit blocks.
iterator end() const
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:470
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:949
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:582
LLVM_ABI MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition LoopInfo.cpp:558
Metadata node.
Definition Metadata.h:1081
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
LLVMContext & getContext() const
Definition Metadata.h:1245
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
A single uniqued string.
Definition Metadata.h:733
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
Tuple of metadata.
Definition Metadata.h:1496
BasicBlock * getBlock() const
Definition MemorySSA.h:164
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:971
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:689
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:707
Root of the metadata hierarchy.
Definition Metadata.h:64
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void setIncomingValue(unsigned i, Value *V)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
bool insert(const T &X)
Insert a new element into the PriorityWorklist.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindRecurrenceKind(RecurKind Kind)
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
A global registry used in conjunction with static constructors to make pluggable components (like tar...
Definition Registry.h:116
Legacy wrapper pass to provide the SCEVAAResult object.
This node represents a polynomial recurrence on the trip count of the specified loop.
This class uses information about analyze scalars to rewrite expressions in canonical form.
ScalarEvolution * getSE()
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
LLVM_ABI void eraseDeadInstructions(Value *Root)
Remove inserted instructions that are dead, e.g.
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, ValueToSCEVMapTy &Map)
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI 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...
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI SCEVUse getSCEVAtExit(const SCEV *S, const Loop *L, const BasicBlock *ExitingBlock)
Return the SCEV expression at the specified loop exit.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopInvariant
The SCEV is loop-invariant.
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
size_type size() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Value handle that tracks a Value across RAUW.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
bool match(Val *V, const Pattern &P)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:694
This is an optimization pass for GlobalISel generic memory operations.
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 Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
LLVM_ABI std::optional< ElementCount > getOptionalElementCountLoopAttribute(const Loop *TheLoop)
Find a combination of metadata ("llvm.loop.vectorize.width" and "llvm.loop.vectorize....
LLVM_ABI bool collectCompressedPtrs(DenseMap< Value *, const SCEVAddRecExpr * > &CompressedPtrs, const Loop &L, const ConditionalInductionDescriptor &CondID, ScalarEvolution &SE)
Collect pointer values used by loads and stores whose addresses are derived from the conditional indu...
LLVM_ABI BranchProbability getBranchProbability(CondBrInst *B, bool ForFirstTarget)
Based on branch weight metadata, return either:
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
LLVM_ABI Value * addRuntimeChecks(Instruction *Loc, Loop *TheLoop, const SmallVectorImpl< RuntimePointerCheck > &PointerChecks, SCEVExpander &Expander, bool HoistRuntimeChecks=false)
Add code that checks at runtime if the accessed arrays in PointerChecks overlap.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
LLVM_ABI bool isKnownNonPositiveInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-positive in loop L.
DenseMap< const Value *, const SCEV * > ValueToSCEVMapTy
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:2570
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
void appendReversedLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
LLVM_ABI void initializeLoopPassPass(PassRegistry &)
Manually defined generic "LoopPass" dependency initialization.
constexpr from_range_t from_range
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
LLVM_ABI Value * getReductionIdentity(Intrinsic::ID RdxID, Type *Ty, FastMathFlags FMF)
Given information about an @llvm.vector.reduce.
LLVM_ABI std::optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
LLVM_ABI unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
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:649
LLVM_ABI char & LCSSAID
Definition LCSSA.cpp:545
std::pair< const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup * > RuntimePointerCheck
A memcheck which made up of a pair of grouped pointers.
LLVM_ABI char & LoopSimplifyID
LLVM_ABI Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
LLVM_ABI SmallVector< BasicBlock *, 16 > collectChildrenInLoop(DominatorTree *DT, DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
LLVM_ABI void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
LLVM_ABI bool cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned max.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition MathExtras.h:453
LLVM_ABI TransformationMode hasVectorizeTransformation(const Loop *L)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
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:1762
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:408
LLVM_ABI SmallVector< Instruction *, 8 > findDefsUsedOutsideOfLoop(Loop *L)
Returns the instructions that use values defined in the loop.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI constexpr Intrinsic::ID getReductionIntrinsicID(RecurKind RK)
Returns the llvm.vector.reduce intrinsic that corresponds to the recurrence kind.
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI 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...
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI TransformationMode hasUnrollAndJamTransformation(const Loop *L)
LLVM_ABI void deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, LoopInfo *LI, MemorySSA *MSSA=nullptr)
This function deletes dead loops.
bool hasIrregularType(Type *Ty, const DataLayout &DL)
A helper function that returns true if the given type is irregular.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool hasDisableAllTransformsHint(const Loop *L)
Look for the loop attribute that disables all transformation heuristic.
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
LLVM_ABI Value * getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op, TargetTransformInfo::ReductionShuffle RS, RecurKind MinMaxKind=RecurKind::None)
Generates a vector reduction using shufflevectors to reduce the value.
LLVM_ABI TransformationMode hasUnrollTransformation(const Loop *L)
LLVM_ABI BranchProbability getLoopProbability(Loop *L)
Based on branch weight metadata, return either:
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:76
LLVM_ABI TransformationMode hasDistributeTransformation(const Loop *L)
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1853
LLVM_ABI void breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA)
Remove the backedge of the specified loop.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_ABI void propagateIRFlags(Value *I, ArrayRef< Value * > VL, Value *OpValue=nullptr, bool IncludeWrapFlags=true)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
LLVM_ABI bool isKnownPositiveInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always positive in loop L.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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:2592
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
LLVM_ABI bool setLoopProbability(Loop *L, BranchProbability P)
Set branch weight metadata for the latch of L to indicate that, at the end of any iteration,...
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
TargetTransformInfo TTI
LLVM_ABI CmpInst::Predicate getMinMaxReductionPredicate(RecurKind RK)
Returns the comparison predicate used when expanding a min/max reduction.
LLVM_ABI TransformationMode hasLICMVersioningTransformation(const Loop *L)
TransformationMode
The mode sets how eager a transformation should be applied.
Definition LoopUtils.h:292
@ TM_Unspecified
The pass can use heuristics to determine whether a transformation should be applied.
Definition LoopUtils.h:295
@ TM_SuppressedByUser
The transformation must not be applied.
Definition LoopUtils.h:315
@ TM_ForcedByUser
The transformation was directed by the user, e.g.
Definition LoopUtils.h:309
@ TM_Disable
The transformation should not be applied.
Definition LoopUtils.h:301
@ TM_Enable
The transformation should be applied without considering a cost model.
Definition LoopUtils.h:298
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
LLVM_ABI bool hasDisableLICMTransformsHint(const Loop *L)
Look for the loop attribute that disables the LICM transformation heuristics.
template LLVM_TEMPLATE_ABI void appendLoopsToWorklist< Loop & >(Loop &L, SmallPriorityWorklist< Loop *, 4 > &Worklist)
LLVM_ABI Intrinsic::ID getReductionForBinop(Instruction::BinaryOps Opc)
Returns the reduction intrinsic id corresponding to the binary operation.
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ None
Not a recurrence.
@ Xor
Bitwise or logical XOR of integers.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
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 BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
Definition LoopUtils.cpp:59
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool isKnownNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always negative in loop L.
LLVM_ABI StringRef getLoopVectorizeKindPrefix(const Loop *L)
Return a short prefix describing the loop's vectorizer origin based on the llvm.loop....
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI Value * expandReductionViaLoop(IRBuilderBase &Builder, Value *Vec, unsigned RdxOpcode, Value *Acc, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Expand a scalable vector reduction into a runtime loop that applies RdxOpcode element by element,...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
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 bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
LLVM_ABI RuntimeCheckBounds getRuntimeCheckBounds(const RuntimeCheckingPtrGroup *CG, const Loop *TheLoop, ScalarEvolution &SE, bool HoistRuntimeChecks)
Return the bounds of CG in TheLoop.
LLVM_ABI bool hasIterationCountInvariantInParent(Loop *L, ScalarEvolution &SE)
Check inner loop (L) backedge count is known to be invariant on all iterations of its outer loop.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isAlmostDeadIV(PHINode *IV, BasicBlock *LatchBlock, Value *Cond)
Return true if the induction variable IV in a Loop whose latch is LatchBlock would become dead if the...
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI int rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI, ScalarEvolution *SE, const TargetTransformInfo *TTI, SCEVExpander &Rewriter, DominatorTree *DT, ReplaceExitVal ReplaceExitValue, SmallVector< WeakTrackingVH, 16 > &DeadInsts)
If the final value of any expressions that are recurrent in the loop can be computed,...
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI Value * createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence kind RdxKind.
LLVM_ABI RecurKind getMinMaxReductionRecurKind(Intrinsic::ID RdxID)
Returns the recurence kind used when expanding a min/max reduction.
ReplaceExitVal
Definition LoopUtils.h:604
@ UnusedIndVarInLoop
Definition LoopUtils.h:608
@ OnlyCheapRepl
Definition LoopUtils.h:606
@ AlwaysRepl
Definition LoopUtils.h:609
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI std::optional< IVConditionInfo > hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold, const MemorySSA &MSSA, AAResults &AA)
Check if the loop header has a conditional branch that is not loop-invariant, because it involves loa...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned min.
LLVM_ABI bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-negative in loop L.
LLVM_ABI Value * addDiffRuntimeChecks(Instruction *Loc, ArrayRef< PointerDiffInfo > Checks, SCEVExpander &Expander, ElementCount VF, unsigned IC)
LLVM_ABI Value * getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src, unsigned Op, RecurKind MinMaxKind=RecurKind::None)
Generates an ordered vector reduction using extracts to reduce the value.
LLVM_ABI MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicID(Intrinsic::ID IID)
Returns the llvm.vector.reduce min/max intrinsic that corresponds to the intrinsic op.
@ Enable
Enable colors.
Definition WithColor.h:47
LLVM_ABI Loop * cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, LoopInfo *LI, LPPassManager *LPM)
Recursively clone the specified loop and all of its children, mapping the blocks with the specified m...
SCEVUseT< const SCEV * > SCEVUse
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
DbgLoop(const Loop *L)
const Loop * L
IR Values for the lower and upper bounds of a pointer evolution.
TrackingVH< Value > Start
TrackingVH< Value > End
Value * StrideToCheck
SCEVUse ExpansionSCEV
unsigned Ith
OperandExitValueList OperandExitValues
PHINode * PN
RewritePhi(PHINode *P, unsigned I, SCEVUse Val, Instruction *ExpansionPt, bool H, OperandExitValueList OpExitValues={})
Instruction * ExpansionPoint
Struct to hold information about a partially invariant condition.
Definition LoopUtils.h:692
SCEV bounds of a pointer group: the first accessed byte, the last accessed byte plus one,...
Definition LoopUtils.h:666
unsigned AddressSpace
Address space of the involved pointers.
bool NeedsFreeze
Whether the pointer needs to be frozen after expansion, e.g.
const SCEV * High
The SCEV expression which represents the upper bound of all the pointers in this group.
const SCEV * Low
The SCEV expression which represents the lower bound of all the pointers in this group.
SCEVPtrT getPointer() const