Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / IR / CallSite.h
blob1454874e4efea855663403f48b879860257ba7df
1 //===- CallSite.h - Abstract Call & Invoke instrs ---------------*- 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 the CallSite class, which is a handy wrapper for code that
10 // wants to treat Call, Invoke and CallBr instructions in a generic way. When
11 // in non-mutation context (e.g. an analysis) ImmutableCallSite should be used.
12 // Finally, when some degree of customization is necessary between these two
13 // extremes, CallSiteBase<> can be supplied with fine-tuned parameters.
15 // NOTE: These classes are supposed to have "value semantics". So they should be
16 // passed by value, not by reference; they should not be "new"ed or "delete"d.
17 // They are efficiently copyable, assignable and constructable, with cost
18 // equivalent to copying a pointer (notice that they have only a single data
19 // member). The internal representation carries a flag which indicates which of
20 // the three variants is enclosed. This allows for cheaper checks when various
21 // accessors of CallSite are employed.
23 //===----------------------------------------------------------------------===//
25 #ifndef LLVM_IR_CALLSITE_H
26 #define LLVM_IR_CALLSITE_H
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/PointerIntPair.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/InstrTypes.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/Use.h"
38 #include "llvm/IR/User.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Support/Casting.h"
41 #include <cassert>
42 #include <cstdint>
43 #include <iterator>
45 namespace llvm {
47 namespace Intrinsic {
48 enum ID : unsigned;
51 template <typename FunTy = const Function, typename BBTy = const BasicBlock,
52 typename ValTy = const Value, typename UserTy = const User,
53 typename UseTy = const Use, typename InstrTy = const Instruction,
54 typename CallTy = const CallInst,
55 typename InvokeTy = const InvokeInst,
56 typename CallBrTy = const CallBrInst,
57 typename IterTy = User::const_op_iterator>
58 class CallSiteBase {
59 protected:
60 PointerIntPair<InstrTy *, 2, int> I;
62 CallSiteBase() = default;
63 CallSiteBase(CallTy *CI) : I(CI, 1) { assert(CI); }
64 CallSiteBase(InvokeTy *II) : I(II, 0) { assert(II); }
65 CallSiteBase(CallBrTy *CBI) : I(CBI, 2) { assert(CBI); }
66 explicit CallSiteBase(ValTy *II) { *this = get(II); }
68 private:
69 /// This static method is like a constructor. It will create an appropriate
70 /// call site for a Call, Invoke or CallBr instruction, but it can also create
71 /// a null initialized CallSiteBase object for something which is NOT a call
72 /// site.
73 static CallSiteBase get(ValTy *V) {
74 if (InstrTy *II = dyn_cast<InstrTy>(V)) {
75 if (II->getOpcode() == Instruction::Call)
76 return CallSiteBase(static_cast<CallTy*>(II));
77 if (II->getOpcode() == Instruction::Invoke)
78 return CallSiteBase(static_cast<InvokeTy*>(II));
79 if (II->getOpcode() == Instruction::CallBr)
80 return CallSiteBase(static_cast<CallBrTy *>(II));
82 return CallSiteBase();
85 public:
86 /// Return true if a CallInst is enclosed.
87 bool isCall() const { return I.getInt() == 1; }
89 /// Return true if a InvokeInst is enclosed. !I.getInt() may also signify a
90 /// NULL instruction pointer, so check that.
91 bool isInvoke() const { return getInstruction() && I.getInt() == 0; }
93 /// Return true if a CallBrInst is enclosed.
94 bool isCallBr() const { return I.getInt() == 2; }
96 InstrTy *getInstruction() const { return I.getPointer(); }
97 InstrTy *operator->() const { return I.getPointer(); }
98 explicit operator bool() const { return I.getPointer(); }
100 /// Get the basic block containing the call site.
101 BBTy* getParent() const { return getInstruction()->getParent(); }
103 /// Return the pointer to function that is being called.
104 ValTy *getCalledValue() const {
105 assert(getInstruction() && "Not a call, invoke or callbr instruction!");
106 return *getCallee();
109 /// Return the function being called if this is a direct call, otherwise
110 /// return null (if it's an indirect call).
111 FunTy *getCalledFunction() const {
112 return dyn_cast<FunTy>(getCalledValue());
115 /// Return true if the callsite is an indirect call.
116 bool isIndirectCall() const {
117 const Value *V = getCalledValue();
118 if (!V)
119 return false;
120 if (isa<FunTy>(V) || isa<Constant>(V))
121 return false;
122 if (const CallBase *CB = dyn_cast<CallBase>(getInstruction()))
123 if (CB->isInlineAsm())
124 return false;
125 return true;
128 /// Set the callee to the specified value. Unlike the function of the same
129 /// name on CallBase, does not modify the type!
130 void setCalledFunction(Value *V) {
131 assert(getInstruction() && "Not a call, callbr, or invoke instruction!");
132 assert(cast<PointerType>(V->getType())->getElementType() ==
133 cast<CallBase>(getInstruction())->getFunctionType() &&
134 "New callee type does not match FunctionType on call");
135 *getCallee() = V;
138 /// Return the intrinsic ID of the intrinsic called by this CallSite,
139 /// or Intrinsic::not_intrinsic if the called function is not an
140 /// intrinsic, or if this CallSite is an indirect call.
141 Intrinsic::ID getIntrinsicID() const {
142 if (auto *F = getCalledFunction())
143 return F->getIntrinsicID();
144 // Don't use Intrinsic::not_intrinsic, as it will require pulling
145 // Intrinsics.h into every header that uses CallSite.
146 return static_cast<Intrinsic::ID>(0);
149 /// Determine whether the passed iterator points to the callee operand's Use.
150 bool isCallee(Value::const_user_iterator UI) const {
151 return isCallee(&UI.getUse());
154 /// Determine whether this Use is the callee operand's Use.
155 bool isCallee(const Use *U) const { return getCallee() == U; }
157 /// Determine whether the passed iterator points to an argument operand.
158 bool isArgOperand(Value::const_user_iterator UI) const {
159 return isArgOperand(&UI.getUse());
162 /// Determine whether the passed use points to an argument operand.
163 bool isArgOperand(const Use *U) const {
164 assert(getInstruction() == U->getUser());
165 return arg_begin() <= U && U < arg_end();
168 /// Determine whether the passed iterator points to a bundle operand.
169 bool isBundleOperand(Value::const_user_iterator UI) const {
170 return isBundleOperand(&UI.getUse());
173 /// Determine whether the passed use points to a bundle operand.
174 bool isBundleOperand(const Use *U) const {
175 assert(getInstruction() == U->getUser());
176 if (!hasOperandBundles())
177 return false;
178 unsigned OperandNo = U - (*this)->op_begin();
179 return getBundleOperandsStartIndex() <= OperandNo &&
180 OperandNo < getBundleOperandsEndIndex();
183 /// Determine whether the passed iterator points to a data operand.
184 bool isDataOperand(Value::const_user_iterator UI) const {
185 return isDataOperand(&UI.getUse());
188 /// Determine whether the passed use points to a data operand.
189 bool isDataOperand(const Use *U) const {
190 return data_operands_begin() <= U && U < data_operands_end();
193 ValTy *getArgument(unsigned ArgNo) const {
194 assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!");
195 return *(arg_begin() + ArgNo);
198 void setArgument(unsigned ArgNo, Value* newVal) {
199 assert(getInstruction() && "Not a call, invoke or callbr instruction!");
200 assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!");
201 getInstruction()->setOperand(ArgNo, newVal);
204 /// Given a value use iterator, returns the argument that corresponds to it.
205 /// Iterator must actually correspond to an argument.
206 unsigned getArgumentNo(Value::const_user_iterator I) const {
207 return getArgumentNo(&I.getUse());
210 /// Given a use for an argument, get the argument number that corresponds to
211 /// it.
212 unsigned getArgumentNo(const Use *U) const {
213 assert(getInstruction() && "Not a call, invoke or callbr instruction!");
214 assert(isArgOperand(U) && "Argument # out of range!");
215 return U - arg_begin();
218 /// The type of iterator to use when looping over actual arguments at this
219 /// call site.
220 using arg_iterator = IterTy;
222 iterator_range<IterTy> args() const {
223 return make_range(arg_begin(), arg_end());
225 bool arg_empty() const { return arg_end() == arg_begin(); }
226 unsigned arg_size() const { return unsigned(arg_end() - arg_begin()); }
228 /// Given a value use iterator, return the data operand corresponding to it.
229 /// Iterator must actually correspond to a data operand.
230 unsigned getDataOperandNo(Value::const_user_iterator UI) const {
231 return getDataOperandNo(&UI.getUse());
234 /// Given a use for a data operand, get the data operand number that
235 /// corresponds to it.
236 unsigned getDataOperandNo(const Use *U) const {
237 assert(getInstruction() && "Not a call, invoke or callbr instruction!");
238 assert(isDataOperand(U) && "Data operand # out of range!");
239 return U - data_operands_begin();
242 /// Type of iterator to use when looping over data operands at this call site
243 /// (see below).
244 using data_operand_iterator = IterTy;
246 /// data_operands_begin/data_operands_end - Return iterators iterating over
247 /// the call / invoke / callbr argument list and bundle operands. For invokes,
248 /// this is the set of instruction operands except the invoke target and the
249 /// two successor blocks; for calls this is the set of instruction operands
250 /// except the call target; for callbrs the number of labels to skip must be
251 /// determined first.
253 IterTy data_operands_begin() const {
254 assert(getInstruction() && "Not a call or invoke instruction!");
255 return cast<CallBase>(getInstruction())->data_operands_begin();
257 IterTy data_operands_end() const {
258 assert(getInstruction() && "Not a call or invoke instruction!");
259 return cast<CallBase>(getInstruction())->data_operands_end();
261 iterator_range<IterTy> data_ops() const {
262 return make_range(data_operands_begin(), data_operands_end());
264 bool data_operands_empty() const {
265 return data_operands_end() == data_operands_begin();
267 unsigned data_operands_size() const {
268 return std::distance(data_operands_begin(), data_operands_end());
271 /// Return the type of the instruction that generated this call site.
272 Type *getType() const { return (*this)->getType(); }
274 /// Return the caller function for this call site.
275 FunTy *getCaller() const { return (*this)->getParent()->getParent(); }
277 /// Tests if this call site must be tail call optimized. Only a CallInst can
278 /// be tail call optimized.
279 bool isMustTailCall() const {
280 return isCall() && cast<CallInst>(getInstruction())->isMustTailCall();
283 /// Tests if this call site is marked as a tail call.
284 bool isTailCall() const {
285 return isCall() && cast<CallInst>(getInstruction())->isTailCall();
288 #define CALLSITE_DELEGATE_GETTER(METHOD) \
289 InstrTy *II = getInstruction(); \
290 return isCall() ? cast<CallInst>(II)->METHOD \
291 : isCallBr() ? cast<CallBrInst>(II)->METHOD \
292 : cast<InvokeInst>(II)->METHOD
294 #define CALLSITE_DELEGATE_SETTER(METHOD) \
295 InstrTy *II = getInstruction(); \
296 if (isCall()) \
297 cast<CallInst>(II)->METHOD; \
298 else if (isCallBr()) \
299 cast<CallBrInst>(II)->METHOD; \
300 else \
301 cast<InvokeInst>(II)->METHOD
303 unsigned getNumArgOperands() const {
304 CALLSITE_DELEGATE_GETTER(getNumArgOperands());
307 ValTy *getArgOperand(unsigned i) const {
308 CALLSITE_DELEGATE_GETTER(getArgOperand(i));
311 ValTy *getReturnedArgOperand() const {
312 CALLSITE_DELEGATE_GETTER(getReturnedArgOperand());
315 bool isInlineAsm() const {
316 return cast<CallBase>(getInstruction())->isInlineAsm();
319 /// Get the calling convention of the call.
320 CallingConv::ID getCallingConv() const {
321 CALLSITE_DELEGATE_GETTER(getCallingConv());
323 /// Set the calling convention of the call.
324 void setCallingConv(CallingConv::ID CC) {
325 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
328 FunctionType *getFunctionType() const {
329 CALLSITE_DELEGATE_GETTER(getFunctionType());
332 void mutateFunctionType(FunctionType *Ty) const {
333 CALLSITE_DELEGATE_SETTER(mutateFunctionType(Ty));
336 /// Get the parameter attributes of the call.
337 AttributeList getAttributes() const {
338 CALLSITE_DELEGATE_GETTER(getAttributes());
340 /// Set the parameter attributes of the call.
341 void setAttributes(AttributeList PAL) {
342 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
345 void addAttribute(unsigned i, Attribute::AttrKind Kind) {
346 CALLSITE_DELEGATE_SETTER(addAttribute(i, Kind));
349 void addAttribute(unsigned i, Attribute Attr) {
350 CALLSITE_DELEGATE_SETTER(addAttribute(i, Attr));
353 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
354 CALLSITE_DELEGATE_SETTER(addParamAttr(ArgNo, Kind));
357 void removeAttribute(unsigned i, Attribute::AttrKind Kind) {
358 CALLSITE_DELEGATE_SETTER(removeAttribute(i, Kind));
361 void removeAttribute(unsigned i, StringRef Kind) {
362 CALLSITE_DELEGATE_SETTER(removeAttribute(i, Kind));
365 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
366 CALLSITE_DELEGATE_SETTER(removeParamAttr(ArgNo, Kind));
369 /// Return true if this function has the given attribute.
370 bool hasFnAttr(Attribute::AttrKind Kind) const {
371 CALLSITE_DELEGATE_GETTER(hasFnAttr(Kind));
374 /// Return true if this function has the given attribute.
375 bool hasFnAttr(StringRef Kind) const {
376 CALLSITE_DELEGATE_GETTER(hasFnAttr(Kind));
379 /// Return true if this return value has the given attribute.
380 bool hasRetAttr(Attribute::AttrKind Kind) const {
381 CALLSITE_DELEGATE_GETTER(hasRetAttr(Kind));
384 /// Return true if the call or the callee has the given attribute.
385 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
386 CALLSITE_DELEGATE_GETTER(paramHasAttr(ArgNo, Kind));
389 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
390 CALLSITE_DELEGATE_GETTER(getAttribute(i, Kind));
393 Attribute getAttribute(unsigned i, StringRef Kind) const {
394 CALLSITE_DELEGATE_GETTER(getAttribute(i, Kind));
397 /// Return true if the data operand at index \p i directly or indirectly has
398 /// the attribute \p A.
400 /// Normal call, invoke or callbr arguments have per operand attributes, as
401 /// specified in the attribute set attached to this instruction, while operand
402 /// bundle operands may have some attributes implied by the type of its
403 /// containing operand bundle.
404 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
405 CALLSITE_DELEGATE_GETTER(dataOperandHasImpliedAttr(i, Kind));
408 /// Extract the alignment of the return value.
409 unsigned getRetAlignment() const {
410 CALLSITE_DELEGATE_GETTER(getRetAlignment());
413 /// Extract the alignment for a call or parameter (0=unknown).
414 unsigned getParamAlignment(unsigned ArgNo) const {
415 CALLSITE_DELEGATE_GETTER(getParamAlignment(ArgNo));
418 /// Extract the number of dereferenceable bytes for a call or parameter
419 /// (0=unknown).
420 uint64_t getDereferenceableBytes(unsigned i) const {
421 CALLSITE_DELEGATE_GETTER(getDereferenceableBytes(i));
424 /// Extract the number of dereferenceable_or_null bytes for a call or
425 /// parameter (0=unknown).
426 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
427 CALLSITE_DELEGATE_GETTER(getDereferenceableOrNullBytes(i));
430 /// Determine if the return value is marked with NoAlias attribute.
431 bool returnDoesNotAlias() const {
432 CALLSITE_DELEGATE_GETTER(returnDoesNotAlias());
435 /// Return true if the call should not be treated as a call to a builtin.
436 bool isNoBuiltin() const {
437 CALLSITE_DELEGATE_GETTER(isNoBuiltin());
440 /// Return true if the call requires strict floating point semantics.
441 bool isStrictFP() const {
442 CALLSITE_DELEGATE_GETTER(isStrictFP());
445 /// Return true if the call should not be inlined.
446 bool isNoInline() const {
447 CALLSITE_DELEGATE_GETTER(isNoInline());
449 void setIsNoInline(bool Value = true) {
450 CALLSITE_DELEGATE_SETTER(setIsNoInline(Value));
453 /// Determine if the call does not access memory.
454 bool doesNotAccessMemory() const {
455 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
457 void setDoesNotAccessMemory() {
458 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory());
461 /// Determine if the call does not access or only reads memory.
462 bool onlyReadsMemory() const {
463 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
465 void setOnlyReadsMemory() {
466 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory());
469 /// Determine if the call does not access or only writes memory.
470 bool doesNotReadMemory() const {
471 CALLSITE_DELEGATE_GETTER(doesNotReadMemory());
473 void setDoesNotReadMemory() {
474 CALLSITE_DELEGATE_SETTER(setDoesNotReadMemory());
477 /// Determine if the call can access memmory only using pointers based
478 /// on its arguments.
479 bool onlyAccessesArgMemory() const {
480 CALLSITE_DELEGATE_GETTER(onlyAccessesArgMemory());
482 void setOnlyAccessesArgMemory() {
483 CALLSITE_DELEGATE_SETTER(setOnlyAccessesArgMemory());
486 /// Determine if the function may only access memory that is
487 /// inaccessible from the IR.
488 bool onlyAccessesInaccessibleMemory() const {
489 CALLSITE_DELEGATE_GETTER(onlyAccessesInaccessibleMemory());
491 void setOnlyAccessesInaccessibleMemory() {
492 CALLSITE_DELEGATE_SETTER(setOnlyAccessesInaccessibleMemory());
495 /// Determine if the function may only access memory that is
496 /// either inaccessible from the IR or pointed to by its arguments.
497 bool onlyAccessesInaccessibleMemOrArgMem() const {
498 CALLSITE_DELEGATE_GETTER(onlyAccessesInaccessibleMemOrArgMem());
500 void setOnlyAccessesInaccessibleMemOrArgMem() {
501 CALLSITE_DELEGATE_SETTER(setOnlyAccessesInaccessibleMemOrArgMem());
504 /// Determine if the call cannot return.
505 bool doesNotReturn() const {
506 CALLSITE_DELEGATE_GETTER(doesNotReturn());
508 void setDoesNotReturn() {
509 CALLSITE_DELEGATE_SETTER(setDoesNotReturn());
512 /// Determine if the call cannot unwind.
513 bool doesNotThrow() const {
514 CALLSITE_DELEGATE_GETTER(doesNotThrow());
516 void setDoesNotThrow() {
517 CALLSITE_DELEGATE_SETTER(setDoesNotThrow());
520 /// Determine if the call can be duplicated.
521 bool cannotDuplicate() const {
522 CALLSITE_DELEGATE_GETTER(cannotDuplicate());
524 void setCannotDuplicate() {
525 CALLSITE_DELEGATE_SETTER(setCannotDuplicate());
528 /// Determine if the call is convergent.
529 bool isConvergent() const {
530 CALLSITE_DELEGATE_GETTER(isConvergent());
532 void setConvergent() {
533 CALLSITE_DELEGATE_SETTER(setConvergent());
535 void setNotConvergent() {
536 CALLSITE_DELEGATE_SETTER(setNotConvergent());
539 unsigned getNumOperandBundles() const {
540 CALLSITE_DELEGATE_GETTER(getNumOperandBundles());
543 bool hasOperandBundles() const {
544 CALLSITE_DELEGATE_GETTER(hasOperandBundles());
547 unsigned getBundleOperandsStartIndex() const {
548 CALLSITE_DELEGATE_GETTER(getBundleOperandsStartIndex());
551 unsigned getBundleOperandsEndIndex() const {
552 CALLSITE_DELEGATE_GETTER(getBundleOperandsEndIndex());
555 unsigned getNumTotalBundleOperands() const {
556 CALLSITE_DELEGATE_GETTER(getNumTotalBundleOperands());
559 OperandBundleUse getOperandBundleAt(unsigned Index) const {
560 CALLSITE_DELEGATE_GETTER(getOperandBundleAt(Index));
563 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
564 CALLSITE_DELEGATE_GETTER(getOperandBundle(Name));
567 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
568 CALLSITE_DELEGATE_GETTER(getOperandBundle(ID));
571 unsigned countOperandBundlesOfType(uint32_t ID) const {
572 CALLSITE_DELEGATE_GETTER(countOperandBundlesOfType(ID));
575 bool isBundleOperand(unsigned Idx) const {
576 CALLSITE_DELEGATE_GETTER(isBundleOperand(Idx));
579 IterTy arg_begin() const {
580 CALLSITE_DELEGATE_GETTER(arg_begin());
583 IterTy arg_end() const {
584 CALLSITE_DELEGATE_GETTER(arg_end());
587 #undef CALLSITE_DELEGATE_GETTER
588 #undef CALLSITE_DELEGATE_SETTER
590 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
591 // Since this is actually a getter that "looks like" a setter, don't use the
592 // above macros to avoid confusion.
593 cast<CallBase>(getInstruction())->getOperandBundlesAsDefs(Defs);
596 /// Determine whether this data operand is not captured.
597 bool doesNotCapture(unsigned OpNo) const {
598 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
601 /// Determine whether this argument is passed by value.
602 bool isByValArgument(unsigned ArgNo) const {
603 return paramHasAttr(ArgNo, Attribute::ByVal);
606 /// Determine whether this argument is passed in an alloca.
607 bool isInAllocaArgument(unsigned ArgNo) const {
608 return paramHasAttr(ArgNo, Attribute::InAlloca);
611 /// Determine whether this argument is passed by value or in an alloca.
612 bool isByValOrInAllocaArgument(unsigned ArgNo) const {
613 return paramHasAttr(ArgNo, Attribute::ByVal) ||
614 paramHasAttr(ArgNo, Attribute::InAlloca);
617 /// Determine if there are is an inalloca argument. Only the last argument can
618 /// have the inalloca attribute.
619 bool hasInAllocaArgument() const {
620 return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
623 bool doesNotAccessMemory(unsigned OpNo) const {
624 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
627 bool onlyReadsMemory(unsigned OpNo) const {
628 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
629 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
632 bool doesNotReadMemory(unsigned OpNo) const {
633 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::WriteOnly) ||
634 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
637 /// Return true if the return value is known to be not null.
638 /// This may be because it has the nonnull attribute, or because at least
639 /// one byte is dereferenceable and the pointer is in addrspace(0).
640 bool isReturnNonNull() const {
641 if (hasRetAttr(Attribute::NonNull))
642 return true;
643 else if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 &&
644 !NullPointerIsDefined(getCaller(),
645 getType()->getPointerAddressSpace()))
646 return true;
648 return false;
651 /// Returns true if this CallSite passes the given Value* as an argument to
652 /// the called function.
653 bool hasArgument(const Value *Arg) const {
654 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E;
655 ++AI)
656 if (AI->get() == Arg)
657 return true;
658 return false;
661 private:
662 IterTy getCallee() const {
663 return cast<CallBase>(getInstruction())->op_end() - 1;
667 class CallSite : public CallSiteBase<Function, BasicBlock, Value, User, Use,
668 Instruction, CallInst, InvokeInst,
669 CallBrInst, User::op_iterator> {
670 public:
671 CallSite() = default;
672 CallSite(CallSiteBase B) : CallSiteBase(B) {}
673 CallSite(CallInst *CI) : CallSiteBase(CI) {}
674 CallSite(InvokeInst *II) : CallSiteBase(II) {}
675 CallSite(CallBrInst *CBI) : CallSiteBase(CBI) {}
676 explicit CallSite(Instruction *II) : CallSiteBase(II) {}
677 explicit CallSite(Value *V) : CallSiteBase(V) {}
679 bool operator==(const CallSite &CS) const { return I == CS.I; }
680 bool operator!=(const CallSite &CS) const { return I != CS.I; }
681 bool operator<(const CallSite &CS) const {
682 return getInstruction() < CS.getInstruction();
685 private:
686 friend struct DenseMapInfo<CallSite>;
688 User::op_iterator getCallee() const;
691 /// AbstractCallSite
693 /// An abstract call site is a wrapper that allows to treat direct,
694 /// indirect, and callback calls the same. If an abstract call site
695 /// represents a direct or indirect call site it behaves like a stripped
696 /// down version of a normal call site object. The abstract call site can
697 /// also represent a callback call, thus the fact that the initially
698 /// called function (=broker) may invoke a third one (=callback callee).
699 /// In this case, the abstract call site hides the middle man, hence the
700 /// broker function. The result is a representation of the callback call,
701 /// inside the broker, but in the context of the original call to the broker.
703 /// There are up to three functions involved when we talk about callback call
704 /// sites. The caller (1), which invokes the broker function. The broker
705 /// function (2), that will invoke the callee zero or more times. And finally
706 /// the callee (3), which is the target of the callback call.
708 /// The abstract call site will handle the mapping from parameters to arguments
709 /// depending on the semantic of the broker function. However, it is important
710 /// to note that the mapping is often partial. Thus, some arguments of the
711 /// call/invoke instruction are mapped to parameters of the callee while others
712 /// are not.
713 class AbstractCallSite {
714 public:
716 /// The encoding of a callback with regards to the underlying instruction.
717 struct CallbackInfo {
719 /// For direct/indirect calls the parameter encoding is empty. If it is not,
720 /// the abstract call site represents a callback. In that case, the first
721 /// element of the encoding vector represents which argument of the call
722 /// site CS is the callback callee. The remaining elements map parameters
723 /// (identified by their position) to the arguments that will be passed
724 /// through (also identified by position but in the call site instruction).
726 /// NOTE that we use LLVM argument numbers (starting at 0) and not
727 /// clang/soruce argument numbers (starting at 1). The -1 entries represent
728 /// unknown values that are passed to the callee.
729 using ParameterEncodingTy = SmallVector<int, 0>;
730 ParameterEncodingTy ParameterEncoding;
734 private:
736 /// The underlying call site:
737 /// caller -> callee, if this is a direct or indirect call site
738 /// caller -> broker function, if this is a callback call site
739 CallSite CS;
741 /// The encoding of a callback with regards to the underlying instruction.
742 CallbackInfo CI;
744 public:
745 /// Sole constructor for abstract call sites (ACS).
747 /// An abstract call site can only be constructed through a llvm::Use because
748 /// each operand (=use) of an instruction could potentially be a different
749 /// abstract call site. Furthermore, even if the value of the llvm::Use is the
750 /// same, and the user is as well, the abstract call sites might not be.
752 /// If a use is not associated with an abstract call site the constructed ACS
753 /// will evaluate to false if converted to a boolean.
755 /// If the use is the callee use of a call or invoke instruction, the
756 /// constructed abstract call site will behave as a llvm::CallSite would.
758 /// If the use is not a callee use of a call or invoke instruction, the
759 /// callback metadata is used to determine the argument <-> parameter mapping
760 /// as well as the callee of the abstract call site.
761 AbstractCallSite(const Use *U);
763 /// Conversion operator to conveniently check for a valid/initialized ACS.
764 explicit operator bool() const { return (bool)CS; }
766 /// Return the underlying instruction.
767 Instruction *getInstruction() const { return CS.getInstruction(); }
769 /// Return the call site abstraction for the underlying instruction.
770 CallSite getCallSite() const { return CS; }
772 /// Return true if this ACS represents a direct call.
773 bool isDirectCall() const {
774 return !isCallbackCall() && !CS.isIndirectCall();
777 /// Return true if this ACS represents an indirect call.
778 bool isIndirectCall() const {
779 return !isCallbackCall() && CS.isIndirectCall();
782 /// Return true if this ACS represents a callback call.
783 bool isCallbackCall() const {
784 // For a callback call site the callee is ALWAYS stored first in the
785 // transitive values vector. Thus, a non-empty vector indicates a callback.
786 return !CI.ParameterEncoding.empty();
789 /// Return true if @p UI is the use that defines the callee of this ACS.
790 bool isCallee(Value::const_user_iterator UI) const {
791 return isCallee(&UI.getUse());
794 /// Return true if @p U is the use that defines the callee of this ACS.
795 bool isCallee(const Use *U) const {
796 if (isDirectCall())
797 return CS.isCallee(U);
799 assert(!CI.ParameterEncoding.empty() &&
800 "Callback without parameter encoding!");
802 return (int)CS.getArgumentNo(U) == CI.ParameterEncoding[0];
805 /// Return the number of parameters of the callee.
806 unsigned getNumArgOperands() const {
807 if (isDirectCall())
808 return CS.getNumArgOperands();
809 // Subtract 1 for the callee encoding.
810 return CI.ParameterEncoding.size() - 1;
813 /// Return the operand index of the underlying instruction associated with @p
814 /// Arg.
815 int getCallArgOperandNo(Argument &Arg) const {
816 return getCallArgOperandNo(Arg.getArgNo());
819 /// Return the operand index of the underlying instruction associated with
820 /// the function parameter number @p ArgNo or -1 if there is none.
821 int getCallArgOperandNo(unsigned ArgNo) const {
822 if (isDirectCall())
823 return ArgNo;
824 // Add 1 for the callee encoding.
825 return CI.ParameterEncoding[ArgNo + 1];
828 /// Return the operand of the underlying instruction associated with @p Arg.
829 Value *getCallArgOperand(Argument &Arg) const {
830 return getCallArgOperand(Arg.getArgNo());
833 /// Return the operand of the underlying instruction associated with the
834 /// function parameter number @p ArgNo or nullptr if there is none.
835 Value *getCallArgOperand(unsigned ArgNo) const {
836 if (isDirectCall())
837 return CS.getArgOperand(ArgNo);
838 // Add 1 for the callee encoding.
839 return CI.ParameterEncoding[ArgNo + 1] >= 0
840 ? CS.getArgOperand(CI.ParameterEncoding[ArgNo + 1])
841 : nullptr;
844 /// Return the operand index of the underlying instruction associated with the
845 /// callee of this ACS. Only valid for callback calls!
846 int getCallArgOperandNoForCallee() const {
847 assert(isCallbackCall());
848 assert(CI.ParameterEncoding.size() && CI.ParameterEncoding[0] > 0);
849 return CI.ParameterEncoding[0];
852 /// Return the pointer to function that is being called.
853 Value *getCalledValue() const {
854 if (isDirectCall())
855 return CS.getCalledValue();
856 return CS.getArgOperand(getCallArgOperandNoForCallee());
859 /// Return the function being called if this is a direct call, otherwise
860 /// return null (if it's an indirect call).
861 Function *getCalledFunction() const {
862 Value *V = getCalledValue();
863 return V ? dyn_cast<Function>(V->stripPointerCasts()) : nullptr;
867 template <> struct DenseMapInfo<CallSite> {
868 using BaseInfo = DenseMapInfo<decltype(CallSite::I)>;
870 static CallSite getEmptyKey() {
871 CallSite CS;
872 CS.I = BaseInfo::getEmptyKey();
873 return CS;
876 static CallSite getTombstoneKey() {
877 CallSite CS;
878 CS.I = BaseInfo::getTombstoneKey();
879 return CS;
882 static unsigned getHashValue(const CallSite &CS) {
883 return BaseInfo::getHashValue(CS.I);
886 static bool isEqual(const CallSite &LHS, const CallSite &RHS) {
887 return LHS == RHS;
891 /// Establish a view to a call site for examination.
892 class ImmutableCallSite : public CallSiteBase<> {
893 public:
894 ImmutableCallSite() = default;
895 ImmutableCallSite(const CallInst *CI) : CallSiteBase(CI) {}
896 ImmutableCallSite(const InvokeInst *II) : CallSiteBase(II) {}
897 ImmutableCallSite(const CallBrInst *CBI) : CallSiteBase(CBI) {}
898 explicit ImmutableCallSite(const Instruction *II) : CallSiteBase(II) {}
899 explicit ImmutableCallSite(const Value *V) : CallSiteBase(V) {}
900 ImmutableCallSite(CallSite CS) : CallSiteBase(CS.getInstruction()) {}
903 } // end namespace llvm
905 #endif // LLVM_IR_CALLSITE_H