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...
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_IR_INSTRTYPES_H
16 #define LLVM_IR_INSTRTYPES_H
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Sequence.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/OperandTraits.h"
31 #include "llvm/IR/User.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstddef>
35 #include <cstdint>
36 #include <iterator>
37 #include <optional>
38 #include <string>
39 #include <vector>
40 
41 namespace llvm {
42 
43 class StringRef;
44 class Type;
45 class Value;
46 
47 namespace Intrinsic {
48 typedef unsigned ID;
49 }
50 
51 //===----------------------------------------------------------------------===//
52 //                          UnaryInstruction Class
53 //===----------------------------------------------------------------------===//
54 
55 class UnaryInstruction : public Instruction {
56 protected:
57   UnaryInstruction(Type *Ty, unsigned iType, Value *V,
58                    Instruction *IB = nullptr)
59     : Instruction(Ty, iType, &Op<0>(), 1, IB) {
60     Op<0>() = V;
61   }
UnaryInstruction(Type * Ty,unsigned iType,Value * V,BasicBlock * IAE)62   UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
63     : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
64     Op<0>() = V;
65   }
66 
67 public:
68   // allocate space for exactly one operand
new(size_t S)69   void *operator new(size_t S) { return User::operator new(S, 1); }
delete(void * Ptr)70   void operator delete(void *Ptr) { User::operator delete(Ptr); }
71 
72   /// Transparently provide more efficient getOperand methods.
73   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
74 
75   // Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Instruction * I)76   static bool classof(const Instruction *I) {
77     return I->isUnaryOp() ||
78            I->getOpcode() == Instruction::Alloca ||
79            I->getOpcode() == Instruction::Load ||
80            I->getOpcode() == Instruction::VAArg ||
81            I->getOpcode() == Instruction::ExtractValue ||
82            (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
83   }
classof(const Value * V)84   static bool classof(const Value *V) {
85     return isa<Instruction>(V) && classof(cast<Instruction>(V));
86   }
87 };
88 
89 template <>
90 struct OperandTraits<UnaryInstruction> :
91   public FixedNumOperandTraits<UnaryInstruction, 1> {
92 };
93 
94 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
95 
96 //===----------------------------------------------------------------------===//
97 //                                UnaryOperator Class
98 //===----------------------------------------------------------------------===//
99 
100 class UnaryOperator : public UnaryInstruction {
101   void AssertOK();
102 
103 protected:
104   UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
105                 const Twine &Name, Instruction *InsertBefore);
106   UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
107                 const Twine &Name, BasicBlock *InsertAtEnd);
108 
109   // Note: Instruction needs to be a friend here to call cloneImpl.
110   friend class Instruction;
111 
112   UnaryOperator *cloneImpl() const;
113 
114 public:
115 
116   /// Construct a unary instruction, given the opcode and an operand.
117   /// Optionally (if InstBefore is specified) insert the instruction
118   /// into a BasicBlock right before the specified instruction.  The specified
119   /// Instruction is allowed to be a dereferenced end iterator.
120   ///
121   static UnaryOperator *Create(UnaryOps Op, Value *S,
122                                const Twine &Name = Twine(),
123                                Instruction *InsertBefore = nullptr);
124 
125   /// Construct a unary instruction, given the opcode and an operand.
126   /// Also automatically insert this instruction to the end of the
127   /// BasicBlock specified.
128   ///
129   static UnaryOperator *Create(UnaryOps Op, Value *S,
130                                const Twine &Name,
131                                BasicBlock *InsertAtEnd);
132 
133   /// These methods just forward to Create, and are useful when you
134   /// statically know what type of instruction you're going to create.  These
135   /// helpers just save some typing.
136 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
137   static UnaryOperator *Create##OPC(Value *V, const Twine &Name = "") {\
138     return Create(Instruction::OPC, V, Name);\
139   }
140 #include "llvm/IR/Instruction.def"
141 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
142   static UnaryOperator *Create##OPC(Value *V, const Twine &Name, \
143                                     BasicBlock *BB) {\
144     return Create(Instruction::OPC, V, Name, BB);\
145   }
146 #include "llvm/IR/Instruction.def"
147 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
148   static UnaryOperator *Create##OPC(Value *V, const Twine &Name, \
149                                     Instruction *I) {\
150     return Create(Instruction::OPC, V, Name, I);\
151   }
152 #include "llvm/IR/Instruction.def"
153 
154   static UnaryOperator *
155   CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO,
156                         const Twine &Name = "",
157                         Instruction *InsertBefore = nullptr) {
158     UnaryOperator *UO = Create(Opc, V, Name, InsertBefore);
159     UO->copyIRFlags(CopyO);
160     return UO;
161   }
162 
163   static UnaryOperator *CreateFNegFMF(Value *Op, Instruction *FMFSource,
164                                       const Twine &Name = "",
165                                       Instruction *InsertBefore = nullptr) {
166     return CreateWithCopiedFlags(Instruction::FNeg, Op, FMFSource, Name,
167                                  InsertBefore);
168   }
169 
170   UnaryOps getOpcode() const {
171     return static_cast<UnaryOps>(Instruction::getOpcode());
172   }
173 
174   // Methods for support type inquiry through isa, cast, and dyn_cast:
175   static bool classof(const Instruction *I) {
176     return I->isUnaryOp();
177   }
178   static bool classof(const Value *V) {
179     return isa<Instruction>(V) && classof(cast<Instruction>(V));
180   }
181 };
182 
183 //===----------------------------------------------------------------------===//
184 //                           BinaryOperator Class
185 //===----------------------------------------------------------------------===//
186 
187 class BinaryOperator : public Instruction {
188   void AssertOK();
189 
190 protected:
191   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
192                  const Twine &Name, Instruction *InsertBefore);
193   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
194                  const Twine &Name, BasicBlock *InsertAtEnd);
195 
196   // Note: Instruction needs to be a friend here to call cloneImpl.
197   friend class Instruction;
198 
199   BinaryOperator *cloneImpl() const;
200 
201 public:
202   // allocate space for exactly two operands
203   void *operator new(size_t S) { return User::operator new(S, 2); }
204   void operator delete(void *Ptr) { User::operator delete(Ptr); }
205 
206   /// Transparently provide more efficient getOperand methods.
207   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
208 
209   /// Construct a binary instruction, given the opcode and the two
210   /// operands.  Optionally (if InstBefore is specified) insert the instruction
211   /// into a BasicBlock right before the specified instruction.  The specified
212   /// Instruction is allowed to be a dereferenced end iterator.
213   ///
214   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
215                                 const Twine &Name = Twine(),
216                                 Instruction *InsertBefore = nullptr);
217 
218   /// Construct a binary instruction, given the opcode and the two
219   /// operands.  Also automatically insert this instruction to the end of the
220   /// BasicBlock specified.
221   ///
222   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
223                                 const Twine &Name, BasicBlock *InsertAtEnd);
224 
225   /// These methods just forward to Create, and are useful when you
226   /// statically know what type of instruction you're going to create.  These
227   /// helpers just save some typing.
228 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
229   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
230                                      const Twine &Name = "") {\
231     return Create(Instruction::OPC, V1, V2, Name);\
232   }
233 #include "llvm/IR/Instruction.def"
234 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
235   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
236                                      const Twine &Name, BasicBlock *BB) {\
237     return Create(Instruction::OPC, V1, V2, Name, BB);\
238   }
239 #include "llvm/IR/Instruction.def"
240 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
241   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
242                                      const Twine &Name, Instruction *I) {\
243     return Create(Instruction::OPC, V1, V2, Name, I);\
244   }
245 #include "llvm/IR/Instruction.def"
246 
247   static BinaryOperator *
248   CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO,
249                         const Twine &Name = "",
250                         Instruction *InsertBefore = nullptr) {
251     BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore);
252     BO->copyIRFlags(CopyO);
253     return BO;
254   }
255 
256   static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2,
257                                        Instruction *FMFSource,
258                                        const Twine &Name = "") {
259     return CreateWithCopiedFlags(Instruction::FAdd, V1, V2, FMFSource, Name);
260   }
261   static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2,
262                                        Instruction *FMFSource,
263                                        const Twine &Name = "") {
264     return CreateWithCopiedFlags(Instruction::FSub, V1, V2, FMFSource, Name);
265   }
266   static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2,
267                                        Instruction *FMFSource,
268                                        const Twine &Name = "") {
269     return CreateWithCopiedFlags(Instruction::FMul, V1, V2, FMFSource, Name);
270   }
271   static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2,
272                                        Instruction *FMFSource,
273                                        const Twine &Name = "") {
274     return CreateWithCopiedFlags(Instruction::FDiv, V1, V2, FMFSource, Name);
275   }
276   static BinaryOperator *CreateFRemFMF(Value *V1, Value *V2,
277                                        Instruction *FMFSource,
278                                        const Twine &Name = "") {
279     return CreateWithCopiedFlags(Instruction::FRem, V1, V2, FMFSource, Name);
280   }
281 
282   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
283                                    const Twine &Name = "") {
284     BinaryOperator *BO = Create(Opc, V1, V2, Name);
285     BO->setHasNoSignedWrap(true);
286     return BO;
287   }
288   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
289                                    const Twine &Name, BasicBlock *BB) {
290     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
291     BO->setHasNoSignedWrap(true);
292     return BO;
293   }
294   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
295                                    const Twine &Name, Instruction *I) {
296     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
297     BO->setHasNoSignedWrap(true);
298     return BO;
299   }
300 
301   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
302                                    const Twine &Name = "") {
303     BinaryOperator *BO = Create(Opc, V1, V2, Name);
304     BO->setHasNoUnsignedWrap(true);
305     return BO;
306   }
307   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
308                                    const Twine &Name, BasicBlock *BB) {
309     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
310     BO->setHasNoUnsignedWrap(true);
311     return BO;
312   }
313   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
314                                    const Twine &Name, Instruction *I) {
315     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
316     BO->setHasNoUnsignedWrap(true);
317     return BO;
318   }
319 
320   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
321                                      const Twine &Name = "") {
322     BinaryOperator *BO = Create(Opc, V1, V2, Name);
323     BO->setIsExact(true);
324     return BO;
325   }
326   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
327                                      const Twine &Name, BasicBlock *BB) {
328     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
329     BO->setIsExact(true);
330     return BO;
331   }
332   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
333                                      const Twine &Name, Instruction *I) {
334     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
335     BO->setIsExact(true);
336     return BO;
337   }
338 
339   static inline BinaryOperator *
340   CreateDisjoint(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name = "");
341   static inline BinaryOperator *CreateDisjoint(BinaryOps Opc, Value *V1,
342                                                Value *V2, const Twine &Name,
343                                                BasicBlock *BB);
344   static inline BinaryOperator *CreateDisjoint(BinaryOps Opc, Value *V1,
345                                                Value *V2, const Twine &Name,
346                                                Instruction *I);
347 
348 #define DEFINE_HELPERS(OPC, NUWNSWEXACT)                                       \
349   static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2,        \
350                                                   const Twine &Name = "") {    \
351     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name);                \
352   }                                                                            \
353   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
354       Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) {               \
355     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB);            \
356   }                                                                            \
357   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
358       Value *V1, Value *V2, const Twine &Name, Instruction *I) {               \
359     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I);             \
360   }
361 
362   DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
363   DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
364   DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
365   DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
366   DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
367   DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
368   DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
369   DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
370 
371   DEFINE_HELPERS(SDiv, Exact)  // CreateExactSDiv
372   DEFINE_HELPERS(UDiv, Exact)  // CreateExactUDiv
373   DEFINE_HELPERS(AShr, Exact)  // CreateExactAShr
374   DEFINE_HELPERS(LShr, Exact)  // CreateExactLShr
375 
376   DEFINE_HELPERS(Or, Disjoint) // CreateDisjointOr
377 
378 #undef DEFINE_HELPERS
379 
380   /// Helper functions to construct and inspect unary operations (NEG and NOT)
381   /// via binary operators SUB and XOR:
382   ///
383   /// Create the NEG and NOT instructions out of SUB and XOR instructions.
384   ///
385   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
386                                    Instruction *InsertBefore = nullptr);
387   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
388                                    BasicBlock *InsertAtEnd);
389   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
390                                       Instruction *InsertBefore = nullptr);
391   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
392                                       BasicBlock *InsertAtEnd);
393   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
394                                       Instruction *InsertBefore = nullptr);
395   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
396                                       BasicBlock *InsertAtEnd);
397   static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
398                                    Instruction *InsertBefore = nullptr);
399   static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
400                                    BasicBlock *InsertAtEnd);
401 
402   BinaryOps getOpcode() const {
403     return static_cast<BinaryOps>(Instruction::getOpcode());
404   }
405 
406   /// Exchange the two operands to this instruction.
407   /// This instruction is safe to use on any binary instruction and
408   /// does not modify the semantics of the instruction.  If the instruction
409   /// cannot be reversed (ie, it's a Div), then return true.
410   ///
411   bool swapOperands();
412 
413   // Methods for support type inquiry through isa, cast, and dyn_cast:
414   static bool classof(const Instruction *I) {
415     return I->isBinaryOp();
416   }
417   static bool classof(const Value *V) {
418     return isa<Instruction>(V) && classof(cast<Instruction>(V));
419   }
420 };
421 
422 template <>
423 struct OperandTraits<BinaryOperator> :
424   public FixedNumOperandTraits<BinaryOperator, 2> {
425 };
426 
427 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
428 
429 /// An or instruction, which can be marked as "disjoint", indicating that the
430 /// inputs don't have a 1 in the same bit position. Meaning this instruction
431 /// can also be treated as an add.
432 class PossiblyDisjointInst : public BinaryOperator {
433 public:
434   enum { IsDisjoint = (1 << 0) };
435 
436   void setIsDisjoint(bool B) {
437     SubclassOptionalData =
438         (SubclassOptionalData & ~IsDisjoint) | (B * IsDisjoint);
439   }
440 
441   bool isDisjoint() const { return SubclassOptionalData & IsDisjoint; }
442 
443   static bool classof(const Instruction *I) {
444     return I->getOpcode() == Instruction::Or;
445   }
446 
447   static bool classof(const Value *V) {
448     return isa<Instruction>(V) && classof(cast<Instruction>(V));
449   }
450 };
451 
452 BinaryOperator *BinaryOperator::CreateDisjoint(BinaryOps Opc, Value *V1,
453                                                Value *V2, const Twine &Name) {
454   BinaryOperator *BO = Create(Opc, V1, V2, Name);
455   cast<PossiblyDisjointInst>(BO)->setIsDisjoint(true);
456   return BO;
457 }
458 BinaryOperator *BinaryOperator::CreateDisjoint(BinaryOps Opc, Value *V1,
459                                                Value *V2, const Twine &Name,
460                                                BasicBlock *BB) {
461   BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
462   cast<PossiblyDisjointInst>(BO)->setIsDisjoint(true);
463   return BO;
464 }
465 BinaryOperator *BinaryOperator::CreateDisjoint(BinaryOps Opc, Value *V1,
466                                                Value *V2, const Twine &Name,
467                                                Instruction *I) {
468   BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
469   cast<PossiblyDisjointInst>(BO)->setIsDisjoint(true);
470   return BO;
471 }
472 
473 //===----------------------------------------------------------------------===//
474 //                               CastInst Class
475 //===----------------------------------------------------------------------===//
476 
477 /// This is the base class for all instructions that perform data
478 /// casts. It is simply provided so that instruction category testing
479 /// can be performed with code like:
480 ///
481 /// if (isa<CastInst>(Instr)) { ... }
482 /// Base class of casting instructions.
483 class CastInst : public UnaryInstruction {
484 protected:
485   /// Constructor with insert-before-instruction semantics for subclasses
486   CastInst(Type *Ty, unsigned iType, Value *S,
487            const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
488     : UnaryInstruction(Ty, iType, S, InsertBefore) {
489     setName(NameStr);
490   }
491   /// Constructor with insert-at-end-of-block semantics for subclasses
492   CastInst(Type *Ty, unsigned iType, Value *S,
493            const Twine &NameStr, BasicBlock *InsertAtEnd)
494     : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
495     setName(NameStr);
496   }
497 
498 public:
499   /// Provides a way to construct any of the CastInst subclasses using an
500   /// opcode instead of the subclass's constructor. The opcode must be in the
501   /// CastOps category (Instruction::isCast(opcode) returns true). This
502   /// constructor has insert-before-instruction semantics to automatically
503   /// insert the new CastInst before InsertBefore (if it is non-null).
504   /// Construct any of the CastInst subclasses
505   static CastInst *Create(
506     Instruction::CastOps,    ///< The opcode of the cast instruction
507     Value *S,                ///< The value to be casted (operand 0)
508     Type *Ty,          ///< The type to which cast should be made
509     const Twine &Name = "", ///< Name for the instruction
510     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
511   );
512   /// Provides a way to construct any of the CastInst subclasses using an
513   /// opcode instead of the subclass's constructor. The opcode must be in the
514   /// CastOps category. This constructor has insert-at-end-of-block semantics
515   /// to automatically insert the new CastInst at the end of InsertAtEnd (if
516   /// its non-null).
517   /// Construct any of the CastInst subclasses
518   static CastInst *Create(
519     Instruction::CastOps,    ///< The opcode for the cast instruction
520     Value *S,                ///< The value to be casted (operand 0)
521     Type *Ty,          ///< The type to which operand is casted
522     const Twine &Name, ///< The name for the instruction
523     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
524   );
525 
526   /// Create a ZExt or BitCast cast instruction
527   static CastInst *CreateZExtOrBitCast(
528     Value *S,                ///< The value to be casted (operand 0)
529     Type *Ty,          ///< The type to which cast should be made
530     const Twine &Name = "", ///< Name for the instruction
531     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
532   );
533 
534   /// Create a ZExt or BitCast cast instruction
535   static CastInst *CreateZExtOrBitCast(
536     Value *S,                ///< The value to be casted (operand 0)
537     Type *Ty,          ///< The type to which operand is casted
538     const Twine &Name, ///< The name for the instruction
539     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
540   );
541 
542   /// Create a SExt or BitCast cast instruction
543   static CastInst *CreateSExtOrBitCast(
544     Value *S,                ///< The value to be casted (operand 0)
545     Type *Ty,          ///< The type to which cast should be made
546     const Twine &Name = "", ///< Name for the instruction
547     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
548   );
549 
550   /// Create a SExt or BitCast cast instruction
551   static CastInst *CreateSExtOrBitCast(
552     Value *S,                ///< The value to be casted (operand 0)
553     Type *Ty,          ///< The type to which operand is casted
554     const Twine &Name, ///< The name for the instruction
555     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
556   );
557 
558   /// Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
559   static CastInst *CreatePointerCast(
560     Value *S,                ///< The pointer value to be casted (operand 0)
561     Type *Ty,          ///< The type to which operand is casted
562     const Twine &Name, ///< The name for the instruction
563     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
564   );
565 
566   /// Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
567   static CastInst *CreatePointerCast(
568     Value *S,                ///< The pointer value to be casted (operand 0)
569     Type *Ty,          ///< The type to which cast should be made
570     const Twine &Name = "", ///< Name for the instruction
571     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
572   );
573 
574   /// Create a BitCast or an AddrSpaceCast cast instruction.
575   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
576     Value *S,                ///< The pointer value to be casted (operand 0)
577     Type *Ty,          ///< The type to which operand is casted
578     const Twine &Name, ///< The name for the instruction
579     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
580   );
581 
582   /// Create a BitCast or an AddrSpaceCast cast instruction.
583   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
584     Value *S,                ///< The pointer value to be casted (operand 0)
585     Type *Ty,          ///< The type to which cast should be made
586     const Twine &Name = "", ///< Name for the instruction
587     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
588   );
589 
590   /// Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
591   ///
592   /// If the value is a pointer type and the destination an integer type,
593   /// creates a PtrToInt cast. If the value is an integer type and the
594   /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
595   /// a bitcast.
596   static CastInst *CreateBitOrPointerCast(
597     Value *S,                ///< The pointer value to be casted (operand 0)
598     Type *Ty,          ///< The type to which cast should be made
599     const Twine &Name = "", ///< Name for the instruction
600     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
601   );
602 
603   /// Create a ZExt, BitCast, or Trunc for int -> int casts.
604   static CastInst *CreateIntegerCast(
605     Value *S,                ///< The pointer value to be casted (operand 0)
606     Type *Ty,          ///< The type to which cast should be made
607     bool isSigned,           ///< Whether to regard S as signed or not
608     const Twine &Name = "", ///< Name for the instruction
609     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
610   );
611 
612   /// Create a ZExt, BitCast, or Trunc for int -> int casts.
613   static CastInst *CreateIntegerCast(
614     Value *S,                ///< The integer value to be casted (operand 0)
615     Type *Ty,          ///< The integer type to which operand is casted
616     bool isSigned,           ///< Whether to regard S as signed or not
617     const Twine &Name, ///< The name for the instruction
618     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
619   );
620 
621   /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
622   static CastInst *CreateFPCast(
623     Value *S,                ///< The floating point value to be casted
624     Type *Ty,          ///< The floating point type to cast to
625     const Twine &Name = "", ///< Name for the instruction
626     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
627   );
628 
629   /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
630   static CastInst *CreateFPCast(
631     Value *S,                ///< The floating point value to be casted
632     Type *Ty,          ///< The floating point type to cast to
633     const Twine &Name, ///< The name for the instruction
634     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
635   );
636 
637   /// Create a Trunc or BitCast cast instruction
638   static CastInst *CreateTruncOrBitCast(
639     Value *S,                ///< The value to be casted (operand 0)
640     Type *Ty,          ///< The type to which cast should be made
641     const Twine &Name = "", ///< Name for the instruction
642     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
643   );
644 
645   /// Create a Trunc or BitCast cast instruction
646   static CastInst *CreateTruncOrBitCast(
647     Value *S,                ///< The value to be casted (operand 0)
648     Type *Ty,          ///< The type to which operand is casted
649     const Twine &Name, ///< The name for the instruction
650     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
651   );
652 
653   /// Check whether a bitcast between these types is valid
654   static bool isBitCastable(
655     Type *SrcTy, ///< The Type from which the value should be cast.
656     Type *DestTy ///< The Type to which the value should be cast.
657   );
658 
659   /// Check whether a bitcast, inttoptr, or ptrtoint cast between these
660   /// types is valid and a no-op.
661   ///
662   /// This ensures that any pointer<->integer cast has enough bits in the
663   /// integer and any other cast is a bitcast.
664   static bool isBitOrNoopPointerCastable(
665       Type *SrcTy,  ///< The Type from which the value should be cast.
666       Type *DestTy, ///< The Type to which the value should be cast.
667       const DataLayout &DL);
668 
669   /// Returns the opcode necessary to cast Val into Ty using usual casting
670   /// rules.
671   /// Infer the opcode for cast operand and type
672   static Instruction::CastOps getCastOpcode(
673     const Value *Val, ///< The value to cast
674     bool SrcIsSigned, ///< Whether to treat the source as signed
675     Type *Ty,   ///< The Type to which the value should be casted
676     bool DstIsSigned  ///< Whether to treate the dest. as signed
677   );
678 
679   /// There are several places where we need to know if a cast instruction
680   /// only deals with integer source and destination types. To simplify that
681   /// logic, this method is provided.
682   /// @returns true iff the cast has only integral typed operand and dest type.
683   /// Determine if this is an integer-only cast.
684   bool isIntegerCast() const;
685 
686   /// A no-op cast is one that can be effected without changing any bits.
687   /// It implies that the source and destination types are the same size. The
688   /// DataLayout argument is to determine the pointer size when examining casts
689   /// involving Integer and Pointer types. They are no-op casts if the integer
690   /// is the same size as the pointer. However, pointer size varies with
691   /// platform.  Note that a precondition of this method is that the cast is
692   /// legal - i.e. the instruction formed with these operands would verify.
693   static bool isNoopCast(
694     Instruction::CastOps Opcode, ///< Opcode of cast
695     Type *SrcTy,         ///< SrcTy of cast
696     Type *DstTy,         ///< DstTy of cast
697     const DataLayout &DL ///< DataLayout to get the Int Ptr type from.
698   );
699 
700   /// Determine if this cast is a no-op cast.
701   ///
702   /// \param DL is the DataLayout to determine pointer size.
703   bool isNoopCast(const DataLayout &DL) const;
704 
705   /// Determine how a pair of casts can be eliminated, if they can be at all.
706   /// This is a helper function for both CastInst and ConstantExpr.
707   /// @returns 0 if the CastInst pair can't be eliminated, otherwise
708   /// returns Instruction::CastOps value for a cast that can replace
709   /// the pair, casting SrcTy to DstTy.
710   /// Determine if a cast pair is eliminable
711   static unsigned isEliminableCastPair(
712     Instruction::CastOps firstOpcode,  ///< Opcode of first cast
713     Instruction::CastOps secondOpcode, ///< Opcode of second cast
714     Type *SrcTy, ///< SrcTy of 1st cast
715     Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
716     Type *DstTy, ///< DstTy of 2nd cast
717     Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
718     Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
719     Type *DstIntPtrTy  ///< Integer type corresponding to Ptr DstTy, or null
720   );
721 
722   /// Return the opcode of this CastInst
723   Instruction::CastOps getOpcode() const {
724     return Instruction::CastOps(Instruction::getOpcode());
725   }
726 
727   /// Return the source type, as a convenience
728   Type* getSrcTy() const { return getOperand(0)->getType(); }
729   /// Return the destination type, as a convenience
730   Type* getDestTy() const { return getType(); }
731 
732   /// This method can be used to determine if a cast from SrcTy to DstTy using
733   /// Opcode op is valid or not.
734   /// @returns true iff the proposed cast is valid.
735   /// Determine if a cast is valid without creating one.
736   static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy);
737   static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
738     return castIsValid(op, S->getType(), DstTy);
739   }
740 
741   /// Methods for support type inquiry through isa, cast, and dyn_cast:
742   static bool classof(const Instruction *I) {
743     return I->isCast();
744   }
745   static bool classof(const Value *V) {
746     return isa<Instruction>(V) && classof(cast<Instruction>(V));
747   }
748 };
749 
750 /// Instruction that can have a nneg flag (only zext).
751 class PossiblyNonNegInst : public CastInst {
752 public:
753   enum { NonNeg = (1 << 0) };
754 
755   static bool classof(const Instruction *I) {
756     return I->getOpcode() == Instruction::ZExt;
757   }
758 
759   static bool classof(const Value *V) {
760     return isa<Instruction>(V) && classof(cast<Instruction>(V));
761   }
762 };
763 
764 //===----------------------------------------------------------------------===//
765 //                               CmpInst Class
766 //===----------------------------------------------------------------------===//
767 
768 /// This class is the base class for the comparison instructions.
769 /// Abstract base class of comparison instructions.
770 class CmpInst : public Instruction {
771 public:
772   /// This enumeration lists the possible predicates for CmpInst subclasses.
773   /// Values in the range 0-31 are reserved for FCmpInst, while values in the
774   /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
775   /// predicate values are not overlapping between the classes.
776   ///
777   /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
778   /// FCMP_* values. Changing the bit patterns requires a potential change to
779   /// those passes.
780   enum Predicate : unsigned {
781     // Opcode            U L G E    Intuitive operation
782     FCMP_FALSE = 0, ///< 0 0 0 0    Always false (always folded)
783     FCMP_OEQ = 1,   ///< 0 0 0 1    True if ordered and equal
784     FCMP_OGT = 2,   ///< 0 0 1 0    True if ordered and greater than
785     FCMP_OGE = 3,   ///< 0 0 1 1    True if ordered and greater than or equal
786     FCMP_OLT = 4,   ///< 0 1 0 0    True if ordered and less than
787     FCMP_OLE = 5,   ///< 0 1 0 1    True if ordered and less than or equal
788     FCMP_ONE = 6,   ///< 0 1 1 0    True if ordered and operands are unequal
789     FCMP_ORD = 7,   ///< 0 1 1 1    True if ordered (no nans)
790     FCMP_UNO = 8,   ///< 1 0 0 0    True if unordered: isnan(X) | isnan(Y)
791     FCMP_UEQ = 9,   ///< 1 0 0 1    True if unordered or equal
792     FCMP_UGT = 10,  ///< 1 0 1 0    True if unordered or greater than
793     FCMP_UGE = 11,  ///< 1 0 1 1    True if unordered, greater than, or equal
794     FCMP_ULT = 12,  ///< 1 1 0 0    True if unordered or less than
795     FCMP_ULE = 13,  ///< 1 1 0 1    True if unordered, less than, or equal
796     FCMP_UNE = 14,  ///< 1 1 1 0    True if unordered or not equal
797     FCMP_TRUE = 15, ///< 1 1 1 1    Always true (always folded)
798     FIRST_FCMP_PREDICATE = FCMP_FALSE,
799     LAST_FCMP_PREDICATE = FCMP_TRUE,
800     BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
801     ICMP_EQ = 32,  ///< equal
802     ICMP_NE = 33,  ///< not equal
803     ICMP_UGT = 34, ///< unsigned greater than
804     ICMP_UGE = 35, ///< unsigned greater or equal
805     ICMP_ULT = 36, ///< unsigned less than
806     ICMP_ULE = 37, ///< unsigned less or equal
807     ICMP_SGT = 38, ///< signed greater than
808     ICMP_SGE = 39, ///< signed greater or equal
809     ICMP_SLT = 40, ///< signed less than
810     ICMP_SLE = 41, ///< signed less or equal
811     FIRST_ICMP_PREDICATE = ICMP_EQ,
812     LAST_ICMP_PREDICATE = ICMP_SLE,
813     BAD_ICMP_PREDICATE = ICMP_SLE + 1
814   };
815   using PredicateField =
816       Bitfield::Element<Predicate, 0, 6, LAST_ICMP_PREDICATE>;
817 
818   /// Returns the sequence of all FCmp predicates.
819   static auto FCmpPredicates() {
820     return enum_seq_inclusive(Predicate::FIRST_FCMP_PREDICATE,
821                               Predicate::LAST_FCMP_PREDICATE,
822                               force_iteration_on_noniterable_enum);
823   }
824 
825   /// Returns the sequence of all ICmp predicates.
826   static auto ICmpPredicates() {
827     return enum_seq_inclusive(Predicate::FIRST_ICMP_PREDICATE,
828                               Predicate::LAST_ICMP_PREDICATE,
829                               force_iteration_on_noniterable_enum);
830   }
831 
832 protected:
833   CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
834           Value *LHS, Value *RHS, const Twine &Name = "",
835           Instruction *InsertBefore = nullptr,
836           Instruction *FlagsSource = nullptr);
837 
838   CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
839           Value *LHS, Value *RHS, const Twine &Name,
840           BasicBlock *InsertAtEnd);
841 
842 public:
843   // allocate space for exactly two operands
844   void *operator new(size_t S) { return User::operator new(S, 2); }
845   void operator delete(void *Ptr) { User::operator delete(Ptr); }
846 
847   /// Construct a compare instruction, given the opcode, the predicate and
848   /// the two operands.  Optionally (if InstBefore is specified) insert the
849   /// instruction into a BasicBlock right before the specified instruction.
850   /// The specified Instruction is allowed to be a dereferenced end iterator.
851   /// Create a CmpInst
852   static CmpInst *Create(OtherOps Op,
853                          Predicate predicate, Value *S1,
854                          Value *S2, const Twine &Name = "",
855                          Instruction *InsertBefore = nullptr);
856 
857   /// Construct a compare instruction, given the opcode, the predicate and the
858   /// two operands.  Also automatically insert this instruction to the end of
859   /// the BasicBlock specified.
860   /// Create a CmpInst
861   static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1,
862                          Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
863 
864   /// Get the opcode casted to the right type
865   OtherOps getOpcode() const {
866     return static_cast<OtherOps>(Instruction::getOpcode());
867   }
868 
869   /// Return the predicate for this instruction.
870   Predicate getPredicate() const { return getSubclassData<PredicateField>(); }
871 
872   /// Set the predicate for this instruction to the specified value.
873   void setPredicate(Predicate P) { setSubclassData<PredicateField>(P); }
874 
875   static bool isFPPredicate(Predicate P) {
876     static_assert(FIRST_FCMP_PREDICATE == 0,
877                   "FIRST_FCMP_PREDICATE is required to be 0");
878     return P <= LAST_FCMP_PREDICATE;
879   }
880 
881   static bool isIntPredicate(Predicate P) {
882     return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
883   }
884 
885   static StringRef getPredicateName(Predicate P);
886 
887   bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
888   bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
889 
890   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
891   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
892   /// @returns the inverse predicate for the instruction's current predicate.
893   /// Return the inverse of the instruction's predicate.
894   Predicate getInversePredicate() const {
895     return getInversePredicate(getPredicate());
896   }
897 
898   /// Returns the ordered variant of a floating point compare.
899   ///
900   /// For example, UEQ -> OEQ, ULT -> OLT, OEQ -> OEQ
901   static Predicate getOrderedPredicate(Predicate Pred) {
902     return static_cast<Predicate>(Pred & FCMP_ORD);
903   }
904 
905   Predicate getOrderedPredicate() const {
906     return getOrderedPredicate(getPredicate());
907   }
908 
909   /// Returns the unordered variant of a floating point compare.
910   ///
911   /// For example, OEQ -> UEQ, OLT -> ULT, OEQ -> UEQ
912   static Predicate getUnorderedPredicate(Predicate Pred) {
913     return static_cast<Predicate>(Pred | FCMP_UNO);
914   }
915 
916   Predicate getUnorderedPredicate() const {
917     return getUnorderedPredicate(getPredicate());
918   }
919 
920   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
921   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
922   /// @returns the inverse predicate for predicate provided in \p pred.
923   /// Return the inverse of a given predicate
924   static Predicate getInversePredicate(Predicate pred);
925 
926   /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
927   ///              OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
928   /// @returns the predicate that would be the result of exchanging the two
929   /// operands of the CmpInst instruction without changing the result
930   /// produced.
931   /// Return the predicate as if the operands were swapped
932   Predicate getSwappedPredicate() const {
933     return getSwappedPredicate(getPredicate());
934   }
935 
936   /// This is a static version that you can use without an instruction
937   /// available.
938   /// Return the predicate as if the operands were swapped.
939   static Predicate getSwappedPredicate(Predicate pred);
940 
941   /// This is a static version that you can use without an instruction
942   /// available.
943   /// @returns true if the comparison predicate is strict, false otherwise.
944   static bool isStrictPredicate(Predicate predicate);
945 
946   /// @returns true if the comparison predicate is strict, false otherwise.
947   /// Determine if this instruction is using an strict comparison predicate.
948   bool isStrictPredicate() const { return isStrictPredicate(getPredicate()); }
949 
950   /// This is a static version that you can use without an instruction
951   /// available.
952   /// @returns true if the comparison predicate is non-strict, false otherwise.
953   static bool isNonStrictPredicate(Predicate predicate);
954 
955   /// @returns true if the comparison predicate is non-strict, false otherwise.
956   /// Determine if this instruction is using an non-strict comparison predicate.
957   bool isNonStrictPredicate() const {
958     return isNonStrictPredicate(getPredicate());
959   }
960 
961   /// For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
962   /// Returns the strict version of non-strict comparisons.
963   Predicate getStrictPredicate() const {
964     return getStrictPredicate(getPredicate());
965   }
966 
967   /// This is a static version that you can use without an instruction
968   /// available.
969   /// @returns the strict version of comparison provided in \p pred.
970   /// If \p pred is not a strict comparison predicate, returns \p pred.
971   /// Returns the strict version of non-strict comparisons.
972   static Predicate getStrictPredicate(Predicate pred);
973 
974   /// For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
975   /// Returns the non-strict version of strict comparisons.
976   Predicate getNonStrictPredicate() const {
977     return getNonStrictPredicate(getPredicate());
978   }
979 
980   /// This is a static version that you can use without an instruction
981   /// available.
982   /// @returns the non-strict version of comparison provided in \p pred.
983   /// If \p pred is not a strict comparison predicate, returns \p pred.
984   /// Returns the non-strict version of strict comparisons.
985   static Predicate getNonStrictPredicate(Predicate pred);
986 
987   /// This is a static version that you can use without an instruction
988   /// available.
989   /// Return the flipped strictness of predicate
990   static Predicate getFlippedStrictnessPredicate(Predicate pred);
991 
992   /// For predicate of kind "is X or equal to 0" returns the predicate "is X".
993   /// For predicate of kind "is X" returns the predicate "is X or equal to 0".
994   /// does not support other kind of predicates.
995   /// @returns the predicate that does not contains is equal to zero if
996   /// it had and vice versa.
997   /// Return the flipped strictness of predicate
998   Predicate getFlippedStrictnessPredicate() const {
999     return getFlippedStrictnessPredicate(getPredicate());
1000   }
1001 
1002   /// Provide more efficient getOperand methods.
1003   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1004 
1005   /// This is just a convenience that dispatches to the subclasses.
1006   /// Swap the operands and adjust predicate accordingly to retain
1007   /// the same comparison.
1008   void swapOperands();
1009 
1010   /// This is just a convenience that dispatches to the subclasses.
1011   /// Determine if this CmpInst is commutative.
1012   bool isCommutative() const;
1013 
1014   /// Determine if this is an equals/not equals predicate.
1015   /// This is a static version that you can use without an instruction
1016   /// available.
1017   static bool isEquality(Predicate pred);
1018 
1019   /// Determine if this is an equals/not equals predicate.
1020   bool isEquality() const { return isEquality(getPredicate()); }
1021 
1022   /// Return true if the predicate is relational (not EQ or NE).
1023   static bool isRelational(Predicate P) { return !isEquality(P); }
1024 
1025   /// Return true if the predicate is relational (not EQ or NE).
1026   bool isRelational() const { return !isEquality(); }
1027 
1028   /// @returns true if the comparison is signed, false otherwise.
1029   /// Determine if this instruction is using a signed comparison.
1030   bool isSigned() const {
1031     return isSigned(getPredicate());
1032   }
1033 
1034   /// @returns true if the comparison is unsigned, false otherwise.
1035   /// Determine if this instruction is using an unsigned comparison.
1036   bool isUnsigned() const {
1037     return isUnsigned(getPredicate());
1038   }
1039 
1040   /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1041   /// @returns the signed version of the unsigned predicate pred.
1042   /// return the signed version of a predicate
1043   static Predicate getSignedPredicate(Predicate pred);
1044 
1045   /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1046   /// @returns the signed version of the predicate for this instruction (which
1047   /// has to be an unsigned predicate).
1048   /// return the signed version of a predicate
1049   Predicate getSignedPredicate() {
1050     return getSignedPredicate(getPredicate());
1051   }
1052 
1053   /// For example, SLT->ULT, SLE->ULE, SGT->UGT, SGE->UGE, ULT->Failed assert
1054   /// @returns the unsigned version of the signed predicate pred.
1055   static Predicate getUnsignedPredicate(Predicate pred);
1056 
1057   /// For example, SLT->ULT, SLE->ULE, SGT->UGT, SGE->UGE, ULT->Failed assert
1058   /// @returns the unsigned version of the predicate for this instruction (which
1059   /// has to be an signed predicate).
1060   /// return the unsigned version of a predicate
1061   Predicate getUnsignedPredicate() {
1062     return getUnsignedPredicate(getPredicate());
1063   }
1064 
1065   /// For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->Failed assert
1066   /// @returns the unsigned version of the signed predicate pred or
1067   ///          the signed version of the signed predicate pred.
1068   static Predicate getFlippedSignednessPredicate(Predicate pred);
1069 
1070   /// For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->Failed assert
1071   /// @returns the unsigned version of the signed predicate pred or
1072   ///          the signed version of the signed predicate pred.
1073   Predicate getFlippedSignednessPredicate() {
1074     return getFlippedSignednessPredicate(getPredicate());
1075   }
1076 
1077   /// This is just a convenience.
1078   /// Determine if this is true when both operands are the same.
1079   bool isTrueWhenEqual() const {
1080     return isTrueWhenEqual(getPredicate());
1081   }
1082 
1083   /// This is just a convenience.
1084   /// Determine if this is false when both operands are the same.
1085   bool isFalseWhenEqual() const {
1086     return isFalseWhenEqual(getPredicate());
1087   }
1088 
1089   /// @returns true if the predicate is unsigned, false otherwise.
1090   /// Determine if the predicate is an unsigned operation.
1091   static bool isUnsigned(Predicate predicate);
1092 
1093   /// @returns true if the predicate is signed, false otherwise.
1094   /// Determine if the predicate is an signed operation.
1095   static bool isSigned(Predicate predicate);
1096 
1097   /// Determine if the predicate is an ordered operation.
1098   static bool isOrdered(Predicate predicate);
1099 
1100   /// Determine if the predicate is an unordered operation.
1101   static bool isUnordered(Predicate predicate);
1102 
1103   /// Determine if the predicate is true when comparing a value with itself.
1104   static bool isTrueWhenEqual(Predicate predicate);
1105 
1106   /// Determine if the predicate is false when comparing a value with itself.
1107   static bool isFalseWhenEqual(Predicate predicate);
1108 
1109   /// Determine if Pred1 implies Pred2 is true when two compares have matching
1110   /// operands.
1111   static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2);
1112 
1113   /// Determine if Pred1 implies Pred2 is false when two compares have matching
1114   /// operands.
1115   static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2);
1116 
1117   /// Methods for support type inquiry through isa, cast, and dyn_cast:
1118   static bool classof(const Instruction *I) {
1119     return I->getOpcode() == Instruction::ICmp ||
1120            I->getOpcode() == Instruction::FCmp;
1121   }
1122   static bool classof(const Value *V) {
1123     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1124   }
1125 
1126   /// Create a result type for fcmp/icmp
1127   static Type* makeCmpResultType(Type* opnd_type) {
1128     if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1129       return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1130                              vt->getElementCount());
1131     }
1132     return Type::getInt1Ty(opnd_type->getContext());
1133   }
1134 
1135 private:
1136   // Shadow Value::setValueSubclassData with a private forwarding method so that
1137   // subclasses cannot accidentally use it.
1138   void setValueSubclassData(unsigned short D) {
1139     Value::setValueSubclassData(D);
1140   }
1141 };
1142 
1143 // FIXME: these are redundant if CmpInst < BinaryOperator
1144 template <>
1145 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1146 };
1147 
1148 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1149 
1150 raw_ostream &operator<<(raw_ostream &OS, CmpInst::Predicate Pred);
1151 
1152 /// A lightweight accessor for an operand bundle meant to be passed
1153 /// around by value.
1154 struct OperandBundleUse {
1155   ArrayRef<Use> Inputs;
1156 
1157   OperandBundleUse() = default;
1158   explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1159       : Inputs(Inputs), Tag(Tag) {}
1160 
1161   /// Return true if the operand at index \p Idx in this operand bundle
1162   /// has the attribute A.
1163   bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
1164     if (isDeoptOperandBundle())
1165       if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
1166         return Inputs[Idx]->getType()->isPointerTy();
1167 
1168     // Conservative answer:  no operands have any attributes.
1169     return false;
1170   }
1171 
1172   /// Return the tag of this operand bundle as a string.
1173   StringRef getTagName() const {
1174     return Tag->getKey();
1175   }
1176 
1177   /// Return the tag of this operand bundle as an integer.
1178   ///
1179   /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1180   /// and this function returns the unique integer getOrInsertBundleTag
1181   /// associated the tag of this operand bundle to.
1182   uint32_t getTagID() const {
1183     return Tag->getValue();
1184   }
1185 
1186   /// Return true if this is a "deopt" operand bundle.
1187   bool isDeoptOperandBundle() const {
1188     return getTagID() == LLVMContext::OB_deopt;
1189   }
1190 
1191   /// Return true if this is a "funclet" operand bundle.
1192   bool isFuncletOperandBundle() const {
1193     return getTagID() == LLVMContext::OB_funclet;
1194   }
1195 
1196   /// Return true if this is a "cfguardtarget" operand bundle.
1197   bool isCFGuardTargetOperandBundle() const {
1198     return getTagID() == LLVMContext::OB_cfguardtarget;
1199   }
1200 
1201 private:
1202   /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1203   StringMapEntry<uint32_t> *Tag;
1204 };
1205 
1206 /// A container for an operand bundle being viewed as a set of values
1207 /// rather than a set of uses.
1208 ///
1209 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1210 /// so it is possible to create and pass around "self-contained" instances of
1211 /// OperandBundleDef and ConstOperandBundleDef.
1212 template <typename InputTy> class OperandBundleDefT {
1213   std::string Tag;
1214   std::vector<InputTy> Inputs;
1215 
1216 public:
1217   explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1218       : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1219   explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
1220       : Tag(std::move(Tag)), Inputs(Inputs) {}
1221 
1222   explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1223     Tag = std::string(OBU.getTagName());
1224     llvm::append_range(Inputs, OBU.Inputs);
1225   }
1226 
1227   ArrayRef<InputTy> inputs() const { return Inputs; }
1228 
1229   using input_iterator = typename std::vector<InputTy>::const_iterator;
1230 
1231   size_t input_size() const { return Inputs.size(); }
1232   input_iterator input_begin() const { return Inputs.begin(); }
1233   input_iterator input_end() const { return Inputs.end(); }
1234 
1235   StringRef getTag() const { return Tag; }
1236 };
1237 
1238 using OperandBundleDef = OperandBundleDefT<Value *>;
1239 using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
1240 
1241 //===----------------------------------------------------------------------===//
1242 //                               CallBase Class
1243 //===----------------------------------------------------------------------===//
1244 
1245 /// Base class for all callable instructions (InvokeInst and CallInst)
1246 /// Holds everything related to calling a function.
1247 ///
1248 /// All call-like instructions are required to use a common operand layout:
1249 /// - Zero or more arguments to the call,
1250 /// - Zero or more operand bundles with zero or more operand inputs each
1251 ///   bundle,
1252 /// - Zero or more subclass controlled operands
1253 /// - The called function.
1254 ///
1255 /// This allows this base class to easily access the called function and the
1256 /// start of the arguments without knowing how many other operands a particular
1257 /// subclass requires. Note that accessing the end of the argument list isn't
1258 /// as cheap as most other operations on the base class.
1259 class CallBase : public Instruction {
1260 protected:
1261   // The first two bits are reserved by CallInst for fast retrieval,
1262   using CallInstReservedField = Bitfield::Element<unsigned, 0, 2>;
1263   using CallingConvField =
1264       Bitfield::Element<CallingConv::ID, CallInstReservedField::NextBit, 10,
1265                         CallingConv::MaxID>;
1266   static_assert(
1267       Bitfield::areContiguous<CallInstReservedField, CallingConvField>(),
1268       "Bitfields must be contiguous");
1269 
1270   /// The last operand is the called operand.
1271   static constexpr int CalledOperandOpEndIdx = -1;
1272 
1273   AttributeList Attrs; ///< parameter attributes for callable
1274   FunctionType *FTy;
1275 
1276   template <class... ArgsTy>
1277   CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
1278       : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {}
1279 
1280   using Instruction::Instruction;
1281 
1282   bool hasDescriptor() const { return Value::HasDescriptor; }
1283 
1284   unsigned getNumSubclassExtraOperands() const {
1285     switch (getOpcode()) {
1286     case Instruction::Call:
1287       return 0;
1288     case Instruction::Invoke:
1289       return 2;
1290     case Instruction::CallBr:
1291       return getNumSubclassExtraOperandsDynamic();
1292     }
1293     llvm_unreachable("Invalid opcode!");
1294   }
1295 
1296   /// Get the number of extra operands for instructions that don't have a fixed
1297   /// number of extra operands.
1298   unsigned getNumSubclassExtraOperandsDynamic() const;
1299 
1300 public:
1301   using Instruction::getContext;
1302 
1303   /// Create a clone of \p CB with a different set of operand bundles and
1304   /// insert it before \p InsertPt.
1305   ///
1306   /// The returned call instruction is identical \p CB in every way except that
1307   /// the operand bundles for the new instruction are set to the operand bundles
1308   /// in \p Bundles.
1309   static CallBase *Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
1310                           Instruction *InsertPt = nullptr);
1311 
1312   /// Create a clone of \p CB with the operand bundle with the tag matching
1313   /// \p Bundle's tag replaced with Bundle, and insert it before \p InsertPt.
1314   ///
1315   /// The returned call instruction is identical \p CI in every way except that
1316   /// the specified operand bundle has been replaced.
1317   static CallBase *Create(CallBase *CB,
1318                           OperandBundleDef Bundle,
1319                           Instruction *InsertPt = nullptr);
1320 
1321   /// Create a clone of \p CB with operand bundle \p OB added.
1322   static CallBase *addOperandBundle(CallBase *CB, uint32_t ID,
1323                                     OperandBundleDef OB,
1324                                     Instruction *InsertPt = nullptr);
1325 
1326   /// Create a clone of \p CB with operand bundle \p ID removed.
1327   static CallBase *removeOperandBundle(CallBase *CB, uint32_t ID,
1328                                        Instruction *InsertPt = nullptr);
1329 
1330   static bool classof(const Instruction *I) {
1331     return I->getOpcode() == Instruction::Call ||
1332            I->getOpcode() == Instruction::Invoke ||
1333            I->getOpcode() == Instruction::CallBr;
1334   }
1335   static bool classof(const Value *V) {
1336     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1337   }
1338 
1339   FunctionType *getFunctionType() const { return FTy; }
1340 
1341   void mutateFunctionType(FunctionType *FTy) {
1342     Value::mutateType(FTy->getReturnType());
1343     this->FTy = FTy;
1344   }
1345 
1346   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1347 
1348   /// data_operands_begin/data_operands_end - Return iterators iterating over
1349   /// the call / invoke argument list and bundle operands.  For invokes, this is
1350   /// the set of instruction operands except the invoke target and the two
1351   /// successor blocks; and for calls this is the set of instruction operands
1352   /// except the call target.
1353   User::op_iterator data_operands_begin() { return op_begin(); }
1354   User::const_op_iterator data_operands_begin() const {
1355     return const_cast<CallBase *>(this)->data_operands_begin();
1356   }
1357   User::op_iterator data_operands_end() {
1358     // Walk from the end of the operands over the called operand and any
1359     // subclass operands.
1360     return op_end() - getNumSubclassExtraOperands() - 1;
1361   }
1362   User::const_op_iterator data_operands_end() const {
1363     return const_cast<CallBase *>(this)->data_operands_end();
1364   }
1365   iterator_range<User::op_iterator> data_ops() {
1366     return make_range(data_operands_begin(), data_operands_end());
1367   }
1368   iterator_range<User::const_op_iterator> data_ops() const {
1369     return make_range(data_operands_begin(), data_operands_end());
1370   }
1371   bool data_operands_empty() const {
1372     return data_operands_end() == data_operands_begin();
1373   }
1374   unsigned data_operands_size() const {
1375     return std::distance(data_operands_begin(), data_operands_end());
1376   }
1377 
1378   bool isDataOperand(const Use *U) const {
1379     assert(this == U->getUser() &&
1380            "Only valid to query with a use of this instruction!");
1381     return data_operands_begin() <= U && U < data_operands_end();
1382   }
1383   bool isDataOperand(Value::const_user_iterator UI) const {
1384     return isDataOperand(&UI.getUse());
1385   }
1386 
1387   /// Given a value use iterator, return the data operand corresponding to it.
1388   /// Iterator must actually correspond to a data operand.
1389   unsigned getDataOperandNo(Value::const_user_iterator UI) const {
1390     return getDataOperandNo(&UI.getUse());
1391   }
1392 
1393   /// Given a use for a data operand, get the data operand number that
1394   /// corresponds to it.
1395   unsigned getDataOperandNo(const Use *U) const {
1396     assert(isDataOperand(U) && "Data operand # out of range!");
1397     return U - data_operands_begin();
1398   }
1399 
1400   /// Return the iterator pointing to the beginning of the argument list.
1401   User::op_iterator arg_begin() { return op_begin(); }
1402   User::const_op_iterator arg_begin() const {
1403     return const_cast<CallBase *>(this)->arg_begin();
1404   }
1405 
1406   /// Return the iterator pointing to the end of the argument list.
1407   User::op_iterator arg_end() {
1408     // From the end of the data operands, walk backwards past the bundle
1409     // operands.
1410     return data_operands_end() - getNumTotalBundleOperands();
1411   }
1412   User::const_op_iterator arg_end() const {
1413     return const_cast<CallBase *>(this)->arg_end();
1414   }
1415 
1416   /// Iteration adapter for range-for loops.
1417   iterator_range<User::op_iterator> args() {
1418     return make_range(arg_begin(), arg_end());
1419   }
1420   iterator_range<User::const_op_iterator> args() const {
1421     return make_range(arg_begin(), arg_end());
1422   }
1423   bool arg_empty() const { return arg_end() == arg_begin(); }
1424   unsigned arg_size() const { return arg_end() - arg_begin(); }
1425 
1426   Value *getArgOperand(unsigned i) const {
1427     assert(i < arg_size() && "Out of bounds!");
1428     return getOperand(i);
1429   }
1430 
1431   void setArgOperand(unsigned i, Value *v) {
1432     assert(i < arg_size() && "Out of bounds!");
1433     setOperand(i, v);
1434   }
1435 
1436   /// Wrappers for getting the \c Use of a call argument.
1437   const Use &getArgOperandUse(unsigned i) const {
1438     assert(i < arg_size() && "Out of bounds!");
1439     return User::getOperandUse(i);
1440   }
1441   Use &getArgOperandUse(unsigned i) {
1442     assert(i < arg_size() && "Out of bounds!");
1443     return User::getOperandUse(i);
1444   }
1445 
1446   bool isArgOperand(const Use *U) const {
1447     assert(this == U->getUser() &&
1448            "Only valid to query with a use of this instruction!");
1449     return arg_begin() <= U && U < arg_end();
1450   }
1451   bool isArgOperand(Value::const_user_iterator UI) const {
1452     return isArgOperand(&UI.getUse());
1453   }
1454 
1455   /// Given a use for a arg operand, get the arg operand number that
1456   /// corresponds to it.
1457   unsigned getArgOperandNo(const Use *U) const {
1458     assert(isArgOperand(U) && "Arg operand # out of range!");
1459     return U - arg_begin();
1460   }
1461 
1462   /// Given a value use iterator, return the arg operand number corresponding to
1463   /// it. Iterator must actually correspond to a data operand.
1464   unsigned getArgOperandNo(Value::const_user_iterator UI) const {
1465     return getArgOperandNo(&UI.getUse());
1466   }
1467 
1468   /// Returns true if this CallSite passes the given Value* as an argument to
1469   /// the called function.
1470   bool hasArgument(const Value *V) const {
1471     return llvm::is_contained(args(), V);
1472   }
1473 
1474   Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); }
1475 
1476   const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); }
1477   Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); }
1478 
1479   /// Returns the function called, or null if this is an indirect function
1480   /// invocation or the function signature does not match the call signature.
1481   Function *getCalledFunction() const {
1482     if (auto *F = dyn_cast_or_null<Function>(getCalledOperand()))
1483       if (F->getValueType() == getFunctionType())
1484         return F;
1485     return nullptr;
1486   }
1487 
1488   /// Return true if the callsite is an indirect call.
1489   bool isIndirectCall() const;
1490 
1491   /// Determine whether the passed iterator points to the callee operand's Use.
1492   bool isCallee(Value::const_user_iterator UI) const {
1493     return isCallee(&UI.getUse());
1494   }
1495 
1496   /// Determine whether this Use is the callee operand's Use.
1497   bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; }
1498 
1499   /// Helper to get the caller (the parent function).
1500   Function *getCaller();
1501   const Function *getCaller() const {
1502     return const_cast<CallBase *>(this)->getCaller();
1503   }
1504 
1505   /// Tests if this call site must be tail call optimized. Only a CallInst can
1506   /// be tail call optimized.
1507   bool isMustTailCall() const;
1508 
1509   /// Tests if this call site is marked as a tail call.
1510   bool isTailCall() const;
1511 
1512   /// Returns the intrinsic ID of the intrinsic called or
1513   /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if
1514   /// this is an indirect call.
1515   Intrinsic::ID getIntrinsicID() const;
1516 
1517   void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; }
1518 
1519   /// Sets the function called, including updating the function type.
1520   void setCalledFunction(Function *Fn) {
1521     setCalledFunction(Fn->getFunctionType(), Fn);
1522   }
1523 
1524   /// Sets the function called, including updating the function type.
1525   void setCalledFunction(FunctionCallee Fn) {
1526     setCalledFunction(Fn.getFunctionType(), Fn.getCallee());
1527   }
1528 
1529   /// Sets the function called, including updating to the specified function
1530   /// type.
1531   void setCalledFunction(FunctionType *FTy, Value *Fn) {
1532     this->FTy = FTy;
1533     // This function doesn't mutate the return type, only the function
1534     // type. Seems broken, but I'm just gonna stick an assert in for now.
1535     assert(getType() == FTy->getReturnType());
1536     setCalledOperand(Fn);
1537   }
1538 
1539   CallingConv::ID getCallingConv() const {
1540     return getSubclassData<CallingConvField>();
1541   }
1542 
1543   void setCallingConv(CallingConv::ID CC) {
1544     setSubclassData<CallingConvField>(CC);
1545   }
1546 
1547   /// Check if this call is an inline asm statement.
1548   bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); }
1549 
1550   /// \name Attribute API
1551   ///
1552   /// These methods access and modify attributes on this call (including
1553   /// looking through to the attributes on the called function when necessary).
1554   ///@{
1555 
1556   /// Return the parameter attributes for this call.
1557   ///
1558   AttributeList getAttributes() const { return Attrs; }
1559 
1560   /// Set the parameter attributes for this call.
1561   ///
1562   void setAttributes(AttributeList A) { Attrs = A; }
1563 
1564   /// Determine whether this call has the given attribute. If it does not
1565   /// then determine if the called function has the attribute, but only if
1566   /// the attribute is allowed for the call.
1567   bool hasFnAttr(Attribute::AttrKind Kind) const {
1568     assert(Kind != Attribute::NoBuiltin &&
1569            "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin");
1570     return hasFnAttrImpl(Kind);
1571   }
1572 
1573   /// Determine whether this call has the given attribute. If it does not
1574   /// then determine if the called function has the attribute, but only if
1575   /// the attribute is allowed for the call.
1576   bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); }
1577 
1578   // TODO: remove non-AtIndex versions of these methods.
1579   /// adds the attribute to the list of attributes.
1580   void addAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
1581     Attrs = Attrs.addAttributeAtIndex(getContext(), i, Kind);
1582   }
1583 
1584   /// adds the attribute to the list of attributes.
1585   void addAttributeAtIndex(unsigned i, Attribute Attr) {
1586     Attrs = Attrs.addAttributeAtIndex(getContext(), i, Attr);
1587   }
1588 
1589   /// Adds the attribute to the function.
1590   void addFnAttr(Attribute::AttrKind Kind) {
1591     Attrs = Attrs.addFnAttribute(getContext(), Kind);
1592   }
1593 
1594   /// Adds the attribute to the function.
1595   void addFnAttr(Attribute Attr) {
1596     Attrs = Attrs.addFnAttribute(getContext(), Attr);
1597   }
1598 
1599   /// Adds the attribute to the return value.
1600   void addRetAttr(Attribute::AttrKind Kind) {
1601     Attrs = Attrs.addRetAttribute(getContext(), Kind);
1602   }
1603 
1604   /// Adds the attribute to the return value.
1605   void addRetAttr(Attribute Attr) {
1606     Attrs = Attrs.addRetAttribute(getContext(), Attr);
1607   }
1608 
1609   /// Adds the attribute to the indicated argument
1610   void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1611     assert(ArgNo < arg_size() && "Out of bounds");
1612     Attrs = Attrs.addParamAttribute(getContext(), ArgNo, Kind);
1613   }
1614 
1615   /// Adds the attribute to the indicated argument
1616   void addParamAttr(unsigned ArgNo, Attribute Attr) {
1617     assert(ArgNo < arg_size() && "Out of bounds");
1618     Attrs = Attrs.addParamAttribute(getContext(), ArgNo, Attr);
1619   }
1620 
1621   /// removes the attribute from the list of attributes.
1622   void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
1623     Attrs = Attrs.removeAttributeAtIndex(getContext(), i, Kind);
1624   }
1625 
1626   /// removes the attribute from the list of attributes.
1627   void removeAttributeAtIndex(unsigned i, StringRef Kind) {
1628     Attrs = Attrs.removeAttributeAtIndex(getContext(), i, Kind);
1629   }
1630 
1631   /// Removes the attributes from the function
1632   void removeFnAttrs(const AttributeMask &AttrsToRemove) {
1633     Attrs = Attrs.removeFnAttributes(getContext(), AttrsToRemove);
1634   }
1635 
1636   /// Removes the attribute from the function
1637   void removeFnAttr(Attribute::AttrKind Kind) {
1638     Attrs = Attrs.removeFnAttribute(getContext(), Kind);
1639   }
1640 
1641   /// Removes the attribute from the function
1642   void removeFnAttr(StringRef Kind) {
1643     Attrs = Attrs.removeFnAttribute(getContext(), Kind);
1644   }
1645 
1646   /// Removes the attribute from the return value
1647   void removeRetAttr(Attribute::AttrKind Kind) {
1648     Attrs = Attrs.removeRetAttribute(getContext(), Kind);
1649   }
1650 
1651   /// Removes the attributes from the return value
1652   void removeRetAttrs(const AttributeMask &AttrsToRemove) {
1653     Attrs = Attrs.removeRetAttributes(getContext(), AttrsToRemove);
1654   }
1655 
1656   /// Removes the attribute from the given argument
1657   void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1658     assert(ArgNo < arg_size() && "Out of bounds");
1659     Attrs = Attrs.removeParamAttribute(getContext(), ArgNo, Kind);
1660   }
1661 
1662   /// Removes the attribute from the given argument
1663   void removeParamAttr(unsigned ArgNo, StringRef Kind) {
1664     assert(ArgNo < arg_size() && "Out of bounds");
1665     Attrs = Attrs.removeParamAttribute(getContext(), ArgNo, Kind);
1666   }
1667 
1668   /// Removes the attributes from the given argument
1669   void removeParamAttrs(unsigned ArgNo, const AttributeMask &AttrsToRemove) {
1670     Attrs = Attrs.removeParamAttributes(getContext(), ArgNo, AttrsToRemove);
1671   }
1672 
1673   /// adds the dereferenceable attribute to the list of attributes.
1674   void addDereferenceableParamAttr(unsigned i, uint64_t Bytes) {
1675     Attrs = Attrs.addDereferenceableParamAttr(getContext(), i, Bytes);
1676   }
1677 
1678   /// adds the dereferenceable attribute to the list of attributes.
1679   void addDereferenceableRetAttr(uint64_t Bytes) {
1680     Attrs = Attrs.addDereferenceableRetAttr(getContext(), Bytes);
1681   }
1682 
1683   /// Determine whether the return value has the given attribute.
1684   bool hasRetAttr(Attribute::AttrKind Kind) const {
1685     return hasRetAttrImpl(Kind);
1686   }
1687   /// Determine whether the return value has the given attribute.
1688   bool hasRetAttr(StringRef Kind) const { return hasRetAttrImpl(Kind); }
1689 
1690   /// Determine whether the argument or parameter has the given attribute.
1691   bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1692 
1693   /// Get the attribute of a given kind at a position.
1694   Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const {
1695     return getAttributes().getAttributeAtIndex(i, Kind);
1696   }
1697 
1698   /// Get the attribute of a given kind at a position.
1699   Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const {
1700     return getAttributes().getAttributeAtIndex(i, Kind);
1701   }
1702 
1703   /// Get the attribute of a given kind for the function.
1704   Attribute getFnAttr(StringRef Kind) const {
1705     Attribute Attr = getAttributes().getFnAttr(Kind);
1706     if (Attr.isValid())
1707       return Attr;
1708     return getFnAttrOnCalledFunction(Kind);
1709   }
1710 
1711   /// Get the attribute of a given kind for the function.
1712   Attribute getFnAttr(Attribute::AttrKind Kind) const {
1713     Attribute A = getAttributes().getFnAttr(Kind);
1714     if (A.isValid())
1715       return A;
1716     return getFnAttrOnCalledFunction(Kind);
1717   }
1718 
1719   /// Get the attribute of a given kind from a given arg
1720   Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1721     assert(ArgNo < arg_size() && "Out of bounds");
1722     return getAttributes().getParamAttr(ArgNo, Kind);
1723   }
1724 
1725   /// Get the attribute of a given kind from a given arg
1726   Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1727     assert(ArgNo < arg_size() && "Out of bounds");
1728     return getAttributes().getParamAttr(ArgNo, Kind);
1729   }
1730 
1731   /// Return true if the data operand at index \p i has the attribute \p
1732   /// A.
1733   ///
1734   /// Data operands include call arguments and values used in operand bundles,
1735   /// but does not include the callee operand.
1736   ///
1737   /// The index \p i is interpreted as
1738   ///
1739   ///  \p i in [0, arg_size)  -> argument number (\p i)
1740   ///  \p i in [arg_size, data_operand_size) -> bundle operand at index
1741   ///     (\p i) in the operand list.
1742   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
1743     // Note that we have to add one because `i` isn't zero-indexed.
1744     assert(i < arg_size() + getNumTotalBundleOperands() &&
1745            "Data operand index out of bounds!");
1746 
1747     // The attribute A can either be directly specified, if the operand in
1748     // question is a call argument; or be indirectly implied by the kind of its
1749     // containing operand bundle, if the operand is a bundle operand.
1750 
1751     if (i < arg_size())
1752       return paramHasAttr(i, Kind);
1753 
1754     assert(hasOperandBundles() && i >= getBundleOperandsStartIndex() &&
1755            "Must be either a call argument or an operand bundle!");
1756     return bundleOperandHasAttr(i, Kind);
1757   }
1758 
1759   /// Determine whether this data operand is not captured.
1760   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1761   // better indicate that this may return a conservative answer.
1762   bool doesNotCapture(unsigned OpNo) const {
1763     return dataOperandHasImpliedAttr(OpNo, Attribute::NoCapture);
1764   }
1765 
1766   /// Determine whether this argument is passed by value.
1767   bool isByValArgument(unsigned ArgNo) const {
1768     return paramHasAttr(ArgNo, Attribute::ByVal);
1769   }
1770 
1771   /// Determine whether this argument is passed in an alloca.
1772   bool isInAllocaArgument(unsigned ArgNo) const {
1773     return paramHasAttr(ArgNo, Attribute::InAlloca);
1774   }
1775 
1776   /// Determine whether this argument is passed by value, in an alloca, or is
1777   /// preallocated.
1778   bool isPassPointeeByValueArgument(unsigned ArgNo) const {
1779     return paramHasAttr(ArgNo, Attribute::ByVal) ||
1780            paramHasAttr(ArgNo, Attribute::InAlloca) ||
1781            paramHasAttr(ArgNo, Attribute::Preallocated);
1782   }
1783 
1784   /// Determine whether passing undef to this argument is undefined behavior.
1785   /// If passing undef to this argument is UB, passing poison is UB as well
1786   /// because poison is more undefined than undef.
1787   bool isPassingUndefUB(unsigned ArgNo) const {
1788     return paramHasAttr(ArgNo, Attribute::NoUndef) ||
1789            // dereferenceable implies noundef.
1790            paramHasAttr(ArgNo, Attribute::Dereferenceable) ||
1791            // dereferenceable implies noundef, and null is a well-defined value.
1792            paramHasAttr(ArgNo, Attribute::DereferenceableOrNull);
1793   }
1794 
1795   /// Determine if there are is an inalloca argument. Only the last argument can
1796   /// have the inalloca attribute.
1797   bool hasInAllocaArgument() const {
1798     return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
1799   }
1800 
1801   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1802   // better indicate that this may return a conservative answer.
1803   bool doesNotAccessMemory(unsigned OpNo) const {
1804     return dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone);
1805   }
1806 
1807   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1808   // better indicate that this may return a conservative answer.
1809   bool onlyReadsMemory(unsigned OpNo) const {
1810     return dataOperandHasImpliedAttr(OpNo, Attribute::ReadOnly) ||
1811            dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone);
1812   }
1813 
1814   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1815   // better indicate that this may return a conservative answer.
1816   bool onlyWritesMemory(unsigned OpNo) const {
1817     return dataOperandHasImpliedAttr(OpNo, Attribute::WriteOnly) ||
1818            dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone);
1819   }
1820 
1821   /// Extract the alignment of the return value.
1822   MaybeAlign getRetAlign() const {
1823     if (auto Align = Attrs.getRetAlignment())
1824       return Align;
1825     if (const Function *F = getCalledFunction())
1826       return F->getAttributes().getRetAlignment();
1827     return std::nullopt;
1828   }
1829 
1830   /// Extract the alignment for a call or parameter (0=unknown).
1831   MaybeAlign getParamAlign(unsigned ArgNo) const {
1832     return Attrs.getParamAlignment(ArgNo);
1833   }
1834 
1835   MaybeAlign getParamStackAlign(unsigned ArgNo) const {
1836     return Attrs.getParamStackAlignment(ArgNo);
1837   }
1838 
1839   /// Extract the byval type for a call or parameter.
1840   Type *getParamByValType(unsigned ArgNo) const {
1841     if (auto *Ty = Attrs.getParamByValType(ArgNo))
1842       return Ty;
1843     if (const Function *F = getCalledFunction())
1844       return F->getAttributes().getParamByValType(ArgNo);
1845     return nullptr;
1846   }
1847 
1848   /// Extract the preallocated type for a call or parameter.
1849   Type *getParamPreallocatedType(unsigned ArgNo) const {
1850     if (auto *Ty = Attrs.getParamPreallocatedType(ArgNo))
1851       return Ty;
1852     if (const Function *F = getCalledFunction())
1853       return F->getAttributes().getParamPreallocatedType(ArgNo);
1854     return nullptr;
1855   }
1856 
1857   /// Extract the inalloca type for a call or parameter.
1858   Type *getParamInAllocaType(unsigned ArgNo) const {
1859     if (auto *Ty = Attrs.getParamInAllocaType(ArgNo))
1860       return Ty;
1861     if (const Function *F = getCalledFunction())
1862       return F->getAttributes().getParamInAllocaType(ArgNo);
1863     return nullptr;
1864   }
1865 
1866   /// Extract the sret type for a call or parameter.
1867   Type *getParamStructRetType(unsigned ArgNo) const {
1868     if (auto *Ty = Attrs.getParamStructRetType(ArgNo))
1869       return Ty;
1870     if (const Function *F = getCalledFunction())
1871       return F->getAttributes().getParamStructRetType(ArgNo);
1872     return nullptr;
1873   }
1874 
1875   /// Extract the elementtype type for a parameter.
1876   /// Note that elementtype() can only be applied to call arguments, not
1877   /// function declaration parameters.
1878   Type *getParamElementType(unsigned ArgNo) const {
1879     return Attrs.getParamElementType(ArgNo);
1880   }
1881 
1882   /// Extract the number of dereferenceable bytes for a call or
1883   /// parameter (0=unknown).
1884   uint64_t getRetDereferenceableBytes() const {
1885     uint64_t Bytes = Attrs.getRetDereferenceableBytes();
1886     if (const Function *F = getCalledFunction())
1887       Bytes = std::max(Bytes, F->getAttributes().getRetDereferenceableBytes());
1888     return Bytes;
1889   }
1890 
1891   /// Extract the number of dereferenceable bytes for a call or
1892   /// parameter (0=unknown).
1893   uint64_t getParamDereferenceableBytes(unsigned i) const {
1894     return Attrs.getParamDereferenceableBytes(i);
1895   }
1896 
1897   /// Extract the number of dereferenceable_or_null bytes for a call
1898   /// (0=unknown).
1899   uint64_t getRetDereferenceableOrNullBytes() const {
1900     uint64_t Bytes = Attrs.getRetDereferenceableOrNullBytes();
1901     if (const Function *F = getCalledFunction()) {
1902       Bytes = std::max(Bytes,
1903                        F->getAttributes().getRetDereferenceableOrNullBytes());
1904     }
1905 
1906     return Bytes;
1907   }
1908 
1909   /// Extract the number of dereferenceable_or_null bytes for a
1910   /// parameter (0=unknown).
1911   uint64_t getParamDereferenceableOrNullBytes(unsigned i) const {
1912     return Attrs.getParamDereferenceableOrNullBytes(i);
1913   }
1914 
1915   /// Extract a test mask for disallowed floating-point value classes for the
1916   /// return value.
1917   FPClassTest getRetNoFPClass() const;
1918 
1919   /// Extract a test mask for disallowed floating-point value classes for the
1920   /// parameter.
1921   FPClassTest getParamNoFPClass(unsigned i) const;
1922 
1923   /// Return true if the return value is known to be not null.
1924   /// This may be because it has the nonnull attribute, or because at least
1925   /// one byte is dereferenceable and the pointer is in addrspace(0).
1926   bool isReturnNonNull() const;
1927 
1928   /// Determine if the return value is marked with NoAlias attribute.
1929   bool returnDoesNotAlias() const {
1930     return Attrs.hasRetAttr(Attribute::NoAlias);
1931   }
1932 
1933   /// If one of the arguments has the 'returned' attribute, returns its
1934   /// operand value. Otherwise, return nullptr.
1935   Value *getReturnedArgOperand() const {
1936     return getArgOperandWithAttribute(Attribute::Returned);
1937   }
1938 
1939   /// If one of the arguments has the specified attribute, returns its
1940   /// operand value. Otherwise, return nullptr.
1941   Value *getArgOperandWithAttribute(Attribute::AttrKind Kind) const;
1942 
1943   /// Return true if the call should not be treated as a call to a
1944   /// builtin.
1945   bool isNoBuiltin() const {
1946     return hasFnAttrImpl(Attribute::NoBuiltin) &&
1947            !hasFnAttrImpl(Attribute::Builtin);
1948   }
1949 
1950   /// Determine if the call requires strict floating point semantics.
1951   bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1952 
1953   /// Return true if the call should not be inlined.
1954   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1955   void setIsNoInline() { addFnAttr(Attribute::NoInline); }
1956 
1957   MemoryEffects getMemoryEffects() const;
1958   void setMemoryEffects(MemoryEffects ME);
1959 
1960   /// Determine if the call does not access memory.
1961   bool doesNotAccessMemory() const;
1962   void setDoesNotAccessMemory();
1963 
1964   /// Determine if the call does not access or only reads memory.
1965   bool onlyReadsMemory() const;
1966   void setOnlyReadsMemory();
1967 
1968   /// Determine if the call does not access or only writes memory.
1969   bool onlyWritesMemory() const;
1970   void setOnlyWritesMemory();
1971 
1972   /// Determine if the call can access memmory only using pointers based
1973   /// on its arguments.
1974   bool onlyAccessesArgMemory() const;
1975   void setOnlyAccessesArgMemory();
1976 
1977   /// Determine if the function may only access memory that is
1978   /// inaccessible from the IR.
1979   bool onlyAccessesInaccessibleMemory() const;
1980   void setOnlyAccessesInaccessibleMemory();
1981 
1982   /// Determine if the function may only access memory that is
1983   /// either inaccessible from the IR or pointed to by its arguments.
1984   bool onlyAccessesInaccessibleMemOrArgMem() const;
1985   void setOnlyAccessesInaccessibleMemOrArgMem();
1986 
1987   /// Determine if the call cannot return.
1988   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1989   void setDoesNotReturn() { addFnAttr(Attribute::NoReturn); }
1990 
1991   /// Determine if the call should not perform indirect branch tracking.
1992   bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
1993 
1994   /// Determine if the call cannot unwind.
1995   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1996   void setDoesNotThrow() { addFnAttr(Attribute::NoUnwind); }
1997 
1998   /// Determine if the invoke cannot be duplicated.
1999   bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); }
2000   void setCannotDuplicate() { addFnAttr(Attribute::NoDuplicate); }
2001 
2002   /// Determine if the call cannot be tail merged.
2003   bool cannotMerge() const { return hasFnAttr(Attribute::NoMerge); }
2004   void setCannotMerge() { addFnAttr(Attribute::NoMerge); }
2005 
2006   /// Determine if the invoke is convergent
2007   bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
2008   void setConvergent() { addFnAttr(Attribute::Convergent); }
2009   void setNotConvergent() { removeFnAttr(Attribute::Convergent); }
2010 
2011   /// Determine if the call returns a structure through first
2012   /// pointer argument.
2013   bool hasStructRetAttr() const {
2014     if (arg_empty())
2015       return false;
2016 
2017     // Be friendly and also check the callee.
2018     return paramHasAttr(0, Attribute::StructRet);
2019   }
2020 
2021   /// Determine if any call argument is an aggregate passed by value.
2022   bool hasByValArgument() const {
2023     return Attrs.hasAttrSomewhere(Attribute::ByVal);
2024   }
2025 
2026   ///@}
2027   // End of attribute API.
2028 
2029   /// \name Operand Bundle API
2030   ///
2031   /// This group of methods provides the API to access and manipulate operand
2032   /// bundles on this call.
2033   /// @{
2034 
2035   /// Return the number of operand bundles associated with this User.
2036   unsigned getNumOperandBundles() const {
2037     return std::distance(bundle_op_info_begin(), bundle_op_info_end());
2038   }
2039 
2040   /// Return true if this User has any operand bundles.
2041   bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
2042 
2043   /// Return the index of the first bundle operand in the Use array.
2044   unsigned getBundleOperandsStartIndex() const {
2045     assert(hasOperandBundles() && "Don't call otherwise!");
2046     return bundle_op_info_begin()->Begin;
2047   }
2048 
2049   /// Return the index of the last bundle operand in the Use array.
2050   unsigned getBundleOperandsEndIndex() const {
2051     assert(hasOperandBundles() && "Don't call otherwise!");
2052     return bundle_op_info_end()[-1].End;
2053   }
2054 
2055   /// Return true if the operand at index \p Idx is a bundle operand.
2056   bool isBundleOperand(unsigned Idx) const {
2057     return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
2058            Idx < getBundleOperandsEndIndex();
2059   }
2060 
2061   /// Return true if the operand at index \p Idx is a bundle operand that has
2062   /// tag ID \p ID.
2063   bool isOperandBundleOfType(uint32_t ID, unsigned Idx) const {
2064     return isBundleOperand(Idx) &&
2065            getOperandBundleForOperand(Idx).getTagID() == ID;
2066   }
2067 
2068   /// Returns true if the use is a bundle operand.
2069   bool isBundleOperand(const Use *U) const {
2070     assert(this == U->getUser() &&
2071            "Only valid to query with a use of this instruction!");
2072     return hasOperandBundles() && isBundleOperand(U - op_begin());
2073   }
2074   bool isBundleOperand(Value::const_user_iterator UI) const {
2075     return isBundleOperand(&UI.getUse());
2076   }
2077 
2078   /// Return the total number operands (not operand bundles) used by
2079   /// every operand bundle in this OperandBundleUser.
2080   unsigned getNumTotalBundleOperands() const {
2081     if (!hasOperandBundles())
2082       return 0;
2083 
2084     unsigned Begin = getBundleOperandsStartIndex();
2085     unsigned End = getBundleOperandsEndIndex();
2086 
2087     assert(Begin <= End && "Should be!");
2088     return End - Begin;
2089   }
2090 
2091   /// Return the operand bundle at a specific index.
2092   OperandBundleUse getOperandBundleAt(unsigned Index) const {
2093     assert(Index < getNumOperandBundles() && "Index out of bounds!");
2094     return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
2095   }
2096 
2097   /// Return the number of operand bundles with the tag Name attached to
2098   /// this instruction.
2099   unsigned countOperandBundlesOfType(StringRef Name) const {
2100     unsigned Count = 0;
2101     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
2102       if (getOperandBundleAt(i).getTagName() == Name)
2103         Count++;
2104 
2105     return Count;
2106   }
2107 
2108   /// Return the number of operand bundles with the tag ID attached to
2109   /// this instruction.
2110   unsigned countOperandBundlesOfType(uint32_t ID) const {
2111     unsigned Count = 0;
2112     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
2113       if (getOperandBundleAt(i).getTagID() == ID)
2114         Count++;
2115 
2116     return Count;
2117   }
2118 
2119   /// Return an operand bundle by name, if present.
2120   ///
2121   /// It is an error to call this for operand bundle types that may have
2122   /// multiple instances of them on the same instruction.
2123   std::optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
2124     assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
2125 
2126     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
2127       OperandBundleUse U = getOperandBundleAt(i);
2128       if (U.getTagName() == Name)
2129         return U;
2130     }
2131 
2132     return std::nullopt;
2133   }
2134 
2135   /// Return an operand bundle by tag ID, if present.
2136   ///
2137   /// It is an error to call this for operand bundle types that may have
2138   /// multiple instances of them on the same instruction.
2139   std::optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
2140     assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
2141 
2142     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
2143       OperandBundleUse U = getOperandBundleAt(i);
2144       if (U.getTagID() == ID)
2145         return U;
2146     }
2147 
2148     return std::nullopt;
2149   }
2150 
2151   /// Return the list of operand bundles attached to this instruction as
2152   /// a vector of OperandBundleDefs.
2153   ///
2154   /// This function copies the OperandBundeUse instances associated with this
2155   /// OperandBundleUser to a vector of OperandBundleDefs.  Note:
2156   /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
2157   /// representations of operand bundles (see documentation above).
2158   void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const;
2159 
2160   /// Return the operand bundle for the operand at index OpIdx.
2161   ///
2162   /// It is an error to call this with an OpIdx that does not correspond to an
2163   /// bundle operand.
2164   OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
2165     return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
2166   }
2167 
2168   /// Return true if this operand bundle user has operand bundles that
2169   /// may read from the heap.
2170   bool hasReadingOperandBundles() const;
2171 
2172   /// Return true if this operand bundle user has operand bundles that
2173   /// may write to the heap.
2174   bool hasClobberingOperandBundles() const;
2175 
2176   /// Return true if the bundle operand at index \p OpIdx has the
2177   /// attribute \p A.
2178   bool bundleOperandHasAttr(unsigned OpIdx,  Attribute::AttrKind A) const {
2179     auto &BOI = getBundleOpInfoForOperand(OpIdx);
2180     auto OBU = operandBundleFromBundleOpInfo(BOI);
2181     return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
2182   }
2183 
2184   /// Return true if \p Other has the same sequence of operand bundle
2185   /// tags with the same number of operands on each one of them as this
2186   /// OperandBundleUser.
2187   bool hasIdenticalOperandBundleSchema(const CallBase &Other) const {
2188     if (getNumOperandBundles() != Other.getNumOperandBundles())
2189       return false;
2190 
2191     return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
2192                       Other.bundle_op_info_begin());
2193   }
2194 
2195   /// Return true if this operand bundle user contains operand bundles
2196   /// with tags other than those specified in \p IDs.
2197   bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
2198     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
2199       uint32_t ID = getOperandBundleAt(i).getTagID();
2200       if (!is_contained(IDs, ID))
2201         return true;
2202     }
2203     return false;
2204   }
2205 
2206   /// Used to keep track of an operand bundle.  See the main comment on
2207   /// OperandBundleUser above.
2208   struct BundleOpInfo {
2209     /// The operand bundle tag, interned by
2210     /// LLVMContextImpl::getOrInsertBundleTag.
2211     StringMapEntry<uint32_t> *Tag;
2212 
2213     /// The index in the Use& vector where operands for this operand
2214     /// bundle starts.
2215     uint32_t Begin;
2216 
2217     /// The index in the Use& vector where operands for this operand
2218     /// bundle ends.
2219     uint32_t End;
2220 
2221     bool operator==(const BundleOpInfo &Other) const {
2222       return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
2223     }
2224   };
2225 
2226   /// Simple helper function to map a BundleOpInfo to an
2227   /// OperandBundleUse.
2228   OperandBundleUse
2229   operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
2230     const auto *begin = op_begin();
2231     ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End);
2232     return OperandBundleUse(BOI.Tag, Inputs);
2233   }
2234 
2235   using bundle_op_iterator = BundleOpInfo *;
2236   using const_bundle_op_iterator = const BundleOpInfo *;
2237 
2238   /// Return the start of the list of BundleOpInfo instances associated
2239   /// with this OperandBundleUser.
2240   ///
2241   /// OperandBundleUser uses the descriptor area co-allocated with the host User
2242   /// to store some meta information about which operands are "normal" operands,
2243   /// and which ones belong to some operand bundle.
2244   ///
2245   /// The layout of an operand bundle user is
2246   ///
2247   ///          +-----------uint32_t End-------------------------------------+
2248   ///          |                                                            |
2249   ///          |  +--------uint32_t Begin--------------------+              |
2250   ///          |  |                                          |              |
2251   ///          ^  ^                                          v              v
2252   ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
2253   ///  | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
2254   ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
2255   ///   v  v                                  ^              ^
2256   ///   |  |                                  |              |
2257   ///   |  +--------uint32_t Begin------------+              |
2258   ///   |                                                    |
2259   ///   +-----------uint32_t End-----------------------------+
2260   ///
2261   ///
2262   /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use
2263   /// list. These descriptions are installed and managed by this class, and
2264   /// they're all instances of OperandBundleUser<T>::BundleOpInfo.
2265   ///
2266   /// DU is an additional descriptor installed by User's 'operator new' to keep
2267   /// track of the 'BOI0 ... BOIN' co-allocation.  OperandBundleUser does not
2268   /// access or modify DU in any way, it's an implementation detail private to
2269   /// User.
2270   ///
2271   /// The regular Use& vector for the User starts at U0.  The operand bundle
2272   /// uses are part of the Use& vector, just like normal uses.  In the diagram
2273   /// above, the operand bundle uses start at BOI0_U0.  Each instance of
2274   /// BundleOpInfo has information about a contiguous set of uses constituting
2275   /// an operand bundle, and the total set of operand bundle uses themselves
2276   /// form a contiguous set of uses (i.e. there are no gaps between uses
2277   /// corresponding to individual operand bundles).
2278   ///
2279   /// This class does not know the location of the set of operand bundle uses
2280   /// within the use list -- that is decided by the User using this class via
2281   /// the BeginIdx argument in populateBundleOperandInfos.
2282   ///
2283   /// Currently operand bundle users with hung-off operands are not supported.
2284   bundle_op_iterator bundle_op_info_begin() {
2285     if (!hasDescriptor())
2286       return nullptr;
2287 
2288     uint8_t *BytesBegin = getDescriptor().begin();
2289     return reinterpret_cast<bundle_op_iterator>(BytesBegin);
2290   }
2291 
2292   /// Return the start of the list of BundleOpInfo instances associated
2293   /// with this OperandBundleUser.
2294   const_bundle_op_iterator bundle_op_info_begin() const {
2295     auto *NonConstThis = const_cast<CallBase *>(this);
2296     return NonConstThis->bundle_op_info_begin();
2297   }
2298 
2299   /// Return the end of the list of BundleOpInfo instances associated
2300   /// with this OperandBundleUser.
2301   bundle_op_iterator bundle_op_info_end() {
2302     if (!hasDescriptor())
2303       return nullptr;
2304 
2305     uint8_t *BytesEnd = getDescriptor().end();
2306     return reinterpret_cast<bundle_op_iterator>(BytesEnd);
2307   }
2308 
2309   /// Return the end of the list of BundleOpInfo instances associated
2310   /// with this OperandBundleUser.
2311   const_bundle_op_iterator bundle_op_info_end() const {
2312     auto *NonConstThis = const_cast<CallBase *>(this);
2313     return NonConstThis->bundle_op_info_end();
2314   }
2315 
2316   /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2317   iterator_range<bundle_op_iterator> bundle_op_infos() {
2318     return make_range(bundle_op_info_begin(), bundle_op_info_end());
2319   }
2320 
2321   /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2322   iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
2323     return make_range(bundle_op_info_begin(), bundle_op_info_end());
2324   }
2325 
2326   /// Populate the BundleOpInfo instances and the Use& vector from \p
2327   /// Bundles.  Return the op_iterator pointing to the Use& one past the last
2328   /// last bundle operand use.
2329   ///
2330   /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
2331   /// instance allocated in this User's descriptor.
2332   op_iterator populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
2333                                          const unsigned BeginIndex);
2334 
2335 public:
2336   /// Return the BundleOpInfo for the operand at index OpIdx.
2337   ///
2338   /// It is an error to call this with an OpIdx that does not correspond to an
2339   /// bundle operand.
2340   BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx);
2341   const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
2342     return const_cast<CallBase *>(this)->getBundleOpInfoForOperand(OpIdx);
2343   }
2344 
2345 protected:
2346   /// Return the total number of values used in \p Bundles.
2347   static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
2348     unsigned Total = 0;
2349     for (const auto &B : Bundles)
2350       Total += B.input_size();
2351     return Total;
2352   }
2353 
2354   /// @}
2355   // End of operand bundle API.
2356 
2357 private:
2358   bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
2359   bool hasFnAttrOnCalledFunction(StringRef Kind) const;
2360 
2361   template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
2362     if (Attrs.hasFnAttr(Kind))
2363       return true;
2364 
2365     return hasFnAttrOnCalledFunction(Kind);
2366   }
2367   template <typename AK> Attribute getFnAttrOnCalledFunction(AK Kind) const;
2368 
2369   /// Determine whether the return value has the given attribute. Supports
2370   /// Attribute::AttrKind and StringRef as \p AttrKind types.
2371   template <typename AttrKind> bool hasRetAttrImpl(AttrKind Kind) const {
2372     if (Attrs.hasRetAttr(Kind))
2373       return true;
2374 
2375     // Look at the callee, if available.
2376     if (const Function *F = getCalledFunction())
2377       return F->getAttributes().hasRetAttr(Kind);
2378     return false;
2379   }
2380 };
2381 
2382 template <>
2383 struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase, 1> {};
2384 
2385 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value)
2386 
2387 //===----------------------------------------------------------------------===//
2388 //                           FuncletPadInst Class
2389 //===----------------------------------------------------------------------===//
2390 class FuncletPadInst : public Instruction {
2391 private:
2392   FuncletPadInst(const FuncletPadInst &CPI);
2393 
2394   explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2395                           ArrayRef<Value *> Args, unsigned Values,
2396                           const Twine &NameStr, Instruction *InsertBefore);
2397   explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2398                           ArrayRef<Value *> Args, unsigned Values,
2399                           const Twine &NameStr, BasicBlock *InsertAtEnd);
2400 
2401   void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
2402 
2403 protected:
2404   // Note: Instruction needs to be a friend here to call cloneImpl.
2405   friend class Instruction;
2406   friend class CatchPadInst;
2407   friend class CleanupPadInst;
2408 
2409   FuncletPadInst *cloneImpl() const;
2410 
2411 public:
2412   /// Provide fast operand accessors
2413   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2414 
2415   /// arg_size - Return the number of funcletpad arguments.
2416   ///
2417   unsigned arg_size() const { return getNumOperands() - 1; }
2418 
2419   /// Convenience accessors
2420 
2421   /// Return the outer EH-pad this funclet is nested within.
2422   ///
2423   /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
2424   /// is a CatchPadInst.
2425   Value *getParentPad() const { return Op<-1>(); }
2426   void setParentPad(Value *ParentPad) {
2427     assert(ParentPad);
2428     Op<-1>() = ParentPad;
2429   }
2430 
2431   /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
2432   ///
2433   Value *getArgOperand(unsigned i) const { return getOperand(i); }
2434   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
2435 
2436   /// arg_operands - iteration adapter for range-for loops.
2437   op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
2438 
2439   /// arg_operands - iteration adapter for range-for loops.
2440   const_op_range arg_operands() const {
2441     return const_op_range(op_begin(), op_end() - 1);
2442   }
2443 
2444   // Methods for support type inquiry through isa, cast, and dyn_cast:
2445   static bool classof(const Instruction *I) { return I->isFuncletPad(); }
2446   static bool classof(const Value *V) {
2447     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2448   }
2449 };
2450 
2451 template <>
2452 struct OperandTraits<FuncletPadInst>
2453     : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
2454 
2455 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
2456 
2457 } // end namespace llvm
2458 
2459 #endif // LLVM_IR_INSTRTYPES_H
2460