1 //===----- CGCXXABI.h - Interface to C++ ABIs -------------------*- 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 provides an abstract class for C++ code generation. Concrete subclasses
10 // of this implement code generation for specific C++ ABIs.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGCXXABI_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGCXXABI_H
16 
17 #include "CodeGenFunction.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/CodeGen/CodeGenABITypes.h"
20 
21 namespace llvm {
22 class Constant;
23 class Type;
24 class Value;
25 class CallInst;
26 }
27 
28 namespace clang {
29 class CastExpr;
30 class CXXConstructorDecl;
31 class CXXDestructorDecl;
32 class CXXMethodDecl;
33 class CXXRecordDecl;
34 class FieldDecl;
35 class MangleContext;
36 
37 namespace CodeGen {
38 class CGCallee;
39 class CodeGenFunction;
40 class CodeGenModule;
41 struct CatchTypeInfo;
42 
43 /// Implements C++ ABI-specific code generation functions.
44 class CGCXXABI {
45 protected:
46   CodeGenModule &CGM;
47   std::unique_ptr<MangleContext> MangleCtx;
48 
CGCXXABI(CodeGenModule & CGM)49   CGCXXABI(CodeGenModule &CGM)
50     : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
51 
52 protected:
getThisDecl(CodeGenFunction & CGF)53   ImplicitParamDecl *getThisDecl(CodeGenFunction &CGF) {
54     return CGF.CXXABIThisDecl;
55   }
getThisValue(CodeGenFunction & CGF)56   llvm::Value *getThisValue(CodeGenFunction &CGF) {
57     return CGF.CXXABIThisValue;
58   }
getThisAddress(CodeGenFunction & CGF)59   Address getThisAddress(CodeGenFunction &CGF) {
60     return Address(CGF.CXXABIThisValue, CGF.CXXABIThisAlignment);
61   }
62 
63   /// Issue a diagnostic about unsupported features in the ABI.
64   void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S);
65 
66   /// Get a null value for unsupported member pointers.
67   llvm::Constant *GetBogusMemberPointer(QualType T);
68 
getStructorImplicitParamDecl(CodeGenFunction & CGF)69   ImplicitParamDecl *&getStructorImplicitParamDecl(CodeGenFunction &CGF) {
70     return CGF.CXXStructorImplicitParamDecl;
71   }
getStructorImplicitParamValue(CodeGenFunction & CGF)72   llvm::Value *&getStructorImplicitParamValue(CodeGenFunction &CGF) {
73     return CGF.CXXStructorImplicitParamValue;
74   }
75 
76   /// Loads the incoming C++ this pointer as it was passed by the caller.
77   llvm::Value *loadIncomingCXXThis(CodeGenFunction &CGF);
78 
79   void setCXXABIThisValue(CodeGenFunction &CGF, llvm::Value *ThisPtr);
80 
getContext()81   ASTContext &getContext() const { return CGM.getContext(); }
82 
83   virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
84   virtual bool requiresArrayCookie(const CXXNewExpr *E);
85 
86   /// Determine whether there's something special about the rules of
87   /// the ABI tell us that 'this' is a complete object within the
88   /// given function.  Obvious common logic like being defined on a
89   /// final class will have been taken care of by the caller.
90   virtual bool isThisCompleteObject(GlobalDecl GD) const = 0;
91 
92 public:
93 
94   virtual ~CGCXXABI();
95 
96   /// Gets the mangle context.
getMangleContext()97   MangleContext &getMangleContext() {
98     return *MangleCtx;
99   }
100 
101   /// Returns true if the given constructor or destructor is one of the
102   /// kinds that the ABI says returns 'this' (only applies when called
103   /// non-virtually for destructors).
104   ///
105   /// There currently is no way to indicate if a destructor returns 'this'
106   /// when called virtually, and code generation does not support the case.
HasThisReturn(GlobalDecl GD)107   virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
108 
hasMostDerivedReturn(GlobalDecl GD)109   virtual bool hasMostDerivedReturn(GlobalDecl GD) const { return false; }
110 
useSinitAndSterm()111   virtual bool useSinitAndSterm() const { return false; }
112 
113   /// Returns true if the target allows calling a function through a pointer
114   /// with a different signature than the actual function (or equivalently,
115   /// bitcasting a function or function pointer to a different function type).
116   /// In principle in the most general case this could depend on the target, the
117   /// calling convention, and the actual types of the arguments and return
118   /// value. Here it just means whether the signature mismatch could *ever* be
119   /// allowed; in other words, does the target do strict checking of signatures
120   /// for all calls.
canCallMismatchedFunctionType()121   virtual bool canCallMismatchedFunctionType() const { return true; }
122 
123   /// If the C++ ABI requires the given type be returned in a particular way,
124   /// this method sets RetAI and returns true.
125   virtual bool classifyReturnType(CGFunctionInfo &FI) const = 0;
126 
127   /// Specify how one should pass an argument of a record type.
128   enum RecordArgABI {
129     /// Pass it using the normal C aggregate rules for the ABI, potentially
130     /// introducing extra copies and passing some or all of it in registers.
131     RAA_Default = 0,
132 
133     /// Pass it on the stack using its defined layout.  The argument must be
134     /// evaluated directly into the correct stack position in the arguments area,
135     /// and the call machinery must not move it or introduce extra copies.
136     RAA_DirectInMemory,
137 
138     /// Pass it as a pointer to temporary memory.
139     RAA_Indirect
140   };
141 
142   /// Returns how an argument of the given record type should be passed.
143   virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
144 
145   /// Returns true if the implicit 'sret' parameter comes after the implicit
146   /// 'this' parameter of C++ instance methods.
isSRetParameterAfterThis()147   virtual bool isSRetParameterAfterThis() const { return false; }
148 
149   /// Find the LLVM type used to represent the given member pointer
150   /// type.
151   virtual llvm::Type *
152   ConvertMemberPointerType(const MemberPointerType *MPT);
153 
154   /// Load a member function from an object and a member function
155   /// pointer.  Apply the this-adjustment and set 'This' to the
156   /// adjusted value.
157   virtual CGCallee EmitLoadOfMemberFunctionPointer(
158       CodeGenFunction &CGF, const Expr *E, Address This,
159       llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
160       const MemberPointerType *MPT);
161 
162   /// Calculate an l-value from an object and a data member pointer.
163   virtual llvm::Value *
164   EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
165                                Address Base, llvm::Value *MemPtr,
166                                const MemberPointerType *MPT);
167 
168   /// Perform a derived-to-base, base-to-derived, or bitcast member
169   /// pointer conversion.
170   virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
171                                                    const CastExpr *E,
172                                                    llvm::Value *Src);
173 
174   /// Perform a derived-to-base, base-to-derived, or bitcast member
175   /// pointer conversion on a constant value.
176   virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
177                                                       llvm::Constant *Src);
178 
179   /// Return true if the given member pointer can be zero-initialized
180   /// (in the C++ sense) with an LLVM zeroinitializer.
181   virtual bool isZeroInitializable(const MemberPointerType *MPT);
182 
183   /// Return whether or not a member pointers type is convertible to an IR type.
isMemberPointerConvertible(const MemberPointerType * MPT)184   virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const {
185     return true;
186   }
187 
188   /// Create a null member pointer of the given type.
189   virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
190 
191   /// Create a member pointer for the given method.
192   virtual llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD);
193 
194   /// Create a member pointer for the given field.
195   virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
196                                                 CharUnits offset);
197 
198   /// Create a member pointer for the given member pointer constant.
199   virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
200 
201   /// Emit a comparison between two member pointers.  Returns an i1.
202   virtual llvm::Value *
203   EmitMemberPointerComparison(CodeGenFunction &CGF,
204                               llvm::Value *L,
205                               llvm::Value *R,
206                               const MemberPointerType *MPT,
207                               bool Inequality);
208 
209   /// Determine if a member pointer is non-null.  Returns an i1.
210   virtual llvm::Value *
211   EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
212                              llvm::Value *MemPtr,
213                              const MemberPointerType *MPT);
214 
215 protected:
216   /// A utility method for computing the offset required for the given
217   /// base-to-derived or derived-to-base member-pointer conversion.
218   /// Does not handle virtual conversions (in case we ever fully
219   /// support an ABI that allows this).  Returns null if no adjustment
220   /// is required.
221   llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
222 
223   /// Computes the non-virtual adjustment needed for a member pointer
224   /// conversion along an inheritance path stored in an APValue.  Unlike
225   /// getMemberPointerAdjustment(), the adjustment can be negative if the path
226   /// is from a derived type to a base type.
227   CharUnits getMemberPointerPathAdjustment(const APValue &MP);
228 
229 public:
230   virtual void emitVirtualObjectDelete(CodeGenFunction &CGF,
231                                        const CXXDeleteExpr *DE,
232                                        Address Ptr, QualType ElementType,
233                                        const CXXDestructorDecl *Dtor) = 0;
234   virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) = 0;
235   virtual void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) = 0;
getThrowInfo(QualType T)236   virtual llvm::GlobalVariable *getThrowInfo(QualType T) { return nullptr; }
237 
238   /// Determine whether it's possible to emit a vtable for \p RD, even
239   /// though we do not know that the vtable has been marked as used by semantic
240   /// analysis.
241   virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const = 0;
242 
243   virtual void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) = 0;
244 
245   virtual llvm::CallInst *
246   emitTerminateForUnexpectedException(CodeGenFunction &CGF,
247                                       llvm::Value *Exn);
248 
249   virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
250   virtual CatchTypeInfo
251   getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) = 0;
252   virtual CatchTypeInfo getCatchAllTypeInfo();
253 
254   virtual bool shouldTypeidBeNullChecked(bool IsDeref,
255                                          QualType SrcRecordTy) = 0;
256   virtual void EmitBadTypeidCall(CodeGenFunction &CGF) = 0;
257   virtual llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
258                                   Address ThisPtr,
259                                   llvm::Type *StdTypeInfoPtrTy) = 0;
260 
261   virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
262                                                   QualType SrcRecordTy) = 0;
263 
264   virtual llvm::Value *
265   EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
266                       QualType SrcRecordTy, QualType DestTy,
267                       QualType DestRecordTy, llvm::BasicBlock *CastEnd) = 0;
268 
269   virtual llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF,
270                                              Address Value,
271                                              QualType SrcRecordTy,
272                                              QualType DestTy) = 0;
273 
274   virtual bool EmitBadCastCall(CodeGenFunction &CGF) = 0;
275 
276   virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
277                                                  Address This,
278                                                  const CXXRecordDecl *ClassDecl,
279                                         const CXXRecordDecl *BaseClassDecl) = 0;
280 
281   virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
282                                                           const CXXRecordDecl *RD);
283 
284   /// Emit the code to initialize hidden members required
285   /// to handle virtual inheritance, if needed by the ABI.
286   virtual void
initializeHiddenVirtualInheritanceMembers(CodeGenFunction & CGF,const CXXRecordDecl * RD)287   initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
288                                             const CXXRecordDecl *RD) {}
289 
290   /// Emit constructor variants required by this ABI.
291   virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
292 
293   /// Additional implicit arguments to add to the beginning (Prefix) and end
294   /// (Suffix) of a constructor / destructor arg list.
295   ///
296   /// Note that Prefix should actually be inserted *after* the first existing
297   /// arg; `this` arguments always come first.
298   struct AddedStructorArgs {
299     struct Arg {
300       llvm::Value *Value;
301       QualType Type;
302     };
303     SmallVector<Arg, 1> Prefix;
304     SmallVector<Arg, 1> Suffix;
305     AddedStructorArgs() = default;
AddedStructorArgsAddedStructorArgs306     AddedStructorArgs(SmallVector<Arg, 1> P, SmallVector<Arg, 1> S)
307         : Prefix(std::move(P)), Suffix(std::move(S)) {}
prefixAddedStructorArgs308     static AddedStructorArgs prefix(SmallVector<Arg, 1> Args) {
309       return {std::move(Args), {}};
310     }
suffixAddedStructorArgs311     static AddedStructorArgs suffix(SmallVector<Arg, 1> Args) {
312       return {{}, std::move(Args)};
313     }
314   };
315 
316   /// Similar to AddedStructorArgs, but only notes the number of additional
317   /// arguments.
318   struct AddedStructorArgCounts {
319     unsigned Prefix = 0;
320     unsigned Suffix = 0;
321     AddedStructorArgCounts() = default;
AddedStructorArgCountsAddedStructorArgCounts322     AddedStructorArgCounts(unsigned P, unsigned S) : Prefix(P), Suffix(S) {}
prefixAddedStructorArgCounts323     static AddedStructorArgCounts prefix(unsigned N) { return {N, 0}; }
suffixAddedStructorArgCounts324     static AddedStructorArgCounts suffix(unsigned N) { return {0, N}; }
325   };
326 
327   /// Build the signature of the given constructor or destructor variant by
328   /// adding any required parameters.  For convenience, ArgTys has been
329   /// initialized with the type of 'this'.
330   virtual AddedStructorArgCounts
331   buildStructorSignature(GlobalDecl GD,
332                          SmallVectorImpl<CanQualType> &ArgTys) = 0;
333 
334   /// Returns true if the given destructor type should be emitted as a linkonce
335   /// delegating thunk, regardless of whether the dtor is defined in this TU or
336   /// not.
337   virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
338                                       CXXDtorType DT) const = 0;
339 
340   virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
341                                           const CXXDestructorDecl *Dtor,
342                                           CXXDtorType DT) const;
343 
344   virtual llvm::GlobalValue::LinkageTypes
345   getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
346                           CXXDtorType DT) const;
347 
348   /// Emit destructor variants required by this ABI.
349   virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
350 
351   /// Get the type of the implicit "this" parameter used by a method. May return
352   /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
353   /// parameter to point to some artificial offset in a complete object due to
354   /// vbases being reordered.
355   virtual const CXXRecordDecl *
getThisArgumentTypeForMethod(const CXXMethodDecl * MD)356   getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
357     return MD->getParent();
358   }
359 
360   /// Perform ABI-specific "this" argument adjustment required prior to
361   /// a call of a virtual function.
362   /// The "VirtualCall" argument is true iff the call itself is virtual.
363   virtual Address
adjustThisArgumentForVirtualFunctionCall(CodeGenFunction & CGF,GlobalDecl GD,Address This,bool VirtualCall)364   adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
365                                            Address This, bool VirtualCall) {
366     return This;
367   }
368 
369   /// Build a parameter variable suitable for 'this'.
370   void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
371 
372   /// Insert any ABI-specific implicit parameters into the parameter list for a
373   /// function.  This generally involves extra data for constructors and
374   /// destructors.
375   ///
376   /// ABIs may also choose to override the return type, which has been
377   /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
378   /// the formal return type of the function otherwise.
379   virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
380                                          FunctionArgList &Params) = 0;
381 
382   /// Get the ABI-specific "this" parameter adjustment to apply in the prologue
383   /// of a virtual function.
getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD)384   virtual CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
385     return CharUnits::Zero();
386   }
387 
388   /// Emit the ABI-specific prolog for the function.
389   virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
390 
391   virtual AddedStructorArgs
392   getImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
393                              CXXCtorType Type, bool ForVirtualBase,
394                              bool Delegating) = 0;
395 
396   /// Add any ABI-specific implicit arguments needed to call a constructor.
397   ///
398   /// \return The number of arguments added at the beginning and end of the
399   /// call, which is typically zero or one.
400   AddedStructorArgCounts
401   addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
402                              CXXCtorType Type, bool ForVirtualBase,
403                              bool Delegating, CallArgList &Args);
404 
405   /// Get the implicit (second) parameter that comes after the "this" pointer,
406   /// or nullptr if there is isn't one.
407   virtual llvm::Value *
408   getCXXDestructorImplicitParam(CodeGenFunction &CGF,
409                                 const CXXDestructorDecl *DD, CXXDtorType Type,
410                                 bool ForVirtualBase, bool Delegating) = 0;
411 
412   /// Emit the destructor call.
413   virtual void EmitDestructorCall(CodeGenFunction &CGF,
414                                   const CXXDestructorDecl *DD, CXXDtorType Type,
415                                   bool ForVirtualBase, bool Delegating,
416                                   Address This, QualType ThisTy) = 0;
417 
418   /// Emits the VTable definitions required for the given record type.
419   virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
420                                      const CXXRecordDecl *RD) = 0;
421 
422   /// Checks if ABI requires extra virtual offset for vtable field.
423   virtual bool
424   isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
425                                       CodeGenFunction::VPtr Vptr) = 0;
426 
427   /// Checks if ABI requires to initialize vptrs for given dynamic class.
428   virtual bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) = 0;
429 
430   /// Get the address point of the vtable for the given base subobject.
431   virtual llvm::Constant *
432   getVTableAddressPoint(BaseSubobject Base,
433                         const CXXRecordDecl *VTableClass) = 0;
434 
435   /// Get the address point of the vtable for the given base subobject while
436   /// building a constructor or a destructor.
437   virtual llvm::Value *
438   getVTableAddressPointInStructor(CodeGenFunction &CGF, const CXXRecordDecl *RD,
439                                   BaseSubobject Base,
440                                   const CXXRecordDecl *NearestVBase) = 0;
441 
442   /// Get the address point of the vtable for the given base subobject while
443   /// building a constexpr.
444   virtual llvm::Constant *
445   getVTableAddressPointForConstExpr(BaseSubobject Base,
446                                     const CXXRecordDecl *VTableClass) = 0;
447 
448   /// Get the address of the vtable for the given record decl which should be
449   /// used for the vptr at the given offset in RD.
450   virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
451                                                 CharUnits VPtrOffset) = 0;
452 
453   /// Build a virtual function pointer in the ABI-specific way.
454   virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF,
455                                              GlobalDecl GD, Address This,
456                                              llvm::Type *Ty,
457                                              SourceLocation Loc) = 0;
458 
459   using DeleteOrMemberCallExpr =
460       llvm::PointerUnion<const CXXDeleteExpr *, const CXXMemberCallExpr *>;
461 
462   /// Emit the ABI-specific virtual destructor call.
463   virtual llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
464                                                  const CXXDestructorDecl *Dtor,
465                                                  CXXDtorType DtorType,
466                                                  Address This,
467                                                  DeleteOrMemberCallExpr E) = 0;
468 
adjustCallArgsForDestructorThunk(CodeGenFunction & CGF,GlobalDecl GD,CallArgList & CallArgs)469   virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
470                                                 GlobalDecl GD,
471                                                 CallArgList &CallArgs) {}
472 
473   /// Emit any tables needed to implement virtual inheritance.  For Itanium,
474   /// this emits virtual table tables.  For the MSVC++ ABI, this emits virtual
475   /// base tables.
476   virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
477 
478   virtual bool exportThunk() = 0;
479   virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
480                                GlobalDecl GD, bool ReturnAdjustment) = 0;
481 
482   virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
483                                              Address This,
484                                              const ThisAdjustment &TA) = 0;
485 
486   virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
487                                                Address Ret,
488                                                const ReturnAdjustment &RA) = 0;
489 
490   virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
491                                    RValue RV, QualType ResultType);
492 
493   virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
494                                       FunctionArgList &Args) const = 0;
495 
496   /// Gets the offsets of all the virtual base pointers in a given class.
497   virtual std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD);
498 
499   /// Gets the pure virtual member call function.
500   virtual StringRef GetPureVirtualCallName() = 0;
501 
502   /// Gets the deleted virtual member call name.
503   virtual StringRef GetDeletedVirtualCallName() = 0;
504 
505   /**************************** Array cookies ******************************/
506 
507   /// Returns the extra size required in order to store the array
508   /// cookie for the given new-expression.  May return 0 to indicate that no
509   /// array cookie is required.
510   ///
511   /// Several cases are filtered out before this method is called:
512   ///   - non-array allocations never need a cookie
513   ///   - calls to \::operator new(size_t, void*) never need a cookie
514   ///
515   /// \param expr - the new-expression being allocated.
516   virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
517 
518   /// Initialize the array cookie for the given allocation.
519   ///
520   /// \param NewPtr - a char* which is the presumed-non-null
521   ///   return value of the allocation function
522   /// \param NumElements - the computed number of elements,
523   ///   potentially collapsed from the multidimensional array case;
524   ///   always a size_t
525   /// \param ElementType - the base element allocated type,
526   ///   i.e. the allocated type after stripping all array types
527   virtual Address InitializeArrayCookie(CodeGenFunction &CGF,
528                                         Address NewPtr,
529                                         llvm::Value *NumElements,
530                                         const CXXNewExpr *expr,
531                                         QualType ElementType);
532 
533   /// Reads the array cookie associated with the given pointer,
534   /// if it has one.
535   ///
536   /// \param Ptr - a pointer to the first element in the array
537   /// \param ElementType - the base element type of elements of the array
538   /// \param NumElements - an out parameter which will be initialized
539   ///   with the number of elements allocated, or zero if there is no
540   ///   cookie
541   /// \param AllocPtr - an out parameter which will be initialized
542   ///   with a char* pointing to the address returned by the allocation
543   ///   function
544   /// \param CookieSize - an out parameter which will be initialized
545   ///   with the size of the cookie, or zero if there is no cookie
546   virtual void ReadArrayCookie(CodeGenFunction &CGF, Address Ptr,
547                                const CXXDeleteExpr *expr,
548                                QualType ElementType, llvm::Value *&NumElements,
549                                llvm::Value *&AllocPtr, CharUnits &CookieSize);
550 
551   /// Return whether the given global decl needs a VTT parameter.
552   virtual bool NeedsVTTParameter(GlobalDecl GD);
553 
554 protected:
555   /// Returns the extra size required in order to store the array
556   /// cookie for the given type.  Assumes that an array cookie is
557   /// required.
558   virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
559 
560   /// Reads the array cookie for an allocation which is known to have one.
561   /// This is called by the standard implementation of ReadArrayCookie.
562   ///
563   /// \param ptr - a pointer to the allocation made for an array, as a char*
564   /// \param cookieSize - the computed cookie size of an array
565   ///
566   /// Other parameters are as above.
567   ///
568   /// \return a size_t
569   virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF, Address ptr,
570                                            CharUnits cookieSize);
571 
572 public:
573 
574   /*************************** Static local guards ****************************/
575 
576   /// Emits the guarded initializer and destructor setup for the given
577   /// variable, given that it couldn't be emitted as a constant.
578   /// If \p PerformInit is false, the initialization has been folded to a
579   /// constant and should not be performed.
580   ///
581   /// The variable may be:
582   ///   - a static local variable
583   ///   - a static data member of a class template instantiation
584   virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
585                                llvm::GlobalVariable *DeclPtr,
586                                bool PerformInit) = 0;
587 
588   /// Emit code to force the execution of a destructor during global
589   /// teardown.  The default implementation of this uses atexit.
590   ///
591   /// \param Dtor - a function taking a single pointer argument
592   /// \param Addr - a pointer to pass to the destructor function.
593   virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
594                                   llvm::FunctionCallee Dtor,
595                                   llvm::Constant *Addr) = 0;
596 
597   /*************************** thread_local initialization ********************/
598 
599   /// Emits ABI-required functions necessary to initialize thread_local
600   /// variables in this translation unit.
601   ///
602   /// \param CXXThreadLocals - The thread_local declarations in this translation
603   ///        unit.
604   /// \param CXXThreadLocalInits - If this translation unit contains any
605   ///        non-constant initialization or non-trivial destruction for
606   ///        thread_local variables, a list of functions to perform the
607   ///        initialization.
608   virtual void EmitThreadLocalInitFuncs(
609       CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
610       ArrayRef<llvm::Function *> CXXThreadLocalInits,
611       ArrayRef<const VarDecl *> CXXThreadLocalInitVars) = 0;
612 
613   // Determine if references to thread_local global variables can be made
614   // directly or require access through a thread wrapper function.
615   virtual bool usesThreadWrapperFunction(const VarDecl *VD) const = 0;
616 
617   /// Emit a reference to a non-local thread_local variable (including
618   /// triggering the initialization of all thread_local variables in its
619   /// translation unit).
620   virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
621                                               const VarDecl *VD,
622                                               QualType LValType) = 0;
623 
624   /// Emit a single constructor/destructor with the given type from a C++
625   /// constructor Decl.
626   virtual void emitCXXStructor(GlobalDecl GD) = 0;
627 
628   /// Load a vtable from This, an object of polymorphic type RD, or from one of
629   /// its virtual bases if it does not have its own vtable. Returns the vtable
630   /// and the class from which the vtable was loaded.
631   virtual std::pair<llvm::Value *, const CXXRecordDecl *>
632   LoadVTablePtr(CodeGenFunction &CGF, Address This,
633                 const CXXRecordDecl *RD) = 0;
634 };
635 
636 // Create an instance of a C++ ABI class:
637 
638 /// Creates an Itanium-family ABI.
639 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
640 
641 /// Creates a Microsoft-family ABI.
642 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);
643 
644 struct CatchRetScope final : EHScopeStack::Cleanup {
645   llvm::CatchPadInst *CPI;
646 
CatchRetScopefinal647   CatchRetScope(llvm::CatchPadInst *CPI) : CPI(CPI) {}
648 
Emitfinal649   void Emit(CodeGenFunction &CGF, Flags flags) override {
650     llvm::BasicBlock *BB = CGF.createBasicBlock("catchret.dest");
651     CGF.Builder.CreateCatchRet(CPI, BB);
652     CGF.EmitBlock(BB);
653   }
654 };
655 }
656 }
657 
658 #endif
659