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