LLVM  9.0.0svn
Instruction.cpp
Go to the documentation of this file.
1 //===-- Instruction.cpp - Implement the Instruction class -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Instruction class for the IR library.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/Instruction.h"
14 #include "llvm/IR/IntrinsicInst.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/MDBuilder.h"
19 #include "llvm/IR/Operator.h"
20 #include "llvm/IR/Type.h"
21 using namespace llvm;
22 
23 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
24  Instruction *InsertBefore)
25  : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
26 
27  // If requested, insert this instruction into a basic block...
28  if (InsertBefore) {
29  BasicBlock *BB = InsertBefore->getParent();
30  assert(BB && "Instruction to insert before is not in a basic block!");
31  BB->getInstList().insert(InsertBefore->getIterator(), this);
32  }
33 }
34 
35 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
36  BasicBlock *InsertAtEnd)
37  : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
38 
39  // append this instruction into the basic block
40  assert(InsertAtEnd && "Basic block to append to may not be NULL!");
41  InsertAtEnd->getInstList().push_back(this);
42 }
43 
45  assert(!Parent && "Instruction still linked in the program!");
46  if (hasMetadataHashEntry())
47  clearMetadataHashEntries();
48 }
49 
50 
51 void Instruction::setParent(BasicBlock *P) {
52  Parent = P;
53 }
54 
56  return getParent()->getModule();
57 }
58 
60  return getParent()->getParent();
61 }
62 
65 }
66 
68  return getParent()->getInstList().erase(getIterator());
69 }
70 
71 /// Insert an unlinked instruction into a basic block immediately before the
72 /// specified instruction.
74  InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
75 }
76 
77 /// Insert an unlinked instruction into a basic block immediately after the
78 /// specified instruction.
80  InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
81  this);
82 }
83 
84 /// Unlink this instruction from its current basic block and insert it into the
85 /// basic block that MovePos lives in, right before MovePos.
87  moveBefore(*MovePos->getParent(), MovePos->getIterator());
88 }
89 
91  moveBefore(*MovePos->getParent(), ++MovePos->getIterator());
92 }
93 
96  assert(I == BB.end() || I->getParent() == &BB);
97  BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
98 }
99 
101  cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
102 }
103 
105  cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
106 }
107 
109  cast<PossiblyExactOperator>(this)->setIsExact(b);
110 }
111 
113  return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
114 }
115 
117  return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
118 }
119 
121  switch (getOpcode()) {
122  case Instruction::Add:
123  case Instruction::Sub:
124  case Instruction::Mul:
125  case Instruction::Shl:
126  cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
127  cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
128  break;
129 
130  case Instruction::UDiv:
131  case Instruction::SDiv:
132  case Instruction::AShr:
133  case Instruction::LShr:
134  cast<PossiblyExactOperator>(this)->setIsExact(false);
135  break;
136 
137  case Instruction::GetElementPtr:
138  cast<GetElementPtrInst>(this)->setIsInBounds(false);
139  break;
140  }
141 }
142 
143 bool Instruction::isExact() const {
144  return cast<PossiblyExactOperator>(this)->isExact();
145 }
146 
148  assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
149  cast<FPMathOperator>(this)->setFast(B);
150 }
151 
153  assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
154  cast<FPMathOperator>(this)->setHasAllowReassoc(B);
155 }
156 
158  assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
159  cast<FPMathOperator>(this)->setHasNoNaNs(B);
160 }
161 
163  assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
164  cast<FPMathOperator>(this)->setHasNoInfs(B);
165 }
166 
168  assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
169  cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
170 }
171 
173  assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
174  cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
175 }
176 
178  assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
179  cast<FPMathOperator>(this)->setHasApproxFunc(B);
180 }
181 
183  assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
184  cast<FPMathOperator>(this)->setFastMathFlags(FMF);
185 }
186 
188  assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
189  cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
190 }
191 
192 bool Instruction::isFast() const {
193  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
194  return cast<FPMathOperator>(this)->isFast();
195 }
196 
198  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
199  return cast<FPMathOperator>(this)->hasAllowReassoc();
200 }
201 
203  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
204  return cast<FPMathOperator>(this)->hasNoNaNs();
205 }
206 
208  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
209  return cast<FPMathOperator>(this)->hasNoInfs();
210 }
211 
213  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
214  return cast<FPMathOperator>(this)->hasNoSignedZeros();
215 }
216 
218  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
219  return cast<FPMathOperator>(this)->hasAllowReciprocal();
220 }
221 
223  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
224  return cast<FPMathOperator>(this)->hasAllowContract();
225 }
226 
228  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
229  return cast<FPMathOperator>(this)->hasApproxFunc();
230 }
231 
233  assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
234  return cast<FPMathOperator>(this)->getFastMathFlags();
235 }
236 
239 }
240 
241 void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
242  // Copy the wrapping flags.
243  if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
244  if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
245  setHasNoSignedWrap(OB->hasNoSignedWrap());
246  setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
247  }
248  }
249 
250  // Copy the exact flag.
251  if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
252  if (isa<PossiblyExactOperator>(this))
253  setIsExact(PE->isExact());
254 
255  // Copy the fast-math flags.
256  if (auto *FP = dyn_cast<FPMathOperator>(V))
257  if (isa<FPMathOperator>(this))
258  copyFastMathFlags(FP->getFastMathFlags());
259 
260  if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
261  if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
262  DestGEP->setIsInBounds(SrcGEP->isInBounds() | DestGEP->isInBounds());
263 }
264 
266  if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
267  if (isa<OverflowingBinaryOperator>(this)) {
268  setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
269  setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
270  }
271  }
272 
273  if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
274  if (isa<PossiblyExactOperator>(this))
275  setIsExact(isExact() & PE->isExact());
276 
277  if (auto *FP = dyn_cast<FPMathOperator>(V)) {
278  if (isa<FPMathOperator>(this)) {
280  FM &= FP->getFastMathFlags();
281  copyFastMathFlags(FM);
282  }
283  }
284 
285  if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
286  if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
287  DestGEP->setIsInBounds(SrcGEP->isInBounds() & DestGEP->isInBounds());
288 }
289 
290 const char *Instruction::getOpcodeName(unsigned OpCode) {
291  switch (OpCode) {
292  // Terminators
293  case Ret: return "ret";
294  case Br: return "br";
295  case Switch: return "switch";
296  case IndirectBr: return "indirectbr";
297  case Invoke: return "invoke";
298  case Resume: return "resume";
299  case Unreachable: return "unreachable";
300  case CleanupRet: return "cleanupret";
301  case CatchRet: return "catchret";
302  case CatchPad: return "catchpad";
303  case CatchSwitch: return "catchswitch";
304  case CallBr: return "callbr";
305 
306  // Standard unary operators...
307  case FNeg: return "fneg";
308 
309  // Standard binary operators...
310  case Add: return "add";
311  case FAdd: return "fadd";
312  case Sub: return "sub";
313  case FSub: return "fsub";
314  case Mul: return "mul";
315  case FMul: return "fmul";
316  case UDiv: return "udiv";
317  case SDiv: return "sdiv";
318  case FDiv: return "fdiv";
319  case URem: return "urem";
320  case SRem: return "srem";
321  case FRem: return "frem";
322 
323  // Logical operators...
324  case And: return "and";
325  case Or : return "or";
326  case Xor: return "xor";
327 
328  // Memory instructions...
329  case Alloca: return "alloca";
330  case Load: return "load";
331  case Store: return "store";
332  case AtomicCmpXchg: return "cmpxchg";
333  case AtomicRMW: return "atomicrmw";
334  case Fence: return "fence";
335  case GetElementPtr: return "getelementptr";
336 
337  // Convert instructions...
338  case Trunc: return "trunc";
339  case ZExt: return "zext";
340  case SExt: return "sext";
341  case FPTrunc: return "fptrunc";
342  case FPExt: return "fpext";
343  case FPToUI: return "fptoui";
344  case FPToSI: return "fptosi";
345  case UIToFP: return "uitofp";
346  case SIToFP: return "sitofp";
347  case IntToPtr: return "inttoptr";
348  case PtrToInt: return "ptrtoint";
349  case BitCast: return "bitcast";
350  case AddrSpaceCast: return "addrspacecast";
351 
352  // Other instructions...
353  case ICmp: return "icmp";
354  case FCmp: return "fcmp";
355  case PHI: return "phi";
356  case Select: return "select";
357  case Call: return "call";
358  case Shl: return "shl";
359  case LShr: return "lshr";
360  case AShr: return "ashr";
361  case VAArg: return "va_arg";
362  case ExtractElement: return "extractelement";
363  case InsertElement: return "insertelement";
364  case ShuffleVector: return "shufflevector";
365  case ExtractValue: return "extractvalue";
366  case InsertValue: return "insertvalue";
367  case LandingPad: return "landingpad";
368  case CleanupPad: return "cleanuppad";
369 
370  default: return "<Invalid operator> ";
371  }
372 }
373 
374 /// Return true if both instructions have the same special state. This must be
375 /// kept in sync with FunctionComparator::cmpOperations in
376 /// lib/Transforms/IPO/MergeFunctions.cpp.
377 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
378  bool IgnoreAlignment = false) {
379  assert(I1->getOpcode() == I2->getOpcode() &&
380  "Can not compare special state of different instructions");
381 
382  if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
383  return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
384  (AI->getAlignment() == cast<AllocaInst>(I2)->getAlignment() ||
385  IgnoreAlignment);
386  if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
387  return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
388  (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
389  IgnoreAlignment) &&
390  LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
391  LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
392  if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
393  return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
394  (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
395  IgnoreAlignment) &&
396  SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
397  SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
398  if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
399  return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
400  if (const CallInst *CI = dyn_cast<CallInst>(I1))
401  return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
402  CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
403  CI->getAttributes() == cast<CallInst>(I2)->getAttributes() &&
404  CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
405  if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
406  return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
407  CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() &&
408  CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
409  if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
410  return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
411  CI->getAttributes() == cast<CallBrInst>(I2)->getAttributes() &&
412  CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
413  if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
414  return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
415  if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
416  return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
417  if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
418  return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
419  FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
420  if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
421  return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
422  CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
423  CXI->getSuccessOrdering() ==
424  cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
425  CXI->getFailureOrdering() ==
426  cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
427  CXI->getSyncScopeID() ==
428  cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
429  if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
430  return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
431  RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
432  RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
433  RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
434 
435  return true;
436 }
437 
439  return isIdenticalToWhenDefined(I) &&
441 }
442 
444  if (getOpcode() != I->getOpcode() ||
445  getNumOperands() != I->getNumOperands() ||
446  getType() != I->getType())
447  return false;
448 
449  // If both instructions have no operands, they are identical.
450  if (getNumOperands() == 0 && I->getNumOperands() == 0)
451  return haveSameSpecialState(this, I);
452 
453  // We have two instructions of identical opcode and #operands. Check to see
454  // if all operands are the same.
455  if (!std::equal(op_begin(), op_end(), I->op_begin()))
456  return false;
457 
458  if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
459  const PHINode *otherPHI = cast<PHINode>(I);
460  return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
461  otherPHI->block_begin());
462  }
463 
464  return haveSameSpecialState(this, I);
465 }
466 
467 // Keep this in sync with FunctionComparator::cmpOperations in
468 // lib/Transforms/IPO/MergeFunctions.cpp.
470  unsigned flags) const {
471  bool IgnoreAlignment = flags & CompareIgnoringAlignment;
472  bool UseScalarTypes = flags & CompareUsingScalarTypes;
473 
474  if (getOpcode() != I->getOpcode() ||
475  getNumOperands() != I->getNumOperands() ||
476  (UseScalarTypes ?
477  getType()->getScalarType() != I->getType()->getScalarType() :
478  getType() != I->getType()))
479  return false;
480 
481  // We have two instructions of identical opcode and #operands. Check to see
482  // if all operands are the same type
483  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
484  if (UseScalarTypes ?
485  getOperand(i)->getType()->getScalarType() !=
486  I->getOperand(i)->getType()->getScalarType() :
487  getOperand(i)->getType() != I->getOperand(i)->getType())
488  return false;
489 
490  return haveSameSpecialState(this, I, IgnoreAlignment);
491 }
492 
494  for (const Use &U : uses()) {
495  // PHI nodes uses values in the corresponding predecessor block. For other
496  // instructions, just check to see whether the parent of the use matches up.
497  const Instruction *I = cast<Instruction>(U.getUser());
498  const PHINode *PN = dyn_cast<PHINode>(I);
499  if (!PN) {
500  if (I->getParent() != BB)
501  return true;
502  continue;
503  }
504 
505  if (PN->getIncomingBlock(U) != BB)
506  return true;
507  }
508  return false;
509 }
510 
512  switch (getOpcode()) {
513  default: return false;
514  case Instruction::VAArg:
515  case Instruction::Load:
516  case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
517  case Instruction::AtomicCmpXchg:
518  case Instruction::AtomicRMW:
519  case Instruction::CatchPad:
520  case Instruction::CatchRet:
521  return true;
522  case Instruction::Call:
523  case Instruction::Invoke:
524  case Instruction::CallBr:
525  return !cast<CallBase>(this)->doesNotAccessMemory();
526  case Instruction::Store:
527  return !cast<StoreInst>(this)->isUnordered();
528  }
529 }
530 
532  switch (getOpcode()) {
533  default: return false;
534  case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
535  case Instruction::Store:
536  case Instruction::VAArg:
537  case Instruction::AtomicCmpXchg:
538  case Instruction::AtomicRMW:
539  case Instruction::CatchPad:
540  case Instruction::CatchRet:
541  return true;
542  case Instruction::Call:
543  case Instruction::Invoke:
544  case Instruction::CallBr:
545  return !cast<CallBase>(this)->onlyReadsMemory();
546  case Instruction::Load:
547  return !cast<LoadInst>(this)->isUnordered();
548  }
549 }
550 
551 bool Instruction::isAtomic() const {
552  switch (getOpcode()) {
553  default:
554  return false;
555  case Instruction::AtomicCmpXchg:
556  case Instruction::AtomicRMW:
557  case Instruction::Fence:
558  return true;
559  case Instruction::Load:
560  return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
561  case Instruction::Store:
562  return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
563  }
564 }
565 
567  assert(isAtomic());
568  switch (getOpcode()) {
569  default:
570  return false;
571  case Instruction::AtomicCmpXchg:
572  case Instruction::AtomicRMW:
573  case Instruction::Load:
574  return true;
575  }
576 }
577 
579  assert(isAtomic());
580  switch (getOpcode()) {
581  default:
582  return false;
583  case Instruction::AtomicCmpXchg:
584  case Instruction::AtomicRMW:
585  case Instruction::Store:
586  return true;
587  }
588 }
589 
590 bool Instruction::mayThrow() const {
591  if (const CallInst *CI = dyn_cast<CallInst>(this))
592  return !CI->doesNotThrow();
593  if (const auto *CRI = dyn_cast<CleanupReturnInst>(this))
594  return CRI->unwindsToCaller();
595  if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this))
596  return CatchSwitch->unwindsToCaller();
597  return isa<ResumeInst>(this);
598 }
599 
601  return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
602  !this->isTerminator();
603 }
604 
606  auto II = dyn_cast<IntrinsicInst>(this);
607  if (!II)
608  return false;
609  Intrinsic::ID ID = II->getIntrinsicID();
610  return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
611 }
612 
614  for (const Instruction *I = getNextNode(); I; I = I->getNextNode())
615  if (!isa<DbgInfoIntrinsic>(I))
616  return I;
617  return nullptr;
618 }
619 
621  for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode())
622  if (!isa<DbgInfoIntrinsic>(I))
623  return I;
624  return nullptr;
625 }
626 
628  unsigned Opcode = getOpcode();
629  if (isAssociative(Opcode))
630  return true;
631 
632  switch (Opcode) {
633  case FMul:
634  case FAdd:
635  return cast<FPMathOperator>(this)->hasAllowReassoc() &&
636  cast<FPMathOperator>(this)->hasNoSignedZeros();
637  default:
638  return false;
639  }
640 }
641 
643  switch (getOpcode()) {
644 #define HANDLE_TERM_INST(N, OPC, CLASS) \
645  case Instruction::OPC: \
646  return static_cast<const CLASS *>(this)->getNumSuccessors();
647 #include "llvm/IR/Instruction.def"
648  default:
649  break;
650  }
651  llvm_unreachable("not a terminator");
652 }
653 
654 BasicBlock *Instruction::getSuccessor(unsigned idx) const {
655  switch (getOpcode()) {
656 #define HANDLE_TERM_INST(N, OPC, CLASS) \
657  case Instruction::OPC: \
658  return static_cast<const CLASS *>(this)->getSuccessor(idx);
659 #include "llvm/IR/Instruction.def"
660  default:
661  break;
662  }
663  llvm_unreachable("not a terminator");
664 }
665 
666 void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
667  switch (getOpcode()) {
668 #define HANDLE_TERM_INST(N, OPC, CLASS) \
669  case Instruction::OPC: \
670  return static_cast<CLASS *>(this)->setSuccessor(idx, B);
671 #include "llvm/IR/Instruction.def"
672  default:
673  break;
674  }
675  llvm_unreachable("not a terminator");
676 }
677 
679  for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors();
680  Idx != NumSuccessors; ++Idx)
681  if (getSuccessor(Idx) == OldBB)
682  setSuccessor(Idx, NewBB);
683 }
684 
685 Instruction *Instruction::cloneImpl() const {
686  llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
687 }
688 
690  MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
691  if (!ProfileData || ProfileData->getNumOperands() != 3 ||
692  !isa<MDString>(ProfileData->getOperand(0)))
693  return;
694 
695  MDString *MDName = cast<MDString>(ProfileData->getOperand(0));
696  if (MDName->getString() != "branch_weights")
697  return;
698 
699  // The first operand is the name. Fetch them backwards and build a new one.
700  Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
701  ProfileData->getOperand(1)};
703  MDNode::get(ProfileData->getContext(), Ops));
704 }
705 
707  ArrayRef<unsigned> WL) {
708  if (!SrcInst.hasMetadata())
709  return;
710 
711  DenseSet<unsigned> WLS;
712  for (unsigned M : WL)
713  WLS.insert(M);
714 
715  // Otherwise, enumerate and copy over metadata from the old instruction to the
716  // new one.
718  SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
719  for (const auto &MD : TheMDs) {
720  if (WL.empty() || WLS.count(MD.first))
721  setMetadata(MD.first, MD.second);
722  }
723  if (WL.empty() || WLS.count(LLVMContext::MD_dbg))
724  setDebugLoc(SrcInst.getDebugLoc());
725 }
726 
728  Instruction *New = nullptr;
729  switch (getOpcode()) {
730  default:
731  llvm_unreachable("Unhandled Opcode.");
732 #define HANDLE_INST(num, opc, clas) \
733  case Instruction::opc: \
734  New = cast<clas>(this)->cloneImpl(); \
735  break;
736 #include "llvm/IR/Instruction.def"
737 #undef HANDLE_INST
738  }
739 
741  New->copyMetadata(*this);
742  return New;
743 }
744 
746  assert(isa<CallBase>(this) &&
747  "Can only set weights for call like instructions");
748  SmallVector<uint32_t, 1> Weights;
749  Weights.push_back(W);
750  MDBuilder MDB(getContext());
752 }
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
Definition: Instruction.h:257
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
bool hasNoInfs() const
Determine whether the no-infs flag is set.
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction, which must be an operator which supports these flags.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:722
const Instruction * getPrevNonDebugInstruction() const
Return a pointer to the previous non-debug instruction in the same basic block as &#39;this&#39;...
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
iterator_range< use_iterator > uses()
Definition: Value.h:354
bool hasNoSignedZeros() const
Determine whether the no-signed-zeros flag is set.
This instruction extracts a struct member or array element value from an aggregate value...
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
Instruction * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
iterator erase(iterator where)
Definition: ilist.h:265
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
An instruction for ordering other memory operations.
Definition: Instructions.h:454
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:528
bool isSafeToRemove() const
Return true if the instruction can be removed if the result is unused.
void setProfWeight(uint64_t W)
Sets the branch_weights metadata to W for CallInst.
This class represents a function call, abstracting a target machine&#39;s calling convention.
void setHasNoNaNs(bool B)
Set or clear the no-nans flag on this instruction, which must be an operator which supports this flag...
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
bool hasAtomicLoad() const
Return true if this atomic instruction loads from memory.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:720
bool isTerminator() const
Definition: Instruction.h:128
Metadata node.
Definition: Metadata.h:863
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
An instruction for reading from memory.
Definition: Instructions.h:167
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:691
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
op_iterator op_begin()
Definition: User.h:229
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
bool hasAllowContract() const
Determine whether the allow-contract flag is set.
void setHasApproxFunc(bool B)
Set or clear the approximate-math-functions flag on this instruction, which must be an operator which...
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:133
static uint32_t getAlignment(const MCSectionCOFF &Sec)
bool hasAllowReciprocal() const
Determine whether the allow-reciprocal flag is set.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs...
bool hasApproxFunc() const
Determine whether the approximate-math-functions flag is set.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Definition: Instruction.h:224
Check for equivalence ignoring load/store alignment.
Definition: Instruction.h:636
block_iterator block_begin()
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
Check for equivalence treating a type and a vector of that type as equivalent.
Definition: Instruction.h:639
LLVMContext & getContext() const
Definition: Metadata.h:923
void andIRFlags(const Value *V)
Logical &#39;and&#39; of any supported wrapping, exact, and fast-math flags of V and this instruction...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:234
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
An instruction for storing to memory.
Definition: Instructions.h:320
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
Definition: User.h:169
void setFast(bool B)
Set or clear all fast-math-flags on this instruction, which must be an operator which supports this f...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:303
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
StringRef getString() const
Definition: Metadata.cpp:463
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
#define P(N)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:318
bool isIdenticalToWhenDefined(const Instruction *I) const
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags, which may specify conditions under which the instruction&#39;s result is undefined.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:73
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
const char * getOpcodeName() const
Definition: Instruction.h:127
static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2, bool IgnoreAlignment=false)
Return true if both instructions have the same special state.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:187
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:572
bool mayThrow() const
Return true if this instruction may throw an exception.
const Instruction * getNextNonDebugInstruction() const
Return a pointer to the next non-debug instruction in the same basic block as &#39;this&#39;, or nullptr if no such instruction exists.
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
op_iterator op_end()
Definition: User.h:231
bool isLifetimeStartOrEnd() const
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
void splice(iterator where, iplist_impl &L2)
Definition: ilist.h:327
bool isFast() const
Determine whether all fast-math-flags are set.
self_iterator getIterator()
Definition: ilist_node.h:81
void setHasNoInfs(bool B)
Set or clear the no-infs flag on this instruction, which must be an operator which supports this flag...
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:59
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:37
bool isExact() const
Determine whether the exact flag is set.
void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1222
unsigned char SubclassOptionalData
Hold subclass data that can be dropped.
Definition: Value.h:90
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:333
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Definition: PPCPredicates.h:87
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Definition: User.h:191
void setHasAllowReassoc(bool B)
Set or clear the reassociation flag on this instruction, which must be an operator which supports thi...
iterator end()
Definition: BasicBlock.h:270
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
bool isUsedOutsideOfBlock(const BasicBlock *BB) const
Return true if there are any uses of this instruction in blocks other than the specified block...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
void push_back(pointer val)
Definition: ilist.h:311
static bool isWeak(const MCSymbolELF &Sym)
void removeFromParent()
This method unlinks &#39;this&#39; from the containing basic block, but does not delete it.
Definition: Instruction.cpp:63
pointer remove(iterator &IT)
Definition: ilist.h:249
List that automatically updates parent links and symbol tables.
iterator insert(iterator where, pointer New)
Definition: ilist.h:226
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:321
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
Definition: Instruction.cpp:79
#define I(x, y, z)
Definition: MD5.cpp:58
bool mayReadFromMemory() const
Return true if this instruction may read memory.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:91
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
Instruction(const Instruction &)=delete
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
bool hasAtomicStore() const
Return true if this atomic instruction stores to memory.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:90
LLVM Value Representation.
Definition: Value.h:72
bool hasAllowReassoc() const
Determine whether the allow-reassociation flag is set.
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:86
Invoke instruction.
bool hasNoNaNs() const
Determine whether the no-NaNs flag is set.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:159
A single uniqued string.
Definition: Metadata.h:603
static bool isVolatile(Instruction *Inst)
void setHasNoSignedZeros(bool B)
Set or clear the no-signed-zeros flag on this instruction, which must be an operator which supports t...
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1074
iterator insertAfter(iterator where, pointer New)
Definition: ilist.h:235
Root of the metadata hierarchy.
Definition: Metadata.h:57
void setHasAllowReciprocal(bool B)
Set or clear the allow-reciprocal flag on this instruction, which must be an operator which supports ...
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:43
const BasicBlock * getParent() const
Definition: Instruction.h:66
an instruction to allocate memory on the stack
Definition: Instructions.h:59
This instruction inserts a struct field of array element value into an aggregate value.