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