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"
33#include "llvm/IR/DIBuilder.h"
34#include "llvm/IR/Dominators.h"
37#include "llvm/IR/MDBuilder.h"
38#include "llvm/IR/Module.h"
41#include "llvm/IR/ValueHandle.h"
43#include "llvm/Pass.h"
45#include "llvm/Support/Debug.h"
49
50using namespace llvm;
51using namespace llvm::PatternMatch;
52
53#define DEBUG_TYPE "loop-utils"
54
55static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
56static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
57namespace llvm {
59} // namespace llvm
60
62 MemorySSAUpdater *MSSAU,
63 bool PreserveLCSSA) {
64 bool Changed = false;
65
66 // We re-use a vector for the in-loop predecesosrs.
67 SmallVector<BasicBlock *, 4> InLoopPredecessors;
68
69 auto RewriteExit = [&](BasicBlock *BB) {
70 assert(InLoopPredecessors.empty() &&
71 "Must start with an empty predecessors list!");
72 llvm::scope_exit Cleanup([&] { InLoopPredecessors.clear(); });
73
74 // See if there are any non-loop predecessors of this exit block and
75 // keep track of the in-loop predecessors.
76 bool IsDedicatedExit = true;
77 for (auto *PredBB : predecessors(BB))
78 if (L->contains(PredBB)) {
79 if (isa<IndirectBrInst>(PredBB->getTerminator()))
80 // We cannot rewrite exiting edges from an indirectbr.
81 return false;
82
83 InLoopPredecessors.push_back(PredBB);
84 } else {
85 IsDedicatedExit = false;
86 }
87
88 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
89
90 // Nothing to do if this is already a dedicated exit.
91 if (IsDedicatedExit)
92 return false;
93
94 auto *NewExitBB = SplitBlockPredecessors(
95 BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
96
97 if (!NewExitBB)
99 dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
100 << *L << "\n");
101 else
102 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
103 << NewExitBB->getName() << "\n");
104 return true;
105 };
106
107 // Walk the exit blocks directly rather than building up a data structure for
108 // them, but only visit each one once.
110 for (auto *BB : L->blocks())
111 for (auto *SuccBB : successors(BB)) {
112 // We're looking for exit blocks so skip in-loop successors.
113 if (L->contains(SuccBB))
114 continue;
115
116 // Visit each exit block exactly once.
117 if (!Visited.insert(SuccBB).second)
118 continue;
119
120 Changed |= RewriteExit(SuccBB);
121 }
122
123 return Changed;
124}
125
126/// Returns the instructions that use values defined in the loop.
129
130 for (auto *Block : L->getBlocks())
131 // FIXME: I believe that this could use copy_if if the Inst reference could
132 // be adapted into a pointer.
133 for (auto &Inst : *Block) {
134 auto Users = Inst.users();
135 if (any_of(Users, [&](User *U) {
136 auto *Use = cast<Instruction>(U);
137 return !L->contains(Use->getParent());
138 }))
139 UsedOutside.push_back(&Inst);
140 }
141
142 return UsedOutside;
143}
144
146 // By definition, all loop passes need the LoopInfo analysis and the
147 // Dominator tree it depends on. Because they all participate in the loop
148 // pass manager, they must also preserve these.
153
154 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
155 // here because users shouldn't directly get them from this header.
156 extern char &LoopSimplifyID;
157 extern char &LCSSAID;
162 // This is used in the LPPassManager to perform LCSSA verification on passes
163 // which preserve lcssa form
166
167 // Loop passes are designed to run inside of a loop pass manager which means
168 // that any function analyses they require must be required by the first loop
169 // pass in the manager (so that it is computed before the loop pass manager
170 // runs) and preserved by all loop pasess in the manager. To make this
171 // reasonably robust, the set needed for most loop passes is maintained here.
172 // If your loop pass requires an analysis not listed here, you will need to
173 // carefully audit the loop pass manager nesting structure that results.
181 // FIXME: When all loop passes preserve MemorySSA, it can be required and
182 // preserved here instead of the individual handling in each pass.
183}
184
185/// Manually defined generic "LoopPass" dependency initialization. This is used
186/// to initialize the exact set of passes from above in \c
187/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
188/// with:
189///
190/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
191///
192/// As-if "LoopPass" were a pass.
205
206/// Create MDNode for input string.
207static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
208 LLVMContext &Context = TheLoop->getHeader()->getContext();
209 Metadata *MDs[] = {
210 MDString::get(Context, Name),
211 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
212 return MDNode::get(Context, MDs);
213}
214
215/// Set input string into loop metadata by keeping other values intact.
216/// If the string is already in loop metadata update value if it is
217/// different.
218void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
219 unsigned V) {
221 // If the loop already has metadata, retain it.
222 MDNode *LoopID = TheLoop->getLoopID();
223 if (LoopID) {
224 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
225 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
226 // If it is of form key = value, try to parse it.
227 if (Node->getNumOperands() == 2) {
228 MDString *S = dyn_cast<MDString>(Node->getOperand(0));
229 if (S && S->getString() == StringMD) {
230 ConstantInt *IntMD =
232 if (IntMD && IntMD->getSExtValue() == V)
233 // It is already in place. Do nothing.
234 return;
235 // We need to update the value, so just skip it here and it will
236 // be added after copying other existed nodes.
237 continue;
238 }
239 }
240 MDs.push_back(Node);
241 }
242 }
243 // Add new metadata.
244 MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
245 // Replace current metadata node with new one.
246 LLVMContext &Context = TheLoop->getHeader()->getContext();
247 MDNode *NewLoopID = MDNode::get(Context, MDs);
248 // Set operand 0 to refer to the loop id itself.
249 NewLoopID->replaceOperandWith(0, NewLoopID);
250 TheLoop->setLoopID(NewLoopID);
251}
252
254 LLVMContext &Context = TheLoop->getHeader()->getContext();
256 // Retain existing metadata, skipping a name-only node with the same string.
257 if (MDNode *LoopID = TheLoop->getLoopID())
258 for (const MDOperand &Op : drop_begin(LoopID->operands())) {
260 if (Node->getNumOperands() == 1)
261 if (auto *S = dyn_cast<MDString>(Node->getOperand(0)))
262 if (S->getString() == StringMD)
263 return;
264 MDs.push_back(Node);
265 }
266 MDs.push_back(MDNode::get(Context, {MDString::get(Context, StringMD)}));
267 MDNode *NewLoopID = MDNode::get(Context, MDs);
268 // Set operand 0 to refer to the loop id itself.
269 NewLoopID->replaceOperandWith(0, NewLoopID);
270 TheLoop->setLoopID(NewLoopID);
271}
272
273std::optional<ElementCount>
275 std::optional<int> Width =
276 getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
277
278 if (Width) {
279 std::optional<int> IsScalable = getOptionalIntLoopAttribute(
280 TheLoop, "llvm.loop.vectorize.scalable.enable");
281 return ElementCount::get(*Width, IsScalable.value_or(false));
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 DIBuilder DIB(*ExitBlock->getModule());
696 BasicBlock::iterator InsertDbgValueBefore =
697 ExitBlock->getFirstInsertionPt();
698 assert(InsertDbgValueBefore != ExitBlock->end() &&
699 "There should be a non-PHI instruction in exit block, else these "
700 "instructions will have no parent.");
701
702 // Due to the "head" bit in BasicBlock::iterator, we're going to insert
703 // each DbgVariableRecord right at the start of the block, wheras dbg.values
704 // would be repeatedly inserted before the first instruction. To replicate
705 // this behaviour, do it backwards.
706 for (DbgVariableRecord *DVR : llvm::reverse(DeadDbgVariableRecords))
707 ExitBlock->insertDbgRecordBefore(DVR, InsertDbgValueBefore);
708 }
709
710 // Remove the block from the reference counting scheme, so that we can
711 // delete it freely later.
712 for (auto *Block : L->blocks())
713 Block->dropAllReferences();
714
715 if (MSSA && VerifyMemorySSA)
716 MSSA->verifyMemorySSA();
717
718 if (LI) {
720
721 // Erase the instructions and the blocks without having to worry
722 // about ordering because we already dropped the references.
723 // Remove blocks from loopinfo before erasing them, otherwise the loopinfo
724 // cannot find the loop using block numbers.
725 for (BasicBlock *BB : Blocks) {
726 LI->removeBlock(BB);
727 BB->eraseFromParent();
728 }
729
730 // The last step is to update LoopInfo now that we've eliminated this loop.
731 // Note: LoopInfo::erase remove the given loop and relink its subloops with
732 // its parent. While removeLoop/removeChildLoop remove the given loop but
733 // not relink its subloops, which is what we want.
734 if (Loop *ParentLoop = L->getParentLoop()) {
735 Loop::iterator I = find(*ParentLoop, L);
736 assert(I != ParentLoop->end() && "Couldn't find loop");
737 ParentLoop->removeChildLoop(I);
738 } else {
739 Loop::iterator I = find(*LI, L);
740 assert(I != LI->end() && "Couldn't find loop");
741 LI->removeLoop(I);
742 }
743 LI->destroy(L);
744 }
745}
746
748 LoopInfo &LI, MemorySSA *MSSA) {
749 auto *Latch = L->getLoopLatch();
750 assert(Latch && "multiple latches not yet supported");
751 auto *Header = L->getHeader();
752 Loop *OutermostLoop = L->getOutermostLoop();
753
754 SE.forgetLoop(L);
756
757 std::unique_ptr<MemorySSAUpdater> MSSAU;
758 if (MSSA)
759 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
760
761 // Update the CFG and domtree. We chose to special case a couple of
762 // of common cases for code quality and test readability reasons.
763 [&]() -> void {
764 if (auto *BI = dyn_cast<UncondBrInst>(Latch->getTerminator())) {
765 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
766 (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
767 return;
768 }
769 if (auto *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
770 // Conditional latch/exit - note that latch can be shared by inner
771 // and outer loop so the other target doesn't need to an exit
772 if (L->isLoopExiting(Latch)) {
773 // TODO: Generalize ConstantFoldTerminator so that it can be used
774 // here without invalidating LCSSA or MemorySSA. (Tricky case for
775 // LCSSA: header is an exit block of a preceeding sibling loop w/o
776 // dedicated exits.)
777 const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0;
778 BasicBlock *ExitBB = BI->getSuccessor(ExitIdx);
779
780 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
781 Header->removePredecessor(Latch, true);
782
783 IRBuilder<> Builder(BI);
784 auto *NewBI = Builder.CreateBr(ExitBB);
785 // Transfer the metadata to the new branch instruction (minus the
786 // loop info since this is no longer a loop)
787 NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg,
788 LLVMContext::MD_annotation});
789
790 BI->eraseFromParent();
791 DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}});
792 if (MSSA)
793 MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT);
794 return;
795 }
796 }
797
798 // General case. By splitting the backedge, and then explicitly making it
799 // unreachable we gracefully handle corner cases such as switch and invoke
800 // termiantors.
801 auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
802
803 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
804 (void)changeToUnreachable(BackedgeBB->getTerminator(),
805 /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
806 }();
807
808 // Erase (and destroy) this loop instance. Handles relinking sub-loops
809 // and blocks within the loop as needed.
810 LI.erase(L);
811
812 // If the loop we broke had a parent, then changeToUnreachable might have
813 // caused a block to be removed from the parent loop (see loop_nest_lcssa
814 // test case in zero-btc.ll for an example), thus changing the parent's
815 // exit blocks. If that happened, we need to rebuild LCSSA on the outermost
816 // loop which might have a had a block removed.
817 if (OutermostLoop != L)
818 formLCSSARecursively(*OutermostLoop, DT, &LI, &SE);
819}
820
821
822/// Checks if \p L has an exiting latch branch. There may also be other
823/// exiting blocks. Returns branch instruction terminating the loop
824/// latch if above check is successful, nullptr otherwise.
826 BasicBlock *Latch = L->getLoopLatch();
827 if (!Latch)
828 return nullptr;
829
830 CondBrInst *LatchBR = dyn_cast<CondBrInst>(Latch->getTerminator());
831 if (!LatchBR || !L->isLoopExiting(Latch))
832 return nullptr;
833
834 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
835 LatchBR->getSuccessor(1) == L->getHeader()) &&
836 "At least one edge out of the latch must go to the header");
837
838 return LatchBR;
839}
840
841struct DbgLoop {
842 const Loop *L;
843 explicit DbgLoop(const Loop *L) : L(L) {}
844};
845
846#ifndef NDEBUG
848 OS << "function ";
849 D.L->getHeader()->getParent()->printAsOperand(OS, /*PrintType=*/false);
850 return OS << " " << *D.L;
851}
852#endif // NDEBUG
853
854static std::optional<unsigned> estimateLoopTripCount(Loop *L) {
855 // Currently we take the estimate exit count only from the loop latch,
856 // ignoring other exiting blocks. This can overestimate the trip count
857 // if we exit through another exit, but can never underestimate it.
858 // TODO: incorporate information from other exits
859 CondBrInst *ExitingBranch = getExpectedExitLoopLatchBranch(L);
860 if (!ExitingBranch) {
861 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed to find exiting "
862 << "latch branch of required form in " << DbgLoop(L)
863 << "\n");
864 return std::nullopt;
865 }
866
867 // To estimate the number of times the loop body was executed, we want to
868 // know the number of times the backedge was taken, vs. the number of times
869 // we exited the loop.
870 uint64_t LoopWeight, ExitWeight;
871 if (!extractBranchWeights(*ExitingBranch, LoopWeight, ExitWeight)) {
872 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed to extract branch "
873 << "weights for " << DbgLoop(L) << "\n");
874 return std::nullopt;
875 }
876
877 if (L->contains(ExitingBranch->getSuccessor(1)))
878 std::swap(LoopWeight, ExitWeight);
879
880 if (!ExitWeight) {
881 // Don't have a way to return predicated infinite
882 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Failed because of zero exit "
883 << "probability for " << DbgLoop(L) << "\n");
884 return std::nullopt;
885 }
886
887 // Estimated exit count is a ratio of the loop weight by the weight of the
888 // edge exiting the loop, rounded to nearest.
889 uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight);
890
891 // When ExitCount + 1 would wrap in unsigned, saturate at UINT_MAX.
892 if (ExitCount >= std::numeric_limits<unsigned>::max())
893 return std::numeric_limits<unsigned>::max();
894
895 // Estimated trip count is one plus estimated exit count.
896 uint64_t TC = ExitCount + 1;
897 LLVM_DEBUG(dbgs() << "estimateLoopTripCount: Estimated trip count of " << TC
898 << " for " << DbgLoop(L) << "\n");
899 return TC;
900}
901
902std::optional<unsigned>
904 unsigned *EstimatedLoopInvocationWeight) {
905 // If EstimatedLoopInvocationWeight, we do not support this loop if
906 // getExpectedExitLoopLatchBranch returns nullptr.
907 //
908 // FIXME: Also, this is a stop-gap solution for nested loops. It avoids
909 // mistaking LLVMLoopEstimatedTripCount metadata to be for an outer loop when
910 // it was created for an inner loop. The problem is that loop metadata is
911 // attached to the branch instruction in the loop latch block, but that can be
912 // shared by the loops. A solution is to attach loop metadata to loop headers
913 // instead, but that would be a large change to LLVM.
914 //
915 // Until that happens, we work around the problem as follows.
916 // getExpectedExitLoopLatchBranch (which also guards
917 // setLoopEstimatedTripCount) returns nullptr for a loop unless the loop has
918 // one latch and that latch has exactly two successors one of which is an exit
919 // from the loop. If the latch is shared by nested loops, then that condition
920 // might hold for the inner loop but cannot hold for the outer loop:
921 // - Because the latch is shared, it must have at least two successors: the
922 // inner loop header and the outer loop header, which is also an exit for
923 // the inner loop. That satisifies the condition for the inner loop.
924 // - To satsify the condition for the outer loop, the latch must have a third
925 // successor that is an exit for the outer loop. But that violates the
926 // condition for both loops.
927 CondBrInst *ExitingBranch = getExpectedExitLoopLatchBranch(L);
928 if (!ExitingBranch)
929 return std::nullopt;
930
931 // If requested, either compute *EstimatedLoopInvocationWeight or return
932 // nullopt if cannot.
933 //
934 // TODO: Eventually, once all passes have migrated away from setting branch
935 // weights to indicate estimated trip counts, this function will drop the
936 // EstimatedLoopInvocationWeight parameter.
937 if (EstimatedLoopInvocationWeight) {
938 uint64_t LoopWeight = 0, ExitWeight = 0; // Inits expected to be unused.
939 if (!extractBranchWeights(*ExitingBranch, LoopWeight, ExitWeight))
940 return std::nullopt;
941 if (L->contains(ExitingBranch->getSuccessor(1)))
942 std::swap(LoopWeight, ExitWeight);
943 if (!ExitWeight)
944 return std::nullopt;
945 *EstimatedLoopInvocationWeight = ExitWeight;
946 }
947
948 // Return the estimated trip count from metadata unless the metadata is
949 // missing or has no value.
950 //
951 // Some passes set llvm.loop.estimated_trip_count to 0. For example, after
952 // peeling 10 or more iterations from a loop with an estimated trip count of
953 // 10, llvm.loop.estimated_trip_count becomes 0 on the remaining loop. It
954 // indicates that, each time execution reaches the peeled iterations,
955 // execution is estimated to exit them without reaching the remaining loop's
956 // header.
957 //
958 // Even if the probability of reaching a loop's header is low, if it is
959 // reached, it is the start of an iteration. Consequently, some passes
960 // historically assume that llvm::getLoopEstimatedTripCount always returns a
961 // positive count or std::nullopt. Thus, return std::nullopt when
962 // llvm.loop.estimated_trip_count is 0.
963 if (std::optional<unsigned> TC =
965 LLVM_DEBUG(dbgs() << "getLoopEstimatedTripCount: "
966 << LLVMLoopEstimatedTripCount << " metadata has trip "
967 << "count of " << *TC
968 << (*TC == 0 ? " (returning std::nullopt)" : "")
969 << " for " << DbgLoop(L) << "\n");
970 return *TC == 0 ? std::nullopt : TC;
971 }
972
973 // Estimate the trip count from latch branch weights.
974 return estimateLoopTripCount(L);
975}
976
978 Loop *L, unsigned EstimatedTripCount,
979 std::optional<unsigned> EstimatedloopInvocationWeight) {
980 // If EstimatedLoopInvocationWeight, we do not support this loop if
981 // getExpectedExitLoopLatchBranch returns nullptr.
982 //
983 // FIXME: See comments in getLoopEstimatedTripCount for why this is required
984 // here regardless of EstimatedLoopInvocationWeight.
986 if (!LatchBranch)
987 return false;
988
989 // Set the metadata.
991
992 // At the moment, we currently support changing the estimated trip count in
993 // the latch branch's branch weights only. We could extend this API to
994 // manipulate estimated trip counts for any exit.
995 //
996 // TODO: Eventually, once all passes have migrated away from setting branch
997 // weights to indicate estimated trip counts, we will not set branch weights
998 // here at all.
999 if (!EstimatedloopInvocationWeight)
1000 return true;
1001
1002 // Calculate taken and exit weights.
1003 unsigned LatchExitWeight = ProfcheckDisableMetadataFixes ? 0 : 1;
1004 unsigned BackedgeTakenWeight = 0;
1005
1006 if (EstimatedTripCount != 0) {
1007 LatchExitWeight = *EstimatedloopInvocationWeight;
1008 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
1009 }
1010
1011 // Make a swap if back edge is taken when condition is "false".
1012 if (LatchBranch->getSuccessor(0) != L->getHeader())
1013 std::swap(BackedgeTakenWeight, LatchExitWeight);
1014
1015 // Set/Update profile metadata.
1016 setBranchWeights(*LatchBranch, {BackedgeTakenWeight, LatchExitWeight},
1017 /*IsExpected=*/false);
1018
1019 return true;
1020}
1021
1024 if (!LatchBranch)
1026 bool FirstTargetIsLoop = LatchBranch->getSuccessor(0) == L->getHeader();
1027 return getBranchProbability(LatchBranch, FirstTargetIsLoop);
1028}
1029
1032 if (!LatchBranch)
1033 return false;
1034 bool FirstTargetIsLoop = LatchBranch->getSuccessor(0) == L->getHeader();
1035 setBranchProbability(LatchBranch, P, FirstTargetIsLoop);
1036 return true;
1037}
1038
1040 bool ForFirstTarget) {
1041 uint64_t Weight0, Weight1;
1042 if (!extractBranchWeights(*B, Weight0, Weight1))
1044 uint64_t Denominator = Weight0 + Weight1;
1045 if (Denominator == 0)
1047 if (!ForFirstTarget)
1048 std::swap(Weight0, Weight1);
1049 return BranchProbability::getBranchProbability(Weight0, Denominator);
1050}
1051
1053 assert(Src != Dst && "Passed in same source as destination");
1054
1055 Instruction *TI = Src->getTerminator();
1056 if (!TI || TI->getNumSuccessors() == 0)
1058
1060
1061 if (!extractBranchWeights(*TI, Weights)) {
1062 // No metadata
1064 }
1065 assert(TI->getNumSuccessors() == Weights.size() &&
1066 "Missing weights in branch_weights");
1067
1068 uint64_t Total = 0;
1069 uint32_t Numerator = 0;
1070 for (auto [i, Weight] : llvm::enumerate(Weights)) {
1071 if (TI->getSuccessor(i) == Dst)
1072 Numerator += Weight;
1073 Total += Weight;
1074 }
1075
1076 // Total of edges might be 0 if the metadata is incorrect/set by hand
1077 // or missing. In such case return here to avoid division by 0 later on.
1078 // There might also be a case where the value of Total cannot fit into
1079 // uint32_t, in such case, just bail out.
1080 if (Total == 0 || Total > std::numeric_limits<uint32_t>::max())
1082
1083 return BranchProbability(Numerator, Total);
1084}
1085
1087 bool ForFirstTarget) {
1088 BranchProbability Prob0 = P;
1089 BranchProbability Prob1 = P.getCompl();
1090 if (!ForFirstTarget)
1091 std::swap(Prob0, Prob1);
1092 setBranchWeights(*B, {Prob0.getNumerator(), Prob1.getNumerator()},
1093 /*IsExpected=*/false);
1094}
1095
1097 ScalarEvolution &SE) {
1098 Loop *OuterL = InnerLoop->getParentLoop();
1099 if (!OuterL)
1100 return true;
1101
1102 // Get the backedge taken count for the inner loop
1103 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1104 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
1105 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
1106 !InnerLoopBECountSC->getType()->isIntegerTy())
1107 return false;
1108
1109 // Get whether count is invariant to the outer loop
1111 SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
1113 return false;
1114
1115 return true;
1116}
1117
1119 switch (RK) {
1120 default:
1121 llvm_unreachable("Unexpected recurrence kind");
1123 case RecurKind::Sub:
1124 case RecurKind::Add:
1125 return Intrinsic::vector_reduce_add;
1126 case RecurKind::Mul:
1127 return Intrinsic::vector_reduce_mul;
1128 case RecurKind::And:
1129 return Intrinsic::vector_reduce_and;
1130 case RecurKind::Or:
1131 return Intrinsic::vector_reduce_or;
1132 case RecurKind::Xor:
1133 return Intrinsic::vector_reduce_xor;
1134 case RecurKind::FMulAdd:
1136 case RecurKind::FSub:
1137 case RecurKind::FAdd:
1138 return Intrinsic::vector_reduce_fadd;
1139 case RecurKind::FMul:
1140 return Intrinsic::vector_reduce_fmul;
1141 case RecurKind::SMax:
1142 return Intrinsic::vector_reduce_smax;
1143 case RecurKind::SMin:
1144 return Intrinsic::vector_reduce_smin;
1145 case RecurKind::UMax:
1146 return Intrinsic::vector_reduce_umax;
1147 case RecurKind::UMin:
1148 return Intrinsic::vector_reduce_umin;
1149 case RecurKind::FMax:
1150 case RecurKind::FMaxNum:
1151 return Intrinsic::vector_reduce_fmax;
1152 case RecurKind::FMin:
1153 case RecurKind::FMinNum:
1154 return Intrinsic::vector_reduce_fmin;
1156 return Intrinsic::vector_reduce_fmaximum;
1158 return Intrinsic::vector_reduce_fminimum;
1160 return Intrinsic::vector_reduce_fmax;
1162 return Intrinsic::vector_reduce_fmin;
1163 }
1164}
1165
1167 switch (IID) {
1168 default:
1169 llvm_unreachable("Unexpected intrinsic id");
1170 case Intrinsic::umin:
1171 return Intrinsic::vector_reduce_umin;
1172 case Intrinsic::umax:
1173 return Intrinsic::vector_reduce_umax;
1174 case Intrinsic::smin:
1175 return Intrinsic::vector_reduce_smin;
1176 case Intrinsic::smax:
1177 return Intrinsic::vector_reduce_smax;
1178 }
1179}
1180
1181// This is the inverse to getReductionForBinop
1183 switch (RdxID) {
1184 case Intrinsic::vector_reduce_fadd:
1185 return Instruction::FAdd;
1186 case Intrinsic::vector_reduce_fmul:
1187 return Instruction::FMul;
1188 case Intrinsic::vector_reduce_add:
1189 return Instruction::Add;
1190 case Intrinsic::vector_reduce_mul:
1191 return Instruction::Mul;
1192 case Intrinsic::vector_reduce_and:
1193 return Instruction::And;
1194 case Intrinsic::vector_reduce_or:
1195 return Instruction::Or;
1196 case Intrinsic::vector_reduce_xor:
1197 return Instruction::Xor;
1198 case Intrinsic::vector_reduce_smax:
1199 case Intrinsic::vector_reduce_smin:
1200 case Intrinsic::vector_reduce_umax:
1201 case Intrinsic::vector_reduce_umin:
1202 return Instruction::ICmp;
1203 case Intrinsic::vector_reduce_fmax:
1204 case Intrinsic::vector_reduce_fmin:
1205 case Intrinsic::vector_reduce_fmaximum:
1206 case Intrinsic::vector_reduce_fminimum:
1207 return Instruction::FCmp;
1208 default:
1209 llvm_unreachable("Unexpected ID");
1210 }
1211}
1212
1213// This is the inverse to getArithmeticReductionInstruction
1215 switch (Opc) {
1216 default:
1217 break;
1218 case Instruction::Add:
1219 return Intrinsic::vector_reduce_add;
1220 case Instruction::Mul:
1221 return Intrinsic::vector_reduce_mul;
1222 case Instruction::And:
1223 return Intrinsic::vector_reduce_and;
1224 case Instruction::Or:
1225 return Intrinsic::vector_reduce_or;
1226 case Instruction::Xor:
1227 return Intrinsic::vector_reduce_xor;
1228 case Instruction::FAdd:
1229 return Intrinsic::vector_reduce_fadd;
1230 case Instruction::FMul:
1231 return Intrinsic::vector_reduce_fmul;
1232 }
1234}
1235
1237 switch (RdxID) {
1238 default:
1239 llvm_unreachable("Unknown min/max recurrence kind");
1240 case Intrinsic::vector_reduce_umin:
1241 return Intrinsic::umin;
1242 case Intrinsic::vector_reduce_umax:
1243 return Intrinsic::umax;
1244 case Intrinsic::vector_reduce_smin:
1245 return Intrinsic::smin;
1246 case Intrinsic::vector_reduce_smax:
1247 return Intrinsic::smax;
1248 case Intrinsic::vector_reduce_fmin:
1249 return Intrinsic::minnum;
1250 case Intrinsic::vector_reduce_fmax:
1251 return Intrinsic::maxnum;
1252 case Intrinsic::vector_reduce_fminimum:
1253 return Intrinsic::minimum;
1254 case Intrinsic::vector_reduce_fmaximum:
1255 return Intrinsic::maximum;
1256 }
1257}
1258
1260 switch (RK) {
1261 default:
1262 llvm_unreachable("Unknown min/max recurrence kind");
1263 case RecurKind::UMin:
1264 return Intrinsic::umin;
1265 case RecurKind::UMax:
1266 return Intrinsic::umax;
1267 case RecurKind::SMin:
1268 return Intrinsic::smin;
1269 case RecurKind::SMax:
1270 return Intrinsic::smax;
1271 case RecurKind::FMin:
1272 case RecurKind::FMinNum:
1273 return Intrinsic::minnum;
1274 case RecurKind::FMax:
1275 case RecurKind::FMaxNum:
1276 return Intrinsic::maxnum;
1278 return Intrinsic::minimum;
1280 return Intrinsic::maximum;
1282 return Intrinsic::minimumnum;
1284 return Intrinsic::maximumnum;
1285 }
1286}
1287
1289 switch (RdxID) {
1290 case Intrinsic::vector_reduce_smax:
1291 return RecurKind::SMax;
1292 case Intrinsic::vector_reduce_smin:
1293 return RecurKind::SMin;
1294 case Intrinsic::vector_reduce_umax:
1295 return RecurKind::UMax;
1296 case Intrinsic::vector_reduce_umin:
1297 return RecurKind::UMin;
1298 case Intrinsic::vector_reduce_fmax:
1299 return RecurKind::FMax;
1300 case Intrinsic::vector_reduce_fmin:
1301 return RecurKind::FMin;
1302 case Intrinsic::vector_reduce_fmaximum:
1303 return RecurKind::FMaximum;
1304 case Intrinsic::vector_reduce_fminimum:
1305 return RecurKind::FMinimum;
1306 default:
1307 return RecurKind::None;
1308 }
1309}
1310
1312 switch (RK) {
1313 default:
1314 llvm_unreachable("Unknown min/max recurrence kind");
1315 case RecurKind::UMin:
1316 return CmpInst::ICMP_ULT;
1317 case RecurKind::UMax:
1318 return CmpInst::ICMP_UGT;
1319 case RecurKind::SMin:
1320 return CmpInst::ICMP_SLT;
1321 case RecurKind::SMax:
1322 return CmpInst::ICMP_SGT;
1323 case RecurKind::FMin:
1324 return CmpInst::FCMP_OLT;
1325 case RecurKind::FMax:
1326 return CmpInst::FCMP_OGT;
1327 // We do not add FMinimum/FMaximum recurrence kind here since there is no
1328 // equivalent predicate which compares signed zeroes according to the
1329 // semantics of the intrinsics (llvm.minimum/maximum).
1330 }
1331}
1332
1334 Value *Right) {
1335 Type *Ty = Left->getType();
1336 if (Ty->isIntOrIntVectorTy() ||
1337 (RK == RecurKind::FMinNum || RK == RecurKind::FMaxNum ||
1341 return Builder.CreateIntrinsic(Ty, Id, {Left, Right}, nullptr,
1342 "rdx.minmax");
1343 }
1345 Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp");
1346 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1347 // This select is synthesized fresh, not lowered from an existing branch, so
1348 // it carries no real profile. Mark its weights as explicitly unknown.
1349 if (auto *SI = dyn_cast<SelectInst>(Select))
1351 return Select;
1352}
1353
1354// Helper to generate an ordered reduction.
1356 unsigned Op, RecurKind RdxKind) {
1357 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
1358
1359 // Extract and apply reduction ops in ascending order:
1360 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
1361 Value *Result = Acc;
1362 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
1363 Value *Ext =
1364 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
1365
1366 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1367 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
1368 "bin.rdx");
1369 } else {
1371 "Invalid min/max");
1372 Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
1373 }
1374 }
1375
1376 return Result;
1377}
1378
1380 unsigned RdxOpcode, Value *Acc,
1381 DominatorTree *DT, LoopInfo *LI) {
1382 auto *VTy = cast<VectorType>(Vec->getType());
1383 Type *EltTy = VTy->getElementType();
1384 Function *F = Builder.GetInsertBlock()->getParent();
1385
1386 const DataLayout &DL = F->getDataLayout();
1387 Type *IdxTy = DL.getIndexType(EltTy->getContext(), 0);
1388 unsigned MinElts = VTy->getElementCount().getKnownMinValue();
1389 Value *NumElts = Builder.CreateVScale(IdxTy);
1390 NumElts = Builder.CreateMul(NumElts, ConstantInt::get(IdxTy, MinElts));
1391
1392 BasicBlock *EntryBB = Builder.GetInsertBlock();
1393 BasicBlock *LoopBB = BasicBlock::Create(F->getContext(), "rdx.loop", F);
1394 BasicBlock *ExitBB = SplitBlock(EntryBB, Builder.GetInsertPoint(), DT, LI,
1395 nullptr, "rdx.exit");
1396
1397 EntryBB->getTerminator()->eraseFromParent();
1398 Builder.SetInsertPoint(EntryBB);
1399 Builder.CreateBr(LoopBB);
1400
1401 Builder.SetInsertPoint(LoopBB);
1402 PHINode *IV = Builder.CreatePHI(IdxTy, 2, "rdx.iv");
1403 PHINode *AccPhi = Builder.CreatePHI(EltTy, 2, "rdx.acc");
1404 IV->addIncoming(ConstantInt::get(IdxTy, 0), EntryBB);
1405 AccPhi->addIncoming(Acc, EntryBB);
1406
1407 Value *Elt = Builder.CreateExtractElement(Vec, IV);
1408 Value *Res = Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, AccPhi,
1409 Elt, "rdx.op");
1410
1411 Value *NextIV =
1412 Builder.CreateNUWAdd(IV, ConstantInt::get(IdxTy, 1), "rdx.next");
1413 IV->addIncoming(NextIV, LoopBB);
1414 AccPhi->addIncoming(Res, LoopBB);
1415
1416 Value *Done = Builder.CreateICmpEQ(NextIV, NumElts, "rdx.done");
1417 Builder.CreateCondBr(Done, ExitBB, LoopBB);
1418
1419 // SplitBlock above updated DT/LI for EntryBB -> ExitBB. Now update
1420 // for replacing that edge with EntryBB -> LoopBB -> {ExitBB, LoopBB}.
1421 if (DT)
1422 DT->applyUpdates({{DominatorTree::Insert, EntryBB, LoopBB},
1423 {DominatorTree::Insert, LoopBB, LoopBB},
1424 {DominatorTree::Insert, LoopBB, ExitBB},
1425 {DominatorTree::Delete, EntryBB, ExitBB}});
1426
1427 if (LI) {
1428 Loop *NewLoop = LI->AllocateLoop();
1429 if (Loop *ParentLoop = LI->getLoopFor(EntryBB))
1430 ParentLoop->addChildLoop(NewLoop);
1431 else
1432 LI->addTopLevelLoop(NewLoop);
1433 NewLoop->addBasicBlockToLoop(LoopBB, *LI);
1434 }
1435
1436 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1437 return Res;
1438}
1439
1440// Helper to generate a log2 shuffle reduction.
1442 unsigned Op,
1444 RecurKind RdxKind) {
1445 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
1446 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1447 // and vector ops, reducing the set of values being computed by half each
1448 // round.
1449 assert(isPowerOf2_32(VF) &&
1450 "Reduction emission only supported for pow2 vectors!");
1451 // Note: fast-math-flags flags are controlled by the builder configuration
1452 // and are assumed to apply to all generated arithmetic instructions. Other
1453 // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
1454 // of the builder configuration, and since they're not passed explicitly,
1455 // will never be relevant here. Note that it would be generally unsound to
1456 // propagate these from an intrinsic call to the expansion anyways as we/
1457 // change the order of operations.
1458 auto BuildShuffledOp = [&Builder, &Op,
1459 &RdxKind](SmallVectorImpl<int> &ShuffleMask,
1460 Value *&TmpVec) -> void {
1461 Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
1462 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1463 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
1464 "bin.rdx");
1465 } else {
1467 "Invalid min/max");
1468 TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
1469 }
1470 };
1471
1472 Value *TmpVec = Src;
1474 SmallVector<int, 32> ShuffleMask(VF);
1475 for (unsigned stride = 1; stride < VF; stride <<= 1) {
1476 // Initialise the mask with undef.
1477 llvm::fill(ShuffleMask, -1);
1478 for (unsigned j = 0; j < VF; j += stride << 1) {
1479 ShuffleMask[j] = j + stride;
1480 }
1481 BuildShuffledOp(ShuffleMask, TmpVec);
1482 }
1483 } else {
1484 SmallVector<int, 32> ShuffleMask(VF);
1485 for (unsigned i = VF; i != 1; i >>= 1) {
1486 // Move the upper half of the vector to the lower half.
1487 for (unsigned j = 0; j != i / 2; ++j)
1488 ShuffleMask[j] = i / 2 + j;
1489
1490 // Fill the rest of the mask with undef.
1491 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
1492 BuildShuffledOp(ShuffleMask, TmpVec);
1493 }
1494 }
1495 // The result is in the first element of the vector.
1496 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1497}
1498
1500 Value *InitVal, PHINode *OrigPhi) {
1501 Value *NewVal = nullptr;
1502
1503 // First use the original phi to determine the new value we're trying to
1504 // select from in the loop.
1505 SelectInst *SI = nullptr;
1506 for (auto *U : OrigPhi->users()) {
1507 if ((SI = dyn_cast<SelectInst>(U)))
1508 break;
1509 }
1510 assert(SI && "One user of the original phi should be a select");
1511
1512 if (SI->getTrueValue() == OrigPhi)
1513 NewVal = SI->getFalseValue();
1514 else {
1515 assert(SI->getFalseValue() == OrigPhi &&
1516 "At least one input to the select should be the original Phi");
1517 NewVal = SI->getTrueValue();
1518 }
1519
1520 // If any predicate is true it means that we want to select the new value.
1521 Value *AnyOf =
1522 Src->getType()->isVectorTy() ? Builder.CreateOrReduce(Src) : Src;
1523 // The compares in the loop may yield poison, which propagates through the
1524 // bitwise ORs. Freeze it here before the condition is used.
1525 AnyOf = Builder.CreateFreeze(AnyOf);
1526 return Builder.CreateSelect(AnyOf, NewVal, InitVal, "rdx.select");
1527}
1528
1530 FastMathFlags Flags) {
1531 bool Negative = false;
1532 switch (RdxID) {
1533 default:
1534 llvm_unreachable("Expecting a reduction intrinsic");
1535 case Intrinsic::vector_reduce_add:
1536 case Intrinsic::vector_reduce_mul:
1537 case Intrinsic::vector_reduce_or:
1538 case Intrinsic::vector_reduce_xor:
1539 case Intrinsic::vector_reduce_and:
1540 case Intrinsic::vector_reduce_fadd:
1541 case Intrinsic::vector_reduce_fmul: {
1542 unsigned Opc = getArithmeticReductionInstruction(RdxID);
1543 return ConstantExpr::getBinOpIdentity(Opc, Ty, false,
1544 Flags.noSignedZeros());
1545 }
1546 case Intrinsic::vector_reduce_umax:
1547 case Intrinsic::vector_reduce_umin:
1548 case Intrinsic::vector_reduce_smin:
1549 case Intrinsic::vector_reduce_smax: {
1551 return ConstantExpr::getIntrinsicIdentity(ScalarID, Ty);
1552 }
1553 case Intrinsic::vector_reduce_fmax:
1554 case Intrinsic::vector_reduce_fmaximum:
1555 Negative = true;
1556 [[fallthrough]];
1557 case Intrinsic::vector_reduce_fmin:
1558 case Intrinsic::vector_reduce_fminimum: {
1559 bool PropagatesNaN = RdxID == Intrinsic::vector_reduce_fminimum ||
1560 RdxID == Intrinsic::vector_reduce_fmaximum;
1561 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1562 return (!Flags.noNaNs() && !PropagatesNaN)
1563 ? ConstantFP::getQNaN(Ty, Negative)
1564 : !Flags.noInfs()
1565 ? ConstantFP::getInfinity(Ty, Negative)
1566 : ConstantFP::get(Ty, APFloat::getLargest(Semantics, Negative));
1567 }
1568 }
1569}
1570
1572 assert((!(K == RecurKind::FMin || K == RecurKind::FMax) ||
1573 (FMF.noNaNs() && FMF.noSignedZeros())) &&
1574 "nnan, nsz is expected to be set for FP min/max reduction.");
1576 return getReductionIdentity(RdxID, Tp, FMF);
1577}
1578
1580 RecurKind RdxKind) {
1581 auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
1582 auto getIdentity = [&]() {
1583 return getRecurrenceIdentity(RdxKind, SrcVecEltTy,
1584 Builder.getFastMathFlags());
1585 };
1586 switch (RdxKind) {
1588 case RecurKind::Sub:
1589 case RecurKind::Add:
1590 case RecurKind::Mul:
1591 case RecurKind::And:
1592 case RecurKind::Or:
1593 case RecurKind::Xor:
1594 case RecurKind::SMax:
1595 case RecurKind::SMin:
1596 case RecurKind::UMax:
1597 case RecurKind::UMin:
1598 case RecurKind::FMax:
1599 case RecurKind::FMin:
1600 case RecurKind::FMinNum:
1601 case RecurKind::FMaxNum:
1606 return Builder.CreateUnaryIntrinsic(getReductionIntrinsicID(RdxKind), Src);
1607 case RecurKind::FMulAdd:
1609 case RecurKind::FSub:
1610 case RecurKind::FAdd:
1611 return Builder.CreateFAddReduce(getIdentity(), Src);
1612 case RecurKind::FMul:
1613 return Builder.CreateFMulReduce(getIdentity(), Src);
1614 default:
1615 llvm_unreachable("Unhandled opcode");
1616 }
1617}
1618
1620 RecurKind Kind, Value *Mask, Value *EVL) {
1623 "AnyOf and FindIV reductions are not supported.");
1625 auto VPID = VPIntrinsic::getForIntrinsic(Id);
1627 "No VPIntrinsic for this reduction");
1628 auto *EltTy = cast<VectorType>(Src->getType())->getElementType();
1629 Value *Iden = getRecurrenceIdentity(Kind, EltTy, Builder.getFastMathFlags());
1630 Value *Ops[] = {Iden, Src, Mask, EVL};
1631 return Builder.CreateIntrinsic(EltTy, VPID, Ops);
1632}
1633
1635 Value *Src, Value *Start) {
1636 assert((Kind == RecurKind::FAdd || Kind == RecurKind::FMulAdd) &&
1637 "Unexpected reduction kind");
1638 assert(Src->getType()->isVectorTy() && "Expected a vector type");
1639 assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1640
1641 return B.CreateFAddReduce(Start, Src);
1642}
1643
1645 Value *Src, Value *Start, Value *Mask,
1646 Value *EVL) {
1647 assert((Kind == RecurKind::FAdd || Kind == RecurKind::FMulAdd) &&
1648 "Unexpected reduction kind");
1649 assert(Src->getType()->isVectorTy() && "Expected a vector type");
1650 assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1651
1653 auto VPID = VPIntrinsic::getForIntrinsic(Id);
1655 "No VPIntrinsic for this reduction");
1656 auto *EltTy = cast<VectorType>(Src->getType())->getElementType();
1657 Value *Ops[] = {Start, Src, Mask, EVL};
1658 return Builder.CreateIntrinsic(EltTy, VPID, Ops);
1659}
1660
1662 bool IncludeWrapFlags) {
1663 auto *VecOp = dyn_cast<Instruction>(I);
1664 if (!VecOp)
1665 return;
1666 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1667 : dyn_cast<Instruction>(OpValue);
1668 if (!Intersection)
1669 return;
1670 const unsigned Opcode = Intersection->getOpcode();
1671 VecOp->copyIRFlags(Intersection, IncludeWrapFlags);
1672 for (auto *V : VL) {
1673 auto *Instr = dyn_cast<Instruction>(V);
1674 if (!Instr)
1675 continue;
1676 if (OpValue == nullptr || Opcode == Instr->getOpcode())
1677 VecOp->andIRFlags(V);
1678 }
1679}
1680
1681bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1682 ScalarEvolution &SE) {
1683 const SCEV *Zero = SE.getZero(S->getType());
1684 return SE.isAvailableAtLoopEntry(S, L) &&
1686}
1687
1689 ScalarEvolution &SE) {
1690 const SCEV *Zero = SE.getZero(S->getType());
1691 return SE.isAvailableAtLoopEntry(S, L) &&
1693}
1694
1695bool llvm::isKnownPositiveInLoop(const SCEV *S, const Loop *L,
1696 ScalarEvolution &SE) {
1697 const SCEV *Zero = SE.getZero(S->getType());
1698 return SE.isAvailableAtLoopEntry(S, L) &&
1700}
1701
1703 ScalarEvolution &SE) {
1704 const SCEV *Zero = SE.getZero(S->getType());
1705 return SE.isAvailableAtLoopEntry(S, L) &&
1707}
1708
1710 bool Signed) {
1711 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1714 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1715 return SE.isAvailableAtLoopEntry(S, L) &&
1716 SE.isLoopEntryGuardedByCond(L, Predicate, S,
1717 SE.getConstant(Min));
1718}
1719
1721 bool Signed) {
1722 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1725 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1726 return SE.isAvailableAtLoopEntry(S, L) &&
1727 SE.isLoopEntryGuardedByCond(L, Predicate, S,
1728 SE.getConstant(Max));
1729}
1730
1731//===----------------------------------------------------------------------===//
1732// rewriteLoopExitValues - Optimize IV users outside the loop.
1733// As a side effect, reduces the amount of IV processing within the loop.
1734//===----------------------------------------------------------------------===//
1735
1736static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1739 Visited.insert(I);
1740 WorkList.push_back(I);
1741 while (!WorkList.empty()) {
1742 const Instruction *Curr = WorkList.pop_back_val();
1743 // This use is outside the loop, nothing to do.
1744 if (!L->contains(Curr))
1745 continue;
1746 // Do we assume it is a "hard" use which will not be eliminated easily?
1747 if (Curr->mayHaveSideEffects())
1748 return true;
1749 // Otherwise, add all its users to worklist.
1750 for (const auto *U : Curr->users()) {
1751 auto *UI = cast<Instruction>(U);
1752 if (Visited.insert(UI).second)
1753 WorkList.push_back(UI);
1754 }
1755 }
1756 return false;
1757}
1758
1759// Collect information about PHI nodes which can be transformed in
1760// rewriteLoopExitValues.
1762 PHINode *PN; // For which PHI node is this replacement?
1763 unsigned Ith; // For which incoming value?
1764 const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1765 Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1766 bool HighCost; // Is this expansion a high-cost?
1767
1768 RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1769 bool H)
1770 : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1771 HighCost(H) {}
1772};
1773
1774// Check whether it is possible to delete the loop after rewriting exit
1775// value. If it is possible, ignore ReplaceExitValue and do rewriting
1776// aggressively.
1777static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
1778 BasicBlock *Preheader = L->getLoopPreheader();
1779 // If there is no preheader, the loop will not be deleted.
1780 if (!Preheader)
1781 return false;
1782
1783 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1784 // We obviate multiple ExitingBlocks case for simplicity.
1785 // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1786 // after exit value rewriting, we can enhance the logic here.
1787 SmallVector<BasicBlock *, 4> ExitingBlocks;
1788 L->getExitingBlocks(ExitingBlocks);
1790 L->getUniqueExitBlocks(ExitBlocks);
1791 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1792 return false;
1793
1794 BasicBlock *ExitBlock = ExitBlocks[0];
1795 BasicBlock::iterator BI = ExitBlock->begin();
1796 while (PHINode *P = dyn_cast<PHINode>(BI)) {
1797 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
1798
1799 // If the Incoming value of P is found in RewritePhiSet, we know it
1800 // could be rewritten to use a loop invariant value in transformation
1801 // phase later. Skip it in the loop invariant check below.
1802 bool found = false;
1803 for (const RewritePhi &Phi : RewritePhiSet) {
1804 unsigned i = Phi.Ith;
1805 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1806 found = true;
1807 break;
1808 }
1809 }
1810
1811 Instruction *I;
1812 if (!found && (I = dyn_cast<Instruction>(Incoming)))
1813 if (!L->hasLoopInvariantOperands(I))
1814 return false;
1815
1816 ++BI;
1817 }
1818
1819 for (auto *BB : L->blocks())
1820 if (llvm::any_of(*BB, [](Instruction &I) {
1821 return I.mayHaveSideEffects();
1822 }))
1823 return false;
1824
1825 return true;
1826}
1827
1828/// Checks if it is safe to call InductionDescriptor::isInductionPHI for \p Phi,
1829/// and returns true if this Phi is an induction phi in the loop. When
1830/// isInductionPHI returns true, \p ID will be also be set by isInductionPHI.
1831static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE,
1832 InductionDescriptor &ID) {
1833 if (!Phi)
1834 return false;
1835 if (!L->getLoopPreheader())
1836 return false;
1837 if (Phi->getParent() != L->getHeader())
1838 return false;
1839 return InductionDescriptor::isInductionPHI(Phi, L, SE, ID);
1840}
1841
1843 ScalarEvolution *SE,
1844 const TargetTransformInfo *TTI,
1845 SCEVExpander &Rewriter, DominatorTree *DT,
1848 // Check a pre-condition.
1849 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1850 "Caller did not preserve LCSSA!");
1851
1852 SmallVector<BasicBlock*, 8> ExitBlocks;
1853 L->getUniqueExitBlocks(ExitBlocks);
1854
1855 SmallVector<RewritePhi, 8> RewritePhiSet;
1856 // Find all values that are computed inside the loop, but used outside of it.
1857 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
1858 // the exit blocks of the loop to find them.
1859 for (BasicBlock *ExitBB : ExitBlocks) {
1860 // If there are no PHI nodes in this exit block, then no values defined
1861 // inside the loop are used on this path, skip it.
1862 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
1863 if (!PN) continue;
1864
1865 unsigned NumPreds = PN->getNumIncomingValues();
1866
1867 // Iterate over all of the PHI nodes.
1868 BasicBlock::iterator BBI = ExitBB->begin();
1869 while ((PN = dyn_cast<PHINode>(BBI++))) {
1870 if (PN->use_empty())
1871 continue; // dead use, don't replace it
1872
1873 if (!SE->isSCEVable(PN->getType()))
1874 continue;
1875
1876 // Iterate over all of the values in all the PHI nodes.
1877 for (unsigned i = 0; i != NumPreds; ++i) {
1878 // If the value being merged in is not integer or is not defined
1879 // in the loop, skip it.
1880 Value *InVal = PN->getIncomingValue(i);
1881 if (!isa<Instruction>(InVal))
1882 continue;
1883
1884 // If this pred is for a subloop, not L itself, skip it.
1885 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
1886 continue; // The Block is in a subloop, skip it.
1887
1888 // Check that InVal is defined in the loop.
1889 Instruction *Inst = cast<Instruction>(InVal);
1890 if (!L->contains(Inst))
1891 continue;
1892
1893 // Find exit values which are induction variables in the loop, and are
1894 // unused in the loop, with the only use being the exit block PhiNode,
1895 // and the induction variable update binary operator.
1896 // The exit value can be replaced with the final value when it is cheap
1897 // to do so.
1900 PHINode *IndPhi = dyn_cast<PHINode>(Inst);
1901 if (IndPhi) {
1902 if (!checkIsIndPhi(IndPhi, L, SE, ID))
1903 continue;
1904 // This is an induction PHI. Check that the only users are PHI
1905 // nodes, and induction variable update binary operators.
1906 if (llvm::any_of(Inst->users(), [&](User *U) {
1907 if (!isa<PHINode>(U) && !isa<BinaryOperator>(U))
1908 return true;
1909 BinaryOperator *B = dyn_cast<BinaryOperator>(U);
1910 if (B && B != ID.getInductionBinOp())
1911 return true;
1912 return false;
1913 }))
1914 continue;
1915 } else {
1916 // If it is not an induction phi, it must be an induction update
1917 // binary operator with an induction phi user.
1919 if (!B)
1920 continue;
1921 if (llvm::any_of(Inst->users(), [&](User *U) {
1922 PHINode *Phi = dyn_cast<PHINode>(U);
1923 if (Phi != PN && !checkIsIndPhi(Phi, L, SE, ID))
1924 return true;
1925 return false;
1926 }))
1927 continue;
1928 if (B != ID.getInductionBinOp())
1929 continue;
1930 }
1931 }
1932
1933 // Okay, this instruction has a user outside of the current loop
1934 // and varies predictably *inside* the loop. Evaluate the value it
1935 // contains when the loop exits, if possible. We prefer to start with
1936 // expressions which are true for all exits (so as to maximize
1937 // expression reuse by the SCEVExpander), but resort to per-exit
1938 // evaluation if that fails.
1939 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
1940 if (isa<SCEVCouldNotCompute>(ExitValue) ||
1941 !SE->isLoopInvariant(ExitValue, L) ||
1942 !Rewriter.isSafeToExpand(ExitValue)) {
1943 // TODO: This should probably be sunk into SCEV in some way; maybe a
1944 // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for
1945 // most SCEV expressions and other recurrence types (e.g. shift
1946 // recurrences). Is there existing code we can reuse?
1947 const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
1948 if (isa<SCEVCouldNotCompute>(ExitCount))
1949 continue;
1950 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
1951 if (AddRec->getLoop() == L)
1952 ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
1953 if (isa<SCEVCouldNotCompute>(ExitValue) ||
1954 !SE->isLoopInvariant(ExitValue, L) ||
1955 !Rewriter.isSafeToExpand(ExitValue))
1956 continue;
1957 }
1958
1959 // Computing the value outside of the loop brings no benefit if it is
1960 // definitely used inside the loop in a way which can not be optimized
1961 // away. Avoid doing so unless we know we have a value which computes
1962 // the ExitValue already. TODO: This should be merged into SCEV
1963 // expander to leverage its knowledge of existing expressions.
1964 if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
1965 !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
1966 continue;
1967
1968 // Check if expansions of this SCEV would count as being high cost.
1969 bool HighCost = Rewriter.isHighCostExpansion(
1970 ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1971
1972 // Note that we must not perform expansions until after
1973 // we query *all* the costs, because if we perform temporary expansion
1974 // inbetween, one that we might not intend to keep, said expansion
1975 // *may* affect cost calculation of the next SCEV's we'll query,
1976 // and next SCEV may errneously get smaller cost.
1977
1978 // Collect all the candidate PHINodes to be rewritten.
1979 Instruction *InsertPt =
1980 (isa<PHINode>(Inst) || isa<LandingPadInst>(Inst)) ?
1981 &*Inst->getParent()->getFirstInsertionPt() : Inst;
1982 RewritePhiSet.emplace_back(PN, i, ExitValue, InsertPt, HighCost);
1983 }
1984 }
1985 }
1986
1987 // TODO: evaluate whether it is beneficial to change how we calculate
1988 // high-cost: if we have SCEV 'A' which we know we will expand, should we
1989 // calculate the cost of other SCEV's after expanding SCEV 'A', thus
1990 // potentially giving cost bonus to those other SCEV's?
1991
1992 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
1993 int NumReplaced = 0;
1994
1995 // Transformation.
1996 for (const RewritePhi &Phi : RewritePhiSet) {
1997 PHINode *PN = Phi.PN;
1998
1999 // Only do the rewrite when the ExitValue can be expanded cheaply.
2000 // If LoopCanBeDel is true, rewrite exit value aggressively.
2003 !LoopCanBeDel && Phi.HighCost)
2004 continue;
2005
2006 Value *ExitVal = Rewriter.expandCodeFor(
2007 Phi.ExpansionSCEV, Phi.PN->getType(), Phi.ExpansionPoint);
2008
2009 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
2010 << '\n'
2011 << " LoopVal = " << *(Phi.ExpansionPoint) << "\n");
2012
2013#ifndef NDEBUG
2014 // If we reuse an instruction from a loop which is neither L nor one of
2015 // its containing loops, we end up breaking LCSSA form for this loop by
2016 // creating a new use of its instruction.
2017 if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
2018 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
2019 if (EVL != L)
2020 assert(EVL->contains(L) && "LCSSA breach detected!");
2021#endif
2022
2023 NumReplaced++;
2024 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
2025 PN->setIncomingValue(Phi.Ith, ExitVal);
2026 // It's necessary to tell ScalarEvolution about this explicitly so that
2027 // it can walk the def-use list and forget all SCEVs, as it may not be
2028 // watching the PHI itself. Once the new exit value is in place, there
2029 // may not be a def-use connection between the loop and every instruction
2030 // which got a SCEVAddRecExpr for that loop.
2031 SE->forgetValue(PN);
2032
2033 // If this instruction is dead now, delete it. Don't do it now to avoid
2034 // invalidating iterators.
2035 if (isInstructionTriviallyDead(Inst, TLI))
2036 DeadInsts.push_back(Inst);
2037
2038 // Replace PN with ExitVal if that is legal and does not break LCSSA.
2039 if (PN->getNumIncomingValues() == 1 &&
2040 LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
2041 PN->replaceAllUsesWith(ExitVal);
2042 PN->eraseFromParent();
2043 }
2044 }
2045
2046 // The insertion point instruction may have been deleted; clear it out
2047 // so that the rewriter doesn't trip over it later.
2048 Rewriter.clearInsertPoint();
2049 return NumReplaced;
2050}
2051
2052/// Utility that implements appending of loops onto a worklist.
2053/// Loops are added in preorder (analogous for reverse postorder for trees),
2054/// and the worklist is processed LIFO.
2055template <typename RangeT>
2057 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
2058 // We use an internal worklist to build up the preorder traversal without
2059 // recursion.
2060 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
2061
2062 // We walk the initial sequence of loops in reverse because we generally want
2063 // to visit defs before uses and the worklist is LIFO.
2064 for (Loop *RootL : Loops) {
2065 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
2066 assert(PreOrderWorklist.empty() &&
2067 "Must start with an empty preorder walk worklist.");
2068 PreOrderWorklist.push_back(RootL);
2069 do {
2070 Loop *L = PreOrderWorklist.pop_back_val();
2071 PreOrderWorklist.append(L->begin(), L->end());
2072 PreOrderLoops.push_back(L);
2073 } while (!PreOrderWorklist.empty());
2074
2075 Worklist.insert(std::move(PreOrderLoops));
2076 PreOrderLoops.clear();
2077 }
2078}
2079
2080template <typename RangeT>
2084}
2085
2086template LLVM_EXPORT_TEMPLATE void
2089
2090template LLVM_EXPORT_TEMPLATE void
2093
2098
2100 LoopInfo *LI, LPPassManager *LPM) {
2101 Loop &New = *LI->AllocateLoop();
2102 if (PL)
2103 PL->addChildLoop(&New);
2104 else
2105 LI->addTopLevelLoop(&New);
2106
2107 if (LPM)
2108 LPM->addLoop(New);
2109
2110 // Add all of the blocks in L to the new loop.
2111 for (BasicBlock *BB : L->blocks())
2112 if (LI->getLoopFor(BB) == L)
2113 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI);
2114
2115 // Add all of the subloops to the new loop.
2116 for (Loop *I : *L)
2117 cloneLoop(I, &New, VM, LI, LPM);
2118
2119 return &New;
2120}
2121
2122/// IR Values for the lower and upper bounds of a pointer evolution. We
2123/// need to use value-handles because SCEV expansion can invalidate previously
2124/// expanded values. Thus expansion of a pointer can invalidate the bounds for
2125/// a previous one.
2131
2132/// Expand code for the lower and upper bound of the pointer group \p CG
2133/// in \p TheLoop. \return the values for the bounds.
2135 Loop *TheLoop, Instruction *Loc,
2136 SCEVExpander &Exp, bool HoistRuntimeChecks) {
2137 LLVMContext &Ctx = Loc->getContext();
2138 Type *PtrArithTy = PointerType::get(Ctx, CG->AddressSpace);
2139
2140 Value *Start = nullptr, *End = nullptr;
2141 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
2142 const SCEV *Low = CG->Low, *High = CG->High, *Stride = nullptr;
2143
2144 // If the Low and High values are themselves loop-variant, then we may want
2145 // to expand the range to include those covered by the outer loop as well.
2146 // There is a trade-off here with the advantage being that creating checks
2147 // using the expanded range permits the runtime memory checks to be hoisted
2148 // out of the outer loop. This reduces the cost of entering the inner loop,
2149 // which can be significant for low trip counts. The disadvantage is that
2150 // there is a chance we may now never enter the vectorized inner loop,
2151 // whereas using a restricted range check could have allowed us to enter at
2152 // least once. This is why the behaviour is not currently the default and is
2153 // controlled by the parameter 'HoistRuntimeChecks'.
2154 if (HoistRuntimeChecks && TheLoop->getParentLoop() &&
2156 auto *HighAR = cast<SCEVAddRecExpr>(High);
2157 auto *LowAR = cast<SCEVAddRecExpr>(Low);
2158 const Loop *OuterLoop = TheLoop->getParentLoop();
2159 ScalarEvolution &SE = *Exp.getSE();
2160 const SCEV *Recur = LowAR->getStepRecurrence(SE);
2161 if (Recur == HighAR->getStepRecurrence(SE) &&
2162 HighAR->getLoop() == OuterLoop && LowAR->getLoop() == OuterLoop) {
2163 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2164 const SCEV *OuterExitCount = SE.getExitCount(OuterLoop, OuterLoopLatch);
2165 if (!isa<SCEVCouldNotCompute>(OuterExitCount) &&
2166 OuterExitCount->getType()->isIntegerTy()) {
2167 const SCEV *NewHigh =
2168 cast<SCEVAddRecExpr>(High)->evaluateAtIteration(OuterExitCount, SE);
2169 if (!isa<SCEVCouldNotCompute>(NewHigh)) {
2170 LLVM_DEBUG(dbgs() << "LAA: Expanded RT check for range to include "
2171 "outer loop in order to permit hoisting\n");
2172 High = NewHigh;
2173 Low = cast<SCEVAddRecExpr>(Low)->getStart();
2174 // If there is a possibility that the stride is negative then we have
2175 // to generate extra checks to ensure the stride is positive.
2176 if (!SE.isKnownNonNegative(
2177 SE.applyLoopGuards(Recur, HighAR->getLoop()))) {
2178 Stride = Recur;
2179 LLVM_DEBUG(dbgs() << "LAA: ... but need to check stride is "
2180 "positive: "
2181 << *Stride << '\n');
2182 }
2183 }
2184 }
2185 }
2186 }
2187
2188 Start = Exp.expandCodeFor(Low, PtrArithTy, Loc);
2189 End = Exp.expandCodeFor(High, PtrArithTy, Loc);
2190 if (CG->NeedsFreeze) {
2191 IRBuilder<> Builder(Loc);
2192 Start = Builder.CreateFreeze(Start, Start->getName() + ".fr");
2193 End = Builder.CreateFreeze(End, End->getName() + ".fr");
2194 }
2195 Value *StrideVal =
2196 Stride ? Exp.expandCodeFor(Stride, Stride->getType(), Loc) : nullptr;
2197 LLVM_DEBUG(dbgs() << "Start: " << *Low << " End: " << *High << "\n");
2198 return {Start, End, StrideVal};
2199}
2200
2201/// Turns a collection of checks into a collection of expanded upper and
2202/// lower bounds for both pointers in the check.
2207
2208 // Here we're relying on the SCEV Expander's cache to only emit code for the
2209 // same bounds once.
2210 transform(PointerChecks, std::back_inserter(ChecksWithBounds),
2211 [&](const RuntimePointerCheck &Check) {
2212 PointerBounds First = expandBounds(Check.first, L, Loc, Exp,
2214 Second = expandBounds(Check.second, L, Loc, Exp,
2216 return std::make_pair(First, Second);
2217 });
2218
2219 return ChecksWithBounds;
2220}
2221
2223 Instruction *Loc, Loop *TheLoop,
2224 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
2225 SCEVExpander &Exp, bool HoistRuntimeChecks) {
2226 // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
2227 // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible
2228 auto ExpandedChecks =
2229 expandBounds(PointerChecks, TheLoop, Loc, Exp, HoistRuntimeChecks);
2230
2231 LLVMContext &Ctx = Loc->getContext();
2232 IRBuilder ChkBuilder(Ctx, InstSimplifyFolder(Loc->getDataLayout()));
2233 ChkBuilder.SetInsertPoint(Loc);
2234 // Our instructions might fold to a constant.
2235 Value *MemoryRuntimeCheck = nullptr;
2236
2237 for (const auto &[A, B] : ExpandedChecks) {
2238 // Check if two pointers (A and B) conflict where conflict is computed as:
2239 // start(A) <= end(B) && start(B) <= end(A)
2240
2241 assert((A.Start->getType()->getPointerAddressSpace() ==
2242 B.End->getType()->getPointerAddressSpace()) &&
2243 (B.Start->getType()->getPointerAddressSpace() ==
2244 A.End->getType()->getPointerAddressSpace()) &&
2245 "Trying to bounds check pointers with different address spaces");
2246
2247 // [A|B].Start points to the first accessed byte under base [A|B].
2248 // [A|B].End points to the last accessed byte, plus one.
2249 // There is no conflict when the intervals are disjoint:
2250 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
2251 //
2252 // bound0 = (B.Start < A.End)
2253 // bound1 = (A.Start < B.End)
2254 // IsConflict = bound0 & bound1
2255 Value *Cmp0 = ChkBuilder.CreateICmpULT(A.Start, B.End, "bound0");
2256 Value *Cmp1 = ChkBuilder.CreateICmpULT(B.Start, A.End, "bound1");
2257 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2258 if (A.StrideToCheck) {
2259 Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
2260 A.StrideToCheck, ConstantInt::get(A.StrideToCheck->getType(), 0),
2261 "stride.check");
2262 IsConflict = ChkBuilder.CreateOr(IsConflict, IsNegativeStride);
2263 }
2264 if (B.StrideToCheck) {
2265 Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
2266 B.StrideToCheck, ConstantInt::get(B.StrideToCheck->getType(), 0),
2267 "stride.check");
2268 IsConflict = ChkBuilder.CreateOr(IsConflict, IsNegativeStride);
2269 }
2270 if (MemoryRuntimeCheck) {
2271 IsConflict =
2272 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
2273 }
2274 MemoryRuntimeCheck = IsConflict;
2275 }
2276
2277 Exp.eraseDeadInstructions(MemoryRuntimeCheck);
2278 return MemoryRuntimeCheck;
2279}
2280
2283 function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC) {
2284
2285 LLVMContext &Ctx = Loc->getContext();
2286 IRBuilder ChkBuilder(Ctx, InstSimplifyFolder(Loc->getDataLayout()));
2287 ChkBuilder.SetInsertPoint(Loc);
2288 // Our instructions might fold to a constant.
2289 Value *MemoryRuntimeCheck = nullptr;
2290
2291 auto &SE = *Expander.getSE();
2292 // Map to keep track of created compares, The key is the pair of operands for
2293 // the compare, to allow detecting and re-using redundant compares.
2295 // Cache of (VF * IC * AccessSize) - 1, shared across checks with matching
2296 // type and IC*AccessSize to avoid emitting duplicate runtime computations.
2298 for (const auto &[SrcStart, SinkStart, AccessSize, NeedsFreeze] : Checks) {
2299 assert(IC * AccessSize > 0 &&
2300 "Threshold must be non-zero to use diff-check");
2301 Type *Ty = SinkStart->getType();
2302 unsigned ICTimesAccessSize = IC * AccessSize;
2303 Value *One = ConstantInt::get(Ty, 1);
2304 Value *&ThresholdMinusOne = ThresholdCache[{Ty, ICTimesAccessSize}];
2305 if (!ThresholdMinusOne) {
2306 Value *VFTimesICTimesSize =
2307 ChkBuilder.CreateMul(GetVF(ChkBuilder, Ty->getScalarSizeInBits()),
2308 ConstantInt::get(Ty, ICTimesAccessSize));
2309 ThresholdMinusOne = ChkBuilder.CreateSub(VFTimesICTimesSize, One);
2310 }
2311 Value *Diff =
2312 Expander.expandCodeFor(SE.getMinusSCEV(SinkStart, SrcStart), Ty, Loc);
2313
2314 // Check if the same compare has already been created earlier. In that case,
2315 // there is no need to check it again.
2316 Value *IsConflict = SeenCompares.lookup({Diff, ThresholdMinusOne});
2317 if (IsConflict)
2318 continue;
2319
2320 // Use (Diff - 1) <u (Threshold - 1), equivalent to 0 < Diff <u Threshold,
2321 // to exclude Diff == 0 (equal pointers are safe).
2322 IsConflict = ChkBuilder.CreateICmpULT(ChkBuilder.CreateSub(Diff, One),
2323 ThresholdMinusOne, "diff.check");
2324 SeenCompares.insert({{Diff, ThresholdMinusOne}, IsConflict});
2325 if (NeedsFreeze)
2326 IsConflict =
2327 ChkBuilder.CreateFreeze(IsConflict, IsConflict->getName() + ".fr");
2328 if (MemoryRuntimeCheck) {
2329 IsConflict =
2330 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
2331 }
2332 MemoryRuntimeCheck = IsConflict;
2333 }
2334
2335 Expander.eraseDeadInstructions(MemoryRuntimeCheck);
2336 return MemoryRuntimeCheck;
2337}
2338
2339std::optional<IVConditionInfo>
2341 const MemorySSA &MSSA, AAResults &AA) {
2342 auto *TI = dyn_cast<CondBrInst>(L.getHeader()->getTerminator());
2343 if (!TI)
2344 return {};
2345
2346 auto *CondI = dyn_cast<Instruction>(TI->getCondition());
2347 // The case with the condition outside the loop should already be handled
2348 // earlier.
2349 // Allow CmpInst and TruncInsts as they may be users of load instructions
2350 // and have potential for partial unswitching
2351 if (!CondI || !isa<CmpInst, TruncInst>(CondI) || !L.contains(CondI))
2352 return {};
2353
2354 SmallVector<Instruction *> InstToDuplicate;
2355 InstToDuplicate.push_back(CondI);
2356
2357 SmallVector<Value *, 4> WorkList;
2358 WorkList.append(CondI->op_begin(), CondI->op_end());
2359
2360 SmallVector<MemoryAccess *, 4> AccessesToCheck;
2361 SmallVector<MemoryLocation, 4> AccessedLocs;
2362 while (!WorkList.empty()) {
2364 if (!I || !L.contains(I))
2365 continue;
2366
2367 // TODO: support additional instructions.
2369 return {};
2370
2371 // Do not duplicate volatile and atomic loads.
2372 if (auto *LI = dyn_cast<LoadInst>(I))
2373 if (LI->isVolatile() || LI->isAtomic())
2374 return {};
2375
2376 InstToDuplicate.push_back(I);
2377 if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
2378 if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
2379 // Queue the defining access to check for alias checks.
2380 AccessesToCheck.push_back(MemUse->getDefiningAccess());
2381 AccessedLocs.push_back(MemoryLocation::get(I));
2382 } else {
2383 // MemoryDefs may clobber the location or may be atomic memory
2384 // operations. Bail out.
2385 return {};
2386 }
2387 }
2388 WorkList.append(I->op_begin(), I->op_end());
2389 }
2390
2391 if (InstToDuplicate.empty())
2392 return {};
2393
2394 SmallVector<BasicBlock *, 4> ExitingBlocks;
2395 L.getExitingBlocks(ExitingBlocks);
2396 auto HasNoClobbersOnPath =
2397 [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
2398 MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
2399 SmallVector<MemoryAccess *, 4> AccessesToCheck)
2400 -> std::optional<IVConditionInfo> {
2401 IVConditionInfo Info;
2402 // First, collect all blocks in the loop that are on a patch from Succ
2403 // to the header.
2405 WorkList.push_back(Succ);
2406 WorkList.push_back(Header);
2408 Seen.insert(Header);
2409 Info.PathIsNoop &=
2410 all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); });
2411
2412 while (!WorkList.empty()) {
2413 BasicBlock *Current = WorkList.pop_back_val();
2414 if (!L.contains(Current))
2415 continue;
2416 const auto &SeenIns = Seen.insert(Current);
2417 if (!SeenIns.second)
2418 continue;
2419
2420 Info.PathIsNoop &= all_of(
2421 *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); });
2422 WorkList.append(succ_begin(Current), succ_end(Current));
2423 }
2424
2425 // Require at least 2 blocks on a path through the loop. This skips
2426 // paths that directly exit the loop.
2427 if (Seen.size() < 2)
2428 return {};
2429
2430 // Next, check if there are any MemoryDefs that are on the path through
2431 // the loop (in the Seen set) and they may-alias any of the locations in
2432 // AccessedLocs. If that is the case, they may modify the condition and
2433 // partial unswitching is not possible.
2434 SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
2435 while (!AccessesToCheck.empty()) {
2436 MemoryAccess *Current = AccessesToCheck.pop_back_val();
2437 auto SeenI = SeenAccesses.insert(Current);
2438 if (!SeenI.second || !Seen.contains(Current->getBlock()))
2439 continue;
2440
2441 // Bail out if exceeded the threshold.
2442 if (SeenAccesses.size() >= MSSAThreshold)
2443 return {};
2444
2445 // MemoryUse are read-only accesses.
2446 if (isa<MemoryUse>(Current))
2447 continue;
2448
2449 // For a MemoryDef, check if is aliases any of the location feeding
2450 // the original condition.
2451 if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
2452 if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) {
2453 return isModSet(
2454 AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc));
2455 }))
2456 return {};
2457 }
2458
2459 for (Use &U : Current->uses())
2460 AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
2461 }
2462
2463 // We could also allow loops with known trip counts without mustprogress,
2464 // but ScalarEvolution may not be available.
2465 Info.PathIsNoop &= isMustProgress(&L);
2466
2467 // If the path is considered a no-op so far, check if it reaches a
2468 // single exit block without any phis. This ensures no values from the
2469 // loop are used outside of the loop.
2470 if (Info.PathIsNoop) {
2471 for (auto *Exiting : ExitingBlocks) {
2472 if (!Seen.contains(Exiting))
2473 continue;
2474 for (auto *Succ : successors(Exiting)) {
2475 if (L.contains(Succ))
2476 continue;
2477
2478 Info.PathIsNoop &= Succ->phis().empty() &&
2479 (!Info.ExitForPath || Info.ExitForPath == Succ);
2480 if (!Info.PathIsNoop)
2481 break;
2482 assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
2483 "cannot have multiple exit blocks");
2484 Info.ExitForPath = Succ;
2485 }
2486 }
2487 }
2488 if (!Info.ExitForPath)
2489 Info.PathIsNoop = false;
2490
2491 Info.InstToDuplicate = std::move(InstToDuplicate);
2492 return Info;
2493 };
2494
2495 // If we branch to the same successor, partial unswitching will not be
2496 // beneficial.
2497 if (TI->getSuccessor(0) == TI->getSuccessor(1))
2498 return {};
2499
2500 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(),
2501 AccessesToCheck)) {
2502 Info->KnownValue = ConstantInt::getTrue(TI->getContext());
2503 return Info;
2504 }
2505 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(),
2506 AccessesToCheck)) {
2507 Info->KnownValue = ConstantInt::getFalse(TI->getContext());
2508 return Info;
2509 }
2510
2511 return {};
2512}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:217
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
static cl::opt< ReplaceExitVal > ReplaceExitValue("replexitval", cl::Hidden, cl::init(OnlyCheapRepl), cl::desc("Choose the strategy to replace exit value in IndVarSimplify"), cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"), clEnumValN(OnlyCheapRepl, "cheap", "only replace exit value when the cost is cheap"), clEnumValN(UnusedIndVarInLoop, "unusedindvarinloop", "only replace exit value when it is an unused " "induction variable in the loop and has cheap replacement cost"), clEnumValN(NoHardUse, "noharduse", "only replace exit values when loop def likely dead"), clEnumValN(AlwaysRepl, "always", "always replace exit value whenever possible")))
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:56
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:55
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...
#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.
const SmallVectorImpl< MachineOperand > & 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.
#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:1234
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:207
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
Represent the analysis usage information of a pass.
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
Definition Pass.cpp:289
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:446
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
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
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:250
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
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:315
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:114
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2391
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2728
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1439
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1570
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2407
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1592
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1456
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
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 unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
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.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
void addLoop(Loop &L)
Definition LoopPass.cpp:77
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:612
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:459
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:924
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:557
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition LoopInfo.cpp:533
Metadata node.
Definition Metadata.h:1069
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
LLVMContext & getContext() const
Definition Metadata.h:1233
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
A single uniqued string.
Definition Metadata.h:722
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:633
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
Tuple of metadata.
Definition Metadata.h:1484
BasicBlock * getBlock() const
Definition MemorySSA.h:162
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:975
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
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:720
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:911
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 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.
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.
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.
LLVM_ABI const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
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.
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.
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
size_type size() const
Definition SmallPtrSet.h:99
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:345
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:309
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
static LLVM_ABI Intrinsic::ID getForIntrinsic(Intrinsic::ID Id)
The llvm.vp.
static LLVM_ABI bool isVPReduction(Intrinsic::ID ID)
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
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:683
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:315
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 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:1765
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:1759
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
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:1739
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.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
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)
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.
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:633
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:459
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:2026
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:403
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:407
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.
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 TransformationMode hasDistributeTransformation(const Loop *L)
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:2552
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)
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
TransformationMode
The mode sets how eager a transformation should be applied.
Definition LoopUtils.h:283
@ TM_Unspecified
The pass can use heuristics to determine whether a transformation should be applied.
Definition LoopUtils.h:286
@ TM_SuppressedByUser
The transformation must not be applied.
Definition LoopUtils.h:306
@ TM_ForcedByUser
The transformation was directed by the user, e.g.
Definition LoopUtils.h:300
@ TM_Disable
The transformation should not be applied.
Definition LoopUtils.h:292
@ TM_Enable
The transformation should be applied without considering a cost model.
Definition LoopUtils.h:289
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.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ 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:61
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,...
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 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
static cl::opt< unsigned > MSSAThreshold("simple-loop-unswitch-memoryssa-threshold", cl::desc("Max number of memory uses to explore during " "partial unswitching analysis"), cl::init(100), cl::Hidden)
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,...
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 Value * addDiffRuntimeChecks(Instruction *Loc, ArrayRef< PointerDiffInfo > Checks, SCEVExpander &Expander, function_ref< Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC)
LLVM_ABI RecurKind getMinMaxReductionRecurKind(Intrinsic::ID RdxID)
Returns the recurence kind used when expanding a min/max reduction.
ReplaceExitVal
Definition LoopUtils.h:601
@ UnusedIndVarInLoop
Definition LoopUtils.h:605
@ OnlyCheapRepl
Definition LoopUtils.h:603
@ AlwaysRepl
Definition LoopUtils.h:606
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...
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 Value * createAnyOfReduction(IRBuilderBase &B, Value *Src, Value *InitVal, PHINode *OrigPhi)
Create a reduction of the given vector Src for a reduction of kind RecurKind::AnyOf.
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 * 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...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#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
unsigned Ith
RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt, bool H)
const SCEV * ExpansionSCEV
PHINode * PN
Instruction * ExpansionPoint
Struct to hold information about a partially invariant condition.
Definition LoopUtils.h:673
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.