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