CGCXXABI.h revision 256281
1//===----- CGCXXABI.h - Interface to C++ ABIs -------------------*- 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 provides an abstract class for C++ code generation. Concrete subclasses
11// of this implement code generation for specific C++ ABIs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef CLANG_CODEGEN_CXXABI_H
16#define CLANG_CODEGEN_CXXABI_H
17
18#include "CodeGenFunction.h"
19#include "clang/Basic/LLVM.h"
20
21namespace llvm {
22  class Constant;
23  class Type;
24  class Value;
25}
26
27namespace clang {
28  class CastExpr;
29  class CXXConstructorDecl;
30  class CXXDestructorDecl;
31  class CXXMethodDecl;
32  class CXXRecordDecl;
33  class FieldDecl;
34  class MangleContext;
35
36namespace CodeGen {
37  class CodeGenFunction;
38  class CodeGenModule;
39
40/// \brief Implements C++ ABI-specific code generation functions.
41class CGCXXABI {
42protected:
43  CodeGenModule &CGM;
44  OwningPtr<MangleContext> MangleCtx;
45
46  CGCXXABI(CodeGenModule &CGM)
47    : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
48
49protected:
50  ImplicitParamDecl *&getThisDecl(CodeGenFunction &CGF) {
51    return CGF.CXXABIThisDecl;
52  }
53  llvm::Value *&getThisValue(CodeGenFunction &CGF) {
54    return CGF.CXXABIThisValue;
55  }
56
57  /// Issue a diagnostic about unsupported features in the ABI.
58  void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S);
59
60  /// Get a null value for unsupported member pointers.
61  llvm::Constant *GetBogusMemberPointer(QualType T);
62
63  // FIXME: Every place that calls getVTT{Decl,Value} is something
64  // that needs to be abstracted properly.
65  ImplicitParamDecl *&getVTTDecl(CodeGenFunction &CGF) {
66    return CGF.CXXStructorImplicitParamDecl;
67  }
68  llvm::Value *&getVTTValue(CodeGenFunction &CGF) {
69    return CGF.CXXStructorImplicitParamValue;
70  }
71
72  ImplicitParamDecl *&getStructorImplicitParamDecl(CodeGenFunction &CGF) {
73    return CGF.CXXStructorImplicitParamDecl;
74  }
75  llvm::Value *&getStructorImplicitParamValue(CodeGenFunction &CGF) {
76    return CGF.CXXStructorImplicitParamValue;
77  }
78
79  /// Build a parameter variable suitable for 'this'.
80  void BuildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
81
82  /// Perform prolog initialization of the parameter variable suitable
83  /// for 'this' emitted by BuildThisParam.
84  void EmitThisParam(CodeGenFunction &CGF);
85
86  ASTContext &getContext() const { return CGM.getContext(); }
87
88  virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
89  virtual bool requiresArrayCookie(const CXXNewExpr *E);
90
91public:
92
93  virtual ~CGCXXABI();
94
95  /// Gets the mangle context.
96  MangleContext &getMangleContext() {
97    return *MangleCtx;
98  }
99
100  /// Returns true if the given instance method is one of the
101  /// kinds that the ABI says returns 'this'.
102  virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
103
104  /// Returns true if the given record type should be returned indirectly.
105  virtual bool isReturnTypeIndirect(const CXXRecordDecl *RD) const = 0;
106
107  /// Specify how one should pass an argument of a record type.
108  enum RecordArgABI {
109    /// Pass it using the normal C aggregate rules for the ABI, potentially
110    /// introducing extra copies and passing some or all of it in registers.
111    RAA_Default = 0,
112
113    /// Pass it on the stack using its defined layout.  The argument must be
114    /// evaluated directly into the correct stack position in the arguments area,
115    /// and the call machinery must not move it or introduce extra copies.
116    RAA_DirectInMemory,
117
118    /// Pass it as a pointer to temporary memory.
119    RAA_Indirect
120  };
121
122  /// Returns how an argument of the given record type should be passed.
123  virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
124
125  /// Find the LLVM type used to represent the given member pointer
126  /// type.
127  virtual llvm::Type *
128  ConvertMemberPointerType(const MemberPointerType *MPT);
129
130  /// Load a member function from an object and a member function
131  /// pointer.  Apply the this-adjustment and set 'This' to the
132  /// adjusted value.
133  virtual llvm::Value *
134  EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
135                                  llvm::Value *&This,
136                                  llvm::Value *MemPtr,
137                                  const MemberPointerType *MPT);
138
139  /// Calculate an l-value from an object and a data member pointer.
140  virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
141                                                    llvm::Value *Base,
142                                                    llvm::Value *MemPtr,
143                                            const MemberPointerType *MPT);
144
145  /// Perform a derived-to-base, base-to-derived, or bitcast member
146  /// pointer conversion.
147  virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
148                                                   const CastExpr *E,
149                                                   llvm::Value *Src);
150
151  /// Perform a derived-to-base, base-to-derived, or bitcast member
152  /// pointer conversion on a constant value.
153  virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
154                                                      llvm::Constant *Src);
155
156  /// Return true if the given member pointer can be zero-initialized
157  /// (in the C++ sense) with an LLVM zeroinitializer.
158  virtual bool isZeroInitializable(const MemberPointerType *MPT);
159
160  /// Create a null member pointer of the given type.
161  virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
162
163  /// Create a member pointer for the given method.
164  virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
165
166  /// Create a member pointer for the given field.
167  virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
168                                                CharUnits offset);
169
170  /// Create a member pointer for the given member pointer constant.
171  virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
172
173  /// Emit a comparison between two member pointers.  Returns an i1.
174  virtual llvm::Value *
175  EmitMemberPointerComparison(CodeGenFunction &CGF,
176                              llvm::Value *L,
177                              llvm::Value *R,
178                              const MemberPointerType *MPT,
179                              bool Inequality);
180
181  /// Determine if a member pointer is non-null.  Returns an i1.
182  virtual llvm::Value *
183  EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
184                             llvm::Value *MemPtr,
185                             const MemberPointerType *MPT);
186
187protected:
188  /// A utility method for computing the offset required for the given
189  /// base-to-derived or derived-to-base member-pointer conversion.
190  /// Does not handle virtual conversions (in case we ever fully
191  /// support an ABI that allows this).  Returns null if no adjustment
192  /// is required.
193  llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
194
195public:
196  /// Adjust the given non-null pointer to an object of polymorphic
197  /// type to point to the complete object.
198  ///
199  /// The IR type of the result should be a pointer but is otherwise
200  /// irrelevant.
201  virtual llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
202                                              llvm::Value *ptr,
203                                              QualType type) = 0;
204
205  /// Build the signature of the given constructor variant by adding
206  /// any required parameters.  For convenience, ResTy has been
207  /// initialized to 'void', and ArgTys has been initialized with the
208  /// type of 'this' (although this may be changed by the ABI) and
209  /// will have the formal parameters added to it afterwards.
210  ///
211  /// If there are ever any ABIs where the implicit parameters are
212  /// intermixed with the formal parameters, we can address those
213  /// then.
214  virtual void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
215                                         CXXCtorType T,
216                                         CanQualType &ResTy,
217                               SmallVectorImpl<CanQualType> &ArgTys) = 0;
218
219  virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF);
220
221  /// Build the signature of the given destructor variant by adding
222  /// any required parameters.  For convenience, ResTy has been
223  /// initialized to 'void' and ArgTys has been initialized with the
224  /// type of 'this' (although this may be changed by the ABI).
225  virtual void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
226                                        CXXDtorType T,
227                                        CanQualType &ResTy,
228                               SmallVectorImpl<CanQualType> &ArgTys) = 0;
229
230  /// Build the ABI-specific portion of the parameter list for a
231  /// function.  This generally involves a 'this' parameter and
232  /// possibly some extra data for constructors and destructors.
233  ///
234  /// ABIs may also choose to override the return type, which has been
235  /// initialized with the formal return type of the function.
236  virtual void BuildInstanceFunctionParams(CodeGenFunction &CGF,
237                                           QualType &ResTy,
238                                           FunctionArgList &Params) = 0;
239
240  /// Emit the ABI-specific prolog for the function.
241  virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
242
243  /// Emit the constructor call. Return the function that is called.
244  virtual llvm::Value *EmitConstructorCall(CodeGenFunction &CGF,
245                                   const CXXConstructorDecl *D,
246                                   CXXCtorType Type, bool ForVirtualBase,
247                                   bool Delegating,
248                                   llvm::Value *This,
249                                   CallExpr::const_arg_iterator ArgBeg,
250                                   CallExpr::const_arg_iterator ArgEnd) = 0;
251
252  /// Emit the ABI-specific virtual destructor call.
253  virtual RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
254                                           const CXXDestructorDecl *Dtor,
255                                           CXXDtorType DtorType,
256                                           SourceLocation CallLoc,
257                                           ReturnValueSlot ReturnValue,
258                                           llvm::Value *This) = 0;
259
260  virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
261                                   RValue RV, QualType ResultType);
262
263  /// Gets the pure virtual member call function.
264  virtual StringRef GetPureVirtualCallName() = 0;
265
266  /// Gets the deleted virtual member call name.
267  virtual StringRef GetDeletedVirtualCallName() = 0;
268
269  /**************************** Array cookies ******************************/
270
271  /// Returns the extra size required in order to store the array
272  /// cookie for the given new-expression.  May return 0 to indicate that no
273  /// array cookie is required.
274  ///
275  /// Several cases are filtered out before this method is called:
276  ///   - non-array allocations never need a cookie
277  ///   - calls to \::operator new(size_t, void*) never need a cookie
278  ///
279  /// \param expr - the new-expression being allocated.
280  virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
281
282  /// Initialize the array cookie for the given allocation.
283  ///
284  /// \param NewPtr - a char* which is the presumed-non-null
285  ///   return value of the allocation function
286  /// \param NumElements - the computed number of elements,
287  ///   potentially collapsed from the multidimensional array case;
288  ///   always a size_t
289  /// \param ElementType - the base element allocated type,
290  ///   i.e. the allocated type after stripping all array types
291  virtual llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
292                                             llvm::Value *NewPtr,
293                                             llvm::Value *NumElements,
294                                             const CXXNewExpr *expr,
295                                             QualType ElementType);
296
297  /// Reads the array cookie associated with the given pointer,
298  /// if it has one.
299  ///
300  /// \param Ptr - a pointer to the first element in the array
301  /// \param ElementType - the base element type of elements of the array
302  /// \param NumElements - an out parameter which will be initialized
303  ///   with the number of elements allocated, or zero if there is no
304  ///   cookie
305  /// \param AllocPtr - an out parameter which will be initialized
306  ///   with a char* pointing to the address returned by the allocation
307  ///   function
308  /// \param CookieSize - an out parameter which will be initialized
309  ///   with the size of the cookie, or zero if there is no cookie
310  virtual void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
311                               const CXXDeleteExpr *expr,
312                               QualType ElementType, llvm::Value *&NumElements,
313                               llvm::Value *&AllocPtr, CharUnits &CookieSize);
314
315protected:
316  /// Returns the extra size required in order to store the array
317  /// cookie for the given type.  Assumes that an array cookie is
318  /// required.
319  virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
320
321  /// Reads the array cookie for an allocation which is known to have one.
322  /// This is called by the standard implementation of ReadArrayCookie.
323  ///
324  /// \param ptr - a pointer to the allocation made for an array, as a char*
325  /// \param cookieSize - the computed cookie size of an array
326  ///
327  /// Other parameters are as above.
328  ///
329  /// \return a size_t
330  virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF,
331                                           llvm::Value *ptr,
332                                           CharUnits cookieSize);
333
334public:
335
336  /*************************** Static local guards ****************************/
337
338  /// Emits the guarded initializer and destructor setup for the given
339  /// variable, given that it couldn't be emitted as a constant.
340  /// If \p PerformInit is false, the initialization has been folded to a
341  /// constant and should not be performed.
342  ///
343  /// The variable may be:
344  ///   - a static local variable
345  ///   - a static data member of a class template instantiation
346  virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
347                               llvm::GlobalVariable *DeclPtr, bool PerformInit);
348
349  /// Emit code to force the execution of a destructor during global
350  /// teardown.  The default implementation of this uses atexit.
351  ///
352  /// \param dtor - a function taking a single pointer argument
353  /// \param addr - a pointer to pass to the destructor function.
354  virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
355                                  llvm::Constant *dtor, llvm::Constant *addr);
356
357  /*************************** thread_local initialization ********************/
358
359  /// Emits ABI-required functions necessary to initialize thread_local
360  /// variables in this translation unit.
361  ///
362  /// \param Decls The thread_local declarations in this translation unit.
363  /// \param InitFunc If this translation unit contains any non-constant
364  ///        initialization or non-trivial destruction for thread_local
365  ///        variables, a function to perform the initialization. Otherwise, 0.
366  virtual void EmitThreadLocalInitFuncs(
367      llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
368      llvm::Function *InitFunc);
369
370  /// Emit a reference to a non-local thread_local variable (including
371  /// triggering the initialization of all thread_local variables in its
372  /// translation unit).
373  virtual LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
374                                            const DeclRefExpr *DRE);
375};
376
377// Create an instance of a C++ ABI class:
378
379/// Creates an Itanium-family ABI.
380CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
381
382/// Creates a Microsoft-family ABI.
383CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);
384
385}
386}
387
388#endif
389