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(InsertBefore ? InsertBefore->getIterator()
47 : InstListType::iterator()) {}
49 : InsertAt(InsertAtEnd ? InsertAtEnd->end() : InstListType::iterator()) {}
50
51Instruction::Instruction(Type *ty, unsigned it, AllocInfo AllocInfo,
52 InsertPosition InsertBefore)
53 : User(ty, Value::InstructionVal + it, AllocInfo) {
54 // When called with an iterator, there must be a block to insert into.
55 if (InstListType::iterator InsertIt = InsertBefore; InsertIt.isValid()) {
56 BasicBlock *BB = InsertIt.getNodeParent();
57 assert(BB && "Instruction to insert before is not in a basic block!");
58 insertInto(BB, InsertBefore);
59 }
60}
61
63 assert(!getParent() && "Instruction still linked in the program!");
64
65 // Replace any extant metadata uses of this instruction with poison to
66 // preserve debug info accuracy. Some alternatives include:
67 // - Treat Instruction like any other Value, and point its extant metadata
68 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses
69 // trivially dead (i.e. fair game for deletion in many passes), leading to
70 // stale dbg.values being in effect for too long.
71 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal
72 // correct. OTOH results in wasted work in some common cases (e.g. when all
73 // instructions in a BasicBlock are deleted).
74 if (isUsedByMetadata())
76
77 // Remove associated metadata from context.
78 if (hasMetadata()) {
79 // Explicitly remove DIAssignID metadata to clear up ID -> Instruction(s)
80 // mapping in LLVMContext.
81 updateDIAssignIDMapping(nullptr);
82 clearMetadata();
83 }
84}
85
86const Module *Instruction::getModule() const {
87 return getParent()->getModule();
88}
89
91 return getParent()->getParent();
92}
93
95 return getModule()->getDataLayout();
96}
97
99 // Perform any debug-info maintenence required.
100 handleMarkerRemoval();
101
102 getParent()->getInstList().remove(getIterator());
103}
104
106 if (!DebugMarker)
107 return;
108
109 DebugMarker->removeMarker();
110}
111
113 handleMarkerRemoval();
114 return getParent()->getInstList().erase(getIterator());
115}
116
117void Instruction::insertBefore(Instruction *InsertPos) {
118 insertBefore(InsertPos->getIterator());
119}
120
121/// Insert an unlinked instruction into a basic block immediately before the
122/// specified instruction.
124 insertBefore(*InsertPos->getParent(), InsertPos);
125}
126
127/// Insert an unlinked instruction into a basic block immediately after the
128/// specified instruction.
129void Instruction::insertAfter(Instruction *InsertPos) {
130 BasicBlock *DestParent = InsertPos->getParent();
131
132 DestParent->getInstList().insertAfter(InsertPos->getIterator(), this);
133}
134
136 BasicBlock *DestParent = InsertPos->getParent();
137
138 DestParent->getInstList().insertAfter(InsertPos, this);
139}
140
143 assert(getParent() == nullptr && "Expected detached instruction");
144 assert((It == ParentBB->end() || It->getParent() == ParentBB) &&
145 "It not in ParentBB");
146 insertBefore(*ParentBB, It);
147 return getIterator();
148}
149
151 InstListType::iterator InsertPos) {
152 assert(!DebugMarker);
153
154 BB.getInstList().insert(InsertPos, this);
155
156 // We've inserted "this": if InsertAtHead is set then it comes before any
157 // DbgVariableRecords attached to InsertPos. But if it's not set, then any
158 // DbgRecords should now come before "this".
159 bool InsertAtHead = InsertPos.getHeadBit();
160 if (!InsertAtHead) {
161 DbgMarker *SrcMarker = BB.getMarker(InsertPos);
162 if (SrcMarker && !SrcMarker->empty()) {
163 // If this assertion fires, the calling code is about to insert a PHI
164 // after debug-records, which would form a sequence like:
165 // %0 = PHI
166 // #dbg_value
167 // %1 = PHI
168 // Which is de-normalised and undesired -- hence the assertion. To avoid
169 // this, you must insert at that position using an iterator, and it must
170 // be aquired by calling getFirstNonPHIIt / begin or similar methods on
171 // the block. This will signal to this behind-the-scenes debug-info
172 // maintenence code that you intend the PHI to be ahead of everything,
173 // including any debug-info.
174 assert(!isa<PHINode>(this) && "Inserting PHI after debug-records!");
175 adoptDbgRecords(&BB, InsertPos, false);
176 }
177 }
178
179 // If we're inserting a terminator, check if we need to flush out
180 // TrailingDbgRecords. Inserting instructions at the end of an incomplete
181 // block is handled by the code block above.
182 if (isTerminator())
183 getParent()->flushTerminatorDbgRecords();
184}
185
186/// Unlink this instruction from its current basic block and insert it into the
187/// basic block that MovePos lives in, right before MovePos.
189 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), false);
190}
191
193 moveBeforeImpl(*MovePos->getParent(), MovePos, false);
194}
195
197 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), true);
198}
199
201 moveBeforeImpl(*MovePos->getParent(), MovePos, true);
202}
203
204void Instruction::moveAfter(Instruction *MovePos) {
205 auto NextIt = std::next(MovePos->getIterator());
206 // We want this instruction to be moved to after NextIt in the instruction
207 // list, but before NextIt's debug value range.
208 NextIt.setHeadBit(true);
209 moveBeforeImpl(*MovePos->getParent(), NextIt, false);
210}
211
212void Instruction::moveAfter(InstListType::iterator MovePos) {
213 // We want this instruction to be moved to after NextIt in the instruction
214 // list, but before NextIt's debug value range.
215 MovePos.setHeadBit(true);
216 moveBeforeImpl(*MovePos->getParent(), MovePos, false);
217}
218
220 auto NextIt = std::next(MovePos->getIterator());
221 // We want this instruction and its debug range to be moved to after NextIt
222 // in the instruction list, but before NextIt's debug value range.
223 NextIt.setHeadBit(true);
224 moveBeforeImpl(*MovePos->getParent(), NextIt, true);
225}
226
227void Instruction::moveBefore(BasicBlock &BB, InstListType::iterator I) {
228 moveBeforeImpl(BB, I, false);
229}
230
232 InstListType::iterator I) {
233 moveBeforeImpl(BB, I, true);
234}
235
236void Instruction::moveBeforeImpl(BasicBlock &BB, InstListType::iterator I,
237 bool Preserve) {
238 assert(I == BB.end() || I->getParent() == &BB);
239 bool InsertAtHead = I.getHeadBit();
240
241 // If we've been given the "Preserve" flag, then just move the DbgRecords with
242 // the instruction, no more special handling needed.
243 if (DebugMarker && !Preserve) {
244 if (I != this->getIterator() || InsertAtHead) {
245 // "this" is definitely moving in the list, or it's moving ahead of its
246 // attached DbgVariableRecords. Detach any existing DbgRecords.
247 handleMarkerRemoval();
248 }
249 }
250
251 // Move this single instruction. Use the list splice method directly, not
252 // the block splicer, which will do more debug-info things.
253 BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
254
255 if (!Preserve) {
256 DbgMarker *NextMarker = getParent()->getNextMarker(this);
257
258 // If we're inserting at point I, and not in front of the DbgRecords
259 // attached there, then we should absorb the DbgRecords attached to I.
260 if (!InsertAtHead && NextMarker && !NextMarker->empty()) {
261 adoptDbgRecords(&BB, I, false);
262 }
263 }
264
265 if (isTerminator())
266 getParent()->flushTerminatorDbgRecords();
267}
268
270 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
271 bool InsertAtHead) {
272 if (!From->DebugMarker)
274
275 if (!DebugMarker)
276 getParent()->createMarker(this);
277
278 return DebugMarker->cloneDebugInfoFrom(From->DebugMarker, FromHere,
279 InsertAtHead);
280}
281
282std::optional<DbgRecord::self_iterator>
284 // Is there a marker on the next instruction?
285 DbgMarker *NextMarker = getParent()->getNextMarker(this);
286 if (!NextMarker)
287 return std::nullopt;
288
289 // Are there any DbgRecords in the next marker?
290 if (NextMarker->StoredDbgRecords.empty())
291 return std::nullopt;
292
293 return NextMarker->StoredDbgRecords.begin();
294}
295
296bool Instruction::hasDbgRecords() const { return !getDbgRecordRange().empty(); }
297
299 bool InsertAtHead) {
300 DbgMarker *SrcMarker = BB->getMarker(It);
301 auto ReleaseTrailingDbgRecords = [BB, It, SrcMarker]() {
302 if (BB->end() == It) {
303 SrcMarker->eraseFromParent();
305 }
306 };
307
308 if (!SrcMarker || SrcMarker->StoredDbgRecords.empty()) {
309 ReleaseTrailingDbgRecords();
310 return;
311 }
312
313 // If we have DbgMarkers attached to this instruction, we have to honour the
314 // ordering of DbgRecords between this and the other marker. Fall back to just
315 // absorbing from the source.
316 if (DebugMarker || It == BB->end()) {
317 // Ensure we _do_ have a marker.
318 getParent()->createMarker(this);
319 DebugMarker->absorbDebugValues(*SrcMarker, InsertAtHead);
320
321 // Having transferred everything out of SrcMarker, we _could_ clean it up
322 // and free the marker now. However, that's a lot of heap-accounting for a
323 // small amount of memory with a good chance of re-use. Leave it for the
324 // moment. It will be released when the Instruction is freed in the worst
325 // case.
326 // However: if we transferred from a trailing marker off the end of the
327 // block, it's important to not leave the empty marker trailing. It will
328 // give a misleading impression that some debug records have been left
329 // trailing.
330 ReleaseTrailingDbgRecords();
331 } else {
332 // Optimisation: we're transferring all the DbgRecords from the source
333 // marker onto this empty location: just adopt the other instructions
334 // marker.
335 DebugMarker = SrcMarker;
336 DebugMarker->MarkedInstr = this;
337 It->DebugMarker = nullptr;
338 }
339}
340
342 if (DebugMarker)
343 DebugMarker->dropDbgRecords();
344}
345
347 DebugMarker->dropOneDbgRecord(DVR);
348}
349
350bool Instruction::comesBefore(const Instruction *Other) const {
351 assert(getParent() && Other->getParent() &&
352 "instructions without BB parents have no order");
353 assert(getParent() == Other->getParent() &&
354 "cross-BB instruction order comparison");
355 if (!getParent()->isInstrOrderValid())
356 const_cast<BasicBlock *>(getParent())->renumberInstructions();
357 return Order < Other->Order;
358}
359
360std::optional<BasicBlock::iterator> Instruction::getInsertionPointAfterDef() {
361 assert(!getType()->isVoidTy() && "Instruction must define result");
362 BasicBlock *InsertBB;
363 BasicBlock::iterator InsertPt;
364 if (auto *PN = dyn_cast<PHINode>(this)) {
365 InsertBB = PN->getParent();
366 InsertPt = InsertBB->getFirstInsertionPt();
367 } else if (auto *II = dyn_cast<InvokeInst>(this)) {
368 InsertBB = II->getNormalDest();
369 InsertPt = InsertBB->getFirstInsertionPt();
370 } else if (isa<CallBrInst>(this)) {
371 // Def is available in multiple successors, there's no single dominating
372 // insertion point.
373 return std::nullopt;
374 } else {
375 assert(!isTerminator() && "Only invoke/callbr terminators return value");
376 InsertBB = getParent();
377 InsertPt = std::next(getIterator());
378 // Any instruction inserted immediately after "this" will come before any
379 // debug-info records take effect -- thus, set the head bit indicating that
380 // to debug-info-transfer code.
381 InsertPt.setHeadBit(true);
382 }
383
384 // catchswitch blocks don't have any legal insertion point (because they
385 // are both an exception pad and a terminator).
386 if (InsertPt == InsertBB->end())
387 return std::nullopt;
388 return InsertPt;
389}
390
392 return any_of(operands(), [](const Value *V) { return V->hasOneUser(); });
393}
394
396 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
397 Inst->setHasNoUnsignedWrap(b);
398 else
399 cast<TruncInst>(this)->setHasNoUnsignedWrap(b);
400}
401
403 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
404 Inst->setHasNoSignedWrap(b);
405 else
406 cast<TruncInst>(this)->setHasNoSignedWrap(b);
407}
408
409void Instruction::setIsExact(bool b) {
410 cast<PossiblyExactOperator>(this)->setIsExact(b);
411}
412
413void Instruction::setNonNeg(bool b) {
414 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
415 SubclassOptionalData = (SubclassOptionalData & ~PossiblyNonNegInst::NonNeg) |
417}
418
420 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
421 return Inst->hasNoUnsignedWrap();
422
423 return cast<TruncInst>(this)->hasNoUnsignedWrap();
424}
425
426bool Instruction::hasNoSignedWrap() const {
427 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
428 return Inst->hasNoSignedWrap();
429
430 return cast<TruncInst>(this)->hasNoSignedWrap();
431}
432
433bool Instruction::hasNonNeg() const {
434 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
435 return (SubclassOptionalData & PossiblyNonNegInst::NonNeg) != 0;
436}
437
439 return cast<Operator>(this)->hasPoisonGeneratingFlags();
440}
441
443 switch (getOpcode()) {
444 case Instruction::Add:
445 case Instruction::Sub:
446 case Instruction::Mul:
447 case Instruction::Shl:
448 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
449 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
450 break;
451
452 case Instruction::UDiv:
453 case Instruction::SDiv:
454 case Instruction::AShr:
455 case Instruction::LShr:
456 cast<PossiblyExactOperator>(this)->setIsExact(false);
457 break;
458
459 case Instruction::Or:
460 cast<PossiblyDisjointInst>(this)->setIsDisjoint(false);
461 break;
462
463 case Instruction::GetElementPtr:
464 cast<GetElementPtrInst>(this)->setNoWrapFlags(GEPNoWrapFlags::none());
465 break;
466
467 case Instruction::UIToFP:
468 case Instruction::ZExt:
469 setNonNeg(false);
470 break;
471
472 case Instruction::Trunc:
473 cast<TruncInst>(this)->setHasNoUnsignedWrap(false);
474 cast<TruncInst>(this)->setHasNoSignedWrap(false);
475 break;
476
477 case Instruction::ICmp:
478 cast<ICmpInst>(this)->setSameSign(false);
479 break;
480
481 case Instruction::Call: {
482 if (auto *II = dyn_cast<IntrinsicInst>(this)) {
483 switch (II->getIntrinsicID()) {
484 case Intrinsic::ctlz:
485 case Intrinsic::cttz:
486 case Intrinsic::abs:
487 II->setOperand(1, ConstantInt::getFalse(getContext()));
488 break;
489 }
490 }
491 break;
492 }
493 }
494
495 if (isa<FPMathOperator>(this)) {
496 setHasNoNaNs(false);
497 setHasNoInfs(false);
498 }
499
500 assert(!hasPoisonGeneratingFlags() && "must be kept in sync");
501}
502
505 [this](unsigned ID) { return hasMetadata(ID); });
506}
507
509 // If there is no loop metadata at all, we also don't have
510 // non-debug loop metadata, obviously.
511 if (!hasMetadata(LLVMContext::MD_loop))
512 return false;
513
514 // If we do have loop metadata, retrieve it.
515 MDNode *LoopMD = getMetadata(LLVMContext::MD_loop);
516
517 // Check if the existing operands are debug locations. This loop
518 // should terminate after at most three iterations. Skip
519 // the first item because it is a self-reference.
520 for (const MDOperand &Op : llvm::drop_begin(LoopMD->operands())) {
521 // check for debug location type by attempting a cast.
522 if (!isa<DILocation>(Op)) {
523 return true;
524 }
525 }
526
527 // If we get here, then all we have is debug locations in the loop metadata.
528 return false;
529}
530
532 for (unsigned ID : Metadata::PoisonGeneratingIDs)
533 eraseMetadata(ID);
534}
535
537 if (const auto *CB = dyn_cast<CallBase>(this)) {
538 auto HasPoisonGeneratingAttributes = [](AttributeSet Attrs) {
539 return Attrs.hasAttribute(Attribute::Range) ||
540 Attrs.hasAttribute(Attribute::Alignment) ||
541 Attrs.hasAttribute(Attribute::NonNull) ||
542 Attrs.hasAttribute(Attribute::NoFPClass);
543 };
544 if (HasPoisonGeneratingAttributes(CB->getRetAttributes()))
545 return true;
546 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
547 if (HasPoisonGeneratingAttributes(CB->getParamAttributes(ArgNo)))
548 return true;
549 }
550 return false;
551}
552
554 if (auto *CB = dyn_cast<CallBase>(this)) {
555 AttributeMask AM;
556 AM.addAttribute(Attribute::Range);
557 AM.addAttribute(Attribute::Alignment);
558 AM.addAttribute(Attribute::NonNull);
559 AM.addAttribute(Attribute::NoFPClass);
560 CB->removeRetAttrs(AM);
561 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
562 CB->removeParamAttrs(ArgNo, AM);
563 }
564 assert(!hasPoisonGeneratingAttributes() && "must be kept in sync");
565}
566
568 ArrayRef<unsigned> KnownIDs) {
569 dropUnknownNonDebugMetadata(KnownIDs);
570 auto *CB = dyn_cast<CallBase>(this);
571 if (!CB)
572 return;
573 // For call instructions, we also need to drop parameter and return attributes
574 // that can cause UB if the call is moved to a location where the attribute is
575 // not valid.
576 AttributeList AL = CB->getAttributes();
577 if (AL.isEmpty())
578 return;
579 AttributeMask UBImplyingAttributes =
580 AttributeFuncs::getUBImplyingAttributes();
581 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
582 CB->removeParamAttrs(ArgNo, UBImplyingAttributes);
583 CB->removeRetAttrs(UBImplyingAttributes);
584}
585
587 // !annotation and !prof metadata does not impact semantics.
588 // !range, !nonnull, !align and !nofpclass produce poison, so they are safe to
589 // speculate.
590 // !fpmath specifies floating-point precision and does not imply UB.
591 // !mem.cache_hint is a performance hint and does not imply UB.
592 // !noundef and various AA metadata must be dropped, as it generally produces
593 // immediate undefined behavior.
594 static const unsigned KnownIDs[] = {
595 LLVMContext::MD_annotation, LLVMContext::MD_range,
596 LLVMContext::MD_nonnull, LLVMContext::MD_align,
597 LLVMContext::MD_fpmath, LLVMContext::MD_prof,
598 LLVMContext::MD_mem_cache_hint, LLVMContext::MD_nofpclass};
599 SmallVector<unsigned> KeepIDs;
600 KeepIDs.reserve(Keep.size() + std::size(KnownIDs));
601 append_range(KeepIDs, (!ProfcheckDisableMetadataFixes ? KnownIDs
602 : drop_end(KnownIDs)));
603 append_range(KeepIDs, Keep);
604 dropUBImplyingAttrsAndUnknownMetadata(KeepIDs);
605}
606
608 auto *CB = dyn_cast<CallBase>(this);
609 if (!CB)
610 return false;
611 // For call instructions, we also need to check parameter and return
612 // attributes that can cause UB.
613 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
614 if (CB->isPassingUndefUB(ArgNo))
615 return true;
616 return CB->hasRetAttr(Attribute::NoUndef) ||
617 CB->hasRetAttr(Attribute::Dereferenceable) ||
618 CB->hasRetAttr(Attribute::DereferenceableOrNull);
619}
620
621bool Instruction::isExact() const {
622 return cast<PossiblyExactOperator>(this)->isExact();
623}
624
625void Instruction::setFast(bool B) {
626 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
627 cast<FPMathOperator>(this)->setFast(B);
628}
629
631 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
632 cast<FPMathOperator>(this)->setHasAllowReassoc(B);
633}
634
635void Instruction::setHasNoNaNs(bool B) {
636 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
637 cast<FPMathOperator>(this)->setHasNoNaNs(B);
638}
639
640void Instruction::setHasNoInfs(bool B) {
641 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
642 cast<FPMathOperator>(this)->setHasNoInfs(B);
643}
644
646 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
647 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
648}
649
651 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
652 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
653}
654
656 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
657 cast<FPMathOperator>(this)->setHasAllowContract(B);
658}
659
661 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
662 cast<FPMathOperator>(this)->setHasApproxFunc(B);
663}
664
666 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
667 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
668}
669
671 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
672 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
673}
674
675bool Instruction::isFast() const {
676 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
677 return cast<FPMathOperator>(this)->isFast();
678}
679
680bool Instruction::hasAllowReassoc() const {
681 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
682 return cast<FPMathOperator>(this)->hasAllowReassoc();
683}
684
685bool Instruction::hasNoNaNs() const {
686 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
687 return cast<FPMathOperator>(this)->hasNoNaNs();
688}
689
690bool Instruction::hasNoInfs() const {
691 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
692 return cast<FPMathOperator>(this)->hasNoInfs();
693}
694
696 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
697 return cast<FPMathOperator>(this)->hasNoSignedZeros();
698}
699
701 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
702 return cast<FPMathOperator>(this)->hasAllowReciprocal();
703}
704
706 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
707 return cast<FPMathOperator>(this)->hasAllowContract();
708}
709
710bool Instruction::hasApproxFunc() const {
711 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
712 return cast<FPMathOperator>(this)->hasApproxFunc();
713}
714
716 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
717 return cast<FPMathOperator>(this)->getFastMathFlags();
718}
719
721 if (!isa<FPMathOperator>(this))
722 return {};
723 return cast<FPMathOperator>(this)->getFastMathFlags();
724}
725
727 copyFastMathFlags(I->getFastMathFlags());
728}
729
730void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
731 // Copy the wrapping flags.
732 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
733 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
734 setHasNoSignedWrap(OB->hasNoSignedWrap());
735 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
736 }
737 }
738
739 if (auto *TI = dyn_cast<TruncInst>(V)) {
740 if (isa<TruncInst>(this)) {
741 setHasNoSignedWrap(TI->hasNoSignedWrap());
742 setHasNoUnsignedWrap(TI->hasNoUnsignedWrap());
743 }
744 }
745
746 // Copy the exact flag.
747 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
749 setIsExact(PE->isExact());
750
751 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
752 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
753 DestPD->setIsDisjoint(SrcPD->isDisjoint());
754
755 // Copy the fast-math flags.
756 if (auto *FP = dyn_cast<FPMathOperator>(V))
757 if (isa<FPMathOperator>(this))
758 copyFastMathFlags(FP->getFastMathFlags());
759
760 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
761 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
762 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() |
763 DestGEP->getNoWrapFlags());
764
765 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
766 if (isa<PossiblyNonNegInst>(this))
767 setNonNeg(NNI->hasNonNeg());
768
769 if (auto *SrcICmp = dyn_cast<ICmpInst>(V))
770 if (auto *DestICmp = dyn_cast<ICmpInst>(this))
771 DestICmp->setSameSign(SrcICmp->hasSameSign());
772}
773
774void Instruction::andIRFlags(const Value *V) {
775 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
777 setHasNoSignedWrap(hasNoSignedWrap() && OB->hasNoSignedWrap());
778 setHasNoUnsignedWrap(hasNoUnsignedWrap() && OB->hasNoUnsignedWrap());
779 }
780 }
781
782 if (auto *TI = dyn_cast<TruncInst>(V)) {
783 if (isa<TruncInst>(this)) {
784 setHasNoSignedWrap(hasNoSignedWrap() && TI->hasNoSignedWrap());
785 setHasNoUnsignedWrap(hasNoUnsignedWrap() && TI->hasNoUnsignedWrap());
786 }
787 }
788
789 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
791 setIsExact(isExact() && PE->isExact());
792
793 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
794 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
795 DestPD->setIsDisjoint(DestPD->isDisjoint() && SrcPD->isDisjoint());
796
797 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
798 if (isa<FPMathOperator>(this)) {
800 FM &= FP->getFastMathFlags();
801 copyFastMathFlags(FM);
802 }
803 }
804
805 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
806 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
807 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() &
808 DestGEP->getNoWrapFlags());
809
810 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
811 if (isa<PossiblyNonNegInst>(this))
812 setNonNeg(hasNonNeg() && NNI->hasNonNeg());
813
814 if (auto *SrcICmp = dyn_cast<ICmpInst>(V))
815 if (auto *DestICmp = dyn_cast<ICmpInst>(this))
816 DestICmp->setSameSign(DestICmp->hasSameSign() && SrcICmp->hasSameSign());
817}
818
819const char *Instruction::getOpcodeName(unsigned OpCode) {
820 switch (OpCode) {
821 // Terminators
822 case Ret: return "ret";
823 case UncondBr: return "br";
824 case CondBr: return "br";
825 case Switch: return "switch";
826 case IndirectBr: return "indirectbr";
827 case Invoke: return "invoke";
828 case Resume: return "resume";
829 case Unreachable: return "unreachable";
830 case CleanupRet: return "cleanupret";
831 case CatchRet: return "catchret";
832 case CatchPad: return "catchpad";
833 case CatchSwitch: return "catchswitch";
834 case CallBr: return "callbr";
835
836 // Standard unary operators...
837 case FNeg: return "fneg";
838
839 // Standard binary operators...
840 case Add: return "add";
841 case FAdd: return "fadd";
842 case Sub: return "sub";
843 case FSub: return "fsub";
844 case Mul: return "mul";
845 case FMul: return "fmul";
846 case UDiv: return "udiv";
847 case SDiv: return "sdiv";
848 case FDiv: return "fdiv";
849 case URem: return "urem";
850 case SRem: return "srem";
851 case FRem: return "frem";
852
853 // Logical operators...
854 case And: return "and";
855 case Or : return "or";
856 case Xor: return "xor";
857
858 // Memory instructions...
859 case Alloca: return "alloca";
860 case Load: return "load";
861 case Store: return "store";
862 case AtomicCmpXchg: return "cmpxchg";
863 case AtomicRMW: return "atomicrmw";
864 case Fence: return "fence";
865 case GetElementPtr: return "getelementptr";
866
867 // Convert instructions...
868 case Trunc: return "trunc";
869 case ZExt: return "zext";
870 case SExt: return "sext";
871 case FPTrunc: return "fptrunc";
872 case FPExt: return "fpext";
873 case FPToUI: return "fptoui";
874 case FPToSI: return "fptosi";
875 case UIToFP: return "uitofp";
876 case SIToFP: return "sitofp";
877 case IntToPtr: return "inttoptr";
878 case PtrToAddr: return "ptrtoaddr";
879 case PtrToInt: return "ptrtoint";
880 case BitCast: return "bitcast";
881 case AddrSpaceCast: return "addrspacecast";
882
883 // Other instructions...
884 case ICmp: return "icmp";
885 case FCmp: return "fcmp";
886 case PHI: return "phi";
887 case Select: return "select";
888 case Call: return "call";
889 case Shl: return "shl";
890 case LShr: return "lshr";
891 case AShr: return "ashr";
892 case VAArg: return "va_arg";
893 case ExtractElement: return "extractelement";
894 case InsertElement: return "insertelement";
895 case ShuffleVector: return "shufflevector";
896 case ExtractValue: return "extractvalue";
897 case InsertValue: return "insertvalue";
898 case LandingPad: return "landingpad";
899 case CleanupPad: return "cleanuppad";
900 case Freeze: return "freeze";
901
902 default: return "<Invalid operator> ";
903 }
904}
905
906/// This must be kept in sync with FunctionComparator::cmpOperations in
907/// lib/Transforms/Utils/FunctionComparator.cpp.
909 bool IgnoreAlignment,
910 bool IntersectAttrs) const {
911 const auto *I1 = this;
912 assert(I1->getOpcode() == I2->getOpcode() &&
913 "Can not compare special state of different instructions");
914
915 auto CheckAttrsSame = [IntersectAttrs](const CallBase *CB0,
916 const CallBase *CB1) {
917 return IntersectAttrs
918 ? CB0->getAttributes()
919 .intersectWith(CB0->getContext(), CB1->getAttributes())
920 .has_value()
921 : CB0->getAttributes() == CB1->getAttributes();
922 };
923
924 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
925 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
926 (AI->getAlign() == cast<AllocaInst>(I2)->getAlign() ||
927 IgnoreAlignment);
928 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
929 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
930 LI->isElementwise() == cast<LoadInst>(I2)->isElementwise() &&
931 (LI->getAlign() == cast<LoadInst>(I2)->getAlign() ||
932 IgnoreAlignment) &&
933 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
934 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
935 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
936 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
937 (SI->getAlign() == cast<StoreInst>(I2)->getAlign() ||
938 IgnoreAlignment) &&
939 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
940 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
941 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
942 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
943 if (const CallInst *CI = dyn_cast<CallInst>(I1))
944 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
945 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
946 CheckAttrsSame(CI, cast<CallInst>(I2)) &&
947 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
948 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
949 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
950 CheckAttrsSame(CI, cast<InvokeInst>(I2)) &&
951 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
952 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
953 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
954 CheckAttrsSame(CI, cast<CallBrInst>(I2)) &&
955 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
956 if (const SwitchInst *SI = dyn_cast<SwitchInst>(I1)) {
957 for (auto [Case1, Case2] : zip(SI->cases(), cast<SwitchInst>(I2)->cases()))
958 if (Case1.getCaseValue() != Case2.getCaseValue())
959 return false;
960 return true;
961 }
962 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
963 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
964 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
965 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
966 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
967 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
968 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
970 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
971 (CXI->getAlign() == cast<AtomicCmpXchgInst>(I2)->getAlign() ||
972 IgnoreAlignment) &&
973 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
974 CXI->getSuccessOrdering() ==
975 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
976 CXI->getFailureOrdering() ==
977 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
978 CXI->getSyncScopeID() ==
979 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
980 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
981 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
982 RMWI->isElementwise() == cast<AtomicRMWInst>(I2)->isElementwise() &&
983 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
984 (RMWI->getAlign() == cast<AtomicRMWInst>(I2)->getAlign() ||
985 IgnoreAlignment) &&
986 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
987 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
989 return SVI->getShuffleMask() ==
990 cast<ShuffleVectorInst>(I2)->getShuffleMask();
992 return GEP->getSourceElementType() ==
993 cast<GetElementPtrInst>(I2)->getSourceElementType();
994
995 return true;
996}
997
998bool Instruction::isIdenticalTo(const Instruction *I) const {
999 return isIdenticalToWhenDefined(I) &&
1000 SubclassOptionalData == I->SubclassOptionalData;
1001}
1002
1004 bool IntersectAttrs) const {
1005 if (getOpcode() != I->getOpcode() ||
1006 getNumOperands() != I->getNumOperands() || getType() != I->getType())
1007 return false;
1008
1009 // If both instructions have no operands, they are identical.
1010 if (getNumOperands() == 0 && I->getNumOperands() == 0)
1011 return this->hasSameSpecialState(I, /*IgnoreAlignment=*/false,
1012 IntersectAttrs);
1013
1014 // We have two instructions of identical opcode and #operands. Check to see
1015 // if all operands are the same.
1016 if (!equal(operands(), I->operands()))
1017 return false;
1018
1019 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()!
1020 if (const PHINode *Phi = dyn_cast<PHINode>(this)) {
1021 const PHINode *OtherPhi = cast<PHINode>(I);
1022 return equal(Phi->blocks(), OtherPhi->blocks());
1023 }
1024
1025 return this->hasSameSpecialState(I, /*IgnoreAlignment=*/false,
1026 IntersectAttrs);
1027}
1028
1029// Keep this in sync with FunctionComparator::cmpOperations in
1030// lib/Transforms/IPO/MergeFunctions.cpp.
1032 unsigned flags) const {
1033 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
1034 bool UseScalarTypes = flags & CompareUsingScalarTypes;
1035 bool IntersectAttrs = flags & CompareUsingIntersectedAttrs;
1036
1037 if (getOpcode() != I->getOpcode() ||
1038 getNumOperands() != I->getNumOperands() ||
1039 (UseScalarTypes ?
1040 getType()->getScalarType() != I->getType()->getScalarType() :
1041 getType() != I->getType()))
1042 return false;
1043
1044 // We have two instructions of identical opcode and #operands. Check to see
1045 // if all operands are the same type
1046 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1047 if (UseScalarTypes ?
1048 getOperand(i)->getType()->getScalarType() !=
1049 I->getOperand(i)->getType()->getScalarType() :
1050 getOperand(i)->getType() != I->getOperand(i)->getType())
1051 return false;
1052
1053 return this->hasSameSpecialState(I, IgnoreAlignment, IntersectAttrs);
1054}
1055
1056bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
1057 for (const Use &U : uses()) {
1058 // PHI nodes uses values in the corresponding predecessor block. For other
1059 // instructions, just check to see whether the parent of the use matches up.
1060 const Instruction *I = cast<Instruction>(U.getUser());
1061 const PHINode *PN = dyn_cast<PHINode>(I);
1062 if (!PN) {
1063 if (I->getParent() != BB)
1064 return true;
1065 continue;
1066 }
1067
1068 if (PN->getIncomingBlock(U) != BB)
1069 return true;
1070 }
1071 return false;
1072}
1073
1075 auto GetEffects = [](ModRefInfo BaseMR, AtomicOrdering Ordering,
1076 bool IsVolatile) {
1077 if (isStrongerThanMonotonic(Ordering))
1078 return MemoryEffects::unknown();
1079
1080 if (IsVolatile)
1082
1083 if (isStrongerThanUnordered(Ordering))
1085
1086 return MemoryEffects::argMemOnly(BaseMR);
1087 };
1088 switch (getOpcode()) {
1089 default:
1090 return MemoryEffects::none();
1091 case Instruction::VAArg:
1093 case Instruction::CatchPad:
1094 case Instruction::CatchRet:
1095 case Instruction::Fence:
1096 return MemoryEffects::unknown();
1097 case Instruction::Call:
1098 case Instruction::Invoke:
1099 case Instruction::CallBr:
1100 return cast<CallBase>(this)->getMemoryEffects();
1101 case Instruction::Load: {
1102 auto *LI = cast<LoadInst>(this);
1103 return GetEffects(ModRefInfo::Ref, LI->getOrdering(), LI->isVolatile());
1104 }
1105 case Instruction::Store: {
1106 auto *SI = cast<StoreInst>(this);
1107 return GetEffects(ModRefInfo::Mod, SI->getOrdering(), SI->isVolatile());
1108 }
1109 case Instruction::AtomicRMW: {
1110 auto *RMW = cast<AtomicRMWInst>(this);
1111 return GetEffects(ModRefInfo::ModRef, RMW->getOrdering(),
1112 RMW->isVolatile());
1113 }
1114 case Instruction::AtomicCmpXchg: {
1115 auto *CX = cast<AtomicCmpXchgInst>(this);
1116 return GetEffects(ModRefInfo::ModRef, CX->getSuccessOrdering(),
1117 CX->isVolatile());
1118 }
1119 }
1120}
1121
1122// This is duplicating the logic from getMemoryEffects() for performance
1123// reasons. Computing the full MemoryEffects just to perform a Mod/Ref check
1124// is expensive.
1125
1126bool Instruction::mayReadFromMemory() const {
1127 switch (getOpcode()) {
1128 default: return false;
1129 case Instruction::VAArg:
1130 case Instruction::Load:
1131 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
1132 case Instruction::AtomicCmpXchg:
1133 case Instruction::AtomicRMW:
1134 case Instruction::CatchPad:
1135 case Instruction::CatchRet:
1136 return true;
1137 case Instruction::Call:
1138 case Instruction::Invoke:
1139 case Instruction::CallBr:
1140 return !cast<CallBase>(this)->onlyWritesMemory();
1141 case Instruction::Store:
1142 return !cast<StoreInst>(this)->isUnordered();
1143 }
1144}
1145
1146bool Instruction::mayWriteToMemory() const {
1147 switch (getOpcode()) {
1148 default: return false;
1149 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
1150 case Instruction::Store:
1151 case Instruction::VAArg:
1152 case Instruction::AtomicCmpXchg:
1153 case Instruction::AtomicRMW:
1154 case Instruction::CatchPad:
1155 case Instruction::CatchRet:
1156 return true;
1157 case Instruction::Call:
1158 case Instruction::Invoke:
1159 case Instruction::CallBr:
1160 return !cast<CallBase>(this)->onlyReadsMemory();
1161 case Instruction::Load:
1162 return !cast<LoadInst>(this)->isUnordered();
1163 }
1164}
1165
1166bool Instruction::isAtomic() const {
1167 switch (getOpcode()) {
1168 default:
1169 return false;
1170 case Instruction::AtomicCmpXchg:
1171 case Instruction::AtomicRMW:
1172 case Instruction::Fence:
1173 return true;
1174 case Instruction::Load:
1175 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
1176 case Instruction::Store:
1177 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
1178 }
1179}
1180
1181bool Instruction::hasAtomicLoad() const {
1182 assert(isAtomic());
1183 switch (getOpcode()) {
1184 default:
1185 return false;
1186 case Instruction::AtomicCmpXchg:
1187 case Instruction::AtomicRMW:
1188 case Instruction::Load:
1189 return true;
1190 }
1191}
1192
1193bool Instruction::hasAtomicStore() const {
1194 assert(isAtomic());
1195 switch (getOpcode()) {
1196 default:
1197 return false;
1198 case Instruction::AtomicCmpXchg:
1199 case Instruction::AtomicRMW:
1200 case Instruction::Store:
1201 return true;
1202 }
1203}
1204
1205bool Instruction::isVolatile() const {
1206 switch (getOpcode()) {
1207 default:
1208 return false;
1209 case Instruction::AtomicRMW:
1210 return cast<AtomicRMWInst>(this)->isVolatile();
1211 case Instruction::Store:
1212 return cast<StoreInst>(this)->isVolatile();
1213 case Instruction::Load:
1214 return cast<LoadInst>(this)->isVolatile();
1215 case Instruction::AtomicCmpXchg:
1216 return cast<AtomicCmpXchgInst>(this)->isVolatile();
1217 case Instruction::Call:
1218 case Instruction::Invoke:
1219 // There are a very limited number of intrinsics with volatile flags.
1220 if (auto *II = dyn_cast<IntrinsicInst>(this)) {
1221 if (auto *MI = dyn_cast<MemIntrinsic>(II))
1222 return MI->isVolatile();
1223 switch (II->getIntrinsicID()) {
1224 default: break;
1225 case Intrinsic::matrix_column_major_load:
1226 return cast<ConstantInt>(II->getArgOperand(2))->isOne();
1227 case Intrinsic::matrix_column_major_store:
1228 return cast<ConstantInt>(II->getArgOperand(3))->isOne();
1229 }
1230 }
1231 return false;
1232 }
1233}
1234
1235bool Instruction::maySynchronize() const {
1236 // FIXME: This currently treats atomics with monotonic ordering as
1237 // synchronizing. This is unnecessarily conservative and does not match
1238 // our LangRef definition of the property.
1239 switch (getOpcode()) {
1240 default:
1241 assert(!isAtomic() && "Unhandled atomic instruction");
1242 return false;
1243 case Instruction::Fence: {
1244 // All legal orderings for fence are stronger than monotonic.
1245 auto *FI = cast<FenceInst>(this);
1246 return FI->getSyncScopeID() != SyncScope::SingleThread;
1247 }
1248 case Instruction::AtomicRMW:
1249 case Instruction::AtomicCmpXchg:
1250 return true;
1251 case Instruction::Store:
1252 return isStrongerThanUnordered(cast<StoreInst>(this)->getOrdering());
1253 case Instruction::Load:
1254 return isStrongerThanUnordered(cast<LoadInst>(this)->getOrdering());
1255 case Instruction::Call:
1256 case Instruction::Invoke:
1257 case Instruction::CallBr:
1258 return !cast<CallBase>(this)->hasFnAttr(Attribute::NoSync);
1259 }
1260}
1261
1262Type *Instruction::getAccessType() const {
1263 switch (getOpcode()) {
1264 case Instruction::Store:
1265 return cast<StoreInst>(this)->getValueOperand()->getType();
1266 case Instruction::Load:
1267 case Instruction::AtomicRMW:
1268 return getType();
1269 case Instruction::AtomicCmpXchg:
1270 return cast<AtomicCmpXchgInst>(this)->getNewValOperand()->getType();
1271 case Instruction::Call:
1272 case Instruction::Invoke:
1273 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(this)) {
1274 switch (II->getIntrinsicID()) {
1275 case Intrinsic::masked_load:
1276 case Intrinsic::masked_gather:
1277 case Intrinsic::masked_expandload:
1278 case Intrinsic::vp_load:
1279 case Intrinsic::vp_gather:
1280 case Intrinsic::experimental_vp_strided_load:
1281 return II->getType();
1282 case Intrinsic::masked_store:
1283 case Intrinsic::masked_scatter:
1284 case Intrinsic::masked_compressstore:
1285 case Intrinsic::vp_store:
1286 case Intrinsic::vp_scatter:
1287 case Intrinsic::experimental_vp_strided_store:
1288 return II->getOperand(0)->getType();
1289 default:
1290 break;
1291 }
1292 }
1293 }
1294
1295 return nullptr;
1296}
1297
1298static bool canUnwindPastLandingPad(const LandingPadInst *LP,
1299 bool IncludePhaseOneUnwind) {
1300 // Because phase one unwinding skips cleanup landingpads, we effectively
1301 // unwind past this frame, and callers need to have valid unwind info.
1302 if (LP->isCleanup())
1303 return IncludePhaseOneUnwind;
1304
1305 for (unsigned I = 0; I < LP->getNumClauses(); ++I) {
1306 Constant *Clause = LP->getClause(I);
1307 // catch ptr null catches all exceptions.
1308 if (LP->isCatch(I) && isa<ConstantPointerNull>(Clause))
1309 return false;
1310 // filter [0 x ptr] catches all exceptions.
1311 if (LP->isFilter(I) && Clause->getType()->getArrayNumElements() == 0)
1312 return false;
1313 }
1314
1315 // May catch only some subset of exceptions, in which case other exceptions
1316 // will continue unwinding.
1317 return true;
1318}
1319
1320bool Instruction::mayThrow(bool IncludePhaseOneUnwind) const {
1321 switch (getOpcode()) {
1322 case Instruction::Call:
1323 return !cast<CallInst>(this)->doesNotThrow();
1324 case Instruction::CleanupRet:
1325 return cast<CleanupReturnInst>(this)->unwindsToCaller();
1326 case Instruction::CatchSwitch:
1327 return cast<CatchSwitchInst>(this)->unwindsToCaller();
1328 case Instruction::Resume:
1329 return true;
1330 case Instruction::Invoke: {
1331 // Landingpads themselves don't unwind -- however, an invoke of a skipped
1332 // landingpad may continue unwinding.
1333 BasicBlock *UnwindDest = cast<InvokeInst>(this)->getUnwindDest();
1334 BasicBlock::iterator Pad = UnwindDest->getFirstNonPHIIt();
1335 if (auto *LP = dyn_cast<LandingPadInst>(Pad))
1336 return canUnwindPastLandingPad(LP, IncludePhaseOneUnwind);
1337 return false;
1338 }
1339 case Instruction::CleanupPad:
1340 // Treat the same as cleanup landingpad.
1341 return IncludePhaseOneUnwind;
1342 default:
1343 return false;
1344 }
1345}
1346
1348 return mayWriteToMemory() || mayThrow() || !willReturn();
1349}
1350
1351bool Instruction::isSafeToRemove() const {
1352 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
1353 !this->isTerminator() && !this->isEHPad();
1354}
1355
1356bool Instruction::willReturn() const {
1357 // Volatile operations are not guaranteed to return.
1358 if (isVolatile())
1359 return false;
1360
1361 if (const auto *CB = dyn_cast<CallBase>(this))
1362 return CB->hasFnAttr(Attribute::WillReturn);
1363 return true;
1364}
1365
1367 auto *II = dyn_cast<IntrinsicInst>(this);
1368 if (!II)
1369 return false;
1370 Intrinsic::ID ID = II->getIntrinsicID();
1371 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
1372}
1373
1375 auto *II = dyn_cast<IntrinsicInst>(this);
1376 if (!II)
1377 return false;
1378 Intrinsic::ID ID = II->getIntrinsicID();
1379 return ID == Intrinsic::launder_invariant_group ||
1380 ID == Intrinsic::strip_invariant_group;
1381}
1382
1384 return isa<DbgInfoIntrinsic>(this) || isa<PseudoProbeInst>(this);
1385}
1386
1388 return getDebugLoc();
1389}
1390
1391bool Instruction::isAssociative() const {
1392 if (auto *II = dyn_cast<IntrinsicInst>(this))
1393 return II->isAssociative();
1394 unsigned Opcode = getOpcode();
1395 if (isAssociative(Opcode))
1396 return true;
1397
1398 switch (Opcode) {
1399 case FMul:
1400 return cast<FPMathOperator>(this)->hasAllowReassoc();
1401 case FAdd:
1402 return cast<FPMathOperator>(this)->hasAllowReassoc() &&
1403 cast<FPMathOperator>(this)->hasNoSignedZeros();
1404 default:
1405 return false;
1406 }
1407}
1408
1409bool Instruction::isCommutative() const {
1410 if (auto *II = dyn_cast<IntrinsicInst>(this))
1411 return II->isCommutative();
1412 // TODO: Should allow icmp/fcmp?
1413 return isCommutative(getOpcode());
1414}
1415
1416bool Instruction::isCommutableOperand(unsigned Op) const {
1417 if (auto *II = dyn_cast<IntrinsicInst>(this))
1418 return II->isCommutableOperand(Op);
1419 // TODO: Should allow icmp/fcmp?
1420 return isCommutative(getOpcode());
1421}
1422
1423unsigned Instruction::getNumSuccessors() const {
1424 switch (getOpcode()) {
1425#define HANDLE_TERM_INST(N, OPC, CLASS) \
1426 case Instruction::OPC: \
1427 return static_cast<const CLASS *>(this)->getNumSuccessors();
1428#include "llvm/IR/Instruction.def"
1429 default:
1430 break;
1431 }
1432 llvm_unreachable("not a terminator");
1433}
1434
1435BasicBlock *Instruction::getSuccessor(unsigned idx) const {
1436 switch (getOpcode()) {
1437#define HANDLE_TERM_INST(N, OPC, CLASS) \
1438 case Instruction::OPC: \
1439 return static_cast<const CLASS *>(this)->getSuccessor(idx);
1440#include "llvm/IR/Instruction.def"
1441 default:
1442 break;
1443 }
1444 llvm_unreachable("not a terminator");
1445}
1446
1447void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
1448 switch (getOpcode()) {
1449#define HANDLE_TERM_INST(N, OPC, CLASS) \
1450 case Instruction::OPC: \
1451 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
1452#include "llvm/IR/Instruction.def"
1453 default:
1454 break;
1455 }
1456 llvm_unreachable("not a terminator");
1457}
1458
1461 switch (getOpcode()) {
1462#define HANDLE_TERM_INST(N, OPC, CLASS) \
1463 case Instruction::OPC: \
1464 return static_cast<const CLASS *>(this)->successors();
1465#include "llvm/IR/Instruction.def"
1466 default:
1467 break;
1468 }
1469 llvm_unreachable("not a terminator");
1470}
1471
1473 auto Succs = successors();
1474 for (auto I = Succs.begin(), E = Succs.end(); I != E; ++I)
1475 if (*I == OldBB)
1476 I.getUse()->set(NewBB);
1477}
1478
1479Instruction *Instruction::cloneImpl() const {
1480 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
1481}
1482
1484 MDNode *ProfileData = getBranchWeightMDNode(*this);
1485 if (!ProfileData)
1486 return;
1487 unsigned FirstIdx = getBranchWeightOffset(ProfileData);
1488 if (ProfileData->getNumOperands() != 2 + FirstIdx)
1489 return;
1490
1491 unsigned SecondIdx = FirstIdx + 1;
1493 // If there are more weights past the second, we can't swap them
1494 if (ProfileData->getNumOperands() > SecondIdx + 1)
1495 return;
1496 for (unsigned Idx = 0; Idx < FirstIdx; ++Idx) {
1497 Ops.push_back(ProfileData->getOperand(Idx));
1498 }
1499 // Switch the order of the weights
1500 Ops.push_back(ProfileData->getOperand(SecondIdx));
1501 Ops.push_back(ProfileData->getOperand(FirstIdx));
1502 setMetadata(LLVMContext::MD_prof,
1503 MDNode::get(ProfileData->getContext(), Ops));
1504}
1505
1506void Instruction::copyMetadata(const Instruction &SrcInst,
1507 ArrayRef<unsigned> WL) {
1508 if (WL.empty() || is_contained(WL, LLVMContext::MD_dbg))
1509 setDebugLoc(SrcInst.getDebugLoc().orElse(getDebugLoc()));
1510
1511 if (!SrcInst.hasMetadata())
1512 return;
1513
1514 SmallDenseSet<unsigned, 4> WLS(WL.begin(), WL.end());
1515
1516 // Otherwise, enumerate and copy over metadata from the old instruction to the
1517 // new one.
1519 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
1520 for (const auto &MD : TheMDs) {
1521 if (WL.empty() || WLS.count(MD.first))
1522 setMetadata(MD.first, MD.second);
1523 }
1524}
1525
1527 Instruction *New = nullptr;
1528 switch (getOpcode()) {
1529 default:
1530 llvm_unreachable("Unhandled Opcode.");
1531#define HANDLE_INST(num, opc, clas) \
1532 case Instruction::opc: \
1533 New = cast<clas>(this)->cloneImpl(); \
1534 break;
1535#include "llvm/IR/Instruction.def"
1536#undef HANDLE_INST
1537 }
1538
1539 New->SubclassOptionalData = SubclassOptionalData;
1540 New->copyMetadata(*this);
1541 return New;
1542}
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:474
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 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:1565
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:552
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
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:31
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:392
iterator end() const
Definition BasicBlock.h:89
bool isCommutative(const Instruction *I, const Value *ValWithUses, bool IsCopyable)
Definition SLPUtils.cpp:127
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:162
Summary of memprof metadata on allocations.
Matching combinators.