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