1 //===----- CGCXXABI.h - Interface to C++ ABIs -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides an abstract class for C++ code generation. Concrete subclasses
11 // of this implement code generation for specific C++ ABIs.
13 //===----------------------------------------------------------------------===//
15 #ifndef CLANG_CODEGEN_CXXABI_H
16 #define CLANG_CODEGEN_CXXABI_H
18 #include "CodeGenFunction.h"
19 #include "clang/Basic/LLVM.h"
29 class CXXConstructorDecl;
30 class CXXDestructorDecl;
37 class CodeGenFunction;
40 /// \brief Implements C++ ABI-specific code generation functions.
44 std::unique_ptr<MangleContext> MangleCtx;
46 CGCXXABI(CodeGenModule &CGM)
47 : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
50 ImplicitParamDecl *&getThisDecl(CodeGenFunction &CGF) {
51 return CGF.CXXABIThisDecl;
53 llvm::Value *&getThisValue(CodeGenFunction &CGF) {
54 return CGF.CXXABIThisValue;
57 /// Issue a diagnostic about unsupported features in the ABI.
58 void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S);
60 /// Get a null value for unsupported member pointers.
61 llvm::Constant *GetBogusMemberPointer(QualType T);
63 ImplicitParamDecl *&getStructorImplicitParamDecl(CodeGenFunction &CGF) {
64 return CGF.CXXStructorImplicitParamDecl;
66 llvm::Value *&getStructorImplicitParamValue(CodeGenFunction &CGF) {
67 return CGF.CXXStructorImplicitParamValue;
70 /// Perform prolog initialization of the parameter variable suitable
71 /// for 'this' emitted by buildThisParam.
72 void EmitThisParam(CodeGenFunction &CGF);
74 ASTContext &getContext() const { return CGM.getContext(); }
76 virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
77 virtual bool requiresArrayCookie(const CXXNewExpr *E);
83 /// Gets the mangle context.
84 MangleContext &getMangleContext() {
88 /// Returns true if the given constructor or destructor is one of the
89 /// kinds that the ABI says returns 'this' (only applies when called
90 /// non-virtually for destructors).
92 /// There currently is no way to indicate if a destructor returns 'this'
93 /// when called virtually, and code generation does not support the case.
94 virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
96 /// If the C++ ABI requires the given type be returned in a particular way,
97 /// this method sets RetAI and returns true.
98 virtual bool classifyReturnType(CGFunctionInfo &FI) const = 0;
100 /// Specify how one should pass an argument of a record type.
102 /// Pass it using the normal C aggregate rules for the ABI, potentially
103 /// introducing extra copies and passing some or all of it in registers.
106 /// Pass it on the stack using its defined layout. The argument must be
107 /// evaluated directly into the correct stack position in the arguments area,
108 /// and the call machinery must not move it or introduce extra copies.
111 /// Pass it as a pointer to temporary memory.
115 /// Returns true if C++ allows us to copy the memory of an object of type RD
116 /// when it is passed as an argument.
117 bool canCopyArgument(const CXXRecordDecl *RD) const;
119 /// Returns how an argument of the given record type should be passed.
120 virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
122 /// Returns true if the implicit 'sret' parameter comes after the implicit
123 /// 'this' parameter of C++ instance methods.
124 virtual bool isSRetParameterAfterThis() const { return false; }
126 /// Find the LLVM type used to represent the given member pointer
129 ConvertMemberPointerType(const MemberPointerType *MPT);
131 /// Load a member function from an object and a member function
132 /// pointer. Apply the this-adjustment and set 'This' to the
134 virtual llvm::Value *EmitLoadOfMemberFunctionPointer(
135 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
136 llvm::Value *MemPtr, const MemberPointerType *MPT);
138 /// Calculate an l-value from an object and a data member pointer.
139 virtual llvm::Value *
140 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
141 llvm::Value *Base, llvm::Value *MemPtr,
142 const MemberPointerType *MPT);
144 /// Perform a derived-to-base, base-to-derived, or bitcast member
145 /// pointer conversion.
146 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
150 /// Perform a derived-to-base, base-to-derived, or bitcast member
151 /// pointer conversion on a constant value.
152 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
153 llvm::Constant *Src);
155 /// Return true if the given member pointer can be zero-initialized
156 /// (in the C++ sense) with an LLVM zeroinitializer.
157 virtual bool isZeroInitializable(const MemberPointerType *MPT);
159 /// Return whether or not a member pointers type is convertible to an IR type.
160 virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const {
164 /// Create a null member pointer of the given type.
165 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
167 /// Create a member pointer for the given method.
168 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
170 /// Create a member pointer for the given field.
171 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
174 /// Create a member pointer for the given member pointer constant.
175 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
177 /// Emit a comparison between two member pointers. Returns an i1.
178 virtual llvm::Value *
179 EmitMemberPointerComparison(CodeGenFunction &CGF,
182 const MemberPointerType *MPT,
185 /// Determine if a member pointer is non-null. Returns an i1.
186 virtual llvm::Value *
187 EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
189 const MemberPointerType *MPT);
192 /// A utility method for computing the offset required for the given
193 /// base-to-derived or derived-to-base member-pointer conversion.
194 /// Does not handle virtual conversions (in case we ever fully
195 /// support an ABI that allows this). Returns null if no adjustment
197 llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
199 /// \brief Computes the non-virtual adjustment needed for a member pointer
200 /// conversion along an inheritance path stored in an APValue. Unlike
201 /// getMemberPointerAdjustment(), the adjustment can be negative if the path
202 /// is from a derived type to a base type.
203 CharUnits getMemberPointerPathAdjustment(const APValue &MP);
206 /// Adjust the given non-null pointer to an object of polymorphic
207 /// type to point to the complete object.
209 /// The IR type of the result should be a pointer but is otherwise
211 virtual llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
215 virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
217 virtual bool shouldTypeidBeNullChecked(bool IsDeref,
218 QualType SrcRecordTy) = 0;
219 virtual void EmitBadTypeidCall(CodeGenFunction &CGF) = 0;
220 virtual llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
221 llvm::Value *ThisPtr,
222 llvm::Type *StdTypeInfoPtrTy) = 0;
224 virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
225 QualType SrcRecordTy) = 0;
227 virtual llvm::Value *
228 EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
229 QualType SrcRecordTy, QualType DestTy,
230 QualType DestRecordTy, llvm::BasicBlock *CastEnd) = 0;
232 virtual llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF,
234 QualType SrcRecordTy,
235 QualType DestTy) = 0;
237 virtual bool EmitBadCastCall(CodeGenFunction &CGF) = 0;
239 virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
241 const CXXRecordDecl *ClassDecl,
242 const CXXRecordDecl *BaseClassDecl) = 0;
244 /// Build the signature of the given constructor variant by adding
245 /// any required parameters. For convenience, ArgTys has been initialized
246 /// with the type of 'this' and ResTy has been initialized with the type of
247 /// 'this' if HasThisReturn(GlobalDecl(Ctor, T)) is true or 'void' otherwise
248 /// (although both may be changed by the ABI).
250 /// If there are ever any ABIs where the implicit parameters are
251 /// intermixed with the formal parameters, we can address those
253 virtual void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
256 SmallVectorImpl<CanQualType> &ArgTys) = 0;
258 virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
259 const CXXRecordDecl *RD);
261 /// Emit the code to initialize hidden members required
262 /// to handle virtual inheritance, if needed by the ABI.
264 initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
265 const CXXRecordDecl *RD) {}
267 /// Emit constructor variants required by this ABI.
268 virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
270 /// Build the signature of the given destructor variant by adding
271 /// any required parameters. For convenience, ArgTys has been initialized
272 /// with the type of 'this' and ResTy has been initialized with the type of
273 /// 'this' if HasThisReturn(GlobalDecl(Dtor, T)) is true or 'void' otherwise
274 /// (although both may be changed by the ABI).
275 virtual void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
278 SmallVectorImpl<CanQualType> &ArgTys) = 0;
280 /// Returns true if the given destructor type should be emitted as a linkonce
281 /// delegating thunk, regardless of whether the dtor is defined in this TU or
283 virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
284 CXXDtorType DT) const = 0;
286 /// Emit destructor variants required by this ABI.
287 virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
289 /// Get the type of the implicit "this" parameter used by a method. May return
290 /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
291 /// parameter to point to some artificial offset in a complete object due to
292 /// vbases being reordered.
293 virtual const CXXRecordDecl *
294 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
295 return MD->getParent();
298 /// Perform ABI-specific "this" argument adjustment required prior to
299 /// a call of a virtual function.
300 /// The "VirtualCall" argument is true iff the call itself is virtual.
301 virtual llvm::Value *
302 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
308 /// Build a parameter variable suitable for 'this'.
309 void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
311 /// Insert any ABI-specific implicit parameters into the parameter list for a
312 /// function. This generally involves extra data for constructors and
315 /// ABIs may also choose to override the return type, which has been
316 /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
317 /// the formal return type of the function otherwise.
318 virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
319 FunctionArgList &Params) = 0;
321 /// Perform ABI-specific "this" parameter adjustment in a virtual function
323 virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
324 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
328 /// Emit the ABI-specific prolog for the function.
329 virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
331 /// Add any ABI-specific implicit arguments needed to call a constructor.
333 /// \return The number of args added to the call, which is typically zero or
336 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
337 CXXCtorType Type, bool ForVirtualBase,
338 bool Delegating, CallArgList &Args) = 0;
340 /// Emit the destructor call.
341 virtual void EmitDestructorCall(CodeGenFunction &CGF,
342 const CXXDestructorDecl *DD, CXXDtorType Type,
343 bool ForVirtualBase, bool Delegating,
344 llvm::Value *This) = 0;
346 /// Emits the VTable definitions required for the given record type.
347 virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
348 const CXXRecordDecl *RD) = 0;
350 /// Get the address point of the vtable for the given base subobject while
351 /// building a constructor or a destructor. On return, NeedsVirtualOffset
352 /// tells if a virtual base adjustment is needed in order to get the offset
353 /// of the base subobject.
354 virtual llvm::Value *getVTableAddressPointInStructor(
355 CodeGenFunction &CGF, const CXXRecordDecl *RD, BaseSubobject Base,
356 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) = 0;
358 /// Get the address point of the vtable for the given base subobject while
359 /// building a constexpr.
360 virtual llvm::Constant *
361 getVTableAddressPointForConstExpr(BaseSubobject Base,
362 const CXXRecordDecl *VTableClass) = 0;
364 /// Get the address of the vtable for the given record decl which should be
365 /// used for the vptr at the given offset in RD.
366 virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
367 CharUnits VPtrOffset) = 0;
369 /// Build a virtual function pointer in the ABI-specific way.
370 virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF,
375 /// Emit the ABI-specific virtual destructor call.
376 virtual void EmitVirtualDestructorCall(CodeGenFunction &CGF,
377 const CXXDestructorDecl *Dtor,
378 CXXDtorType DtorType,
379 SourceLocation CallLoc,
380 llvm::Value *This) = 0;
382 virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
384 CallArgList &CallArgs) {}
386 /// Emit any tables needed to implement virtual inheritance. For Itanium,
387 /// this emits virtual table tables. For the MSVC++ ABI, this emits virtual
389 virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
391 virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
392 GlobalDecl GD, bool ReturnAdjustment) = 0;
394 virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
396 const ThisAdjustment &TA) = 0;
398 virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
400 const ReturnAdjustment &RA) = 0;
402 virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
403 RValue RV, QualType ResultType);
405 /// Gets the pure virtual member call function.
406 virtual StringRef GetPureVirtualCallName() = 0;
408 /// Gets the deleted virtual member call name.
409 virtual StringRef GetDeletedVirtualCallName() = 0;
411 /**************************** Array cookies ******************************/
413 /// Returns the extra size required in order to store the array
414 /// cookie for the given new-expression. May return 0 to indicate that no
415 /// array cookie is required.
417 /// Several cases are filtered out before this method is called:
418 /// - non-array allocations never need a cookie
419 /// - calls to \::operator new(size_t, void*) never need a cookie
421 /// \param expr - the new-expression being allocated.
422 virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
424 /// Initialize the array cookie for the given allocation.
426 /// \param NewPtr - a char* which is the presumed-non-null
427 /// return value of the allocation function
428 /// \param NumElements - the computed number of elements,
429 /// potentially collapsed from the multidimensional array case;
431 /// \param ElementType - the base element allocated type,
432 /// i.e. the allocated type after stripping all array types
433 virtual llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
435 llvm::Value *NumElements,
436 const CXXNewExpr *expr,
437 QualType ElementType);
439 /// Reads the array cookie associated with the given pointer,
442 /// \param Ptr - a pointer to the first element in the array
443 /// \param ElementType - the base element type of elements of the array
444 /// \param NumElements - an out parameter which will be initialized
445 /// with the number of elements allocated, or zero if there is no
447 /// \param AllocPtr - an out parameter which will be initialized
448 /// with a char* pointing to the address returned by the allocation
450 /// \param CookieSize - an out parameter which will be initialized
451 /// with the size of the cookie, or zero if there is no cookie
452 virtual void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
453 const CXXDeleteExpr *expr,
454 QualType ElementType, llvm::Value *&NumElements,
455 llvm::Value *&AllocPtr, CharUnits &CookieSize);
457 /// Return whether the given global decl needs a VTT parameter.
458 virtual bool NeedsVTTParameter(GlobalDecl GD);
461 /// Returns the extra size required in order to store the array
462 /// cookie for the given type. Assumes that an array cookie is
464 virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
466 /// Reads the array cookie for an allocation which is known to have one.
467 /// This is called by the standard implementation of ReadArrayCookie.
469 /// \param ptr - a pointer to the allocation made for an array, as a char*
470 /// \param cookieSize - the computed cookie size of an array
472 /// Other parameters are as above.
475 virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF,
477 CharUnits cookieSize);
481 /*************************** Static local guards ****************************/
483 /// Emits the guarded initializer and destructor setup for the given
484 /// variable, given that it couldn't be emitted as a constant.
485 /// If \p PerformInit is false, the initialization has been folded to a
486 /// constant and should not be performed.
488 /// The variable may be:
489 /// - a static local variable
490 /// - a static data member of a class template instantiation
491 virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
492 llvm::GlobalVariable *DeclPtr,
493 bool PerformInit) = 0;
495 /// Emit code to force the execution of a destructor during global
496 /// teardown. The default implementation of this uses atexit.
498 /// \param dtor - a function taking a single pointer argument
499 /// \param addr - a pointer to pass to the destructor function.
500 virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
501 llvm::Constant *dtor, llvm::Constant *addr);
503 /*************************** thread_local initialization ********************/
505 /// Emits ABI-required functions necessary to initialize thread_local
506 /// variables in this translation unit.
508 /// \param Decls The thread_local declarations in this translation unit.
509 /// \param InitFunc If this translation unit contains any non-constant
510 /// initialization or non-trivial destruction for thread_local
511 /// variables, a function to perform the initialization. Otherwise, 0.
512 virtual void EmitThreadLocalInitFuncs(
513 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
514 llvm::Function *InitFunc);
516 /// Emit a reference to a non-local thread_local variable (including
517 /// triggering the initialization of all thread_local variables in its
518 /// translation unit).
519 virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
524 // Create an instance of a C++ ABI class:
526 /// Creates an Itanium-family ABI.
527 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
529 /// Creates a Microsoft-family ABI.
530 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);