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