1 //===-- Instruction.cpp - Implement the Instruction class -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Instruction class for the IR library.
12 //===----------------------------------------------------------------------===//
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"
23 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
24 Instruction *InsertBefore)
25 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
27 // If requested, insert this instruction into a basic block...
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);
35 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
36 BasicBlock *InsertAtEnd)
37 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
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);
45 // Out of line virtual method, so the vtable, etc has a home.
46 Instruction::~Instruction() {
47 assert(!Parent && "Instruction still linked in the program!");
48 if (hasMetadataHashEntry())
49 clearMetadataHashEntries();
53 void Instruction::setParent(BasicBlock *P) {
57 const Module *Instruction::getModule() const {
58 return getParent()->getModule();
61 Module *Instruction::getModule() {
62 return getParent()->getModule();
65 Function *Instruction::getFunction() { return getParent()->getParent(); }
67 const Function *Instruction::getFunction() const {
68 return getParent()->getParent();
71 void Instruction::removeFromParent() {
72 getParent()->getInstList().remove(getIterator());
75 iplist<Instruction>::iterator Instruction::eraseFromParent() {
76 return getParent()->getInstList().erase(getIterator());
79 /// insertBefore - Insert an unlinked instructions into a basic block
80 /// immediately before the specified instruction.
81 void Instruction::insertBefore(Instruction *InsertPos) {
82 InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
85 /// insertAfter - Insert an unlinked instructions into a basic block
86 /// immediately after the specified instruction.
87 void Instruction::insertAfter(Instruction *InsertPos) {
88 InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
92 /// moveBefore - Unlink this instruction from its current basic block and
93 /// insert it into the basic block that MovePos lives in, right before
95 void Instruction::moveBefore(Instruction *MovePos) {
96 MovePos->getParent()->getInstList().splice(
97 MovePos->getIterator(), getParent()->getInstList(), getIterator());
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
103 void Instruction::setHasUnsafeAlgebra(bool B) {
104 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
105 cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
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.
110 void Instruction::setHasNoNaNs(bool B) {
111 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
112 cast<FPMathOperator>(this)->setHasNoNaNs(B);
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.
117 void Instruction::setHasNoInfs(bool B) {
118 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
119 cast<FPMathOperator>(this)->setHasNoInfs(B);
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
125 void Instruction::setHasNoSignedZeros(bool B) {
126 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
127 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
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
133 void Instruction::setHasAllowReciprocal(bool B) {
134 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
135 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
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.
141 void Instruction::setFastMathFlags(FastMathFlags FMF) {
142 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
143 cast<FPMathOperator>(this)->setFastMathFlags(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);
151 /// Determine whether the unsafe-algebra flag is set.
152 bool Instruction::hasUnsafeAlgebra() const {
153 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
154 return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
157 /// Determine whether the no-NaNs flag is set.
158 bool Instruction::hasNoNaNs() const {
159 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
160 return cast<FPMathOperator>(this)->hasNoNaNs();
163 /// Determine whether the no-infs flag is set.
164 bool Instruction::hasNoInfs() const {
165 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
166 return cast<FPMathOperator>(this)->hasNoInfs();
169 /// Determine whether the no-signed-zeros flag is set.
170 bool Instruction::hasNoSignedZeros() const {
171 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
172 return cast<FPMathOperator>(this)->hasNoSignedZeros();
175 /// Determine whether the allow-reciprocal flag is set.
176 bool Instruction::hasAllowReciprocal() const {
177 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
178 return cast<FPMathOperator>(this)->hasAllowReciprocal();
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
184 FastMathFlags Instruction::getFastMathFlags() const {
185 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
186 return cast<FPMathOperator>(this)->getFastMathFlags();
189 /// Copy I's fast-math flags
190 void Instruction::copyFastMathFlags(const Instruction *I) {
191 copyFastMathFlags(I->getFastMathFlags());
195 const char *Instruction::getOpcodeName(unsigned OpCode) {
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 CleanupEndPad: return "cleanupendpad";
206 case CleanupRet: return "cleanupret";
207 case CatchEndPad: return "catchendpad";
208 case CatchRet: return "catchret";
209 case CatchPad: return "catchpad";
210 case TerminatePad: return "terminatepad";
212 // Standard binary operators...
213 case Add: return "add";
214 case FAdd: return "fadd";
215 case Sub: return "sub";
216 case FSub: return "fsub";
217 case Mul: return "mul";
218 case FMul: return "fmul";
219 case UDiv: return "udiv";
220 case SDiv: return "sdiv";
221 case FDiv: return "fdiv";
222 case URem: return "urem";
223 case SRem: return "srem";
224 case FRem: return "frem";
226 // Logical operators...
227 case And: return "and";
228 case Or : return "or";
229 case Xor: return "xor";
231 // Memory instructions...
232 case Alloca: return "alloca";
233 case Load: return "load";
234 case Store: return "store";
235 case AtomicCmpXchg: return "cmpxchg";
236 case AtomicRMW: return "atomicrmw";
237 case Fence: return "fence";
238 case GetElementPtr: return "getelementptr";
240 // Convert instructions...
241 case Trunc: return "trunc";
242 case ZExt: return "zext";
243 case SExt: return "sext";
244 case FPTrunc: return "fptrunc";
245 case FPExt: return "fpext";
246 case FPToUI: return "fptoui";
247 case FPToSI: return "fptosi";
248 case UIToFP: return "uitofp";
249 case SIToFP: return "sitofp";
250 case IntToPtr: return "inttoptr";
251 case PtrToInt: return "ptrtoint";
252 case BitCast: return "bitcast";
253 case AddrSpaceCast: return "addrspacecast";
255 // Other instructions...
256 case ICmp: return "icmp";
257 case FCmp: return "fcmp";
258 case PHI: return "phi";
259 case Select: return "select";
260 case Call: return "call";
261 case Shl: return "shl";
262 case LShr: return "lshr";
263 case AShr: return "ashr";
264 case VAArg: return "va_arg";
265 case ExtractElement: return "extractelement";
266 case InsertElement: return "insertelement";
267 case ShuffleVector: return "shufflevector";
268 case ExtractValue: return "extractvalue";
269 case InsertValue: return "insertvalue";
270 case LandingPad: return "landingpad";
271 case CleanupPad: return "cleanuppad";
273 default: return "<Invalid operator> ";
277 /// Return true if both instructions have the same special state
278 /// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp.
279 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
280 bool IgnoreAlignment = false) {
281 assert(I1->getOpcode() == I2->getOpcode() &&
282 "Can not compare special state of different instructions");
284 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
285 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
286 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
288 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
289 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
290 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
291 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
292 (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
294 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
295 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
296 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
297 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
298 if (const CallInst *CI = dyn_cast<CallInst>(I1))
299 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
300 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
301 CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
302 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
303 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
304 CI->getAttributes() ==
305 cast<InvokeInst>(I2)->getAttributes();
306 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
307 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
308 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
309 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
310 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
311 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
312 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
313 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
314 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
315 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
316 CXI->getSuccessOrdering() ==
317 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
318 CXI->getFailureOrdering() ==
319 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
320 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
321 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
322 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
323 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
324 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
325 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
330 /// isIdenticalTo - Return true if the specified instruction is exactly
331 /// identical to the current one. This means that all operands match and any
332 /// extra information (e.g. load is volatile) agree.
333 bool Instruction::isIdenticalTo(const Instruction *I) const {
334 return isIdenticalToWhenDefined(I) &&
335 SubclassOptionalData == I->SubclassOptionalData;
338 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
339 /// ignores the SubclassOptionalData flags, which specify conditions
340 /// under which the instruction's result is undefined.
341 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
342 if (getOpcode() != I->getOpcode() ||
343 getNumOperands() != I->getNumOperands() ||
344 getType() != I->getType())
347 // If both instructions have no operands, they are identical.
348 if (getNumOperands() == 0 && I->getNumOperands() == 0)
349 return haveSameSpecialState(this, I);
351 // We have two instructions of identical opcode and #operands. Check to see
352 // if all operands are the same.
353 if (!std::equal(op_begin(), op_end(), I->op_begin()))
356 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
357 const PHINode *otherPHI = cast<PHINode>(I);
358 return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
359 otherPHI->block_begin());
362 return haveSameSpecialState(this, I);
366 // This should be kept in sync with isEquivalentOperation in
367 // lib/Transforms/IPO/MergeFunctions.cpp.
368 bool Instruction::isSameOperationAs(const Instruction *I,
369 unsigned flags) const {
370 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
371 bool UseScalarTypes = flags & CompareUsingScalarTypes;
373 if (getOpcode() != I->getOpcode() ||
374 getNumOperands() != I->getNumOperands() ||
376 getType()->getScalarType() != I->getType()->getScalarType() :
377 getType() != I->getType()))
380 // We have two instructions of identical opcode and #operands. Check to see
381 // if all operands are the same type
382 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
384 getOperand(i)->getType()->getScalarType() !=
385 I->getOperand(i)->getType()->getScalarType() :
386 getOperand(i)->getType() != I->getOperand(i)->getType())
389 return haveSameSpecialState(this, I, IgnoreAlignment);
392 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
393 /// specified block. Note that PHI nodes are considered to evaluate their
394 /// operands in the corresponding predecessor block.
395 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
396 for (const Use &U : uses()) {
397 // PHI nodes uses values in the corresponding predecessor block. For other
398 // instructions, just check to see whether the parent of the use matches up.
399 const Instruction *I = cast<Instruction>(U.getUser());
400 const PHINode *PN = dyn_cast<PHINode>(I);
402 if (I->getParent() != BB)
407 if (PN->getIncomingBlock(U) != BB)
413 /// mayReadFromMemory - Return true if this instruction may read memory.
415 bool Instruction::mayReadFromMemory() const {
416 switch (getOpcode()) {
417 default: return false;
418 case Instruction::VAArg:
419 case Instruction::Load:
420 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
421 case Instruction::AtomicCmpXchg:
422 case Instruction::AtomicRMW:
423 case Instruction::CatchPad:
424 case Instruction::CatchRet:
425 case Instruction::TerminatePad:
427 case Instruction::Call:
428 return !cast<CallInst>(this)->doesNotAccessMemory();
429 case Instruction::Invoke:
430 return !cast<InvokeInst>(this)->doesNotAccessMemory();
431 case Instruction::Store:
432 return !cast<StoreInst>(this)->isUnordered();
436 /// mayWriteToMemory - Return true if this instruction may modify memory.
438 bool Instruction::mayWriteToMemory() const {
439 switch (getOpcode()) {
440 default: return false;
441 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
442 case Instruction::Store:
443 case Instruction::VAArg:
444 case Instruction::AtomicCmpXchg:
445 case Instruction::AtomicRMW:
446 case Instruction::CatchPad:
447 case Instruction::CatchRet:
448 case Instruction::TerminatePad:
450 case Instruction::Call:
451 return !cast<CallInst>(this)->onlyReadsMemory();
452 case Instruction::Invoke:
453 return !cast<InvokeInst>(this)->onlyReadsMemory();
454 case Instruction::Load:
455 return !cast<LoadInst>(this)->isUnordered();
459 bool Instruction::isAtomic() const {
460 switch (getOpcode()) {
463 case Instruction::AtomicCmpXchg:
464 case Instruction::AtomicRMW:
465 case Instruction::Fence:
467 case Instruction::Load:
468 return cast<LoadInst>(this)->getOrdering() != NotAtomic;
469 case Instruction::Store:
470 return cast<StoreInst>(this)->getOrdering() != NotAtomic;
474 bool Instruction::mayThrow() const {
475 if (const CallInst *CI = dyn_cast<CallInst>(this))
476 return !CI->doesNotThrow();
477 if (const auto *CRI = dyn_cast<CleanupReturnInst>(this))
478 return CRI->unwindsToCaller();
479 if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(this))
480 return CEPI->unwindsToCaller();
481 if (const auto *CEPI = dyn_cast<CatchEndPadInst>(this))
482 return CEPI->unwindsToCaller();
483 if (const auto *TPI = dyn_cast<TerminatePadInst>(this))
484 return TPI->unwindsToCaller();
485 return isa<ResumeInst>(this);
488 bool Instruction::mayReturn() const {
489 if (const CallInst *CI = dyn_cast<CallInst>(this))
490 return !CI->doesNotReturn();
494 /// isAssociative - Return true if the instruction is associative:
496 /// Associative operators satisfy: x op (y op z) === (x op y) op z
498 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
500 bool Instruction::isAssociative(unsigned Opcode) {
501 return Opcode == And || Opcode == Or || Opcode == Xor ||
502 Opcode == Add || Opcode == Mul;
505 bool Instruction::isAssociative() const {
506 unsigned Opcode = getOpcode();
507 if (isAssociative(Opcode))
513 return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
519 /// isCommutative - Return true if the instruction is commutative:
521 /// Commutative operators satisfy: (x op y) === (y op x)
523 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
524 /// applied to any type.
526 bool Instruction::isCommutative(unsigned op) {
541 /// isIdempotent - Return true if the instruction is idempotent:
543 /// Idempotent operators satisfy: x op x === x
545 /// In LLVM, the And and Or operators are idempotent.
547 bool Instruction::isIdempotent(unsigned Opcode) {
548 return Opcode == And || Opcode == Or;
551 /// isNilpotent - Return true if the instruction is nilpotent:
553 /// Nilpotent operators satisfy: x op x === Id,
555 /// where Id is the identity for the operator, i.e. a constant such that
556 /// x op Id === x and Id op x === x for all x.
558 /// In LLVM, the Xor operator is nilpotent.
560 bool Instruction::isNilpotent(unsigned Opcode) {
561 return Opcode == Xor;
564 Instruction *Instruction::cloneImpl() const {
565 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
568 Instruction *Instruction::clone() const {
569 Instruction *New = nullptr;
570 switch (getOpcode()) {
572 llvm_unreachable("Unhandled Opcode.");
573 #define HANDLE_INST(num, opc, clas) \
574 case Instruction::opc: \
575 New = cast<clas>(this)->cloneImpl(); \
577 #include "llvm/IR/Instruction.def"
581 New->SubclassOptionalData = SubclassOptionalData;
585 // Otherwise, enumerate and copy over metadata from the old instruction to the
587 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
588 getAllMetadataOtherThanDebugLoc(TheMDs);
589 for (const auto &MD : TheMDs)
590 New->setMetadata(MD.first, MD.second);
592 New->setDebugLoc(getDebugLoc());