Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / IR / InstrTypes.h
blob6f506687ee5523e4b611a15bae05d993f3bdf9a1
1 //===- llvm/InstrTypes.h - Important Instruction subclasses -----*- C++ -*-===//
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 defines various meta classes of instructions that exist in the VM
10 // representation. Specific concrete subclasses of these may be found in the
11 // i*.h files...
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_INSTRTYPES_H
16 #define LLVM_IR_INSTRTYPES_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/OperandTraits.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstddef>
42 #include <cstdint>
43 #include <iterator>
44 #include <string>
45 #include <vector>
47 namespace llvm {
49 namespace Intrinsic {
50 enum ID : unsigned;
53 //===----------------------------------------------------------------------===//
54 // UnaryInstruction Class
55 //===----------------------------------------------------------------------===//
57 class UnaryInstruction : public Instruction {
58 protected:
59 UnaryInstruction(Type *Ty, unsigned iType, Value *V,
60 Instruction *IB = nullptr)
61 : Instruction(Ty, iType, &Op<0>(), 1, IB) {
62 Op<0>() = V;
64 UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
65 : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
66 Op<0>() = V;
69 public:
70 // allocate space for exactly one operand
71 void *operator new(size_t s) {
72 return User::operator new(s, 1);
75 /// Transparently provide more efficient getOperand methods.
76 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
78 // Methods for support type inquiry through isa, cast, and dyn_cast:
79 static bool classof(const Instruction *I) {
80 return I->getOpcode() == Instruction::Alloca ||
81 I->getOpcode() == Instruction::Load ||
82 I->getOpcode() == Instruction::VAArg ||
83 I->getOpcode() == Instruction::ExtractValue ||
84 (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
86 static bool classof(const Value *V) {
87 return isa<Instruction>(V) && classof(cast<Instruction>(V));
91 template <>
92 struct OperandTraits<UnaryInstruction> :
93 public FixedNumOperandTraits<UnaryInstruction, 1> {
96 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
98 //===----------------------------------------------------------------------===//
99 // BinaryOperator Class
100 //===----------------------------------------------------------------------===//
102 class BinaryOperator : public Instruction {
103 void AssertOK();
105 protected:
106 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
107 const Twine &Name, Instruction *InsertBefore);
108 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
109 const Twine &Name, BasicBlock *InsertAtEnd);
111 // Note: Instruction needs to be a friend here to call cloneImpl.
112 friend class Instruction;
114 BinaryOperator *cloneImpl() const;
116 public:
117 // allocate space for exactly two operands
118 void *operator new(size_t s) {
119 return User::operator new(s, 2);
122 /// Transparently provide more efficient getOperand methods.
123 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
125 /// Construct a binary instruction, given the opcode and the two
126 /// operands. Optionally (if InstBefore is specified) insert the instruction
127 /// into a BasicBlock right before the specified instruction. The specified
128 /// Instruction is allowed to be a dereferenced end iterator.
130 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
131 const Twine &Name = Twine(),
132 Instruction *InsertBefore = nullptr);
134 /// Construct a binary instruction, given the opcode and the two
135 /// operands. Also automatically insert this instruction to the end of the
136 /// BasicBlock specified.
138 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
139 const Twine &Name, BasicBlock *InsertAtEnd);
141 /// These methods just forward to Create, and are useful when you
142 /// statically know what type of instruction you're going to create. These
143 /// helpers just save some typing.
144 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
145 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
146 const Twine &Name = "") {\
147 return Create(Instruction::OPC, V1, V2, Name);\
149 #include "llvm/IR/Instruction.def"
150 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
151 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
152 const Twine &Name, BasicBlock *BB) {\
153 return Create(Instruction::OPC, V1, V2, Name, BB);\
155 #include "llvm/IR/Instruction.def"
156 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
157 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
158 const Twine &Name, Instruction *I) {\
159 return Create(Instruction::OPC, V1, V2, Name, I);\
161 #include "llvm/IR/Instruction.def"
163 static BinaryOperator *CreateWithCopiedFlags(BinaryOps Opc,
164 Value *V1, Value *V2,
165 BinaryOperator *CopyBO,
166 const Twine &Name = "") {
167 BinaryOperator *BO = Create(Opc, V1, V2, Name);
168 BO->copyIRFlags(CopyBO);
169 return BO;
172 static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2,
173 BinaryOperator *FMFSource,
174 const Twine &Name = "") {
175 return CreateWithCopiedFlags(Instruction::FAdd, V1, V2, FMFSource, Name);
177 static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2,
178 BinaryOperator *FMFSource,
179 const Twine &Name = "") {
180 return CreateWithCopiedFlags(Instruction::FSub, V1, V2, FMFSource, Name);
182 static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2,
183 BinaryOperator *FMFSource,
184 const Twine &Name = "") {
185 return CreateWithCopiedFlags(Instruction::FMul, V1, V2, FMFSource, Name);
187 static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2,
188 BinaryOperator *FMFSource,
189 const Twine &Name = "") {
190 return CreateWithCopiedFlags(Instruction::FDiv, V1, V2, FMFSource, Name);
192 static BinaryOperator *CreateFRemFMF(Value *V1, Value *V2,
193 BinaryOperator *FMFSource,
194 const Twine &Name = "") {
195 return CreateWithCopiedFlags(Instruction::FRem, V1, V2, FMFSource, Name);
197 static BinaryOperator *CreateFNegFMF(Value *Op, BinaryOperator *FMFSource,
198 const Twine &Name = "") {
199 Value *Zero = ConstantFP::getNegativeZero(Op->getType());
200 return CreateWithCopiedFlags(Instruction::FSub, Zero, Op, FMFSource);
203 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
204 const Twine &Name = "") {
205 BinaryOperator *BO = Create(Opc, V1, V2, Name);
206 BO->setHasNoSignedWrap(true);
207 return BO;
209 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
210 const Twine &Name, BasicBlock *BB) {
211 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
212 BO->setHasNoSignedWrap(true);
213 return BO;
215 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
216 const Twine &Name, Instruction *I) {
217 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
218 BO->setHasNoSignedWrap(true);
219 return BO;
222 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
223 const Twine &Name = "") {
224 BinaryOperator *BO = Create(Opc, V1, V2, Name);
225 BO->setHasNoUnsignedWrap(true);
226 return BO;
228 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
229 const Twine &Name, BasicBlock *BB) {
230 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
231 BO->setHasNoUnsignedWrap(true);
232 return BO;
234 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
235 const Twine &Name, Instruction *I) {
236 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
237 BO->setHasNoUnsignedWrap(true);
238 return BO;
241 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
242 const Twine &Name = "") {
243 BinaryOperator *BO = Create(Opc, V1, V2, Name);
244 BO->setIsExact(true);
245 return BO;
247 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
248 const Twine &Name, BasicBlock *BB) {
249 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
250 BO->setIsExact(true);
251 return BO;
253 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
254 const Twine &Name, Instruction *I) {
255 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
256 BO->setIsExact(true);
257 return BO;
260 #define DEFINE_HELPERS(OPC, NUWNSWEXACT) \
261 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \
262 const Twine &Name = "") { \
263 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \
265 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
266 Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \
267 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \
269 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
270 Value *V1, Value *V2, const Twine &Name, Instruction *I) { \
271 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \
274 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
275 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
276 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
277 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
278 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
279 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
280 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
281 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
283 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv
284 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv
285 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr
286 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr
288 #undef DEFINE_HELPERS
290 /// Helper functions to construct and inspect unary operations (NEG and NOT)
291 /// via binary operators SUB and XOR:
293 /// Create the NEG and NOT instructions out of SUB and XOR instructions.
295 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
296 Instruction *InsertBefore = nullptr);
297 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
298 BasicBlock *InsertAtEnd);
299 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
300 Instruction *InsertBefore = nullptr);
301 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
302 BasicBlock *InsertAtEnd);
303 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
304 Instruction *InsertBefore = nullptr);
305 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
306 BasicBlock *InsertAtEnd);
307 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
308 Instruction *InsertBefore = nullptr);
309 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
310 BasicBlock *InsertAtEnd);
311 static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
312 Instruction *InsertBefore = nullptr);
313 static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
314 BasicBlock *InsertAtEnd);
316 BinaryOps getOpcode() const {
317 return static_cast<BinaryOps>(Instruction::getOpcode());
320 /// Exchange the two operands to this instruction.
321 /// This instruction is safe to use on any binary instruction and
322 /// does not modify the semantics of the instruction. If the instruction
323 /// cannot be reversed (ie, it's a Div), then return true.
325 bool swapOperands();
327 // Methods for support type inquiry through isa, cast, and dyn_cast:
328 static bool classof(const Instruction *I) {
329 return I->isBinaryOp();
331 static bool classof(const Value *V) {
332 return isa<Instruction>(V) && classof(cast<Instruction>(V));
336 template <>
337 struct OperandTraits<BinaryOperator> :
338 public FixedNumOperandTraits<BinaryOperator, 2> {
341 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
343 //===----------------------------------------------------------------------===//
344 // CastInst Class
345 //===----------------------------------------------------------------------===//
347 /// This is the base class for all instructions that perform data
348 /// casts. It is simply provided so that instruction category testing
349 /// can be performed with code like:
351 /// if (isa<CastInst>(Instr)) { ... }
352 /// Base class of casting instructions.
353 class CastInst : public UnaryInstruction {
354 protected:
355 /// Constructor with insert-before-instruction semantics for subclasses
356 CastInst(Type *Ty, unsigned iType, Value *S,
357 const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
358 : UnaryInstruction(Ty, iType, S, InsertBefore) {
359 setName(NameStr);
361 /// Constructor with insert-at-end-of-block semantics for subclasses
362 CastInst(Type *Ty, unsigned iType, Value *S,
363 const Twine &NameStr, BasicBlock *InsertAtEnd)
364 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
365 setName(NameStr);
368 public:
369 /// Provides a way to construct any of the CastInst subclasses using an
370 /// opcode instead of the subclass's constructor. The opcode must be in the
371 /// CastOps category (Instruction::isCast(opcode) returns true). This
372 /// constructor has insert-before-instruction semantics to automatically
373 /// insert the new CastInst before InsertBefore (if it is non-null).
374 /// Construct any of the CastInst subclasses
375 static CastInst *Create(
376 Instruction::CastOps, ///< The opcode of the cast instruction
377 Value *S, ///< The value to be casted (operand 0)
378 Type *Ty, ///< The type to which cast should be made
379 const Twine &Name = "", ///< Name for the instruction
380 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
382 /// Provides a way to construct any of the CastInst subclasses using an
383 /// opcode instead of the subclass's constructor. The opcode must be in the
384 /// CastOps category. This constructor has insert-at-end-of-block semantics
385 /// to automatically insert the new CastInst at the end of InsertAtEnd (if
386 /// its non-null).
387 /// Construct any of the CastInst subclasses
388 static CastInst *Create(
389 Instruction::CastOps, ///< The opcode for the cast instruction
390 Value *S, ///< The value to be casted (operand 0)
391 Type *Ty, ///< The type to which operand is casted
392 const Twine &Name, ///< The name for the instruction
393 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
396 /// Create a ZExt or BitCast cast instruction
397 static CastInst *CreateZExtOrBitCast(
398 Value *S, ///< The value to be casted (operand 0)
399 Type *Ty, ///< The type to which cast should be made
400 const Twine &Name = "", ///< Name for the instruction
401 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
404 /// Create a ZExt or BitCast cast instruction
405 static CastInst *CreateZExtOrBitCast(
406 Value *S, ///< The value to be casted (operand 0)
407 Type *Ty, ///< The type to which operand is casted
408 const Twine &Name, ///< The name for the instruction
409 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
412 /// Create a SExt or BitCast cast instruction
413 static CastInst *CreateSExtOrBitCast(
414 Value *S, ///< The value to be casted (operand 0)
415 Type *Ty, ///< The type to which cast should be made
416 const Twine &Name = "", ///< Name for the instruction
417 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
420 /// Create a SExt or BitCast cast instruction
421 static CastInst *CreateSExtOrBitCast(
422 Value *S, ///< The value to be casted (operand 0)
423 Type *Ty, ///< The type to which operand is casted
424 const Twine &Name, ///< The name for the instruction
425 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
428 /// Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
429 static CastInst *CreatePointerCast(
430 Value *S, ///< The pointer value to be casted (operand 0)
431 Type *Ty, ///< The type to which operand is casted
432 const Twine &Name, ///< The name for the instruction
433 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
436 /// Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
437 static CastInst *CreatePointerCast(
438 Value *S, ///< The pointer value to be casted (operand 0)
439 Type *Ty, ///< The type to which cast should be made
440 const Twine &Name = "", ///< Name for the instruction
441 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
444 /// Create a BitCast or an AddrSpaceCast cast instruction.
445 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
446 Value *S, ///< The pointer value to be casted (operand 0)
447 Type *Ty, ///< The type to which operand is casted
448 const Twine &Name, ///< The name for the instruction
449 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
452 /// Create a BitCast or an AddrSpaceCast cast instruction.
453 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
454 Value *S, ///< The pointer value to be casted (operand 0)
455 Type *Ty, ///< The type to which cast should be made
456 const Twine &Name = "", ///< Name for the instruction
457 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
460 /// Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
462 /// If the value is a pointer type and the destination an integer type,
463 /// creates a PtrToInt cast. If the value is an integer type and the
464 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
465 /// a bitcast.
466 static CastInst *CreateBitOrPointerCast(
467 Value *S, ///< The pointer value to be casted (operand 0)
468 Type *Ty, ///< The type to which cast should be made
469 const Twine &Name = "", ///< Name for the instruction
470 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
473 /// Create a ZExt, BitCast, or Trunc for int -> int casts.
474 static CastInst *CreateIntegerCast(
475 Value *S, ///< The pointer value to be casted (operand 0)
476 Type *Ty, ///< The type to which cast should be made
477 bool isSigned, ///< Whether to regard S as signed or not
478 const Twine &Name = "", ///< Name for the instruction
479 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
482 /// Create a ZExt, BitCast, or Trunc for int -> int casts.
483 static CastInst *CreateIntegerCast(
484 Value *S, ///< The integer value to be casted (operand 0)
485 Type *Ty, ///< The integer type to which operand is casted
486 bool isSigned, ///< Whether to regard S as signed or not
487 const Twine &Name, ///< The name for the instruction
488 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
491 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
492 static CastInst *CreateFPCast(
493 Value *S, ///< The floating point value to be casted
494 Type *Ty, ///< The floating point type to cast to
495 const Twine &Name = "", ///< Name for the instruction
496 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
499 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
500 static CastInst *CreateFPCast(
501 Value *S, ///< The floating point value to be casted
502 Type *Ty, ///< The floating point type to cast to
503 const Twine &Name, ///< The name for the instruction
504 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
507 /// Create a Trunc or BitCast cast instruction
508 static CastInst *CreateTruncOrBitCast(
509 Value *S, ///< The value to be casted (operand 0)
510 Type *Ty, ///< The type to which cast should be made
511 const Twine &Name = "", ///< Name for the instruction
512 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
515 /// Create a Trunc or BitCast cast instruction
516 static CastInst *CreateTruncOrBitCast(
517 Value *S, ///< The value to be casted (operand 0)
518 Type *Ty, ///< The type to which operand is casted
519 const Twine &Name, ///< The name for the instruction
520 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
523 /// Check whether it is valid to call getCastOpcode for these types.
524 static bool isCastable(
525 Type *SrcTy, ///< The Type from which the value should be cast.
526 Type *DestTy ///< The Type to which the value should be cast.
529 /// Check whether a bitcast between these types is valid
530 static bool isBitCastable(
531 Type *SrcTy, ///< The Type from which the value should be cast.
532 Type *DestTy ///< The Type to which the value should be cast.
535 /// Check whether a bitcast, inttoptr, or ptrtoint cast between these
536 /// types is valid and a no-op.
538 /// This ensures that any pointer<->integer cast has enough bits in the
539 /// integer and any other cast is a bitcast.
540 static bool isBitOrNoopPointerCastable(
541 Type *SrcTy, ///< The Type from which the value should be cast.
542 Type *DestTy, ///< The Type to which the value should be cast.
543 const DataLayout &DL);
545 /// Returns the opcode necessary to cast Val into Ty using usual casting
546 /// rules.
547 /// Infer the opcode for cast operand and type
548 static Instruction::CastOps getCastOpcode(
549 const Value *Val, ///< The value to cast
550 bool SrcIsSigned, ///< Whether to treat the source as signed
551 Type *Ty, ///< The Type to which the value should be casted
552 bool DstIsSigned ///< Whether to treate the dest. as signed
555 /// There are several places where we need to know if a cast instruction
556 /// only deals with integer source and destination types. To simplify that
557 /// logic, this method is provided.
558 /// @returns true iff the cast has only integral typed operand and dest type.
559 /// Determine if this is an integer-only cast.
560 bool isIntegerCast() const;
562 /// A lossless cast is one that does not alter the basic value. It implies
563 /// a no-op cast but is more stringent, preventing things like int->float,
564 /// long->double, or int->ptr.
565 /// @returns true iff the cast is lossless.
566 /// Determine if this is a lossless cast.
567 bool isLosslessCast() const;
569 /// A no-op cast is one that can be effected without changing any bits.
570 /// It implies that the source and destination types are the same size. The
571 /// DataLayout argument is to determine the pointer size when examining casts
572 /// involving Integer and Pointer types. They are no-op casts if the integer
573 /// is the same size as the pointer. However, pointer size varies with
574 /// platform.
575 /// Determine if the described cast is a no-op cast.
576 static bool isNoopCast(
577 Instruction::CastOps Opcode, ///< Opcode of cast
578 Type *SrcTy, ///< SrcTy of cast
579 Type *DstTy, ///< DstTy of cast
580 const DataLayout &DL ///< DataLayout to get the Int Ptr type from.
583 /// Determine if this cast is a no-op cast.
585 /// \param DL is the DataLayout to determine pointer size.
586 bool isNoopCast(const DataLayout &DL) const;
588 /// Determine how a pair of casts can be eliminated, if they can be at all.
589 /// This is a helper function for both CastInst and ConstantExpr.
590 /// @returns 0 if the CastInst pair can't be eliminated, otherwise
591 /// returns Instruction::CastOps value for a cast that can replace
592 /// the pair, casting SrcTy to DstTy.
593 /// Determine if a cast pair is eliminable
594 static unsigned isEliminableCastPair(
595 Instruction::CastOps firstOpcode, ///< Opcode of first cast
596 Instruction::CastOps secondOpcode, ///< Opcode of second cast
597 Type *SrcTy, ///< SrcTy of 1st cast
598 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
599 Type *DstTy, ///< DstTy of 2nd cast
600 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
601 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
602 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null
605 /// Return the opcode of this CastInst
606 Instruction::CastOps getOpcode() const {
607 return Instruction::CastOps(Instruction::getOpcode());
610 /// Return the source type, as a convenience
611 Type* getSrcTy() const { return getOperand(0)->getType(); }
612 /// Return the destination type, as a convenience
613 Type* getDestTy() const { return getType(); }
615 /// This method can be used to determine if a cast from S to DstTy using
616 /// Opcode op is valid or not.
617 /// @returns true iff the proposed cast is valid.
618 /// Determine if a cast is valid without creating one.
619 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
621 /// Methods for support type inquiry through isa, cast, and dyn_cast:
622 static bool classof(const Instruction *I) {
623 return I->isCast();
625 static bool classof(const Value *V) {
626 return isa<Instruction>(V) && classof(cast<Instruction>(V));
630 //===----------------------------------------------------------------------===//
631 // CmpInst Class
632 //===----------------------------------------------------------------------===//
634 /// This class is the base class for the comparison instructions.
635 /// Abstract base class of comparison instructions.
636 class CmpInst : public Instruction {
637 public:
638 /// This enumeration lists the possible predicates for CmpInst subclasses.
639 /// Values in the range 0-31 are reserved for FCmpInst, while values in the
640 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
641 /// predicate values are not overlapping between the classes.
643 /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
644 /// FCMP_* values. Changing the bit patterns requires a potential change to
645 /// those passes.
646 enum Predicate {
647 // Opcode U L G E Intuitive operation
648 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
649 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
650 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
651 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
652 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
653 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
654 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
655 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
656 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
657 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
658 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
659 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
660 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
661 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
662 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
663 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
664 FIRST_FCMP_PREDICATE = FCMP_FALSE,
665 LAST_FCMP_PREDICATE = FCMP_TRUE,
666 BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
667 ICMP_EQ = 32, ///< equal
668 ICMP_NE = 33, ///< not equal
669 ICMP_UGT = 34, ///< unsigned greater than
670 ICMP_UGE = 35, ///< unsigned greater or equal
671 ICMP_ULT = 36, ///< unsigned less than
672 ICMP_ULE = 37, ///< unsigned less or equal
673 ICMP_SGT = 38, ///< signed greater than
674 ICMP_SGE = 39, ///< signed greater or equal
675 ICMP_SLT = 40, ///< signed less than
676 ICMP_SLE = 41, ///< signed less or equal
677 FIRST_ICMP_PREDICATE = ICMP_EQ,
678 LAST_ICMP_PREDICATE = ICMP_SLE,
679 BAD_ICMP_PREDICATE = ICMP_SLE + 1
682 protected:
683 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
684 Value *LHS, Value *RHS, const Twine &Name = "",
685 Instruction *InsertBefore = nullptr,
686 Instruction *FlagsSource = nullptr);
688 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
689 Value *LHS, Value *RHS, const Twine &Name,
690 BasicBlock *InsertAtEnd);
692 public:
693 // allocate space for exactly two operands
694 void *operator new(size_t s) {
695 return User::operator new(s, 2);
698 /// Construct a compare instruction, given the opcode, the predicate and
699 /// the two operands. Optionally (if InstBefore is specified) insert the
700 /// instruction into a BasicBlock right before the specified instruction.
701 /// The specified Instruction is allowed to be a dereferenced end iterator.
702 /// Create a CmpInst
703 static CmpInst *Create(OtherOps Op,
704 Predicate predicate, Value *S1,
705 Value *S2, const Twine &Name = "",
706 Instruction *InsertBefore = nullptr);
708 /// Construct a compare instruction, given the opcode, the predicate and the
709 /// two operands. Also automatically insert this instruction to the end of
710 /// the BasicBlock specified.
711 /// Create a CmpInst
712 static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1,
713 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
715 /// Get the opcode casted to the right type
716 OtherOps getOpcode() const {
717 return static_cast<OtherOps>(Instruction::getOpcode());
720 /// Return the predicate for this instruction.
721 Predicate getPredicate() const {
722 return Predicate(getSubclassDataFromInstruction());
725 /// Set the predicate for this instruction to the specified value.
726 void setPredicate(Predicate P) { setInstructionSubclassData(P); }
728 static bool isFPPredicate(Predicate P) {
729 return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
732 static bool isIntPredicate(Predicate P) {
733 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
736 static StringRef getPredicateName(Predicate P);
738 bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
739 bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
741 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
742 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
743 /// @returns the inverse predicate for the instruction's current predicate.
744 /// Return the inverse of the instruction's predicate.
745 Predicate getInversePredicate() const {
746 return getInversePredicate(getPredicate());
749 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
750 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
751 /// @returns the inverse predicate for predicate provided in \p pred.
752 /// Return the inverse of a given predicate
753 static Predicate getInversePredicate(Predicate pred);
755 /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
756 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
757 /// @returns the predicate that would be the result of exchanging the two
758 /// operands of the CmpInst instruction without changing the result
759 /// produced.
760 /// Return the predicate as if the operands were swapped
761 Predicate getSwappedPredicate() const {
762 return getSwappedPredicate(getPredicate());
765 /// This is a static version that you can use without an instruction
766 /// available.
767 /// Return the predicate as if the operands were swapped.
768 static Predicate getSwappedPredicate(Predicate pred);
770 /// For predicate of kind "is X or equal to 0" returns the predicate "is X".
771 /// For predicate of kind "is X" returns the predicate "is X or equal to 0".
772 /// does not support other kind of predicates.
773 /// @returns the predicate that does not contains is equal to zero if
774 /// it had and vice versa.
775 /// Return the flipped strictness of predicate
776 Predicate getFlippedStrictnessPredicate() const {
777 return getFlippedStrictnessPredicate(getPredicate());
780 /// This is a static version that you can use without an instruction
781 /// available.
782 /// Return the flipped strictness of predicate
783 static Predicate getFlippedStrictnessPredicate(Predicate pred);
785 /// For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
786 /// Returns the non-strict version of strict comparisons.
787 Predicate getNonStrictPredicate() const {
788 return getNonStrictPredicate(getPredicate());
791 /// This is a static version that you can use without an instruction
792 /// available.
793 /// @returns the non-strict version of comparison provided in \p pred.
794 /// If \p pred is not a strict comparison predicate, returns \p pred.
795 /// Returns the non-strict version of strict comparisons.
796 static Predicate getNonStrictPredicate(Predicate pred);
798 /// Provide more efficient getOperand methods.
799 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
801 /// This is just a convenience that dispatches to the subclasses.
802 /// Swap the operands and adjust predicate accordingly to retain
803 /// the same comparison.
804 void swapOperands();
806 /// This is just a convenience that dispatches to the subclasses.
807 /// Determine if this CmpInst is commutative.
808 bool isCommutative() const;
810 /// This is just a convenience that dispatches to the subclasses.
811 /// Determine if this is an equals/not equals predicate.
812 bool isEquality() const;
814 /// @returns true if the comparison is signed, false otherwise.
815 /// Determine if this instruction is using a signed comparison.
816 bool isSigned() const {
817 return isSigned(getPredicate());
820 /// @returns true if the comparison is unsigned, false otherwise.
821 /// Determine if this instruction is using an unsigned comparison.
822 bool isUnsigned() const {
823 return isUnsigned(getPredicate());
826 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
827 /// @returns the signed version of the unsigned predicate pred.
828 /// return the signed version of a predicate
829 static Predicate getSignedPredicate(Predicate pred);
831 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
832 /// @returns the signed version of the predicate for this instruction (which
833 /// has to be an unsigned predicate).
834 /// return the signed version of a predicate
835 Predicate getSignedPredicate() {
836 return getSignedPredicate(getPredicate());
839 /// This is just a convenience.
840 /// Determine if this is true when both operands are the same.
841 bool isTrueWhenEqual() const {
842 return isTrueWhenEqual(getPredicate());
845 /// This is just a convenience.
846 /// Determine if this is false when both operands are the same.
847 bool isFalseWhenEqual() const {
848 return isFalseWhenEqual(getPredicate());
851 /// @returns true if the predicate is unsigned, false otherwise.
852 /// Determine if the predicate is an unsigned operation.
853 static bool isUnsigned(Predicate predicate);
855 /// @returns true if the predicate is signed, false otherwise.
856 /// Determine if the predicate is an signed operation.
857 static bool isSigned(Predicate predicate);
859 /// Determine if the predicate is an ordered operation.
860 static bool isOrdered(Predicate predicate);
862 /// Determine if the predicate is an unordered operation.
863 static bool isUnordered(Predicate predicate);
865 /// Determine if the predicate is true when comparing a value with itself.
866 static bool isTrueWhenEqual(Predicate predicate);
868 /// Determine if the predicate is false when comparing a value with itself.
869 static bool isFalseWhenEqual(Predicate predicate);
871 /// Determine if Pred1 implies Pred2 is true when two compares have matching
872 /// operands.
873 static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2);
875 /// Determine if Pred1 implies Pred2 is false when two compares have matching
876 /// operands.
877 static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2);
879 /// Methods for support type inquiry through isa, cast, and dyn_cast:
880 static bool classof(const Instruction *I) {
881 return I->getOpcode() == Instruction::ICmp ||
882 I->getOpcode() == Instruction::FCmp;
884 static bool classof(const Value *V) {
885 return isa<Instruction>(V) && classof(cast<Instruction>(V));
888 /// Create a result type for fcmp/icmp
889 static Type* makeCmpResultType(Type* opnd_type) {
890 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
891 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
892 vt->getNumElements());
894 return Type::getInt1Ty(opnd_type->getContext());
897 private:
898 // Shadow Value::setValueSubclassData with a private forwarding method so that
899 // subclasses cannot accidentally use it.
900 void setValueSubclassData(unsigned short D) {
901 Value::setValueSubclassData(D);
905 // FIXME: these are redundant if CmpInst < BinaryOperator
906 template <>
907 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
910 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
912 /// A lightweight accessor for an operand bundle meant to be passed
913 /// around by value.
914 struct OperandBundleUse {
915 ArrayRef<Use> Inputs;
917 OperandBundleUse() = default;
918 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
919 : Inputs(Inputs), Tag(Tag) {}
921 /// Return true if the operand at index \p Idx in this operand bundle
922 /// has the attribute A.
923 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
924 if (isDeoptOperandBundle())
925 if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
926 return Inputs[Idx]->getType()->isPointerTy();
928 // Conservative answer: no operands have any attributes.
929 return false;
932 /// Return the tag of this operand bundle as a string.
933 StringRef getTagName() const {
934 return Tag->getKey();
937 /// Return the tag of this operand bundle as an integer.
939 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
940 /// and this function returns the unique integer getOrInsertBundleTag
941 /// associated the tag of this operand bundle to.
942 uint32_t getTagID() const {
943 return Tag->getValue();
946 /// Return true if this is a "deopt" operand bundle.
947 bool isDeoptOperandBundle() const {
948 return getTagID() == LLVMContext::OB_deopt;
951 /// Return true if this is a "funclet" operand bundle.
952 bool isFuncletOperandBundle() const {
953 return getTagID() == LLVMContext::OB_funclet;
956 private:
957 /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
958 StringMapEntry<uint32_t> *Tag;
961 /// A container for an operand bundle being viewed as a set of values
962 /// rather than a set of uses.
964 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
965 /// so it is possible to create and pass around "self-contained" instances of
966 /// OperandBundleDef and ConstOperandBundleDef.
967 template <typename InputTy> class OperandBundleDefT {
968 std::string Tag;
969 std::vector<InputTy> Inputs;
971 public:
972 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
973 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
974 explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
975 : Tag(std::move(Tag)), Inputs(Inputs) {}
977 explicit OperandBundleDefT(const OperandBundleUse &OBU) {
978 Tag = OBU.getTagName();
979 Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
982 ArrayRef<InputTy> inputs() const { return Inputs; }
984 using input_iterator = typename std::vector<InputTy>::const_iterator;
986 size_t input_size() const { return Inputs.size(); }
987 input_iterator input_begin() const { return Inputs.begin(); }
988 input_iterator input_end() const { return Inputs.end(); }
990 StringRef getTag() const { return Tag; }
993 using OperandBundleDef = OperandBundleDefT<Value *>;
994 using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
996 //===----------------------------------------------------------------------===//
997 // CallBase Class
998 //===----------------------------------------------------------------------===//
1000 /// Base class for all callable instructions (InvokeInst and CallInst)
1001 /// Holds everything related to calling a function.
1003 /// All call-like instructions are required to use a common operand layout:
1004 /// - Zero or more arguments to the call,
1005 /// - Zero or more operand bundles with zero or more operand inputs each
1006 /// bundle,
1007 /// - Zero or more subclass controlled operands
1008 /// - The called function.
1010 /// This allows this base class to easily access the called function and the
1011 /// start of the arguments without knowing how many other operands a particular
1012 /// subclass requires. Note that accessing the end of the argument list isn't
1013 /// as cheap as most other operations on the base class.
1014 class CallBase : public Instruction {
1015 protected:
1016 /// The last operand is the called operand.
1017 static constexpr int CalledOperandOpEndIdx = -1;
1019 AttributeList Attrs; ///< parameter attributes for callable
1020 FunctionType *FTy;
1022 template <class... ArgsTy>
1023 CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
1024 : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {}
1026 using Instruction::Instruction;
1028 bool hasDescriptor() const { return Value::HasDescriptor; }
1030 unsigned getNumSubclassExtraOperands() const {
1031 switch (getOpcode()) {
1032 case Instruction::Call:
1033 return 0;
1034 case Instruction::Invoke:
1035 return 2;
1036 case Instruction::CallBr:
1037 return getNumSubclassExtraOperandsDynamic();
1039 llvm_unreachable("Invalid opcode!");
1042 /// Get the number of extra operands for instructions that don't have a fixed
1043 /// number of extra operands.
1044 unsigned getNumSubclassExtraOperandsDynamic() const;
1046 public:
1047 using Instruction::getContext;
1049 static bool classof(const Instruction *I) {
1050 return I->getOpcode() == Instruction::Call ||
1051 I->getOpcode() == Instruction::Invoke ||
1052 I->getOpcode() == Instruction::CallBr;
1054 static bool classof(const Value *V) {
1055 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1058 FunctionType *getFunctionType() const { return FTy; }
1060 void mutateFunctionType(FunctionType *FTy) {
1061 Value::mutateType(FTy->getReturnType());
1062 this->FTy = FTy;
1065 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1067 /// data_operands_begin/data_operands_end - Return iterators iterating over
1068 /// the call / invoke argument list and bundle operands. For invokes, this is
1069 /// the set of instruction operands except the invoke target and the two
1070 /// successor blocks; and for calls this is the set of instruction operands
1071 /// except the call target.
1072 User::op_iterator data_operands_begin() { return op_begin(); }
1073 User::const_op_iterator data_operands_begin() const {
1074 return const_cast<CallBase *>(this)->data_operands_begin();
1076 User::op_iterator data_operands_end() {
1077 // Walk from the end of the operands over the called operand and any
1078 // subclass operands.
1079 return op_end() - getNumSubclassExtraOperands() - 1;
1081 User::const_op_iterator data_operands_end() const {
1082 return const_cast<CallBase *>(this)->data_operands_end();
1084 iterator_range<User::op_iterator> data_ops() {
1085 return make_range(data_operands_begin(), data_operands_end());
1087 iterator_range<User::const_op_iterator> data_ops() const {
1088 return make_range(data_operands_begin(), data_operands_end());
1090 bool data_operands_empty() const {
1091 return data_operands_end() == data_operands_begin();
1093 unsigned data_operands_size() const {
1094 return std::distance(data_operands_begin(), data_operands_end());
1097 bool isDataOperand(const Use *U) const {
1098 assert(this == U->getUser() &&
1099 "Only valid to query with a use of this instruction!");
1100 return data_operands_begin() <= U && U < data_operands_end();
1102 bool isDataOperand(Value::const_user_iterator UI) const {
1103 return isDataOperand(&UI.getUse());
1106 /// Given a value use iterator, return the data operand corresponding to it.
1107 /// Iterator must actually correspond to a data operand.
1108 unsigned getDataOperandNo(Value::const_user_iterator UI) const {
1109 return getDataOperandNo(&UI.getUse());
1112 /// Given a use for a data operand, get the data operand number that
1113 /// corresponds to it.
1114 unsigned getDataOperandNo(const Use *U) const {
1115 assert(isDataOperand(U) && "Data operand # out of range!");
1116 return U - data_operands_begin();
1119 /// Return the iterator pointing to the beginning of the argument list.
1120 User::op_iterator arg_begin() { return op_begin(); }
1121 User::const_op_iterator arg_begin() const {
1122 return const_cast<CallBase *>(this)->arg_begin();
1125 /// Return the iterator pointing to the end of the argument list.
1126 User::op_iterator arg_end() {
1127 // From the end of the data operands, walk backwards past the bundle
1128 // operands.
1129 return data_operands_end() - getNumTotalBundleOperands();
1131 User::const_op_iterator arg_end() const {
1132 return const_cast<CallBase *>(this)->arg_end();
1135 /// Iteration adapter for range-for loops.
1136 iterator_range<User::op_iterator> args() {
1137 return make_range(arg_begin(), arg_end());
1139 iterator_range<User::const_op_iterator> args() const {
1140 return make_range(arg_begin(), arg_end());
1142 bool arg_empty() const { return arg_end() == arg_begin(); }
1143 unsigned arg_size() const { return arg_end() - arg_begin(); }
1145 // Legacy API names that duplicate the above and will be removed once users
1146 // are migrated.
1147 iterator_range<User::op_iterator> arg_operands() {
1148 return make_range(arg_begin(), arg_end());
1150 iterator_range<User::const_op_iterator> arg_operands() const {
1151 return make_range(arg_begin(), arg_end());
1153 unsigned getNumArgOperands() const { return arg_size(); }
1155 Value *getArgOperand(unsigned i) const {
1156 assert(i < getNumArgOperands() && "Out of bounds!");
1157 return getOperand(i);
1160 void setArgOperand(unsigned i, Value *v) {
1161 assert(i < getNumArgOperands() && "Out of bounds!");
1162 setOperand(i, v);
1165 /// Wrappers for getting the \c Use of a call argument.
1166 const Use &getArgOperandUse(unsigned i) const {
1167 assert(i < getNumArgOperands() && "Out of bounds!");
1168 return User::getOperandUse(i);
1170 Use &getArgOperandUse(unsigned i) {
1171 assert(i < getNumArgOperands() && "Out of bounds!");
1172 return User::getOperandUse(i);
1175 bool isArgOperand(const Use *U) const {
1176 assert(this == U->getUser() &&
1177 "Only valid to query with a use of this instruction!");
1178 return arg_begin() <= U && U < arg_end();
1180 bool isArgOperand(Value::const_user_iterator UI) const {
1181 return isArgOperand(&UI.getUse());
1184 /// Returns true if this CallSite passes the given Value* as an argument to
1185 /// the called function.
1186 bool hasArgument(const Value *V) const {
1187 return llvm::any_of(args(), [V](const Value *Arg) { return Arg == V; });
1190 Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); }
1192 // DEPRECATED: This routine will be removed in favor of `getCalledOperand` in
1193 // the near future.
1194 Value *getCalledValue() const { return getCalledOperand(); }
1196 const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); }
1197 Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); }
1199 /// Returns the function called, or null if this is an
1200 /// indirect function invocation.
1201 Function *getCalledFunction() const {
1202 return dyn_cast_or_null<Function>(getCalledOperand());
1205 /// Return true if the callsite is an indirect call.
1206 bool isIndirectCall() const;
1208 /// Determine whether the passed iterator points to the callee operand's Use.
1209 bool isCallee(Value::const_user_iterator UI) const {
1210 return isCallee(&UI.getUse());
1213 /// Determine whether this Use is the callee operand's Use.
1214 bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; }
1216 /// Helper to get the caller (the parent function).
1217 Function *getCaller();
1218 const Function *getCaller() const {
1219 return const_cast<CallBase *>(this)->getCaller();
1222 /// Tests if this call site must be tail call optimized. Only a CallInst can
1223 /// be tail call optimized.
1224 bool isMustTailCall() const;
1226 /// Tests if this call site is marked as a tail call.
1227 bool isTailCall() const;
1229 /// Returns the intrinsic ID of the intrinsic called or
1230 /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if
1231 /// this is an indirect call.
1232 Intrinsic::ID getIntrinsicID() const;
1234 void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; }
1236 /// Sets the function called, including updating the function type.
1237 void setCalledFunction(Function *Fn) {
1238 setCalledFunction(Fn->getFunctionType(), Fn);
1241 /// Sets the function called, including updating the function type.
1242 void setCalledFunction(FunctionCallee Fn) {
1243 setCalledFunction(Fn.getFunctionType(), Fn.getCallee());
1246 /// Sets the function called, including updating to the specified function
1247 /// type.
1248 void setCalledFunction(FunctionType *FTy, Value *Fn) {
1249 this->FTy = FTy;
1250 assert(FTy == cast<FunctionType>(
1251 cast<PointerType>(Fn->getType())->getElementType()));
1252 // This function doesn't mutate the return type, only the function
1253 // type. Seems broken, but I'm just gonna stick an assert in for now.
1254 assert(getType() == FTy->getReturnType());
1255 setCalledOperand(Fn);
1258 CallingConv::ID getCallingConv() const {
1259 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1262 void setCallingConv(CallingConv::ID CC) {
1263 auto ID = static_cast<unsigned>(CC);
1264 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1265 setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1266 (ID << 2));
1269 /// Check if this call is an inline asm statement.
1270 bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); }
1272 /// \name Attribute API
1274 /// These methods access and modify attributes on this call (including
1275 /// looking through to the attributes on the called function when necessary).
1276 ///@{
1278 /// Return the parameter attributes for this call.
1280 AttributeList getAttributes() const { return Attrs; }
1282 /// Set the parameter attributes for this call.
1284 void setAttributes(AttributeList A) { Attrs = A; }
1286 /// Determine whether this call has the given attribute.
1287 bool hasFnAttr(Attribute::AttrKind Kind) const {
1288 assert(Kind != Attribute::NoBuiltin &&
1289 "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin");
1290 return hasFnAttrImpl(Kind);
1293 /// Determine whether this call has the given attribute.
1294 bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); }
1296 /// adds the attribute to the list of attributes.
1297 void addAttribute(unsigned i, Attribute::AttrKind Kind) {
1298 AttributeList PAL = getAttributes();
1299 PAL = PAL.addAttribute(getContext(), i, Kind);
1300 setAttributes(PAL);
1303 /// adds the attribute to the list of attributes.
1304 void addAttribute(unsigned i, Attribute Attr) {
1305 AttributeList PAL = getAttributes();
1306 PAL = PAL.addAttribute(getContext(), i, Attr);
1307 setAttributes(PAL);
1310 /// Adds the attribute to the indicated argument
1311 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1312 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1313 AttributeList PAL = getAttributes();
1314 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
1315 setAttributes(PAL);
1318 /// Adds the attribute to the indicated argument
1319 void addParamAttr(unsigned ArgNo, Attribute Attr) {
1320 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1321 AttributeList PAL = getAttributes();
1322 PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
1323 setAttributes(PAL);
1326 /// removes the attribute from the list of attributes.
1327 void removeAttribute(unsigned i, Attribute::AttrKind Kind) {
1328 AttributeList PAL = getAttributes();
1329 PAL = PAL.removeAttribute(getContext(), i, Kind);
1330 setAttributes(PAL);
1333 /// removes the attribute from the list of attributes.
1334 void removeAttribute(unsigned i, StringRef Kind) {
1335 AttributeList PAL = getAttributes();
1336 PAL = PAL.removeAttribute(getContext(), i, Kind);
1337 setAttributes(PAL);
1340 /// Removes the attribute from the given argument
1341 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1342 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1343 AttributeList PAL = getAttributes();
1344 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1345 setAttributes(PAL);
1348 /// Removes the attribute from the given argument
1349 void removeParamAttr(unsigned ArgNo, StringRef Kind) {
1350 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1351 AttributeList PAL = getAttributes();
1352 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1353 setAttributes(PAL);
1356 /// adds the dereferenceable attribute to the list of attributes.
1357 void addDereferenceableAttr(unsigned i, uint64_t Bytes) {
1358 AttributeList PAL = getAttributes();
1359 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
1360 setAttributes(PAL);
1363 /// adds the dereferenceable_or_null attribute to the list of
1364 /// attributes.
1365 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
1366 AttributeList PAL = getAttributes();
1367 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
1368 setAttributes(PAL);
1371 /// Determine whether the return value has the given attribute.
1372 bool hasRetAttr(Attribute::AttrKind Kind) const;
1374 /// Determine whether the argument or parameter has the given attribute.
1375 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1377 /// Get the attribute of a given kind at a position.
1378 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1379 return getAttributes().getAttribute(i, Kind);
1382 /// Get the attribute of a given kind at a position.
1383 Attribute getAttribute(unsigned i, StringRef Kind) const {
1384 return getAttributes().getAttribute(i, Kind);
1387 /// Get the attribute of a given kind from a given arg
1388 Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1389 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1390 return getAttributes().getParamAttr(ArgNo, Kind);
1393 /// Get the attribute of a given kind from a given arg
1394 Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1395 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1396 return getAttributes().getParamAttr(ArgNo, Kind);
1399 /// Return true if the data operand at index \p i has the attribute \p
1400 /// A.
1402 /// Data operands include call arguments and values used in operand bundles,
1403 /// but does not include the callee operand. This routine dispatches to the
1404 /// underlying AttributeList or the OperandBundleUser as appropriate.
1406 /// The index \p i is interpreted as
1408 /// \p i == Attribute::ReturnIndex -> the return value
1409 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
1410 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1411 /// (\p i - 1) in the operand list.
1412 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
1413 // Note that we have to add one because `i` isn't zero-indexed.
1414 assert(i < (getNumArgOperands() + getNumTotalBundleOperands() + 1) &&
1415 "Data operand index out of bounds!");
1417 // The attribute A can either be directly specified, if the operand in
1418 // question is a call argument; or be indirectly implied by the kind of its
1419 // containing operand bundle, if the operand is a bundle operand.
1421 if (i == AttributeList::ReturnIndex)
1422 return hasRetAttr(Kind);
1424 // FIXME: Avoid these i - 1 calculations and update the API to use
1425 // zero-based indices.
1426 if (i < (getNumArgOperands() + 1))
1427 return paramHasAttr(i - 1, Kind);
1429 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
1430 "Must be either a call argument or an operand bundle!");
1431 return bundleOperandHasAttr(i - 1, Kind);
1434 /// Determine whether this data operand is not captured.
1435 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1436 // better indicate that this may return a conservative answer.
1437 bool doesNotCapture(unsigned OpNo) const {
1438 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
1441 /// Determine whether this argument is passed by value.
1442 bool isByValArgument(unsigned ArgNo) const {
1443 return paramHasAttr(ArgNo, Attribute::ByVal);
1446 /// Determine whether this argument is passed in an alloca.
1447 bool isInAllocaArgument(unsigned ArgNo) const {
1448 return paramHasAttr(ArgNo, Attribute::InAlloca);
1451 /// Determine whether this argument is passed by value or in an alloca.
1452 bool isByValOrInAllocaArgument(unsigned ArgNo) const {
1453 return paramHasAttr(ArgNo, Attribute::ByVal) ||
1454 paramHasAttr(ArgNo, Attribute::InAlloca);
1457 /// Determine if there are is an inalloca argument. Only the last argument can
1458 /// have the inalloca attribute.
1459 bool hasInAllocaArgument() const {
1460 return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
1463 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1464 // better indicate that this may return a conservative answer.
1465 bool doesNotAccessMemory(unsigned OpNo) const {
1466 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1469 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1470 // better indicate that this may return a conservative answer.
1471 bool onlyReadsMemory(unsigned OpNo) const {
1472 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
1473 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1476 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1477 // better indicate that this may return a conservative answer.
1478 bool doesNotReadMemory(unsigned OpNo) const {
1479 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::WriteOnly) ||
1480 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1483 /// Extract the alignment of the return value.
1484 unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
1486 /// Extract the alignment for a call or parameter (0=unknown).
1487 unsigned getParamAlignment(unsigned ArgNo) const {
1488 return Attrs.getParamAlignment(ArgNo);
1491 /// Extract the number of dereferenceable bytes for a call or
1492 /// parameter (0=unknown).
1493 uint64_t getDereferenceableBytes(unsigned i) const {
1494 return Attrs.getDereferenceableBytes(i);
1497 /// Extract the number of dereferenceable_or_null bytes for a call or
1498 /// parameter (0=unknown).
1499 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1500 return Attrs.getDereferenceableOrNullBytes(i);
1503 /// Return true if the return value is known to be not null.
1504 /// This may be because it has the nonnull attribute, or because at least
1505 /// one byte is dereferenceable and the pointer is in addrspace(0).
1506 bool isReturnNonNull() const;
1508 /// Determine if the return value is marked with NoAlias attribute.
1509 bool returnDoesNotAlias() const {
1510 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1513 /// If one of the arguments has the 'returned' attribute, returns its
1514 /// operand value. Otherwise, return nullptr.
1515 Value *getReturnedArgOperand() const;
1517 /// Return true if the call should not be treated as a call to a
1518 /// builtin.
1519 bool isNoBuiltin() const {
1520 return hasFnAttrImpl(Attribute::NoBuiltin) &&
1521 !hasFnAttrImpl(Attribute::Builtin);
1524 /// Determine if the call requires strict floating point semantics.
1525 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1527 /// Return true if the call should not be inlined.
1528 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1529 void setIsNoInline() {
1530 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1532 /// Determine if the call does not access memory.
1533 bool doesNotAccessMemory() const { return hasFnAttr(Attribute::ReadNone); }
1534 void setDoesNotAccessMemory() {
1535 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1538 /// Determine if the call does not access or only reads memory.
1539 bool onlyReadsMemory() const {
1540 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1542 void setOnlyReadsMemory() {
1543 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1546 /// Determine if the call does not access or only writes memory.
1547 bool doesNotReadMemory() const {
1548 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1550 void setDoesNotReadMemory() {
1551 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1554 /// Determine if the call can access memmory only using pointers based
1555 /// on its arguments.
1556 bool onlyAccessesArgMemory() const {
1557 return hasFnAttr(Attribute::ArgMemOnly);
1559 void setOnlyAccessesArgMemory() {
1560 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1563 /// Determine if the function may only access memory that is
1564 /// inaccessible from the IR.
1565 bool onlyAccessesInaccessibleMemory() const {
1566 return hasFnAttr(Attribute::InaccessibleMemOnly);
1568 void setOnlyAccessesInaccessibleMemory() {
1569 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
1572 /// Determine if the function may only access memory that is
1573 /// either inaccessible from the IR or pointed to by its arguments.
1574 bool onlyAccessesInaccessibleMemOrArgMem() const {
1575 return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
1577 void setOnlyAccessesInaccessibleMemOrArgMem() {
1578 addAttribute(AttributeList::FunctionIndex,
1579 Attribute::InaccessibleMemOrArgMemOnly);
1581 /// Determine if the call cannot return.
1582 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1583 void setDoesNotReturn() {
1584 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1587 /// Determine if the call should not perform indirect branch tracking.
1588 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
1590 /// Determine if the call cannot unwind.
1591 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1592 void setDoesNotThrow() {
1593 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1596 /// Determine if the invoke cannot be duplicated.
1597 bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); }
1598 void setCannotDuplicate() {
1599 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1602 /// Determine if the invoke is convergent
1603 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1604 void setConvergent() {
1605 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1607 void setNotConvergent() {
1608 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1611 /// Determine if the call returns a structure through first
1612 /// pointer argument.
1613 bool hasStructRetAttr() const {
1614 if (getNumArgOperands() == 0)
1615 return false;
1617 // Be friendly and also check the callee.
1618 return paramHasAttr(0, Attribute::StructRet);
1621 /// Determine if any call argument is an aggregate passed by value.
1622 bool hasByValArgument() const {
1623 return Attrs.hasAttrSomewhere(Attribute::ByVal);
1626 ///@{
1627 // End of attribute API.
1629 /// \name Operand Bundle API
1631 /// This group of methods provides the API to access and manipulate operand
1632 /// bundles on this call.
1633 /// @{
1635 /// Return the number of operand bundles associated with this User.
1636 unsigned getNumOperandBundles() const {
1637 return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1640 /// Return true if this User has any operand bundles.
1641 bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1643 /// Return the index of the first bundle operand in the Use array.
1644 unsigned getBundleOperandsStartIndex() const {
1645 assert(hasOperandBundles() && "Don't call otherwise!");
1646 return bundle_op_info_begin()->Begin;
1649 /// Return the index of the last bundle operand in the Use array.
1650 unsigned getBundleOperandsEndIndex() const {
1651 assert(hasOperandBundles() && "Don't call otherwise!");
1652 return bundle_op_info_end()[-1].End;
1655 /// Return true if the operand at index \p Idx is a bundle operand.
1656 bool isBundleOperand(unsigned Idx) const {
1657 return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1658 Idx < getBundleOperandsEndIndex();
1661 /// Returns true if the use is a bundle operand.
1662 bool isBundleOperand(const Use *U) const {
1663 assert(this == U->getUser() &&
1664 "Only valid to query with a use of this instruction!");
1665 return hasOperandBundles() && isBundleOperand(U - op_begin());
1667 bool isBundleOperand(Value::const_user_iterator UI) const {
1668 return isBundleOperand(&UI.getUse());
1671 /// Return the total number operands (not operand bundles) used by
1672 /// every operand bundle in this OperandBundleUser.
1673 unsigned getNumTotalBundleOperands() const {
1674 if (!hasOperandBundles())
1675 return 0;
1677 unsigned Begin = getBundleOperandsStartIndex();
1678 unsigned End = getBundleOperandsEndIndex();
1680 assert(Begin <= End && "Should be!");
1681 return End - Begin;
1684 /// Return the operand bundle at a specific index.
1685 OperandBundleUse getOperandBundleAt(unsigned Index) const {
1686 assert(Index < getNumOperandBundles() && "Index out of bounds!");
1687 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1690 /// Return the number of operand bundles with the tag Name attached to
1691 /// this instruction.
1692 unsigned countOperandBundlesOfType(StringRef Name) const {
1693 unsigned Count = 0;
1694 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1695 if (getOperandBundleAt(i).getTagName() == Name)
1696 Count++;
1698 return Count;
1701 /// Return the number of operand bundles with the tag ID attached to
1702 /// this instruction.
1703 unsigned countOperandBundlesOfType(uint32_t ID) const {
1704 unsigned Count = 0;
1705 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1706 if (getOperandBundleAt(i).getTagID() == ID)
1707 Count++;
1709 return Count;
1712 /// Return an operand bundle by name, if present.
1714 /// It is an error to call this for operand bundle types that may have
1715 /// multiple instances of them on the same instruction.
1716 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1717 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1719 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1720 OperandBundleUse U = getOperandBundleAt(i);
1721 if (U.getTagName() == Name)
1722 return U;
1725 return None;
1728 /// Return an operand bundle by tag ID, if present.
1730 /// It is an error to call this for operand bundle types that may have
1731 /// multiple instances of them on the same instruction.
1732 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1733 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1735 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1736 OperandBundleUse U = getOperandBundleAt(i);
1737 if (U.getTagID() == ID)
1738 return U;
1741 return None;
1744 /// Return the list of operand bundles attached to this instruction as
1745 /// a vector of OperandBundleDefs.
1747 /// This function copies the OperandBundeUse instances associated with this
1748 /// OperandBundleUser to a vector of OperandBundleDefs. Note:
1749 /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1750 /// representations of operand bundles (see documentation above).
1751 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1752 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1753 Defs.emplace_back(getOperandBundleAt(i));
1756 /// Return the operand bundle for the operand at index OpIdx.
1758 /// It is an error to call this with an OpIdx that does not correspond to an
1759 /// bundle operand.
1760 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1761 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1764 /// Return true if this operand bundle user has operand bundles that
1765 /// may read from the heap.
1766 bool hasReadingOperandBundles() const {
1767 // Implementation note: this is a conservative implementation of operand
1768 // bundle semantics, where *any* operand bundle forces a callsite to be at
1769 // least readonly.
1770 return hasOperandBundles();
1773 /// Return true if this operand bundle user has operand bundles that
1774 /// may write to the heap.
1775 bool hasClobberingOperandBundles() const {
1776 for (auto &BOI : bundle_op_infos()) {
1777 if (BOI.Tag->second == LLVMContext::OB_deopt ||
1778 BOI.Tag->second == LLVMContext::OB_funclet)
1779 continue;
1781 // This instruction has an operand bundle that is not known to us.
1782 // Assume the worst.
1783 return true;
1786 return false;
1789 /// Return true if the bundle operand at index \p OpIdx has the
1790 /// attribute \p A.
1791 bool bundleOperandHasAttr(unsigned OpIdx, Attribute::AttrKind A) const {
1792 auto &BOI = getBundleOpInfoForOperand(OpIdx);
1793 auto OBU = operandBundleFromBundleOpInfo(BOI);
1794 return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
1797 /// Return true if \p Other has the same sequence of operand bundle
1798 /// tags with the same number of operands on each one of them as this
1799 /// OperandBundleUser.
1800 bool hasIdenticalOperandBundleSchema(const CallBase &Other) const {
1801 if (getNumOperandBundles() != Other.getNumOperandBundles())
1802 return false;
1804 return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
1805 Other.bundle_op_info_begin());
1808 /// Return true if this operand bundle user contains operand bundles
1809 /// with tags other than those specified in \p IDs.
1810 bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
1811 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1812 uint32_t ID = getOperandBundleAt(i).getTagID();
1813 if (!is_contained(IDs, ID))
1814 return true;
1816 return false;
1819 /// Is the function attribute S disallowed by some operand bundle on
1820 /// this operand bundle user?
1821 bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1822 // Operand bundles only possibly disallow readnone, readonly and argmenonly
1823 // attributes. All String attributes are fine.
1824 return false;
1827 /// Is the function attribute A disallowed by some operand bundle on
1828 /// this operand bundle user?
1829 bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1830 switch (A) {
1831 default:
1832 return false;
1834 case Attribute::InaccessibleMemOrArgMemOnly:
1835 return hasReadingOperandBundles();
1837 case Attribute::InaccessibleMemOnly:
1838 return hasReadingOperandBundles();
1840 case Attribute::ArgMemOnly:
1841 return hasReadingOperandBundles();
1843 case Attribute::ReadNone:
1844 return hasReadingOperandBundles();
1846 case Attribute::ReadOnly:
1847 return hasClobberingOperandBundles();
1850 llvm_unreachable("switch has a default case!");
1853 /// Used to keep track of an operand bundle. See the main comment on
1854 /// OperandBundleUser above.
1855 struct BundleOpInfo {
1856 /// The operand bundle tag, interned by
1857 /// LLVMContextImpl::getOrInsertBundleTag.
1858 StringMapEntry<uint32_t> *Tag;
1860 /// The index in the Use& vector where operands for this operand
1861 /// bundle starts.
1862 uint32_t Begin;
1864 /// The index in the Use& vector where operands for this operand
1865 /// bundle ends.
1866 uint32_t End;
1868 bool operator==(const BundleOpInfo &Other) const {
1869 return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
1873 /// Simple helper function to map a BundleOpInfo to an
1874 /// OperandBundleUse.
1875 OperandBundleUse
1876 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1877 auto begin = op_begin();
1878 ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End);
1879 return OperandBundleUse(BOI.Tag, Inputs);
1882 using bundle_op_iterator = BundleOpInfo *;
1883 using const_bundle_op_iterator = const BundleOpInfo *;
1885 /// Return the start of the list of BundleOpInfo instances associated
1886 /// with this OperandBundleUser.
1888 /// OperandBundleUser uses the descriptor area co-allocated with the host User
1889 /// to store some meta information about which operands are "normal" operands,
1890 /// and which ones belong to some operand bundle.
1892 /// The layout of an operand bundle user is
1894 /// +-----------uint32_t End-------------------------------------+
1895 /// | |
1896 /// | +--------uint32_t Begin--------------------+ |
1897 /// | | | |
1898 /// ^ ^ v v
1899 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1900 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1901 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1902 /// v v ^ ^
1903 /// | | | |
1904 /// | +--------uint32_t Begin------------+ |
1905 /// | |
1906 /// +-----------uint32_t End-----------------------------+
1909 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use
1910 /// list. These descriptions are installed and managed by this class, and
1911 /// they're all instances of OperandBundleUser<T>::BundleOpInfo.
1913 /// DU is an additional descriptor installed by User's 'operator new' to keep
1914 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not
1915 /// access or modify DU in any way, it's an implementation detail private to
1916 /// User.
1918 /// The regular Use& vector for the User starts at U0. The operand bundle
1919 /// uses are part of the Use& vector, just like normal uses. In the diagram
1920 /// above, the operand bundle uses start at BOI0_U0. Each instance of
1921 /// BundleOpInfo has information about a contiguous set of uses constituting
1922 /// an operand bundle, and the total set of operand bundle uses themselves
1923 /// form a contiguous set of uses (i.e. there are no gaps between uses
1924 /// corresponding to individual operand bundles).
1926 /// This class does not know the location of the set of operand bundle uses
1927 /// within the use list -- that is decided by the User using this class via
1928 /// the BeginIdx argument in populateBundleOperandInfos.
1930 /// Currently operand bundle users with hung-off operands are not supported.
1931 bundle_op_iterator bundle_op_info_begin() {
1932 if (!hasDescriptor())
1933 return nullptr;
1935 uint8_t *BytesBegin = getDescriptor().begin();
1936 return reinterpret_cast<bundle_op_iterator>(BytesBegin);
1939 /// Return the start of the list of BundleOpInfo instances associated
1940 /// with this OperandBundleUser.
1941 const_bundle_op_iterator bundle_op_info_begin() const {
1942 auto *NonConstThis = const_cast<CallBase *>(this);
1943 return NonConstThis->bundle_op_info_begin();
1946 /// Return the end of the list of BundleOpInfo instances associated
1947 /// with this OperandBundleUser.
1948 bundle_op_iterator bundle_op_info_end() {
1949 if (!hasDescriptor())
1950 return nullptr;
1952 uint8_t *BytesEnd = getDescriptor().end();
1953 return reinterpret_cast<bundle_op_iterator>(BytesEnd);
1956 /// Return the end of the list of BundleOpInfo instances associated
1957 /// with this OperandBundleUser.
1958 const_bundle_op_iterator bundle_op_info_end() const {
1959 auto *NonConstThis = const_cast<CallBase *>(this);
1960 return NonConstThis->bundle_op_info_end();
1963 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1964 iterator_range<bundle_op_iterator> bundle_op_infos() {
1965 return make_range(bundle_op_info_begin(), bundle_op_info_end());
1968 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1969 iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
1970 return make_range(bundle_op_info_begin(), bundle_op_info_end());
1973 /// Populate the BundleOpInfo instances and the Use& vector from \p
1974 /// Bundles. Return the op_iterator pointing to the Use& one past the last
1975 /// last bundle operand use.
1977 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
1978 /// instance allocated in this User's descriptor.
1979 op_iterator populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
1980 const unsigned BeginIndex);
1982 /// Return the BundleOpInfo for the operand at index OpIdx.
1984 /// It is an error to call this with an OpIdx that does not correspond to an
1985 /// bundle operand.
1986 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
1987 for (auto &BOI : bundle_op_infos())
1988 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
1989 return BOI;
1991 llvm_unreachable("Did not find operand bundle for operand!");
1994 protected:
1995 /// Return the total number of values used in \p Bundles.
1996 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
1997 unsigned Total = 0;
1998 for (auto &B : Bundles)
1999 Total += B.input_size();
2000 return Total;
2003 /// @}
2004 // End of operand bundle API.
2006 private:
2007 bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
2008 bool hasFnAttrOnCalledFunction(StringRef Kind) const;
2010 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
2011 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
2012 return true;
2014 // Operand bundles override attributes on the called function, but don't
2015 // override attributes directly present on the call instruction.
2016 if (isFnAttrDisallowedByOpBundle(Kind))
2017 return false;
2019 return hasFnAttrOnCalledFunction(Kind);
2023 template <>
2024 struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase, 1> {};
2026 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value)
2028 //===----------------------------------------------------------------------===//
2029 // FuncletPadInst Class
2030 //===----------------------------------------------------------------------===//
2031 class FuncletPadInst : public Instruction {
2032 private:
2033 FuncletPadInst(const FuncletPadInst &CPI);
2035 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2036 ArrayRef<Value *> Args, unsigned Values,
2037 const Twine &NameStr, Instruction *InsertBefore);
2038 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2039 ArrayRef<Value *> Args, unsigned Values,
2040 const Twine &NameStr, BasicBlock *InsertAtEnd);
2042 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
2044 protected:
2045 // Note: Instruction needs to be a friend here to call cloneImpl.
2046 friend class Instruction;
2047 friend class CatchPadInst;
2048 friend class CleanupPadInst;
2050 FuncletPadInst *cloneImpl() const;
2052 public:
2053 /// Provide fast operand accessors
2054 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2056 /// getNumArgOperands - Return the number of funcletpad arguments.
2058 unsigned getNumArgOperands() const { return getNumOperands() - 1; }
2060 /// Convenience accessors
2062 /// Return the outer EH-pad this funclet is nested within.
2064 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
2065 /// is a CatchPadInst.
2066 Value *getParentPad() const { return Op<-1>(); }
2067 void setParentPad(Value *ParentPad) {
2068 assert(ParentPad);
2069 Op<-1>() = ParentPad;
2072 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
2074 Value *getArgOperand(unsigned i) const { return getOperand(i); }
2075 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
2077 /// arg_operands - iteration adapter for range-for loops.
2078 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
2080 /// arg_operands - iteration adapter for range-for loops.
2081 const_op_range arg_operands() const {
2082 return const_op_range(op_begin(), op_end() - 1);
2085 // Methods for support type inquiry through isa, cast, and dyn_cast:
2086 static bool classof(const Instruction *I) { return I->isFuncletPad(); }
2087 static bool classof(const Value *V) {
2088 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2092 template <>
2093 struct OperandTraits<FuncletPadInst>
2094 : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
2096 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
2098 } // end namespace llvm
2100 #endif // LLVM_IR_INSTRTYPES_H