LLVM 24.0.0git
Instruction.cpp
Go to the documentation of this file.
1//===-- Instruction.cpp - Implement the Instruction class -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Instruction class for the IR library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Instruction.h"
14#include "llvm/ADT/DenseSet.h"
15#include "llvm/ADT/STLExtras.h"
17#include "llvm/IR/Attributes.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/InstrTypes.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
28#include "llvm/IR/Type.h"
31using namespace llvm;
32
33namespace llvm {
34
35// FIXME: Flag used for an ablation performance test, Issue #147390. Placing it
36// here because referencing IR should be feasible from anywhere. Will be
37// removed after the ablation test.
39 "profcheck-disable-metadata-fixes", cl::Hidden, cl::init(false),
41 "Disable metadata propagation fixes discovered through Issue #147390"));
42
43} // end namespace llvm
44
46 : InsertAt(InsertAtEnd ? InsertAtEnd->end() : InstListType::iterator()) {}
47
48Instruction::Instruction(Type *ty, unsigned it, AllocInfo AllocInfo,
49 InsertPosition InsertBefore)
50 : User(ty, Value::InstructionVal + it, AllocInfo) {
51 // When called with an iterator, there must be a block to insert into.
52 if (InstListType::iterator InsertIt = InsertBefore; InsertIt.isValid()) {
53 BasicBlock *BB = InsertIt.getNodeParent();
54 assert(BB && "Instruction to insert before is not in a basic block!");
55 insertInto(BB, InsertBefore);
56 }
57}
58
60 assert(!getParent() && "Instruction still linked in the program!");
61
62 // Replace any extant metadata uses of this instruction with poison to
63 // preserve debug info accuracy. Some alternatives include:
64 // - Treat Instruction like any other Value, and point its extant metadata
65 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses
66 // trivially dead (i.e. fair game for deletion in many passes), leading to
67 // stale dbg.values being in effect for too long.
68 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal
69 // correct. OTOH results in wasted work in some common cases (e.g. when all
70 // instructions in a BasicBlock are deleted).
71 if (isUsedByMetadata())
73
74 // Remove associated metadata from context.
75 if (hasMetadata()) {
76 // Explicitly remove DIAssignID metadata to clear up ID -> Instruction(s)
77 // mapping in LLVMContext.
78 updateDIAssignIDMapping(nullptr);
79 clearMetadata();
80 }
81}
82
83const Module *Instruction::getModule() const {
84 return getParent()->getModule();
85}
86
88 return getParent()->getParent();
89}
90
92 return getModule()->getDataLayout();
93}
94
96 // Perform any debug-info maintenence required.
97 handleMarkerRemoval();
98
99 getParent()->getInstList().remove(getIterator());
100}
101
103 if (!DebugMarker)
104 return;
105
106 DebugMarker->removeMarker();
107}
108
110 handleMarkerRemoval();
111 return getParent()->getInstList().erase(getIterator());
112}
113
114void Instruction::insertBefore(Instruction *InsertPos) {
115 insertBefore(InsertPos->getIterator());
116}
117
118/// Insert an unlinked instruction into a basic block immediately before the
119/// specified instruction.
121 insertBefore(*InsertPos->getParent(), InsertPos);
122}
123
124/// Insert an unlinked instruction into a basic block immediately after the
125/// specified instruction.
126void Instruction::insertAfter(Instruction *InsertPos) {
127 BasicBlock *DestParent = InsertPos->getParent();
128
129 DestParent->getInstList().insertAfter(InsertPos->getIterator(), this);
130}
131
133 BasicBlock *DestParent = InsertPos->getParent();
134
135 DestParent->getInstList().insertAfter(InsertPos, this);
136}
137
140 assert(getParent() == nullptr && "Expected detached instruction");
141 assert((It == ParentBB->end() || It->getParent() == ParentBB) &&
142 "It not in ParentBB");
143 insertBefore(*ParentBB, It);
144 return getIterator();
145}
146
148 InstListType::iterator InsertPos) {
149 assert(!DebugMarker);
150
151 BB.getInstList().insert(InsertPos, this);
152
153 // We've inserted "this": if InsertAtHead is set then it comes before any
154 // DbgVariableRecords attached to InsertPos. But if it's not set, then any
155 // DbgRecords should now come before "this".
156 bool InsertAtHead = InsertPos.getHeadBit();
157 if (!InsertAtHead) {
158 DbgMarker *SrcMarker = BB.getMarker(InsertPos);
159 if (SrcMarker && !SrcMarker->empty()) {
160 // If this assertion fires, the calling code is about to insert a PHI
161 // after debug-records, which would form a sequence like:
162 // %0 = PHI
163 // #dbg_value
164 // %1 = PHI
165 // Which is de-normalised and undesired -- hence the assertion. To avoid
166 // this, you must insert at that position using an iterator, and it must
167 // be aquired by calling getFirstNonPHIIt / begin or similar methods on
168 // the block. This will signal to this behind-the-scenes debug-info
169 // maintenence code that you intend the PHI to be ahead of everything,
170 // including any debug-info.
171 assert(!isa<PHINode>(this) && "Inserting PHI after debug-records!");
172 adoptDbgRecords(&BB, InsertPos, false);
173 }
174 }
175
176 // If we're inserting a terminator, check if we need to flush out
177 // TrailingDbgRecords. Inserting instructions at the end of an incomplete
178 // block is handled by the code block above.
179 if (isTerminator())
180 getParent()->flushTerminatorDbgRecords();
181}
182
183/// Unlink this instruction from its current basic block and insert it into the
184/// basic block that MovePos lives in, right before MovePos.
186 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), false);
187}
188
190 moveBeforeImpl(*MovePos->getParent(), MovePos, false);
191}
192
194 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), true);
195}
196
198 moveBeforeImpl(*MovePos->getParent(), MovePos, true);
199}
200
201void Instruction::moveAfter(Instruction *MovePos) {
202 auto NextIt = std::next(MovePos->getIterator());
203 // We want this instruction to be moved to after NextIt in the instruction
204 // list, but before NextIt's debug value range.
205 NextIt.setHeadBit(true);
206 moveBeforeImpl(*MovePos->getParent(), NextIt, false);
207}
208
209void Instruction::moveAfter(InstListType::iterator MovePos) {
210 // We want this instruction to be moved to after NextIt in the instruction
211 // list, but before NextIt's debug value range.
212 MovePos.setHeadBit(true);
213 moveBeforeImpl(*MovePos->getParent(), MovePos, false);
214}
215
217 auto NextIt = std::next(MovePos->getIterator());
218 // We want this instruction and its debug range to be moved to after NextIt
219 // in the instruction list, but before NextIt's debug value range.
220 NextIt.setHeadBit(true);
221 moveBeforeImpl(*MovePos->getParent(), NextIt, true);
222}
223
224void Instruction::moveBefore(BasicBlock &BB, InstListType::iterator I) {
225 moveBeforeImpl(BB, I, false);
226}
227
229 InstListType::iterator I) {
230 moveBeforeImpl(BB, I, true);
231}
232
233void Instruction::moveBeforeImpl(BasicBlock &BB, InstListType::iterator I,
234 bool Preserve) {
235 assert(I == BB.end() || I->getParent() == &BB);
236 bool InsertAtHead = I.getHeadBit();
237
238 // If we've been given the "Preserve" flag, then just move the DbgRecords with
239 // the instruction, no more special handling needed.
240 if (DebugMarker && !Preserve) {
241 if (I != this->getIterator() || InsertAtHead) {
242 // "this" is definitely moving in the list, or it's moving ahead of its
243 // attached DbgVariableRecords. Detach any existing DbgRecords.
244 handleMarkerRemoval();
245 }
246 }
247
248 // Move this single instruction. Use the list splice method directly, not
249 // the block splicer, which will do more debug-info things.
250 BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
251
252 if (!Preserve) {
253 DbgMarker *NextMarker = getParent()->getNextMarker(this);
254
255 // If we're inserting at point I, and not in front of the DbgRecords
256 // attached there, then we should absorb the DbgRecords attached to I.
257 if (!InsertAtHead && NextMarker && !NextMarker->empty()) {
258 adoptDbgRecords(&BB, I, false);
259 }
260 }
261
262 if (isTerminator())
263 getParent()->flushTerminatorDbgRecords();
264}
265
267 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
268 bool InsertAtHead) {
269 if (!From->DebugMarker)
271
272 if (!DebugMarker)
273 getParent()->createMarker(this);
274
275 return DebugMarker->cloneDebugInfoFrom(From->DebugMarker, FromHere,
276 InsertAtHead);
277}
278
279std::optional<DbgRecord::self_iterator>
281 // Is there a marker on the next instruction?
282 DbgMarker *NextMarker = getParent()->getNextMarker(this);
283 if (!NextMarker)
284 return std::nullopt;
285
286 // Are there any DbgRecords in the next marker?
287 if (NextMarker->StoredDbgRecords.empty())
288 return std::nullopt;
289
290 return NextMarker->StoredDbgRecords.begin();
291}
292
293bool Instruction::hasDbgRecords() const { return !getDbgRecordRange().empty(); }
294
296 bool InsertAtHead) {
297 DbgMarker *SrcMarker = BB->getMarker(It);
298 auto ReleaseTrailingDbgRecords = [BB, It, SrcMarker]() {
299 if (BB->end() == It) {
300 SrcMarker->eraseFromParent();
302 }
303 };
304
305 if (!SrcMarker || SrcMarker->StoredDbgRecords.empty()) {
306 ReleaseTrailingDbgRecords();
307 return;
308 }
309
310 // If we have DbgMarkers attached to this instruction, we have to honour the
311 // ordering of DbgRecords between this and the other marker. Fall back to just
312 // absorbing from the source.
313 if (DebugMarker || It == BB->end()) {
314 // Ensure we _do_ have a marker.
315 getParent()->createMarker(this);
316 DebugMarker->absorbDebugValues(*SrcMarker, InsertAtHead);
317
318 // Having transferred everything out of SrcMarker, we _could_ clean it up
319 // and free the marker now. However, that's a lot of heap-accounting for a
320 // small amount of memory with a good chance of re-use. Leave it for the
321 // moment. It will be released when the Instruction is freed in the worst
322 // case.
323 // However: if we transferred from a trailing marker off the end of the
324 // block, it's important to not leave the empty marker trailing. It will
325 // give a misleading impression that some debug records have been left
326 // trailing.
327 ReleaseTrailingDbgRecords();
328 } else {
329 // Optimisation: we're transferring all the DbgRecords from the source
330 // marker onto this empty location: just adopt the other instructions
331 // marker.
332 DebugMarker = SrcMarker;
333 DebugMarker->MarkedInstr = this;
334 It->DebugMarker = nullptr;
335 }
336}
337
339 if (DebugMarker)
340 DebugMarker->dropDbgRecords();
341}
342
344 DebugMarker->dropOneDbgRecord(DVR);
345}
346
347bool Instruction::comesBefore(const Instruction *Other) const {
348 assert(getParent() && Other->getParent() &&
349 "instructions without BB parents have no order");
350 assert(getParent() == Other->getParent() &&
351 "cross-BB instruction order comparison");
352 if (!getParent()->isInstrOrderValid())
353 const_cast<BasicBlock *>(getParent())->renumberInstructions();
354 return Order < Other->Order;
355}
356
357std::optional<BasicBlock::iterator> Instruction::getInsertionPointAfterDef() {
358 assert(!getType()->isVoidTy() && "Instruction must define result");
359 BasicBlock *InsertBB;
360 BasicBlock::iterator InsertPt;
361 if (auto *PN = dyn_cast<PHINode>(this)) {
362 InsertBB = PN->getParent();
363 InsertPt = InsertBB->getFirstInsertionPt();
364 } else if (auto *II = dyn_cast<InvokeInst>(this)) {
365 InsertBB = II->getNormalDest();
366 InsertPt = InsertBB->getFirstInsertionPt();
367 } else if (isa<CallBrInst>(this)) {
368 // Def is available in multiple successors, there's no single dominating
369 // insertion point.
370 return std::nullopt;
371 } else {
372 assert(!isTerminator() && "Only invoke/callbr terminators return value");
373 InsertBB = getParent();
374 InsertPt = std::next(getIterator());
375 // Any instruction inserted immediately after "this" will come before any
376 // debug-info records take effect -- thus, set the head bit indicating that
377 // to debug-info-transfer code.
378 InsertPt.setHeadBit(true);
379 }
380
381 // catchswitch blocks don't have any legal insertion point (because they
382 // are both an exception pad and a terminator).
383 if (InsertPt == InsertBB->end())
384 return std::nullopt;
385 return InsertPt;
386}
387
389 return any_of(operands(), [](const Value *V) { return V->hasOneUser(); });
390}
391
393 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
394 Inst->setHasNoUnsignedWrap(b);
395 else
396 cast<TruncInst>(this)->setHasNoUnsignedWrap(b);
397}
398
400 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
401 Inst->setHasNoSignedWrap(b);
402 else
403 cast<TruncInst>(this)->setHasNoSignedWrap(b);
404}
405
406void Instruction::setIsExact(bool b) {
407 cast<PossiblyExactOperator>(this)->setIsExact(b);
408}
409
410void Instruction::setNonNeg(bool b) {
411 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
412 SubclassOptionalData = (SubclassOptionalData & ~PossiblyNonNegInst::NonNeg) |
414}
415
417 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
418 return Inst->hasNoUnsignedWrap();
419
420 return cast<TruncInst>(this)->hasNoUnsignedWrap();
421}
422
423bool Instruction::hasNoSignedWrap() const {
424 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
425 return Inst->hasNoSignedWrap();
426
427 return cast<TruncInst>(this)->hasNoSignedWrap();
428}
429
430bool Instruction::hasNonNeg() const {
431 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
432 return (SubclassOptionalData & PossiblyNonNegInst::NonNeg) != 0;
433}
434
436 return cast<Operator>(this)->hasPoisonGeneratingFlags();
437}
438
440 switch (getOpcode()) {
441 case Instruction::Add:
442 case Instruction::Sub:
443 case Instruction::Mul:
444 case Instruction::Shl:
445 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
446 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
447 break;
448
449 case Instruction::UDiv:
450 case Instruction::SDiv:
451 case Instruction::AShr:
452 case Instruction::LShr:
453 cast<PossiblyExactOperator>(this)->setIsExact(false);
454 break;
455
456 case Instruction::Or:
457 cast<PossiblyDisjointInst>(this)->setIsDisjoint(false);
458 break;
459
460 case Instruction::GetElementPtr:
461 cast<GetElementPtrInst>(this)->setNoWrapFlags(GEPNoWrapFlags::none());
462 break;
463
464 case Instruction::UIToFP:
465 case Instruction::ZExt:
466 setNonNeg(false);
467 break;
468
469 case Instruction::Trunc:
470 cast<TruncInst>(this)->setHasNoUnsignedWrap(false);
471 cast<TruncInst>(this)->setHasNoSignedWrap(false);
472 break;
473
474 case Instruction::ICmp:
475 cast<ICmpInst>(this)->setSameSign(false);
476 break;
477
478 case Instruction::Call: {
479 if (auto *II = dyn_cast<IntrinsicInst>(this)) {
480 switch (II->getIntrinsicID()) {
481 case Intrinsic::ctlz:
482 case Intrinsic::cttz:
483 case Intrinsic::abs:
484 II->setOperand(1, ConstantInt::getFalse(getContext()));
485 break;
486 }
487 }
488 break;
489 }
490 }
491
492 if (isa<FPMathOperator>(this)) {
493 setHasNoNaNs(false);
494 setHasNoInfs(false);
495 }
496
497 assert(!hasPoisonGeneratingFlags() && "must be kept in sync");
498}
499
502 [this](unsigned ID) { return hasMetadata(ID); });
503}
504
506 // If there is no loop metadata at all, we also don't have
507 // non-debug loop metadata, obviously.
508 if (!hasMetadata(LLVMContext::MD_loop))
509 return false;
510
511 // If we do have loop metadata, retrieve it.
512 MDNode *LoopMD = getMetadata(LLVMContext::MD_loop);
513
514 // Check if the existing operands are debug locations. This loop
515 // should terminate after at most three iterations. Skip
516 // the first item because it is a self-reference.
517 for (const MDOperand &Op : llvm::drop_begin(LoopMD->operands())) {
518 // check for debug location type by attempting a cast.
519 if (!isa<DILocation>(Op)) {
520 return true;
521 }
522 }
523
524 // If we get here, then all we have is debug locations in the loop metadata.
525 return false;
526}
527
529 for (unsigned ID : Metadata::PoisonGeneratingIDs)
530 eraseMetadata(ID);
531}
532
534 if (const auto *CB = dyn_cast<CallBase>(this)) {
535 auto HasPoisonGeneratingAttributes = [](AttributeSet Attrs) {
536 return Attrs.hasAttribute(Attribute::Range) ||
537 Attrs.hasAttribute(Attribute::Alignment) ||
538 Attrs.hasAttribute(Attribute::NonNull) ||
539 Attrs.hasAttribute(Attribute::NoFPClass);
540 };
541 if (HasPoisonGeneratingAttributes(CB->getRetAttributes()))
542 return true;
543 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
544 if (HasPoisonGeneratingAttributes(CB->getParamAttributes(ArgNo)))
545 return true;
546 }
547 return false;
548}
549
551 if (auto *CB = dyn_cast<CallBase>(this)) {
552 AttributeMask AM;
553 AM.addAttribute(Attribute::Range);
554 AM.addAttribute(Attribute::Alignment);
555 AM.addAttribute(Attribute::NonNull);
556 AM.addAttribute(Attribute::NoFPClass);
557 CB->removeRetAttrs(AM);
558 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
559 CB->removeParamAttrs(ArgNo, AM);
560 }
561 assert(!hasPoisonGeneratingAttributes() && "must be kept in sync");
562}
563
565 ArrayRef<unsigned> KnownIDs) {
566 dropUnknownNonDebugMetadata(KnownIDs);
567 auto *CB = dyn_cast<CallBase>(this);
568 if (!CB)
569 return;
570 // For call instructions, we also need to drop parameter and return attributes
571 // that can cause UB if the call is moved to a location where the attribute is
572 // not valid.
573 AttributeList AL = CB->getAttributes();
574 if (AL.isEmpty())
575 return;
576 AttributeMask UBImplyingAttributes =
577 AttributeFuncs::getUBImplyingAttributes();
578 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
579 CB->removeParamAttrs(ArgNo, UBImplyingAttributes);
580 CB->removeRetAttrs(UBImplyingAttributes);
581}
582
584 // !annotation and !prof metadata does not impact semantics.
585 // !range, !nonnull, !align and !nofpclass produce poison, so they are safe to
586 // speculate.
587 // !fpmath specifies floating-point precision and does not imply UB.
588 // !mem.cache_hint is a performance hint and does not imply UB.
589 // !noundef and various AA metadata must be dropped, as it generally produces
590 // immediate undefined behavior.
591 static const unsigned KnownIDs[] = {
592 LLVMContext::MD_annotation, LLVMContext::MD_range,
593 LLVMContext::MD_nonnull, LLVMContext::MD_align,
594 LLVMContext::MD_fpmath, LLVMContext::MD_prof,
595 LLVMContext::MD_mem_cache_hint, LLVMContext::MD_nofpclass};
596 SmallVector<unsigned> KeepIDs;
597 KeepIDs.reserve(Keep.size() + std::size(KnownIDs));
598 append_range(KeepIDs, (!ProfcheckDisableMetadataFixes ? KnownIDs
599 : drop_end(KnownIDs)));
600 append_range(KeepIDs, Keep);
601 dropUBImplyingAttrsAndUnknownMetadata(KeepIDs);
602}
603
605 auto *CB = dyn_cast<CallBase>(this);
606 if (!CB)
607 return false;
608 // For call instructions, we also need to check parameter and return
609 // attributes that can cause UB.
610 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
611 if (CB->isPassingUndefUB(ArgNo))
612 return true;
613 return CB->hasRetAttr(Attribute::NoUndef) ||
614 CB->hasRetAttr(Attribute::Dereferenceable) ||
615 CB->hasRetAttr(Attribute::DereferenceableOrNull);
616}
617
618bool Instruction::isExact() const {
619 return cast<PossiblyExactOperator>(this)->isExact();
620}
621
622void Instruction::setFast(bool B) {
623 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
624 cast<FPMathOperator>(this)->setFast(B);
625}
626
628 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
629 cast<FPMathOperator>(this)->setHasAllowReassoc(B);
630}
631
632void Instruction::setHasNoNaNs(bool B) {
633 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
634 cast<FPMathOperator>(this)->setHasNoNaNs(B);
635}
636
637void Instruction::setHasNoInfs(bool B) {
638 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
639 cast<FPMathOperator>(this)->setHasNoInfs(B);
640}
641
643 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
644 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
645}
646
648 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
649 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
650}
651
653 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
654 cast<FPMathOperator>(this)->setHasAllowContract(B);
655}
656
658 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
659 cast<FPMathOperator>(this)->setHasApproxFunc(B);
660}
661
663 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
664 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
665}
666
668 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
669 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
670}
671
672bool Instruction::isFast() const {
673 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
674 return cast<FPMathOperator>(this)->isFast();
675}
676
677bool Instruction::hasAllowReassoc() const {
678 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
679 return cast<FPMathOperator>(this)->hasAllowReassoc();
680}
681
682bool Instruction::hasNoNaNs() const {
683 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
684 return cast<FPMathOperator>(this)->hasNoNaNs();
685}
686
687bool Instruction::hasNoInfs() const {
688 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
689 return cast<FPMathOperator>(this)->hasNoInfs();
690}
691
693 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
694 return cast<FPMathOperator>(this)->hasNoSignedZeros();
695}
696
698 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
699 return cast<FPMathOperator>(this)->hasAllowReciprocal();
700}
701
703 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
704 return cast<FPMathOperator>(this)->hasAllowContract();
705}
706
707bool Instruction::hasApproxFunc() const {
708 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
709 return cast<FPMathOperator>(this)->hasApproxFunc();
710}
711
713 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
714 return cast<FPMathOperator>(this)->getFastMathFlags();
715}
716
718 if (!isa<FPMathOperator>(this))
719 return {};
720 return cast<FPMathOperator>(this)->getFastMathFlags();
721}
722
724 copyFastMathFlags(I->getFastMathFlags());
725}
726
727void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
728 // Copy the wrapping flags.
729 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
730 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
731 setHasNoSignedWrap(OB->hasNoSignedWrap());
732 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
733 }
734 }
735
736 if (auto *TI = dyn_cast<TruncInst>(V)) {
737 if (isa<TruncInst>(this)) {
738 setHasNoSignedWrap(TI->hasNoSignedWrap());
739 setHasNoUnsignedWrap(TI->hasNoUnsignedWrap());
740 }
741 }
742
743 // Copy the exact flag.
744 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
746 setIsExact(PE->isExact());
747
748 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
749 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
750 DestPD->setIsDisjoint(SrcPD->isDisjoint());
751
752 // Copy the fast-math flags.
753 if (auto *FP = dyn_cast<FPMathOperator>(V))
754 if (isa<FPMathOperator>(this))
755 copyFastMathFlags(FP->getFastMathFlags());
756
757 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
758 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
759 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() |
760 DestGEP->getNoWrapFlags());
761
762 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
763 if (isa<PossiblyNonNegInst>(this))
764 setNonNeg(NNI->hasNonNeg());
765
766 if (auto *SrcICmp = dyn_cast<ICmpInst>(V))
767 if (auto *DestICmp = dyn_cast<ICmpInst>(this))
768 DestICmp->setSameSign(SrcICmp->hasSameSign());
769}
770
771void Instruction::andIRFlags(const Value *V) {
772 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
774 setHasNoSignedWrap(hasNoSignedWrap() && OB->hasNoSignedWrap());
775 setHasNoUnsignedWrap(hasNoUnsignedWrap() && OB->hasNoUnsignedWrap());
776 }
777 }
778
779 if (auto *TI = dyn_cast<TruncInst>(V)) {
780 if (isa<TruncInst>(this)) {
781 setHasNoSignedWrap(hasNoSignedWrap() && TI->hasNoSignedWrap());
782 setHasNoUnsignedWrap(hasNoUnsignedWrap() && TI->hasNoUnsignedWrap());
783 }
784 }
785
786 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
788 setIsExact(isExact() && PE->isExact());
789
790 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
791 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
792 DestPD->setIsDisjoint(DestPD->isDisjoint() && SrcPD->isDisjoint());
793
794 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
795 if (isa<FPMathOperator>(this)) {
797 FM &= FP->getFastMathFlags();
798 copyFastMathFlags(FM);
799 }
800 }
801
802 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
803 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
804 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() &
805 DestGEP->getNoWrapFlags());
806
807 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
808 if (isa<PossiblyNonNegInst>(this))
809 setNonNeg(hasNonNeg() && NNI->hasNonNeg());
810
811 if (auto *SrcICmp = dyn_cast<ICmpInst>(V))
812 if (auto *DestICmp = dyn_cast<ICmpInst>(this))
813 DestICmp->setSameSign(DestICmp->hasSameSign() && SrcICmp->hasSameSign());
814}
815
816const char *Instruction::getOpcodeName(unsigned OpCode) {
817 switch (OpCode) {
818 // Terminators
819 case Ret: return "ret";
820 case UncondBr: return "br";
821 case CondBr: return "br";
822 case Switch: return "switch";
823 case IndirectBr: return "indirectbr";
824 case Invoke: return "invoke";
825 case Resume: return "resume";
826 case Unreachable: return "unreachable";
827 case CleanupRet: return "cleanupret";
828 case CatchRet: return "catchret";
829 case CatchPad: return "catchpad";
830 case CatchSwitch: return "catchswitch";
831 case CallBr: return "callbr";
832
833 // Standard unary operators...
834 case FNeg: return "fneg";
835
836 // Standard binary operators...
837 case Add: return "add";
838 case FAdd: return "fadd";
839 case Sub: return "sub";
840 case FSub: return "fsub";
841 case Mul: return "mul";
842 case FMul: return "fmul";
843 case UDiv: return "udiv";
844 case SDiv: return "sdiv";
845 case FDiv: return "fdiv";
846 case URem: return "urem";
847 case SRem: return "srem";
848 case FRem: return "frem";
849
850 // Logical operators...
851 case And: return "and";
852 case Or : return "or";
853 case Xor: return "xor";
854
855 // Memory instructions...
856 case Alloca: return "alloca";
857 case Load: return "load";
858 case Store: return "store";
859 case AtomicCmpXchg: return "cmpxchg";
860 case AtomicRMW: return "atomicrmw";
861 case Fence: return "fence";
862 case GetElementPtr: return "getelementptr";
863
864 // Convert instructions...
865 case Trunc: return "trunc";
866 case ZExt: return "zext";
867 case SExt: return "sext";
868 case FPTrunc: return "fptrunc";
869 case FPExt: return "fpext";
870 case FPToUI: return "fptoui";
871 case FPToSI: return "fptosi";
872 case UIToFP: return "uitofp";
873 case SIToFP: return "sitofp";
874 case IntToPtr: return "inttoptr";
875 case PtrToAddr: return "ptrtoaddr";
876 case PtrToInt: return "ptrtoint";
877 case BitCast: return "bitcast";
878 case AddrSpaceCast: return "addrspacecast";
879
880 // Other instructions...
881 case ICmp: return "icmp";
882 case FCmp: return "fcmp";
883 case PHI: return "phi";
884 case Select: return "select";
885 case Call: return "call";
886 case Shl: return "shl";
887 case LShr: return "lshr";
888 case AShr: return "ashr";
889 case VAArg: return "va_arg";
890 case ExtractElement: return "extractelement";
891 case InsertElement: return "insertelement";
892 case ShuffleVector: return "shufflevector";
893 case ExtractValue: return "extractvalue";
894 case InsertValue: return "insertvalue";
895 case LandingPad: return "landingpad";
896 case CleanupPad: return "cleanuppad";
897 case Freeze: return "freeze";
898
899 default: return "<Invalid operator> ";
900 }
901}
902
903/// This must be kept in sync with FunctionComparator::cmpOperations in
904/// lib/Transforms/Utils/FunctionComparator.cpp.
906 bool IgnoreAlignment,
907 bool IntersectAttrs) const {
908 const auto *I1 = this;
909 assert(I1->getOpcode() == I2->getOpcode() &&
910 "Can not compare special state of different instructions");
911
912 auto CheckAttrsSame = [IntersectAttrs](const CallBase *CB0,
913 const CallBase *CB1) {
914 return IntersectAttrs
915 ? CB0->getAttributes()
916 .intersectWith(CB0->getContext(), CB1->getAttributes())
917 .has_value()
918 : CB0->getAttributes() == CB1->getAttributes();
919 };
920
921 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
922 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
923 (AI->getAlign() == cast<AllocaInst>(I2)->getAlign() ||
924 IgnoreAlignment);
925 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
926 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
927 LI->isElementwise() == cast<LoadInst>(I2)->isElementwise() &&
928 (LI->getAlign() == cast<LoadInst>(I2)->getAlign() ||
929 IgnoreAlignment) &&
930 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
931 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
932 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
933 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
934 (SI->getAlign() == cast<StoreInst>(I2)->getAlign() ||
935 IgnoreAlignment) &&
936 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
937 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
938 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
939 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
940 if (const CallInst *CI = dyn_cast<CallInst>(I1))
941 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
942 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
943 CheckAttrsSame(CI, cast<CallInst>(I2)) &&
944 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
945 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
946 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
947 CheckAttrsSame(CI, cast<InvokeInst>(I2)) &&
948 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
949 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
950 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
951 CheckAttrsSame(CI, cast<CallBrInst>(I2)) &&
952 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
953 if (const SwitchInst *SI = dyn_cast<SwitchInst>(I1)) {
954 for (auto [Case1, Case2] : zip(SI->cases(), cast<SwitchInst>(I2)->cases()))
955 if (Case1.getCaseValue() != Case2.getCaseValue())
956 return false;
957 return true;
958 }
959 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
960 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
961 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
962 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
963 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
964 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
965 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
967 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
968 (CXI->getAlign() == cast<AtomicCmpXchgInst>(I2)->getAlign() ||
969 IgnoreAlignment) &&
970 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
971 CXI->getSuccessOrdering() ==
972 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
973 CXI->getFailureOrdering() ==
974 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
975 CXI->getSyncScopeID() ==
976 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
977 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
978 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
979 RMWI->isElementwise() == cast<AtomicRMWInst>(I2)->isElementwise() &&
980 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
981 (RMWI->getAlign() == cast<AtomicRMWInst>(I2)->getAlign() ||
982 IgnoreAlignment) &&
983 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
984 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
986 return SVI->getShuffleMask() ==
987 cast<ShuffleVectorInst>(I2)->getShuffleMask();
989 return GEP->getSourceElementType() ==
990 cast<GetElementPtrInst>(I2)->getSourceElementType();
991
992 return true;
993}
994
995bool Instruction::isIdenticalTo(const Instruction *I) const {
996 return isIdenticalToWhenDefined(I) &&
997 SubclassOptionalData == I->SubclassOptionalData;
998}
999
1001 bool IntersectAttrs) const {
1002 if (getOpcode() != I->getOpcode() ||
1003 getNumOperands() != I->getNumOperands() || getType() != I->getType())
1004 return false;
1005
1006 // If both instructions have no operands, they are identical.
1007 if (getNumOperands() == 0 && I->getNumOperands() == 0)
1008 return this->hasSameSpecialState(I, /*IgnoreAlignment=*/false,
1009 IntersectAttrs);
1010
1011 // We have two instructions of identical opcode and #operands. Check to see
1012 // if all operands are the same.
1013 if (!equal(operands(), I->operands()))
1014 return false;
1015
1016 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()!
1017 if (const PHINode *Phi = dyn_cast<PHINode>(this)) {
1018 const PHINode *OtherPhi = cast<PHINode>(I);
1019 return equal(Phi->blocks(), OtherPhi->blocks());
1020 }
1021
1022 return this->hasSameSpecialState(I, /*IgnoreAlignment=*/false,
1023 IntersectAttrs);
1024}
1025
1026// Keep this in sync with FunctionComparator::cmpOperations in
1027// lib/Transforms/IPO/MergeFunctions.cpp.
1029 unsigned flags) const {
1030 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
1031 bool UseScalarTypes = flags & CompareUsingScalarTypes;
1032 bool IntersectAttrs = flags & CompareUsingIntersectedAttrs;
1033
1034 if (getOpcode() != I->getOpcode() ||
1035 getNumOperands() != I->getNumOperands() ||
1036 (UseScalarTypes ?
1037 getType()->getScalarType() != I->getType()->getScalarType() :
1038 getType() != I->getType()))
1039 return false;
1040
1041 // We have two instructions of identical opcode and #operands. Check to see
1042 // if all operands are the same type
1043 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1044 if (UseScalarTypes ?
1045 getOperand(i)->getType()->getScalarType() !=
1046 I->getOperand(i)->getType()->getScalarType() :
1047 getOperand(i)->getType() != I->getOperand(i)->getType())
1048 return false;
1049
1050 return this->hasSameSpecialState(I, IgnoreAlignment, IntersectAttrs);
1051}
1052
1053bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
1054 for (const Use &U : uses()) {
1055 // PHI nodes uses values in the corresponding predecessor block. For other
1056 // instructions, just check to see whether the parent of the use matches up.
1057 const Instruction *I = cast<Instruction>(U.getUser());
1058 const PHINode *PN = dyn_cast<PHINode>(I);
1059 if (!PN) {
1060 if (I->getParent() != BB)
1061 return true;
1062 continue;
1063 }
1064
1065 if (PN->getIncomingBlock(U) != BB)
1066 return true;
1067 }
1068 return false;
1069}
1070
1072 auto GetEffects = [](ModRefInfo BaseMR, AtomicOrdering Ordering,
1073 bool IsVolatile) {
1074 if (isStrongerThanMonotonic(Ordering))
1075 return MemoryEffects::unknown();
1076
1077 if (IsVolatile)
1079
1080 if (isStrongerThanUnordered(Ordering))
1082
1083 return MemoryEffects::argMemOnly(BaseMR);
1084 };
1085 switch (getOpcode()) {
1086 default:
1087 return MemoryEffects::none();
1088 case Instruction::VAArg:
1090 case Instruction::CatchPad:
1091 case Instruction::CatchRet:
1092 case Instruction::Fence:
1093 return MemoryEffects::unknown();
1094 case Instruction::Call:
1095 case Instruction::Invoke:
1096 case Instruction::CallBr:
1097 return cast<CallBase>(this)->getMemoryEffects();
1098 case Instruction::Load: {
1099 auto *LI = cast<LoadInst>(this);
1100 return GetEffects(ModRefInfo::Ref, LI->getOrdering(), LI->isVolatile());
1101 }
1102 case Instruction::Store: {
1103 auto *SI = cast<StoreInst>(this);
1104 return GetEffects(ModRefInfo::Mod, SI->getOrdering(), SI->isVolatile());
1105 }
1106 case Instruction::AtomicRMW: {
1107 auto *RMW = cast<AtomicRMWInst>(this);
1108 return GetEffects(ModRefInfo::ModRef, RMW->getOrdering(),
1109 RMW->isVolatile());
1110 }
1111 case Instruction::AtomicCmpXchg: {
1112 auto *CX = cast<AtomicCmpXchgInst>(this);
1113 return GetEffects(ModRefInfo::ModRef, CX->getSuccessOrdering(),
1114 CX->isVolatile());
1115 }
1116 }
1117}
1118
1119// This is duplicating the logic from getMemoryEffects() for performance
1120// reasons. Computing the full MemoryEffects just to perform a Mod/Ref check
1121// is expensive.
1122
1123bool Instruction::mayReadFromMemory() const {
1124 switch (getOpcode()) {
1125 default: return false;
1126 case Instruction::VAArg:
1127 case Instruction::Load:
1128 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
1129 case Instruction::AtomicCmpXchg:
1130 case Instruction::AtomicRMW:
1131 case Instruction::CatchPad:
1132 case Instruction::CatchRet:
1133 return true;
1134 case Instruction::Call:
1135 case Instruction::Invoke:
1136 case Instruction::CallBr:
1137 return !cast<CallBase>(this)->onlyWritesMemory();
1138 case Instruction::Store:
1139 return !cast<StoreInst>(this)->isUnordered();
1140 }
1141}
1142
1143bool Instruction::mayWriteToMemory() const {
1144 switch (getOpcode()) {
1145 default: return false;
1146 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
1147 case Instruction::Store:
1148 case Instruction::VAArg:
1149 case Instruction::AtomicCmpXchg:
1150 case Instruction::AtomicRMW:
1151 case Instruction::CatchPad:
1152 case Instruction::CatchRet:
1153 return true;
1154 case Instruction::Call:
1155 case Instruction::Invoke:
1156 case Instruction::CallBr:
1157 return !cast<CallBase>(this)->onlyReadsMemory();
1158 case Instruction::Load:
1159 return !cast<LoadInst>(this)->isUnordered();
1160 }
1161}
1162
1163bool Instruction::isAtomic() const {
1164 switch (getOpcode()) {
1165 default:
1166 return false;
1167 case Instruction::AtomicCmpXchg:
1168 case Instruction::AtomicRMW:
1169 case Instruction::Fence:
1170 return true;
1171 case Instruction::Load:
1172 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
1173 case Instruction::Store:
1174 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
1175 }
1176}
1177
1178bool Instruction::hasAtomicLoad() const {
1179 assert(isAtomic());
1180 switch (getOpcode()) {
1181 default:
1182 return false;
1183 case Instruction::AtomicCmpXchg:
1184 case Instruction::AtomicRMW:
1185 case Instruction::Load:
1186 return true;
1187 }
1188}
1189
1190bool Instruction::hasAtomicStore() const {
1191 assert(isAtomic());
1192 switch (getOpcode()) {
1193 default:
1194 return false;
1195 case Instruction::AtomicCmpXchg:
1196 case Instruction::AtomicRMW:
1197 case Instruction::Store:
1198 return true;
1199 }
1200}
1201
1202bool Instruction::isVolatile() const {
1203 switch (getOpcode()) {
1204 default:
1205 return false;
1206 case Instruction::AtomicRMW:
1207 return cast<AtomicRMWInst>(this)->isVolatile();
1208 case Instruction::Store:
1209 return cast<StoreInst>(this)->isVolatile();
1210 case Instruction::Load:
1211 return cast<LoadInst>(this)->isVolatile();
1212 case Instruction::AtomicCmpXchg:
1213 return cast<AtomicCmpXchgInst>(this)->isVolatile();
1214 case Instruction::Call:
1215 case Instruction::Invoke:
1216 // There are a very limited number of intrinsics with volatile flags.
1217 if (auto *II = dyn_cast<IntrinsicInst>(this)) {
1218 if (auto *MI = dyn_cast<MemIntrinsic>(II))
1219 return MI->isVolatile();
1220 switch (II->getIntrinsicID()) {
1221 default: break;
1222 case Intrinsic::matrix_column_major_load:
1223 return cast<ConstantInt>(II->getArgOperand(2))->isOne();
1224 case Intrinsic::matrix_column_major_store:
1225 return cast<ConstantInt>(II->getArgOperand(3))->isOne();
1226 }
1227 }
1228 return false;
1229 }
1230}
1231
1232bool Instruction::maySynchronize() const {
1233 // FIXME: This currently treats atomics with monotonic ordering as
1234 // synchronizing. This is unnecessarily conservative and does not match
1235 // our LangRef definition of the property.
1236 switch (getOpcode()) {
1237 default:
1238 assert(!isAtomic() && "Unhandled atomic instruction");
1239 return false;
1240 case Instruction::Fence: {
1241 // All legal orderings for fence are stronger than monotonic.
1242 auto *FI = cast<FenceInst>(this);
1243 return FI->getSyncScopeID() != SyncScope::SingleThread;
1244 }
1245 case Instruction::AtomicRMW:
1246 case Instruction::AtomicCmpXchg:
1247 return true;
1248 case Instruction::Store:
1249 return isStrongerThanUnordered(cast<StoreInst>(this)->getOrdering());
1250 case Instruction::Load:
1251 return isStrongerThanUnordered(cast<LoadInst>(this)->getOrdering());
1252 case Instruction::Call:
1253 case Instruction::Invoke:
1254 case Instruction::CallBr:
1255 return !cast<CallBase>(this)->hasFnAttr(Attribute::NoSync);
1256 }
1257}
1258
1259Type *Instruction::getAccessType() const {
1260 switch (getOpcode()) {
1261 case Instruction::Store:
1262 return cast<StoreInst>(this)->getValueOperand()->getType();
1263 case Instruction::Load:
1264 case Instruction::AtomicRMW:
1265 return getType();
1266 case Instruction::AtomicCmpXchg:
1267 return cast<AtomicCmpXchgInst>(this)->getNewValOperand()->getType();
1268 case Instruction::Call:
1269 case Instruction::Invoke:
1270 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(this)) {
1271 switch (II->getIntrinsicID()) {
1272 case Intrinsic::masked_load:
1273 case Intrinsic::masked_gather:
1274 case Intrinsic::masked_expandload:
1275 case Intrinsic::vp_load:
1276 case Intrinsic::vp_gather:
1277 case Intrinsic::experimental_vp_strided_load:
1278 return II->getType();
1279 case Intrinsic::masked_store:
1280 case Intrinsic::masked_scatter:
1281 case Intrinsic::masked_compressstore:
1282 case Intrinsic::vp_store:
1283 case Intrinsic::vp_scatter:
1284 case Intrinsic::experimental_vp_strided_store:
1285 return II->getOperand(0)->getType();
1286 default:
1287 break;
1288 }
1289 }
1290 }
1291
1292 return nullptr;
1293}
1294
1295static bool canUnwindPastLandingPad(const LandingPadInst *LP,
1296 bool IncludePhaseOneUnwind) {
1297 // Because phase one unwinding skips cleanup landingpads, we effectively
1298 // unwind past this frame, and callers need to have valid unwind info.
1299 if (LP->isCleanup())
1300 return IncludePhaseOneUnwind;
1301
1302 for (unsigned I = 0; I < LP->getNumClauses(); ++I) {
1303 Constant *Clause = LP->getClause(I);
1304 // catch ptr null catches all exceptions.
1305 if (LP->isCatch(I) && isa<ConstantPointerNull>(Clause))
1306 return false;
1307 // filter [0 x ptr] catches all exceptions.
1308 if (LP->isFilter(I) && Clause->getType()->getArrayNumElements() == 0)
1309 return false;
1310 }
1311
1312 // May catch only some subset of exceptions, in which case other exceptions
1313 // will continue unwinding.
1314 return true;
1315}
1316
1317bool Instruction::mayThrow(bool IncludePhaseOneUnwind) const {
1318 switch (getOpcode()) {
1319 case Instruction::Call:
1320 return !cast<CallInst>(this)->doesNotThrow();
1321 case Instruction::CleanupRet:
1322 return cast<CleanupReturnInst>(this)->unwindsToCaller();
1323 case Instruction::CatchSwitch:
1324 return cast<CatchSwitchInst>(this)->unwindsToCaller();
1325 case Instruction::Resume:
1326 return true;
1327 case Instruction::Invoke: {
1328 // Landingpads themselves don't unwind -- however, an invoke of a skipped
1329 // landingpad may continue unwinding.
1330 BasicBlock *UnwindDest = cast<InvokeInst>(this)->getUnwindDest();
1331 BasicBlock::iterator Pad = UnwindDest->getFirstNonPHIIt();
1332 if (auto *LP = dyn_cast<LandingPadInst>(Pad))
1333 return canUnwindPastLandingPad(LP, IncludePhaseOneUnwind);
1334 return false;
1335 }
1336 case Instruction::CleanupPad:
1337 // Treat the same as cleanup landingpad.
1338 return IncludePhaseOneUnwind;
1339 default:
1340 return false;
1341 }
1342}
1343
1345 return mayWriteToMemory() || mayThrow() || !willReturn();
1346}
1347
1348bool Instruction::isSafeToRemove() const {
1349 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
1350 !this->isTerminator() && !this->isEHPad();
1351}
1352
1353bool Instruction::willReturn() const {
1354 // Volatile operations are not guaranteed to return.
1355 if (isVolatile())
1356 return false;
1357
1358 if (const auto *CB = dyn_cast<CallBase>(this))
1359 return CB->hasFnAttr(Attribute::WillReturn);
1360 return true;
1361}
1362
1364 auto *II = dyn_cast<IntrinsicInst>(this);
1365 if (!II)
1366 return false;
1367 Intrinsic::ID ID = II->getIntrinsicID();
1368 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
1369}
1370
1372 auto *II = dyn_cast<IntrinsicInst>(this);
1373 if (!II)
1374 return false;
1375 Intrinsic::ID ID = II->getIntrinsicID();
1376 return ID == Intrinsic::launder_invariant_group ||
1377 ID == Intrinsic::strip_invariant_group;
1378}
1379
1381 return isa<DbgInfoIntrinsic>(this) || isa<PseudoProbeInst>(this);
1382}
1383
1385 return getDebugLoc();
1386}
1387
1388bool Instruction::isAssociative() const {
1389 if (auto *II = dyn_cast<IntrinsicInst>(this))
1390 return II->isAssociative();
1391 unsigned Opcode = getOpcode();
1392 if (isAssociative(Opcode))
1393 return true;
1394
1395 switch (Opcode) {
1396 case FMul:
1397 return cast<FPMathOperator>(this)->hasAllowReassoc();
1398 case FAdd:
1399 return cast<FPMathOperator>(this)->hasAllowReassoc() &&
1400 cast<FPMathOperator>(this)->hasNoSignedZeros();
1401 default:
1402 return false;
1403 }
1404}
1405
1406bool Instruction::isCommutative() const {
1407 if (auto *II = dyn_cast<IntrinsicInst>(this))
1408 return II->isCommutative();
1409 // TODO: Should allow icmp/fcmp?
1410 return isCommutative(getOpcode());
1411}
1412
1413bool Instruction::isCommutableOperand(unsigned Op) const {
1414 if (auto *II = dyn_cast<IntrinsicInst>(this))
1415 return II->isCommutableOperand(Op);
1416 // TODO: Should allow icmp/fcmp?
1417 return isCommutative(getOpcode());
1418}
1419
1420unsigned Instruction::getNumSuccessors() const {
1421 switch (getOpcode()) {
1422#define HANDLE_TERM_INST(N, OPC, CLASS) \
1423 case Instruction::OPC: \
1424 return static_cast<const CLASS *>(this)->getNumSuccessors();
1425#include "llvm/IR/Instruction.def"
1426 default:
1427 break;
1428 }
1429 llvm_unreachable("not a terminator");
1430}
1431
1432BasicBlock *Instruction::getSuccessor(unsigned idx) const {
1433 switch (getOpcode()) {
1434#define HANDLE_TERM_INST(N, OPC, CLASS) \
1435 case Instruction::OPC: \
1436 return static_cast<const CLASS *>(this)->getSuccessor(idx);
1437#include "llvm/IR/Instruction.def"
1438 default:
1439 break;
1440 }
1441 llvm_unreachable("not a terminator");
1442}
1443
1444void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
1445 switch (getOpcode()) {
1446#define HANDLE_TERM_INST(N, OPC, CLASS) \
1447 case Instruction::OPC: \
1448 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
1449#include "llvm/IR/Instruction.def"
1450 default:
1451 break;
1452 }
1453 llvm_unreachable("not a terminator");
1454}
1455
1458 switch (getOpcode()) {
1459#define HANDLE_TERM_INST(N, OPC, CLASS) \
1460 case Instruction::OPC: \
1461 return static_cast<const CLASS *>(this)->successors();
1462#include "llvm/IR/Instruction.def"
1463 default:
1464 break;
1465 }
1466 llvm_unreachable("not a terminator");
1467}
1468
1470 auto Succs = successors();
1471 for (auto I = Succs.begin(), E = Succs.end(); I != E; ++I)
1472 if (*I == OldBB)
1473 I.getUse()->set(NewBB);
1474}
1475
1476Instruction *Instruction::cloneImpl() const {
1477 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
1478}
1479
1481 MDNode *ProfileData = getBranchWeightMDNode(*this);
1482 if (!ProfileData)
1483 return;
1484 unsigned FirstIdx = getBranchWeightOffset(ProfileData);
1485 if (ProfileData->getNumOperands() != 2 + FirstIdx)
1486 return;
1487
1488 unsigned SecondIdx = FirstIdx + 1;
1490 // If there are more weights past the second, we can't swap them
1491 if (ProfileData->getNumOperands() > SecondIdx + 1)
1492 return;
1493 for (unsigned Idx = 0; Idx < FirstIdx; ++Idx) {
1494 Ops.push_back(ProfileData->getOperand(Idx));
1495 }
1496 // Switch the order of the weights
1497 Ops.push_back(ProfileData->getOperand(SecondIdx));
1498 Ops.push_back(ProfileData->getOperand(FirstIdx));
1499 setMetadata(LLVMContext::MD_prof,
1500 MDNode::get(ProfileData->getContext(), Ops));
1501}
1502
1504 // TODO: Include additional metadata in the future if appropriate.
1505 static const unsigned SafeIDs[] = {
1506 LLVMContext::MD_dbg, LLVMContext::MD_prof, LLVMContext::MD_memprof,
1507 LLVMContext::MD_callsite};
1508 copyMetadata(SrcInst, SafeIDs);
1509}
1510
1511void Instruction::copyMetadata(const Instruction &SrcInst,
1512 ArrayRef<unsigned> WL) {
1513 if (WL.empty() || is_contained(WL, LLVMContext::MD_dbg))
1514 setDebugLoc(SrcInst.getDebugLoc().orElse(getDebugLoc()));
1515
1516 if (!SrcInst.hasMetadata())
1517 return;
1518
1519 SmallDenseSet<unsigned, 4> WLS(WL.begin(), WL.end());
1520
1521 // Otherwise, enumerate and copy over metadata from the old instruction to the
1522 // new one.
1524 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
1525 for (const auto &MD : TheMDs) {
1526 if (WL.empty() || WLS.count(MD.first))
1527 setMetadata(MD.first, MD.second);
1528 }
1529}
1530
1532 Instruction *New = nullptr;
1533 switch (getOpcode()) {
1534 default:
1535 llvm_unreachable("Unhandled Opcode.");
1536#define HANDLE_INST(num, opc, clas) \
1537 case Instruction::opc: \
1538 New = cast<clas>(this)->cloneImpl(); \
1539 break;
1540#include "llvm/IR/Instruction.def"
1541#undef HANDLE_INST
1542 }
1543
1544 New->SubclassOptionalData = SubclassOptionalData;
1545 New->copyMetadata(*this);
1546 return New;
1547}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
Rewrite undef for PHI
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static bool hasNoSignedWrap(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
uint64_t IntrinsicInst * II
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
This file contains the declarations for profiling metadata utility functions.
static bool mayHaveSideEffects(MachineInstr &MI)
Func MI getDebugLoc()))
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
This file contains some templates that are useful if you are working with the STL at all.
static bool canUnwindPastLandingPad(const LandingPadInst *LP, bool IncludePhaseOneUnwind)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static bool isAssociative(const COFFSection &Section)
BinaryOperator * Mul
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:407
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
LLVM_ABI void deleteTrailingDbgRecords()
Delete any trailing DbgRecords at the end of this block, see setTrailingDbgRecords.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI DbgMarker * getMarker(InstListType::iterator It)
Return the DbgMarker for the position given by It, so that DbgRecords can be inserted there.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
AttributeList getAttributes() const
Return the attributes for this call.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Per-instruction record of debug-info.
static iterator_range< simple_ilist< DbgRecord >::iterator > getEmptyDbgRecordRange()
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
LLVM_ABI void eraseFromParent()
simple_ilist< DbgRecord > StoredDbgRecords
List of DbgRecords, the non-instruction equivalent of llvm.dbg.
Base class for non-instruction debug metadata records that have positions within IR.
A debug info location.
Definition DebugLoc.h:126
DebugLoc orElse(DebugLoc Other) const
If this DebugLoc is non-empty, returns this DebugLoc; otherwise, selects Other.
Definition DebugLoc.h:187
This instruction extracts a struct member or array element value from an aggregate value.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
An instruction for ordering other memory operations.
static GEPNoWrapFlags none()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
InsertPosition(std::nullptr_t)
Definition Instruction.h:56
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI const DebugLoc & getStableDebugLoc() const
Fetch the debug location for this node, unless this is a debug intrinsic, in which case fetch the deb...
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
DbgMarker * DebugMarker
Optional marker recording the position for debugging information that takes effect immediately before...
LLVM_ABI MemoryEffects getMemoryEffects() const LLVM_READONLY
Return memory effects of the instruction.
LLVM_ABI bool mayThrow(bool IncludePhaseOneUnwind=false) const LLVM_READONLY
Return true if this instruction may throw an exception.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
LLVM_ABI bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
LLVM_ABI bool hasPoisonGeneratingAttributes() const LLVM_READONLY
Return true if this instruction has poison-generating attribute.
LLVM_ABI void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
LLVM_ABI bool isSameOperationAs(const Instruction *I, unsigned flags=0) const LLVM_READONLY
This function determines if the specified instruction executes the same operation as the current one.
LLVM_ABI ~Instruction()
LLVM_ABI void setHasNoSignedZeros(bool B)
Set or clear the no-signed-zeros flag on this instruction, which must be an operator which supports t...
LLVM_ABI bool hasNoSignedZeros() const LLVM_READONLY
Determine whether the no-signed-zeros flag is set.
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
LLVM_ABI FastMathFlags getFastMathFlagsOrNone() const LLVM_READONLY
Convenience function for getting fast-math flags, or default-constructed FastMathFlags when not a FPM...
LLVM_ABI void copyProfileAndDebugMetadata(const Instruction &SrcInst)
Copy debug, profile, and memprof metadata from SrcInst to this instruction without copying alias-anal...
LLVM_ABI bool isDebugOrPseudoInst() const LLVM_READONLY
Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI void setHasAllowContract(bool B)
Set or clear the allow-contract flag on this instruction, which must be an operator which supports th...
LLVM_ABI bool hasAtomicStore() const LLVM_READONLY
Return true if this atomic instruction stores to memory.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool isOnlyUserOfAnyOperand()
It checks if this instruction is the only user of at least one of its operands.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
LLVM_ABI void setHasNoNaNs(bool B)
Set or clear the no-nans flag on this instruction, which must be an operator which supports this flag...
LLVM_ABI bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
LLVM_ABI void setHasApproxFunc(bool B)
Set or clear the approximate-math-functions flag on this instruction, which must be an operator which...
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI bool hasSameSpecialState(const Instruction *I2, bool IgnoreAlignment=false, bool IntersectAttrs=false) const LLVM_READONLY
This function determines if the speficied instruction has the same "special" characteristics as the c...
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI void setHasAllowReassoc(bool B)
Set or clear the reassociation flag on this instruction, which must be an operator which supports thi...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
LLVM_ABI bool isFast() const LLVM_READONLY
Determine whether all fast-math-flags are set.
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
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.
LLVM_ABI void dropOneDbgRecord(DbgRecord *I)
Erase a single DbgRecord I that is attached to this instruction.
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
LLVM_ABI Type * getAccessType() const LLVM_READONLY
Return the type this instruction accesses in memory, if any.
LLVM_ABI bool hasAllowReciprocal() const LLVM_READONLY
Determine whether the allow-reciprocal flag is set.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
LLVM_ABI bool hasNonNeg() const LLVM_READONLY
Determine whether the the nneg flag is set.
LLVM_ABI bool maySynchronize() const LLVM_READONLY
Return true if this instruction may synchronize, in the sense that it may introduce a synchronizes-wi...
LLVM_ABI bool hasPoisonGeneratingFlags() const LLVM_READONLY
Return true if this operator has flags which may cause this instruction to evaluate to poison despite...
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY
Return true if there are any uses of this instruction in blocks other than the specified block.
LLVM_ABI bool isVolatile() const LLVM_READONLY
Return true if this instruction has a volatile memory access.
LLVM_ABI void setHasNoInfs(bool B)
Set or clear the no-infs flag on this instruction, which must be an operator which supports this flag...
LLVM_ABI iterator_range< const_succ_iterator > successors() const LLVM_READONLY
LLVM_ABI void adoptDbgRecords(BasicBlock *BB, InstListType::iterator It, bool InsertAtHead)
Transfer any DbgRecords on the position It onto this instruction, by simply adopting the sequence of ...
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
const char * getOpcodeName() const
LLVM_ABI bool willReturn() const LLVM_READONLY
Return true if the instruction will return (unwinding is considered as a form of returning control fl...
LLVM_ABI bool hasNonDebugLocLoopMetadata() const
LLVM_ABI bool hasApproxFunc() const LLVM_READONLY
Determine whether the approximate-math-functions flag is set.
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
LLVM_ABI void moveAfterPreserving(Instruction *MovePos)
See moveBeforePreserving .
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI bool hasAtomicLoad() const LLVM_READONLY
Return true if this atomic instruction loads from memory.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void dropPoisonGeneratingMetadata()
Drops metadata that may generate poison.
LLVM_ABI void setHasAllowReciprocal(bool B)
Set or clear the allow-reciprocal flag on this instruction, which must be an operator which supports ...
LLVM_ABI void handleMarkerRemoval()
Handle the debug-info implications of this instruction being removed.
LLVM_ABI bool hasUBImplyingAttrs() const LLVM_READONLY
Return true if this instruction has UB-implying attributes that can cause immediate undefined behavio...
LLVM_ABI std::optional< InstListType::iterator > getInsertionPointAfterDef()
Get the first insertion point at which the result of this instruction is defined.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
LLVM_ABI void dropPoisonGeneratingAttributes()
Drops attributes that may generate poison.
LLVM_ABI void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef< unsigned > KnownIDs={})
This function drops non-debug unknown metadata (through dropUnknownNonDebugMetadata).
LLVM_ABI bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
LLVM_ABI std::optional< simple_ilist< DbgRecord >::iterator > getDbgReinsertionPosition()
Return an iterator to the position of the "Next" DbgRecord after this instruction,...
LLVM_ABI bool isLaunderOrStripInvariantGroup() const LLVM_READONLY
Return true if the instruction is a llvm.launder.invariant.group or llvm.strip.invariant....
LLVM_ABI bool hasAllowContract() const LLVM_READONLY
Determine whether the allow-contract flag is set.
LLVM_ABI void moveBeforePreserving(InstListType::iterator MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
LLVM_ABI bool hasPoisonGeneratingMetadata() const LLVM_READONLY
Return true if this instruction has poison-generating metadata.
Instruction(const Instruction &)=delete
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
LLVM_ABI bool isCommutableOperand(unsigned Op) const LLVM_READONLY
Checks if the operand is commutative.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void setFast(bool B)
Set or clear all fast-math-flags on this instruction, which must be an operator which supports this f...
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
LLVM_ABI void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
LLVM_ABI bool isSafeToRemove() const LLVM_READONLY
Return true if the instruction can be removed if the result is unused.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
LLVM_ABI bool hasDbgRecords() const
Returns true if any DbgRecords are attached to this instruction.
A wrapper class for inspecting calls to intrinsic functions.
Invoke instruction.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
LLVMContext & getContext() const
Definition Metadata.h:1233
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
static constexpr const unsigned PoisonGeneratingIDs[]
Metadata IDs that may generate poison.
Definition Metadata.h:146
iterator_range< const_block_iterator > blocks() const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Instruction that can have a nneg flag (zext/uitofp).
Definition InstrTypes.h:703
This instruction constructs a fixed permutation of two input vectors.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
void reserve(size_type N)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Multiway switch.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
static LLVM_ABI void handleRAUW(Value *From, Value *To)
Definition Metadata.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
void splice(iterator where, iplist_impl &L2)
Definition ilist.h:266
iterator insertAfter(iterator where, pointer New)
Definition ilist.h:174
iterator insert(iterator where, pointer New)
Definition ilist.h:165
A range adaptor for a pair of iterators.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr bool isAtomic(const T &...O)
Definition SIDefines.h:389
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:55
bool mayThrow(const MachineInstr &MI)
@ OB
OB - OneByte - Set if this instruction has a one byte opcode.
initializer< Ty > init(const Ty &Val)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
iterator end() const
Definition BasicBlock.h:89
bool isCommutative(const Instruction *I, const Value *ValWithUses, bool IsCopyable)
Definition SLPUtils.cpp:161
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:830
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isStrongerThanMonotonic(AtomicOrdering AO)
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
bool isStrongerThanUnordered(AtomicOrdering AO)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange(DbgMarker *DebugMarker)
Inline helper to return a range of DbgRecords attached to a marker.
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
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:322
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ Other
Any other memory.
Definition ModRef.h:68
@ FSub
Subtraction of floats.
@ Xor
Bitwise or logical XOR of integers.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2146
@ Keep
No function return thunk.
Definition CodeGen.h:229
Summary of memprof metadata on allocations.
Matching combinators.