• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/IR/CallSite.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IR/Operator.h"
20 #include "llvm/IR/Type.h"
21 using namespace llvm;
22 
Instruction(Type * ty,unsigned it,Use * Ops,unsigned NumOps,Instruction * InsertBefore)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 
Instruction(Type * ty,unsigned it,Use * Ops,unsigned NumOps,BasicBlock * InsertAtEnd)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 
45 // Out of line virtual method, so the vtable, etc has a home.
~Instruction()46 Instruction::~Instruction() {
47   assert(!Parent && "Instruction still linked in the program!");
48   if (hasMetadataHashEntry())
49     clearMetadataHashEntries();
50 }
51 
52 
setParent(BasicBlock * P)53 void Instruction::setParent(BasicBlock *P) {
54   Parent = P;
55 }
56 
getModule() const57 const Module *Instruction::getModule() const {
58   return getParent()->getModule();
59 }
60 
getModule()61 Module *Instruction::getModule() {
62   return getParent()->getModule();
63 }
64 
getFunction()65 Function *Instruction::getFunction() { return getParent()->getParent(); }
66 
getFunction() const67 const Function *Instruction::getFunction() const {
68   return getParent()->getParent();
69 }
70 
removeFromParent()71 void Instruction::removeFromParent() {
72   getParent()->getInstList().remove(getIterator());
73 }
74 
eraseFromParent()75 iplist<Instruction>::iterator Instruction::eraseFromParent() {
76   return getParent()->getInstList().erase(getIterator());
77 }
78 
79 /// insertBefore - Insert an unlinked instructions into a basic block
80 /// immediately before the specified instruction.
insertBefore(Instruction * InsertPos)81 void Instruction::insertBefore(Instruction *InsertPos) {
82   InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
83 }
84 
85 /// insertAfter - Insert an unlinked instructions into a basic block
86 /// immediately after the specified instruction.
insertAfter(Instruction * InsertPos)87 void Instruction::insertAfter(Instruction *InsertPos) {
88   InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
89                                                     this);
90 }
91 
92 /// moveBefore - Unlink this instruction from its current basic block and
93 /// insert it into the basic block that MovePos lives in, right before
94 /// MovePos.
moveBefore(Instruction * MovePos)95 void Instruction::moveBefore(Instruction *MovePos) {
96   MovePos->getParent()->getInstList().splice(
97       MovePos->getIterator(), getParent()->getInstList(), getIterator());
98 }
99 
100 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
101 /// operator which supports this flag. See LangRef.html for the meaning of this
102 /// flag.
setHasUnsafeAlgebra(bool B)103 void Instruction::setHasUnsafeAlgebra(bool B) {
104   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
105   cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
106 }
107 
108 /// Set or clear the NoNaNs flag on this instruction, which must be an operator
109 /// which supports this flag. See LangRef.html for the meaning of this flag.
setHasNoNaNs(bool B)110 void Instruction::setHasNoNaNs(bool B) {
111   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
112   cast<FPMathOperator>(this)->setHasNoNaNs(B);
113 }
114 
115 /// Set or clear the no-infs flag on this instruction, which must be an operator
116 /// which supports this flag. See LangRef.html for the meaning of this flag.
setHasNoInfs(bool B)117 void Instruction::setHasNoInfs(bool B) {
118   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
119   cast<FPMathOperator>(this)->setHasNoInfs(B);
120 }
121 
122 /// Set or clear the no-signed-zeros flag on this instruction, which must be an
123 /// operator which supports this flag. See LangRef.html for the meaning of this
124 /// flag.
setHasNoSignedZeros(bool B)125 void Instruction::setHasNoSignedZeros(bool B) {
126   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
127   cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
128 }
129 
130 /// Set or clear the allow-reciprocal flag on this instruction, which must be an
131 /// operator which supports this flag. See LangRef.html for the meaning of this
132 /// flag.
setHasAllowReciprocal(bool B)133 void Instruction::setHasAllowReciprocal(bool B) {
134   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
135   cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
136 }
137 
138 /// Convenience function for setting all the fast-math flags on this
139 /// instruction, which must be an operator which supports these flags. See
140 /// LangRef.html for the meaning of these flats.
setFastMathFlags(FastMathFlags FMF)141 void Instruction::setFastMathFlags(FastMathFlags FMF) {
142   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
143   cast<FPMathOperator>(this)->setFastMathFlags(FMF);
144 }
145 
copyFastMathFlags(FastMathFlags FMF)146 void Instruction::copyFastMathFlags(FastMathFlags FMF) {
147   assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
148   cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
149 }
150 
151 /// Determine whether the unsafe-algebra flag is set.
hasUnsafeAlgebra() const152 bool Instruction::hasUnsafeAlgebra() const {
153   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
154   return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
155 }
156 
157 /// Determine whether the no-NaNs flag is set.
hasNoNaNs() const158 bool Instruction::hasNoNaNs() const {
159   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
160   return cast<FPMathOperator>(this)->hasNoNaNs();
161 }
162 
163 /// Determine whether the no-infs flag is set.
hasNoInfs() const164 bool Instruction::hasNoInfs() const {
165   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
166   return cast<FPMathOperator>(this)->hasNoInfs();
167 }
168 
169 /// Determine whether the no-signed-zeros flag is set.
hasNoSignedZeros() const170 bool Instruction::hasNoSignedZeros() const {
171   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
172   return cast<FPMathOperator>(this)->hasNoSignedZeros();
173 }
174 
175 /// Determine whether the allow-reciprocal flag is set.
hasAllowReciprocal() const176 bool Instruction::hasAllowReciprocal() const {
177   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
178   return cast<FPMathOperator>(this)->hasAllowReciprocal();
179 }
180 
181 /// Convenience function for getting all the fast-math flags, which must be an
182 /// operator which supports these flags. See LangRef.html for the meaning of
183 /// these flags.
getFastMathFlags() const184 FastMathFlags Instruction::getFastMathFlags() const {
185   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
186   return cast<FPMathOperator>(this)->getFastMathFlags();
187 }
188 
189 /// Copy I's fast-math flags
copyFastMathFlags(const Instruction * I)190 void Instruction::copyFastMathFlags(const Instruction *I) {
191   copyFastMathFlags(I->getFastMathFlags());
192 }
193 
194 
getOpcodeName(unsigned OpCode)195 const char *Instruction::getOpcodeName(unsigned OpCode) {
196   switch (OpCode) {
197   // Terminators
198   case Ret:    return "ret";
199   case Br:     return "br";
200   case Switch: return "switch";
201   case IndirectBr: return "indirectbr";
202   case Invoke: return "invoke";
203   case Resume: return "resume";
204   case Unreachable: return "unreachable";
205   case CleanupRet: return "cleanupret";
206   case CatchRet: return "catchret";
207   case CatchPad: return "catchpad";
208   case CatchSwitch: return "catchswitch";
209 
210   // Standard binary operators...
211   case Add: return "add";
212   case FAdd: return "fadd";
213   case Sub: return "sub";
214   case FSub: return "fsub";
215   case Mul: return "mul";
216   case FMul: return "fmul";
217   case UDiv: return "udiv";
218   case SDiv: return "sdiv";
219   case FDiv: return "fdiv";
220   case URem: return "urem";
221   case SRem: return "srem";
222   case FRem: return "frem";
223 
224   // Logical operators...
225   case And: return "and";
226   case Or : return "or";
227   case Xor: return "xor";
228 
229   // Memory instructions...
230   case Alloca:        return "alloca";
231   case Load:          return "load";
232   case Store:         return "store";
233   case AtomicCmpXchg: return "cmpxchg";
234   case AtomicRMW:     return "atomicrmw";
235   case Fence:         return "fence";
236   case GetElementPtr: return "getelementptr";
237 
238   // Convert instructions...
239   case Trunc:         return "trunc";
240   case ZExt:          return "zext";
241   case SExt:          return "sext";
242   case FPTrunc:       return "fptrunc";
243   case FPExt:         return "fpext";
244   case FPToUI:        return "fptoui";
245   case FPToSI:        return "fptosi";
246   case UIToFP:        return "uitofp";
247   case SIToFP:        return "sitofp";
248   case IntToPtr:      return "inttoptr";
249   case PtrToInt:      return "ptrtoint";
250   case BitCast:       return "bitcast";
251   case AddrSpaceCast: return "addrspacecast";
252 
253   // Other instructions...
254   case ICmp:           return "icmp";
255   case FCmp:           return "fcmp";
256   case PHI:            return "phi";
257   case Select:         return "select";
258   case Call:           return "call";
259   case Shl:            return "shl";
260   case LShr:           return "lshr";
261   case AShr:           return "ashr";
262   case VAArg:          return "va_arg";
263   case ExtractElement: return "extractelement";
264   case InsertElement:  return "insertelement";
265   case ShuffleVector:  return "shufflevector";
266   case ExtractValue:   return "extractvalue";
267   case InsertValue:    return "insertvalue";
268   case LandingPad:     return "landingpad";
269   case CleanupPad:     return "cleanuppad";
270 
271   default: return "<Invalid operator> ";
272   }
273 }
274 
275 /// Return true if both instructions have the same special state
276 /// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp.
haveSameSpecialState(const Instruction * I1,const Instruction * I2,bool IgnoreAlignment=false)277 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
278                                  bool IgnoreAlignment = false) {
279   assert(I1->getOpcode() == I2->getOpcode() &&
280          "Can not compare special state of different instructions");
281 
282   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
283     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
284            (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
285             IgnoreAlignment) &&
286            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
287            LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
288   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
289     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
290            (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
291             IgnoreAlignment) &&
292            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
293            SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
294   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
295     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
296   if (const CallInst *CI = dyn_cast<CallInst>(I1))
297     return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
298            CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
299            CI->getAttributes() == cast<CallInst>(I2)->getAttributes() &&
300            CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
301   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
302     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
303            CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() &&
304            CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
305   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
306     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
307   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
308     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
309   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
310     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
311            FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
312   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
313     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
314            CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
315            CXI->getSuccessOrdering() ==
316                cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
317            CXI->getFailureOrdering() ==
318                cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
319            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
320   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
321     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
322            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
323            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
324            RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
325 
326   return true;
327 }
328 
329 /// isIdenticalTo - Return true if the specified instruction is exactly
330 /// identical to the current one.  This means that all operands match and any
331 /// extra information (e.g. load is volatile) agree.
isIdenticalTo(const Instruction * I) const332 bool Instruction::isIdenticalTo(const Instruction *I) const {
333   return isIdenticalToWhenDefined(I) &&
334          SubclassOptionalData == I->SubclassOptionalData;
335 }
336 
337 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
338 /// ignores the SubclassOptionalData flags, which specify conditions
339 /// under which the instruction's result is undefined.
isIdenticalToWhenDefined(const Instruction * I) const340 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
341   if (getOpcode() != I->getOpcode() ||
342       getNumOperands() != I->getNumOperands() ||
343       getType() != I->getType())
344     return false;
345 
346   // If both instructions have no operands, they are identical.
347   if (getNumOperands() == 0 && I->getNumOperands() == 0)
348     return haveSameSpecialState(this, I);
349 
350   // We have two instructions of identical opcode and #operands.  Check to see
351   // if all operands are the same.
352   if (!std::equal(op_begin(), op_end(), I->op_begin()))
353     return false;
354 
355   if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
356     const PHINode *otherPHI = cast<PHINode>(I);
357     return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
358                       otherPHI->block_begin());
359   }
360 
361   return haveSameSpecialState(this, I);
362 }
363 
364 // isSameOperationAs
365 // This should be kept in sync with isEquivalentOperation in
366 // lib/Transforms/IPO/MergeFunctions.cpp.
isSameOperationAs(const Instruction * I,unsigned flags) const367 bool Instruction::isSameOperationAs(const Instruction *I,
368                                     unsigned flags) const {
369   bool IgnoreAlignment = flags & CompareIgnoringAlignment;
370   bool UseScalarTypes  = flags & CompareUsingScalarTypes;
371 
372   if (getOpcode() != I->getOpcode() ||
373       getNumOperands() != I->getNumOperands() ||
374       (UseScalarTypes ?
375        getType()->getScalarType() != I->getType()->getScalarType() :
376        getType() != I->getType()))
377     return false;
378 
379   // We have two instructions of identical opcode and #operands.  Check to see
380   // if all operands are the same type
381   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
382     if (UseScalarTypes ?
383         getOperand(i)->getType()->getScalarType() !=
384           I->getOperand(i)->getType()->getScalarType() :
385         getOperand(i)->getType() != I->getOperand(i)->getType())
386       return false;
387 
388   return haveSameSpecialState(this, I, IgnoreAlignment);
389 }
390 
391 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
392 /// specified block.  Note that PHI nodes are considered to evaluate their
393 /// operands in the corresponding predecessor block.
isUsedOutsideOfBlock(const BasicBlock * BB) const394 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
395   for (const Use &U : uses()) {
396     // PHI nodes uses values in the corresponding predecessor block.  For other
397     // instructions, just check to see whether the parent of the use matches up.
398     const Instruction *I = cast<Instruction>(U.getUser());
399     const PHINode *PN = dyn_cast<PHINode>(I);
400     if (!PN) {
401       if (I->getParent() != BB)
402         return true;
403       continue;
404     }
405 
406     if (PN->getIncomingBlock(U) != BB)
407       return true;
408   }
409   return false;
410 }
411 
412 /// mayReadFromMemory - Return true if this instruction may read memory.
413 ///
mayReadFromMemory() const414 bool Instruction::mayReadFromMemory() const {
415   switch (getOpcode()) {
416   default: return false;
417   case Instruction::VAArg:
418   case Instruction::Load:
419   case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
420   case Instruction::AtomicCmpXchg:
421   case Instruction::AtomicRMW:
422   case Instruction::CatchPad:
423   case Instruction::CatchRet:
424     return true;
425   case Instruction::Call:
426     return !cast<CallInst>(this)->doesNotAccessMemory();
427   case Instruction::Invoke:
428     return !cast<InvokeInst>(this)->doesNotAccessMemory();
429   case Instruction::Store:
430     return !cast<StoreInst>(this)->isUnordered();
431   }
432 }
433 
434 /// mayWriteToMemory - Return true if this instruction may modify memory.
435 ///
mayWriteToMemory() const436 bool Instruction::mayWriteToMemory() const {
437   switch (getOpcode()) {
438   default: return false;
439   case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
440   case Instruction::Store:
441   case Instruction::VAArg:
442   case Instruction::AtomicCmpXchg:
443   case Instruction::AtomicRMW:
444   case Instruction::CatchPad:
445   case Instruction::CatchRet:
446     return true;
447   case Instruction::Call:
448     return !cast<CallInst>(this)->onlyReadsMemory();
449   case Instruction::Invoke:
450     return !cast<InvokeInst>(this)->onlyReadsMemory();
451   case Instruction::Load:
452     return !cast<LoadInst>(this)->isUnordered();
453   }
454 }
455 
isAtomic() const456 bool Instruction::isAtomic() const {
457   switch (getOpcode()) {
458   default:
459     return false;
460   case Instruction::AtomicCmpXchg:
461   case Instruction::AtomicRMW:
462   case Instruction::Fence:
463     return true;
464   case Instruction::Load:
465     return cast<LoadInst>(this)->getOrdering() != NotAtomic;
466   case Instruction::Store:
467     return cast<StoreInst>(this)->getOrdering() != NotAtomic;
468   }
469 }
470 
mayThrow() const471 bool Instruction::mayThrow() const {
472   if (const CallInst *CI = dyn_cast<CallInst>(this))
473     return !CI->doesNotThrow();
474   if (const auto *CRI = dyn_cast<CleanupReturnInst>(this))
475     return CRI->unwindsToCaller();
476   if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this))
477     return CatchSwitch->unwindsToCaller();
478   return isa<ResumeInst>(this);
479 }
480 
mayReturn() const481 bool Instruction::mayReturn() const {
482   if (const CallInst *CI = dyn_cast<CallInst>(this))
483     return !CI->doesNotReturn();
484   return true;
485 }
486 
487 /// isAssociative - Return true if the instruction is associative:
488 ///
489 ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
490 ///
491 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
492 ///
isAssociative(unsigned Opcode)493 bool Instruction::isAssociative(unsigned Opcode) {
494   return Opcode == And || Opcode == Or || Opcode == Xor ||
495          Opcode == Add || Opcode == Mul;
496 }
497 
isAssociative() const498 bool Instruction::isAssociative() const {
499   unsigned Opcode = getOpcode();
500   if (isAssociative(Opcode))
501     return true;
502 
503   switch (Opcode) {
504   case FMul:
505   case FAdd:
506     return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
507   default:
508     return false;
509   }
510 }
511 
512 /// isCommutative - Return true if the instruction is commutative:
513 ///
514 ///   Commutative operators satisfy: (x op y) === (y op x)
515 ///
516 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
517 /// applied to any type.
518 ///
isCommutative(unsigned op)519 bool Instruction::isCommutative(unsigned op) {
520   switch (op) {
521   case Add:
522   case FAdd:
523   case Mul:
524   case FMul:
525   case And:
526   case Or:
527   case Xor:
528     return true;
529   default:
530     return false;
531   }
532 }
533 
534 /// isIdempotent - Return true if the instruction is idempotent:
535 ///
536 ///   Idempotent operators satisfy:  x op x === x
537 ///
538 /// In LLVM, the And and Or operators are idempotent.
539 ///
isIdempotent(unsigned Opcode)540 bool Instruction::isIdempotent(unsigned Opcode) {
541   return Opcode == And || Opcode == Or;
542 }
543 
544 /// isNilpotent - Return true if the instruction is nilpotent:
545 ///
546 ///   Nilpotent operators satisfy:  x op x === Id,
547 ///
548 ///   where Id is the identity for the operator, i.e. a constant such that
549 ///     x op Id === x and Id op x === x for all x.
550 ///
551 /// In LLVM, the Xor operator is nilpotent.
552 ///
isNilpotent(unsigned Opcode)553 bool Instruction::isNilpotent(unsigned Opcode) {
554   return Opcode == Xor;
555 }
556 
cloneImpl() const557 Instruction *Instruction::cloneImpl() const {
558   llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
559 }
560 
clone() const561 Instruction *Instruction::clone() const {
562   Instruction *New = nullptr;
563   switch (getOpcode()) {
564   default:
565     llvm_unreachable("Unhandled Opcode.");
566 #define HANDLE_INST(num, opc, clas)                                            \
567   case Instruction::opc:                                                       \
568     New = cast<clas>(this)->cloneImpl();                                       \
569     break;
570 #include "llvm/IR/Instruction.def"
571 #undef HANDLE_INST
572   }
573 
574   New->SubclassOptionalData = SubclassOptionalData;
575   if (!hasMetadata())
576     return New;
577 
578   // Otherwise, enumerate and copy over metadata from the old instruction to the
579   // new one.
580   SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
581   getAllMetadataOtherThanDebugLoc(TheMDs);
582   for (const auto &MD : TheMDs)
583     New->setMetadata(MD.first, MD.second);
584 
585   New->setDebugLoc(getDebugLoc());
586   return New;
587 }
588