LLVM 20.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"
29using namespace llvm;
30
31InsertPosition::InsertPosition(Instruction *InsertBefore)
32 : InsertAt(InsertBefore ? InsertBefore->getIterator()
33 : InstListType::iterator()) {}
34InsertPosition::InsertPosition(BasicBlock *InsertAtEnd)
35 : InsertAt(InsertAtEnd ? InsertAtEnd->end() : InstListType::iterator()) {}
36
37Instruction::Instruction(Type *ty, unsigned it, AllocInfo AllocInfo,
38 InsertPosition InsertBefore)
39 : User(ty, Value::InstructionVal + it, AllocInfo) {
40 // When called with an iterator, there must be a block to insert into.
41 if (InstListType::iterator InsertIt = InsertBefore; InsertIt.isValid()) {
42 BasicBlock *BB = InsertIt.getNodeParent();
43 assert(BB && "Instruction to insert before is not in a basic block!");
44 insertInto(BB, InsertBefore);
45 }
46}
47
48Instruction::~Instruction() {
49 assert(!getParent() && "Instruction still linked in the program!");
50
51 // Replace any extant metadata uses of this instruction with undef to
52 // preserve debug info accuracy. Some alternatives include:
53 // - Treat Instruction like any other Value, and point its extant metadata
54 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses
55 // trivially dead (i.e. fair game for deletion in many passes), leading to
56 // stale dbg.values being in effect for too long.
57 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal
58 // correct. OTOH results in wasted work in some common cases (e.g. when all
59 // instructions in a BasicBlock are deleted).
60 if (isUsedByMetadata())
61 ValueAsMetadata::handleRAUW(this, UndefValue::get(getType()));
62
63 // Explicitly remove DIAssignID metadata to clear up ID -> Instruction(s)
64 // mapping in LLVMContext.
65 setMetadata(LLVMContext::MD_DIAssignID, nullptr);
66}
67
68const Module *Instruction::getModule() const {
69 return getParent()->getModule();
70}
71
72const Function *Instruction::getFunction() const {
73 return getParent()->getParent();
74}
75
76const DataLayout &Instruction::getDataLayout() const {
77 return getModule()->getDataLayout();
78}
79
80void Instruction::removeFromParent() {
81 // Perform any debug-info maintenence required.
82 handleMarkerRemoval();
83
84 getParent()->getInstList().remove(getIterator());
85}
86
87void Instruction::handleMarkerRemoval() {
88 if (!getParent()->IsNewDbgInfoFormat || !DebugMarker)
89 return;
90
91 DebugMarker->removeMarker();
92}
93
94BasicBlock::iterator Instruction::eraseFromParent() {
95 handleMarkerRemoval();
96 return getParent()->getInstList().erase(getIterator());
97}
98
99void Instruction::insertBefore(Instruction *InsertPos) {
100 insertBefore(InsertPos->getIterator());
101}
102
103/// Insert an unlinked instruction into a basic block immediately before the
104/// specified instruction.
105void Instruction::insertBefore(BasicBlock::iterator InsertPos) {
106 insertBefore(*InsertPos->getParent(), InsertPos);
107}
108
109/// Insert an unlinked instruction into a basic block immediately after the
110/// specified instruction.
111void Instruction::insertAfter(Instruction *InsertPos) {
112 BasicBlock *DestParent = InsertPos->getParent();
113
114 DestParent->getInstList().insertAfter(InsertPos->getIterator(), this);
115}
116
117BasicBlock::iterator Instruction::insertInto(BasicBlock *ParentBB,
119 assert(getParent() == nullptr && "Expected detached instruction");
120 assert((It == ParentBB->end() || It->getParent() == ParentBB) &&
121 "It not in ParentBB");
122 insertBefore(*ParentBB, It);
123 return getIterator();
124}
125
127
128void Instruction::insertBefore(BasicBlock &BB,
129 InstListType::iterator InsertPos) {
130 assert(!DebugMarker);
131
132 BB.getInstList().insert(InsertPos, this);
133
134 if (!BB.IsNewDbgInfoFormat)
135 return;
136
137 // We've inserted "this": if InsertAtHead is set then it comes before any
138 // DbgVariableRecords attached to InsertPos. But if it's not set, then any
139 // DbgRecords should now come before "this".
140 bool InsertAtHead = InsertPos.getHeadBit();
141 if (!InsertAtHead) {
142 DbgMarker *SrcMarker = BB.getMarker(InsertPos);
143 if (SrcMarker && !SrcMarker->empty()) {
144 // If this assertion fires, the calling code is about to insert a PHI
145 // after debug-records, which would form a sequence like:
146 // %0 = PHI
147 // #dbg_value
148 // %1 = PHI
149 // Which is de-normalised and undesired -- hence the assertion. To avoid
150 // this, you must insert at that position using an iterator, and it must
151 // be aquired by calling getFirstNonPHIIt / begin or similar methods on
152 // the block. This will signal to this behind-the-scenes debug-info
153 // maintenence code that you intend the PHI to be ahead of everything,
154 // including any debug-info.
155 assert(!isa<PHINode>(this) && "Inserting PHI after debug-records!");
156 adoptDbgRecords(&BB, InsertPos, false);
157 }
158 }
159
160 // If we're inserting a terminator, check if we need to flush out
161 // TrailingDbgRecords. Inserting instructions at the end of an incomplete
162 // block is handled by the code block above.
163 if (isTerminator())
164 getParent()->flushTerminatorDbgRecords();
165}
166
167/// Unlink this instruction from its current basic block and insert it into the
168/// basic block that MovePos lives in, right before MovePos.
169void Instruction::moveBefore(Instruction *MovePos) {
170 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), false);
171}
172
173void Instruction::moveBeforePreserving(Instruction *MovePos) {
174 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), true);
175}
176
177void Instruction::moveAfter(Instruction *MovePos) {
178 auto NextIt = std::next(MovePos->getIterator());
179 // We want this instruction to be moved to before NextIt in the instruction
180 // list, but before NextIt's debug value range.
181 NextIt.setHeadBit(true);
182 moveBeforeImpl(*MovePos->getParent(), NextIt, false);
183}
184
185void Instruction::moveAfterPreserving(Instruction *MovePos) {
186 auto NextIt = std::next(MovePos->getIterator());
187 // We want this instruction and its debug range to be moved to before NextIt
188 // in the instruction list, but before NextIt's debug value range.
189 NextIt.setHeadBit(true);
190 moveBeforeImpl(*MovePos->getParent(), NextIt, true);
191}
192
193void Instruction::moveBefore(BasicBlock &BB, InstListType::iterator I) {
194 moveBeforeImpl(BB, I, false);
195}
196
197void Instruction::moveBeforePreserving(BasicBlock &BB,
198 InstListType::iterator I) {
199 moveBeforeImpl(BB, I, true);
200}
201
202void Instruction::moveBeforeImpl(BasicBlock &BB, InstListType::iterator I,
203 bool Preserve) {
204 assert(I == BB.end() || I->getParent() == &BB);
205 bool InsertAtHead = I.getHeadBit();
206
207 // If we've been given the "Preserve" flag, then just move the DbgRecords with
208 // the instruction, no more special handling needed.
209 if (BB.IsNewDbgInfoFormat && DebugMarker && !Preserve) {
210 if (I != this->getIterator() || InsertAtHead) {
211 // "this" is definitely moving in the list, or it's moving ahead of its
212 // attached DbgVariableRecords. Detach any existing DbgRecords.
213 handleMarkerRemoval();
214 }
215 }
216
217 // Move this single instruction. Use the list splice method directly, not
218 // the block splicer, which will do more debug-info things.
219 BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
220
221 if (BB.IsNewDbgInfoFormat && !Preserve) {
222 DbgMarker *NextMarker = getParent()->getNextMarker(this);
223
224 // If we're inserting at point I, and not in front of the DbgRecords
225 // attached there, then we should absorb the DbgRecords attached to I.
226 if (!InsertAtHead && NextMarker && !NextMarker->empty()) {
227 adoptDbgRecords(&BB, I, false);
228 }
229 }
230
231 if (isTerminator())
232 getParent()->flushTerminatorDbgRecords();
233}
234
235iterator_range<DbgRecord::self_iterator> Instruction::cloneDebugInfoFrom(
236 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
237 bool InsertAtHead) {
238 if (!From->DebugMarker)
239 return DbgMarker::getEmptyDbgRecordRange();
240
241 assert(getParent()->IsNewDbgInfoFormat);
242 assert(getParent()->IsNewDbgInfoFormat ==
243 From->getParent()->IsNewDbgInfoFormat);
244
245 if (!DebugMarker)
246 getParent()->createMarker(this);
247
248 return DebugMarker->cloneDebugInfoFrom(From->DebugMarker, FromHere,
249 InsertAtHead);
250}
251
252std::optional<DbgRecord::self_iterator>
253Instruction::getDbgReinsertionPosition() {
254 // Is there a marker on the next instruction?
255 DbgMarker *NextMarker = getParent()->getNextMarker(this);
256 if (!NextMarker)
257 return std::nullopt;
258
259 // Are there any DbgRecords in the next marker?
260 if (NextMarker->StoredDbgRecords.empty())
261 return std::nullopt;
262
263 return NextMarker->StoredDbgRecords.begin();
264}
265
266bool Instruction::hasDbgRecords() const { return !getDbgRecordRange().empty(); }
267
268void Instruction::adoptDbgRecords(BasicBlock *BB, BasicBlock::iterator It,
269 bool InsertAtHead) {
270 DbgMarker *SrcMarker = BB->getMarker(It);
271 auto ReleaseTrailingDbgRecords = [BB, It, SrcMarker]() {
272 if (BB->end() == It) {
273 SrcMarker->eraseFromParent();
275 }
276 };
277
278 if (!SrcMarker || SrcMarker->StoredDbgRecords.empty()) {
279 ReleaseTrailingDbgRecords();
280 return;
281 }
282
283 // If we have DbgMarkers attached to this instruction, we have to honour the
284 // ordering of DbgRecords between this and the other marker. Fall back to just
285 // absorbing from the source.
286 if (DebugMarker || It == BB->end()) {
287 // Ensure we _do_ have a marker.
288 getParent()->createMarker(this);
289 DebugMarker->absorbDebugValues(*SrcMarker, InsertAtHead);
290
291 // Having transferred everything out of SrcMarker, we _could_ clean it up
292 // and free the marker now. However, that's a lot of heap-accounting for a
293 // small amount of memory with a good chance of re-use. Leave it for the
294 // moment. It will be released when the Instruction is freed in the worst
295 // case.
296 // However: if we transferred from a trailing marker off the end of the
297 // block, it's important to not leave the empty marker trailing. It will
298 // give a misleading impression that some debug records have been left
299 // trailing.
300 ReleaseTrailingDbgRecords();
301 } else {
302 // Optimisation: we're transferring all the DbgRecords from the source
303 // marker onto this empty location: just adopt the other instructions
304 // marker.
305 DebugMarker = SrcMarker;
306 DebugMarker->MarkedInstr = this;
307 It->DebugMarker = nullptr;
308 }
309}
310
311void Instruction::dropDbgRecords() {
312 if (DebugMarker)
313 DebugMarker->dropDbgRecords();
314}
315
316void Instruction::dropOneDbgRecord(DbgRecord *DVR) {
317 DebugMarker->dropOneDbgRecord(DVR);
318}
319
320bool Instruction::comesBefore(const Instruction *Other) const {
321 assert(getParent() && Other->getParent() &&
322 "instructions without BB parents have no order");
323 assert(getParent() == Other->getParent() &&
324 "cross-BB instruction order comparison");
325 if (!getParent()->isInstrOrderValid())
326 const_cast<BasicBlock *>(getParent())->renumberInstructions();
327 return Order < Other->Order;
328}
329
330std::optional<BasicBlock::iterator> Instruction::getInsertionPointAfterDef() {
331 assert(!getType()->isVoidTy() && "Instruction must define result");
332 BasicBlock *InsertBB;
333 BasicBlock::iterator InsertPt;
334 if (auto *PN = dyn_cast<PHINode>(this)) {
335 InsertBB = PN->getParent();
336 InsertPt = InsertBB->getFirstInsertionPt();
337 } else if (auto *II = dyn_cast<InvokeInst>(this)) {
338 InsertBB = II->getNormalDest();
339 InsertPt = InsertBB->getFirstInsertionPt();
340 } else if (isa<CallBrInst>(this)) {
341 // Def is available in multiple successors, there's no single dominating
342 // insertion point.
343 return std::nullopt;
344 } else {
345 assert(!isTerminator() && "Only invoke/callbr terminators return value");
346 InsertBB = getParent();
347 InsertPt = std::next(getIterator());
348 // Any instruction inserted immediately after "this" will come before any
349 // debug-info records take effect -- thus, set the head bit indicating that
350 // to debug-info-transfer code.
351 InsertPt.setHeadBit(true);
352 }
353
354 // catchswitch blocks don't have any legal insertion point (because they
355 // are both an exception pad and a terminator).
356 if (InsertPt == InsertBB->end())
357 return std::nullopt;
358 return InsertPt;
359}
360
361bool Instruction::isOnlyUserOfAnyOperand() {
362 return any_of(operands(), [](Value *V) { return V->hasOneUser(); });
363}
364
365void Instruction::setHasNoUnsignedWrap(bool b) {
366 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
367 Inst->setHasNoUnsignedWrap(b);
368 else
369 cast<TruncInst>(this)->setHasNoUnsignedWrap(b);
370}
371
372void Instruction::setHasNoSignedWrap(bool b) {
373 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
374 Inst->setHasNoSignedWrap(b);
375 else
376 cast<TruncInst>(this)->setHasNoSignedWrap(b);
377}
378
379void Instruction::setIsExact(bool b) {
380 cast<PossiblyExactOperator>(this)->setIsExact(b);
381}
382
383void Instruction::setNonNeg(bool b) {
384 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
385 SubclassOptionalData = (SubclassOptionalData & ~PossiblyNonNegInst::NonNeg) |
386 (b * PossiblyNonNegInst::NonNeg);
387}
388
389bool Instruction::hasNoUnsignedWrap() const {
390 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
391 return Inst->hasNoUnsignedWrap();
392
393 return cast<TruncInst>(this)->hasNoUnsignedWrap();
394}
395
396bool Instruction::hasNoSignedWrap() const {
397 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
398 return Inst->hasNoSignedWrap();
399
400 return cast<TruncInst>(this)->hasNoSignedWrap();
401}
402
403bool Instruction::hasNonNeg() const {
404 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
405 return (SubclassOptionalData & PossiblyNonNegInst::NonNeg) != 0;
406}
407
408bool Instruction::hasPoisonGeneratingFlags() const {
409 return cast<Operator>(this)->hasPoisonGeneratingFlags();
410}
411
412void Instruction::dropPoisonGeneratingFlags() {
413 switch (getOpcode()) {
414 case Instruction::Add:
415 case Instruction::Sub:
416 case Instruction::Mul:
417 case Instruction::Shl:
418 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
419 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
420 break;
421
422 case Instruction::UDiv:
423 case Instruction::SDiv:
424 case Instruction::AShr:
425 case Instruction::LShr:
426 cast<PossiblyExactOperator>(this)->setIsExact(false);
427 break;
428
429 case Instruction::Or:
430 cast<PossiblyDisjointInst>(this)->setIsDisjoint(false);
431 break;
432
433 case Instruction::GetElementPtr:
434 cast<GetElementPtrInst>(this)->setNoWrapFlags(GEPNoWrapFlags::none());
435 break;
436
437 case Instruction::UIToFP:
438 case Instruction::ZExt:
439 setNonNeg(false);
440 break;
441
442 case Instruction::Trunc:
443 cast<TruncInst>(this)->setHasNoUnsignedWrap(false);
444 cast<TruncInst>(this)->setHasNoSignedWrap(false);
445 break;
446
447 case Instruction::ICmp:
448 cast<ICmpInst>(this)->setSameSign(false);
449 break;
450 }
451
452 if (isa<FPMathOperator>(this)) {
453 setHasNoNaNs(false);
454 setHasNoInfs(false);
455 }
456
457 assert(!hasPoisonGeneratingFlags() && "must be kept in sync");
458}
459
460bool Instruction::hasPoisonGeneratingMetadata() const {
461 return hasMetadata(LLVMContext::MD_range) ||
462 hasMetadata(LLVMContext::MD_nonnull) ||
463 hasMetadata(LLVMContext::MD_align);
464}
465
466bool Instruction::hasNonDebugLocLoopMetadata() const {
467 // If there is no loop metadata at all, we also don't have
468 // non-debug loop metadata, obviously.
469 if (!hasMetadata(LLVMContext::MD_loop))
470 return false;
471
472 // If we do have loop metadata, retrieve it.
473 MDNode *LoopMD = getMetadata(LLVMContext::MD_loop);
474
475 // Check if the existing operands are debug locations. This loop
476 // should terminate after at most three iterations. Skip
477 // the first item because it is a self-reference.
478 for (const MDOperand &Op : llvm::drop_begin(LoopMD->operands())) {
479 // check for debug location type by attempting a cast.
480 if (!dyn_cast<DILocation>(Op)) {
481 return true;
482 }
483 }
484
485 // If we get here, then all we have is debug locations in the loop metadata.
486 return false;
487}
488
489void Instruction::dropPoisonGeneratingMetadata() {
490 eraseMetadata(LLVMContext::MD_range);
491 eraseMetadata(LLVMContext::MD_nonnull);
492 eraseMetadata(LLVMContext::MD_align);
493}
494
495bool Instruction::hasPoisonGeneratingReturnAttributes() const {
496 if (const auto *CB = dyn_cast<CallBase>(this)) {
497 AttributeSet RetAttrs = CB->getAttributes().getRetAttrs();
498 return RetAttrs.hasAttribute(Attribute::Range) ||
499 RetAttrs.hasAttribute(Attribute::Alignment) ||
500 RetAttrs.hasAttribute(Attribute::NonNull);
501 }
502 return false;
503}
504
505void Instruction::dropPoisonGeneratingReturnAttributes() {
506 if (auto *CB = dyn_cast<CallBase>(this)) {
507 AttributeMask AM;
508 AM.addAttribute(Attribute::Range);
509 AM.addAttribute(Attribute::Alignment);
510 AM.addAttribute(Attribute::NonNull);
511 CB->removeRetAttrs(AM);
512 }
513 assert(!hasPoisonGeneratingReturnAttributes() && "must be kept in sync");
514}
515
516void Instruction::dropUBImplyingAttrsAndUnknownMetadata(
517 ArrayRef<unsigned> KnownIDs) {
518 dropUnknownNonDebugMetadata(KnownIDs);
519 auto *CB = dyn_cast<CallBase>(this);
520 if (!CB)
521 return;
522 // For call instructions, we also need to drop parameter and return attributes
523 // that are can cause UB if the call is moved to a location where the
524 // attribute is not valid.
525 AttributeList AL = CB->getAttributes();
526 if (AL.isEmpty())
527 return;
528 AttributeMask UBImplyingAttributes =
529 AttributeFuncs::getUBImplyingAttributes();
530 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
531 CB->removeParamAttrs(ArgNo, UBImplyingAttributes);
532 CB->removeRetAttrs(UBImplyingAttributes);
533}
534
535void Instruction::dropUBImplyingAttrsAndMetadata() {
536 // !annotation metadata does not impact semantics.
537 // !range, !nonnull and !align produce poison, so they are safe to speculate.
538 // !noundef and various AA metadata must be dropped, as it generally produces
539 // immediate undefined behavior.
540 unsigned KnownIDs[] = {LLVMContext::MD_annotation, LLVMContext::MD_range,
541 LLVMContext::MD_nonnull, LLVMContext::MD_align};
542 dropUBImplyingAttrsAndUnknownMetadata(KnownIDs);
543}
544
545bool Instruction::isExact() const {
546 return cast<PossiblyExactOperator>(this)->isExact();
547}
548
549void Instruction::setFast(bool B) {
550 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
551 cast<FPMathOperator>(this)->setFast(B);
552}
553
554void Instruction::setHasAllowReassoc(bool B) {
555 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
556 cast<FPMathOperator>(this)->setHasAllowReassoc(B);
557}
558
559void Instruction::setHasNoNaNs(bool B) {
560 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
561 cast<FPMathOperator>(this)->setHasNoNaNs(B);
562}
563
564void Instruction::setHasNoInfs(bool B) {
565 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
566 cast<FPMathOperator>(this)->setHasNoInfs(B);
567}
568
569void Instruction::setHasNoSignedZeros(bool B) {
570 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
571 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
572}
573
574void Instruction::setHasAllowReciprocal(bool B) {
575 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
576 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
577}
578
579void Instruction::setHasAllowContract(bool B) {
580 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
581 cast<FPMathOperator>(this)->setHasAllowContract(B);
582}
583
584void Instruction::setHasApproxFunc(bool B) {
585 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
586 cast<FPMathOperator>(this)->setHasApproxFunc(B);
587}
588
589void Instruction::setFastMathFlags(FastMathFlags FMF) {
590 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
591 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
592}
593
594void Instruction::copyFastMathFlags(FastMathFlags FMF) {
595 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
596 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
597}
598
599bool Instruction::isFast() const {
600 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
601 return cast<FPMathOperator>(this)->isFast();
602}
603
604bool Instruction::hasAllowReassoc() const {
605 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
606 return cast<FPMathOperator>(this)->hasAllowReassoc();
607}
608
609bool Instruction::hasNoNaNs() const {
610 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
611 return cast<FPMathOperator>(this)->hasNoNaNs();
612}
613
614bool Instruction::hasNoInfs() const {
615 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
616 return cast<FPMathOperator>(this)->hasNoInfs();
617}
618
619bool Instruction::hasNoSignedZeros() const {
620 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
621 return cast<FPMathOperator>(this)->hasNoSignedZeros();
622}
623
624bool Instruction::hasAllowReciprocal() const {
625 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
626 return cast<FPMathOperator>(this)->hasAllowReciprocal();
627}
628
629bool Instruction::hasAllowContract() const {
630 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
631 return cast<FPMathOperator>(this)->hasAllowContract();
632}
633
634bool Instruction::hasApproxFunc() const {
635 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
636 return cast<FPMathOperator>(this)->hasApproxFunc();
637}
638
639FastMathFlags Instruction::getFastMathFlags() const {
640 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
641 return cast<FPMathOperator>(this)->getFastMathFlags();
642}
643
644void Instruction::copyFastMathFlags(const Instruction *I) {
645 copyFastMathFlags(I->getFastMathFlags());
646}
647
648void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
649 // Copy the wrapping flags.
650 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
651 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
652 setHasNoSignedWrap(OB->hasNoSignedWrap());
653 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
654 }
655 }
656
657 if (auto *TI = dyn_cast<TruncInst>(V)) {
658 if (isa<TruncInst>(this)) {
659 setHasNoSignedWrap(TI->hasNoSignedWrap());
660 setHasNoUnsignedWrap(TI->hasNoUnsignedWrap());
661 }
662 }
663
664 // Copy the exact flag.
665 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
666 if (isa<PossiblyExactOperator>(this))
667 setIsExact(PE->isExact());
668
669 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
670 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
671 DestPD->setIsDisjoint(SrcPD->isDisjoint());
672
673 // Copy the fast-math flags.
674 if (auto *FP = dyn_cast<FPMathOperator>(V))
675 if (isa<FPMathOperator>(this))
676 copyFastMathFlags(FP->getFastMathFlags());
677
678 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
679 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
680 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() |
681 DestGEP->getNoWrapFlags());
682
683 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
684 if (isa<PossiblyNonNegInst>(this))
685 setNonNeg(NNI->hasNonNeg());
686
687 if (auto *SrcICmp = dyn_cast<ICmpInst>(V))
688 if (auto *DestICmp = dyn_cast<ICmpInst>(this))
689 DestICmp->setSameSign(SrcICmp->hasSameSign());
690}
691
692void Instruction::andIRFlags(const Value *V) {
693 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
694 if (isa<OverflowingBinaryOperator>(this)) {
695 setHasNoSignedWrap(hasNoSignedWrap() && OB->hasNoSignedWrap());
696 setHasNoUnsignedWrap(hasNoUnsignedWrap() && OB->hasNoUnsignedWrap());
697 }
698 }
699
700 if (auto *TI = dyn_cast<TruncInst>(V)) {
701 if (isa<TruncInst>(this)) {
702 setHasNoSignedWrap(hasNoSignedWrap() && TI->hasNoSignedWrap());
703 setHasNoUnsignedWrap(hasNoUnsignedWrap() && TI->hasNoUnsignedWrap());
704 }
705 }
706
707 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
708 if (isa<PossiblyExactOperator>(this))
709 setIsExact(isExact() && PE->isExact());
710
711 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
712 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
713 DestPD->setIsDisjoint(DestPD->isDisjoint() && SrcPD->isDisjoint());
714
715 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
716 if (isa<FPMathOperator>(this)) {
718 FM &= FP->getFastMathFlags();
719 copyFastMathFlags(FM);
720 }
721 }
722
723 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
724 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
725 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() &
726 DestGEP->getNoWrapFlags());
727
728 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
729 if (isa<PossiblyNonNegInst>(this))
730 setNonNeg(hasNonNeg() && NNI->hasNonNeg());
731
732 if (auto *SrcICmp = dyn_cast<ICmpInst>(V))
733 if (auto *DestICmp = dyn_cast<ICmpInst>(this))
734 DestICmp->setSameSign(DestICmp->hasSameSign() && SrcICmp->hasSameSign());
735}
736
737const char *Instruction::getOpcodeName(unsigned OpCode) {
738 switch (OpCode) {
739 // Terminators
740 case Ret: return "ret";
741 case Br: return "br";
742 case Switch: return "switch";
743 case IndirectBr: return "indirectbr";
744 case Invoke: return "invoke";
745 case Resume: return "resume";
746 case Unreachable: return "unreachable";
747 case CleanupRet: return "cleanupret";
748 case CatchRet: return "catchret";
749 case CatchPad: return "catchpad";
750 case CatchSwitch: return "catchswitch";
751 case CallBr: return "callbr";
752
753 // Standard unary operators...
754 case FNeg: return "fneg";
755
756 // Standard binary operators...
757 case Add: return "add";
758 case FAdd: return "fadd";
759 case Sub: return "sub";
760 case FSub: return "fsub";
761 case Mul: return "mul";
762 case FMul: return "fmul";
763 case UDiv: return "udiv";
764 case SDiv: return "sdiv";
765 case FDiv: return "fdiv";
766 case URem: return "urem";
767 case SRem: return "srem";
768 case FRem: return "frem";
769
770 // Logical operators...
771 case And: return "and";
772 case Or : return "or";
773 case Xor: return "xor";
774
775 // Memory instructions...
776 case Alloca: return "alloca";
777 case Load: return "load";
778 case Store: return "store";
779 case AtomicCmpXchg: return "cmpxchg";
780 case AtomicRMW: return "atomicrmw";
781 case Fence: return "fence";
782 case GetElementPtr: return "getelementptr";
783
784 // Convert instructions...
785 case Trunc: return "trunc";
786 case ZExt: return "zext";
787 case SExt: return "sext";
788 case FPTrunc: return "fptrunc";
789 case FPExt: return "fpext";
790 case FPToUI: return "fptoui";
791 case FPToSI: return "fptosi";
792 case UIToFP: return "uitofp";
793 case SIToFP: return "sitofp";
794 case IntToPtr: return "inttoptr";
795 case PtrToInt: return "ptrtoint";
796 case BitCast: return "bitcast";
797 case AddrSpaceCast: return "addrspacecast";
798
799 // Other instructions...
800 case ICmp: return "icmp";
801 case FCmp: return "fcmp";
802 case PHI: return "phi";
803 case Select: return "select";
804 case Call: return "call";
805 case Shl: return "shl";
806 case LShr: return "lshr";
807 case AShr: return "ashr";
808 case VAArg: return "va_arg";
809 case ExtractElement: return "extractelement";
810 case InsertElement: return "insertelement";
811 case ShuffleVector: return "shufflevector";
812 case ExtractValue: return "extractvalue";
813 case InsertValue: return "insertvalue";
814 case LandingPad: return "landingpad";
815 case CleanupPad: return "cleanuppad";
816 case Freeze: return "freeze";
817
818 default: return "<Invalid operator> ";
819 }
820}
821
822/// This must be kept in sync with FunctionComparator::cmpOperations in
823/// lib/Transforms/IPO/MergeFunctions.cpp.
824bool Instruction::hasSameSpecialState(const Instruction *I2,
825 bool IgnoreAlignment,
826 bool IntersectAttrs) const {
827 auto I1 = this;
828 assert(I1->getOpcode() == I2->getOpcode() &&
829 "Can not compare special state of different instructions");
830
831 auto CheckAttrsSame = [IntersectAttrs](const CallBase *CB0,
832 const CallBase *CB1) {
833 return IntersectAttrs
834 ? CB0->getAttributes()
835 .intersectWith(CB0->getContext(), CB1->getAttributes())
836 .has_value()
837 : CB0->getAttributes() == CB1->getAttributes();
838 };
839
840 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
841 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
842 (AI->getAlign() == cast<AllocaInst>(I2)->getAlign() ||
843 IgnoreAlignment);
844 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
845 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
846 (LI->getAlign() == cast<LoadInst>(I2)->getAlign() ||
847 IgnoreAlignment) &&
848 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
849 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
850 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
851 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
852 (SI->getAlign() == cast<StoreInst>(I2)->getAlign() ||
853 IgnoreAlignment) &&
854 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
855 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
856 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
857 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
858 if (const CallInst *CI = dyn_cast<CallInst>(I1))
859 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
860 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
861 CheckAttrsSame(CI, cast<CallInst>(I2)) &&
862 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
863 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
864 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
865 CheckAttrsSame(CI, cast<InvokeInst>(I2)) &&
866 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
867 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
868 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
869 CheckAttrsSame(CI, cast<CallBrInst>(I2)) &&
870 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
871 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
872 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
873 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
874 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
875 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
876 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
877 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
878 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
879 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
880 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
881 CXI->getSuccessOrdering() ==
882 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
883 CXI->getFailureOrdering() ==
884 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
885 CXI->getSyncScopeID() ==
886 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
887 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
888 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
889 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
890 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
891 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
892 if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I1))
893 return SVI->getShuffleMask() ==
894 cast<ShuffleVectorInst>(I2)->getShuffleMask();
895 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I1))
896 return GEP->getSourceElementType() ==
897 cast<GetElementPtrInst>(I2)->getSourceElementType();
898
899 return true;
900}
901
902bool Instruction::isIdenticalTo(const Instruction *I) const {
903 return isIdenticalToWhenDefined(I) &&
904 SubclassOptionalData == I->SubclassOptionalData;
905}
906
907bool Instruction::isIdenticalToWhenDefined(const Instruction *I,
908 bool IntersectAttrs) const {
909 if (getOpcode() != I->getOpcode() ||
910 getNumOperands() != I->getNumOperands() || getType() != I->getType())
911 return false;
912
913 // If both instructions have no operands, they are identical.
914 if (getNumOperands() == 0 && I->getNumOperands() == 0)
915 return this->hasSameSpecialState(I, /*IgnoreAlignment=*/false,
916 IntersectAttrs);
917
918 // We have two instructions of identical opcode and #operands. Check to see
919 // if all operands are the same.
920 if (!std::equal(op_begin(), op_end(), I->op_begin()))
921 return false;
922
923 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()!
924 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
925 const PHINode *otherPHI = cast<PHINode>(I);
926 return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
927 otherPHI->block_begin());
928 }
929
930 return this->hasSameSpecialState(I, /*IgnoreAlignment=*/false,
931 IntersectAttrs);
932}
933
934// Keep this in sync with FunctionComparator::cmpOperations in
935// lib/Transforms/IPO/MergeFunctions.cpp.
936bool Instruction::isSameOperationAs(const Instruction *I,
937 unsigned flags) const {
938 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
939 bool UseScalarTypes = flags & CompareUsingScalarTypes;
940 bool IntersectAttrs = flags & CompareUsingIntersectedAttrs;
941
942 if (getOpcode() != I->getOpcode() ||
943 getNumOperands() != I->getNumOperands() ||
944 (UseScalarTypes ?
945 getType()->getScalarType() != I->getType()->getScalarType() :
946 getType() != I->getType()))
947 return false;
948
949 // We have two instructions of identical opcode and #operands. Check to see
950 // if all operands are the same type
951 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
952 if (UseScalarTypes ?
953 getOperand(i)->getType()->getScalarType() !=
954 I->getOperand(i)->getType()->getScalarType() :
955 getOperand(i)->getType() != I->getOperand(i)->getType())
956 return false;
957
958 return this->hasSameSpecialState(I, IgnoreAlignment, IntersectAttrs);
959}
960
961bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
962 for (const Use &U : uses()) {
963 // PHI nodes uses values in the corresponding predecessor block. For other
964 // instructions, just check to see whether the parent of the use matches up.
965 const Instruction *I = cast<Instruction>(U.getUser());
966 const PHINode *PN = dyn_cast<PHINode>(I);
967 if (!PN) {
968 if (I->getParent() != BB)
969 return true;
970 continue;
971 }
972
973 if (PN->getIncomingBlock(U) != BB)
974 return true;
975 }
976 return false;
977}
978
979bool Instruction::mayReadFromMemory() const {
980 switch (getOpcode()) {
981 default: return false;
982 case Instruction::VAArg:
983 case Instruction::Load:
984 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
985 case Instruction::AtomicCmpXchg:
986 case Instruction::AtomicRMW:
987 case Instruction::CatchPad:
988 case Instruction::CatchRet:
989 return true;
990 case Instruction::Call:
991 case Instruction::Invoke:
992 case Instruction::CallBr:
993 return !cast<CallBase>(this)->onlyWritesMemory();
994 case Instruction::Store:
995 return !cast<StoreInst>(this)->isUnordered();
996 }
997}
998
999bool Instruction::mayWriteToMemory() const {
1000 switch (getOpcode()) {
1001 default: return false;
1002 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
1003 case Instruction::Store:
1004 case Instruction::VAArg:
1005 case Instruction::AtomicCmpXchg:
1006 case Instruction::AtomicRMW:
1007 case Instruction::CatchPad:
1008 case Instruction::CatchRet:
1009 return true;
1010 case Instruction::Call:
1011 case Instruction::Invoke:
1012 case Instruction::CallBr:
1013 return !cast<CallBase>(this)->onlyReadsMemory();
1014 case Instruction::Load:
1015 return !cast<LoadInst>(this)->isUnordered();
1016 }
1017}
1018
1019bool Instruction::isAtomic() const {
1020 switch (getOpcode()) {
1021 default:
1022 return false;
1023 case Instruction::AtomicCmpXchg:
1024 case Instruction::AtomicRMW:
1025 case Instruction::Fence:
1026 return true;
1027 case Instruction::Load:
1028 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
1029 case Instruction::Store:
1030 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
1031 }
1032}
1033
1034bool Instruction::hasAtomicLoad() const {
1035 assert(isAtomic());
1036 switch (getOpcode()) {
1037 default:
1038 return false;
1039 case Instruction::AtomicCmpXchg:
1040 case Instruction::AtomicRMW:
1041 case Instruction::Load:
1042 return true;
1043 }
1044}
1045
1046bool Instruction::hasAtomicStore() const {
1047 assert(isAtomic());
1048 switch (getOpcode()) {
1049 default:
1050 return false;
1051 case Instruction::AtomicCmpXchg:
1052 case Instruction::AtomicRMW:
1053 case Instruction::Store:
1054 return true;
1055 }
1056}
1057
1058bool Instruction::isVolatile() const {
1059 switch (getOpcode()) {
1060 default:
1061 return false;
1062 case Instruction::AtomicRMW:
1063 return cast<AtomicRMWInst>(this)->isVolatile();
1064 case Instruction::Store:
1065 return cast<StoreInst>(this)->isVolatile();
1066 case Instruction::Load:
1067 return cast<LoadInst>(this)->isVolatile();
1068 case Instruction::AtomicCmpXchg:
1069 return cast<AtomicCmpXchgInst>(this)->isVolatile();
1070 case Instruction::Call:
1071 case Instruction::Invoke:
1072 // There are a very limited number of intrinsics with volatile flags.
1073 if (auto *II = dyn_cast<IntrinsicInst>(this)) {
1074 if (auto *MI = dyn_cast<MemIntrinsic>(II))
1075 return MI->isVolatile();
1076 switch (II->getIntrinsicID()) {
1077 default: break;
1078 case Intrinsic::matrix_column_major_load:
1079 return cast<ConstantInt>(II->getArgOperand(2))->isOne();
1080 case Intrinsic::matrix_column_major_store:
1081 return cast<ConstantInt>(II->getArgOperand(3))->isOne();
1082 }
1083 }
1084 return false;
1085 }
1086}
1087
1088Type *Instruction::getAccessType() const {
1089 switch (getOpcode()) {
1090 case Instruction::Store:
1091 return cast<StoreInst>(this)->getValueOperand()->getType();
1092 case Instruction::Load:
1093 case Instruction::AtomicRMW:
1094 return getType();
1095 case Instruction::AtomicCmpXchg:
1096 return cast<AtomicCmpXchgInst>(this)->getNewValOperand()->getType();
1097 case Instruction::Call:
1098 case Instruction::Invoke:
1099 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(this)) {
1100 switch (II->getIntrinsicID()) {
1101 case Intrinsic::masked_load:
1102 case Intrinsic::masked_gather:
1103 case Intrinsic::masked_expandload:
1104 case Intrinsic::vp_load:
1105 case Intrinsic::vp_gather:
1106 case Intrinsic::experimental_vp_strided_load:
1107 return II->getType();
1108 case Intrinsic::masked_store:
1109 case Intrinsic::masked_scatter:
1110 case Intrinsic::masked_compressstore:
1111 case Intrinsic::vp_store:
1112 case Intrinsic::vp_scatter:
1113 case Intrinsic::experimental_vp_strided_store:
1114 return II->getOperand(0)->getType();
1115 default:
1116 break;
1117 }
1118 }
1119 }
1120
1121 return nullptr;
1122}
1123
1124static bool canUnwindPastLandingPad(const LandingPadInst *LP,
1125 bool IncludePhaseOneUnwind) {
1126 // Because phase one unwinding skips cleanup landingpads, we effectively
1127 // unwind past this frame, and callers need to have valid unwind info.
1128 if (LP->isCleanup())
1129 return IncludePhaseOneUnwind;
1130
1131 for (unsigned I = 0; I < LP->getNumClauses(); ++I) {
1132 Constant *Clause = LP->getClause(I);
1133 // catch ptr null catches all exceptions.
1134 if (LP->isCatch(I) && isa<ConstantPointerNull>(Clause))
1135 return false;
1136 // filter [0 x ptr] catches all exceptions.
1137 if (LP->isFilter(I) && Clause->getType()->getArrayNumElements() == 0)
1138 return false;
1139 }
1140
1141 // May catch only some subset of exceptions, in which case other exceptions
1142 // will continue unwinding.
1143 return true;
1144}
1145
1146bool Instruction::mayThrow(bool IncludePhaseOneUnwind) const {
1147 switch (getOpcode()) {
1148 case Instruction::Call:
1149 return !cast<CallInst>(this)->doesNotThrow();
1150 case Instruction::CleanupRet:
1151 return cast<CleanupReturnInst>(this)->unwindsToCaller();
1152 case Instruction::CatchSwitch:
1153 return cast<CatchSwitchInst>(this)->unwindsToCaller();
1154 case Instruction::Resume:
1155 return true;
1156 case Instruction::Invoke: {
1157 // Landingpads themselves don't unwind -- however, an invoke of a skipped
1158 // landingpad may continue unwinding.
1159 BasicBlock *UnwindDest = cast<InvokeInst>(this)->getUnwindDest();
1160 Instruction *Pad = UnwindDest->getFirstNonPHI();
1161 if (auto *LP = dyn_cast<LandingPadInst>(Pad))
1162 return canUnwindPastLandingPad(LP, IncludePhaseOneUnwind);
1163 return false;
1164 }
1165 case Instruction::CleanupPad:
1166 // Treat the same as cleanup landingpad.
1167 return IncludePhaseOneUnwind;
1168 default:
1169 return false;
1170 }
1171}
1172
1173bool Instruction::mayHaveSideEffects() const {
1174 return mayWriteToMemory() || mayThrow() || !willReturn();
1175}
1176
1177bool Instruction::isSafeToRemove() const {
1178 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
1179 !this->isTerminator() && !this->isEHPad();
1180}
1181
1182bool Instruction::willReturn() const {
1183 // Volatile store isn't guaranteed to return; see LangRef.
1184 if (auto *SI = dyn_cast<StoreInst>(this))
1185 return !SI->isVolatile();
1186
1187 if (const auto *CB = dyn_cast<CallBase>(this))
1188 return CB->hasFnAttr(Attribute::WillReturn);
1189 return true;
1190}
1191
1192bool Instruction::isLifetimeStartOrEnd() const {
1193 auto *II = dyn_cast<IntrinsicInst>(this);
1194 if (!II)
1195 return false;
1196 Intrinsic::ID ID = II->getIntrinsicID();
1197 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
1198}
1199
1200bool Instruction::isLaunderOrStripInvariantGroup() const {
1201 auto *II = dyn_cast<IntrinsicInst>(this);
1202 if (!II)
1203 return false;
1204 Intrinsic::ID ID = II->getIntrinsicID();
1205 return ID == Intrinsic::launder_invariant_group ||
1206 ID == Intrinsic::strip_invariant_group;
1207}
1208
1209bool Instruction::isDebugOrPseudoInst() const {
1210 return isa<DbgInfoIntrinsic>(this) || isa<PseudoProbeInst>(this);
1211}
1212
1213const Instruction *
1214Instruction::getNextNonDebugInstruction(bool SkipPseudoOp) const {
1215 for (const Instruction *I = getNextNode(); I; I = I->getNextNode())
1216 if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I)))
1217 return I;
1218 return nullptr;
1219}
1220
1221const Instruction *
1222Instruction::getPrevNonDebugInstruction(bool SkipPseudoOp) const {
1223 for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode())
1224 if (!isa<DbgInfoIntrinsic>(I) &&
1225 !(SkipPseudoOp && isa<PseudoProbeInst>(I)) &&
1226 !(isa<IntrinsicInst>(I) &&
1227 cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fake_use))
1228 return I;
1229 return nullptr;
1230}
1231
1232const DebugLoc &Instruction::getStableDebugLoc() const {
1233 if (isa<DbgInfoIntrinsic>(this))
1234 if (const Instruction *Next = getNextNonDebugInstruction())
1235 return Next->getDebugLoc();
1236 return getDebugLoc();
1237}
1238
1239bool Instruction::isAssociative() const {
1240 if (auto *II = dyn_cast<IntrinsicInst>(this))
1241 return II->isAssociative();
1242 unsigned Opcode = getOpcode();
1243 if (isAssociative(Opcode))
1244 return true;
1245
1246 switch (Opcode) {
1247 case FMul:
1248 case FAdd:
1249 return cast<FPMathOperator>(this)->hasAllowReassoc() &&
1250 cast<FPMathOperator>(this)->hasNoSignedZeros();
1251 default:
1252 return false;
1253 }
1254}
1255
1256bool Instruction::isCommutative() const {
1257 if (auto *II = dyn_cast<IntrinsicInst>(this))
1258 return II->isCommutative();
1259 // TODO: Should allow icmp/fcmp?
1260 return isCommutative(getOpcode());
1261}
1262
1263unsigned Instruction::getNumSuccessors() const {
1264 switch (getOpcode()) {
1265#define HANDLE_TERM_INST(N, OPC, CLASS) \
1266 case Instruction::OPC: \
1267 return static_cast<const CLASS *>(this)->getNumSuccessors();
1268#include "llvm/IR/Instruction.def"
1269 default:
1270 break;
1271 }
1272 llvm_unreachable("not a terminator");
1273}
1274
1275BasicBlock *Instruction::getSuccessor(unsigned idx) const {
1276 switch (getOpcode()) {
1277#define HANDLE_TERM_INST(N, OPC, CLASS) \
1278 case Instruction::OPC: \
1279 return static_cast<const CLASS *>(this)->getSuccessor(idx);
1280#include "llvm/IR/Instruction.def"
1281 default:
1282 break;
1283 }
1284 llvm_unreachable("not a terminator");
1285}
1286
1287void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
1288 switch (getOpcode()) {
1289#define HANDLE_TERM_INST(N, OPC, CLASS) \
1290 case Instruction::OPC: \
1291 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
1292#include "llvm/IR/Instruction.def"
1293 default:
1294 break;
1295 }
1296 llvm_unreachable("not a terminator");
1297}
1298
1299void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) {
1300 for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors();
1301 Idx != NumSuccessors; ++Idx)
1302 if (getSuccessor(Idx) == OldBB)
1303 setSuccessor(Idx, NewBB);
1304}
1305
1306Instruction *Instruction::cloneImpl() const {
1307 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
1308}
1309
1310void Instruction::swapProfMetadata() {
1311 MDNode *ProfileData = getBranchWeightMDNode(*this);
1312 if (!ProfileData)
1313 return;
1314 unsigned FirstIdx = getBranchWeightOffset(ProfileData);
1315 if (ProfileData->getNumOperands() != 2 + FirstIdx)
1316 return;
1317
1318 unsigned SecondIdx = FirstIdx + 1;
1320 // If there are more weights past the second, we can't swap them
1321 if (ProfileData->getNumOperands() > SecondIdx + 1)
1322 return;
1323 for (unsigned Idx = 0; Idx < FirstIdx; ++Idx) {
1324 Ops.push_back(ProfileData->getOperand(Idx));
1325 }
1326 // Switch the order of the weights
1327 Ops.push_back(ProfileData->getOperand(SecondIdx));
1328 Ops.push_back(ProfileData->getOperand(FirstIdx));
1329 setMetadata(LLVMContext::MD_prof,
1330 MDNode::get(ProfileData->getContext(), Ops));
1331}
1332
1333void Instruction::copyMetadata(const Instruction &SrcInst,
1334 ArrayRef<unsigned> WL) {
1335 if (!SrcInst.hasMetadata())
1336 return;
1337
1339
1340 // Otherwise, enumerate and copy over metadata from the old instruction to the
1341 // new one.
1343 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
1344 for (const auto &MD : TheMDs) {
1345 if (WL.empty() || WLS.count(MD.first))
1346 setMetadata(MD.first, MD.second);
1347 }
1348 if (WL.empty() || WLS.count(LLVMContext::MD_dbg))
1349 setDebugLoc(SrcInst.getDebugLoc());
1350}
1351
1352Instruction *Instruction::clone() const {
1353 Instruction *New = nullptr;
1354 switch (getOpcode()) {
1355 default:
1356 llvm_unreachable("Unhandled Opcode.");
1357#define HANDLE_INST(num, opc, clas) \
1358 case Instruction::opc: \
1359 New = cast<clas>(this)->cloneImpl(); \
1360 break;
1361#include "llvm/IR/Instruction.def"
1362#undef HANDLE_INST
1363 }
1364
1365 New->SubclassOptionalData = SubclassOptionalData;
1366 New->copyMetadata(*this);
1367 return New;
1368}
static unsigned getIntrinsicID(const SDNode *N)
AMDGPU Register Bank Select
Rewrite undef for PHI
VarLocInsertPt getNextNode(const DbgRecord *DVR)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
BlockVerifier::State From
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...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live propagate it s liveness to any other values it uses(according to Uses). void DeadArgumentEliminationPass
This file defines the DenseSet and SmallDenseSet classes.
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1315
Hexagon Common GEP
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)
#define I(x, y, z)
Definition: MD5.cpp:58
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, 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)
llvm::cl::opt< bool > UseNewDbgInfoFormat
This file contains the declarations for profiling metadata utility functions.
static bool mayHaveSideEffects(MachineInstr &MI)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isCommutative(Instruction *I)
static unsigned getFastMathFlags(const MachineInstr &I)
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 std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
static bool isAssociative(const COFFSection &Section)
BinaryOperator * Mul
an instruction to allocate memory on the stack
Definition: Instructions.h:63
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:157
iterator begin() const
Definition: ArrayRef.h:156
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:163
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:501
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:704
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
std::optional< AttributeList > intersectWith(LLVMContext &C, AttributeList Other) const
Try to intersect this AttributeList with Other.
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
Definition: AttributeMask.h:44
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:461
void deleteTrailingDbgRecords()
Delete any trailing DbgRecords at the end of this block, see setTrailingDbgRecords.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:416
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:367
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
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:177
bool IsNewDbgInfoFormat
Flag recording whether or not this block stores debug-info in the form of intrinsic instructions (fal...
Definition: BasicBlock.h:67
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1120
AttributeList getAttributes() const
Return the attributes for this call.
Definition: InstrTypes.h:1425
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:661
This is an important base class in LLVM.
Definition: Constant.h:42
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Per-instruction record of debug-info.
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
void dropDbgRecords()
Erase all DbgRecords in this DbgMarker.
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:33
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:20
An instruction for ordering other memory operations.
Definition: Instructions.h:424
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:933
This instruction inserts a struct field of array element value into an aggregate value.
DbgMarker * DebugMarker
Optional marker recording the position for debugging information that takes effect immediately before...
Definition: Instruction.h:84
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:475
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Definition: Instruction.h:368
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
Definition: Instruction.h:415
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
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.
Definition: Instructions.h:176
Metadata node.
Definition: Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1430
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1428
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1436
LLVMContext & getContext() const
Definition: Metadata.h:1233
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:891
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const_block_iterator block_begin() const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Instruction that can have a nneg flag (zext/uitofp).
Definition: InstrTypes.h:636
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:298
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
An instruction for storing to memory.
Definition: Instructions.h:292
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
LLVM Value Representation.
Definition: Value.h:74
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool mayThrow(const MachineInstr &MI)
@ OB
OB - OneByte - Set if this instruction has a one byte opcode.
Definition: X86BaseInfo.h:732
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
constexpr double e
Definition: MathExtras.h:47
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1746
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange(DbgMarker *DebugMarker)
Inline helper to return a range of DbgRecords attached to a marker.
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ FMul
Product of floats.
@ And
Bitwise or logical AND of integers.
@ FAdd
Sum of floats.
Summary of memprof metadata on allocations.