[OperandBundles] Have InstCombine play nice with operand bundles
[oota-llvm.git] / include / llvm / IR / CallSite.h
1 //===- CallSite.h - Abstract Call & Invoke instrs ---------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the CallSite class, which is a handy wrapper for code that
11 // wants to treat Call and Invoke instructions in a generic way. When in non-
12 // mutation context (e.g. an analysis) ImmutableCallSite should be used.
13 // Finally, when some degree of customization is necessary between these two
14 // extremes, CallSiteBase<> can be supplied with fine-tuned parameters.
15 //
16 // NOTE: These classes are supposed to have "value semantics". So they should be
17 // passed by value, not by reference; they should not be "new"ed or "delete"d.
18 // They are efficiently copyable, assignable and constructable, with cost
19 // equivalent to copying a pointer (notice that they have only a single data
20 // member). The internal representation carries a flag which indicates which of
21 // the two variants is enclosed. This allows for cheaper checks when various
22 // accessors of CallSite are employed.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #ifndef LLVM_IR_CALLSITE_H
27 #define LLVM_IR_CALLSITE_H
28
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/Instructions.h"
34
35 namespace llvm {
36
37 class CallInst;
38 class InvokeInst;
39
40 template <typename FunTy = const Function,
41           typename BBTy = const BasicBlock,
42           typename ValTy = const Value,
43           typename UserTy = const User,
44           typename UseTy = const Use,
45           typename InstrTy = const Instruction,
46           typename CallTy = const CallInst,
47           typename InvokeTy = const InvokeInst,
48           typename IterTy = User::const_op_iterator>
49 class CallSiteBase {
50 protected:
51   PointerIntPair<InstrTy*, 1, bool> I;
52
53   CallSiteBase() : I(nullptr, false) {}
54   CallSiteBase(CallTy *CI) : I(CI, true) { assert(CI); }
55   CallSiteBase(InvokeTy *II) : I(II, false) { assert(II); }
56   explicit CallSiteBase(ValTy *II) { *this = get(II); }
57
58 private:
59   /// CallSiteBase::get - This static method is sort of like a constructor.  It
60   /// will create an appropriate call site for a Call or Invoke instruction, but
61   /// it can also create a null initialized CallSiteBase object for something
62   /// which is NOT a call site.
63   ///
64   static CallSiteBase get(ValTy *V) {
65     if (InstrTy *II = dyn_cast<InstrTy>(V)) {
66       if (II->getOpcode() == Instruction::Call)
67         return CallSiteBase(static_cast<CallTy*>(II));
68       else if (II->getOpcode() == Instruction::Invoke)
69         return CallSiteBase(static_cast<InvokeTy*>(II));
70     }
71     return CallSiteBase();
72   }
73
74 public:
75   /// isCall - true if a CallInst is enclosed.
76   /// Note that !isCall() does not mean it is an InvokeInst enclosed,
77   /// it also could signify a NULL Instruction pointer.
78   bool isCall() const { return I.getInt(); }
79
80   /// isInvoke - true if a InvokeInst is enclosed.
81   ///
82   bool isInvoke() const { return getInstruction() && !I.getInt(); }
83
84   InstrTy *getInstruction() const { return I.getPointer(); }
85   InstrTy *operator->() const { return I.getPointer(); }
86   explicit operator bool() const { return I.getPointer(); }
87
88   /// Get the basic block containing the call site
89   BBTy* getParent() const { return getInstruction()->getParent(); }
90
91   /// getCalledValue - Return the pointer to function that is being called.
92   ///
93   ValTy *getCalledValue() const {
94     assert(getInstruction() && "Not a call or invoke instruction!");
95     return *getCallee();
96   }
97
98   /// getCalledFunction - Return the function being called if this is a direct
99   /// call, otherwise return null (if it's an indirect call).
100   ///
101   FunTy *getCalledFunction() const {
102     return dyn_cast<FunTy>(getCalledValue());
103   }
104
105   /// setCalledFunction - Set the callee to the specified value.
106   ///
107   void setCalledFunction(Value *V) {
108     assert(getInstruction() && "Not a call or invoke instruction!");
109     *getCallee() = V;
110   }
111
112   /// isCallee - Determine whether the passed iterator points to the
113   /// callee operand's Use.
114   bool isCallee(Value::const_user_iterator UI) const {
115     return isCallee(&UI.getUse());
116   }
117
118   /// Determine whether this Use is the callee operand's Use.
119   bool isCallee(const Use *U) const { return getCallee() == U; }
120
121   /// \brief Determine whether the passed iterator points to an argument
122   /// operand.
123   bool isArgOperand(Value::const_user_iterator UI) const {
124     return isArgOperand(&UI.getUse());
125   }
126
127   /// \brief Determine whether the passed use points to an argument operand.
128   bool isArgOperand(const Use *U) const {
129     return arg_begin() <= U && U < arg_end();
130   }
131
132   /// \brief Determine whether the passed iterator points to a bundle operand.
133   bool isBundleOperand(Value::const_user_iterator UI) const {
134     return isBundleOperand(&UI.getUse());
135   }
136
137   /// \brief Determine whether the passed use points to a bundle operand.
138   bool isBundleOperand(const Use *U) const {
139     if (!hasOperandBundles())
140       return false;
141     unsigned OperandNo = U->getOperandNo();
142     return getBundleOperandsStartIndex() <= OperandNo &&
143            OperandNo < getBundleOperandsEndIndex();
144   }
145
146   /// \brief Determine whether the passed iterator points to a data operand.
147   bool isDataOperand(Value::const_user_iterator UI) const {
148     return isDataOperand(&UI.getUse());
149   }
150
151   /// \brief Determine whether the passed use points to a data operand.
152   bool isDataOperand(const Use *U) const {
153     return data_operands_begin() <= U && U < data_operands_end();
154   }
155
156   ValTy *getArgument(unsigned ArgNo) const {
157     assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!");
158     return *(arg_begin() + ArgNo);
159   }
160
161   void setArgument(unsigned ArgNo, Value* newVal) {
162     assert(getInstruction() && "Not a call or invoke instruction!");
163     assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!");
164     getInstruction()->setOperand(ArgNo, newVal);
165   }
166
167   /// Given a value use iterator, returns the argument that corresponds to it.
168   /// Iterator must actually correspond to an argument.
169   unsigned getArgumentNo(Value::const_user_iterator I) const {
170     return getArgumentNo(&I.getUse());
171   }
172
173   /// Given a use for an argument, get the argument number that corresponds to
174   /// it.
175   unsigned getArgumentNo(const Use *U) const {
176     assert(getInstruction() && "Not a call or invoke instruction!");
177     assert(isArgOperand(U) && "Argument # out of range!");
178     return U - arg_begin();
179   }
180
181   /// arg_iterator - The type of iterator to use when looping over actual
182   /// arguments at this call site.
183   typedef IterTy arg_iterator;
184
185   iterator_range<IterTy> args() const {
186     return make_range(arg_begin(), arg_end());
187   }
188   bool arg_empty() const { return arg_end() == arg_begin(); }
189   unsigned arg_size() const { return unsigned(arg_end() - arg_begin()); }
190
191   /// Given a value use iterator, returns the data operand that corresponds to
192   /// it.
193   /// Iterator must actually correspond to a data operand.
194   unsigned getDataOperandNo(Value::const_user_iterator UI) const {
195     return getDataOperandNo(&UI.getUse());
196   }
197
198   /// Given a use for a data operand, get the data operand number that
199   /// corresponds to it.
200   unsigned getDataOperandNo(const Use *U) const {
201     assert(getInstruction() && "Not a call or invoke instruction!");
202     assert(isDataOperand(U) && "Data operand # out of range!");
203     return U - data_operands_begin();
204   }
205
206   /// Type of iterator to use when looping over data operands at this call site
207   /// (see below).
208   typedef IterTy data_operand_iterator;
209
210   /// data_operands_begin/data_operands_end - Return iterators iterating over
211   /// the call / invoke argument list and bundle operands.  For invokes, this is
212   /// the set of instruction operands except the invoke target and the two
213   /// successor blocks; and for calls this is the set of instruction operands
214   /// except the call target.
215
216   IterTy data_operands_begin() const {
217     assert(getInstruction() && "Not a call or invoke instruction!");
218     return (*this)->op_begin();
219   }
220   IterTy data_operands_end() const {
221     assert(getInstruction() && "Not a call or invoke instruction!");
222     return (*this)->op_end() - (isCall() ? 1 : 3);
223   }
224   iterator_range<IterTy> data_ops() const {
225     return make_range(data_operands_begin(), data_operands_end());
226   }
227   bool data_operands_empty() const {
228     return data_operands_end() == data_operands_begin();
229   }
230   unsigned data_operands_size() const {
231     return std::distance(data_operands_begin(), data_operands_end());
232   }
233
234   /// getType - Return the type of the instruction that generated this call site
235   ///
236   Type *getType() const { return (*this)->getType(); }
237
238   /// getCaller - Return the caller function for this call site
239   ///
240   FunTy *getCaller() const { return (*this)->getParent()->getParent(); }
241
242   /// \brief Tests if this call site must be tail call optimized.  Only a
243   /// CallInst can be tail call optimized.
244   bool isMustTailCall() const {
245     return isCall() && cast<CallInst>(getInstruction())->isMustTailCall();
246   }
247
248   /// \brief Tests if this call site is marked as a tail call.
249   bool isTailCall() const {
250     return isCall() && cast<CallInst>(getInstruction())->isTailCall();
251   }
252
253 #define CALLSITE_DELEGATE_GETTER(METHOD) \
254   InstrTy *II = getInstruction();    \
255   return isCall()                        \
256     ? cast<CallInst>(II)->METHOD         \
257     : cast<InvokeInst>(II)->METHOD
258
259 #define CALLSITE_DELEGATE_SETTER(METHOD) \
260   InstrTy *II = getInstruction();    \
261   if (isCall())                          \
262     cast<CallInst>(II)->METHOD;          \
263   else                                   \
264     cast<InvokeInst>(II)->METHOD
265
266   unsigned getNumArgOperands() const {
267     CALLSITE_DELEGATE_GETTER(getNumArgOperands());
268   }
269
270   ValTy *getArgOperand(unsigned i) const {
271     CALLSITE_DELEGATE_GETTER(getArgOperand(i));
272   }
273
274   bool isInlineAsm() const {
275     if (isCall())
276       return cast<CallInst>(getInstruction())->isInlineAsm();
277     return false;
278   }
279
280   /// getCallingConv/setCallingConv - get or set the calling convention of the
281   /// call.
282   CallingConv::ID getCallingConv() const {
283     CALLSITE_DELEGATE_GETTER(getCallingConv());
284   }
285   void setCallingConv(CallingConv::ID CC) {
286     CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
287   }
288
289   FunctionType *getFunctionType() const {
290     CALLSITE_DELEGATE_GETTER(getFunctionType());
291   }
292
293   void mutateFunctionType(FunctionType *Ty) const {
294     CALLSITE_DELEGATE_SETTER(mutateFunctionType(Ty));
295   }
296
297   /// getAttributes/setAttributes - get or set the parameter attributes of
298   /// the call.
299   const AttributeSet &getAttributes() const {
300     CALLSITE_DELEGATE_GETTER(getAttributes());
301   }
302   void setAttributes(const AttributeSet &PAL) {
303     CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
304   }
305
306   /// \brief Return true if this function has the given attribute.
307   bool hasFnAttr(Attribute::AttrKind A) const {
308     CALLSITE_DELEGATE_GETTER(hasFnAttr(A));
309   }
310
311   /// \brief Return true if the call or the callee has the given attribute.
312   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const {
313     CALLSITE_DELEGATE_GETTER(paramHasAttr(i, A));
314   }
315
316   /// \brief Return true if the data operand at index \p i directly or
317   /// indirectly has the attribute \p A.
318   ///
319   /// Normal call or invoke arguments have per operand attributes, as specified
320   /// in the attribute set attached to this instruction, while operand bundle
321   /// operands may have some attributes implied by the type of its containing
322   /// operand bundle.
323   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind A) const {
324     CALLSITE_DELEGATE_GETTER(dataOperandHasImpliedAttr(i, A));
325   }
326
327   /// @brief Extract the alignment for a call or parameter (0=unknown).
328   uint16_t getParamAlignment(uint16_t i) const {
329     CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
330   }
331
332   /// @brief Extract the number of dereferenceable bytes for a call or
333   /// parameter (0=unknown).
334   uint64_t getDereferenceableBytes(uint16_t i) const {
335     CALLSITE_DELEGATE_GETTER(getDereferenceableBytes(i));
336   }
337
338   /// @brief Extract the number of dereferenceable_or_null bytes for a call or
339   /// parameter (0=unknown).
340   uint64_t getDereferenceableOrNullBytes(uint16_t i) const {
341     CALLSITE_DELEGATE_GETTER(getDereferenceableOrNullBytes(i));
342   }
343
344   /// @brief Determine if the parameter or return value is marked with NoAlias
345   /// attribute.
346   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
347   bool doesNotAlias(unsigned n) const {
348     CALLSITE_DELEGATE_GETTER(doesNotAlias(n));
349   }
350
351   /// \brief Return true if the call should not be treated as a call to a
352   /// builtin.
353   bool isNoBuiltin() const {
354     CALLSITE_DELEGATE_GETTER(isNoBuiltin());
355   }
356
357   /// @brief Return true if the call should not be inlined.
358   bool isNoInline() const {
359     CALLSITE_DELEGATE_GETTER(isNoInline());
360   }
361   void setIsNoInline(bool Value = true) {
362     CALLSITE_DELEGATE_SETTER(setIsNoInline(Value));
363   }
364
365   /// @brief Determine if the call does not access memory.
366   bool doesNotAccessMemory() const {
367     CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
368   }
369   void setDoesNotAccessMemory() {
370     CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory());
371   }
372
373   /// @brief Determine if the call does not access or only reads memory.
374   bool onlyReadsMemory() const {
375     CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
376   }
377   void setOnlyReadsMemory() {
378     CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory());
379   }
380
381   /// @brief Determine if the call can access memmory only using pointers based
382   /// on its arguments.
383   bool onlyAccessesArgMemory() const {
384     CALLSITE_DELEGATE_GETTER(onlyAccessesArgMemory());
385   }
386   void setOnlyAccessesArgMemory() {
387     CALLSITE_DELEGATE_SETTER(setOnlyAccessesArgMemory());
388   }
389
390   /// @brief Determine if the call cannot return.
391   bool doesNotReturn() const {
392     CALLSITE_DELEGATE_GETTER(doesNotReturn());
393   }
394   void setDoesNotReturn() {
395     CALLSITE_DELEGATE_SETTER(setDoesNotReturn());
396   }
397
398   /// @brief Determine if the call cannot unwind.
399   bool doesNotThrow() const {
400     CALLSITE_DELEGATE_GETTER(doesNotThrow());
401   }
402   void setDoesNotThrow() {
403     CALLSITE_DELEGATE_SETTER(setDoesNotThrow());
404   }
405
406   unsigned getNumOperandBundles() const {
407     CALLSITE_DELEGATE_GETTER(getNumOperandBundles());
408   }
409
410   bool hasOperandBundles() const {
411     CALLSITE_DELEGATE_GETTER(hasOperandBundles());
412   }
413
414   unsigned getBundleOperandsStartIndex() const {
415     CALLSITE_DELEGATE_GETTER(getBundleOperandsStartIndex());
416   }
417
418   unsigned getBundleOperandsEndIndex() const {
419     CALLSITE_DELEGATE_GETTER(getBundleOperandsEndIndex());
420   }
421
422   unsigned getNumTotalBundleOperands() const {
423     CALLSITE_DELEGATE_GETTER(getNumTotalBundleOperands());
424   }
425
426   OperandBundleUse getOperandBundleAt(unsigned Index) const {
427     CALLSITE_DELEGATE_GETTER(getOperandBundleAt(Index));
428   }
429
430   Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
431     CALLSITE_DELEGATE_GETTER(getOperandBundle(Name));
432   }
433
434   Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
435     CALLSITE_DELEGATE_GETTER(getOperandBundle(ID));
436   }
437
438   IterTy arg_begin() const {
439     CALLSITE_DELEGATE_GETTER(arg_begin());
440   }
441
442   IterTy arg_end() const {
443     CALLSITE_DELEGATE_GETTER(arg_end());
444   }
445
446 #undef CALLSITE_DELEGATE_GETTER
447 #undef CALLSITE_DELEGATE_SETTER
448
449   void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
450     const Instruction *II = getInstruction();
451     // Since this is actually a getter that "looks like" a setter, don't use the
452     // above macros to avoid confusion.
453     if (isCall())
454       cast<CallInst>(II)->getOperandBundlesAsDefs(Defs);
455     else
456       cast<InvokeInst>(II)->getOperandBundlesAsDefs(Defs);
457   }
458
459   /// @brief Determine whether this data operand is not captured.
460   bool doesNotCapture(unsigned OpNo) const {
461     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
462   }
463
464   /// @brief Determine whether this argument is passed by value.
465   bool isByValArgument(unsigned ArgNo) const {
466     return paramHasAttr(ArgNo + 1, Attribute::ByVal);
467   }
468
469   /// @brief Determine whether this argument is passed in an alloca.
470   bool isInAllocaArgument(unsigned ArgNo) const {
471     return paramHasAttr(ArgNo + 1, Attribute::InAlloca);
472   }
473
474   /// @brief Determine whether this argument is passed by value or in an alloca.
475   bool isByValOrInAllocaArgument(unsigned ArgNo) const {
476     return paramHasAttr(ArgNo + 1, Attribute::ByVal) ||
477            paramHasAttr(ArgNo + 1, Attribute::InAlloca);
478   }
479
480   /// @brief Determine if there are is an inalloca argument.  Only the last
481   /// argument can have the inalloca attribute.
482   bool hasInAllocaArgument() const {
483     return paramHasAttr(arg_size(), Attribute::InAlloca);
484   }
485
486   bool doesNotAccessMemory(unsigned OpNo) const {
487     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
488   }
489
490   bool onlyReadsMemory(unsigned OpNo) const {
491     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
492            dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
493   }
494
495   /// @brief Return true if the return value is known to be not null.
496   /// This may be because it has the nonnull attribute, or because at least
497   /// one byte is dereferenceable and the pointer is in addrspace(0).
498   bool isReturnNonNull() const {
499     if (paramHasAttr(0, Attribute::NonNull))
500       return true;
501     else if (getDereferenceableBytes(0) > 0 &&
502              getType()->getPointerAddressSpace() == 0)
503       return true;
504
505     return false;
506   }
507
508   /// hasArgument - Returns true if this CallSite passes the given Value* as an
509   /// argument to the called function.
510   bool hasArgument(const Value *Arg) const {
511     for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E;
512          ++AI)
513       if (AI->get() == Arg)
514         return true;
515     return false;
516   }
517
518 private:
519   IterTy getCallee() const {
520     if (isCall()) // Skip Callee
521       return cast<CallInst>(getInstruction())->op_end() - 1;
522     else // Skip BB, BB, Callee
523       return cast<InvokeInst>(getInstruction())->op_end() - 3;
524   }
525 };
526
527 class CallSite : public CallSiteBase<Function, BasicBlock, Value, User, Use,
528                                      Instruction, CallInst, InvokeInst,
529                                      User::op_iterator> {
530 public:
531   CallSite() {}
532   CallSite(CallSiteBase B) : CallSiteBase(B) {}
533   CallSite(CallInst *CI) : CallSiteBase(CI) {}
534   CallSite(InvokeInst *II) : CallSiteBase(II) {}
535   explicit CallSite(Instruction *II) : CallSiteBase(II) {}
536   explicit CallSite(Value *V) : CallSiteBase(V) {}
537
538   bool operator==(const CallSite &CS) const { return I == CS.I; }
539   bool operator!=(const CallSite &CS) const { return I != CS.I; }
540   bool operator<(const CallSite &CS) const {
541     return getInstruction() < CS.getInstruction();
542   }
543
544 private:
545   User::op_iterator getCallee() const;
546 };
547
548 /// ImmutableCallSite - establish a view to a call site for examination
549 class ImmutableCallSite : public CallSiteBase<> {
550 public:
551   ImmutableCallSite() {}
552   ImmutableCallSite(const CallInst *CI) : CallSiteBase(CI) {}
553   ImmutableCallSite(const InvokeInst *II) : CallSiteBase(II) {}
554   explicit ImmutableCallSite(const Instruction *II) : CallSiteBase(II) {}
555   explicit ImmutableCallSite(const Value *V) : CallSiteBase(V) {}
556   ImmutableCallSite(CallSite CS) : CallSiteBase(CS.getInstruction()) {}
557 };
558
559 } // End llvm namespace
560
561 #endif