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"
16#include "llvm/IR/AttributeMask.h"
17#include "llvm/IR/Attributes.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/InstrTypes.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
27#include "llvm/IR/ProfDataUtils.h"
28#include "llvm/IR/Type.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Compiler.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.
38cl::opt<bool> ProfcheckDisableMetadataFixes(
39 "profcheck-disable-metadata-fixes", cl::Hidden, cl::init(Val: false),
40 cl::desc(
41 "Disable metadata propagation fixes discovered through Issue #147390"));
42
43} // end namespace llvm
44
45InsertPosition::InsertPosition(BasicBlock *InsertAtEnd)
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(ParentBB: BB, It: InsertBefore);
56 }
57}
58
59Instruction::~Instruction() {
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())
72 ValueAsMetadata::handleRAUW(From: this, To: PoisonValue::get(T: getType()));
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(ID: nullptr);
79 clearMetadata();
80 }
81}
82
83const Module *Instruction::getModule() const {
84 return getParent()->getModule();
85}
86
87const Function *Instruction::getFunction() const {
88 return getParent()->getParent();
89}
90
91const DataLayout &Instruction::getDataLayout() const {
92 return getModule()->getDataLayout();
93}
94
95void Instruction::removeFromParent() {
96 // Perform any debug-info maintenence required.
97 handleMarkerRemoval();
98
99 getParent()->getInstList().remove(IT: getIterator());
100}
101
102void Instruction::handleMarkerRemoval() {
103 if (!DebugMarker)
104 return;
105
106 DebugMarker->removeMarker();
107}
108
109BasicBlock::iterator Instruction::eraseFromParent() {
110 handleMarkerRemoval();
111 return getParent()->getInstList().erase(where: getIterator());
112}
113
114/// Insert an unlinked instruction into a basic block immediately before the
115/// specified instruction.
116void Instruction::insertBefore(BasicBlock::iterator InsertPos) {
117 insertBefore(BB&: *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(where: InsertPos->getIterator(), New: this);
126}
127
128void Instruction::insertAfter(BasicBlock::iterator InsertPos) {
129 BasicBlock *DestParent = InsertPos->getParent();
130
131 DestParent->getInstList().insertAfter(where: InsertPos, New: this);
132}
133
134BasicBlock::iterator Instruction::insertInto(BasicBlock *ParentBB,
135 BasicBlock::iterator It) {
136 assert(getParent() == nullptr && "Expected detached instruction");
137 assert((It == ParentBB->end() || It->getParent() == ParentBB) &&
138 "It not in ParentBB");
139 insertBefore(BB&: *ParentBB, InsertPos: It);
140 return getIterator();
141}
142
143void Instruction::insertBefore(BasicBlock &BB,
144 InstListType::iterator InsertPos) {
145 assert(!DebugMarker);
146
147 BB.getInstList().insert(where: InsertPos, New: 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(It: 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: &BB, It: InsertPos, InsertAtHead: 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.
181void Instruction::moveBefore(BasicBlock::iterator MovePos) {
182 moveBeforeImpl(BB&: *MovePos->getParent(), I: MovePos, Preserve: false);
183}
184
185void Instruction::moveBeforePreserving(BasicBlock::iterator MovePos) {
186 moveBeforeImpl(BB&: *MovePos->getParent(), I: MovePos, Preserve: true);
187}
188
189void Instruction::moveAfter(Instruction *MovePos) {
190 auto NextIt = std::next(x: 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(BB&: *MovePos->getParent(), I: NextIt, Preserve: 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(BB&: *MovePos->getParent(), I: MovePos, Preserve: false);
202}
203
204void Instruction::moveAfterPreserving(Instruction *MovePos) {
205 auto NextIt = std::next(x: 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(BB&: *MovePos->getParent(), I: NextIt, Preserve: true);
210}
211
212void Instruction::moveBefore(BasicBlock &BB, InstListType::iterator I) {
213 moveBeforeImpl(BB, I, Preserve: false);
214}
215
216void Instruction::moveBeforePreserving(BasicBlock &BB,
217 InstListType::iterator I) {
218 moveBeforeImpl(BB, I, Preserve: 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(where: I, L2&: getParent()->getInstList(), first: getIterator());
239
240 if (!Preserve) {
241 DbgMarker *NextMarker = getParent()->getNextMarker(I: 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: &BB, It: I, InsertAtHead: false);
247 }
248 }
249
250 if (isTerminator())
251 getParent()->flushTerminatorDbgRecords();
252}
253
254iterator_range<DbgRecord::self_iterator> Instruction::cloneDebugInfoFrom(
255 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
256 bool InsertAtHead) {
257 if (!From->DebugMarker)
258 return DbgMarker::getEmptyDbgRecordRange();
259
260 if (!DebugMarker)
261 getParent()->createMarker(I: this);
262
263 return DebugMarker->cloneDebugInfoFrom(From: From->DebugMarker, FromHere,
264 InsertAtHead);
265}
266
267std::optional<DbgRecord::self_iterator>
268Instruction::getDbgReinsertionPosition() {
269 // Is there a marker on the next instruction?
270 DbgMarker *NextMarker = getParent()->getNextMarker(I: 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
283void Instruction::adoptDbgRecords(BasicBlock *BB, BasicBlock::iterator It,
284 bool InsertAtHead) {
285 DbgMarker *SrcMarker = BB->getMarker(It);
286 auto ReleaseTrailingDbgRecords = [BB, It, SrcMarker]() {
287 if (BB->end() == It) {
288 SrcMarker->eraseFromParent();
289 BB->deleteTrailingDbgRecords();
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(I: this);
304 DebugMarker->absorbDebugValues(Src&: *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
326void Instruction::dropDbgRecords() {
327 if (DebugMarker)
328 DebugMarker->dropDbgRecords();
329}
330
331void Instruction::dropOneDbgRecord(DbgRecord *DVR) {
332 DebugMarker->dropOneDbgRecord(DR: 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>(Val: this)) {
350 InsertBB = PN->getParent();
351 InsertPt = InsertBB->getFirstInsertionPt();
352 } else if (auto *II = dyn_cast<InvokeInst>(Val: this)) {
353 InsertBB = II->getNormalDest();
354 InsertPt = InsertBB->getFirstInsertionPt();
355 } else if (isa<CallBrInst>(Val: 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(x: 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
376bool Instruction::isOnlyUserOfAnyOperand() {
377 return any_of(Range: operands(), P: [](const Value *V) { return V->hasOneUser(); });
378}
379
380void Instruction::setHasNoUnsignedWrap(bool b) {
381 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(Val: this))
382 Inst->setHasNoUnsignedWrap(b);
383 else
384 cast<TruncInst>(Val: this)->setHasNoUnsignedWrap(b);
385}
386
387void Instruction::setHasNoSignedWrap(bool b) {
388 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(Val: this))
389 Inst->setHasNoSignedWrap(b);
390 else
391 cast<TruncInst>(Val: this)->setHasNoSignedWrap(b);
392}
393
394void Instruction::setIsExact(bool b) {
395 cast<PossiblyExactOperator>(Val: this)->setIsExact(b);
396}
397
398void Instruction::setNonNeg(bool b) {
399 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
400 SubclassOptionalData = (SubclassOptionalData & ~PossiblyNonNegInst::NonNeg) |
401 (b * PossiblyNonNegInst::NonNeg);
402}
403
404bool Instruction::hasNoUnsignedWrap() const {
405 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(Val: this))
406 return Inst->hasNoUnsignedWrap();
407
408 return cast<TruncInst>(Val: this)->hasNoUnsignedWrap();
409}
410
411bool Instruction::hasNoSignedWrap() const {
412 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(Val: this))
413 return Inst->hasNoSignedWrap();
414
415 return cast<TruncInst>(Val: 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
423bool Instruction::hasPoisonGeneratingFlags() const {
424 return cast<Operator>(Val: this)->hasPoisonGeneratingFlags();
425}
426
427void Instruction::dropPoisonGeneratingFlags() {
428 switch (getOpcode()) {
429 case Instruction::Add:
430 case Instruction::Sub:
431 case Instruction::Mul:
432 case Instruction::Shl:
433 cast<OverflowingBinaryOperator>(Val: this)->setHasNoUnsignedWrap(false);
434 cast<OverflowingBinaryOperator>(Val: 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>(Val: this)->setIsExact(false);
442 break;
443
444 case Instruction::Or:
445 cast<PossiblyDisjointInst>(Val: this)->setIsDisjoint(false);
446 break;
447
448 case Instruction::GetElementPtr:
449 cast<GetElementPtrInst>(Val: 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>(Val: this)->setHasNoUnsignedWrap(false);
459 cast<TruncInst>(Val: this)->setHasNoSignedWrap(false);
460 break;
461
462 case Instruction::ICmp:
463 cast<ICmpInst>(Val: this)->setSameSign(false);
464 break;
465
466 case Instruction::Call: {
467 if (auto *II = dyn_cast<IntrinsicInst>(Val: this)) {
468 switch (II->getIntrinsicID()) {
469 case Intrinsic::ctlz:
470 case Intrinsic::cttz:
471 case Intrinsic::abs:
472 II->setOperand(i_nocapture: 1, Val_nocapture: ConstantInt::getFalse(Context&: getContext()));
473 break;
474 }
475 }
476 break;
477 }
478 }
479
480 if (isa<FPMathOperator>(Val: this)) {
481 setHasNoNaNs(false);
482 setHasNoInfs(false);
483 }
484
485 assert(!hasPoisonGeneratingFlags() && "must be kept in sync");
486}
487
488bool Instruction::hasPoisonGeneratingMetadata() const {
489 return any_of(Range: Metadata::PoisonGeneratingIDs,
490 P: [this](unsigned ID) { return hasMetadata(KindID: ID); });
491}
492
493bool Instruction::hasNonDebugLocLoopMetadata() const {
494 // If there is no loop metadata at all, we also don't have
495 // non-debug loop metadata, obviously.
496 if (!hasMetadata(KindID: LLVMContext::MD_loop))
497 return false;
498
499 // If we do have loop metadata, retrieve it.
500 MDNode *LoopMD = getMetadata(KindID: LLVMContext::MD_loop);
501
502 // Check if the existing operands are debug locations. This loop
503 // should terminate after at most three iterations. Skip
504 // the first item because it is a self-reference.
505 for (const MDOperand &Op : llvm::drop_begin(RangeOrContainer: LoopMD->operands())) {
506 // check for debug location type by attempting a cast.
507 if (!isa<DILocation>(Val: Op)) {
508 return true;
509 }
510 }
511
512 // If we get here, then all we have is debug locations in the loop metadata.
513 return false;
514}
515
516void Instruction::dropPoisonGeneratingMetadata() {
517 for (unsigned ID : Metadata::PoisonGeneratingIDs)
518 eraseMetadata(KindID: ID);
519}
520
521bool Instruction::hasPoisonGeneratingAttributes() const {
522 if (const auto *CB = dyn_cast<CallBase>(Val: this)) {
523 auto HasPoisonGeneratingAttributes = [](AttributeSet Attrs) {
524 return Attrs.hasAttribute(Kind: Attribute::Range) ||
525 Attrs.hasAttribute(Kind: Attribute::Alignment) ||
526 Attrs.hasAttribute(Kind: Attribute::NonNull) ||
527 Attrs.hasAttribute(Kind: Attribute::NoFPClass);
528 };
529 if (HasPoisonGeneratingAttributes(CB->getRetAttributes()))
530 return true;
531 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
532 if (HasPoisonGeneratingAttributes(CB->getParamAttributes(ArgNo)))
533 return true;
534 }
535 return false;
536}
537
538void Instruction::dropPoisonGeneratingAttributes() {
539 if (auto *CB = dyn_cast<CallBase>(Val: this)) {
540 AttributeMask AM;
541 AM.addAttribute(Val: Attribute::Range);
542 AM.addAttribute(Val: Attribute::Alignment);
543 AM.addAttribute(Val: Attribute::NonNull);
544 AM.addAttribute(Val: Attribute::NoFPClass);
545 CB->removeRetAttrs(AttrsToRemove: AM);
546 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
547 CB->removeParamAttrs(ArgNo, AttrsToRemove: AM);
548 }
549 assert(!hasPoisonGeneratingAttributes() && "must be kept in sync");
550}
551
552void Instruction::dropUBImplyingAttrsAndUnknownMetadata(
553 ArrayRef<unsigned> KnownIDs) {
554 dropUnknownNonDebugMetadata(KnownIDs);
555 auto *CB = dyn_cast<CallBase>(Val: this);
556 if (!CB)
557 return;
558 // For call instructions, we also need to drop parameter and return attributes
559 // that can cause UB if the call is moved to a location where the attribute is
560 // not valid.
561 AttributeList AL = CB->getAttributes();
562 if (AL.isEmpty())
563 return;
564 AttributeMask UBImplyingAttributes =
565 AttributeFuncs::getUBImplyingAttributes();
566 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
567 CB->removeParamAttrs(ArgNo, AttrsToRemove: UBImplyingAttributes);
568 CB->removeRetAttrs(AttrsToRemove: UBImplyingAttributes);
569}
570
571void Instruction::dropUBImplyingAttrsAndMetadata(ArrayRef<unsigned> Keep) {
572 // !annotation and !prof metadata does not impact semantics.
573 // !range, !nonnull, !align and !nofpclass produce poison, so they are safe to
574 // speculate.
575 // !fpmath specifies floating-point precision and does not imply UB.
576 // !mem.cache_hint is a performance hint and does not imply UB.
577 // !noundef and various AA metadata must be dropped, as it generally produces
578 // immediate undefined behavior.
579 static const unsigned KnownIDs[] = {
580 LLVMContext::MD_annotation, LLVMContext::MD_range,
581 LLVMContext::MD_nonnull, LLVMContext::MD_align,
582 LLVMContext::MD_fpmath, LLVMContext::MD_prof,
583 LLVMContext::MD_mem_cache_hint, LLVMContext::MD_nofpclass};
584 SmallVector<unsigned> KeepIDs;
585 KeepIDs.reserve(N: Keep.size() + std::size(KnownIDs));
586 append_range(C&: KeepIDs, R: (!ProfcheckDisableMetadataFixes ? KnownIDs
587 : drop_end(RangeOrContainer: KnownIDs)));
588 append_range(C&: KeepIDs, R&: Keep);
589 dropUBImplyingAttrsAndUnknownMetadata(KnownIDs: KeepIDs);
590}
591
592bool Instruction::hasUBImplyingAttrs() const {
593 auto *CB = dyn_cast<CallBase>(Val: this);
594 if (!CB)
595 return false;
596 // For call instructions, we also need to check parameter and return
597 // attributes that can cause UB.
598 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
599 if (CB->isPassingUndefUB(ArgNo))
600 return true;
601 return CB->hasRetAttr(Kind: Attribute::NoUndef) ||
602 CB->hasRetAttr(Kind: Attribute::Dereferenceable) ||
603 CB->hasRetAttr(Kind: Attribute::DereferenceableOrNull);
604}
605
606bool Instruction::isExact() const {
607 return cast<PossiblyExactOperator>(Val: this)->isExact();
608}
609
610void Instruction::setFast(bool B) {
611 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
612 cast<FPMathOperator>(Val: this)->setFast(B);
613}
614
615void Instruction::setHasAllowReassoc(bool B) {
616 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
617 cast<FPMathOperator>(Val: this)->setHasAllowReassoc(B);
618}
619
620void Instruction::setHasNoNaNs(bool B) {
621 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
622 cast<FPMathOperator>(Val: this)->setHasNoNaNs(B);
623}
624
625void Instruction::setHasNoInfs(bool B) {
626 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
627 cast<FPMathOperator>(Val: this)->setHasNoInfs(B);
628}
629
630void Instruction::setHasNoSignedZeros(bool B) {
631 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
632 cast<FPMathOperator>(Val: this)->setHasNoSignedZeros(B);
633}
634
635void Instruction::setHasAllowReciprocal(bool B) {
636 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
637 cast<FPMathOperator>(Val: this)->setHasAllowReciprocal(B);
638}
639
640void Instruction::setHasAllowContract(bool B) {
641 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
642 cast<FPMathOperator>(Val: this)->setHasAllowContract(B);
643}
644
645void Instruction::setHasApproxFunc(bool B) {
646 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
647 cast<FPMathOperator>(Val: this)->setHasApproxFunc(B);
648}
649
650void Instruction::setFastMathFlags(FastMathFlags FMF) {
651 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
652 cast<FPMathOperator>(Val: this)->setFastMathFlags(FMF);
653}
654
655void Instruction::copyFastMathFlags(FastMathFlags FMF) {
656 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
657 cast<FPMathOperator>(Val: this)->copyFastMathFlags(FMF);
658}
659
660bool Instruction::isFast() const {
661 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
662 return cast<FPMathOperator>(Val: this)->isFast();
663}
664
665bool Instruction::hasAllowReassoc() const {
666 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
667 return cast<FPMathOperator>(Val: this)->hasAllowReassoc();
668}
669
670bool Instruction::hasNoNaNs() const {
671 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
672 return cast<FPMathOperator>(Val: this)->hasNoNaNs();
673}
674
675bool Instruction::hasNoInfs() const {
676 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
677 return cast<FPMathOperator>(Val: this)->hasNoInfs();
678}
679
680bool Instruction::hasNoSignedZeros() const {
681 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
682 return cast<FPMathOperator>(Val: this)->hasNoSignedZeros();
683}
684
685bool Instruction::hasAllowReciprocal() const {
686 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
687 return cast<FPMathOperator>(Val: this)->hasAllowReciprocal();
688}
689
690bool Instruction::hasAllowContract() const {
691 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
692 return cast<FPMathOperator>(Val: this)->hasAllowContract();
693}
694
695bool Instruction::hasApproxFunc() const {
696 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
697 return cast<FPMathOperator>(Val: this)->hasApproxFunc();
698}
699
700FastMathFlags Instruction::getFastMathFlags() const {
701 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
702 return cast<FPMathOperator>(Val: this)->getFastMathFlags();
703}
704
705FastMathFlags Instruction::getFastMathFlagsOrNone() const {
706 if (!isa<FPMathOperator>(Val: this))
707 return {};
708 return cast<FPMathOperator>(Val: this)->getFastMathFlags();
709}
710
711void Instruction::copyFastMathFlags(const Instruction *I) {
712 copyFastMathFlags(FMF: I->getFastMathFlags());
713}
714
715void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
716 // Copy the wrapping flags.
717 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(Val: this)) {
718 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(Val: V)) {
719 setHasNoSignedWrap(OB->hasNoSignedWrap());
720 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
721 }
722 }
723
724 if (auto *TI = dyn_cast<TruncInst>(Val: V)) {
725 if (isa<TruncInst>(Val: this)) {
726 setHasNoSignedWrap(TI->hasNoSignedWrap());
727 setHasNoUnsignedWrap(TI->hasNoUnsignedWrap());
728 }
729 }
730
731 // Copy the exact flag.
732 if (auto *PE = dyn_cast<PossiblyExactOperator>(Val: V))
733 if (isa<PossiblyExactOperator>(Val: this))
734 setIsExact(PE->isExact());
735
736 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(Val: V))
737 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(Val: this))
738 DestPD->setIsDisjoint(SrcPD->isDisjoint());
739
740 // Copy the fast-math flags.
741 if (auto *FP = dyn_cast<FPMathOperator>(Val: V))
742 if (isa<FPMathOperator>(Val: this))
743 copyFastMathFlags(FMF: FP->getFastMathFlags());
744
745 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(Val: V))
746 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(Val: this))
747 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() |
748 DestGEP->getNoWrapFlags());
749
750 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(Val: V))
751 if (isa<PossiblyNonNegInst>(Val: this))
752 setNonNeg(NNI->hasNonNeg());
753
754 if (auto *SrcICmp = dyn_cast<ICmpInst>(Val: V))
755 if (auto *DestICmp = dyn_cast<ICmpInst>(Val: this))
756 DestICmp->setSameSign(SrcICmp->hasSameSign());
757}
758
759void Instruction::andIRFlags(const Value *V) {
760 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(Val: V)) {
761 if (isa<OverflowingBinaryOperator>(Val: this)) {
762 setHasNoSignedWrap(hasNoSignedWrap() && OB->hasNoSignedWrap());
763 setHasNoUnsignedWrap(hasNoUnsignedWrap() && OB->hasNoUnsignedWrap());
764 }
765 }
766
767 if (auto *TI = dyn_cast<TruncInst>(Val: V)) {
768 if (isa<TruncInst>(Val: this)) {
769 setHasNoSignedWrap(hasNoSignedWrap() && TI->hasNoSignedWrap());
770 setHasNoUnsignedWrap(hasNoUnsignedWrap() && TI->hasNoUnsignedWrap());
771 }
772 }
773
774 if (auto *PE = dyn_cast<PossiblyExactOperator>(Val: V))
775 if (isa<PossiblyExactOperator>(Val: this))
776 setIsExact(isExact() && PE->isExact());
777
778 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(Val: V))
779 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(Val: this))
780 DestPD->setIsDisjoint(DestPD->isDisjoint() && SrcPD->isDisjoint());
781
782 if (auto *FP = dyn_cast<FPMathOperator>(Val: V)) {
783 if (isa<FPMathOperator>(Val: this)) {
784 FastMathFlags FM = getFastMathFlags();
785 FM &= FP->getFastMathFlags();
786 copyFastMathFlags(FMF: FM);
787 }
788 }
789
790 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(Val: V))
791 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(Val: this))
792 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() &
793 DestGEP->getNoWrapFlags());
794
795 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(Val: V))
796 if (isa<PossiblyNonNegInst>(Val: this))
797 setNonNeg(hasNonNeg() && NNI->hasNonNeg());
798
799 if (auto *SrcICmp = dyn_cast<ICmpInst>(Val: V))
800 if (auto *DestICmp = dyn_cast<ICmpInst>(Val: this))
801 DestICmp->setSameSign(DestICmp->hasSameSign() && SrcICmp->hasSameSign());
802}
803
804const char *Instruction::getOpcodeName(unsigned OpCode) {
805 switch (OpCode) {
806 // Terminators
807 case Ret: return "ret";
808 case UncondBr: return "br";
809 case CondBr: return "br";
810 case Switch: return "switch";
811 case IndirectBr: return "indirectbr";
812 case Invoke: return "invoke";
813 case Resume: return "resume";
814 case Unreachable: return "unreachable";
815 case CleanupRet: return "cleanupret";
816 case CatchRet: return "catchret";
817 case CatchPad: return "catchpad";
818 case CatchSwitch: return "catchswitch";
819 case CallBr: return "callbr";
820
821 // Standard unary operators...
822 case FNeg: return "fneg";
823
824 // Standard binary operators...
825 case Add: return "add";
826 case FAdd: return "fadd";
827 case Sub: return "sub";
828 case FSub: return "fsub";
829 case Mul: return "mul";
830 case FMul: return "fmul";
831 case UDiv: return "udiv";
832 case SDiv: return "sdiv";
833 case FDiv: return "fdiv";
834 case URem: return "urem";
835 case SRem: return "srem";
836 case FRem: return "frem";
837
838 // Logical operators...
839 case And: return "and";
840 case Or : return "or";
841 case Xor: return "xor";
842
843 // Memory instructions...
844 case Alloca: return "alloca";
845 case Load: return "load";
846 case Store: return "store";
847 case AtomicCmpXchg: return "cmpxchg";
848 case AtomicRMW: return "atomicrmw";
849 case Fence: return "fence";
850 case GetElementPtr: return "getelementptr";
851
852 // Convert instructions...
853 case Trunc: return "trunc";
854 case ZExt: return "zext";
855 case SExt: return "sext";
856 case FPTrunc: return "fptrunc";
857 case FPExt: return "fpext";
858 case FPToUI: return "fptoui";
859 case FPToSI: return "fptosi";
860 case UIToFP: return "uitofp";
861 case SIToFP: return "sitofp";
862 case IntToPtr: return "inttoptr";
863 case PtrToAddr: return "ptrtoaddr";
864 case PtrToInt: return "ptrtoint";
865 case BitCast: return "bitcast";
866 case AddrSpaceCast: return "addrspacecast";
867
868 // Other instructions...
869 case ICmp: return "icmp";
870 case FCmp: return "fcmp";
871 case PHI: return "phi";
872 case Select: return "select";
873 case Call: return "call";
874 case Shl: return "shl";
875 case LShr: return "lshr";
876 case AShr: return "ashr";
877 case VAArg: return "va_arg";
878 case ExtractElement: return "extractelement";
879 case InsertElement: return "insertelement";
880 case ShuffleVector: return "shufflevector";
881 case ExtractValue: return "extractvalue";
882 case InsertValue: return "insertvalue";
883 case LandingPad: return "landingpad";
884 case CleanupPad: return "cleanuppad";
885 case Freeze: return "freeze";
886
887 default: return "<Invalid operator> ";
888 }
889}
890
891/// This must be kept in sync with FunctionComparator::cmpOperations in
892/// lib/Transforms/Utils/FunctionComparator.cpp.
893bool Instruction::hasSameSpecialState(const Instruction *I2,
894 bool IgnoreAlignment,
895 bool IntersectAttrs) const {
896 const auto *I1 = this;
897 assert(I1->getOpcode() == I2->getOpcode() &&
898 "Can not compare special state of different instructions");
899
900 auto CheckAttrsSame = [IntersectAttrs](const CallBase *CB0,
901 const CallBase *CB1) {
902 return IntersectAttrs
903 ? CB0->getAttributes()
904 .intersectWith(C&: CB0->getContext(), Other: CB1->getAttributes())
905 .has_value()
906 : CB0->getAttributes() == CB1->getAttributes();
907 };
908
909 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: I1))
910 return AI->getAllocatedType() == cast<AllocaInst>(Val: I2)->getAllocatedType() &&
911 (AI->getAlign() == cast<AllocaInst>(Val: I2)->getAlign() ||
912 IgnoreAlignment);
913 if (const LoadInst *LI = dyn_cast<LoadInst>(Val: I1))
914 return LI->isVolatile() == cast<LoadInst>(Val: I2)->isVolatile() &&
915 LI->isElementwise() == cast<LoadInst>(Val: I2)->isElementwise() &&
916 (LI->getAlign() == cast<LoadInst>(Val: I2)->getAlign() ||
917 IgnoreAlignment) &&
918 LI->getOrdering() == cast<LoadInst>(Val: I2)->getOrdering() &&
919 LI->getSyncScopeID() == cast<LoadInst>(Val: I2)->getSyncScopeID();
920 if (const StoreInst *SI = dyn_cast<StoreInst>(Val: I1))
921 return SI->isVolatile() == cast<StoreInst>(Val: I2)->isVolatile() &&
922 SI->isElementwise() == cast<StoreInst>(Val: I2)->isElementwise() &&
923 (SI->getAlign() == cast<StoreInst>(Val: I2)->getAlign() ||
924 IgnoreAlignment) &&
925 SI->getOrdering() == cast<StoreInst>(Val: I2)->getOrdering() &&
926 SI->getSyncScopeID() == cast<StoreInst>(Val: I2)->getSyncScopeID();
927 if (const CmpInst *CI = dyn_cast<CmpInst>(Val: I1))
928 return CI->getPredicate() == cast<CmpInst>(Val: I2)->getPredicate();
929 if (const CallInst *CI = dyn_cast<CallInst>(Val: I1))
930 return CI->isTailCall() == cast<CallInst>(Val: I2)->isTailCall() &&
931 CI->getCallingConv() == cast<CallInst>(Val: I2)->getCallingConv() &&
932 CheckAttrsSame(CI, cast<CallInst>(Val: I2)) &&
933 CI->hasIdenticalOperandBundleSchema(Other: *cast<CallInst>(Val: I2));
934 if (const InvokeInst *CI = dyn_cast<InvokeInst>(Val: I1))
935 return CI->getCallingConv() == cast<InvokeInst>(Val: I2)->getCallingConv() &&
936 CheckAttrsSame(CI, cast<InvokeInst>(Val: I2)) &&
937 CI->hasIdenticalOperandBundleSchema(Other: *cast<InvokeInst>(Val: I2));
938 if (const CallBrInst *CI = dyn_cast<CallBrInst>(Val: I1))
939 return CI->getCallingConv() == cast<CallBrInst>(Val: I2)->getCallingConv() &&
940 CheckAttrsSame(CI, cast<CallBrInst>(Val: I2)) &&
941 CI->hasIdenticalOperandBundleSchema(Other: *cast<CallBrInst>(Val: I2));
942 if (const SwitchInst *SI = dyn_cast<SwitchInst>(Val: I1)) {
943 for (auto [Case1, Case2] : zip(t: SI->cases(), u: cast<SwitchInst>(Val: I2)->cases()))
944 if (Case1.getCaseValue() != Case2.getCaseValue())
945 return false;
946 return true;
947 }
948 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Val: I1))
949 return IVI->getIndices() == cast<InsertValueInst>(Val: I2)->getIndices();
950 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val: I1))
951 return EVI->getIndices() == cast<ExtractValueInst>(Val: I2)->getIndices();
952 if (const FenceInst *FI = dyn_cast<FenceInst>(Val: I1))
953 return FI->getOrdering() == cast<FenceInst>(Val: I2)->getOrdering() &&
954 FI->getSyncScopeID() == cast<FenceInst>(Val: I2)->getSyncScopeID();
955 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(Val: I1))
956 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(Val: I2)->isVolatile() &&
957 (CXI->getAlign() == cast<AtomicCmpXchgInst>(Val: I2)->getAlign() ||
958 IgnoreAlignment) &&
959 CXI->isWeak() == cast<AtomicCmpXchgInst>(Val: I2)->isWeak() &&
960 CXI->getSuccessOrdering() ==
961 cast<AtomicCmpXchgInst>(Val: I2)->getSuccessOrdering() &&
962 CXI->getFailureOrdering() ==
963 cast<AtomicCmpXchgInst>(Val: I2)->getFailureOrdering() &&
964 CXI->getSyncScopeID() ==
965 cast<AtomicCmpXchgInst>(Val: I2)->getSyncScopeID();
966 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(Val: I1))
967 return RMWI->getOperation() == cast<AtomicRMWInst>(Val: I2)->getOperation() &&
968 RMWI->isElementwise() == cast<AtomicRMWInst>(Val: I2)->isElementwise() &&
969 RMWI->isVolatile() == cast<AtomicRMWInst>(Val: I2)->isVolatile() &&
970 (RMWI->getAlign() == cast<AtomicRMWInst>(Val: I2)->getAlign() ||
971 IgnoreAlignment) &&
972 RMWI->getOrdering() == cast<AtomicRMWInst>(Val: I2)->getOrdering() &&
973 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(Val: I2)->getSyncScopeID();
974 if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Val: I1))
975 return SVI->getShuffleMask() ==
976 cast<ShuffleVectorInst>(Val: I2)->getShuffleMask();
977 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: I1))
978 return GEP->getSourceElementType() ==
979 cast<GetElementPtrInst>(Val: I2)->getSourceElementType();
980
981 return true;
982}
983
984bool Instruction::isIdenticalTo(const Instruction *I) const {
985 return isIdenticalToWhenDefined(I) &&
986 SubclassOptionalData == I->SubclassOptionalData;
987}
988
989bool Instruction::isIdenticalToWhenDefined(const Instruction *I,
990 bool IntersectAttrs) const {
991 if (getOpcode() != I->getOpcode() ||
992 getNumOperands() != I->getNumOperands() || getType() != I->getType())
993 return false;
994
995 // If both instructions have no operands, they are identical.
996 if (getNumOperands() == 0 && I->getNumOperands() == 0)
997 return this->hasSameSpecialState(I2: I, /*IgnoreAlignment=*/false,
998 IntersectAttrs);
999
1000 // We have two instructions of identical opcode and #operands. Check to see
1001 // if all operands are the same.
1002 if (!equal(LRange: operands(), RRange: I->operands()))
1003 return false;
1004
1005 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()!
1006 if (const PHINode *Phi = dyn_cast<PHINode>(Val: this)) {
1007 const PHINode *OtherPhi = cast<PHINode>(Val: I);
1008 return equal(LRange: Phi->blocks(), RRange: OtherPhi->blocks());
1009 }
1010
1011 return this->hasSameSpecialState(I2: I, /*IgnoreAlignment=*/false,
1012 IntersectAttrs);
1013}
1014
1015// Keep this in sync with FunctionComparator::cmpOperations in
1016// lib/Transforms/IPO/MergeFunctions.cpp.
1017bool Instruction::isSameOperationAs(const Instruction *I,
1018 unsigned flags) const {
1019 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
1020 bool UseScalarTypes = flags & CompareUsingScalarTypes;
1021 bool IntersectAttrs = flags & CompareUsingIntersectedAttrs;
1022
1023 if (getOpcode() != I->getOpcode() ||
1024 getNumOperands() != I->getNumOperands() ||
1025 (UseScalarTypes ?
1026 getType()->getScalarType() != I->getType()->getScalarType() :
1027 getType() != I->getType()))
1028 return false;
1029
1030 // We have two instructions of identical opcode and #operands. Check to see
1031 // if all operands are the same type
1032 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1033 if (UseScalarTypes ?
1034 getOperand(i)->getType()->getScalarType() !=
1035 I->getOperand(i)->getType()->getScalarType() :
1036 getOperand(i)->getType() != I->getOperand(i)->getType())
1037 return false;
1038
1039 return this->hasSameSpecialState(I2: I, IgnoreAlignment, IntersectAttrs);
1040}
1041
1042bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
1043 for (const Use &U : uses()) {
1044 // PHI nodes uses values in the corresponding predecessor block. For other
1045 // instructions, just check to see whether the parent of the use matches up.
1046 const Instruction *I = cast<Instruction>(Val: U.getUser());
1047 const PHINode *PN = dyn_cast<PHINode>(Val: I);
1048 if (!PN) {
1049 if (I->getParent() != BB)
1050 return true;
1051 continue;
1052 }
1053
1054 if (PN->getIncomingBlock(U) != BB)
1055 return true;
1056 }
1057 return false;
1058}
1059
1060MemoryEffects Instruction::getMemoryEffects() const {
1061 auto GetEffects = [](ModRefInfo BaseMR, AtomicOrdering Ordering,
1062 bool IsVolatile) {
1063 if (isStrongerThanMonotonic(AO: Ordering))
1064 return MemoryEffects::unknown();
1065
1066 if (IsVolatile)
1067 return MemoryEffects::inaccessibleOrArgMemOnly();
1068
1069 if (isStrongerThanUnordered(AO: Ordering))
1070 return MemoryEffects::argMemOnly();
1071
1072 return MemoryEffects::argMemOnly(MR: BaseMR);
1073 };
1074 switch (getOpcode()) {
1075 default:
1076 return MemoryEffects::none();
1077 case Instruction::VAArg:
1078 return MemoryEffects::argMemOnly();
1079 case Instruction::CatchPad:
1080 case Instruction::CatchRet:
1081 case Instruction::Fence:
1082 return MemoryEffects::unknown();
1083 case Instruction::Call:
1084 case Instruction::Invoke:
1085 case Instruction::CallBr:
1086 return cast<CallBase>(Val: this)->getMemoryEffects();
1087 case Instruction::Load: {
1088 auto *LI = cast<LoadInst>(Val: this);
1089 return GetEffects(ModRefInfo::Ref, LI->getOrdering(), LI->isVolatile());
1090 }
1091 case Instruction::Store: {
1092 auto *SI = cast<StoreInst>(Val: this);
1093 return GetEffects(ModRefInfo::Mod, SI->getOrdering(), SI->isVolatile());
1094 }
1095 case Instruction::AtomicRMW: {
1096 auto *RMW = cast<AtomicRMWInst>(Val: this);
1097 return GetEffects(ModRefInfo::ModRef, RMW->getOrdering(),
1098 RMW->isVolatile());
1099 }
1100 case Instruction::AtomicCmpXchg: {
1101 auto *CX = cast<AtomicCmpXchgInst>(Val: this);
1102 return GetEffects(ModRefInfo::ModRef, CX->getSuccessOrdering(),
1103 CX->isVolatile());
1104 }
1105 }
1106}
1107
1108// This is duplicating the logic from getMemoryEffects() for performance
1109// reasons. Computing the full MemoryEffects just to perform a Mod/Ref check
1110// is expensive.
1111
1112bool Instruction::mayReadFromMemory() const {
1113 switch (getOpcode()) {
1114 default: return false;
1115 case Instruction::VAArg:
1116 case Instruction::Load:
1117 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
1118 case Instruction::AtomicCmpXchg:
1119 case Instruction::AtomicRMW:
1120 case Instruction::CatchPad:
1121 case Instruction::CatchRet:
1122 return true;
1123 case Instruction::Call:
1124 case Instruction::Invoke:
1125 case Instruction::CallBr:
1126 return !cast<CallBase>(Val: this)->onlyWritesMemory();
1127 case Instruction::Store:
1128 return !cast<StoreInst>(Val: this)->isUnordered();
1129 }
1130}
1131
1132bool Instruction::mayWriteToMemory() const {
1133 switch (getOpcode()) {
1134 default: return false;
1135 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
1136 case Instruction::Store:
1137 case Instruction::VAArg:
1138 case Instruction::AtomicCmpXchg:
1139 case Instruction::AtomicRMW:
1140 case Instruction::CatchPad:
1141 case Instruction::CatchRet:
1142 return true;
1143 case Instruction::Call:
1144 case Instruction::Invoke:
1145 case Instruction::CallBr:
1146 return !cast<CallBase>(Val: this)->onlyReadsMemory();
1147 case Instruction::Load:
1148 return !cast<LoadInst>(Val: this)->isUnordered();
1149 }
1150}
1151
1152bool Instruction::isAtomic() const {
1153 switch (getOpcode()) {
1154 default:
1155 return false;
1156 case Instruction::AtomicCmpXchg:
1157 case Instruction::AtomicRMW:
1158 case Instruction::Fence:
1159 return true;
1160 case Instruction::Load:
1161 return cast<LoadInst>(Val: this)->getOrdering() != AtomicOrdering::NotAtomic;
1162 case Instruction::Store:
1163 return cast<StoreInst>(Val: this)->getOrdering() != AtomicOrdering::NotAtomic;
1164 }
1165}
1166
1167bool Instruction::hasAtomicLoad() const {
1168 assert(isAtomic());
1169 switch (getOpcode()) {
1170 default:
1171 return false;
1172 case Instruction::AtomicCmpXchg:
1173 case Instruction::AtomicRMW:
1174 case Instruction::Load:
1175 return true;
1176 }
1177}
1178
1179bool Instruction::hasAtomicStore() const {
1180 assert(isAtomic());
1181 switch (getOpcode()) {
1182 default:
1183 return false;
1184 case Instruction::AtomicCmpXchg:
1185 case Instruction::AtomicRMW:
1186 case Instruction::Store:
1187 return true;
1188 }
1189}
1190
1191bool Instruction::isVolatile() const {
1192 switch (getOpcode()) {
1193 default:
1194 return false;
1195 case Instruction::AtomicRMW:
1196 return cast<AtomicRMWInst>(Val: this)->isVolatile();
1197 case Instruction::Store:
1198 return cast<StoreInst>(Val: this)->isVolatile();
1199 case Instruction::Load:
1200 return cast<LoadInst>(Val: this)->isVolatile();
1201 case Instruction::AtomicCmpXchg:
1202 return cast<AtomicCmpXchgInst>(Val: this)->isVolatile();
1203 case Instruction::Call:
1204 case Instruction::Invoke:
1205 // There are a very limited number of intrinsics with volatile flags.
1206 if (auto *II = dyn_cast<IntrinsicInst>(Val: this)) {
1207 if (auto *MI = dyn_cast<MemIntrinsic>(Val: II))
1208 return MI->isVolatile();
1209 switch (II->getIntrinsicID()) {
1210 default: break;
1211 case Intrinsic::matrix_column_major_load:
1212 return cast<ConstantInt>(Val: II->getArgOperand(i: 2))->isOne();
1213 case Intrinsic::matrix_column_major_store:
1214 return cast<ConstantInt>(Val: II->getArgOperand(i: 3))->isOne();
1215 }
1216 }
1217 return false;
1218 }
1219}
1220
1221bool Instruction::maySynchronize() const {
1222 // FIXME: This currently treats atomics with monotonic ordering as
1223 // synchronizing. This is unnecessarily conservative and does not match
1224 // our LangRef definition of the property.
1225 switch (getOpcode()) {
1226 default:
1227 assert(!isAtomic() && "Unhandled atomic instruction");
1228 return false;
1229 case Instruction::Fence: {
1230 // All legal orderings for fence are stronger than monotonic.
1231 auto *FI = cast<FenceInst>(Val: this);
1232 return FI->getSyncScopeID() != SyncScope::SingleThread;
1233 }
1234 case Instruction::AtomicRMW:
1235 case Instruction::AtomicCmpXchg:
1236 return true;
1237 case Instruction::Store:
1238 return isStrongerThanUnordered(AO: cast<StoreInst>(Val: this)->getOrdering());
1239 case Instruction::Load:
1240 return isStrongerThanUnordered(AO: cast<LoadInst>(Val: this)->getOrdering());
1241 case Instruction::Call:
1242 case Instruction::Invoke:
1243 case Instruction::CallBr:
1244 return !cast<CallBase>(Val: this)->hasFnAttr(Kind: Attribute::NoSync);
1245 }
1246}
1247
1248Type *Instruction::getAccessType() const {
1249 switch (getOpcode()) {
1250 case Instruction::Store:
1251 return cast<StoreInst>(Val: this)->getValueOperand()->getType();
1252 case Instruction::Load:
1253 case Instruction::AtomicRMW:
1254 return getType();
1255 case Instruction::AtomicCmpXchg:
1256 return cast<AtomicCmpXchgInst>(Val: this)->getNewValOperand()->getType();
1257 case Instruction::Call:
1258 case Instruction::Invoke:
1259 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: this)) {
1260 switch (II->getIntrinsicID()) {
1261 case Intrinsic::masked_load:
1262 case Intrinsic::masked_gather:
1263 case Intrinsic::masked_expandload:
1264 case Intrinsic::vp_load:
1265 case Intrinsic::vp_gather:
1266 case Intrinsic::experimental_vp_strided_load:
1267 return II->getType();
1268 case Intrinsic::masked_store:
1269 case Intrinsic::masked_scatter:
1270 case Intrinsic::masked_compressstore:
1271 case Intrinsic::vp_store:
1272 case Intrinsic::vp_scatter:
1273 case Intrinsic::experimental_vp_strided_store:
1274 return II->getOperand(i_nocapture: 0)->getType();
1275 default:
1276 break;
1277 }
1278 }
1279 }
1280
1281 return nullptr;
1282}
1283
1284static bool canUnwindPastLandingPad(const LandingPadInst *LP,
1285 bool IncludePhaseOneUnwind) {
1286 // Because phase one unwinding skips cleanup landingpads, we effectively
1287 // unwind past this frame, and callers need to have valid unwind info.
1288 if (LP->isCleanup())
1289 return IncludePhaseOneUnwind;
1290
1291 for (unsigned I = 0; I < LP->getNumClauses(); ++I) {
1292 Constant *Clause = LP->getClause(Idx: I);
1293 // catch ptr null catches all exceptions.
1294 if (LP->isCatch(Idx: I) && isa<ConstantPointerNull>(Val: Clause))
1295 return false;
1296 // filter [0 x ptr] catches all exceptions.
1297 if (LP->isFilter(Idx: I) && Clause->getType()->getArrayNumElements() == 0)
1298 return false;
1299 }
1300
1301 // May catch only some subset of exceptions, in which case other exceptions
1302 // will continue unwinding.
1303 return true;
1304}
1305
1306bool Instruction::mayThrow(bool IncludePhaseOneUnwind) const {
1307 switch (getOpcode()) {
1308 case Instruction::Call:
1309 return !cast<CallInst>(Val: this)->doesNotThrow();
1310 case Instruction::CleanupRet:
1311 return cast<CleanupReturnInst>(Val: this)->unwindsToCaller();
1312 case Instruction::CatchSwitch:
1313 return cast<CatchSwitchInst>(Val: this)->unwindsToCaller();
1314 case Instruction::Resume:
1315 return true;
1316 case Instruction::Invoke: {
1317 // Landingpads themselves don't unwind -- however, an invoke of a skipped
1318 // landingpad may continue unwinding.
1319 BasicBlock *UnwindDest = cast<InvokeInst>(Val: this)->getUnwindDest();
1320 BasicBlock::iterator Pad = UnwindDest->getFirstNonPHIIt();
1321 if (auto *LP = dyn_cast<LandingPadInst>(Val&: Pad))
1322 return canUnwindPastLandingPad(LP, IncludePhaseOneUnwind);
1323 return false;
1324 }
1325 case Instruction::CleanupPad:
1326 // Treat the same as cleanup landingpad.
1327 return IncludePhaseOneUnwind;
1328 default:
1329 return false;
1330 }
1331}
1332
1333bool Instruction::mayHaveSideEffects() const {
1334 return mayWriteToMemory() || mayThrow() || !willReturn();
1335}
1336
1337bool Instruction::isSafeToRemove() const {
1338 return (!isa<CallInst>(Val: this) || !this->mayHaveSideEffects()) &&
1339 !this->isTerminator() && !this->isEHPad();
1340}
1341
1342bool Instruction::willReturn() const {
1343 // Volatile operations are not guaranteed to return.
1344 if (isVolatile())
1345 return false;
1346
1347 if (const auto *CB = dyn_cast<CallBase>(Val: this))
1348 return CB->hasFnAttr(Kind: Attribute::WillReturn);
1349 return true;
1350}
1351
1352bool Instruction::isLifetimeStartOrEnd() const {
1353 auto *II = dyn_cast<IntrinsicInst>(Val: this);
1354 if (!II)
1355 return false;
1356 Intrinsic::ID ID = II->getIntrinsicID();
1357 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
1358}
1359
1360bool Instruction::isLaunderOrStripInvariantGroup() const {
1361 auto *II = dyn_cast<IntrinsicInst>(Val: this);
1362 if (!II)
1363 return false;
1364 Intrinsic::ID ID = II->getIntrinsicID();
1365 return ID == Intrinsic::launder_invariant_group ||
1366 ID == Intrinsic::strip_invariant_group;
1367}
1368
1369bool Instruction::isDebugOrPseudoInst() const {
1370 return isa<DbgInfoIntrinsic>(Val: this) || isa<PseudoProbeInst>(Val: this);
1371}
1372
1373const DebugLoc &Instruction::getStableDebugLoc() const {
1374 return getDebugLoc();
1375}
1376
1377bool Instruction::isAssociative() const {
1378 if (auto *II = dyn_cast<IntrinsicInst>(Val: this))
1379 return II->isAssociative();
1380 unsigned Opcode = getOpcode();
1381 if (isAssociative(Opcode))
1382 return true;
1383
1384 switch (Opcode) {
1385 case FMul:
1386 return cast<FPMathOperator>(Val: this)->hasAllowReassoc();
1387 case FAdd:
1388 return cast<FPMathOperator>(Val: this)->hasAllowReassoc() &&
1389 cast<FPMathOperator>(Val: this)->hasNoSignedZeros();
1390 default:
1391 return false;
1392 }
1393}
1394
1395bool Instruction::isCommutative() const {
1396 if (auto *II = dyn_cast<IntrinsicInst>(Val: this))
1397 return II->isCommutative();
1398 // TODO: Should allow icmp/fcmp?
1399 return isCommutative(Opcode: getOpcode());
1400}
1401
1402bool Instruction::isCommutableOperand(unsigned Op) const {
1403 if (auto *II = dyn_cast<IntrinsicInst>(Val: this))
1404 return II->isCommutableOperand(Op);
1405 // TODO: Should allow icmp/fcmp?
1406 return isCommutative(Opcode: getOpcode());
1407}
1408
1409unsigned Instruction::getNumSuccessors() const {
1410 switch (getOpcode()) {
1411#define HANDLE_TERM_INST(N, OPC, CLASS) \
1412 case Instruction::OPC: \
1413 return static_cast<const CLASS *>(this)->getNumSuccessors();
1414#include "llvm/IR/Instruction.def"
1415 default:
1416 break;
1417 }
1418 llvm_unreachable("not a terminator");
1419}
1420
1421BasicBlock *Instruction::getSuccessor(unsigned idx) const {
1422 switch (getOpcode()) {
1423#define HANDLE_TERM_INST(N, OPC, CLASS) \
1424 case Instruction::OPC: \
1425 return static_cast<const CLASS *>(this)->getSuccessor(idx);
1426#include "llvm/IR/Instruction.def"
1427 default:
1428 break;
1429 }
1430 llvm_unreachable("not a terminator");
1431}
1432
1433void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
1434 switch (getOpcode()) {
1435#define HANDLE_TERM_INST(N, OPC, CLASS) \
1436 case Instruction::OPC: \
1437 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
1438#include "llvm/IR/Instruction.def"
1439 default:
1440 break;
1441 }
1442 llvm_unreachable("not a terminator");
1443}
1444
1445iterator_range<Instruction::const_succ_iterator>
1446Instruction::successors() const {
1447 switch (getOpcode()) {
1448#define HANDLE_TERM_INST(N, OPC, CLASS) \
1449 case Instruction::OPC: \
1450 return static_cast<const CLASS *>(this)->successors();
1451#include "llvm/IR/Instruction.def"
1452 default:
1453 break;
1454 }
1455 llvm_unreachable("not a terminator");
1456}
1457
1458void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) {
1459 auto Succs = successors();
1460 for (auto I = Succs.begin(), E = Succs.end(); I != E; ++I)
1461 if (*I == OldBB)
1462 I.getUse()->set(NewBB);
1463}
1464
1465Instruction *Instruction::cloneImpl() const {
1466 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
1467}
1468
1469void Instruction::swapProfMetadata() {
1470 MDNode *ProfileData = getBranchWeightMDNode(I: *this);
1471 if (!ProfileData)
1472 return;
1473 unsigned FirstIdx = getBranchWeightOffset(ProfileData);
1474 if (ProfileData->getNumOperands() != 2 + FirstIdx)
1475 return;
1476
1477 unsigned SecondIdx = FirstIdx + 1;
1478 SmallVector<Metadata *, 4> Ops;
1479 // If there are more weights past the second, we can't swap them
1480 if (ProfileData->getNumOperands() > SecondIdx + 1)
1481 return;
1482 for (unsigned Idx = 0; Idx < FirstIdx; ++Idx) {
1483 Ops.push_back(Elt: ProfileData->getOperand(I: Idx));
1484 }
1485 // Switch the order of the weights
1486 Ops.push_back(Elt: ProfileData->getOperand(I: SecondIdx));
1487 Ops.push_back(Elt: ProfileData->getOperand(I: FirstIdx));
1488 setMetadata(KindID: LLVMContext::MD_prof,
1489 Node: MDNode::get(Context&: ProfileData->getContext(), MDs: Ops));
1490}
1491
1492void Instruction::copyProfileAndDebugMetadata(const Instruction &SrcInst) {
1493 // TODO: Include additional metadata in the future if appropriate.
1494 static const unsigned SafeIDs[] = {
1495 LLVMContext::MD_dbg, LLVMContext::MD_prof, LLVMContext::MD_memprof,
1496 LLVMContext::MD_callsite};
1497 copyMetadata(SrcInst, WL: SafeIDs);
1498}
1499
1500void Instruction::copyMetadata(const Instruction &SrcInst,
1501 ArrayRef<unsigned> WL) {
1502 if (WL.empty() || is_contained(Range&: WL, Element: LLVMContext::MD_dbg))
1503 setDebugLoc(SrcInst.getDebugLoc().orElse(Other: getDebugLoc()));
1504
1505 if (!SrcInst.hasMetadata())
1506 return;
1507
1508 SmallDenseSet<unsigned, 4> WLS(WL.begin(), WL.end());
1509
1510 // Otherwise, enumerate and copy over metadata from the old instruction to the
1511 // new one.
1512 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
1513 SrcInst.getAllMetadataOtherThanDebugLoc(MDs&: TheMDs);
1514 for (const auto &MD : TheMDs) {
1515 if (WL.empty() || WLS.count(V: MD.first))
1516 setMetadata(KindID: MD.first, Node: MD.second);
1517 }
1518}
1519
1520Instruction *Instruction::clone() const {
1521 Instruction *New = nullptr;
1522 switch (getOpcode()) {
1523 default:
1524 llvm_unreachable("Unhandled Opcode.");
1525#define HANDLE_INST(num, opc, clas) \
1526 case Instruction::opc: \
1527 New = cast<clas>(this)->cloneImpl(); \
1528 break;
1529#include "llvm/IR/Instruction.def"
1530#undef HANDLE_INST
1531 }
1532
1533 New->SubclassOptionalData = SubclassOptionalData;
1534 New->copyMetadata(SrcInst: *this);
1535 return New;
1536}
1537