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/IR/IntrinsicInst.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/MDBuilder.h"
19 #include "llvm/IR/Operator.h"
20 #include "llvm/IR/Type.h"
21 using namespace llvm;
22 
23 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
24                          Instruction *InsertBefore)
25   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
26 
27   // If requested, insert this instruction into a basic block...
28   if (InsertBefore) {
29     BasicBlock *BB = InsertBefore->getParent();
30     assert(BB && "Instruction to insert before is not in a basic block!");
31     BB->getInstList().insert(InsertBefore->getIterator(), this);
32   }
33 }
34 
35 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
36                          BasicBlock *InsertAtEnd)
37   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
38 
39   // append this instruction into the basic block
40   assert(InsertAtEnd && "Basic block to append to may not be NULL!");
41   InsertAtEnd->getInstList().push_back(this);
42 }
43 
44 Instruction::~Instruction() {
45   assert(!Parent && "Instruction still linked in the program!");
46   if (hasMetadataHashEntry())
47     clearMetadataHashEntries();
48 }
49 
50 
51 void Instruction::setParent(BasicBlock *P) {
52   Parent = P;
53 }
54 
55 const Module *Instruction::getModule() const {
56   return getParent()->getModule();
57 }
58 
59 const Function *Instruction::getFunction() const {
60   return getParent()->getParent();
61 }
62 
63 void Instruction::removeFromParent() {
64   getParent()->getInstList().remove(getIterator());
65 }
66 
67 iplist<Instruction>::iterator Instruction::eraseFromParent() {
68   return getParent()->getInstList().erase(getIterator());
69 }
70 
71 /// Insert an unlinked instruction into a basic block immediately before the
72 /// specified instruction.
73 void Instruction::insertBefore(Instruction *InsertPos) {
74   InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
75 }
76 
77 /// Insert an unlinked instruction into a basic block immediately after the
78 /// specified instruction.
79 void Instruction::insertAfter(Instruction *InsertPos) {
80   InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
81                                                     this);
82 }
83 
84 /// Unlink this instruction from its current basic block and insert it into the
85 /// basic block that MovePos lives in, right before MovePos.
86 void Instruction::moveBefore(Instruction *MovePos) {
87   moveBefore(*MovePos->getParent(), MovePos->getIterator());
88 }
89 
90 void Instruction::moveAfter(Instruction *MovePos) {
91   moveBefore(*MovePos->getParent(), ++MovePos->getIterator());
92 }
93 
94 void Instruction::moveBefore(BasicBlock &BB,
95                              SymbolTableList<Instruction>::iterator I) {
96   assert(I == BB.end() || I->getParent() == &BB);
97   BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
98 }
99 
100 bool Instruction::comesBefore(const Instruction *Other) const {
101   assert(Parent && Other->Parent &&
102          "instructions without BB parents have no order");
103   assert(Parent == Other->Parent && "cross-BB instruction order comparison");
104   if (!Parent->isInstrOrderValid())
105     Parent->renumberInstructions();
106   return Order < Other->Order;
107 }
108 
109 void Instruction::setHasNoUnsignedWrap(bool b) {
110   cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
111 }
112 
113 void Instruction::setHasNoSignedWrap(bool b) {
114   cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
115 }
116 
117 void Instruction::setIsExact(bool b) {
118   cast<PossiblyExactOperator>(this)->setIsExact(b);
119 }
120 
121 bool Instruction::hasNoUnsignedWrap() const {
122   return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
123 }
124 
125 bool Instruction::hasNoSignedWrap() const {
126   return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
127 }
128 
129 void Instruction::dropPoisonGeneratingFlags() {
130   switch (getOpcode()) {
131   case Instruction::Add:
132   case Instruction::Sub:
133   case Instruction::Mul:
134   case Instruction::Shl:
135     cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
136     cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
137     break;
138 
139   case Instruction::UDiv:
140   case Instruction::SDiv:
141   case Instruction::AShr:
142   case Instruction::LShr:
143     cast<PossiblyExactOperator>(this)->setIsExact(false);
144     break;
145 
146   case Instruction::GetElementPtr:
147     cast<GetElementPtrInst>(this)->setIsInBounds(false);
148     break;
149   }
150   // TODO: FastMathFlags!
151 }
152 
153 
154 bool Instruction::isExact() const {
155   return cast<PossiblyExactOperator>(this)->isExact();
156 }
157 
158 void Instruction::setFast(bool B) {
159   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
160   cast<FPMathOperator>(this)->setFast(B);
161 }
162 
163 void Instruction::setHasAllowReassoc(bool B) {
164   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
165   cast<FPMathOperator>(this)->setHasAllowReassoc(B);
166 }
167 
168 void Instruction::setHasNoNaNs(bool B) {
169   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
170   cast<FPMathOperator>(this)->setHasNoNaNs(B);
171 }
172 
173 void Instruction::setHasNoInfs(bool B) {
174   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
175   cast<FPMathOperator>(this)->setHasNoInfs(B);
176 }
177 
178 void Instruction::setHasNoSignedZeros(bool B) {
179   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
180   cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
181 }
182 
183 void Instruction::setHasAllowReciprocal(bool B) {
184   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
185   cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
186 }
187 
188 void Instruction::setHasApproxFunc(bool B) {
189   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
190   cast<FPMathOperator>(this)->setHasApproxFunc(B);
191 }
192 
193 void Instruction::setFastMathFlags(FastMathFlags FMF) {
194   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
195   cast<FPMathOperator>(this)->setFastMathFlags(FMF);
196 }
197 
198 void Instruction::copyFastMathFlags(FastMathFlags FMF) {
199   assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
200   cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
201 }
202 
203 bool Instruction::isFast() const {
204   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
205   return cast<FPMathOperator>(this)->isFast();
206 }
207 
208 bool Instruction::hasAllowReassoc() const {
209   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
210   return cast<FPMathOperator>(this)->hasAllowReassoc();
211 }
212 
213 bool Instruction::hasNoNaNs() const {
214   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
215   return cast<FPMathOperator>(this)->hasNoNaNs();
216 }
217 
218 bool Instruction::hasNoInfs() const {
219   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
220   return cast<FPMathOperator>(this)->hasNoInfs();
221 }
222 
223 bool Instruction::hasNoSignedZeros() const {
224   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
225   return cast<FPMathOperator>(this)->hasNoSignedZeros();
226 }
227 
228 bool Instruction::hasAllowReciprocal() const {
229   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
230   return cast<FPMathOperator>(this)->hasAllowReciprocal();
231 }
232 
233 bool Instruction::hasAllowContract() const {
234   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
235   return cast<FPMathOperator>(this)->hasAllowContract();
236 }
237 
238 bool Instruction::hasApproxFunc() const {
239   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
240   return cast<FPMathOperator>(this)->hasApproxFunc();
241 }
242 
243 FastMathFlags Instruction::getFastMathFlags() const {
244   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
245   return cast<FPMathOperator>(this)->getFastMathFlags();
246 }
247 
248 void Instruction::copyFastMathFlags(const Instruction *I) {
249   copyFastMathFlags(I->getFastMathFlags());
250 }
251 
252 void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
253   // Copy the wrapping flags.
254   if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
255     if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
256       setHasNoSignedWrap(OB->hasNoSignedWrap());
257       setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
258     }
259   }
260 
261   // Copy the exact flag.
262   if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
263     if (isa<PossiblyExactOperator>(this))
264       setIsExact(PE->isExact());
265 
266   // Copy the fast-math flags.
267   if (auto *FP = dyn_cast<FPMathOperator>(V))
268     if (isa<FPMathOperator>(this))
269       copyFastMathFlags(FP->getFastMathFlags());
270 
271   if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
272     if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
273       DestGEP->setIsInBounds(SrcGEP->isInBounds() | DestGEP->isInBounds());
274 }
275 
276 void Instruction::andIRFlags(const Value *V) {
277   if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
278     if (isa<OverflowingBinaryOperator>(this)) {
279       setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
280       setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
281     }
282   }
283 
284   if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
285     if (isa<PossiblyExactOperator>(this))
286       setIsExact(isExact() & PE->isExact());
287 
288   if (auto *FP = dyn_cast<FPMathOperator>(V)) {
289     if (isa<FPMathOperator>(this)) {
290       FastMathFlags FM = getFastMathFlags();
291       FM &= FP->getFastMathFlags();
292       copyFastMathFlags(FM);
293     }
294   }
295 
296   if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
297     if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
298       DestGEP->setIsInBounds(SrcGEP->isInBounds() & DestGEP->isInBounds());
299 }
300 
301 const char *Instruction::getOpcodeName(unsigned OpCode) {
302   switch (OpCode) {
303   // Terminators
304   case Ret:    return "ret";
305   case Br:     return "br";
306   case Switch: return "switch";
307   case IndirectBr: return "indirectbr";
308   case Invoke: return "invoke";
309   case Resume: return "resume";
310   case Unreachable: return "unreachable";
311   case CleanupRet: return "cleanupret";
312   case CatchRet: return "catchret";
313   case CatchPad: return "catchpad";
314   case CatchSwitch: return "catchswitch";
315   case CallBr: return "callbr";
316 
317   // Standard unary operators...
318   case FNeg: return "fneg";
319 
320   // Standard binary operators...
321   case Add: return "add";
322   case FAdd: return "fadd";
323   case Sub: return "sub";
324   case FSub: return "fsub";
325   case Mul: return "mul";
326   case FMul: return "fmul";
327   case UDiv: return "udiv";
328   case SDiv: return "sdiv";
329   case FDiv: return "fdiv";
330   case URem: return "urem";
331   case SRem: return "srem";
332   case FRem: return "frem";
333 
334   // Logical operators...
335   case And: return "and";
336   case Or : return "or";
337   case Xor: return "xor";
338 
339   // Memory instructions...
340   case Alloca:        return "alloca";
341   case Load:          return "load";
342   case Store:         return "store";
343   case AtomicCmpXchg: return "cmpxchg";
344   case AtomicRMW:     return "atomicrmw";
345   case Fence:         return "fence";
346   case GetElementPtr: return "getelementptr";
347 
348   // Convert instructions...
349   case Trunc:         return "trunc";
350   case ZExt:          return "zext";
351   case SExt:          return "sext";
352   case FPTrunc:       return "fptrunc";
353   case FPExt:         return "fpext";
354   case FPToUI:        return "fptoui";
355   case FPToSI:        return "fptosi";
356   case UIToFP:        return "uitofp";
357   case SIToFP:        return "sitofp";
358   case IntToPtr:      return "inttoptr";
359   case PtrToInt:      return "ptrtoint";
360   case BitCast:       return "bitcast";
361   case AddrSpaceCast: return "addrspacecast";
362 
363   // Other instructions...
364   case ICmp:           return "icmp";
365   case FCmp:           return "fcmp";
366   case PHI:            return "phi";
367   case Select:         return "select";
368   case Call:           return "call";
369   case Shl:            return "shl";
370   case LShr:           return "lshr";
371   case AShr:           return "ashr";
372   case VAArg:          return "va_arg";
373   case ExtractElement: return "extractelement";
374   case InsertElement:  return "insertelement";
375   case ShuffleVector:  return "shufflevector";
376   case ExtractValue:   return "extractvalue";
377   case InsertValue:    return "insertvalue";
378   case LandingPad:     return "landingpad";
379   case CleanupPad:     return "cleanuppad";
380   case Freeze:         return "freeze";
381 
382   default: return "<Invalid operator> ";
383   }
384 }
385 
386 /// Return true if both instructions have the same special state. This must be
387 /// kept in sync with FunctionComparator::cmpOperations in
388 /// lib/Transforms/IPO/MergeFunctions.cpp.
389 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
390                                  bool IgnoreAlignment = false) {
391   assert(I1->getOpcode() == I2->getOpcode() &&
392          "Can not compare special state of different instructions");
393 
394   if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
395     return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
396            (AI->getAlignment() == cast<AllocaInst>(I2)->getAlignment() ||
397             IgnoreAlignment);
398   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
399     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
400            (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
401             IgnoreAlignment) &&
402            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
403            LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
404   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
405     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
406            (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
407             IgnoreAlignment) &&
408            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
409            SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
410   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
411     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
412   if (const CallInst *CI = dyn_cast<CallInst>(I1))
413     return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
414            CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
415            CI->getAttributes() == cast<CallInst>(I2)->getAttributes() &&
416            CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
417   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
418     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
419            CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() &&
420            CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
421   if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
422     return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
423            CI->getAttributes() == cast<CallBrInst>(I2)->getAttributes() &&
424            CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
425   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
426     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
427   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
428     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
429   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
430     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
431            FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
432   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
433     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
434            CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
435            CXI->getSuccessOrdering() ==
436                cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
437            CXI->getFailureOrdering() ==
438                cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
439            CXI->getSyncScopeID() ==
440                cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
441   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
442     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
443            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
444            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
445            RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
446   if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I1))
447     return SVI->getShuffleMask() ==
448            cast<ShuffleVectorInst>(I2)->getShuffleMask();
449 
450   return true;
451 }
452 
453 bool Instruction::isIdenticalTo(const Instruction *I) const {
454   return isIdenticalToWhenDefined(I) &&
455          SubclassOptionalData == I->SubclassOptionalData;
456 }
457 
458 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
459   if (getOpcode() != I->getOpcode() ||
460       getNumOperands() != I->getNumOperands() ||
461       getType() != I->getType())
462     return false;
463 
464   // If both instructions have no operands, they are identical.
465   if (getNumOperands() == 0 && I->getNumOperands() == 0)
466     return haveSameSpecialState(this, I);
467 
468   // We have two instructions of identical opcode and #operands.  Check to see
469   // if all operands are the same.
470   if (!std::equal(op_begin(), op_end(), I->op_begin()))
471     return false;
472 
473   if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
474     const PHINode *otherPHI = cast<PHINode>(I);
475     return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
476                       otherPHI->block_begin());
477   }
478 
479   return haveSameSpecialState(this, I);
480 }
481 
482 // Keep this in sync with FunctionComparator::cmpOperations in
483 // lib/Transforms/IPO/MergeFunctions.cpp.
484 bool Instruction::isSameOperationAs(const Instruction *I,
485                                     unsigned flags) const {
486   bool IgnoreAlignment = flags & CompareIgnoringAlignment;
487   bool UseScalarTypes  = flags & CompareUsingScalarTypes;
488 
489   if (getOpcode() != I->getOpcode() ||
490       getNumOperands() != I->getNumOperands() ||
491       (UseScalarTypes ?
492        getType()->getScalarType() != I->getType()->getScalarType() :
493        getType() != I->getType()))
494     return false;
495 
496   // We have two instructions of identical opcode and #operands.  Check to see
497   // if all operands are the same type
498   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
499     if (UseScalarTypes ?
500         getOperand(i)->getType()->getScalarType() !=
501           I->getOperand(i)->getType()->getScalarType() :
502         getOperand(i)->getType() != I->getOperand(i)->getType())
503       return false;
504 
505   return haveSameSpecialState(this, I, IgnoreAlignment);
506 }
507 
508 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
509   for (const Use &U : uses()) {
510     // PHI nodes uses values in the corresponding predecessor block.  For other
511     // instructions, just check to see whether the parent of the use matches up.
512     const Instruction *I = cast<Instruction>(U.getUser());
513     const PHINode *PN = dyn_cast<PHINode>(I);
514     if (!PN) {
515       if (I->getParent() != BB)
516         return true;
517       continue;
518     }
519 
520     if (PN->getIncomingBlock(U) != BB)
521       return true;
522   }
523   return false;
524 }
525 
526 bool Instruction::mayReadFromMemory() const {
527   switch (getOpcode()) {
528   default: return false;
529   case Instruction::VAArg:
530   case Instruction::Load:
531   case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
532   case Instruction::AtomicCmpXchg:
533   case Instruction::AtomicRMW:
534   case Instruction::CatchPad:
535   case Instruction::CatchRet:
536     return true;
537   case Instruction::Call:
538   case Instruction::Invoke:
539   case Instruction::CallBr:
540     return !cast<CallBase>(this)->doesNotReadMemory();
541   case Instruction::Store:
542     return !cast<StoreInst>(this)->isUnordered();
543   }
544 }
545 
546 bool Instruction::mayWriteToMemory() const {
547   switch (getOpcode()) {
548   default: return false;
549   case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
550   case Instruction::Store:
551   case Instruction::VAArg:
552   case Instruction::AtomicCmpXchg:
553   case Instruction::AtomicRMW:
554   case Instruction::CatchPad:
555   case Instruction::CatchRet:
556     return true;
557   case Instruction::Call:
558   case Instruction::Invoke:
559   case Instruction::CallBr:
560     return !cast<CallBase>(this)->onlyReadsMemory();
561   case Instruction::Load:
562     return !cast<LoadInst>(this)->isUnordered();
563   }
564 }
565 
566 bool Instruction::isAtomic() const {
567   switch (getOpcode()) {
568   default:
569     return false;
570   case Instruction::AtomicCmpXchg:
571   case Instruction::AtomicRMW:
572   case Instruction::Fence:
573     return true;
574   case Instruction::Load:
575     return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
576   case Instruction::Store:
577     return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
578   }
579 }
580 
581 bool Instruction::hasAtomicLoad() const {
582   assert(isAtomic());
583   switch (getOpcode()) {
584   default:
585     return false;
586   case Instruction::AtomicCmpXchg:
587   case Instruction::AtomicRMW:
588   case Instruction::Load:
589     return true;
590   }
591 }
592 
593 bool Instruction::hasAtomicStore() const {
594   assert(isAtomic());
595   switch (getOpcode()) {
596   default:
597     return false;
598   case Instruction::AtomicCmpXchg:
599   case Instruction::AtomicRMW:
600   case Instruction::Store:
601     return true;
602   }
603 }
604 
605 bool Instruction::mayThrow() const {
606   if (const CallInst *CI = dyn_cast<CallInst>(this))
607     return !CI->doesNotThrow();
608   if (const auto *CRI = dyn_cast<CleanupReturnInst>(this))
609     return CRI->unwindsToCaller();
610   if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this))
611     return CatchSwitch->unwindsToCaller();
612   return isa<ResumeInst>(this);
613 }
614 
615 bool Instruction::isSafeToRemove() const {
616   return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
617          !this->isTerminator();
618 }
619 
620 bool Instruction::isLifetimeStartOrEnd() const {
621   auto II = dyn_cast<IntrinsicInst>(this);
622   if (!II)
623     return false;
624   Intrinsic::ID ID = II->getIntrinsicID();
625   return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
626 }
627 
628 const Instruction *Instruction::getNextNonDebugInstruction() const {
629   for (const Instruction *I = getNextNode(); I; I = I->getNextNode())
630     if (!isa<DbgInfoIntrinsic>(I))
631       return I;
632   return nullptr;
633 }
634 
635 const Instruction *Instruction::getPrevNonDebugInstruction() const {
636   for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode())
637     if (!isa<DbgInfoIntrinsic>(I))
638       return I;
639   return nullptr;
640 }
641 
642 bool Instruction::isAssociative() const {
643   unsigned Opcode = getOpcode();
644   if (isAssociative(Opcode))
645     return true;
646 
647   switch (Opcode) {
648   case FMul:
649   case FAdd:
650     return cast<FPMathOperator>(this)->hasAllowReassoc() &&
651            cast<FPMathOperator>(this)->hasNoSignedZeros();
652   default:
653     return false;
654   }
655 }
656 
657 unsigned Instruction::getNumSuccessors() const {
658   switch (getOpcode()) {
659 #define HANDLE_TERM_INST(N, OPC, CLASS)                                        \
660   case Instruction::OPC:                                                       \
661     return static_cast<const CLASS *>(this)->getNumSuccessors();
662 #include "llvm/IR/Instruction.def"
663   default:
664     break;
665   }
666   llvm_unreachable("not a terminator");
667 }
668 
669 BasicBlock *Instruction::getSuccessor(unsigned idx) const {
670   switch (getOpcode()) {
671 #define HANDLE_TERM_INST(N, OPC, CLASS)                                        \
672   case Instruction::OPC:                                                       \
673     return static_cast<const CLASS *>(this)->getSuccessor(idx);
674 #include "llvm/IR/Instruction.def"
675   default:
676     break;
677   }
678   llvm_unreachable("not a terminator");
679 }
680 
681 void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
682   switch (getOpcode()) {
683 #define HANDLE_TERM_INST(N, OPC, CLASS)                                        \
684   case Instruction::OPC:                                                       \
685     return static_cast<CLASS *>(this)->setSuccessor(idx, B);
686 #include "llvm/IR/Instruction.def"
687   default:
688     break;
689   }
690   llvm_unreachable("not a terminator");
691 }
692 
693 void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) {
694   for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors();
695        Idx != NumSuccessors; ++Idx)
696     if (getSuccessor(Idx) == OldBB)
697       setSuccessor(Idx, NewBB);
698 }
699 
700 Instruction *Instruction::cloneImpl() const {
701   llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
702 }
703 
704 void Instruction::swapProfMetadata() {
705   MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
706   if (!ProfileData || ProfileData->getNumOperands() != 3 ||
707       !isa<MDString>(ProfileData->getOperand(0)))
708     return;
709 
710   MDString *MDName = cast<MDString>(ProfileData->getOperand(0));
711   if (MDName->getString() != "branch_weights")
712     return;
713 
714   // The first operand is the name. Fetch them backwards and build a new one.
715   Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
716                      ProfileData->getOperand(1)};
717   setMetadata(LLVMContext::MD_prof,
718               MDNode::get(ProfileData->getContext(), Ops));
719 }
720 
721 void Instruction::copyMetadata(const Instruction &SrcInst,
722                                ArrayRef<unsigned> WL) {
723   if (!SrcInst.hasMetadata())
724     return;
725 
726   DenseSet<unsigned> WLS;
727   for (unsigned M : WL)
728     WLS.insert(M);
729 
730   // Otherwise, enumerate and copy over metadata from the old instruction to the
731   // new one.
732   SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
733   SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
734   for (const auto &MD : TheMDs) {
735     if (WL.empty() || WLS.count(MD.first))
736       setMetadata(MD.first, MD.second);
737   }
738   if (WL.empty() || WLS.count(LLVMContext::MD_dbg))
739     setDebugLoc(SrcInst.getDebugLoc());
740 }
741 
742 Instruction *Instruction::clone() const {
743   Instruction *New = nullptr;
744   switch (getOpcode()) {
745   default:
746     llvm_unreachable("Unhandled Opcode.");
747 #define HANDLE_INST(num, opc, clas)                                            \
748   case Instruction::opc:                                                       \
749     New = cast<clas>(this)->cloneImpl();                                       \
750     break;
751 #include "llvm/IR/Instruction.def"
752 #undef HANDLE_INST
753   }
754 
755   New->SubclassOptionalData = SubclassOptionalData;
756   New->copyMetadata(*this);
757   return New;
758 }
759 
760 void Instruction::setProfWeight(uint64_t W) {
761   assert(isa<CallBase>(this) &&
762          "Can only set weights for call like instructions");
763   SmallVector<uint32_t, 1> Weights;
764   Weights.push_back(W);
765   MDBuilder MDB(getContext());
766   setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
767 }
768