1 //===----- CGCXXABI.h - Interface to C++ ABIs -------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This provides an abstract class for C++ code generation. Concrete subclasses
10 // of this implement code generation for specific C++ ABIs.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGCXXABI_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGCXXABI_H
17 #include "CodeGenFunction.h"
18 #include "clang/Basic/LLVM.h"
29 class CXXConstructorDecl;
30 class CXXDestructorDecl;
38 class CodeGenFunction;
42 /// Implements C++ ABI-specific code generation functions.
46 std::unique_ptr<MangleContext> MangleCtx;
48 CGCXXABI(CodeGenModule &CGM)
49 : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
52 ImplicitParamDecl *getThisDecl(CodeGenFunction &CGF) {
53 return CGF.CXXABIThisDecl;
55 llvm::Value *getThisValue(CodeGenFunction &CGF) {
56 return CGF.CXXABIThisValue;
58 Address getThisAddress(CodeGenFunction &CGF) {
59 return Address(CGF.CXXABIThisValue, CGF.CXXABIThisAlignment);
62 /// Issue a diagnostic about unsupported features in the ABI.
63 void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S);
65 /// Get a null value for unsupported member pointers.
66 llvm::Constant *GetBogusMemberPointer(QualType T);
68 ImplicitParamDecl *&getStructorImplicitParamDecl(CodeGenFunction &CGF) {
69 return CGF.CXXStructorImplicitParamDecl;
71 llvm::Value *&getStructorImplicitParamValue(CodeGenFunction &CGF) {
72 return CGF.CXXStructorImplicitParamValue;
75 /// Loads the incoming C++ this pointer as it was passed by the caller.
76 llvm::Value *loadIncomingCXXThis(CodeGenFunction &CGF);
78 void setCXXABIThisValue(CodeGenFunction &CGF, llvm::Value *ThisPtr);
80 ASTContext &getContext() const { return CGM.getContext(); }
82 virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
83 virtual bool requiresArrayCookie(const CXXNewExpr *E);
85 /// Determine whether there's something special about the rules of
86 /// the ABI tell us that 'this' is a complete object within the
87 /// given function. Obvious common logic like being defined on a
88 /// final class will have been taken care of by the caller.
89 virtual bool isThisCompleteObject(GlobalDecl GD) const = 0;
95 /// Gets the mangle context.
96 MangleContext &getMangleContext() {
100 /// Returns true if the given constructor or destructor is one of the
101 /// kinds that the ABI says returns 'this' (only applies when called
102 /// non-virtually for destructors).
104 /// There currently is no way to indicate if a destructor returns 'this'
105 /// when called virtually, and code generation does not support the case.
106 virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
108 virtual bool hasMostDerivedReturn(GlobalDecl GD) const { return false; }
110 /// Returns true if the target allows calling a function through a pointer
111 /// with a different signature than the actual function (or equivalently,
112 /// bitcasting a function or function pointer to a different function type).
113 /// In principle in the most general case this could depend on the target, the
114 /// calling convention, and the actual types of the arguments and return
115 /// value. Here it just means whether the signature mismatch could *ever* be
116 /// allowed; in other words, does the target do strict checking of signatures
118 virtual bool canCallMismatchedFunctionType() const { return true; }
120 /// If the C++ ABI requires the given type be returned in a particular way,
121 /// this method sets RetAI and returns true.
122 virtual bool classifyReturnType(CGFunctionInfo &FI) const = 0;
124 /// Specify how one should pass an argument of a record type.
126 /// Pass it using the normal C aggregate rules for the ABI, potentially
127 /// introducing extra copies and passing some or all of it in registers.
130 /// Pass it on the stack using its defined layout. The argument must be
131 /// evaluated directly into the correct stack position in the arguments area,
132 /// and the call machinery must not move it or introduce extra copies.
135 /// Pass it as a pointer to temporary memory.
139 /// Returns how an argument of the given record type should be passed.
140 virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
142 /// Returns true if the implicit 'sret' parameter comes after the implicit
143 /// 'this' parameter of C++ instance methods.
144 virtual bool isSRetParameterAfterThis() const { return false; }
146 /// Find the LLVM type used to represent the given member pointer
149 ConvertMemberPointerType(const MemberPointerType *MPT);
151 /// Load a member function from an object and a member function
152 /// pointer. Apply the this-adjustment and set 'This' to the
154 virtual CGCallee EmitLoadOfMemberFunctionPointer(
155 CodeGenFunction &CGF, const Expr *E, Address This,
156 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
157 const MemberPointerType *MPT);
159 /// Calculate an l-value from an object and a data member pointer.
160 virtual llvm::Value *
161 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
162 Address Base, llvm::Value *MemPtr,
163 const MemberPointerType *MPT);
165 /// Perform a derived-to-base, base-to-derived, or bitcast member
166 /// pointer conversion.
167 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
171 /// Perform a derived-to-base, base-to-derived, or bitcast member
172 /// pointer conversion on a constant value.
173 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
174 llvm::Constant *Src);
176 /// Return true if the given member pointer can be zero-initialized
177 /// (in the C++ sense) with an LLVM zeroinitializer.
178 virtual bool isZeroInitializable(const MemberPointerType *MPT);
180 /// Return whether or not a member pointers type is convertible to an IR type.
181 virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const {
185 /// Create a null member pointer of the given type.
186 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
188 /// Create a member pointer for the given method.
189 virtual llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD);
191 /// Create a member pointer for the given field.
192 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
195 /// Create a member pointer for the given member pointer constant.
196 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
198 /// Emit a comparison between two member pointers. Returns an i1.
199 virtual llvm::Value *
200 EmitMemberPointerComparison(CodeGenFunction &CGF,
203 const MemberPointerType *MPT,
206 /// Determine if a member pointer is non-null. Returns an i1.
207 virtual llvm::Value *
208 EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
210 const MemberPointerType *MPT);
213 /// A utility method for computing the offset required for the given
214 /// base-to-derived or derived-to-base member-pointer conversion.
215 /// Does not handle virtual conversions (in case we ever fully
216 /// support an ABI that allows this). Returns null if no adjustment
218 llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
220 /// Computes the non-virtual adjustment needed for a member pointer
221 /// conversion along an inheritance path stored in an APValue. Unlike
222 /// getMemberPointerAdjustment(), the adjustment can be negative if the path
223 /// is from a derived type to a base type.
224 CharUnits getMemberPointerPathAdjustment(const APValue &MP);
227 virtual void emitVirtualObjectDelete(CodeGenFunction &CGF,
228 const CXXDeleteExpr *DE,
229 Address Ptr, QualType ElementType,
230 const CXXDestructorDecl *Dtor) = 0;
231 virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) = 0;
232 virtual void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) = 0;
233 virtual llvm::GlobalVariable *getThrowInfo(QualType T) { return nullptr; }
235 /// Determine whether it's possible to emit a vtable for \p RD, even
236 /// though we do not know that the vtable has been marked as used by semantic
238 virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const = 0;
240 virtual void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) = 0;
242 virtual llvm::CallInst *
243 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
246 virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
247 virtual CatchTypeInfo
248 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) = 0;
249 virtual CatchTypeInfo getCatchAllTypeInfo();
251 virtual bool shouldTypeidBeNullChecked(bool IsDeref,
252 QualType SrcRecordTy) = 0;
253 virtual void EmitBadTypeidCall(CodeGenFunction &CGF) = 0;
254 virtual llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
256 llvm::Type *StdTypeInfoPtrTy) = 0;
258 virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
259 QualType SrcRecordTy) = 0;
261 virtual llvm::Value *
262 EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
263 QualType SrcRecordTy, QualType DestTy,
264 QualType DestRecordTy, llvm::BasicBlock *CastEnd) = 0;
266 virtual llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF,
268 QualType SrcRecordTy,
269 QualType DestTy) = 0;
271 virtual bool EmitBadCastCall(CodeGenFunction &CGF) = 0;
273 virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
275 const CXXRecordDecl *ClassDecl,
276 const CXXRecordDecl *BaseClassDecl) = 0;
278 virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
279 const CXXRecordDecl *RD);
281 /// Emit the code to initialize hidden members required
282 /// to handle virtual inheritance, if needed by the ABI.
284 initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
285 const CXXRecordDecl *RD) {}
287 /// Emit constructor variants required by this ABI.
288 virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
290 /// Notes how many arguments were added to the beginning (Prefix) and ending
291 /// (Suffix) of an arg list.
293 /// Note that Prefix actually refers to the number of args *after* the first
294 /// one: `this` arguments always come first.
295 struct AddedStructorArgs {
298 AddedStructorArgs() = default;
299 AddedStructorArgs(unsigned P, unsigned S) : Prefix(P), Suffix(S) {}
300 static AddedStructorArgs prefix(unsigned N) { return {N, 0}; }
301 static AddedStructorArgs suffix(unsigned N) { return {0, N}; }
304 /// Build the signature of the given constructor or destructor variant by
305 /// adding any required parameters. For convenience, ArgTys has been
306 /// initialized with the type of 'this'.
307 virtual AddedStructorArgs
308 buildStructorSignature(GlobalDecl GD,
309 SmallVectorImpl<CanQualType> &ArgTys) = 0;
311 /// Returns true if the given destructor type should be emitted as a linkonce
312 /// delegating thunk, regardless of whether the dtor is defined in this TU or
314 virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
315 CXXDtorType DT) const = 0;
317 virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
318 const CXXDestructorDecl *Dtor,
319 CXXDtorType DT) const;
321 virtual llvm::GlobalValue::LinkageTypes
322 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
323 CXXDtorType DT) const;
325 /// Emit destructor variants required by this ABI.
326 virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
328 /// Get the type of the implicit "this" parameter used by a method. May return
329 /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
330 /// parameter to point to some artificial offset in a complete object due to
331 /// vbases being reordered.
332 virtual const CXXRecordDecl *
333 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
334 return MD->getParent();
337 /// Perform ABI-specific "this" argument adjustment required prior to
338 /// a call of a virtual function.
339 /// The "VirtualCall" argument is true iff the call itself is virtual.
341 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
342 Address This, bool VirtualCall) {
346 /// Build a parameter variable suitable for 'this'.
347 void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
349 /// Insert any ABI-specific implicit parameters into the parameter list for a
350 /// function. This generally involves extra data for constructors and
353 /// ABIs may also choose to override the return type, which has been
354 /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
355 /// the formal return type of the function otherwise.
356 virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
357 FunctionArgList &Params) = 0;
359 /// Get the ABI-specific "this" parameter adjustment to apply in the prologue
360 /// of a virtual function.
361 virtual CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
362 return CharUnits::Zero();
365 /// Emit the ABI-specific prolog for the function.
366 virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
368 /// Add any ABI-specific implicit arguments needed to call a constructor.
370 /// \return The number of arguments added at the beginning and end of the
371 /// call, which is typically zero or one.
372 virtual AddedStructorArgs
373 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
374 CXXCtorType Type, bool ForVirtualBase,
375 bool Delegating, CallArgList &Args) = 0;
377 /// Emit the destructor call.
378 virtual void EmitDestructorCall(CodeGenFunction &CGF,
379 const CXXDestructorDecl *DD, CXXDtorType Type,
380 bool ForVirtualBase, bool Delegating,
381 Address This, QualType ThisTy) = 0;
383 /// Emits the VTable definitions required for the given record type.
384 virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
385 const CXXRecordDecl *RD) = 0;
387 /// Checks if ABI requires extra virtual offset for vtable field.
389 isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
390 CodeGenFunction::VPtr Vptr) = 0;
392 /// Checks if ABI requires to initialize vptrs for given dynamic class.
393 virtual bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) = 0;
395 /// Get the address point of the vtable for the given base subobject.
396 virtual llvm::Constant *
397 getVTableAddressPoint(BaseSubobject Base,
398 const CXXRecordDecl *VTableClass) = 0;
400 /// Get the address point of the vtable for the given base subobject while
401 /// building a constructor or a destructor.
402 virtual llvm::Value *
403 getVTableAddressPointInStructor(CodeGenFunction &CGF, const CXXRecordDecl *RD,
405 const CXXRecordDecl *NearestVBase) = 0;
407 /// Get the address point of the vtable for the given base subobject while
408 /// building a constexpr.
409 virtual llvm::Constant *
410 getVTableAddressPointForConstExpr(BaseSubobject Base,
411 const CXXRecordDecl *VTableClass) = 0;
413 /// Get the address of the vtable for the given record decl which should be
414 /// used for the vptr at the given offset in RD.
415 virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
416 CharUnits VPtrOffset) = 0;
418 /// Build a virtual function pointer in the ABI-specific way.
419 virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF,
420 GlobalDecl GD, Address This,
422 SourceLocation Loc) = 0;
424 using DeleteOrMemberCallExpr =
425 llvm::PointerUnion<const CXXDeleteExpr *, const CXXMemberCallExpr *>;
427 /// Emit the ABI-specific virtual destructor call.
428 virtual llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
429 const CXXDestructorDecl *Dtor,
430 CXXDtorType DtorType,
432 DeleteOrMemberCallExpr E) = 0;
434 virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
436 CallArgList &CallArgs) {}
438 /// Emit any tables needed to implement virtual inheritance. For Itanium,
439 /// this emits virtual table tables. For the MSVC++ ABI, this emits virtual
441 virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
443 virtual bool exportThunk() = 0;
444 virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
445 GlobalDecl GD, bool ReturnAdjustment) = 0;
447 virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
449 const ThisAdjustment &TA) = 0;
451 virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
453 const ReturnAdjustment &RA) = 0;
455 virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
456 RValue RV, QualType ResultType);
458 virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
459 FunctionArgList &Args) const = 0;
461 /// Gets the offsets of all the virtual base pointers in a given class.
462 virtual std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD);
464 /// Gets the pure virtual member call function.
465 virtual StringRef GetPureVirtualCallName() = 0;
467 /// Gets the deleted virtual member call name.
468 virtual StringRef GetDeletedVirtualCallName() = 0;
470 /**************************** Array cookies ******************************/
472 /// Returns the extra size required in order to store the array
473 /// cookie for the given new-expression. May return 0 to indicate that no
474 /// array cookie is required.
476 /// Several cases are filtered out before this method is called:
477 /// - non-array allocations never need a cookie
478 /// - calls to \::operator new(size_t, void*) never need a cookie
480 /// \param expr - the new-expression being allocated.
481 virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
483 /// Initialize the array cookie for the given allocation.
485 /// \param NewPtr - a char* which is the presumed-non-null
486 /// return value of the allocation function
487 /// \param NumElements - the computed number of elements,
488 /// potentially collapsed from the multidimensional array case;
490 /// \param ElementType - the base element allocated type,
491 /// i.e. the allocated type after stripping all array types
492 virtual Address InitializeArrayCookie(CodeGenFunction &CGF,
494 llvm::Value *NumElements,
495 const CXXNewExpr *expr,
496 QualType ElementType);
498 /// Reads the array cookie associated with the given pointer,
501 /// \param Ptr - a pointer to the first element in the array
502 /// \param ElementType - the base element type of elements of the array
503 /// \param NumElements - an out parameter which will be initialized
504 /// with the number of elements allocated, or zero if there is no
506 /// \param AllocPtr - an out parameter which will be initialized
507 /// with a char* pointing to the address returned by the allocation
509 /// \param CookieSize - an out parameter which will be initialized
510 /// with the size of the cookie, or zero if there is no cookie
511 virtual void ReadArrayCookie(CodeGenFunction &CGF, Address Ptr,
512 const CXXDeleteExpr *expr,
513 QualType ElementType, llvm::Value *&NumElements,
514 llvm::Value *&AllocPtr, CharUnits &CookieSize);
516 /// Return whether the given global decl needs a VTT parameter.
517 virtual bool NeedsVTTParameter(GlobalDecl GD);
520 /// Returns the extra size required in order to store the array
521 /// cookie for the given type. Assumes that an array cookie is
523 virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
525 /// Reads the array cookie for an allocation which is known to have one.
526 /// This is called by the standard implementation of ReadArrayCookie.
528 /// \param ptr - a pointer to the allocation made for an array, as a char*
529 /// \param cookieSize - the computed cookie size of an array
531 /// Other parameters are as above.
534 virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF, Address ptr,
535 CharUnits cookieSize);
539 /*************************** Static local guards ****************************/
541 /// Emits the guarded initializer and destructor setup for the given
542 /// variable, given that it couldn't be emitted as a constant.
543 /// If \p PerformInit is false, the initialization has been folded to a
544 /// constant and should not be performed.
546 /// The variable may be:
547 /// - a static local variable
548 /// - a static data member of a class template instantiation
549 virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
550 llvm::GlobalVariable *DeclPtr,
551 bool PerformInit) = 0;
553 /// Emit code to force the execution of a destructor during global
554 /// teardown. The default implementation of this uses atexit.
556 /// \param Dtor - a function taking a single pointer argument
557 /// \param Addr - a pointer to pass to the destructor function.
558 virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
559 llvm::FunctionCallee Dtor,
560 llvm::Constant *Addr) = 0;
562 /*************************** thread_local initialization ********************/
564 /// Emits ABI-required functions necessary to initialize thread_local
565 /// variables in this translation unit.
567 /// \param CXXThreadLocals - The thread_local declarations in this translation
569 /// \param CXXThreadLocalInits - If this translation unit contains any
570 /// non-constant initialization or non-trivial destruction for
571 /// thread_local variables, a list of functions to perform the
573 virtual void EmitThreadLocalInitFuncs(
574 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
575 ArrayRef<llvm::Function *> CXXThreadLocalInits,
576 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) = 0;
578 // Determine if references to thread_local global variables can be made
579 // directly or require access through a thread wrapper function.
580 virtual bool usesThreadWrapperFunction(const VarDecl *VD) const = 0;
582 /// Emit a reference to a non-local thread_local variable (including
583 /// triggering the initialization of all thread_local variables in its
584 /// translation unit).
585 virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
587 QualType LValType) = 0;
589 /// Emit a single constructor/destructor with the given type from a C++
590 /// constructor Decl.
591 virtual void emitCXXStructor(GlobalDecl GD) = 0;
593 /// Load a vtable from This, an object of polymorphic type RD, or from one of
594 /// its virtual bases if it does not have its own vtable. Returns the vtable
595 /// and the class from which the vtable was loaded.
596 virtual std::pair<llvm::Value *, const CXXRecordDecl *>
597 LoadVTablePtr(CodeGenFunction &CGF, Address This,
598 const CXXRecordDecl *RD) = 0;
601 // Create an instance of a C++ ABI class:
603 /// Creates an Itanium-family ABI.
604 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
606 /// Creates a Microsoft-family ABI.
607 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);
609 struct CatchRetScope final : EHScopeStack::Cleanup {
610 llvm::CatchPadInst *CPI;
612 CatchRetScope(llvm::CatchPadInst *CPI) : CPI(CPI) {}
614 void Emit(CodeGenFunction &CGF, Flags flags) override {
615 llvm::BasicBlock *BB = CGF.createBasicBlock("catchret.dest");
616 CGF.Builder.CreateCatchRet(CPI, BB);