xref: /aosp_15_r20/external/clang/lib/CodeGen/ItaniumCXXABI.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This provides C++ code generation targeting the Itanium C++ ABI.  The class
11*67e74705SXin Li // in this file generates structures that follow the Itanium C++ ABI, which is
12*67e74705SXin Li // documented at:
13*67e74705SXin Li //  http://www.codesourcery.com/public/cxx-abi/abi.html
14*67e74705SXin Li //  http://www.codesourcery.com/public/cxx-abi/abi-eh.html
15*67e74705SXin Li //
16*67e74705SXin Li // It also supports the closely-related ARM ABI, documented at:
17*67e74705SXin Li // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18*67e74705SXin Li //
19*67e74705SXin Li //===----------------------------------------------------------------------===//
20*67e74705SXin Li 
21*67e74705SXin Li #include "CGCXXABI.h"
22*67e74705SXin Li #include "CGCleanup.h"
23*67e74705SXin Li #include "CGRecordLayout.h"
24*67e74705SXin Li #include "CGVTables.h"
25*67e74705SXin Li #include "CodeGenFunction.h"
26*67e74705SXin Li #include "CodeGenModule.h"
27*67e74705SXin Li #include "TargetInfo.h"
28*67e74705SXin Li #include "clang/AST/Mangle.h"
29*67e74705SXin Li #include "clang/AST/Type.h"
30*67e74705SXin Li #include "clang/AST/StmtCXX.h"
31*67e74705SXin Li #include "llvm/IR/CallSite.h"
32*67e74705SXin Li #include "llvm/IR/DataLayout.h"
33*67e74705SXin Li #include "llvm/IR/Instructions.h"
34*67e74705SXin Li #include "llvm/IR/Intrinsics.h"
35*67e74705SXin Li #include "llvm/IR/Value.h"
36*67e74705SXin Li 
37*67e74705SXin Li using namespace clang;
38*67e74705SXin Li using namespace CodeGen;
39*67e74705SXin Li 
40*67e74705SXin Li namespace {
41*67e74705SXin Li class ItaniumCXXABI : public CodeGen::CGCXXABI {
42*67e74705SXin Li   /// VTables - All the vtables which have been defined.
43*67e74705SXin Li   llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
44*67e74705SXin Li 
45*67e74705SXin Li protected:
46*67e74705SXin Li   bool UseARMMethodPtrABI;
47*67e74705SXin Li   bool UseARMGuardVarABI;
48*67e74705SXin Li 
getMangleContext()49*67e74705SXin Li   ItaniumMangleContext &getMangleContext() {
50*67e74705SXin Li     return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
51*67e74705SXin Li   }
52*67e74705SXin Li 
53*67e74705SXin Li public:
ItaniumCXXABI(CodeGen::CodeGenModule & CGM,bool UseARMMethodPtrABI=false,bool UseARMGuardVarABI=false)54*67e74705SXin Li   ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
55*67e74705SXin Li                 bool UseARMMethodPtrABI = false,
56*67e74705SXin Li                 bool UseARMGuardVarABI = false) :
57*67e74705SXin Li     CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
58*67e74705SXin Li     UseARMGuardVarABI(UseARMGuardVarABI) { }
59*67e74705SXin Li 
60*67e74705SXin Li   bool classifyReturnType(CGFunctionInfo &FI) const override;
61*67e74705SXin Li 
getRecordArgABI(const CXXRecordDecl * RD) const62*67e74705SXin Li   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
63*67e74705SXin Li     // Structures with either a non-trivial destructor or a non-trivial
64*67e74705SXin Li     // copy constructor are always indirect.
65*67e74705SXin Li     // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
66*67e74705SXin Li     // special members.
67*67e74705SXin Li     if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
68*67e74705SXin Li       return RAA_Indirect;
69*67e74705SXin Li     return RAA_Default;
70*67e74705SXin Li   }
71*67e74705SXin Li 
isThisCompleteObject(GlobalDecl GD) const72*67e74705SXin Li   bool isThisCompleteObject(GlobalDecl GD) const override {
73*67e74705SXin Li     // The Itanium ABI has separate complete-object vs.  base-object
74*67e74705SXin Li     // variants of both constructors and destructors.
75*67e74705SXin Li     if (isa<CXXDestructorDecl>(GD.getDecl())) {
76*67e74705SXin Li       switch (GD.getDtorType()) {
77*67e74705SXin Li       case Dtor_Complete:
78*67e74705SXin Li       case Dtor_Deleting:
79*67e74705SXin Li         return true;
80*67e74705SXin Li 
81*67e74705SXin Li       case Dtor_Base:
82*67e74705SXin Li         return false;
83*67e74705SXin Li 
84*67e74705SXin Li       case Dtor_Comdat:
85*67e74705SXin Li         llvm_unreachable("emitting dtor comdat as function?");
86*67e74705SXin Li       }
87*67e74705SXin Li       llvm_unreachable("bad dtor kind");
88*67e74705SXin Li     }
89*67e74705SXin Li     if (isa<CXXConstructorDecl>(GD.getDecl())) {
90*67e74705SXin Li       switch (GD.getCtorType()) {
91*67e74705SXin Li       case Ctor_Complete:
92*67e74705SXin Li         return true;
93*67e74705SXin Li 
94*67e74705SXin Li       case Ctor_Base:
95*67e74705SXin Li         return false;
96*67e74705SXin Li 
97*67e74705SXin Li       case Ctor_CopyingClosure:
98*67e74705SXin Li       case Ctor_DefaultClosure:
99*67e74705SXin Li         llvm_unreachable("closure ctors in Itanium ABI?");
100*67e74705SXin Li 
101*67e74705SXin Li       case Ctor_Comdat:
102*67e74705SXin Li         llvm_unreachable("emitting ctor comdat as function?");
103*67e74705SXin Li       }
104*67e74705SXin Li       llvm_unreachable("bad dtor kind");
105*67e74705SXin Li     }
106*67e74705SXin Li 
107*67e74705SXin Li     // No other kinds.
108*67e74705SXin Li     return false;
109*67e74705SXin Li   }
110*67e74705SXin Li 
111*67e74705SXin Li   bool isZeroInitializable(const MemberPointerType *MPT) override;
112*67e74705SXin Li 
113*67e74705SXin Li   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
114*67e74705SXin Li 
115*67e74705SXin Li   llvm::Value *
116*67e74705SXin Li     EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
117*67e74705SXin Li                                     const Expr *E,
118*67e74705SXin Li                                     Address This,
119*67e74705SXin Li                                     llvm::Value *&ThisPtrForCall,
120*67e74705SXin Li                                     llvm::Value *MemFnPtr,
121*67e74705SXin Li                                     const MemberPointerType *MPT) override;
122*67e74705SXin Li 
123*67e74705SXin Li   llvm::Value *
124*67e74705SXin Li     EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
125*67e74705SXin Li                                  Address Base,
126*67e74705SXin Li                                  llvm::Value *MemPtr,
127*67e74705SXin Li                                  const MemberPointerType *MPT) override;
128*67e74705SXin Li 
129*67e74705SXin Li   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
130*67e74705SXin Li                                            const CastExpr *E,
131*67e74705SXin Li                                            llvm::Value *Src) override;
132*67e74705SXin Li   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
133*67e74705SXin Li                                               llvm::Constant *Src) override;
134*67e74705SXin Li 
135*67e74705SXin Li   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
136*67e74705SXin Li 
137*67e74705SXin Li   llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
138*67e74705SXin Li   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
139*67e74705SXin Li                                         CharUnits offset) override;
140*67e74705SXin Li   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
141*67e74705SXin Li   llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
142*67e74705SXin Li                                      CharUnits ThisAdjustment);
143*67e74705SXin Li 
144*67e74705SXin Li   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
145*67e74705SXin Li                                            llvm::Value *L, llvm::Value *R,
146*67e74705SXin Li                                            const MemberPointerType *MPT,
147*67e74705SXin Li                                            bool Inequality) override;
148*67e74705SXin Li 
149*67e74705SXin Li   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
150*67e74705SXin Li                                          llvm::Value *Addr,
151*67e74705SXin Li                                          const MemberPointerType *MPT) override;
152*67e74705SXin Li 
153*67e74705SXin Li   void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
154*67e74705SXin Li                                Address Ptr, QualType ElementType,
155*67e74705SXin Li                                const CXXDestructorDecl *Dtor) override;
156*67e74705SXin Li 
getAlignmentOfExnObject()157*67e74705SXin Li   CharUnits getAlignmentOfExnObject() {
158*67e74705SXin Li     unsigned Align = CGM.getContext().getTargetInfo().getExnObjectAlignment();
159*67e74705SXin Li     return CGM.getContext().toCharUnitsFromBits(Align);
160*67e74705SXin Li   }
161*67e74705SXin Li 
162*67e74705SXin Li   void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
163*67e74705SXin Li   void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
164*67e74705SXin Li 
165*67e74705SXin Li   void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
166*67e74705SXin Li 
167*67e74705SXin Li   llvm::CallInst *
168*67e74705SXin Li   emitTerminateForUnexpectedException(CodeGenFunction &CGF,
169*67e74705SXin Li                                       llvm::Value *Exn) override;
170*67e74705SXin Li 
171*67e74705SXin Li   void EmitFundamentalRTTIDescriptor(QualType Type);
172*67e74705SXin Li   void EmitFundamentalRTTIDescriptors();
173*67e74705SXin Li   llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
174*67e74705SXin Li   CatchTypeInfo
getAddrOfCXXCatchHandlerType(QualType Ty,QualType CatchHandlerType)175*67e74705SXin Li   getAddrOfCXXCatchHandlerType(QualType Ty,
176*67e74705SXin Li                                QualType CatchHandlerType) override {
177*67e74705SXin Li     return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
178*67e74705SXin Li   }
179*67e74705SXin Li 
180*67e74705SXin Li   bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
181*67e74705SXin Li   void EmitBadTypeidCall(CodeGenFunction &CGF) override;
182*67e74705SXin Li   llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
183*67e74705SXin Li                           Address ThisPtr,
184*67e74705SXin Li                           llvm::Type *StdTypeInfoPtrTy) override;
185*67e74705SXin Li 
186*67e74705SXin Li   bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
187*67e74705SXin Li                                           QualType SrcRecordTy) override;
188*67e74705SXin Li 
189*67e74705SXin Li   llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
190*67e74705SXin Li                                    QualType SrcRecordTy, QualType DestTy,
191*67e74705SXin Li                                    QualType DestRecordTy,
192*67e74705SXin Li                                    llvm::BasicBlock *CastEnd) override;
193*67e74705SXin Li 
194*67e74705SXin Li   llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
195*67e74705SXin Li                                      QualType SrcRecordTy,
196*67e74705SXin Li                                      QualType DestTy) override;
197*67e74705SXin Li 
198*67e74705SXin Li   bool EmitBadCastCall(CodeGenFunction &CGF) override;
199*67e74705SXin Li 
200*67e74705SXin Li   llvm::Value *
201*67e74705SXin Li     GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
202*67e74705SXin Li                               const CXXRecordDecl *ClassDecl,
203*67e74705SXin Li                               const CXXRecordDecl *BaseClassDecl) override;
204*67e74705SXin Li 
205*67e74705SXin Li   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
206*67e74705SXin Li 
207*67e74705SXin Li   void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
208*67e74705SXin Li                               SmallVectorImpl<CanQualType> &ArgTys) override;
209*67e74705SXin Li 
useThunkForDtorVariant(const CXXDestructorDecl * Dtor,CXXDtorType DT) const210*67e74705SXin Li   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
211*67e74705SXin Li                               CXXDtorType DT) const override {
212*67e74705SXin Li     // Itanium does not emit any destructor variant as an inline thunk.
213*67e74705SXin Li     // Delegating may occur as an optimization, but all variants are either
214*67e74705SXin Li     // emitted with external linkage or as linkonce if they are inline and used.
215*67e74705SXin Li     return false;
216*67e74705SXin Li   }
217*67e74705SXin Li 
218*67e74705SXin Li   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
219*67e74705SXin Li 
220*67e74705SXin Li   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
221*67e74705SXin Li                                  FunctionArgList &Params) override;
222*67e74705SXin Li 
223*67e74705SXin Li   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
224*67e74705SXin Li 
225*67e74705SXin Li   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
226*67e74705SXin Li                                       const CXXConstructorDecl *D,
227*67e74705SXin Li                                       CXXCtorType Type, bool ForVirtualBase,
228*67e74705SXin Li                                       bool Delegating,
229*67e74705SXin Li                                       CallArgList &Args) override;
230*67e74705SXin Li 
231*67e74705SXin Li   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
232*67e74705SXin Li                           CXXDtorType Type, bool ForVirtualBase,
233*67e74705SXin Li                           bool Delegating, Address This) override;
234*67e74705SXin Li 
235*67e74705SXin Li   void emitVTableDefinitions(CodeGenVTables &CGVT,
236*67e74705SXin Li                              const CXXRecordDecl *RD) override;
237*67e74705SXin Li 
238*67e74705SXin Li   bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
239*67e74705SXin Li                                            CodeGenFunction::VPtr Vptr) override;
240*67e74705SXin Li 
doStructorsInitializeVPtrs(const CXXRecordDecl * VTableClass)241*67e74705SXin Li   bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
242*67e74705SXin Li     return true;
243*67e74705SXin Li   }
244*67e74705SXin Li 
245*67e74705SXin Li   llvm::Constant *
246*67e74705SXin Li   getVTableAddressPoint(BaseSubobject Base,
247*67e74705SXin Li                         const CXXRecordDecl *VTableClass) override;
248*67e74705SXin Li 
249*67e74705SXin Li   llvm::Value *getVTableAddressPointInStructor(
250*67e74705SXin Li       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
251*67e74705SXin Li       BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
252*67e74705SXin Li 
253*67e74705SXin Li   llvm::Value *getVTableAddressPointInStructorWithVTT(
254*67e74705SXin Li       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
255*67e74705SXin Li       BaseSubobject Base, const CXXRecordDecl *NearestVBase);
256*67e74705SXin Li 
257*67e74705SXin Li   llvm::Constant *
258*67e74705SXin Li   getVTableAddressPointForConstExpr(BaseSubobject Base,
259*67e74705SXin Li                                     const CXXRecordDecl *VTableClass) override;
260*67e74705SXin Li 
261*67e74705SXin Li   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
262*67e74705SXin Li                                         CharUnits VPtrOffset) override;
263*67e74705SXin Li 
264*67e74705SXin Li   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
265*67e74705SXin Li                                          Address This, llvm::Type *Ty,
266*67e74705SXin Li                                          SourceLocation Loc) override;
267*67e74705SXin Li 
268*67e74705SXin Li   llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
269*67e74705SXin Li                                          const CXXDestructorDecl *Dtor,
270*67e74705SXin Li                                          CXXDtorType DtorType,
271*67e74705SXin Li                                          Address This,
272*67e74705SXin Li                                          const CXXMemberCallExpr *CE) override;
273*67e74705SXin Li 
274*67e74705SXin Li   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
275*67e74705SXin Li 
276*67e74705SXin Li   bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
277*67e74705SXin Li 
setThunkLinkage(llvm::Function * Thunk,bool ForVTable,GlobalDecl GD,bool ReturnAdjustment)278*67e74705SXin Li   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
279*67e74705SXin Li                        bool ReturnAdjustment) override {
280*67e74705SXin Li     // Allow inlining of thunks by emitting them with available_externally
281*67e74705SXin Li     // linkage together with vtables when needed.
282*67e74705SXin Li     if (ForVTable && !Thunk->hasLocalLinkage())
283*67e74705SXin Li       Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
284*67e74705SXin Li   }
285*67e74705SXin Li 
286*67e74705SXin Li   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
287*67e74705SXin Li                                      const ThisAdjustment &TA) override;
288*67e74705SXin Li 
289*67e74705SXin Li   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
290*67e74705SXin Li                                        const ReturnAdjustment &RA) override;
291*67e74705SXin Li 
getSrcArgforCopyCtor(const CXXConstructorDecl *,FunctionArgList & Args) const292*67e74705SXin Li   size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
293*67e74705SXin Li                               FunctionArgList &Args) const override {
294*67e74705SXin Li     assert(!Args.empty() && "expected the arglist to not be empty!");
295*67e74705SXin Li     return Args.size() - 1;
296*67e74705SXin Li   }
297*67e74705SXin Li 
GetPureVirtualCallName()298*67e74705SXin Li   StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
GetDeletedVirtualCallName()299*67e74705SXin Li   StringRef GetDeletedVirtualCallName() override
300*67e74705SXin Li     { return "__cxa_deleted_virtual"; }
301*67e74705SXin Li 
302*67e74705SXin Li   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
303*67e74705SXin Li   Address InitializeArrayCookie(CodeGenFunction &CGF,
304*67e74705SXin Li                                 Address NewPtr,
305*67e74705SXin Li                                 llvm::Value *NumElements,
306*67e74705SXin Li                                 const CXXNewExpr *expr,
307*67e74705SXin Li                                 QualType ElementType) override;
308*67e74705SXin Li   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
309*67e74705SXin Li                                    Address allocPtr,
310*67e74705SXin Li                                    CharUnits cookieSize) override;
311*67e74705SXin Li 
312*67e74705SXin Li   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
313*67e74705SXin Li                        llvm::GlobalVariable *DeclPtr,
314*67e74705SXin Li                        bool PerformInit) override;
315*67e74705SXin Li   void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
316*67e74705SXin Li                           llvm::Constant *dtor, llvm::Constant *addr) override;
317*67e74705SXin Li 
318*67e74705SXin Li   llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
319*67e74705SXin Li                                                 llvm::Value *Val);
320*67e74705SXin Li   void EmitThreadLocalInitFuncs(
321*67e74705SXin Li       CodeGenModule &CGM,
322*67e74705SXin Li       ArrayRef<const VarDecl *> CXXThreadLocals,
323*67e74705SXin Li       ArrayRef<llvm::Function *> CXXThreadLocalInits,
324*67e74705SXin Li       ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
325*67e74705SXin Li 
usesThreadWrapperFunction() const326*67e74705SXin Li   bool usesThreadWrapperFunction() const override { return true; }
327*67e74705SXin Li   LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
328*67e74705SXin Li                                       QualType LValType) override;
329*67e74705SXin Li 
330*67e74705SXin Li   bool NeedsVTTParameter(GlobalDecl GD) override;
331*67e74705SXin Li 
332*67e74705SXin Li   /**************************** RTTI Uniqueness ******************************/
333*67e74705SXin Li 
334*67e74705SXin Li protected:
335*67e74705SXin Li   /// Returns true if the ABI requires RTTI type_info objects to be unique
336*67e74705SXin Li   /// across a program.
shouldRTTIBeUnique() const337*67e74705SXin Li   virtual bool shouldRTTIBeUnique() const { return true; }
338*67e74705SXin Li 
339*67e74705SXin Li public:
340*67e74705SXin Li   /// What sort of unique-RTTI behavior should we use?
341*67e74705SXin Li   enum RTTIUniquenessKind {
342*67e74705SXin Li     /// We are guaranteeing, or need to guarantee, that the RTTI string
343*67e74705SXin Li     /// is unique.
344*67e74705SXin Li     RUK_Unique,
345*67e74705SXin Li 
346*67e74705SXin Li     /// We are not guaranteeing uniqueness for the RTTI string, so we
347*67e74705SXin Li     /// can demote to hidden visibility but must use string comparisons.
348*67e74705SXin Li     RUK_NonUniqueHidden,
349*67e74705SXin Li 
350*67e74705SXin Li     /// We are not guaranteeing uniqueness for the RTTI string, so we
351*67e74705SXin Li     /// have to use string comparisons, but we also have to emit it with
352*67e74705SXin Li     /// non-hidden visibility.
353*67e74705SXin Li     RUK_NonUniqueVisible
354*67e74705SXin Li   };
355*67e74705SXin Li 
356*67e74705SXin Li   /// Return the required visibility status for the given type and linkage in
357*67e74705SXin Li   /// the current ABI.
358*67e74705SXin Li   RTTIUniquenessKind
359*67e74705SXin Li   classifyRTTIUniqueness(QualType CanTy,
360*67e74705SXin Li                          llvm::GlobalValue::LinkageTypes Linkage) const;
361*67e74705SXin Li   friend class ItaniumRTTIBuilder;
362*67e74705SXin Li 
363*67e74705SXin Li   void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
364*67e74705SXin Li 
365*67e74705SXin Li  private:
hasAnyUsedVirtualInlineFunction(const CXXRecordDecl * RD) const366*67e74705SXin Li    bool hasAnyUsedVirtualInlineFunction(const CXXRecordDecl *RD) const {
367*67e74705SXin Li     const auto &VtableLayout =
368*67e74705SXin Li         CGM.getItaniumVTableContext().getVTableLayout(RD);
369*67e74705SXin Li 
370*67e74705SXin Li     for (const auto &VtableComponent : VtableLayout.vtable_components()) {
371*67e74705SXin Li       if (!VtableComponent.isUsedFunctionPointerKind())
372*67e74705SXin Li         continue;
373*67e74705SXin Li 
374*67e74705SXin Li       const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
375*67e74705SXin Li       if (Method->getCanonicalDecl()->isInlined())
376*67e74705SXin Li         return true;
377*67e74705SXin Li     }
378*67e74705SXin Li     return false;
379*67e74705SXin Li   }
380*67e74705SXin Li 
isVTableHidden(const CXXRecordDecl * RD) const381*67e74705SXin Li   bool isVTableHidden(const CXXRecordDecl *RD) const {
382*67e74705SXin Li     const auto &VtableLayout =
383*67e74705SXin Li             CGM.getItaniumVTableContext().getVTableLayout(RD);
384*67e74705SXin Li 
385*67e74705SXin Li     for (const auto &VtableComponent : VtableLayout.vtable_components()) {
386*67e74705SXin Li       if (VtableComponent.isRTTIKind()) {
387*67e74705SXin Li         const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
388*67e74705SXin Li         if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
389*67e74705SXin Li           return true;
390*67e74705SXin Li       } else if (VtableComponent.isUsedFunctionPointerKind()) {
391*67e74705SXin Li         const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
392*67e74705SXin Li         if (Method->getVisibility() == Visibility::HiddenVisibility &&
393*67e74705SXin Li             !Method->isDefined())
394*67e74705SXin Li           return true;
395*67e74705SXin Li       }
396*67e74705SXin Li     }
397*67e74705SXin Li     return false;
398*67e74705SXin Li   }
399*67e74705SXin Li };
400*67e74705SXin Li 
401*67e74705SXin Li class ARMCXXABI : public ItaniumCXXABI {
402*67e74705SXin Li public:
ARMCXXABI(CodeGen::CodeGenModule & CGM)403*67e74705SXin Li   ARMCXXABI(CodeGen::CodeGenModule &CGM) :
404*67e74705SXin Li     ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
405*67e74705SXin Li                   /* UseARMGuardVarABI = */ true) {}
406*67e74705SXin Li 
HasThisReturn(GlobalDecl GD) const407*67e74705SXin Li   bool HasThisReturn(GlobalDecl GD) const override {
408*67e74705SXin Li     return (isa<CXXConstructorDecl>(GD.getDecl()) || (
409*67e74705SXin Li               isa<CXXDestructorDecl>(GD.getDecl()) &&
410*67e74705SXin Li               GD.getDtorType() != Dtor_Deleting));
411*67e74705SXin Li   }
412*67e74705SXin Li 
413*67e74705SXin Li   void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
414*67e74705SXin Li                            QualType ResTy) override;
415*67e74705SXin Li 
416*67e74705SXin Li   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
417*67e74705SXin Li   Address InitializeArrayCookie(CodeGenFunction &CGF,
418*67e74705SXin Li                                 Address NewPtr,
419*67e74705SXin Li                                 llvm::Value *NumElements,
420*67e74705SXin Li                                 const CXXNewExpr *expr,
421*67e74705SXin Li                                 QualType ElementType) override;
422*67e74705SXin Li   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
423*67e74705SXin Li                                    CharUnits cookieSize) override;
424*67e74705SXin Li };
425*67e74705SXin Li 
426*67e74705SXin Li class iOS64CXXABI : public ARMCXXABI {
427*67e74705SXin Li public:
iOS64CXXABI(CodeGen::CodeGenModule & CGM)428*67e74705SXin Li   iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
429*67e74705SXin Li 
430*67e74705SXin Li   // ARM64 libraries are prepared for non-unique RTTI.
shouldRTTIBeUnique() const431*67e74705SXin Li   bool shouldRTTIBeUnique() const override { return false; }
432*67e74705SXin Li };
433*67e74705SXin Li 
434*67e74705SXin Li class WebAssemblyCXXABI final : public ItaniumCXXABI {
435*67e74705SXin Li public:
WebAssemblyCXXABI(CodeGen::CodeGenModule & CGM)436*67e74705SXin Li   explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
437*67e74705SXin Li       : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
438*67e74705SXin Li                       /*UseARMGuardVarABI=*/true) {}
439*67e74705SXin Li 
440*67e74705SXin Li private:
HasThisReturn(GlobalDecl GD) const441*67e74705SXin Li   bool HasThisReturn(GlobalDecl GD) const override {
442*67e74705SXin Li     return isa<CXXConstructorDecl>(GD.getDecl()) ||
443*67e74705SXin Li            (isa<CXXDestructorDecl>(GD.getDecl()) &&
444*67e74705SXin Li             GD.getDtorType() != Dtor_Deleting);
445*67e74705SXin Li   }
canCallMismatchedFunctionType() const446*67e74705SXin Li   bool canCallMismatchedFunctionType() const override { return false; }
447*67e74705SXin Li };
448*67e74705SXin Li }
449*67e74705SXin Li 
CreateItaniumCXXABI(CodeGenModule & CGM)450*67e74705SXin Li CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
451*67e74705SXin Li   switch (CGM.getTarget().getCXXABI().getKind()) {
452*67e74705SXin Li   // For IR-generation purposes, there's no significant difference
453*67e74705SXin Li   // between the ARM and iOS ABIs.
454*67e74705SXin Li   case TargetCXXABI::GenericARM:
455*67e74705SXin Li   case TargetCXXABI::iOS:
456*67e74705SXin Li   case TargetCXXABI::WatchOS:
457*67e74705SXin Li     return new ARMCXXABI(CGM);
458*67e74705SXin Li 
459*67e74705SXin Li   case TargetCXXABI::iOS64:
460*67e74705SXin Li     return new iOS64CXXABI(CGM);
461*67e74705SXin Li 
462*67e74705SXin Li   // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
463*67e74705SXin Li   // include the other 32-bit ARM oddities: constructor/destructor return values
464*67e74705SXin Li   // and array cookies.
465*67e74705SXin Li   case TargetCXXABI::GenericAArch64:
466*67e74705SXin Li     return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
467*67e74705SXin Li                              /* UseARMGuardVarABI = */ true);
468*67e74705SXin Li 
469*67e74705SXin Li   case TargetCXXABI::GenericMIPS:
470*67e74705SXin Li     return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
471*67e74705SXin Li 
472*67e74705SXin Li   case TargetCXXABI::WebAssembly:
473*67e74705SXin Li     return new WebAssemblyCXXABI(CGM);
474*67e74705SXin Li 
475*67e74705SXin Li   case TargetCXXABI::GenericItanium:
476*67e74705SXin Li     if (CGM.getContext().getTargetInfo().getTriple().getArch()
477*67e74705SXin Li         == llvm::Triple::le32) {
478*67e74705SXin Li       // For PNaCl, use ARM-style method pointers so that PNaCl code
479*67e74705SXin Li       // does not assume anything about the alignment of function
480*67e74705SXin Li       // pointers.
481*67e74705SXin Li       return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
482*67e74705SXin Li                                /* UseARMGuardVarABI = */ false);
483*67e74705SXin Li     }
484*67e74705SXin Li     return new ItaniumCXXABI(CGM);
485*67e74705SXin Li 
486*67e74705SXin Li   case TargetCXXABI::Microsoft:
487*67e74705SXin Li     llvm_unreachable("Microsoft ABI is not Itanium-based");
488*67e74705SXin Li   }
489*67e74705SXin Li   llvm_unreachable("bad ABI kind");
490*67e74705SXin Li }
491*67e74705SXin Li 
492*67e74705SXin Li llvm::Type *
ConvertMemberPointerType(const MemberPointerType * MPT)493*67e74705SXin Li ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
494*67e74705SXin Li   if (MPT->isMemberDataPointer())
495*67e74705SXin Li     return CGM.PtrDiffTy;
496*67e74705SXin Li   return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
497*67e74705SXin Li }
498*67e74705SXin Li 
499*67e74705SXin Li /// In the Itanium and ARM ABIs, method pointers have the form:
500*67e74705SXin Li ///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
501*67e74705SXin Li ///
502*67e74705SXin Li /// In the Itanium ABI:
503*67e74705SXin Li ///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
504*67e74705SXin Li ///  - the this-adjustment is (memptr.adj)
505*67e74705SXin Li ///  - the virtual offset is (memptr.ptr - 1)
506*67e74705SXin Li ///
507*67e74705SXin Li /// In the ARM ABI:
508*67e74705SXin Li ///  - method pointers are virtual if (memptr.adj & 1) is nonzero
509*67e74705SXin Li ///  - the this-adjustment is (memptr.adj >> 1)
510*67e74705SXin Li ///  - the virtual offset is (memptr.ptr)
511*67e74705SXin Li /// ARM uses 'adj' for the virtual flag because Thumb functions
512*67e74705SXin Li /// may be only single-byte aligned.
513*67e74705SXin Li ///
514*67e74705SXin Li /// If the member is virtual, the adjusted 'this' pointer points
515*67e74705SXin Li /// to a vtable pointer from which the virtual offset is applied.
516*67e74705SXin Li ///
517*67e74705SXin Li /// If the member is non-virtual, memptr.ptr is the address of
518*67e74705SXin Li /// the function to call.
EmitLoadOfMemberFunctionPointer(CodeGenFunction & CGF,const Expr * E,Address ThisAddr,llvm::Value * & ThisPtrForCall,llvm::Value * MemFnPtr,const MemberPointerType * MPT)519*67e74705SXin Li llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
520*67e74705SXin Li     CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
521*67e74705SXin Li     llvm::Value *&ThisPtrForCall,
522*67e74705SXin Li     llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
523*67e74705SXin Li   CGBuilderTy &Builder = CGF.Builder;
524*67e74705SXin Li 
525*67e74705SXin Li   const FunctionProtoType *FPT =
526*67e74705SXin Li     MPT->getPointeeType()->getAs<FunctionProtoType>();
527*67e74705SXin Li   const CXXRecordDecl *RD =
528*67e74705SXin Li     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
529*67e74705SXin Li 
530*67e74705SXin Li   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
531*67e74705SXin Li       CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
532*67e74705SXin Li 
533*67e74705SXin Li   llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
534*67e74705SXin Li 
535*67e74705SXin Li   llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
536*67e74705SXin Li   llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
537*67e74705SXin Li   llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
538*67e74705SXin Li 
539*67e74705SXin Li   // Extract memptr.adj, which is in the second field.
540*67e74705SXin Li   llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
541*67e74705SXin Li 
542*67e74705SXin Li   // Compute the true adjustment.
543*67e74705SXin Li   llvm::Value *Adj = RawAdj;
544*67e74705SXin Li   if (UseARMMethodPtrABI)
545*67e74705SXin Li     Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
546*67e74705SXin Li 
547*67e74705SXin Li   // Apply the adjustment and cast back to the original struct type
548*67e74705SXin Li   // for consistency.
549*67e74705SXin Li   llvm::Value *This = ThisAddr.getPointer();
550*67e74705SXin Li   llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
551*67e74705SXin Li   Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
552*67e74705SXin Li   This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
553*67e74705SXin Li   ThisPtrForCall = This;
554*67e74705SXin Li 
555*67e74705SXin Li   // Load the function pointer.
556*67e74705SXin Li   llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
557*67e74705SXin Li 
558*67e74705SXin Li   // If the LSB in the function pointer is 1, the function pointer points to
559*67e74705SXin Li   // a virtual function.
560*67e74705SXin Li   llvm::Value *IsVirtual;
561*67e74705SXin Li   if (UseARMMethodPtrABI)
562*67e74705SXin Li     IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
563*67e74705SXin Li   else
564*67e74705SXin Li     IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
565*67e74705SXin Li   IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
566*67e74705SXin Li   Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
567*67e74705SXin Li 
568*67e74705SXin Li   // In the virtual path, the adjustment left 'This' pointing to the
569*67e74705SXin Li   // vtable of the correct base subobject.  The "function pointer" is an
570*67e74705SXin Li   // offset within the vtable (+1 for the virtual flag on non-ARM).
571*67e74705SXin Li   CGF.EmitBlock(FnVirtual);
572*67e74705SXin Li 
573*67e74705SXin Li   // Cast the adjusted this to a pointer to vtable pointer and load.
574*67e74705SXin Li   llvm::Type *VTableTy = Builder.getInt8PtrTy();
575*67e74705SXin Li   CharUnits VTablePtrAlign =
576*67e74705SXin Li     CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
577*67e74705SXin Li                                       CGF.getPointerAlign());
578*67e74705SXin Li   llvm::Value *VTable =
579*67e74705SXin Li     CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
580*67e74705SXin Li 
581*67e74705SXin Li   // Apply the offset.
582*67e74705SXin Li   llvm::Value *VTableOffset = FnAsInt;
583*67e74705SXin Li   if (!UseARMMethodPtrABI)
584*67e74705SXin Li     VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
585*67e74705SXin Li   VTable = Builder.CreateGEP(VTable, VTableOffset);
586*67e74705SXin Li 
587*67e74705SXin Li   // Load the virtual function to call.
588*67e74705SXin Li   VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
589*67e74705SXin Li   llvm::Value *VirtualFn =
590*67e74705SXin Li     Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
591*67e74705SXin Li                               "memptr.virtualfn");
592*67e74705SXin Li   CGF.EmitBranch(FnEnd);
593*67e74705SXin Li 
594*67e74705SXin Li   // In the non-virtual path, the function pointer is actually a
595*67e74705SXin Li   // function pointer.
596*67e74705SXin Li   CGF.EmitBlock(FnNonVirtual);
597*67e74705SXin Li   llvm::Value *NonVirtualFn =
598*67e74705SXin Li     Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
599*67e74705SXin Li 
600*67e74705SXin Li   // We're done.
601*67e74705SXin Li   CGF.EmitBlock(FnEnd);
602*67e74705SXin Li   llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
603*67e74705SXin Li   Callee->addIncoming(VirtualFn, FnVirtual);
604*67e74705SXin Li   Callee->addIncoming(NonVirtualFn, FnNonVirtual);
605*67e74705SXin Li   return Callee;
606*67e74705SXin Li }
607*67e74705SXin Li 
608*67e74705SXin Li /// Compute an l-value by applying the given pointer-to-member to a
609*67e74705SXin Li /// base object.
EmitMemberDataPointerAddress(CodeGenFunction & CGF,const Expr * E,Address Base,llvm::Value * MemPtr,const MemberPointerType * MPT)610*67e74705SXin Li llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
611*67e74705SXin Li     CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
612*67e74705SXin Li     const MemberPointerType *MPT) {
613*67e74705SXin Li   assert(MemPtr->getType() == CGM.PtrDiffTy);
614*67e74705SXin Li 
615*67e74705SXin Li   CGBuilderTy &Builder = CGF.Builder;
616*67e74705SXin Li 
617*67e74705SXin Li   // Cast to char*.
618*67e74705SXin Li   Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
619*67e74705SXin Li 
620*67e74705SXin Li   // Apply the offset, which we assume is non-null.
621*67e74705SXin Li   llvm::Value *Addr =
622*67e74705SXin Li     Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
623*67e74705SXin Li 
624*67e74705SXin Li   // Cast the address to the appropriate pointer type, adopting the
625*67e74705SXin Li   // address space of the base pointer.
626*67e74705SXin Li   llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
627*67e74705SXin Li                             ->getPointerTo(Base.getAddressSpace());
628*67e74705SXin Li   return Builder.CreateBitCast(Addr, PType);
629*67e74705SXin Li }
630*67e74705SXin Li 
631*67e74705SXin Li /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
632*67e74705SXin Li /// conversion.
633*67e74705SXin Li ///
634*67e74705SXin Li /// Bitcast conversions are always a no-op under Itanium.
635*67e74705SXin Li ///
636*67e74705SXin Li /// Obligatory offset/adjustment diagram:
637*67e74705SXin Li ///         <-- offset -->          <-- adjustment -->
638*67e74705SXin Li ///   |--------------------------|----------------------|--------------------|
639*67e74705SXin Li ///   ^Derived address point     ^Base address point    ^Member address point
640*67e74705SXin Li ///
641*67e74705SXin Li /// So when converting a base member pointer to a derived member pointer,
642*67e74705SXin Li /// we add the offset to the adjustment because the address point has
643*67e74705SXin Li /// decreased;  and conversely, when converting a derived MP to a base MP
644*67e74705SXin Li /// we subtract the offset from the adjustment because the address point
645*67e74705SXin Li /// has increased.
646*67e74705SXin Li ///
647*67e74705SXin Li /// The standard forbids (at compile time) conversion to and from
648*67e74705SXin Li /// virtual bases, which is why we don't have to consider them here.
649*67e74705SXin Li ///
650*67e74705SXin Li /// The standard forbids (at run time) casting a derived MP to a base
651*67e74705SXin Li /// MP when the derived MP does not point to a member of the base.
652*67e74705SXin Li /// This is why -1 is a reasonable choice for null data member
653*67e74705SXin Li /// pointers.
654*67e74705SXin Li llvm::Value *
EmitMemberPointerConversion(CodeGenFunction & CGF,const CastExpr * E,llvm::Value * src)655*67e74705SXin Li ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
656*67e74705SXin Li                                            const CastExpr *E,
657*67e74705SXin Li                                            llvm::Value *src) {
658*67e74705SXin Li   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
659*67e74705SXin Li          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
660*67e74705SXin Li          E->getCastKind() == CK_ReinterpretMemberPointer);
661*67e74705SXin Li 
662*67e74705SXin Li   // Under Itanium, reinterprets don't require any additional processing.
663*67e74705SXin Li   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
664*67e74705SXin Li 
665*67e74705SXin Li   // Use constant emission if we can.
666*67e74705SXin Li   if (isa<llvm::Constant>(src))
667*67e74705SXin Li     return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
668*67e74705SXin Li 
669*67e74705SXin Li   llvm::Constant *adj = getMemberPointerAdjustment(E);
670*67e74705SXin Li   if (!adj) return src;
671*67e74705SXin Li 
672*67e74705SXin Li   CGBuilderTy &Builder = CGF.Builder;
673*67e74705SXin Li   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
674*67e74705SXin Li 
675*67e74705SXin Li   const MemberPointerType *destTy =
676*67e74705SXin Li     E->getType()->castAs<MemberPointerType>();
677*67e74705SXin Li 
678*67e74705SXin Li   // For member data pointers, this is just a matter of adding the
679*67e74705SXin Li   // offset if the source is non-null.
680*67e74705SXin Li   if (destTy->isMemberDataPointer()) {
681*67e74705SXin Li     llvm::Value *dst;
682*67e74705SXin Li     if (isDerivedToBase)
683*67e74705SXin Li       dst = Builder.CreateNSWSub(src, adj, "adj");
684*67e74705SXin Li     else
685*67e74705SXin Li       dst = Builder.CreateNSWAdd(src, adj, "adj");
686*67e74705SXin Li 
687*67e74705SXin Li     // Null check.
688*67e74705SXin Li     llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
689*67e74705SXin Li     llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
690*67e74705SXin Li     return Builder.CreateSelect(isNull, src, dst);
691*67e74705SXin Li   }
692*67e74705SXin Li 
693*67e74705SXin Li   // The this-adjustment is left-shifted by 1 on ARM.
694*67e74705SXin Li   if (UseARMMethodPtrABI) {
695*67e74705SXin Li     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
696*67e74705SXin Li     offset <<= 1;
697*67e74705SXin Li     adj = llvm::ConstantInt::get(adj->getType(), offset);
698*67e74705SXin Li   }
699*67e74705SXin Li 
700*67e74705SXin Li   llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
701*67e74705SXin Li   llvm::Value *dstAdj;
702*67e74705SXin Li   if (isDerivedToBase)
703*67e74705SXin Li     dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
704*67e74705SXin Li   else
705*67e74705SXin Li     dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
706*67e74705SXin Li 
707*67e74705SXin Li   return Builder.CreateInsertValue(src, dstAdj, 1);
708*67e74705SXin Li }
709*67e74705SXin Li 
710*67e74705SXin Li llvm::Constant *
EmitMemberPointerConversion(const CastExpr * E,llvm::Constant * src)711*67e74705SXin Li ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
712*67e74705SXin Li                                            llvm::Constant *src) {
713*67e74705SXin Li   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
714*67e74705SXin Li          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
715*67e74705SXin Li          E->getCastKind() == CK_ReinterpretMemberPointer);
716*67e74705SXin Li 
717*67e74705SXin Li   // Under Itanium, reinterprets don't require any additional processing.
718*67e74705SXin Li   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
719*67e74705SXin Li 
720*67e74705SXin Li   // If the adjustment is trivial, we don't need to do anything.
721*67e74705SXin Li   llvm::Constant *adj = getMemberPointerAdjustment(E);
722*67e74705SXin Li   if (!adj) return src;
723*67e74705SXin Li 
724*67e74705SXin Li   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
725*67e74705SXin Li 
726*67e74705SXin Li   const MemberPointerType *destTy =
727*67e74705SXin Li     E->getType()->castAs<MemberPointerType>();
728*67e74705SXin Li 
729*67e74705SXin Li   // For member data pointers, this is just a matter of adding the
730*67e74705SXin Li   // offset if the source is non-null.
731*67e74705SXin Li   if (destTy->isMemberDataPointer()) {
732*67e74705SXin Li     // null maps to null.
733*67e74705SXin Li     if (src->isAllOnesValue()) return src;
734*67e74705SXin Li 
735*67e74705SXin Li     if (isDerivedToBase)
736*67e74705SXin Li       return llvm::ConstantExpr::getNSWSub(src, adj);
737*67e74705SXin Li     else
738*67e74705SXin Li       return llvm::ConstantExpr::getNSWAdd(src, adj);
739*67e74705SXin Li   }
740*67e74705SXin Li 
741*67e74705SXin Li   // The this-adjustment is left-shifted by 1 on ARM.
742*67e74705SXin Li   if (UseARMMethodPtrABI) {
743*67e74705SXin Li     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
744*67e74705SXin Li     offset <<= 1;
745*67e74705SXin Li     adj = llvm::ConstantInt::get(adj->getType(), offset);
746*67e74705SXin Li   }
747*67e74705SXin Li 
748*67e74705SXin Li   llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
749*67e74705SXin Li   llvm::Constant *dstAdj;
750*67e74705SXin Li   if (isDerivedToBase)
751*67e74705SXin Li     dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
752*67e74705SXin Li   else
753*67e74705SXin Li     dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
754*67e74705SXin Li 
755*67e74705SXin Li   return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
756*67e74705SXin Li }
757*67e74705SXin Li 
758*67e74705SXin Li llvm::Constant *
EmitNullMemberPointer(const MemberPointerType * MPT)759*67e74705SXin Li ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
760*67e74705SXin Li   // Itanium C++ ABI 2.3:
761*67e74705SXin Li   //   A NULL pointer is represented as -1.
762*67e74705SXin Li   if (MPT->isMemberDataPointer())
763*67e74705SXin Li     return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
764*67e74705SXin Li 
765*67e74705SXin Li   llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
766*67e74705SXin Li   llvm::Constant *Values[2] = { Zero, Zero };
767*67e74705SXin Li   return llvm::ConstantStruct::getAnon(Values);
768*67e74705SXin Li }
769*67e74705SXin Li 
770*67e74705SXin Li llvm::Constant *
EmitMemberDataPointer(const MemberPointerType * MPT,CharUnits offset)771*67e74705SXin Li ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
772*67e74705SXin Li                                      CharUnits offset) {
773*67e74705SXin Li   // Itanium C++ ABI 2.3:
774*67e74705SXin Li   //   A pointer to data member is an offset from the base address of
775*67e74705SXin Li   //   the class object containing it, represented as a ptrdiff_t
776*67e74705SXin Li   return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
777*67e74705SXin Li }
778*67e74705SXin Li 
779*67e74705SXin Li llvm::Constant *
EmitMemberFunctionPointer(const CXXMethodDecl * MD)780*67e74705SXin Li ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
781*67e74705SXin Li   return BuildMemberPointer(MD, CharUnits::Zero());
782*67e74705SXin Li }
783*67e74705SXin Li 
BuildMemberPointer(const CXXMethodDecl * MD,CharUnits ThisAdjustment)784*67e74705SXin Li llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
785*67e74705SXin Li                                                   CharUnits ThisAdjustment) {
786*67e74705SXin Li   assert(MD->isInstance() && "Member function must not be static!");
787*67e74705SXin Li   MD = MD->getCanonicalDecl();
788*67e74705SXin Li 
789*67e74705SXin Li   CodeGenTypes &Types = CGM.getTypes();
790*67e74705SXin Li 
791*67e74705SXin Li   // Get the function pointer (or index if this is a virtual function).
792*67e74705SXin Li   llvm::Constant *MemPtr[2];
793*67e74705SXin Li   if (MD->isVirtual()) {
794*67e74705SXin Li     uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
795*67e74705SXin Li 
796*67e74705SXin Li     const ASTContext &Context = getContext();
797*67e74705SXin Li     CharUnits PointerWidth =
798*67e74705SXin Li       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
799*67e74705SXin Li     uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
800*67e74705SXin Li 
801*67e74705SXin Li     if (UseARMMethodPtrABI) {
802*67e74705SXin Li       // ARM C++ ABI 3.2.1:
803*67e74705SXin Li       //   This ABI specifies that adj contains twice the this
804*67e74705SXin Li       //   adjustment, plus 1 if the member function is virtual. The
805*67e74705SXin Li       //   least significant bit of adj then makes exactly the same
806*67e74705SXin Li       //   discrimination as the least significant bit of ptr does for
807*67e74705SXin Li       //   Itanium.
808*67e74705SXin Li       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
809*67e74705SXin Li       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
810*67e74705SXin Li                                          2 * ThisAdjustment.getQuantity() + 1);
811*67e74705SXin Li     } else {
812*67e74705SXin Li       // Itanium C++ ABI 2.3:
813*67e74705SXin Li       //   For a virtual function, [the pointer field] is 1 plus the
814*67e74705SXin Li       //   virtual table offset (in bytes) of the function,
815*67e74705SXin Li       //   represented as a ptrdiff_t.
816*67e74705SXin Li       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
817*67e74705SXin Li       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
818*67e74705SXin Li                                          ThisAdjustment.getQuantity());
819*67e74705SXin Li     }
820*67e74705SXin Li   } else {
821*67e74705SXin Li     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
822*67e74705SXin Li     llvm::Type *Ty;
823*67e74705SXin Li     // Check whether the function has a computable LLVM signature.
824*67e74705SXin Li     if (Types.isFuncTypeConvertible(FPT)) {
825*67e74705SXin Li       // The function has a computable LLVM signature; use the correct type.
826*67e74705SXin Li       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
827*67e74705SXin Li     } else {
828*67e74705SXin Li       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
829*67e74705SXin Li       // function type is incomplete.
830*67e74705SXin Li       Ty = CGM.PtrDiffTy;
831*67e74705SXin Li     }
832*67e74705SXin Li     llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
833*67e74705SXin Li 
834*67e74705SXin Li     MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
835*67e74705SXin Li     MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
836*67e74705SXin Li                                        (UseARMMethodPtrABI ? 2 : 1) *
837*67e74705SXin Li                                        ThisAdjustment.getQuantity());
838*67e74705SXin Li   }
839*67e74705SXin Li 
840*67e74705SXin Li   return llvm::ConstantStruct::getAnon(MemPtr);
841*67e74705SXin Li }
842*67e74705SXin Li 
EmitMemberPointer(const APValue & MP,QualType MPType)843*67e74705SXin Li llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
844*67e74705SXin Li                                                  QualType MPType) {
845*67e74705SXin Li   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
846*67e74705SXin Li   const ValueDecl *MPD = MP.getMemberPointerDecl();
847*67e74705SXin Li   if (!MPD)
848*67e74705SXin Li     return EmitNullMemberPointer(MPT);
849*67e74705SXin Li 
850*67e74705SXin Li   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
851*67e74705SXin Li 
852*67e74705SXin Li   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
853*67e74705SXin Li     return BuildMemberPointer(MD, ThisAdjustment);
854*67e74705SXin Li 
855*67e74705SXin Li   CharUnits FieldOffset =
856*67e74705SXin Li     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
857*67e74705SXin Li   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
858*67e74705SXin Li }
859*67e74705SXin Li 
860*67e74705SXin Li /// The comparison algorithm is pretty easy: the member pointers are
861*67e74705SXin Li /// the same if they're either bitwise identical *or* both null.
862*67e74705SXin Li ///
863*67e74705SXin Li /// ARM is different here only because null-ness is more complicated.
864*67e74705SXin Li llvm::Value *
EmitMemberPointerComparison(CodeGenFunction & CGF,llvm::Value * L,llvm::Value * R,const MemberPointerType * MPT,bool Inequality)865*67e74705SXin Li ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
866*67e74705SXin Li                                            llvm::Value *L,
867*67e74705SXin Li                                            llvm::Value *R,
868*67e74705SXin Li                                            const MemberPointerType *MPT,
869*67e74705SXin Li                                            bool Inequality) {
870*67e74705SXin Li   CGBuilderTy &Builder = CGF.Builder;
871*67e74705SXin Li 
872*67e74705SXin Li   llvm::ICmpInst::Predicate Eq;
873*67e74705SXin Li   llvm::Instruction::BinaryOps And, Or;
874*67e74705SXin Li   if (Inequality) {
875*67e74705SXin Li     Eq = llvm::ICmpInst::ICMP_NE;
876*67e74705SXin Li     And = llvm::Instruction::Or;
877*67e74705SXin Li     Or = llvm::Instruction::And;
878*67e74705SXin Li   } else {
879*67e74705SXin Li     Eq = llvm::ICmpInst::ICMP_EQ;
880*67e74705SXin Li     And = llvm::Instruction::And;
881*67e74705SXin Li     Or = llvm::Instruction::Or;
882*67e74705SXin Li   }
883*67e74705SXin Li 
884*67e74705SXin Li   // Member data pointers are easy because there's a unique null
885*67e74705SXin Li   // value, so it just comes down to bitwise equality.
886*67e74705SXin Li   if (MPT->isMemberDataPointer())
887*67e74705SXin Li     return Builder.CreateICmp(Eq, L, R);
888*67e74705SXin Li 
889*67e74705SXin Li   // For member function pointers, the tautologies are more complex.
890*67e74705SXin Li   // The Itanium tautology is:
891*67e74705SXin Li   //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
892*67e74705SXin Li   // The ARM tautology is:
893*67e74705SXin Li   //   (L == R) <==> (L.ptr == R.ptr &&
894*67e74705SXin Li   //                  (L.adj == R.adj ||
895*67e74705SXin Li   //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
896*67e74705SXin Li   // The inequality tautologies have exactly the same structure, except
897*67e74705SXin Li   // applying De Morgan's laws.
898*67e74705SXin Li 
899*67e74705SXin Li   llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
900*67e74705SXin Li   llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
901*67e74705SXin Li 
902*67e74705SXin Li   // This condition tests whether L.ptr == R.ptr.  This must always be
903*67e74705SXin Li   // true for equality to hold.
904*67e74705SXin Li   llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
905*67e74705SXin Li 
906*67e74705SXin Li   // This condition, together with the assumption that L.ptr == R.ptr,
907*67e74705SXin Li   // tests whether the pointers are both null.  ARM imposes an extra
908*67e74705SXin Li   // condition.
909*67e74705SXin Li   llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
910*67e74705SXin Li   llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
911*67e74705SXin Li 
912*67e74705SXin Li   // This condition tests whether L.adj == R.adj.  If this isn't
913*67e74705SXin Li   // true, the pointers are unequal unless they're both null.
914*67e74705SXin Li   llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
915*67e74705SXin Li   llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
916*67e74705SXin Li   llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
917*67e74705SXin Li 
918*67e74705SXin Li   // Null member function pointers on ARM clear the low bit of Adj,
919*67e74705SXin Li   // so the zero condition has to check that neither low bit is set.
920*67e74705SXin Li   if (UseARMMethodPtrABI) {
921*67e74705SXin Li     llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
922*67e74705SXin Li 
923*67e74705SXin Li     // Compute (l.adj | r.adj) & 1 and test it against zero.
924*67e74705SXin Li     llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
925*67e74705SXin Li     llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
926*67e74705SXin Li     llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
927*67e74705SXin Li                                                       "cmp.or.adj");
928*67e74705SXin Li     EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
929*67e74705SXin Li   }
930*67e74705SXin Li 
931*67e74705SXin Li   // Tie together all our conditions.
932*67e74705SXin Li   llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
933*67e74705SXin Li   Result = Builder.CreateBinOp(And, PtrEq, Result,
934*67e74705SXin Li                                Inequality ? "memptr.ne" : "memptr.eq");
935*67e74705SXin Li   return Result;
936*67e74705SXin Li }
937*67e74705SXin Li 
938*67e74705SXin Li llvm::Value *
EmitMemberPointerIsNotNull(CodeGenFunction & CGF,llvm::Value * MemPtr,const MemberPointerType * MPT)939*67e74705SXin Li ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
940*67e74705SXin Li                                           llvm::Value *MemPtr,
941*67e74705SXin Li                                           const MemberPointerType *MPT) {
942*67e74705SXin Li   CGBuilderTy &Builder = CGF.Builder;
943*67e74705SXin Li 
944*67e74705SXin Li   /// For member data pointers, this is just a check against -1.
945*67e74705SXin Li   if (MPT->isMemberDataPointer()) {
946*67e74705SXin Li     assert(MemPtr->getType() == CGM.PtrDiffTy);
947*67e74705SXin Li     llvm::Value *NegativeOne =
948*67e74705SXin Li       llvm::Constant::getAllOnesValue(MemPtr->getType());
949*67e74705SXin Li     return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
950*67e74705SXin Li   }
951*67e74705SXin Li 
952*67e74705SXin Li   // In Itanium, a member function pointer is not null if 'ptr' is not null.
953*67e74705SXin Li   llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
954*67e74705SXin Li 
955*67e74705SXin Li   llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
956*67e74705SXin Li   llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
957*67e74705SXin Li 
958*67e74705SXin Li   // On ARM, a member function pointer is also non-null if the low bit of 'adj'
959*67e74705SXin Li   // (the virtual bit) is set.
960*67e74705SXin Li   if (UseARMMethodPtrABI) {
961*67e74705SXin Li     llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
962*67e74705SXin Li     llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
963*67e74705SXin Li     llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
964*67e74705SXin Li     llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
965*67e74705SXin Li                                                   "memptr.isvirtual");
966*67e74705SXin Li     Result = Builder.CreateOr(Result, IsVirtual);
967*67e74705SXin Li   }
968*67e74705SXin Li 
969*67e74705SXin Li   return Result;
970*67e74705SXin Li }
971*67e74705SXin Li 
classifyReturnType(CGFunctionInfo & FI) const972*67e74705SXin Li bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
973*67e74705SXin Li   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
974*67e74705SXin Li   if (!RD)
975*67e74705SXin Li     return false;
976*67e74705SXin Li 
977*67e74705SXin Li   // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
978*67e74705SXin Li   // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
979*67e74705SXin Li   // special members.
980*67e74705SXin Li   if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
981*67e74705SXin Li     auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
982*67e74705SXin Li     FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
983*67e74705SXin Li     return true;
984*67e74705SXin Li   }
985*67e74705SXin Li   return false;
986*67e74705SXin Li }
987*67e74705SXin Li 
988*67e74705SXin Li /// The Itanium ABI requires non-zero initialization only for data
989*67e74705SXin Li /// member pointers, for which '0' is a valid offset.
isZeroInitializable(const MemberPointerType * MPT)990*67e74705SXin Li bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
991*67e74705SXin Li   return MPT->isMemberFunctionPointer();
992*67e74705SXin Li }
993*67e74705SXin Li 
994*67e74705SXin Li /// The Itanium ABI always places an offset to the complete object
995*67e74705SXin Li /// at entry -2 in the vtable.
emitVirtualObjectDelete(CodeGenFunction & CGF,const CXXDeleteExpr * DE,Address Ptr,QualType ElementType,const CXXDestructorDecl * Dtor)996*67e74705SXin Li void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
997*67e74705SXin Li                                             const CXXDeleteExpr *DE,
998*67e74705SXin Li                                             Address Ptr,
999*67e74705SXin Li                                             QualType ElementType,
1000*67e74705SXin Li                                             const CXXDestructorDecl *Dtor) {
1001*67e74705SXin Li   bool UseGlobalDelete = DE->isGlobalDelete();
1002*67e74705SXin Li   if (UseGlobalDelete) {
1003*67e74705SXin Li     // Derive the complete-object pointer, which is what we need
1004*67e74705SXin Li     // to pass to the deallocation function.
1005*67e74705SXin Li 
1006*67e74705SXin Li     // Grab the vtable pointer as an intptr_t*.
1007*67e74705SXin Li     auto *ClassDecl =
1008*67e74705SXin Li         cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1009*67e74705SXin Li     llvm::Value *VTable =
1010*67e74705SXin Li         CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
1011*67e74705SXin Li 
1012*67e74705SXin Li     // Track back to entry -2 and pull out the offset there.
1013*67e74705SXin Li     llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1014*67e74705SXin Li         VTable, -2, "complete-offset.ptr");
1015*67e74705SXin Li     llvm::Value *Offset =
1016*67e74705SXin Li       CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
1017*67e74705SXin Li 
1018*67e74705SXin Li     // Apply the offset.
1019*67e74705SXin Li     llvm::Value *CompletePtr =
1020*67e74705SXin Li       CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
1021*67e74705SXin Li     CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1022*67e74705SXin Li 
1023*67e74705SXin Li     // If we're supposed to call the global delete, make sure we do so
1024*67e74705SXin Li     // even if the destructor throws.
1025*67e74705SXin Li     CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1026*67e74705SXin Li                                     ElementType);
1027*67e74705SXin Li   }
1028*67e74705SXin Li 
1029*67e74705SXin Li   // FIXME: Provide a source location here even though there's no
1030*67e74705SXin Li   // CXXMemberCallExpr for dtor call.
1031*67e74705SXin Li   CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1032*67e74705SXin Li   EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1033*67e74705SXin Li 
1034*67e74705SXin Li   if (UseGlobalDelete)
1035*67e74705SXin Li     CGF.PopCleanupBlock();
1036*67e74705SXin Li }
1037*67e74705SXin Li 
emitRethrow(CodeGenFunction & CGF,bool isNoReturn)1038*67e74705SXin Li void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1039*67e74705SXin Li   // void __cxa_rethrow();
1040*67e74705SXin Li 
1041*67e74705SXin Li   llvm::FunctionType *FTy =
1042*67e74705SXin Li     llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1043*67e74705SXin Li 
1044*67e74705SXin Li   llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1045*67e74705SXin Li 
1046*67e74705SXin Li   if (isNoReturn)
1047*67e74705SXin Li     CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1048*67e74705SXin Li   else
1049*67e74705SXin Li     CGF.EmitRuntimeCallOrInvoke(Fn);
1050*67e74705SXin Li }
1051*67e74705SXin Li 
getAllocateExceptionFn(CodeGenModule & CGM)1052*67e74705SXin Li static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1053*67e74705SXin Li   // void *__cxa_allocate_exception(size_t thrown_size);
1054*67e74705SXin Li 
1055*67e74705SXin Li   llvm::FunctionType *FTy =
1056*67e74705SXin Li     llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1057*67e74705SXin Li 
1058*67e74705SXin Li   return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1059*67e74705SXin Li }
1060*67e74705SXin Li 
getThrowFn(CodeGenModule & CGM)1061*67e74705SXin Li static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1062*67e74705SXin Li   // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1063*67e74705SXin Li   //                  void (*dest) (void *));
1064*67e74705SXin Li 
1065*67e74705SXin Li   llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1066*67e74705SXin Li   llvm::FunctionType *FTy =
1067*67e74705SXin Li     llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1068*67e74705SXin Li 
1069*67e74705SXin Li   return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1070*67e74705SXin Li }
1071*67e74705SXin Li 
emitThrow(CodeGenFunction & CGF,const CXXThrowExpr * E)1072*67e74705SXin Li void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1073*67e74705SXin Li   QualType ThrowType = E->getSubExpr()->getType();
1074*67e74705SXin Li   // Now allocate the exception object.
1075*67e74705SXin Li   llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1076*67e74705SXin Li   uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1077*67e74705SXin Li 
1078*67e74705SXin Li   llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1079*67e74705SXin Li   llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1080*67e74705SXin Li       AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1081*67e74705SXin Li 
1082*67e74705SXin Li   CharUnits ExnAlign = getAlignmentOfExnObject();
1083*67e74705SXin Li   CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
1084*67e74705SXin Li 
1085*67e74705SXin Li   // Now throw the exception.
1086*67e74705SXin Li   llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1087*67e74705SXin Li                                                          /*ForEH=*/true);
1088*67e74705SXin Li 
1089*67e74705SXin Li   // The address of the destructor.  If the exception type has a
1090*67e74705SXin Li   // trivial destructor (or isn't a record), we just pass null.
1091*67e74705SXin Li   llvm::Constant *Dtor = nullptr;
1092*67e74705SXin Li   if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1093*67e74705SXin Li     CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1094*67e74705SXin Li     if (!Record->hasTrivialDestructor()) {
1095*67e74705SXin Li       CXXDestructorDecl *DtorD = Record->getDestructor();
1096*67e74705SXin Li       Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1097*67e74705SXin Li       Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1098*67e74705SXin Li     }
1099*67e74705SXin Li   }
1100*67e74705SXin Li   if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1101*67e74705SXin Li 
1102*67e74705SXin Li   llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1103*67e74705SXin Li   CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1104*67e74705SXin Li }
1105*67e74705SXin Li 
getItaniumDynamicCastFn(CodeGenFunction & CGF)1106*67e74705SXin Li static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1107*67e74705SXin Li   // void *__dynamic_cast(const void *sub,
1108*67e74705SXin Li   //                      const abi::__class_type_info *src,
1109*67e74705SXin Li   //                      const abi::__class_type_info *dst,
1110*67e74705SXin Li   //                      std::ptrdiff_t src2dst_offset);
1111*67e74705SXin Li 
1112*67e74705SXin Li   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1113*67e74705SXin Li   llvm::Type *PtrDiffTy =
1114*67e74705SXin Li     CGF.ConvertType(CGF.getContext().getPointerDiffType());
1115*67e74705SXin Li 
1116*67e74705SXin Li   llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1117*67e74705SXin Li 
1118*67e74705SXin Li   llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1119*67e74705SXin Li 
1120*67e74705SXin Li   // Mark the function as nounwind readonly.
1121*67e74705SXin Li   llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1122*67e74705SXin Li                                             llvm::Attribute::ReadOnly };
1123*67e74705SXin Li   llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1124*67e74705SXin Li       CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1125*67e74705SXin Li 
1126*67e74705SXin Li   return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1127*67e74705SXin Li }
1128*67e74705SXin Li 
getBadCastFn(CodeGenFunction & CGF)1129*67e74705SXin Li static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1130*67e74705SXin Li   // void __cxa_bad_cast();
1131*67e74705SXin Li   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1132*67e74705SXin Li   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1133*67e74705SXin Li }
1134*67e74705SXin Li 
1135*67e74705SXin Li /// \brief Compute the src2dst_offset hint as described in the
1136*67e74705SXin Li /// Itanium C++ ABI [2.9.7]
computeOffsetHint(ASTContext & Context,const CXXRecordDecl * Src,const CXXRecordDecl * Dst)1137*67e74705SXin Li static CharUnits computeOffsetHint(ASTContext &Context,
1138*67e74705SXin Li                                    const CXXRecordDecl *Src,
1139*67e74705SXin Li                                    const CXXRecordDecl *Dst) {
1140*67e74705SXin Li   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1141*67e74705SXin Li                      /*DetectVirtual=*/false);
1142*67e74705SXin Li 
1143*67e74705SXin Li   // If Dst is not derived from Src we can skip the whole computation below and
1144*67e74705SXin Li   // return that Src is not a public base of Dst.  Record all inheritance paths.
1145*67e74705SXin Li   if (!Dst->isDerivedFrom(Src, Paths))
1146*67e74705SXin Li     return CharUnits::fromQuantity(-2ULL);
1147*67e74705SXin Li 
1148*67e74705SXin Li   unsigned NumPublicPaths = 0;
1149*67e74705SXin Li   CharUnits Offset;
1150*67e74705SXin Li 
1151*67e74705SXin Li   // Now walk all possible inheritance paths.
1152*67e74705SXin Li   for (const CXXBasePath &Path : Paths) {
1153*67e74705SXin Li     if (Path.Access != AS_public)  // Ignore non-public inheritance.
1154*67e74705SXin Li       continue;
1155*67e74705SXin Li 
1156*67e74705SXin Li     ++NumPublicPaths;
1157*67e74705SXin Li 
1158*67e74705SXin Li     for (const CXXBasePathElement &PathElement : Path) {
1159*67e74705SXin Li       // If the path contains a virtual base class we can't give any hint.
1160*67e74705SXin Li       // -1: no hint.
1161*67e74705SXin Li       if (PathElement.Base->isVirtual())
1162*67e74705SXin Li         return CharUnits::fromQuantity(-1ULL);
1163*67e74705SXin Li 
1164*67e74705SXin Li       if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1165*67e74705SXin Li         continue;
1166*67e74705SXin Li 
1167*67e74705SXin Li       // Accumulate the base class offsets.
1168*67e74705SXin Li       const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1169*67e74705SXin Li       Offset += L.getBaseClassOffset(
1170*67e74705SXin Li           PathElement.Base->getType()->getAsCXXRecordDecl());
1171*67e74705SXin Li     }
1172*67e74705SXin Li   }
1173*67e74705SXin Li 
1174*67e74705SXin Li   // -2: Src is not a public base of Dst.
1175*67e74705SXin Li   if (NumPublicPaths == 0)
1176*67e74705SXin Li     return CharUnits::fromQuantity(-2ULL);
1177*67e74705SXin Li 
1178*67e74705SXin Li   // -3: Src is a multiple public base type but never a virtual base type.
1179*67e74705SXin Li   if (NumPublicPaths > 1)
1180*67e74705SXin Li     return CharUnits::fromQuantity(-3ULL);
1181*67e74705SXin Li 
1182*67e74705SXin Li   // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1183*67e74705SXin Li   // Return the offset of Src from the origin of Dst.
1184*67e74705SXin Li   return Offset;
1185*67e74705SXin Li }
1186*67e74705SXin Li 
getBadTypeidFn(CodeGenFunction & CGF)1187*67e74705SXin Li static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1188*67e74705SXin Li   // void __cxa_bad_typeid();
1189*67e74705SXin Li   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1190*67e74705SXin Li 
1191*67e74705SXin Li   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1192*67e74705SXin Li }
1193*67e74705SXin Li 
shouldTypeidBeNullChecked(bool IsDeref,QualType SrcRecordTy)1194*67e74705SXin Li bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1195*67e74705SXin Li                                               QualType SrcRecordTy) {
1196*67e74705SXin Li   return IsDeref;
1197*67e74705SXin Li }
1198*67e74705SXin Li 
EmitBadTypeidCall(CodeGenFunction & CGF)1199*67e74705SXin Li void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1200*67e74705SXin Li   llvm::Value *Fn = getBadTypeidFn(CGF);
1201*67e74705SXin Li   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1202*67e74705SXin Li   CGF.Builder.CreateUnreachable();
1203*67e74705SXin Li }
1204*67e74705SXin Li 
EmitTypeid(CodeGenFunction & CGF,QualType SrcRecordTy,Address ThisPtr,llvm::Type * StdTypeInfoPtrTy)1205*67e74705SXin Li llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1206*67e74705SXin Li                                        QualType SrcRecordTy,
1207*67e74705SXin Li                                        Address ThisPtr,
1208*67e74705SXin Li                                        llvm::Type *StdTypeInfoPtrTy) {
1209*67e74705SXin Li   auto *ClassDecl =
1210*67e74705SXin Li       cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
1211*67e74705SXin Li   llvm::Value *Value =
1212*67e74705SXin Li       CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
1213*67e74705SXin Li 
1214*67e74705SXin Li   // Load the type info.
1215*67e74705SXin Li   Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1216*67e74705SXin Li   return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
1217*67e74705SXin Li }
1218*67e74705SXin Li 
shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,QualType SrcRecordTy)1219*67e74705SXin Li bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1220*67e74705SXin Li                                                        QualType SrcRecordTy) {
1221*67e74705SXin Li   return SrcIsPtr;
1222*67e74705SXin Li }
1223*67e74705SXin Li 
EmitDynamicCastCall(CodeGenFunction & CGF,Address ThisAddr,QualType SrcRecordTy,QualType DestTy,QualType DestRecordTy,llvm::BasicBlock * CastEnd)1224*67e74705SXin Li llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1225*67e74705SXin Li     CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1226*67e74705SXin Li     QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1227*67e74705SXin Li   llvm::Type *PtrDiffLTy =
1228*67e74705SXin Li       CGF.ConvertType(CGF.getContext().getPointerDiffType());
1229*67e74705SXin Li   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1230*67e74705SXin Li 
1231*67e74705SXin Li   llvm::Value *SrcRTTI =
1232*67e74705SXin Li       CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1233*67e74705SXin Li   llvm::Value *DestRTTI =
1234*67e74705SXin Li       CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1235*67e74705SXin Li 
1236*67e74705SXin Li   // Compute the offset hint.
1237*67e74705SXin Li   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1238*67e74705SXin Li   const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1239*67e74705SXin Li   llvm::Value *OffsetHint = llvm::ConstantInt::get(
1240*67e74705SXin Li       PtrDiffLTy,
1241*67e74705SXin Li       computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1242*67e74705SXin Li 
1243*67e74705SXin Li   // Emit the call to __dynamic_cast.
1244*67e74705SXin Li   llvm::Value *Value = ThisAddr.getPointer();
1245*67e74705SXin Li   Value = CGF.EmitCastToVoidPtr(Value);
1246*67e74705SXin Li 
1247*67e74705SXin Li   llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1248*67e74705SXin Li   Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1249*67e74705SXin Li   Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1250*67e74705SXin Li 
1251*67e74705SXin Li   /// C++ [expr.dynamic.cast]p9:
1252*67e74705SXin Li   ///   A failed cast to reference type throws std::bad_cast
1253*67e74705SXin Li   if (DestTy->isReferenceType()) {
1254*67e74705SXin Li     llvm::BasicBlock *BadCastBlock =
1255*67e74705SXin Li         CGF.createBasicBlock("dynamic_cast.bad_cast");
1256*67e74705SXin Li 
1257*67e74705SXin Li     llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1258*67e74705SXin Li     CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1259*67e74705SXin Li 
1260*67e74705SXin Li     CGF.EmitBlock(BadCastBlock);
1261*67e74705SXin Li     EmitBadCastCall(CGF);
1262*67e74705SXin Li   }
1263*67e74705SXin Li 
1264*67e74705SXin Li   return Value;
1265*67e74705SXin Li }
1266*67e74705SXin Li 
EmitDynamicCastToVoid(CodeGenFunction & CGF,Address ThisAddr,QualType SrcRecordTy,QualType DestTy)1267*67e74705SXin Li llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1268*67e74705SXin Li                                                   Address ThisAddr,
1269*67e74705SXin Li                                                   QualType SrcRecordTy,
1270*67e74705SXin Li                                                   QualType DestTy) {
1271*67e74705SXin Li   llvm::Type *PtrDiffLTy =
1272*67e74705SXin Li       CGF.ConvertType(CGF.getContext().getPointerDiffType());
1273*67e74705SXin Li   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1274*67e74705SXin Li 
1275*67e74705SXin Li   auto *ClassDecl =
1276*67e74705SXin Li       cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
1277*67e74705SXin Li   // Get the vtable pointer.
1278*67e74705SXin Li   llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1279*67e74705SXin Li       ClassDecl);
1280*67e74705SXin Li 
1281*67e74705SXin Li   // Get the offset-to-top from the vtable.
1282*67e74705SXin Li   llvm::Value *OffsetToTop =
1283*67e74705SXin Li       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1284*67e74705SXin Li   OffsetToTop =
1285*67e74705SXin Li     CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1286*67e74705SXin Li                                   "offset.to.top");
1287*67e74705SXin Li 
1288*67e74705SXin Li   // Finally, add the offset to the pointer.
1289*67e74705SXin Li   llvm::Value *Value = ThisAddr.getPointer();
1290*67e74705SXin Li   Value = CGF.EmitCastToVoidPtr(Value);
1291*67e74705SXin Li   Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1292*67e74705SXin Li 
1293*67e74705SXin Li   return CGF.Builder.CreateBitCast(Value, DestLTy);
1294*67e74705SXin Li }
1295*67e74705SXin Li 
EmitBadCastCall(CodeGenFunction & CGF)1296*67e74705SXin Li bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1297*67e74705SXin Li   llvm::Value *Fn = getBadCastFn(CGF);
1298*67e74705SXin Li   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1299*67e74705SXin Li   CGF.Builder.CreateUnreachable();
1300*67e74705SXin Li   return true;
1301*67e74705SXin Li }
1302*67e74705SXin Li 
1303*67e74705SXin Li llvm::Value *
GetVirtualBaseClassOffset(CodeGenFunction & CGF,Address This,const CXXRecordDecl * ClassDecl,const CXXRecordDecl * BaseClassDecl)1304*67e74705SXin Li ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1305*67e74705SXin Li                                          Address This,
1306*67e74705SXin Li                                          const CXXRecordDecl *ClassDecl,
1307*67e74705SXin Li                                          const CXXRecordDecl *BaseClassDecl) {
1308*67e74705SXin Li   llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
1309*67e74705SXin Li   CharUnits VBaseOffsetOffset =
1310*67e74705SXin Li       CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1311*67e74705SXin Li                                                                BaseClassDecl);
1312*67e74705SXin Li 
1313*67e74705SXin Li   llvm::Value *VBaseOffsetPtr =
1314*67e74705SXin Li     CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1315*67e74705SXin Li                                    "vbase.offset.ptr");
1316*67e74705SXin Li   VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1317*67e74705SXin Li                                              CGM.PtrDiffTy->getPointerTo());
1318*67e74705SXin Li 
1319*67e74705SXin Li   llvm::Value *VBaseOffset =
1320*67e74705SXin Li     CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1321*67e74705SXin Li                                   "vbase.offset");
1322*67e74705SXin Li 
1323*67e74705SXin Li   return VBaseOffset;
1324*67e74705SXin Li }
1325*67e74705SXin Li 
EmitCXXConstructors(const CXXConstructorDecl * D)1326*67e74705SXin Li void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1327*67e74705SXin Li   // Just make sure we're in sync with TargetCXXABI.
1328*67e74705SXin Li   assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1329*67e74705SXin Li 
1330*67e74705SXin Li   // The constructor used for constructing this as a base class;
1331*67e74705SXin Li   // ignores virtual bases.
1332*67e74705SXin Li   CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1333*67e74705SXin Li 
1334*67e74705SXin Li   // The constructor used for constructing this as a complete class;
1335*67e74705SXin Li   // constructs the virtual bases, then calls the base constructor.
1336*67e74705SXin Li   if (!D->getParent()->isAbstract()) {
1337*67e74705SXin Li     // We don't need to emit the complete ctor if the class is abstract.
1338*67e74705SXin Li     CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1339*67e74705SXin Li   }
1340*67e74705SXin Li }
1341*67e74705SXin Li 
1342*67e74705SXin Li void
buildStructorSignature(const CXXMethodDecl * MD,StructorType T,SmallVectorImpl<CanQualType> & ArgTys)1343*67e74705SXin Li ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1344*67e74705SXin Li                                       SmallVectorImpl<CanQualType> &ArgTys) {
1345*67e74705SXin Li   ASTContext &Context = getContext();
1346*67e74705SXin Li 
1347*67e74705SXin Li   // All parameters are already in place except VTT, which goes after 'this'.
1348*67e74705SXin Li   // These are Clang types, so we don't need to worry about sret yet.
1349*67e74705SXin Li 
1350*67e74705SXin Li   // Check if we need to add a VTT parameter (which has type void **).
1351*67e74705SXin Li   if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1352*67e74705SXin Li     ArgTys.insert(ArgTys.begin() + 1,
1353*67e74705SXin Li                   Context.getPointerType(Context.VoidPtrTy));
1354*67e74705SXin Li }
1355*67e74705SXin Li 
EmitCXXDestructors(const CXXDestructorDecl * D)1356*67e74705SXin Li void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1357*67e74705SXin Li   // The destructor used for destructing this as a base class; ignores
1358*67e74705SXin Li   // virtual bases.
1359*67e74705SXin Li   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1360*67e74705SXin Li 
1361*67e74705SXin Li   // The destructor used for destructing this as a most-derived class;
1362*67e74705SXin Li   // call the base destructor and then destructs any virtual bases.
1363*67e74705SXin Li   CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1364*67e74705SXin Li 
1365*67e74705SXin Li   // The destructor in a virtual table is always a 'deleting'
1366*67e74705SXin Li   // destructor, which calls the complete destructor and then uses the
1367*67e74705SXin Li   // appropriate operator delete.
1368*67e74705SXin Li   if (D->isVirtual())
1369*67e74705SXin Li     CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1370*67e74705SXin Li }
1371*67e74705SXin Li 
addImplicitStructorParams(CodeGenFunction & CGF,QualType & ResTy,FunctionArgList & Params)1372*67e74705SXin Li void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1373*67e74705SXin Li                                               QualType &ResTy,
1374*67e74705SXin Li                                               FunctionArgList &Params) {
1375*67e74705SXin Li   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1376*67e74705SXin Li   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1377*67e74705SXin Li 
1378*67e74705SXin Li   // Check if we need a VTT parameter as well.
1379*67e74705SXin Li   if (NeedsVTTParameter(CGF.CurGD)) {
1380*67e74705SXin Li     ASTContext &Context = getContext();
1381*67e74705SXin Li 
1382*67e74705SXin Li     // FIXME: avoid the fake decl
1383*67e74705SXin Li     QualType T = Context.getPointerType(Context.VoidPtrTy);
1384*67e74705SXin Li     ImplicitParamDecl *VTTDecl
1385*67e74705SXin Li       = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
1386*67e74705SXin Li                                   &Context.Idents.get("vtt"), T);
1387*67e74705SXin Li     Params.insert(Params.begin() + 1, VTTDecl);
1388*67e74705SXin Li     getStructorImplicitParamDecl(CGF) = VTTDecl;
1389*67e74705SXin Li   }
1390*67e74705SXin Li }
1391*67e74705SXin Li 
EmitInstanceFunctionProlog(CodeGenFunction & CGF)1392*67e74705SXin Li void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1393*67e74705SXin Li   /// Initialize the 'this' slot.
1394*67e74705SXin Li   EmitThisParam(CGF);
1395*67e74705SXin Li 
1396*67e74705SXin Li   /// Initialize the 'vtt' slot if needed.
1397*67e74705SXin Li   if (getStructorImplicitParamDecl(CGF)) {
1398*67e74705SXin Li     getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1399*67e74705SXin Li         CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1400*67e74705SXin Li   }
1401*67e74705SXin Li 
1402*67e74705SXin Li   /// If this is a function that the ABI specifies returns 'this', initialize
1403*67e74705SXin Li   /// the return slot to 'this' at the start of the function.
1404*67e74705SXin Li   ///
1405*67e74705SXin Li   /// Unlike the setting of return types, this is done within the ABI
1406*67e74705SXin Li   /// implementation instead of by clients of CGCXXABI because:
1407*67e74705SXin Li   /// 1) getThisValue is currently protected
1408*67e74705SXin Li   /// 2) in theory, an ABI could implement 'this' returns some other way;
1409*67e74705SXin Li   ///    HasThisReturn only specifies a contract, not the implementation
1410*67e74705SXin Li   if (HasThisReturn(CGF.CurGD))
1411*67e74705SXin Li     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1412*67e74705SXin Li }
1413*67e74705SXin Li 
addImplicitConstructorArgs(CodeGenFunction & CGF,const CXXConstructorDecl * D,CXXCtorType Type,bool ForVirtualBase,bool Delegating,CallArgList & Args)1414*67e74705SXin Li unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1415*67e74705SXin Li     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1416*67e74705SXin Li     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1417*67e74705SXin Li   if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1418*67e74705SXin Li     return 0;
1419*67e74705SXin Li 
1420*67e74705SXin Li   // Insert the implicit 'vtt' argument as the second argument.
1421*67e74705SXin Li   llvm::Value *VTT =
1422*67e74705SXin Li       CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1423*67e74705SXin Li   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1424*67e74705SXin Li   Args.insert(Args.begin() + 1,
1425*67e74705SXin Li               CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1426*67e74705SXin Li   return 1;  // Added one arg.
1427*67e74705SXin Li }
1428*67e74705SXin Li 
EmitDestructorCall(CodeGenFunction & CGF,const CXXDestructorDecl * DD,CXXDtorType Type,bool ForVirtualBase,bool Delegating,Address This)1429*67e74705SXin Li void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1430*67e74705SXin Li                                        const CXXDestructorDecl *DD,
1431*67e74705SXin Li                                        CXXDtorType Type, bool ForVirtualBase,
1432*67e74705SXin Li                                        bool Delegating, Address This) {
1433*67e74705SXin Li   GlobalDecl GD(DD, Type);
1434*67e74705SXin Li   llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1435*67e74705SXin Li   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1436*67e74705SXin Li 
1437*67e74705SXin Li   llvm::Value *Callee = nullptr;
1438*67e74705SXin Li   if (getContext().getLangOpts().AppleKext)
1439*67e74705SXin Li     Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1440*67e74705SXin Li 
1441*67e74705SXin Li   if (!Callee)
1442*67e74705SXin Li     Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
1443*67e74705SXin Li 
1444*67e74705SXin Li   CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
1445*67e74705SXin Li                                   This.getPointer(), VTT, VTTTy, nullptr);
1446*67e74705SXin Li }
1447*67e74705SXin Li 
emitVTableDefinitions(CodeGenVTables & CGVT,const CXXRecordDecl * RD)1448*67e74705SXin Li void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1449*67e74705SXin Li                                           const CXXRecordDecl *RD) {
1450*67e74705SXin Li   llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1451*67e74705SXin Li   if (VTable->hasInitializer())
1452*67e74705SXin Li     return;
1453*67e74705SXin Li 
1454*67e74705SXin Li   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1455*67e74705SXin Li   const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1456*67e74705SXin Li   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1457*67e74705SXin Li   llvm::Constant *RTTI =
1458*67e74705SXin Li       CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
1459*67e74705SXin Li 
1460*67e74705SXin Li   // Create and set the initializer.
1461*67e74705SXin Li   llvm::Constant *Init = CGVT.CreateVTableInitializer(
1462*67e74705SXin Li       RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
1463*67e74705SXin Li       VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
1464*67e74705SXin Li   VTable->setInitializer(Init);
1465*67e74705SXin Li 
1466*67e74705SXin Li   // Set the correct linkage.
1467*67e74705SXin Li   VTable->setLinkage(Linkage);
1468*67e74705SXin Li 
1469*67e74705SXin Li   if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1470*67e74705SXin Li     VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
1471*67e74705SXin Li 
1472*67e74705SXin Li   // Set the right visibility.
1473*67e74705SXin Li   CGM.setGlobalVisibility(VTable, RD);
1474*67e74705SXin Li 
1475*67e74705SXin Li   // Use pointer alignment for the vtable. Otherwise we would align them based
1476*67e74705SXin Li   // on the size of the initializer which doesn't make sense as only single
1477*67e74705SXin Li   // values are read.
1478*67e74705SXin Li   unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1479*67e74705SXin Li   VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1480*67e74705SXin Li 
1481*67e74705SXin Li   // If this is the magic class __cxxabiv1::__fundamental_type_info,
1482*67e74705SXin Li   // we will emit the typeinfo for the fundamental types. This is the
1483*67e74705SXin Li   // same behaviour as GCC.
1484*67e74705SXin Li   const DeclContext *DC = RD->getDeclContext();
1485*67e74705SXin Li   if (RD->getIdentifier() &&
1486*67e74705SXin Li       RD->getIdentifier()->isStr("__fundamental_type_info") &&
1487*67e74705SXin Li       isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1488*67e74705SXin Li       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1489*67e74705SXin Li       DC->getParent()->isTranslationUnit())
1490*67e74705SXin Li     EmitFundamentalRTTIDescriptors();
1491*67e74705SXin Li 
1492*67e74705SXin Li   if (!VTable->isDeclarationForLinker())
1493*67e74705SXin Li     CGM.EmitVTableTypeMetadata(VTable, VTLayout);
1494*67e74705SXin Li }
1495*67e74705SXin Li 
isVirtualOffsetNeededForVTableField(CodeGenFunction & CGF,CodeGenFunction::VPtr Vptr)1496*67e74705SXin Li bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1497*67e74705SXin Li     CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1498*67e74705SXin Li   if (Vptr.NearestVBase == nullptr)
1499*67e74705SXin Li     return false;
1500*67e74705SXin Li   return NeedsVTTParameter(CGF.CurGD);
1501*67e74705SXin Li }
1502*67e74705SXin Li 
getVTableAddressPointInStructor(CodeGenFunction & CGF,const CXXRecordDecl * VTableClass,BaseSubobject Base,const CXXRecordDecl * NearestVBase)1503*67e74705SXin Li llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1504*67e74705SXin Li     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1505*67e74705SXin Li     const CXXRecordDecl *NearestVBase) {
1506*67e74705SXin Li 
1507*67e74705SXin Li   if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1508*67e74705SXin Li       NeedsVTTParameter(CGF.CurGD)) {
1509*67e74705SXin Li     return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1510*67e74705SXin Li                                                   NearestVBase);
1511*67e74705SXin Li   }
1512*67e74705SXin Li   return getVTableAddressPoint(Base, VTableClass);
1513*67e74705SXin Li }
1514*67e74705SXin Li 
1515*67e74705SXin Li llvm::Constant *
getVTableAddressPoint(BaseSubobject Base,const CXXRecordDecl * VTableClass)1516*67e74705SXin Li ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1517*67e74705SXin Li                                      const CXXRecordDecl *VTableClass) {
1518*67e74705SXin Li   llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
1519*67e74705SXin Li 
1520*67e74705SXin Li   // Find the appropriate vtable within the vtable group.
1521*67e74705SXin Li   uint64_t AddressPoint = CGM.getItaniumVTableContext()
1522*67e74705SXin Li                               .getVTableLayout(VTableClass)
1523*67e74705SXin Li                               .getAddressPoint(Base);
1524*67e74705SXin Li   llvm::Value *Indices[] = {
1525*67e74705SXin Li     llvm::ConstantInt::get(CGM.Int32Ty, 0),
1526*67e74705SXin Li     llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint)
1527*67e74705SXin Li   };
1528*67e74705SXin Li 
1529*67e74705SXin Li   return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable->getValueType(),
1530*67e74705SXin Li                                                       VTable, Indices);
1531*67e74705SXin Li }
1532*67e74705SXin Li 
getVTableAddressPointInStructorWithVTT(CodeGenFunction & CGF,const CXXRecordDecl * VTableClass,BaseSubobject Base,const CXXRecordDecl * NearestVBase)1533*67e74705SXin Li llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1534*67e74705SXin Li     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1535*67e74705SXin Li     const CXXRecordDecl *NearestVBase) {
1536*67e74705SXin Li   assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1537*67e74705SXin Li          NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1538*67e74705SXin Li 
1539*67e74705SXin Li   // Get the secondary vpointer index.
1540*67e74705SXin Li   uint64_t VirtualPointerIndex =
1541*67e74705SXin Li       CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1542*67e74705SXin Li 
1543*67e74705SXin Li   /// Load the VTT.
1544*67e74705SXin Li   llvm::Value *VTT = CGF.LoadCXXVTT();
1545*67e74705SXin Li   if (VirtualPointerIndex)
1546*67e74705SXin Li     VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1547*67e74705SXin Li 
1548*67e74705SXin Li   // And load the address point from the VTT.
1549*67e74705SXin Li   return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1550*67e74705SXin Li }
1551*67e74705SXin Li 
getVTableAddressPointForConstExpr(BaseSubobject Base,const CXXRecordDecl * VTableClass)1552*67e74705SXin Li llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1553*67e74705SXin Li     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1554*67e74705SXin Li   return getVTableAddressPoint(Base, VTableClass);
1555*67e74705SXin Li }
1556*67e74705SXin Li 
getAddrOfVTable(const CXXRecordDecl * RD,CharUnits VPtrOffset)1557*67e74705SXin Li llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1558*67e74705SXin Li                                                      CharUnits VPtrOffset) {
1559*67e74705SXin Li   assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1560*67e74705SXin Li 
1561*67e74705SXin Li   llvm::GlobalVariable *&VTable = VTables[RD];
1562*67e74705SXin Li   if (VTable)
1563*67e74705SXin Li     return VTable;
1564*67e74705SXin Li 
1565*67e74705SXin Li   // Queue up this vtable for possible deferred emission.
1566*67e74705SXin Li   CGM.addDeferredVTable(RD);
1567*67e74705SXin Li 
1568*67e74705SXin Li   SmallString<256> Name;
1569*67e74705SXin Li   llvm::raw_svector_ostream Out(Name);
1570*67e74705SXin Li   getMangleContext().mangleCXXVTable(RD, Out);
1571*67e74705SXin Li 
1572*67e74705SXin Li   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1573*67e74705SXin Li   llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1574*67e74705SXin Li       CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1575*67e74705SXin Li 
1576*67e74705SXin Li   VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1577*67e74705SXin Li       Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1578*67e74705SXin Li   VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1579*67e74705SXin Li 
1580*67e74705SXin Li   if (RD->hasAttr<DLLImportAttr>())
1581*67e74705SXin Li     VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1582*67e74705SXin Li   else if (RD->hasAttr<DLLExportAttr>())
1583*67e74705SXin Li     VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1584*67e74705SXin Li 
1585*67e74705SXin Li   return VTable;
1586*67e74705SXin Li }
1587*67e74705SXin Li 
getVirtualFunctionPointer(CodeGenFunction & CGF,GlobalDecl GD,Address This,llvm::Type * Ty,SourceLocation Loc)1588*67e74705SXin Li llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1589*67e74705SXin Li                                                       GlobalDecl GD,
1590*67e74705SXin Li                                                       Address This,
1591*67e74705SXin Li                                                       llvm::Type *Ty,
1592*67e74705SXin Li                                                       SourceLocation Loc) {
1593*67e74705SXin Li   GD = GD.getCanonicalDecl();
1594*67e74705SXin Li   Ty = Ty->getPointerTo()->getPointerTo();
1595*67e74705SXin Li   auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1596*67e74705SXin Li   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
1597*67e74705SXin Li 
1598*67e74705SXin Li   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
1599*67e74705SXin Li   if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1600*67e74705SXin Li     return CGF.EmitVTableTypeCheckedLoad(
1601*67e74705SXin Li         MethodDecl->getParent(), VTable,
1602*67e74705SXin Li         VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1603*67e74705SXin Li   } else {
1604*67e74705SXin Li     CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1605*67e74705SXin Li 
1606*67e74705SXin Li     llvm::Value *VFuncPtr =
1607*67e74705SXin Li         CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1608*67e74705SXin Li     return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1609*67e74705SXin Li   }
1610*67e74705SXin Li }
1611*67e74705SXin Li 
EmitVirtualDestructorCall(CodeGenFunction & CGF,const CXXDestructorDecl * Dtor,CXXDtorType DtorType,Address This,const CXXMemberCallExpr * CE)1612*67e74705SXin Li llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1613*67e74705SXin Li     CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1614*67e74705SXin Li     Address This, const CXXMemberCallExpr *CE) {
1615*67e74705SXin Li   assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1616*67e74705SXin Li   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1617*67e74705SXin Li 
1618*67e74705SXin Li   const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1619*67e74705SXin Li       Dtor, getFromDtorType(DtorType));
1620*67e74705SXin Li   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1621*67e74705SXin Li   llvm::Value *Callee =
1622*67e74705SXin Li       getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1623*67e74705SXin Li                                 CE ? CE->getLocStart() : SourceLocation());
1624*67e74705SXin Li 
1625*67e74705SXin Li   CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1626*67e74705SXin Li                                   This.getPointer(), /*ImplicitParam=*/nullptr,
1627*67e74705SXin Li                                   QualType(), CE);
1628*67e74705SXin Li   return nullptr;
1629*67e74705SXin Li }
1630*67e74705SXin Li 
emitVirtualInheritanceTables(const CXXRecordDecl * RD)1631*67e74705SXin Li void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1632*67e74705SXin Li   CodeGenVTables &VTables = CGM.getVTables();
1633*67e74705SXin Li   llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
1634*67e74705SXin Li   VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
1635*67e74705SXin Li }
1636*67e74705SXin Li 
canSpeculativelyEmitVTable(const CXXRecordDecl * RD) const1637*67e74705SXin Li bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
1638*67e74705SXin Li   // We don't emit available_externally vtables if we are in -fapple-kext mode
1639*67e74705SXin Li   // because kext mode does not permit devirtualization.
1640*67e74705SXin Li   if (CGM.getLangOpts().AppleKext)
1641*67e74705SXin Li     return false;
1642*67e74705SXin Li 
1643*67e74705SXin Li   // If we don't have any inline virtual functions, and if vtable is not hidden,
1644*67e74705SXin Li   // then we are safe to emit available_externally copy of vtable.
1645*67e74705SXin Li   // FIXME we can still emit a copy of the vtable if we
1646*67e74705SXin Li   // can emit definition of the inline functions.
1647*67e74705SXin Li   return !hasAnyUsedVirtualInlineFunction(RD) && !isVTableHidden(RD);
1648*67e74705SXin Li }
performTypeAdjustment(CodeGenFunction & CGF,Address InitialPtr,int64_t NonVirtualAdjustment,int64_t VirtualAdjustment,bool IsReturnAdjustment)1649*67e74705SXin Li static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1650*67e74705SXin Li                                           Address InitialPtr,
1651*67e74705SXin Li                                           int64_t NonVirtualAdjustment,
1652*67e74705SXin Li                                           int64_t VirtualAdjustment,
1653*67e74705SXin Li                                           bool IsReturnAdjustment) {
1654*67e74705SXin Li   if (!NonVirtualAdjustment && !VirtualAdjustment)
1655*67e74705SXin Li     return InitialPtr.getPointer();
1656*67e74705SXin Li 
1657*67e74705SXin Li   Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
1658*67e74705SXin Li 
1659*67e74705SXin Li   // In a base-to-derived cast, the non-virtual adjustment is applied first.
1660*67e74705SXin Li   if (NonVirtualAdjustment && !IsReturnAdjustment) {
1661*67e74705SXin Li     V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1662*67e74705SXin Li                               CharUnits::fromQuantity(NonVirtualAdjustment));
1663*67e74705SXin Li   }
1664*67e74705SXin Li 
1665*67e74705SXin Li   // Perform the virtual adjustment if we have one.
1666*67e74705SXin Li   llvm::Value *ResultPtr;
1667*67e74705SXin Li   if (VirtualAdjustment) {
1668*67e74705SXin Li     llvm::Type *PtrDiffTy =
1669*67e74705SXin Li         CGF.ConvertType(CGF.getContext().getPointerDiffType());
1670*67e74705SXin Li 
1671*67e74705SXin Li     Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
1672*67e74705SXin Li     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1673*67e74705SXin Li 
1674*67e74705SXin Li     llvm::Value *OffsetPtr =
1675*67e74705SXin Li         CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1676*67e74705SXin Li 
1677*67e74705SXin Li     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1678*67e74705SXin Li 
1679*67e74705SXin Li     // Load the adjustment offset from the vtable.
1680*67e74705SXin Li     llvm::Value *Offset =
1681*67e74705SXin Li       CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
1682*67e74705SXin Li 
1683*67e74705SXin Li     // Adjust our pointer.
1684*67e74705SXin Li     ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1685*67e74705SXin Li   } else {
1686*67e74705SXin Li     ResultPtr = V.getPointer();
1687*67e74705SXin Li   }
1688*67e74705SXin Li 
1689*67e74705SXin Li   // In a derived-to-base conversion, the non-virtual adjustment is
1690*67e74705SXin Li   // applied second.
1691*67e74705SXin Li   if (NonVirtualAdjustment && IsReturnAdjustment) {
1692*67e74705SXin Li     ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1693*67e74705SXin Li                                                        NonVirtualAdjustment);
1694*67e74705SXin Li   }
1695*67e74705SXin Li 
1696*67e74705SXin Li   // Cast back to the original type.
1697*67e74705SXin Li   return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
1698*67e74705SXin Li }
1699*67e74705SXin Li 
performThisAdjustment(CodeGenFunction & CGF,Address This,const ThisAdjustment & TA)1700*67e74705SXin Li llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1701*67e74705SXin Li                                                   Address This,
1702*67e74705SXin Li                                                   const ThisAdjustment &TA) {
1703*67e74705SXin Li   return performTypeAdjustment(CGF, This, TA.NonVirtual,
1704*67e74705SXin Li                                TA.Virtual.Itanium.VCallOffsetOffset,
1705*67e74705SXin Li                                /*IsReturnAdjustment=*/false);
1706*67e74705SXin Li }
1707*67e74705SXin Li 
1708*67e74705SXin Li llvm::Value *
performReturnAdjustment(CodeGenFunction & CGF,Address Ret,const ReturnAdjustment & RA)1709*67e74705SXin Li ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
1710*67e74705SXin Li                                        const ReturnAdjustment &RA) {
1711*67e74705SXin Li   return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1712*67e74705SXin Li                                RA.Virtual.Itanium.VBaseOffsetOffset,
1713*67e74705SXin Li                                /*IsReturnAdjustment=*/true);
1714*67e74705SXin Li }
1715*67e74705SXin Li 
EmitReturnFromThunk(CodeGenFunction & CGF,RValue RV,QualType ResultType)1716*67e74705SXin Li void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1717*67e74705SXin Li                                     RValue RV, QualType ResultType) {
1718*67e74705SXin Li   if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1719*67e74705SXin Li     return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1720*67e74705SXin Li 
1721*67e74705SXin Li   // Destructor thunks in the ARM ABI have indeterminate results.
1722*67e74705SXin Li   llvm::Type *T = CGF.ReturnValue.getElementType();
1723*67e74705SXin Li   RValue Undef = RValue::get(llvm::UndefValue::get(T));
1724*67e74705SXin Li   return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1725*67e74705SXin Li }
1726*67e74705SXin Li 
1727*67e74705SXin Li /************************** Array allocation cookies **************************/
1728*67e74705SXin Li 
getArrayCookieSizeImpl(QualType elementType)1729*67e74705SXin Li CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1730*67e74705SXin Li   // The array cookie is a size_t; pad that up to the element alignment.
1731*67e74705SXin Li   // The cookie is actually right-justified in that space.
1732*67e74705SXin Li   return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1733*67e74705SXin Li                   CGM.getContext().getTypeAlignInChars(elementType));
1734*67e74705SXin Li }
1735*67e74705SXin Li 
InitializeArrayCookie(CodeGenFunction & CGF,Address NewPtr,llvm::Value * NumElements,const CXXNewExpr * expr,QualType ElementType)1736*67e74705SXin Li Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1737*67e74705SXin Li                                              Address NewPtr,
1738*67e74705SXin Li                                              llvm::Value *NumElements,
1739*67e74705SXin Li                                              const CXXNewExpr *expr,
1740*67e74705SXin Li                                              QualType ElementType) {
1741*67e74705SXin Li   assert(requiresArrayCookie(expr));
1742*67e74705SXin Li 
1743*67e74705SXin Li   unsigned AS = NewPtr.getAddressSpace();
1744*67e74705SXin Li 
1745*67e74705SXin Li   ASTContext &Ctx = getContext();
1746*67e74705SXin Li   CharUnits SizeSize = CGF.getSizeSize();
1747*67e74705SXin Li 
1748*67e74705SXin Li   // The size of the cookie.
1749*67e74705SXin Li   CharUnits CookieSize =
1750*67e74705SXin Li     std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
1751*67e74705SXin Li   assert(CookieSize == getArrayCookieSizeImpl(ElementType));
1752*67e74705SXin Li 
1753*67e74705SXin Li   // Compute an offset to the cookie.
1754*67e74705SXin Li   Address CookiePtr = NewPtr;
1755*67e74705SXin Li   CharUnits CookieOffset = CookieSize - SizeSize;
1756*67e74705SXin Li   if (!CookieOffset.isZero())
1757*67e74705SXin Li     CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
1758*67e74705SXin Li 
1759*67e74705SXin Li   // Write the number of elements into the appropriate slot.
1760*67e74705SXin Li   Address NumElementsPtr =
1761*67e74705SXin Li       CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
1762*67e74705SXin Li   llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1763*67e74705SXin Li 
1764*67e74705SXin Li   // Handle the array cookie specially in ASan.
1765*67e74705SXin Li   if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
1766*67e74705SXin Li       expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
1767*67e74705SXin Li     // The store to the CookiePtr does not need to be instrumented.
1768*67e74705SXin Li     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1769*67e74705SXin Li     llvm::FunctionType *FTy =
1770*67e74705SXin Li         llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
1771*67e74705SXin Li     llvm::Constant *F =
1772*67e74705SXin Li         CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1773*67e74705SXin Li     CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
1774*67e74705SXin Li   }
1775*67e74705SXin Li 
1776*67e74705SXin Li   // Finally, compute a pointer to the actual data buffer by skipping
1777*67e74705SXin Li   // over the cookie completely.
1778*67e74705SXin Li   return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
1779*67e74705SXin Li }
1780*67e74705SXin Li 
readArrayCookieImpl(CodeGenFunction & CGF,Address allocPtr,CharUnits cookieSize)1781*67e74705SXin Li llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1782*67e74705SXin Li                                                 Address allocPtr,
1783*67e74705SXin Li                                                 CharUnits cookieSize) {
1784*67e74705SXin Li   // The element size is right-justified in the cookie.
1785*67e74705SXin Li   Address numElementsPtr = allocPtr;
1786*67e74705SXin Li   CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
1787*67e74705SXin Li   if (!numElementsOffset.isZero())
1788*67e74705SXin Li     numElementsPtr =
1789*67e74705SXin Li       CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
1790*67e74705SXin Li 
1791*67e74705SXin Li   unsigned AS = allocPtr.getAddressSpace();
1792*67e74705SXin Li   numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
1793*67e74705SXin Li   if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
1794*67e74705SXin Li     return CGF.Builder.CreateLoad(numElementsPtr);
1795*67e74705SXin Li   // In asan mode emit a function call instead of a regular load and let the
1796*67e74705SXin Li   // run-time deal with it: if the shadow is properly poisoned return the
1797*67e74705SXin Li   // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1798*67e74705SXin Li   // We can't simply ignore this load using nosanitize metadata because
1799*67e74705SXin Li   // the metadata may be lost.
1800*67e74705SXin Li   llvm::FunctionType *FTy =
1801*67e74705SXin Li       llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1802*67e74705SXin Li   llvm::Constant *F =
1803*67e74705SXin Li       CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1804*67e74705SXin Li   return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
1805*67e74705SXin Li }
1806*67e74705SXin Li 
getArrayCookieSizeImpl(QualType elementType)1807*67e74705SXin Li CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1808*67e74705SXin Li   // ARM says that the cookie is always:
1809*67e74705SXin Li   //   struct array_cookie {
1810*67e74705SXin Li   //     std::size_t element_size; // element_size != 0
1811*67e74705SXin Li   //     std::size_t element_count;
1812*67e74705SXin Li   //   };
1813*67e74705SXin Li   // But the base ABI doesn't give anything an alignment greater than
1814*67e74705SXin Li   // 8, so we can dismiss this as typical ABI-author blindness to
1815*67e74705SXin Li   // actual language complexity and round up to the element alignment.
1816*67e74705SXin Li   return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1817*67e74705SXin Li                   CGM.getContext().getTypeAlignInChars(elementType));
1818*67e74705SXin Li }
1819*67e74705SXin Li 
InitializeArrayCookie(CodeGenFunction & CGF,Address newPtr,llvm::Value * numElements,const CXXNewExpr * expr,QualType elementType)1820*67e74705SXin Li Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1821*67e74705SXin Li                                          Address newPtr,
1822*67e74705SXin Li                                          llvm::Value *numElements,
1823*67e74705SXin Li                                          const CXXNewExpr *expr,
1824*67e74705SXin Li                                          QualType elementType) {
1825*67e74705SXin Li   assert(requiresArrayCookie(expr));
1826*67e74705SXin Li 
1827*67e74705SXin Li   // The cookie is always at the start of the buffer.
1828*67e74705SXin Li   Address cookie = newPtr;
1829*67e74705SXin Li 
1830*67e74705SXin Li   // The first element is the element size.
1831*67e74705SXin Li   cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
1832*67e74705SXin Li   llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1833*67e74705SXin Li                  getContext().getTypeSizeInChars(elementType).getQuantity());
1834*67e74705SXin Li   CGF.Builder.CreateStore(elementSize, cookie);
1835*67e74705SXin Li 
1836*67e74705SXin Li   // The second element is the element count.
1837*67e74705SXin Li   cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
1838*67e74705SXin Li   CGF.Builder.CreateStore(numElements, cookie);
1839*67e74705SXin Li 
1840*67e74705SXin Li   // Finally, compute a pointer to the actual data buffer by skipping
1841*67e74705SXin Li   // over the cookie completely.
1842*67e74705SXin Li   CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1843*67e74705SXin Li   return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
1844*67e74705SXin Li }
1845*67e74705SXin Li 
readArrayCookieImpl(CodeGenFunction & CGF,Address allocPtr,CharUnits cookieSize)1846*67e74705SXin Li llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1847*67e74705SXin Li                                             Address allocPtr,
1848*67e74705SXin Li                                             CharUnits cookieSize) {
1849*67e74705SXin Li   // The number of elements is at offset sizeof(size_t) relative to
1850*67e74705SXin Li   // the allocated pointer.
1851*67e74705SXin Li   Address numElementsPtr
1852*67e74705SXin Li     = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
1853*67e74705SXin Li 
1854*67e74705SXin Li   numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
1855*67e74705SXin Li   return CGF.Builder.CreateLoad(numElementsPtr);
1856*67e74705SXin Li }
1857*67e74705SXin Li 
1858*67e74705SXin Li /*********************** Static local initialization **************************/
1859*67e74705SXin Li 
getGuardAcquireFn(CodeGenModule & CGM,llvm::PointerType * GuardPtrTy)1860*67e74705SXin Li static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1861*67e74705SXin Li                                          llvm::PointerType *GuardPtrTy) {
1862*67e74705SXin Li   // int __cxa_guard_acquire(__guard *guard_object);
1863*67e74705SXin Li   llvm::FunctionType *FTy =
1864*67e74705SXin Li     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1865*67e74705SXin Li                             GuardPtrTy, /*isVarArg=*/false);
1866*67e74705SXin Li   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
1867*67e74705SXin Li                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1868*67e74705SXin Li                                               llvm::AttributeSet::FunctionIndex,
1869*67e74705SXin Li                                                  llvm::Attribute::NoUnwind));
1870*67e74705SXin Li }
1871*67e74705SXin Li 
getGuardReleaseFn(CodeGenModule & CGM,llvm::PointerType * GuardPtrTy)1872*67e74705SXin Li static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1873*67e74705SXin Li                                          llvm::PointerType *GuardPtrTy) {
1874*67e74705SXin Li   // void __cxa_guard_release(__guard *guard_object);
1875*67e74705SXin Li   llvm::FunctionType *FTy =
1876*67e74705SXin Li     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1877*67e74705SXin Li   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
1878*67e74705SXin Li                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1879*67e74705SXin Li                                               llvm::AttributeSet::FunctionIndex,
1880*67e74705SXin Li                                                  llvm::Attribute::NoUnwind));
1881*67e74705SXin Li }
1882*67e74705SXin Li 
getGuardAbortFn(CodeGenModule & CGM,llvm::PointerType * GuardPtrTy)1883*67e74705SXin Li static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1884*67e74705SXin Li                                        llvm::PointerType *GuardPtrTy) {
1885*67e74705SXin Li   // void __cxa_guard_abort(__guard *guard_object);
1886*67e74705SXin Li   llvm::FunctionType *FTy =
1887*67e74705SXin Li     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1888*67e74705SXin Li   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
1889*67e74705SXin Li                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1890*67e74705SXin Li                                               llvm::AttributeSet::FunctionIndex,
1891*67e74705SXin Li                                                  llvm::Attribute::NoUnwind));
1892*67e74705SXin Li }
1893*67e74705SXin Li 
1894*67e74705SXin Li namespace {
1895*67e74705SXin Li   struct CallGuardAbort final : EHScopeStack::Cleanup {
1896*67e74705SXin Li     llvm::GlobalVariable *Guard;
CallGuardAbort__anonbf32792c0211::CallGuardAbort1897*67e74705SXin Li     CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1898*67e74705SXin Li 
Emit__anonbf32792c0211::CallGuardAbort1899*67e74705SXin Li     void Emit(CodeGenFunction &CGF, Flags flags) override {
1900*67e74705SXin Li       CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1901*67e74705SXin Li                                   Guard);
1902*67e74705SXin Li     }
1903*67e74705SXin Li   };
1904*67e74705SXin Li }
1905*67e74705SXin Li 
1906*67e74705SXin Li /// The ARM code here follows the Itanium code closely enough that we
1907*67e74705SXin Li /// just special-case it at particular places.
EmitGuardedInit(CodeGenFunction & CGF,const VarDecl & D,llvm::GlobalVariable * var,bool shouldPerformInit)1908*67e74705SXin Li void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1909*67e74705SXin Li                                     const VarDecl &D,
1910*67e74705SXin Li                                     llvm::GlobalVariable *var,
1911*67e74705SXin Li                                     bool shouldPerformInit) {
1912*67e74705SXin Li   CGBuilderTy &Builder = CGF.Builder;
1913*67e74705SXin Li 
1914*67e74705SXin Li   // Inline variables that weren't instantiated from variable templates have
1915*67e74705SXin Li   // partially-ordered initialization within their translation unit.
1916*67e74705SXin Li   bool NonTemplateInline =
1917*67e74705SXin Li       D.isInline() &&
1918*67e74705SXin Li       !isTemplateInstantiation(D.getTemplateSpecializationKind());
1919*67e74705SXin Li 
1920*67e74705SXin Li   // We only need to use thread-safe statics for local non-TLS variables and
1921*67e74705SXin Li   // inline variables; other global initialization is always single-threaded
1922*67e74705SXin Li   // or (through lazy dynamic loading in multiple threads) unsequenced.
1923*67e74705SXin Li   bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1924*67e74705SXin Li                     (D.isLocalVarDecl() || NonTemplateInline) &&
1925*67e74705SXin Li                     !D.getTLSKind();
1926*67e74705SXin Li 
1927*67e74705SXin Li   // If we have a global variable with internal linkage and thread-safe statics
1928*67e74705SXin Li   // are disabled, we can just let the guard variable be of type i8.
1929*67e74705SXin Li   bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1930*67e74705SXin Li 
1931*67e74705SXin Li   llvm::IntegerType *guardTy;
1932*67e74705SXin Li   CharUnits guardAlignment;
1933*67e74705SXin Li   if (useInt8GuardVariable) {
1934*67e74705SXin Li     guardTy = CGF.Int8Ty;
1935*67e74705SXin Li     guardAlignment = CharUnits::One();
1936*67e74705SXin Li   } else {
1937*67e74705SXin Li     // Guard variables are 64 bits in the generic ABI and size width on ARM
1938*67e74705SXin Li     // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1939*67e74705SXin Li     if (UseARMGuardVarABI) {
1940*67e74705SXin Li       guardTy = CGF.SizeTy;
1941*67e74705SXin Li       guardAlignment = CGF.getSizeAlign();
1942*67e74705SXin Li     } else {
1943*67e74705SXin Li       guardTy = CGF.Int64Ty;
1944*67e74705SXin Li       guardAlignment = CharUnits::fromQuantity(
1945*67e74705SXin Li                              CGM.getDataLayout().getABITypeAlignment(guardTy));
1946*67e74705SXin Li     }
1947*67e74705SXin Li   }
1948*67e74705SXin Li   llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
1949*67e74705SXin Li 
1950*67e74705SXin Li   // Create the guard variable if we don't already have it (as we
1951*67e74705SXin Li   // might if we're double-emitting this function body).
1952*67e74705SXin Li   llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1953*67e74705SXin Li   if (!guard) {
1954*67e74705SXin Li     // Mangle the name for the guard.
1955*67e74705SXin Li     SmallString<256> guardName;
1956*67e74705SXin Li     {
1957*67e74705SXin Li       llvm::raw_svector_ostream out(guardName);
1958*67e74705SXin Li       getMangleContext().mangleStaticGuardVariable(&D, out);
1959*67e74705SXin Li     }
1960*67e74705SXin Li 
1961*67e74705SXin Li     // Create the guard variable with a zero-initializer.
1962*67e74705SXin Li     // Just absorb linkage and visibility from the guarded variable.
1963*67e74705SXin Li     guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1964*67e74705SXin Li                                      false, var->getLinkage(),
1965*67e74705SXin Li                                      llvm::ConstantInt::get(guardTy, 0),
1966*67e74705SXin Li                                      guardName.str());
1967*67e74705SXin Li     guard->setVisibility(var->getVisibility());
1968*67e74705SXin Li     // If the variable is thread-local, so is its guard variable.
1969*67e74705SXin Li     guard->setThreadLocalMode(var->getThreadLocalMode());
1970*67e74705SXin Li     guard->setAlignment(guardAlignment.getQuantity());
1971*67e74705SXin Li 
1972*67e74705SXin Li     // The ABI says: "It is suggested that it be emitted in the same COMDAT
1973*67e74705SXin Li     // group as the associated data object." In practice, this doesn't work for
1974*67e74705SXin Li     // non-ELF object formats, so only do it for ELF.
1975*67e74705SXin Li     llvm::Comdat *C = var->getComdat();
1976*67e74705SXin Li     if (!D.isLocalVarDecl() && C &&
1977*67e74705SXin Li         CGM.getTarget().getTriple().isOSBinFormatELF()) {
1978*67e74705SXin Li       guard->setComdat(C);
1979*67e74705SXin Li       // An inline variable's guard function is run from the per-TU
1980*67e74705SXin Li       // initialization function, not via a dedicated global ctor function, so
1981*67e74705SXin Li       // we can't put it in a comdat.
1982*67e74705SXin Li       if (!NonTemplateInline)
1983*67e74705SXin Li         CGF.CurFn->setComdat(C);
1984*67e74705SXin Li     } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
1985*67e74705SXin Li       guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
1986*67e74705SXin Li     }
1987*67e74705SXin Li 
1988*67e74705SXin Li     CGM.setStaticLocalDeclGuardAddress(&D, guard);
1989*67e74705SXin Li   }
1990*67e74705SXin Li 
1991*67e74705SXin Li   Address guardAddr = Address(guard, guardAlignment);
1992*67e74705SXin Li 
1993*67e74705SXin Li   // Test whether the variable has completed initialization.
1994*67e74705SXin Li   //
1995*67e74705SXin Li   // Itanium C++ ABI 3.3.2:
1996*67e74705SXin Li   //   The following is pseudo-code showing how these functions can be used:
1997*67e74705SXin Li   //     if (obj_guard.first_byte == 0) {
1998*67e74705SXin Li   //       if ( __cxa_guard_acquire (&obj_guard) ) {
1999*67e74705SXin Li   //         try {
2000*67e74705SXin Li   //           ... initialize the object ...;
2001*67e74705SXin Li   //         } catch (...) {
2002*67e74705SXin Li   //            __cxa_guard_abort (&obj_guard);
2003*67e74705SXin Li   //            throw;
2004*67e74705SXin Li   //         }
2005*67e74705SXin Li   //         ... queue object destructor with __cxa_atexit() ...;
2006*67e74705SXin Li   //         __cxa_guard_release (&obj_guard);
2007*67e74705SXin Li   //       }
2008*67e74705SXin Li   //     }
2009*67e74705SXin Li 
2010*67e74705SXin Li   // Load the first byte of the guard variable.
2011*67e74705SXin Li   llvm::LoadInst *LI =
2012*67e74705SXin Li       Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
2013*67e74705SXin Li 
2014*67e74705SXin Li   // Itanium ABI:
2015*67e74705SXin Li   //   An implementation supporting thread-safety on multiprocessor
2016*67e74705SXin Li   //   systems must also guarantee that references to the initialized
2017*67e74705SXin Li   //   object do not occur before the load of the initialization flag.
2018*67e74705SXin Li   //
2019*67e74705SXin Li   // In LLVM, we do this by marking the load Acquire.
2020*67e74705SXin Li   if (threadsafe)
2021*67e74705SXin Li     LI->setAtomic(llvm::AtomicOrdering::Acquire);
2022*67e74705SXin Li 
2023*67e74705SXin Li   // For ARM, we should only check the first bit, rather than the entire byte:
2024*67e74705SXin Li   //
2025*67e74705SXin Li   // ARM C++ ABI 3.2.3.1:
2026*67e74705SXin Li   //   To support the potential use of initialization guard variables
2027*67e74705SXin Li   //   as semaphores that are the target of ARM SWP and LDREX/STREX
2028*67e74705SXin Li   //   synchronizing instructions we define a static initialization
2029*67e74705SXin Li   //   guard variable to be a 4-byte aligned, 4-byte word with the
2030*67e74705SXin Li   //   following inline access protocol.
2031*67e74705SXin Li   //     #define INITIALIZED 1
2032*67e74705SXin Li   //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
2033*67e74705SXin Li   //       if (__cxa_guard_acquire(&obj_guard))
2034*67e74705SXin Li   //         ...
2035*67e74705SXin Li   //     }
2036*67e74705SXin Li   //
2037*67e74705SXin Li   // and similarly for ARM64:
2038*67e74705SXin Li   //
2039*67e74705SXin Li   // ARM64 C++ ABI 3.2.2:
2040*67e74705SXin Li   //   This ABI instead only specifies the value bit 0 of the static guard
2041*67e74705SXin Li   //   variable; all other bits are platform defined. Bit 0 shall be 0 when the
2042*67e74705SXin Li   //   variable is not initialized and 1 when it is.
2043*67e74705SXin Li   llvm::Value *V =
2044*67e74705SXin Li       (UseARMGuardVarABI && !useInt8GuardVariable)
2045*67e74705SXin Li           ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2046*67e74705SXin Li           : LI;
2047*67e74705SXin Li   llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
2048*67e74705SXin Li 
2049*67e74705SXin Li   llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2050*67e74705SXin Li   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2051*67e74705SXin Li 
2052*67e74705SXin Li   // Check if the first byte of the guard variable is zero.
2053*67e74705SXin Li   Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
2054*67e74705SXin Li 
2055*67e74705SXin Li   CGF.EmitBlock(InitCheckBlock);
2056*67e74705SXin Li 
2057*67e74705SXin Li   // Variables used when coping with thread-safe statics and exceptions.
2058*67e74705SXin Li   if (threadsafe) {
2059*67e74705SXin Li     // Call __cxa_guard_acquire.
2060*67e74705SXin Li     llvm::Value *V
2061*67e74705SXin Li       = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
2062*67e74705SXin Li 
2063*67e74705SXin Li     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2064*67e74705SXin Li 
2065*67e74705SXin Li     Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2066*67e74705SXin Li                          InitBlock, EndBlock);
2067*67e74705SXin Li 
2068*67e74705SXin Li     // Call __cxa_guard_abort along the exceptional edge.
2069*67e74705SXin Li     CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
2070*67e74705SXin Li 
2071*67e74705SXin Li     CGF.EmitBlock(InitBlock);
2072*67e74705SXin Li   }
2073*67e74705SXin Li 
2074*67e74705SXin Li   // Emit the initializer and add a global destructor if appropriate.
2075*67e74705SXin Li   CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
2076*67e74705SXin Li 
2077*67e74705SXin Li   if (threadsafe) {
2078*67e74705SXin Li     // Pop the guard-abort cleanup if we pushed one.
2079*67e74705SXin Li     CGF.PopCleanupBlock();
2080*67e74705SXin Li 
2081*67e74705SXin Li     // Call __cxa_guard_release.  This cannot throw.
2082*67e74705SXin Li     CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2083*67e74705SXin Li                                 guardAddr.getPointer());
2084*67e74705SXin Li   } else {
2085*67e74705SXin Li     Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
2086*67e74705SXin Li   }
2087*67e74705SXin Li 
2088*67e74705SXin Li   CGF.EmitBlock(EndBlock);
2089*67e74705SXin Li }
2090*67e74705SXin Li 
2091*67e74705SXin Li /// Register a global destructor using __cxa_atexit.
emitGlobalDtorWithCXAAtExit(CodeGenFunction & CGF,llvm::Constant * dtor,llvm::Constant * addr,bool TLS)2092*67e74705SXin Li static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2093*67e74705SXin Li                                         llvm::Constant *dtor,
2094*67e74705SXin Li                                         llvm::Constant *addr,
2095*67e74705SXin Li                                         bool TLS) {
2096*67e74705SXin Li   const char *Name = "__cxa_atexit";
2097*67e74705SXin Li   if (TLS) {
2098*67e74705SXin Li     const llvm::Triple &T = CGF.getTarget().getTriple();
2099*67e74705SXin Li     Name = T.isOSDarwin() ?  "_tlv_atexit" : "__cxa_thread_atexit";
2100*67e74705SXin Li   }
2101*67e74705SXin Li 
2102*67e74705SXin Li   // We're assuming that the destructor function is something we can
2103*67e74705SXin Li   // reasonably call with the default CC.  Go ahead and cast it to the
2104*67e74705SXin Li   // right prototype.
2105*67e74705SXin Li   llvm::Type *dtorTy =
2106*67e74705SXin Li     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2107*67e74705SXin Li 
2108*67e74705SXin Li   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2109*67e74705SXin Li   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2110*67e74705SXin Li   llvm::FunctionType *atexitTy =
2111*67e74705SXin Li     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2112*67e74705SXin Li 
2113*67e74705SXin Li   // Fetch the actual function.
2114*67e74705SXin Li   llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2115*67e74705SXin Li   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2116*67e74705SXin Li     fn->setDoesNotThrow();
2117*67e74705SXin Li 
2118*67e74705SXin Li   // Create a variable that binds the atexit to this shared object.
2119*67e74705SXin Li   llvm::Constant *handle =
2120*67e74705SXin Li     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2121*67e74705SXin Li 
2122*67e74705SXin Li   llvm::Value *args[] = {
2123*67e74705SXin Li     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2124*67e74705SXin Li     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2125*67e74705SXin Li     handle
2126*67e74705SXin Li   };
2127*67e74705SXin Li   CGF.EmitNounwindRuntimeCall(atexit, args);
2128*67e74705SXin Li }
2129*67e74705SXin Li 
2130*67e74705SXin Li /// Register a global destructor as best as we know how.
registerGlobalDtor(CodeGenFunction & CGF,const VarDecl & D,llvm::Constant * dtor,llvm::Constant * addr)2131*67e74705SXin Li void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
2132*67e74705SXin Li                                        const VarDecl &D,
2133*67e74705SXin Li                                        llvm::Constant *dtor,
2134*67e74705SXin Li                                        llvm::Constant *addr) {
2135*67e74705SXin Li   // Use __cxa_atexit if available.
2136*67e74705SXin Li   if (CGM.getCodeGenOpts().CXAAtExit)
2137*67e74705SXin Li     return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2138*67e74705SXin Li 
2139*67e74705SXin Li   if (D.getTLSKind())
2140*67e74705SXin Li     CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
2141*67e74705SXin Li 
2142*67e74705SXin Li   // In Apple kexts, we want to add a global destructor entry.
2143*67e74705SXin Li   // FIXME: shouldn't this be guarded by some variable?
2144*67e74705SXin Li   if (CGM.getLangOpts().AppleKext) {
2145*67e74705SXin Li     // Generate a global destructor entry.
2146*67e74705SXin Li     return CGM.AddCXXDtorEntry(dtor, addr);
2147*67e74705SXin Li   }
2148*67e74705SXin Li 
2149*67e74705SXin Li   CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
2150*67e74705SXin Li }
2151*67e74705SXin Li 
isThreadWrapperReplaceable(const VarDecl * VD,CodeGen::CodeGenModule & CGM)2152*67e74705SXin Li static bool isThreadWrapperReplaceable(const VarDecl *VD,
2153*67e74705SXin Li                                        CodeGen::CodeGenModule &CGM) {
2154*67e74705SXin Li   assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2155*67e74705SXin Li   // Darwin prefers to have references to thread local variables to go through
2156*67e74705SXin Li   // the thread wrapper instead of directly referencing the backing variable.
2157*67e74705SXin Li   return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2158*67e74705SXin Li          CGM.getTarget().getTriple().isOSDarwin();
2159*67e74705SXin Li }
2160*67e74705SXin Li 
2161*67e74705SXin Li /// Get the appropriate linkage for the wrapper function. This is essentially
2162*67e74705SXin Li /// the weak form of the variable's linkage; every translation unit which needs
2163*67e74705SXin Li /// the wrapper emits a copy, and we want the linker to merge them.
2164*67e74705SXin Li static llvm::GlobalValue::LinkageTypes
getThreadLocalWrapperLinkage(const VarDecl * VD,CodeGen::CodeGenModule & CGM)2165*67e74705SXin Li getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2166*67e74705SXin Li   llvm::GlobalValue::LinkageTypes VarLinkage =
2167*67e74705SXin Li       CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2168*67e74705SXin Li 
2169*67e74705SXin Li   // For internal linkage variables, we don't need an external or weak wrapper.
2170*67e74705SXin Li   if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2171*67e74705SXin Li     return VarLinkage;
2172*67e74705SXin Li 
2173*67e74705SXin Li   // If the thread wrapper is replaceable, give it appropriate linkage.
2174*67e74705SXin Li   if (isThreadWrapperReplaceable(VD, CGM))
2175*67e74705SXin Li     if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2176*67e74705SXin Li         !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2177*67e74705SXin Li       return VarLinkage;
2178*67e74705SXin Li   return llvm::GlobalValue::WeakODRLinkage;
2179*67e74705SXin Li }
2180*67e74705SXin Li 
2181*67e74705SXin Li llvm::Function *
getOrCreateThreadLocalWrapper(const VarDecl * VD,llvm::Value * Val)2182*67e74705SXin Li ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
2183*67e74705SXin Li                                              llvm::Value *Val) {
2184*67e74705SXin Li   // Mangle the name for the thread_local wrapper function.
2185*67e74705SXin Li   SmallString<256> WrapperName;
2186*67e74705SXin Li   {
2187*67e74705SXin Li     llvm::raw_svector_ostream Out(WrapperName);
2188*67e74705SXin Li     getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
2189*67e74705SXin Li   }
2190*67e74705SXin Li 
2191*67e74705SXin Li   // FIXME: If VD is a definition, we should regenerate the function attributes
2192*67e74705SXin Li   // before returning.
2193*67e74705SXin Li   if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
2194*67e74705SXin Li     return cast<llvm::Function>(V);
2195*67e74705SXin Li 
2196*67e74705SXin Li   QualType RetQT = VD->getType();
2197*67e74705SXin Li   if (RetQT->isReferenceType())
2198*67e74705SXin Li     RetQT = RetQT.getNonReferenceType();
2199*67e74705SXin Li 
2200*67e74705SXin Li   const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2201*67e74705SXin Li       getContext().getPointerType(RetQT), FunctionArgList());
2202*67e74705SXin Li 
2203*67e74705SXin Li   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
2204*67e74705SXin Li   llvm::Function *Wrapper =
2205*67e74705SXin Li       llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2206*67e74705SXin Li                              WrapperName.str(), &CGM.getModule());
2207*67e74705SXin Li 
2208*67e74705SXin Li   CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2209*67e74705SXin Li 
2210*67e74705SXin Li   if (VD->hasDefinition())
2211*67e74705SXin Li     CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2212*67e74705SXin Li 
2213*67e74705SXin Li   // Always resolve references to the wrapper at link time.
2214*67e74705SXin Li   if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2215*67e74705SXin Li       !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2216*67e74705SXin Li       !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
2217*67e74705SXin Li     Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
2218*67e74705SXin Li 
2219*67e74705SXin Li   if (isThreadWrapperReplaceable(VD, CGM)) {
2220*67e74705SXin Li     Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2221*67e74705SXin Li     Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2222*67e74705SXin Li   }
2223*67e74705SXin Li   return Wrapper;
2224*67e74705SXin Li }
2225*67e74705SXin Li 
EmitThreadLocalInitFuncs(CodeGenModule & CGM,ArrayRef<const VarDecl * > CXXThreadLocals,ArrayRef<llvm::Function * > CXXThreadLocalInits,ArrayRef<const VarDecl * > CXXThreadLocalInitVars)2226*67e74705SXin Li void ItaniumCXXABI::EmitThreadLocalInitFuncs(
2227*67e74705SXin Li     CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2228*67e74705SXin Li     ArrayRef<llvm::Function *> CXXThreadLocalInits,
2229*67e74705SXin Li     ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2230*67e74705SXin Li   llvm::Function *InitFunc = nullptr;
2231*67e74705SXin Li   if (!CXXThreadLocalInits.empty()) {
2232*67e74705SXin Li     // Generate a guarded initialization function.
2233*67e74705SXin Li     llvm::FunctionType *FTy =
2234*67e74705SXin Li         llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2235*67e74705SXin Li     const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2236*67e74705SXin Li     InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
2237*67e74705SXin Li                                                       SourceLocation(),
2238*67e74705SXin Li                                                       /*TLS=*/true);
2239*67e74705SXin Li     llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2240*67e74705SXin Li         CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2241*67e74705SXin Li         llvm::GlobalVariable::InternalLinkage,
2242*67e74705SXin Li         llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2243*67e74705SXin Li     Guard->setThreadLocal(true);
2244*67e74705SXin Li 
2245*67e74705SXin Li     CharUnits GuardAlign = CharUnits::One();
2246*67e74705SXin Li     Guard->setAlignment(GuardAlign.getQuantity());
2247*67e74705SXin Li 
2248*67e74705SXin Li     CodeGenFunction(CGM)
2249*67e74705SXin Li         .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits,
2250*67e74705SXin Li                                    Address(Guard, GuardAlign));
2251*67e74705SXin Li     // On Darwin platforms, use CXX_FAST_TLS calling convention.
2252*67e74705SXin Li     if (CGM.getTarget().getTriple().isOSDarwin()) {
2253*67e74705SXin Li       InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2254*67e74705SXin Li       InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2255*67e74705SXin Li     }
2256*67e74705SXin Li   }
2257*67e74705SXin Li   for (const VarDecl *VD : CXXThreadLocals) {
2258*67e74705SXin Li     llvm::GlobalVariable *Var =
2259*67e74705SXin Li         cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
2260*67e74705SXin Li 
2261*67e74705SXin Li     // Some targets require that all access to thread local variables go through
2262*67e74705SXin Li     // the thread wrapper.  This means that we cannot attempt to create a thread
2263*67e74705SXin Li     // wrapper or a thread helper.
2264*67e74705SXin Li     if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
2265*67e74705SXin Li       continue;
2266*67e74705SXin Li 
2267*67e74705SXin Li     // Mangle the name for the thread_local initialization function.
2268*67e74705SXin Li     SmallString<256> InitFnName;
2269*67e74705SXin Li     {
2270*67e74705SXin Li       llvm::raw_svector_ostream Out(InitFnName);
2271*67e74705SXin Li       getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2272*67e74705SXin Li     }
2273*67e74705SXin Li 
2274*67e74705SXin Li     // If we have a definition for the variable, emit the initialization
2275*67e74705SXin Li     // function as an alias to the global Init function (if any). Otherwise,
2276*67e74705SXin Li     // produce a declaration of the initialization function.
2277*67e74705SXin Li     llvm::GlobalValue *Init = nullptr;
2278*67e74705SXin Li     bool InitIsInitFunc = false;
2279*67e74705SXin Li     if (VD->hasDefinition()) {
2280*67e74705SXin Li       InitIsInitFunc = true;
2281*67e74705SXin Li       if (InitFunc)
2282*67e74705SXin Li         Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2283*67e74705SXin Li                                          InitFunc);
2284*67e74705SXin Li     } else {
2285*67e74705SXin Li       // Emit a weak global function referring to the initialization function.
2286*67e74705SXin Li       // This function will not exist if the TU defining the thread_local
2287*67e74705SXin Li       // variable in question does not need any dynamic initialization for
2288*67e74705SXin Li       // its thread_local variables.
2289*67e74705SXin Li       llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2290*67e74705SXin Li       Init = llvm::Function::Create(
2291*67e74705SXin Li           FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
2292*67e74705SXin Li           &CGM.getModule());
2293*67e74705SXin Li       const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2294*67e74705SXin Li       CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
2295*67e74705SXin Li     }
2296*67e74705SXin Li 
2297*67e74705SXin Li     if (Init)
2298*67e74705SXin Li       Init->setVisibility(Var->getVisibility());
2299*67e74705SXin Li 
2300*67e74705SXin Li     llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2301*67e74705SXin Li     llvm::LLVMContext &Context = CGM.getModule().getContext();
2302*67e74705SXin Li     llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2303*67e74705SXin Li     CGBuilderTy Builder(CGM, Entry);
2304*67e74705SXin Li     if (InitIsInitFunc) {
2305*67e74705SXin Li       if (Init) {
2306*67e74705SXin Li         llvm::CallInst *CallVal = Builder.CreateCall(Init);
2307*67e74705SXin Li         if (isThreadWrapperReplaceable(VD, CGM))
2308*67e74705SXin Li           CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2309*67e74705SXin Li       }
2310*67e74705SXin Li     } else {
2311*67e74705SXin Li       // Don't know whether we have an init function. Call it if it exists.
2312*67e74705SXin Li       llvm::Value *Have = Builder.CreateIsNotNull(Init);
2313*67e74705SXin Li       llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2314*67e74705SXin Li       llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2315*67e74705SXin Li       Builder.CreateCondBr(Have, InitBB, ExitBB);
2316*67e74705SXin Li 
2317*67e74705SXin Li       Builder.SetInsertPoint(InitBB);
2318*67e74705SXin Li       Builder.CreateCall(Init);
2319*67e74705SXin Li       Builder.CreateBr(ExitBB);
2320*67e74705SXin Li 
2321*67e74705SXin Li       Builder.SetInsertPoint(ExitBB);
2322*67e74705SXin Li     }
2323*67e74705SXin Li 
2324*67e74705SXin Li     // For a reference, the result of the wrapper function is a pointer to
2325*67e74705SXin Li     // the referenced object.
2326*67e74705SXin Li     llvm::Value *Val = Var;
2327*67e74705SXin Li     if (VD->getType()->isReferenceType()) {
2328*67e74705SXin Li       CharUnits Align = CGM.getContext().getDeclAlign(VD);
2329*67e74705SXin Li       Val = Builder.CreateAlignedLoad(Val, Align);
2330*67e74705SXin Li     }
2331*67e74705SXin Li     if (Val->getType() != Wrapper->getReturnType())
2332*67e74705SXin Li       Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2333*67e74705SXin Li           Val, Wrapper->getReturnType(), "");
2334*67e74705SXin Li     Builder.CreateRet(Val);
2335*67e74705SXin Li   }
2336*67e74705SXin Li }
2337*67e74705SXin Li 
EmitThreadLocalVarDeclLValue(CodeGenFunction & CGF,const VarDecl * VD,QualType LValType)2338*67e74705SXin Li LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2339*67e74705SXin Li                                                    const VarDecl *VD,
2340*67e74705SXin Li                                                    QualType LValType) {
2341*67e74705SXin Li   llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
2342*67e74705SXin Li   llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
2343*67e74705SXin Li 
2344*67e74705SXin Li   llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
2345*67e74705SXin Li   if (isThreadWrapperReplaceable(VD, CGF.CGM))
2346*67e74705SXin Li     CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2347*67e74705SXin Li 
2348*67e74705SXin Li   LValue LV;
2349*67e74705SXin Li   if (VD->getType()->isReferenceType())
2350*67e74705SXin Li     LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
2351*67e74705SXin Li   else
2352*67e74705SXin Li     LV = CGF.MakeAddrLValue(CallVal, LValType,
2353*67e74705SXin Li                             CGF.getContext().getDeclAlign(VD));
2354*67e74705SXin Li   // FIXME: need setObjCGCLValueClass?
2355*67e74705SXin Li   return LV;
2356*67e74705SXin Li }
2357*67e74705SXin Li 
2358*67e74705SXin Li /// Return whether the given global decl needs a VTT parameter, which it does
2359*67e74705SXin Li /// if it's a base constructor or destructor with virtual bases.
NeedsVTTParameter(GlobalDecl GD)2360*67e74705SXin Li bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2361*67e74705SXin Li   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2362*67e74705SXin Li 
2363*67e74705SXin Li   // We don't have any virtual bases, just return early.
2364*67e74705SXin Li   if (!MD->getParent()->getNumVBases())
2365*67e74705SXin Li     return false;
2366*67e74705SXin Li 
2367*67e74705SXin Li   // Check if we have a base constructor.
2368*67e74705SXin Li   if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2369*67e74705SXin Li     return true;
2370*67e74705SXin Li 
2371*67e74705SXin Li   // Check if we have a base destructor.
2372*67e74705SXin Li   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2373*67e74705SXin Li     return true;
2374*67e74705SXin Li 
2375*67e74705SXin Li   return false;
2376*67e74705SXin Li }
2377*67e74705SXin Li 
2378*67e74705SXin Li namespace {
2379*67e74705SXin Li class ItaniumRTTIBuilder {
2380*67e74705SXin Li   CodeGenModule &CGM;  // Per-module state.
2381*67e74705SXin Li   llvm::LLVMContext &VMContext;
2382*67e74705SXin Li   const ItaniumCXXABI &CXXABI;  // Per-module state.
2383*67e74705SXin Li 
2384*67e74705SXin Li   /// Fields - The fields of the RTTI descriptor currently being built.
2385*67e74705SXin Li   SmallVector<llvm::Constant *, 16> Fields;
2386*67e74705SXin Li 
2387*67e74705SXin Li   /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2388*67e74705SXin Li   llvm::GlobalVariable *
2389*67e74705SXin Li   GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2390*67e74705SXin Li 
2391*67e74705SXin Li   /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2392*67e74705SXin Li   /// descriptor of the given type.
2393*67e74705SXin Li   llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2394*67e74705SXin Li 
2395*67e74705SXin Li   /// BuildVTablePointer - Build the vtable pointer for the given type.
2396*67e74705SXin Li   void BuildVTablePointer(const Type *Ty);
2397*67e74705SXin Li 
2398*67e74705SXin Li   /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2399*67e74705SXin Li   /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2400*67e74705SXin Li   void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2401*67e74705SXin Li 
2402*67e74705SXin Li   /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2403*67e74705SXin Li   /// classes with bases that do not satisfy the abi::__si_class_type_info
2404*67e74705SXin Li   /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2405*67e74705SXin Li   void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2406*67e74705SXin Li 
2407*67e74705SXin Li   /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2408*67e74705SXin Li   /// for pointer types.
2409*67e74705SXin Li   void BuildPointerTypeInfo(QualType PointeeTy);
2410*67e74705SXin Li 
2411*67e74705SXin Li   /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2412*67e74705SXin Li   /// type_info for an object type.
2413*67e74705SXin Li   void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2414*67e74705SXin Li 
2415*67e74705SXin Li   /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2416*67e74705SXin Li   /// struct, used for member pointer types.
2417*67e74705SXin Li   void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2418*67e74705SXin Li 
2419*67e74705SXin Li public:
ItaniumRTTIBuilder(const ItaniumCXXABI & ABI)2420*67e74705SXin Li   ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2421*67e74705SXin Li       : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2422*67e74705SXin Li 
2423*67e74705SXin Li   // Pointer type info flags.
2424*67e74705SXin Li   enum {
2425*67e74705SXin Li     /// PTI_Const - Type has const qualifier.
2426*67e74705SXin Li     PTI_Const = 0x1,
2427*67e74705SXin Li 
2428*67e74705SXin Li     /// PTI_Volatile - Type has volatile qualifier.
2429*67e74705SXin Li     PTI_Volatile = 0x2,
2430*67e74705SXin Li 
2431*67e74705SXin Li     /// PTI_Restrict - Type has restrict qualifier.
2432*67e74705SXin Li     PTI_Restrict = 0x4,
2433*67e74705SXin Li 
2434*67e74705SXin Li     /// PTI_Incomplete - Type is incomplete.
2435*67e74705SXin Li     PTI_Incomplete = 0x8,
2436*67e74705SXin Li 
2437*67e74705SXin Li     /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2438*67e74705SXin Li     /// (in pointer to member).
2439*67e74705SXin Li     PTI_ContainingClassIncomplete = 0x10
2440*67e74705SXin Li   };
2441*67e74705SXin Li 
2442*67e74705SXin Li   // VMI type info flags.
2443*67e74705SXin Li   enum {
2444*67e74705SXin Li     /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2445*67e74705SXin Li     VMI_NonDiamondRepeat = 0x1,
2446*67e74705SXin Li 
2447*67e74705SXin Li     /// VMI_DiamondShaped - Class is diamond shaped.
2448*67e74705SXin Li     VMI_DiamondShaped = 0x2
2449*67e74705SXin Li   };
2450*67e74705SXin Li 
2451*67e74705SXin Li   // Base class type info flags.
2452*67e74705SXin Li   enum {
2453*67e74705SXin Li     /// BCTI_Virtual - Base class is virtual.
2454*67e74705SXin Li     BCTI_Virtual = 0x1,
2455*67e74705SXin Li 
2456*67e74705SXin Li     /// BCTI_Public - Base class is public.
2457*67e74705SXin Li     BCTI_Public = 0x2
2458*67e74705SXin Li   };
2459*67e74705SXin Li 
2460*67e74705SXin Li   /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2461*67e74705SXin Li   ///
2462*67e74705SXin Li   /// \param Force - true to force the creation of this RTTI value
2463*67e74705SXin Li   llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2464*67e74705SXin Li };
2465*67e74705SXin Li }
2466*67e74705SXin Li 
GetAddrOfTypeName(QualType Ty,llvm::GlobalVariable::LinkageTypes Linkage)2467*67e74705SXin Li llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2468*67e74705SXin Li     QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2469*67e74705SXin Li   SmallString<256> Name;
2470*67e74705SXin Li   llvm::raw_svector_ostream Out(Name);
2471*67e74705SXin Li   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2472*67e74705SXin Li 
2473*67e74705SXin Li   // We know that the mangled name of the type starts at index 4 of the
2474*67e74705SXin Li   // mangled name of the typename, so we can just index into it in order to
2475*67e74705SXin Li   // get the mangled name of the type.
2476*67e74705SXin Li   llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2477*67e74705SXin Li                                                             Name.substr(4));
2478*67e74705SXin Li 
2479*67e74705SXin Li   llvm::GlobalVariable *GV =
2480*67e74705SXin Li     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2481*67e74705SXin Li 
2482*67e74705SXin Li   GV->setInitializer(Init);
2483*67e74705SXin Li 
2484*67e74705SXin Li   return GV;
2485*67e74705SXin Li }
2486*67e74705SXin Li 
2487*67e74705SXin Li llvm::Constant *
GetAddrOfExternalRTTIDescriptor(QualType Ty)2488*67e74705SXin Li ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2489*67e74705SXin Li   // Mangle the RTTI name.
2490*67e74705SXin Li   SmallString<256> Name;
2491*67e74705SXin Li   llvm::raw_svector_ostream Out(Name);
2492*67e74705SXin Li   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2493*67e74705SXin Li 
2494*67e74705SXin Li   // Look for an existing global.
2495*67e74705SXin Li   llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2496*67e74705SXin Li 
2497*67e74705SXin Li   if (!GV) {
2498*67e74705SXin Li     // Create a new global variable.
2499*67e74705SXin Li     GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2500*67e74705SXin Li                                   /*Constant=*/true,
2501*67e74705SXin Li                                   llvm::GlobalValue::ExternalLinkage, nullptr,
2502*67e74705SXin Li                                   Name);
2503*67e74705SXin Li     if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2504*67e74705SXin Li       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2505*67e74705SXin Li       if (RD->hasAttr<DLLImportAttr>())
2506*67e74705SXin Li         GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2507*67e74705SXin Li     }
2508*67e74705SXin Li   }
2509*67e74705SXin Li 
2510*67e74705SXin Li   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2511*67e74705SXin Li }
2512*67e74705SXin Li 
2513*67e74705SXin Li /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2514*67e74705SXin Li /// info for that type is defined in the standard library.
TypeInfoIsInStandardLibrary(const BuiltinType * Ty)2515*67e74705SXin Li static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2516*67e74705SXin Li   // Itanium C++ ABI 2.9.2:
2517*67e74705SXin Li   //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
2518*67e74705SXin Li   //   the run-time support library. Specifically, the run-time support
2519*67e74705SXin Li   //   library should contain type_info objects for the types X, X* and
2520*67e74705SXin Li   //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2521*67e74705SXin Li   //   unsigned char, signed char, short, unsigned short, int, unsigned int,
2522*67e74705SXin Li   //   long, unsigned long, long long, unsigned long long, float, double,
2523*67e74705SXin Li   //   long double, char16_t, char32_t, and the IEEE 754r decimal and
2524*67e74705SXin Li   //   half-precision floating point types.
2525*67e74705SXin Li   //
2526*67e74705SXin Li   // GCC also emits RTTI for __int128.
2527*67e74705SXin Li   // FIXME: We do not emit RTTI information for decimal types here.
2528*67e74705SXin Li 
2529*67e74705SXin Li   // Types added here must also be added to EmitFundamentalRTTIDescriptors.
2530*67e74705SXin Li   switch (Ty->getKind()) {
2531*67e74705SXin Li     case BuiltinType::Void:
2532*67e74705SXin Li     case BuiltinType::NullPtr:
2533*67e74705SXin Li     case BuiltinType::Bool:
2534*67e74705SXin Li     case BuiltinType::WChar_S:
2535*67e74705SXin Li     case BuiltinType::WChar_U:
2536*67e74705SXin Li     case BuiltinType::Char_U:
2537*67e74705SXin Li     case BuiltinType::Char_S:
2538*67e74705SXin Li     case BuiltinType::UChar:
2539*67e74705SXin Li     case BuiltinType::SChar:
2540*67e74705SXin Li     case BuiltinType::Short:
2541*67e74705SXin Li     case BuiltinType::UShort:
2542*67e74705SXin Li     case BuiltinType::Int:
2543*67e74705SXin Li     case BuiltinType::UInt:
2544*67e74705SXin Li     case BuiltinType::Long:
2545*67e74705SXin Li     case BuiltinType::ULong:
2546*67e74705SXin Li     case BuiltinType::LongLong:
2547*67e74705SXin Li     case BuiltinType::ULongLong:
2548*67e74705SXin Li     case BuiltinType::Half:
2549*67e74705SXin Li     case BuiltinType::Float:
2550*67e74705SXin Li     case BuiltinType::Double:
2551*67e74705SXin Li     case BuiltinType::LongDouble:
2552*67e74705SXin Li     case BuiltinType::Float128:
2553*67e74705SXin Li     case BuiltinType::Char16:
2554*67e74705SXin Li     case BuiltinType::Char32:
2555*67e74705SXin Li     case BuiltinType::Int128:
2556*67e74705SXin Li     case BuiltinType::UInt128:
2557*67e74705SXin Li       return true;
2558*67e74705SXin Li 
2559*67e74705SXin Li #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2560*67e74705SXin Li     case BuiltinType::Id:
2561*67e74705SXin Li #include "clang/Basic/OpenCLImageTypes.def"
2562*67e74705SXin Li     case BuiltinType::OCLSampler:
2563*67e74705SXin Li     case BuiltinType::OCLEvent:
2564*67e74705SXin Li     case BuiltinType::OCLClkEvent:
2565*67e74705SXin Li     case BuiltinType::OCLQueue:
2566*67e74705SXin Li     case BuiltinType::OCLNDRange:
2567*67e74705SXin Li     case BuiltinType::OCLReserveID:
2568*67e74705SXin Li       return false;
2569*67e74705SXin Li 
2570*67e74705SXin Li     case BuiltinType::Dependent:
2571*67e74705SXin Li #define BUILTIN_TYPE(Id, SingletonId)
2572*67e74705SXin Li #define PLACEHOLDER_TYPE(Id, SingletonId) \
2573*67e74705SXin Li     case BuiltinType::Id:
2574*67e74705SXin Li #include "clang/AST/BuiltinTypes.def"
2575*67e74705SXin Li       llvm_unreachable("asking for RRTI for a placeholder type!");
2576*67e74705SXin Li 
2577*67e74705SXin Li     case BuiltinType::ObjCId:
2578*67e74705SXin Li     case BuiltinType::ObjCClass:
2579*67e74705SXin Li     case BuiltinType::ObjCSel:
2580*67e74705SXin Li       llvm_unreachable("FIXME: Objective-C types are unsupported!");
2581*67e74705SXin Li   }
2582*67e74705SXin Li 
2583*67e74705SXin Li   llvm_unreachable("Invalid BuiltinType Kind!");
2584*67e74705SXin Li }
2585*67e74705SXin Li 
TypeInfoIsInStandardLibrary(const PointerType * PointerTy)2586*67e74705SXin Li static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2587*67e74705SXin Li   QualType PointeeTy = PointerTy->getPointeeType();
2588*67e74705SXin Li   const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2589*67e74705SXin Li   if (!BuiltinTy)
2590*67e74705SXin Li     return false;
2591*67e74705SXin Li 
2592*67e74705SXin Li   // Check the qualifiers.
2593*67e74705SXin Li   Qualifiers Quals = PointeeTy.getQualifiers();
2594*67e74705SXin Li   Quals.removeConst();
2595*67e74705SXin Li 
2596*67e74705SXin Li   if (!Quals.empty())
2597*67e74705SXin Li     return false;
2598*67e74705SXin Li 
2599*67e74705SXin Li   return TypeInfoIsInStandardLibrary(BuiltinTy);
2600*67e74705SXin Li }
2601*67e74705SXin Li 
2602*67e74705SXin Li /// IsStandardLibraryRTTIDescriptor - Returns whether the type
2603*67e74705SXin Li /// information for the given type exists in the standard library.
IsStandardLibraryRTTIDescriptor(QualType Ty)2604*67e74705SXin Li static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2605*67e74705SXin Li   // Type info for builtin types is defined in the standard library.
2606*67e74705SXin Li   if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2607*67e74705SXin Li     return TypeInfoIsInStandardLibrary(BuiltinTy);
2608*67e74705SXin Li 
2609*67e74705SXin Li   // Type info for some pointer types to builtin types is defined in the
2610*67e74705SXin Li   // standard library.
2611*67e74705SXin Li   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2612*67e74705SXin Li     return TypeInfoIsInStandardLibrary(PointerTy);
2613*67e74705SXin Li 
2614*67e74705SXin Li   return false;
2615*67e74705SXin Li }
2616*67e74705SXin Li 
2617*67e74705SXin Li /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2618*67e74705SXin Li /// the given type exists somewhere else, and that we should not emit the type
2619*67e74705SXin Li /// information in this translation unit.  Assumes that it is not a
2620*67e74705SXin Li /// standard-library type.
ShouldUseExternalRTTIDescriptor(CodeGenModule & CGM,QualType Ty)2621*67e74705SXin Li static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2622*67e74705SXin Li                                             QualType Ty) {
2623*67e74705SXin Li   ASTContext &Context = CGM.getContext();
2624*67e74705SXin Li 
2625*67e74705SXin Li   // If RTTI is disabled, assume it might be disabled in the
2626*67e74705SXin Li   // translation unit that defines any potential key function, too.
2627*67e74705SXin Li   if (!Context.getLangOpts().RTTI) return false;
2628*67e74705SXin Li 
2629*67e74705SXin Li   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2630*67e74705SXin Li     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2631*67e74705SXin Li     if (!RD->hasDefinition())
2632*67e74705SXin Li       return false;
2633*67e74705SXin Li 
2634*67e74705SXin Li     if (!RD->isDynamicClass())
2635*67e74705SXin Li       return false;
2636*67e74705SXin Li 
2637*67e74705SXin Li     // FIXME: this may need to be reconsidered if the key function
2638*67e74705SXin Li     // changes.
2639*67e74705SXin Li     // N.B. We must always emit the RTTI data ourselves if there exists a key
2640*67e74705SXin Li     // function.
2641*67e74705SXin Li     bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
2642*67e74705SXin Li     if (CGM.getVTables().isVTableExternal(RD))
2643*67e74705SXin Li       return IsDLLImport ? false : true;
2644*67e74705SXin Li 
2645*67e74705SXin Li     if (IsDLLImport)
2646*67e74705SXin Li       return true;
2647*67e74705SXin Li   }
2648*67e74705SXin Li 
2649*67e74705SXin Li   return false;
2650*67e74705SXin Li }
2651*67e74705SXin Li 
2652*67e74705SXin Li /// IsIncompleteClassType - Returns whether the given record type is incomplete.
IsIncompleteClassType(const RecordType * RecordTy)2653*67e74705SXin Li static bool IsIncompleteClassType(const RecordType *RecordTy) {
2654*67e74705SXin Li   return !RecordTy->getDecl()->isCompleteDefinition();
2655*67e74705SXin Li }
2656*67e74705SXin Li 
2657*67e74705SXin Li /// ContainsIncompleteClassType - Returns whether the given type contains an
2658*67e74705SXin Li /// incomplete class type. This is true if
2659*67e74705SXin Li ///
2660*67e74705SXin Li ///   * The given type is an incomplete class type.
2661*67e74705SXin Li ///   * The given type is a pointer type whose pointee type contains an
2662*67e74705SXin Li ///     incomplete class type.
2663*67e74705SXin Li ///   * The given type is a member pointer type whose class is an incomplete
2664*67e74705SXin Li ///     class type.
2665*67e74705SXin Li ///   * The given type is a member pointer type whoise pointee type contains an
2666*67e74705SXin Li ///     incomplete class type.
2667*67e74705SXin Li /// is an indirect or direct pointer to an incomplete class type.
ContainsIncompleteClassType(QualType Ty)2668*67e74705SXin Li static bool ContainsIncompleteClassType(QualType Ty) {
2669*67e74705SXin Li   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2670*67e74705SXin Li     if (IsIncompleteClassType(RecordTy))
2671*67e74705SXin Li       return true;
2672*67e74705SXin Li   }
2673*67e74705SXin Li 
2674*67e74705SXin Li   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2675*67e74705SXin Li     return ContainsIncompleteClassType(PointerTy->getPointeeType());
2676*67e74705SXin Li 
2677*67e74705SXin Li   if (const MemberPointerType *MemberPointerTy =
2678*67e74705SXin Li       dyn_cast<MemberPointerType>(Ty)) {
2679*67e74705SXin Li     // Check if the class type is incomplete.
2680*67e74705SXin Li     const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2681*67e74705SXin Li     if (IsIncompleteClassType(ClassType))
2682*67e74705SXin Li       return true;
2683*67e74705SXin Li 
2684*67e74705SXin Li     return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2685*67e74705SXin Li   }
2686*67e74705SXin Li 
2687*67e74705SXin Li   return false;
2688*67e74705SXin Li }
2689*67e74705SXin Li 
2690*67e74705SXin Li // CanUseSingleInheritance - Return whether the given record decl has a "single,
2691*67e74705SXin Li // public, non-virtual base at offset zero (i.e. the derived class is dynamic
2692*67e74705SXin Li // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
CanUseSingleInheritance(const CXXRecordDecl * RD)2693*67e74705SXin Li static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2694*67e74705SXin Li   // Check the number of bases.
2695*67e74705SXin Li   if (RD->getNumBases() != 1)
2696*67e74705SXin Li     return false;
2697*67e74705SXin Li 
2698*67e74705SXin Li   // Get the base.
2699*67e74705SXin Li   CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2700*67e74705SXin Li 
2701*67e74705SXin Li   // Check that the base is not virtual.
2702*67e74705SXin Li   if (Base->isVirtual())
2703*67e74705SXin Li     return false;
2704*67e74705SXin Li 
2705*67e74705SXin Li   // Check that the base is public.
2706*67e74705SXin Li   if (Base->getAccessSpecifier() != AS_public)
2707*67e74705SXin Li     return false;
2708*67e74705SXin Li 
2709*67e74705SXin Li   // Check that the class is dynamic iff the base is.
2710*67e74705SXin Li   const CXXRecordDecl *BaseDecl =
2711*67e74705SXin Li     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2712*67e74705SXin Li   if (!BaseDecl->isEmpty() &&
2713*67e74705SXin Li       BaseDecl->isDynamicClass() != RD->isDynamicClass())
2714*67e74705SXin Li     return false;
2715*67e74705SXin Li 
2716*67e74705SXin Li   return true;
2717*67e74705SXin Li }
2718*67e74705SXin Li 
BuildVTablePointer(const Type * Ty)2719*67e74705SXin Li void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2720*67e74705SXin Li   // abi::__class_type_info.
2721*67e74705SXin Li   static const char * const ClassTypeInfo =
2722*67e74705SXin Li     "_ZTVN10__cxxabiv117__class_type_infoE";
2723*67e74705SXin Li   // abi::__si_class_type_info.
2724*67e74705SXin Li   static const char * const SIClassTypeInfo =
2725*67e74705SXin Li     "_ZTVN10__cxxabiv120__si_class_type_infoE";
2726*67e74705SXin Li   // abi::__vmi_class_type_info.
2727*67e74705SXin Li   static const char * const VMIClassTypeInfo =
2728*67e74705SXin Li     "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2729*67e74705SXin Li 
2730*67e74705SXin Li   const char *VTableName = nullptr;
2731*67e74705SXin Li 
2732*67e74705SXin Li   switch (Ty->getTypeClass()) {
2733*67e74705SXin Li #define TYPE(Class, Base)
2734*67e74705SXin Li #define ABSTRACT_TYPE(Class, Base)
2735*67e74705SXin Li #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2736*67e74705SXin Li #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2737*67e74705SXin Li #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2738*67e74705SXin Li #include "clang/AST/TypeNodes.def"
2739*67e74705SXin Li     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2740*67e74705SXin Li 
2741*67e74705SXin Li   case Type::LValueReference:
2742*67e74705SXin Li   case Type::RValueReference:
2743*67e74705SXin Li     llvm_unreachable("References shouldn't get here");
2744*67e74705SXin Li 
2745*67e74705SXin Li   case Type::Auto:
2746*67e74705SXin Li     llvm_unreachable("Undeduced auto type shouldn't get here");
2747*67e74705SXin Li 
2748*67e74705SXin Li   case Type::Pipe:
2749*67e74705SXin Li     llvm_unreachable("Pipe types shouldn't get here");
2750*67e74705SXin Li 
2751*67e74705SXin Li   case Type::Builtin:
2752*67e74705SXin Li   // GCC treats vector and complex types as fundamental types.
2753*67e74705SXin Li   case Type::Vector:
2754*67e74705SXin Li   case Type::ExtVector:
2755*67e74705SXin Li   case Type::Complex:
2756*67e74705SXin Li   case Type::Atomic:
2757*67e74705SXin Li   // FIXME: GCC treats block pointers as fundamental types?!
2758*67e74705SXin Li   case Type::BlockPointer:
2759*67e74705SXin Li     // abi::__fundamental_type_info.
2760*67e74705SXin Li     VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2761*67e74705SXin Li     break;
2762*67e74705SXin Li 
2763*67e74705SXin Li   case Type::ConstantArray:
2764*67e74705SXin Li   case Type::IncompleteArray:
2765*67e74705SXin Li   case Type::VariableArray:
2766*67e74705SXin Li     // abi::__array_type_info.
2767*67e74705SXin Li     VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2768*67e74705SXin Li     break;
2769*67e74705SXin Li 
2770*67e74705SXin Li   case Type::FunctionNoProto:
2771*67e74705SXin Li   case Type::FunctionProto:
2772*67e74705SXin Li     // abi::__function_type_info.
2773*67e74705SXin Li     VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2774*67e74705SXin Li     break;
2775*67e74705SXin Li 
2776*67e74705SXin Li   case Type::Enum:
2777*67e74705SXin Li     // abi::__enum_type_info.
2778*67e74705SXin Li     VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2779*67e74705SXin Li     break;
2780*67e74705SXin Li 
2781*67e74705SXin Li   case Type::Record: {
2782*67e74705SXin Li     const CXXRecordDecl *RD =
2783*67e74705SXin Li       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2784*67e74705SXin Li 
2785*67e74705SXin Li     if (!RD->hasDefinition() || !RD->getNumBases()) {
2786*67e74705SXin Li       VTableName = ClassTypeInfo;
2787*67e74705SXin Li     } else if (CanUseSingleInheritance(RD)) {
2788*67e74705SXin Li       VTableName = SIClassTypeInfo;
2789*67e74705SXin Li     } else {
2790*67e74705SXin Li       VTableName = VMIClassTypeInfo;
2791*67e74705SXin Li     }
2792*67e74705SXin Li 
2793*67e74705SXin Li     break;
2794*67e74705SXin Li   }
2795*67e74705SXin Li 
2796*67e74705SXin Li   case Type::ObjCObject:
2797*67e74705SXin Li     // Ignore protocol qualifiers.
2798*67e74705SXin Li     Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2799*67e74705SXin Li 
2800*67e74705SXin Li     // Handle id and Class.
2801*67e74705SXin Li     if (isa<BuiltinType>(Ty)) {
2802*67e74705SXin Li       VTableName = ClassTypeInfo;
2803*67e74705SXin Li       break;
2804*67e74705SXin Li     }
2805*67e74705SXin Li 
2806*67e74705SXin Li     assert(isa<ObjCInterfaceType>(Ty));
2807*67e74705SXin Li     // Fall through.
2808*67e74705SXin Li 
2809*67e74705SXin Li   case Type::ObjCInterface:
2810*67e74705SXin Li     if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2811*67e74705SXin Li       VTableName = SIClassTypeInfo;
2812*67e74705SXin Li     } else {
2813*67e74705SXin Li       VTableName = ClassTypeInfo;
2814*67e74705SXin Li     }
2815*67e74705SXin Li     break;
2816*67e74705SXin Li 
2817*67e74705SXin Li   case Type::ObjCObjectPointer:
2818*67e74705SXin Li   case Type::Pointer:
2819*67e74705SXin Li     // abi::__pointer_type_info.
2820*67e74705SXin Li     VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2821*67e74705SXin Li     break;
2822*67e74705SXin Li 
2823*67e74705SXin Li   case Type::MemberPointer:
2824*67e74705SXin Li     // abi::__pointer_to_member_type_info.
2825*67e74705SXin Li     VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2826*67e74705SXin Li     break;
2827*67e74705SXin Li   }
2828*67e74705SXin Li 
2829*67e74705SXin Li   llvm::Constant *VTable =
2830*67e74705SXin Li     CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2831*67e74705SXin Li 
2832*67e74705SXin Li   llvm::Type *PtrDiffTy =
2833*67e74705SXin Li     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2834*67e74705SXin Li 
2835*67e74705SXin Li   // The vtable address point is 2.
2836*67e74705SXin Li   llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2837*67e74705SXin Li   VTable =
2838*67e74705SXin Li       llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
2839*67e74705SXin Li   VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2840*67e74705SXin Li 
2841*67e74705SXin Li   Fields.push_back(VTable);
2842*67e74705SXin Li }
2843*67e74705SXin Li 
2844*67e74705SXin Li /// \brief Return the linkage that the type info and type info name constants
2845*67e74705SXin Li /// should have for the given type.
getTypeInfoLinkage(CodeGenModule & CGM,QualType Ty)2846*67e74705SXin Li static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2847*67e74705SXin Li                                                              QualType Ty) {
2848*67e74705SXin Li   // Itanium C++ ABI 2.9.5p7:
2849*67e74705SXin Li   //   In addition, it and all of the intermediate abi::__pointer_type_info
2850*67e74705SXin Li   //   structs in the chain down to the abi::__class_type_info for the
2851*67e74705SXin Li   //   incomplete class type must be prevented from resolving to the
2852*67e74705SXin Li   //   corresponding type_info structs for the complete class type, possibly
2853*67e74705SXin Li   //   by making them local static objects. Finally, a dummy class RTTI is
2854*67e74705SXin Li   //   generated for the incomplete type that will not resolve to the final
2855*67e74705SXin Li   //   complete class RTTI (because the latter need not exist), possibly by
2856*67e74705SXin Li   //   making it a local static object.
2857*67e74705SXin Li   if (ContainsIncompleteClassType(Ty))
2858*67e74705SXin Li     return llvm::GlobalValue::InternalLinkage;
2859*67e74705SXin Li 
2860*67e74705SXin Li   switch (Ty->getLinkage()) {
2861*67e74705SXin Li   case NoLinkage:
2862*67e74705SXin Li   case InternalLinkage:
2863*67e74705SXin Li   case UniqueExternalLinkage:
2864*67e74705SXin Li     return llvm::GlobalValue::InternalLinkage;
2865*67e74705SXin Li 
2866*67e74705SXin Li   case VisibleNoLinkage:
2867*67e74705SXin Li   case ExternalLinkage:
2868*67e74705SXin Li     if (!CGM.getLangOpts().RTTI) {
2869*67e74705SXin Li       // RTTI is not enabled, which means that this type info struct is going
2870*67e74705SXin Li       // to be used for exception handling. Give it linkonce_odr linkage.
2871*67e74705SXin Li       return llvm::GlobalValue::LinkOnceODRLinkage;
2872*67e74705SXin Li     }
2873*67e74705SXin Li 
2874*67e74705SXin Li     if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2875*67e74705SXin Li       const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2876*67e74705SXin Li       if (RD->hasAttr<WeakAttr>())
2877*67e74705SXin Li         return llvm::GlobalValue::WeakODRLinkage;
2878*67e74705SXin Li       if (RD->isDynamicClass()) {
2879*67e74705SXin Li         llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2880*67e74705SXin Li         // MinGW won't export the RTTI information when there is a key function.
2881*67e74705SXin Li         // Make sure we emit our own copy instead of attempting to dllimport it.
2882*67e74705SXin Li         if (RD->hasAttr<DLLImportAttr>() &&
2883*67e74705SXin Li             llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2884*67e74705SXin Li           LT = llvm::GlobalValue::LinkOnceODRLinkage;
2885*67e74705SXin Li         return LT;
2886*67e74705SXin Li       }
2887*67e74705SXin Li     }
2888*67e74705SXin Li 
2889*67e74705SXin Li     return llvm::GlobalValue::LinkOnceODRLinkage;
2890*67e74705SXin Li   }
2891*67e74705SXin Li 
2892*67e74705SXin Li   llvm_unreachable("Invalid linkage!");
2893*67e74705SXin Li }
2894*67e74705SXin Li 
BuildTypeInfo(QualType Ty,bool Force)2895*67e74705SXin Li llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2896*67e74705SXin Li   // We want to operate on the canonical type.
2897*67e74705SXin Li   Ty = Ty.getCanonicalType();
2898*67e74705SXin Li 
2899*67e74705SXin Li   // Check if we've already emitted an RTTI descriptor for this type.
2900*67e74705SXin Li   SmallString<256> Name;
2901*67e74705SXin Li   llvm::raw_svector_ostream Out(Name);
2902*67e74705SXin Li   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2903*67e74705SXin Li 
2904*67e74705SXin Li   llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2905*67e74705SXin Li   if (OldGV && !OldGV->isDeclaration()) {
2906*67e74705SXin Li     assert(!OldGV->hasAvailableExternallyLinkage() &&
2907*67e74705SXin Li            "available_externally typeinfos not yet implemented");
2908*67e74705SXin Li 
2909*67e74705SXin Li     return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2910*67e74705SXin Li   }
2911*67e74705SXin Li 
2912*67e74705SXin Li   // Check if there is already an external RTTI descriptor for this type.
2913*67e74705SXin Li   bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2914*67e74705SXin Li   if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2915*67e74705SXin Li     return GetAddrOfExternalRTTIDescriptor(Ty);
2916*67e74705SXin Li 
2917*67e74705SXin Li   // Emit the standard library with external linkage.
2918*67e74705SXin Li   llvm::GlobalVariable::LinkageTypes Linkage;
2919*67e74705SXin Li   if (IsStdLib)
2920*67e74705SXin Li     Linkage = llvm::GlobalValue::ExternalLinkage;
2921*67e74705SXin Li   else
2922*67e74705SXin Li     Linkage = getTypeInfoLinkage(CGM, Ty);
2923*67e74705SXin Li 
2924*67e74705SXin Li   // Add the vtable pointer.
2925*67e74705SXin Li   BuildVTablePointer(cast<Type>(Ty));
2926*67e74705SXin Li 
2927*67e74705SXin Li   // And the name.
2928*67e74705SXin Li   llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2929*67e74705SXin Li   llvm::Constant *TypeNameField;
2930*67e74705SXin Li 
2931*67e74705SXin Li   // If we're supposed to demote the visibility, be sure to set a flag
2932*67e74705SXin Li   // to use a string comparison for type_info comparisons.
2933*67e74705SXin Li   ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2934*67e74705SXin Li       CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2935*67e74705SXin Li   if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2936*67e74705SXin Li     // The flag is the sign bit, which on ARM64 is defined to be clear
2937*67e74705SXin Li     // for global pointers.  This is very ARM64-specific.
2938*67e74705SXin Li     TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2939*67e74705SXin Li     llvm::Constant *flag =
2940*67e74705SXin Li         llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2941*67e74705SXin Li     TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2942*67e74705SXin Li     TypeNameField =
2943*67e74705SXin Li         llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2944*67e74705SXin Li   } else {
2945*67e74705SXin Li     TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2946*67e74705SXin Li   }
2947*67e74705SXin Li   Fields.push_back(TypeNameField);
2948*67e74705SXin Li 
2949*67e74705SXin Li   switch (Ty->getTypeClass()) {
2950*67e74705SXin Li #define TYPE(Class, Base)
2951*67e74705SXin Li #define ABSTRACT_TYPE(Class, Base)
2952*67e74705SXin Li #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2953*67e74705SXin Li #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2954*67e74705SXin Li #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2955*67e74705SXin Li #include "clang/AST/TypeNodes.def"
2956*67e74705SXin Li     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2957*67e74705SXin Li 
2958*67e74705SXin Li   // GCC treats vector types as fundamental types.
2959*67e74705SXin Li   case Type::Builtin:
2960*67e74705SXin Li   case Type::Vector:
2961*67e74705SXin Li   case Type::ExtVector:
2962*67e74705SXin Li   case Type::Complex:
2963*67e74705SXin Li   case Type::BlockPointer:
2964*67e74705SXin Li     // Itanium C++ ABI 2.9.5p4:
2965*67e74705SXin Li     // abi::__fundamental_type_info adds no data members to std::type_info.
2966*67e74705SXin Li     break;
2967*67e74705SXin Li 
2968*67e74705SXin Li   case Type::LValueReference:
2969*67e74705SXin Li   case Type::RValueReference:
2970*67e74705SXin Li     llvm_unreachable("References shouldn't get here");
2971*67e74705SXin Li 
2972*67e74705SXin Li   case Type::Auto:
2973*67e74705SXin Li     llvm_unreachable("Undeduced auto type shouldn't get here");
2974*67e74705SXin Li 
2975*67e74705SXin Li   case Type::Pipe:
2976*67e74705SXin Li     llvm_unreachable("Pipe type shouldn't get here");
2977*67e74705SXin Li 
2978*67e74705SXin Li   case Type::ConstantArray:
2979*67e74705SXin Li   case Type::IncompleteArray:
2980*67e74705SXin Li   case Type::VariableArray:
2981*67e74705SXin Li     // Itanium C++ ABI 2.9.5p5:
2982*67e74705SXin Li     // abi::__array_type_info adds no data members to std::type_info.
2983*67e74705SXin Li     break;
2984*67e74705SXin Li 
2985*67e74705SXin Li   case Type::FunctionNoProto:
2986*67e74705SXin Li   case Type::FunctionProto:
2987*67e74705SXin Li     // Itanium C++ ABI 2.9.5p5:
2988*67e74705SXin Li     // abi::__function_type_info adds no data members to std::type_info.
2989*67e74705SXin Li     break;
2990*67e74705SXin Li 
2991*67e74705SXin Li   case Type::Enum:
2992*67e74705SXin Li     // Itanium C++ ABI 2.9.5p5:
2993*67e74705SXin Li     // abi::__enum_type_info adds no data members to std::type_info.
2994*67e74705SXin Li     break;
2995*67e74705SXin Li 
2996*67e74705SXin Li   case Type::Record: {
2997*67e74705SXin Li     const CXXRecordDecl *RD =
2998*67e74705SXin Li       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2999*67e74705SXin Li     if (!RD->hasDefinition() || !RD->getNumBases()) {
3000*67e74705SXin Li       // We don't need to emit any fields.
3001*67e74705SXin Li       break;
3002*67e74705SXin Li     }
3003*67e74705SXin Li 
3004*67e74705SXin Li     if (CanUseSingleInheritance(RD))
3005*67e74705SXin Li       BuildSIClassTypeInfo(RD);
3006*67e74705SXin Li     else
3007*67e74705SXin Li       BuildVMIClassTypeInfo(RD);
3008*67e74705SXin Li 
3009*67e74705SXin Li     break;
3010*67e74705SXin Li   }
3011*67e74705SXin Li 
3012*67e74705SXin Li   case Type::ObjCObject:
3013*67e74705SXin Li   case Type::ObjCInterface:
3014*67e74705SXin Li     BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3015*67e74705SXin Li     break;
3016*67e74705SXin Li 
3017*67e74705SXin Li   case Type::ObjCObjectPointer:
3018*67e74705SXin Li     BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3019*67e74705SXin Li     break;
3020*67e74705SXin Li 
3021*67e74705SXin Li   case Type::Pointer:
3022*67e74705SXin Li     BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3023*67e74705SXin Li     break;
3024*67e74705SXin Li 
3025*67e74705SXin Li   case Type::MemberPointer:
3026*67e74705SXin Li     BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3027*67e74705SXin Li     break;
3028*67e74705SXin Li 
3029*67e74705SXin Li   case Type::Atomic:
3030*67e74705SXin Li     // No fields, at least for the moment.
3031*67e74705SXin Li     break;
3032*67e74705SXin Li   }
3033*67e74705SXin Li 
3034*67e74705SXin Li   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3035*67e74705SXin Li 
3036*67e74705SXin Li   llvm::Module &M = CGM.getModule();
3037*67e74705SXin Li   llvm::GlobalVariable *GV =
3038*67e74705SXin Li       new llvm::GlobalVariable(M, Init->getType(),
3039*67e74705SXin Li                                /*Constant=*/true, Linkage, Init, Name);
3040*67e74705SXin Li 
3041*67e74705SXin Li   // If there's already an old global variable, replace it with the new one.
3042*67e74705SXin Li   if (OldGV) {
3043*67e74705SXin Li     GV->takeName(OldGV);
3044*67e74705SXin Li     llvm::Constant *NewPtr =
3045*67e74705SXin Li       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3046*67e74705SXin Li     OldGV->replaceAllUsesWith(NewPtr);
3047*67e74705SXin Li     OldGV->eraseFromParent();
3048*67e74705SXin Li   }
3049*67e74705SXin Li 
3050*67e74705SXin Li   if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3051*67e74705SXin Li     GV->setComdat(M.getOrInsertComdat(GV->getName()));
3052*67e74705SXin Li 
3053*67e74705SXin Li   // The Itanium ABI specifies that type_info objects must be globally
3054*67e74705SXin Li   // unique, with one exception: if the type is an incomplete class
3055*67e74705SXin Li   // type or a (possibly indirect) pointer to one.  That exception
3056*67e74705SXin Li   // affects the general case of comparing type_info objects produced
3057*67e74705SXin Li   // by the typeid operator, which is why the comparison operators on
3058*67e74705SXin Li   // std::type_info generally use the type_info name pointers instead
3059*67e74705SXin Li   // of the object addresses.  However, the language's built-in uses
3060*67e74705SXin Li   // of RTTI generally require class types to be complete, even when
3061*67e74705SXin Li   // manipulating pointers to those class types.  This allows the
3062*67e74705SXin Li   // implementation of dynamic_cast to rely on address equality tests,
3063*67e74705SXin Li   // which is much faster.
3064*67e74705SXin Li 
3065*67e74705SXin Li   // All of this is to say that it's important that both the type_info
3066*67e74705SXin Li   // object and the type_info name be uniqued when weakly emitted.
3067*67e74705SXin Li 
3068*67e74705SXin Li   // Give the type_info object and name the formal visibility of the
3069*67e74705SXin Li   // type itself.
3070*67e74705SXin Li   llvm::GlobalValue::VisibilityTypes llvmVisibility;
3071*67e74705SXin Li   if (llvm::GlobalValue::isLocalLinkage(Linkage))
3072*67e74705SXin Li     // If the linkage is local, only default visibility makes sense.
3073*67e74705SXin Li     llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3074*67e74705SXin Li   else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3075*67e74705SXin Li     llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3076*67e74705SXin Li   else
3077*67e74705SXin Li     llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3078*67e74705SXin Li   TypeName->setVisibility(llvmVisibility);
3079*67e74705SXin Li   GV->setVisibility(llvmVisibility);
3080*67e74705SXin Li 
3081*67e74705SXin Li   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3082*67e74705SXin Li }
3083*67e74705SXin Li 
3084*67e74705SXin Li /// ComputeQualifierFlags - Compute the pointer type info flags from the
3085*67e74705SXin Li /// given qualifier.
ComputeQualifierFlags(Qualifiers Quals)3086*67e74705SXin Li static unsigned ComputeQualifierFlags(Qualifiers Quals) {
3087*67e74705SXin Li   unsigned Flags = 0;
3088*67e74705SXin Li 
3089*67e74705SXin Li   if (Quals.hasConst())
3090*67e74705SXin Li     Flags |= ItaniumRTTIBuilder::PTI_Const;
3091*67e74705SXin Li   if (Quals.hasVolatile())
3092*67e74705SXin Li     Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3093*67e74705SXin Li   if (Quals.hasRestrict())
3094*67e74705SXin Li     Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3095*67e74705SXin Li 
3096*67e74705SXin Li   return Flags;
3097*67e74705SXin Li }
3098*67e74705SXin Li 
3099*67e74705SXin Li /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3100*67e74705SXin Li /// for the given Objective-C object type.
BuildObjCObjectTypeInfo(const ObjCObjectType * OT)3101*67e74705SXin Li void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3102*67e74705SXin Li   // Drop qualifiers.
3103*67e74705SXin Li   const Type *T = OT->getBaseType().getTypePtr();
3104*67e74705SXin Li   assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3105*67e74705SXin Li 
3106*67e74705SXin Li   // The builtin types are abi::__class_type_infos and don't require
3107*67e74705SXin Li   // extra fields.
3108*67e74705SXin Li   if (isa<BuiltinType>(T)) return;
3109*67e74705SXin Li 
3110*67e74705SXin Li   ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3111*67e74705SXin Li   ObjCInterfaceDecl *Super = Class->getSuperClass();
3112*67e74705SXin Li 
3113*67e74705SXin Li   // Root classes are also __class_type_info.
3114*67e74705SXin Li   if (!Super) return;
3115*67e74705SXin Li 
3116*67e74705SXin Li   QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3117*67e74705SXin Li 
3118*67e74705SXin Li   // Everything else is single inheritance.
3119*67e74705SXin Li   llvm::Constant *BaseTypeInfo =
3120*67e74705SXin Li       ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3121*67e74705SXin Li   Fields.push_back(BaseTypeInfo);
3122*67e74705SXin Li }
3123*67e74705SXin Li 
3124*67e74705SXin Li /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3125*67e74705SXin Li /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
BuildSIClassTypeInfo(const CXXRecordDecl * RD)3126*67e74705SXin Li void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3127*67e74705SXin Li   // Itanium C++ ABI 2.9.5p6b:
3128*67e74705SXin Li   // It adds to abi::__class_type_info a single member pointing to the
3129*67e74705SXin Li   // type_info structure for the base type,
3130*67e74705SXin Li   llvm::Constant *BaseTypeInfo =
3131*67e74705SXin Li     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3132*67e74705SXin Li   Fields.push_back(BaseTypeInfo);
3133*67e74705SXin Li }
3134*67e74705SXin Li 
3135*67e74705SXin Li namespace {
3136*67e74705SXin Li   /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3137*67e74705SXin Li   /// a class hierarchy.
3138*67e74705SXin Li   struct SeenBases {
3139*67e74705SXin Li     llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3140*67e74705SXin Li     llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3141*67e74705SXin Li   };
3142*67e74705SXin Li }
3143*67e74705SXin Li 
3144*67e74705SXin Li /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3145*67e74705SXin Li /// abi::__vmi_class_type_info.
3146*67e74705SXin Li ///
ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier * Base,SeenBases & Bases)3147*67e74705SXin Li static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3148*67e74705SXin Li                                              SeenBases &Bases) {
3149*67e74705SXin Li 
3150*67e74705SXin Li   unsigned Flags = 0;
3151*67e74705SXin Li 
3152*67e74705SXin Li   const CXXRecordDecl *BaseDecl =
3153*67e74705SXin Li     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3154*67e74705SXin Li 
3155*67e74705SXin Li   if (Base->isVirtual()) {
3156*67e74705SXin Li     // Mark the virtual base as seen.
3157*67e74705SXin Li     if (!Bases.VirtualBases.insert(BaseDecl).second) {
3158*67e74705SXin Li       // If this virtual base has been seen before, then the class is diamond
3159*67e74705SXin Li       // shaped.
3160*67e74705SXin Li       Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3161*67e74705SXin Li     } else {
3162*67e74705SXin Li       if (Bases.NonVirtualBases.count(BaseDecl))
3163*67e74705SXin Li         Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3164*67e74705SXin Li     }
3165*67e74705SXin Li   } else {
3166*67e74705SXin Li     // Mark the non-virtual base as seen.
3167*67e74705SXin Li     if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
3168*67e74705SXin Li       // If this non-virtual base has been seen before, then the class has non-
3169*67e74705SXin Li       // diamond shaped repeated inheritance.
3170*67e74705SXin Li       Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3171*67e74705SXin Li     } else {
3172*67e74705SXin Li       if (Bases.VirtualBases.count(BaseDecl))
3173*67e74705SXin Li         Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3174*67e74705SXin Li     }
3175*67e74705SXin Li   }
3176*67e74705SXin Li 
3177*67e74705SXin Li   // Walk all bases.
3178*67e74705SXin Li   for (const auto &I : BaseDecl->bases())
3179*67e74705SXin Li     Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3180*67e74705SXin Li 
3181*67e74705SXin Li   return Flags;
3182*67e74705SXin Li }
3183*67e74705SXin Li 
ComputeVMIClassTypeInfoFlags(const CXXRecordDecl * RD)3184*67e74705SXin Li static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3185*67e74705SXin Li   unsigned Flags = 0;
3186*67e74705SXin Li   SeenBases Bases;
3187*67e74705SXin Li 
3188*67e74705SXin Li   // Walk all bases.
3189*67e74705SXin Li   for (const auto &I : RD->bases())
3190*67e74705SXin Li     Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3191*67e74705SXin Li 
3192*67e74705SXin Li   return Flags;
3193*67e74705SXin Li }
3194*67e74705SXin Li 
3195*67e74705SXin Li /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3196*67e74705SXin Li /// classes with bases that do not satisfy the abi::__si_class_type_info
3197*67e74705SXin Li /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
BuildVMIClassTypeInfo(const CXXRecordDecl * RD)3198*67e74705SXin Li void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3199*67e74705SXin Li   llvm::Type *UnsignedIntLTy =
3200*67e74705SXin Li     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3201*67e74705SXin Li 
3202*67e74705SXin Li   // Itanium C++ ABI 2.9.5p6c:
3203*67e74705SXin Li   //   __flags is a word with flags describing details about the class
3204*67e74705SXin Li   //   structure, which may be referenced by using the __flags_masks
3205*67e74705SXin Li   //   enumeration. These flags refer to both direct and indirect bases.
3206*67e74705SXin Li   unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3207*67e74705SXin Li   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3208*67e74705SXin Li 
3209*67e74705SXin Li   // Itanium C++ ABI 2.9.5p6c:
3210*67e74705SXin Li   //   __base_count is a word with the number of direct proper base class
3211*67e74705SXin Li   //   descriptions that follow.
3212*67e74705SXin Li   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3213*67e74705SXin Li 
3214*67e74705SXin Li   if (!RD->getNumBases())
3215*67e74705SXin Li     return;
3216*67e74705SXin Li 
3217*67e74705SXin Li   llvm::Type *LongLTy =
3218*67e74705SXin Li     CGM.getTypes().ConvertType(CGM.getContext().LongTy);
3219*67e74705SXin Li 
3220*67e74705SXin Li   // Now add the base class descriptions.
3221*67e74705SXin Li 
3222*67e74705SXin Li   // Itanium C++ ABI 2.9.5p6c:
3223*67e74705SXin Li   //   __base_info[] is an array of base class descriptions -- one for every
3224*67e74705SXin Li   //   direct proper base. Each description is of the type:
3225*67e74705SXin Li   //
3226*67e74705SXin Li   //   struct abi::__base_class_type_info {
3227*67e74705SXin Li   //   public:
3228*67e74705SXin Li   //     const __class_type_info *__base_type;
3229*67e74705SXin Li   //     long __offset_flags;
3230*67e74705SXin Li   //
3231*67e74705SXin Li   //     enum __offset_flags_masks {
3232*67e74705SXin Li   //       __virtual_mask = 0x1,
3233*67e74705SXin Li   //       __public_mask = 0x2,
3234*67e74705SXin Li   //       __offset_shift = 8
3235*67e74705SXin Li   //     };
3236*67e74705SXin Li   //   };
3237*67e74705SXin Li   for (const auto &Base : RD->bases()) {
3238*67e74705SXin Li     // The __base_type member points to the RTTI for the base type.
3239*67e74705SXin Li     Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3240*67e74705SXin Li 
3241*67e74705SXin Li     const CXXRecordDecl *BaseDecl =
3242*67e74705SXin Li       cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3243*67e74705SXin Li 
3244*67e74705SXin Li     int64_t OffsetFlags = 0;
3245*67e74705SXin Li 
3246*67e74705SXin Li     // All but the lower 8 bits of __offset_flags are a signed offset.
3247*67e74705SXin Li     // For a non-virtual base, this is the offset in the object of the base
3248*67e74705SXin Li     // subobject. For a virtual base, this is the offset in the virtual table of
3249*67e74705SXin Li     // the virtual base offset for the virtual base referenced (negative).
3250*67e74705SXin Li     CharUnits Offset;
3251*67e74705SXin Li     if (Base.isVirtual())
3252*67e74705SXin Li       Offset =
3253*67e74705SXin Li         CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3254*67e74705SXin Li     else {
3255*67e74705SXin Li       const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3256*67e74705SXin Li       Offset = Layout.getBaseClassOffset(BaseDecl);
3257*67e74705SXin Li     };
3258*67e74705SXin Li 
3259*67e74705SXin Li     OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3260*67e74705SXin Li 
3261*67e74705SXin Li     // The low-order byte of __offset_flags contains flags, as given by the
3262*67e74705SXin Li     // masks from the enumeration __offset_flags_masks.
3263*67e74705SXin Li     if (Base.isVirtual())
3264*67e74705SXin Li       OffsetFlags |= BCTI_Virtual;
3265*67e74705SXin Li     if (Base.getAccessSpecifier() == AS_public)
3266*67e74705SXin Li       OffsetFlags |= BCTI_Public;
3267*67e74705SXin Li 
3268*67e74705SXin Li     Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
3269*67e74705SXin Li   }
3270*67e74705SXin Li }
3271*67e74705SXin Li 
3272*67e74705SXin Li /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3273*67e74705SXin Li /// used for pointer types.
BuildPointerTypeInfo(QualType PointeeTy)3274*67e74705SXin Li void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3275*67e74705SXin Li   Qualifiers Quals;
3276*67e74705SXin Li   QualType UnqualifiedPointeeTy =
3277*67e74705SXin Li     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3278*67e74705SXin Li 
3279*67e74705SXin Li   // Itanium C++ ABI 2.9.5p7:
3280*67e74705SXin Li   //   __flags is a flag word describing the cv-qualification and other
3281*67e74705SXin Li   //   attributes of the type pointed to
3282*67e74705SXin Li   unsigned Flags = ComputeQualifierFlags(Quals);
3283*67e74705SXin Li 
3284*67e74705SXin Li   // Itanium C++ ABI 2.9.5p7:
3285*67e74705SXin Li   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
3286*67e74705SXin Li   //   incomplete class type, the incomplete target type flag is set.
3287*67e74705SXin Li   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3288*67e74705SXin Li     Flags |= PTI_Incomplete;
3289*67e74705SXin Li 
3290*67e74705SXin Li   llvm::Type *UnsignedIntLTy =
3291*67e74705SXin Li     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3292*67e74705SXin Li   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3293*67e74705SXin Li 
3294*67e74705SXin Li   // Itanium C++ ABI 2.9.5p7:
3295*67e74705SXin Li   //  __pointee is a pointer to the std::type_info derivation for the
3296*67e74705SXin Li   //  unqualified type being pointed to.
3297*67e74705SXin Li   llvm::Constant *PointeeTypeInfo =
3298*67e74705SXin Li     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3299*67e74705SXin Li   Fields.push_back(PointeeTypeInfo);
3300*67e74705SXin Li }
3301*67e74705SXin Li 
3302*67e74705SXin Li /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3303*67e74705SXin Li /// struct, used for member pointer types.
3304*67e74705SXin Li void
BuildPointerToMemberTypeInfo(const MemberPointerType * Ty)3305*67e74705SXin Li ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3306*67e74705SXin Li   QualType PointeeTy = Ty->getPointeeType();
3307*67e74705SXin Li 
3308*67e74705SXin Li   Qualifiers Quals;
3309*67e74705SXin Li   QualType UnqualifiedPointeeTy =
3310*67e74705SXin Li     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
3311*67e74705SXin Li 
3312*67e74705SXin Li   // Itanium C++ ABI 2.9.5p7:
3313*67e74705SXin Li   //   __flags is a flag word describing the cv-qualification and other
3314*67e74705SXin Li   //   attributes of the type pointed to.
3315*67e74705SXin Li   unsigned Flags = ComputeQualifierFlags(Quals);
3316*67e74705SXin Li 
3317*67e74705SXin Li   const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3318*67e74705SXin Li 
3319*67e74705SXin Li   // Itanium C++ ABI 2.9.5p7:
3320*67e74705SXin Li   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
3321*67e74705SXin Li   //   incomplete class type, the incomplete target type flag is set.
3322*67e74705SXin Li   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
3323*67e74705SXin Li     Flags |= PTI_Incomplete;
3324*67e74705SXin Li 
3325*67e74705SXin Li   if (IsIncompleteClassType(ClassType))
3326*67e74705SXin Li     Flags |= PTI_ContainingClassIncomplete;
3327*67e74705SXin Li 
3328*67e74705SXin Li   llvm::Type *UnsignedIntLTy =
3329*67e74705SXin Li     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3330*67e74705SXin Li   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3331*67e74705SXin Li 
3332*67e74705SXin Li   // Itanium C++ ABI 2.9.5p7:
3333*67e74705SXin Li   //   __pointee is a pointer to the std::type_info derivation for the
3334*67e74705SXin Li   //   unqualified type being pointed to.
3335*67e74705SXin Li   llvm::Constant *PointeeTypeInfo =
3336*67e74705SXin Li     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
3337*67e74705SXin Li   Fields.push_back(PointeeTypeInfo);
3338*67e74705SXin Li 
3339*67e74705SXin Li   // Itanium C++ ABI 2.9.5p9:
3340*67e74705SXin Li   //   __context is a pointer to an abi::__class_type_info corresponding to the
3341*67e74705SXin Li   //   class type containing the member pointed to
3342*67e74705SXin Li   //   (e.g., the "A" in "int A::*").
3343*67e74705SXin Li   Fields.push_back(
3344*67e74705SXin Li       ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3345*67e74705SXin Li }
3346*67e74705SXin Li 
getAddrOfRTTIDescriptor(QualType Ty)3347*67e74705SXin Li llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
3348*67e74705SXin Li   return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3349*67e74705SXin Li }
3350*67e74705SXin Li 
EmitFundamentalRTTIDescriptor(QualType Type)3351*67e74705SXin Li void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
3352*67e74705SXin Li   QualType PointerType = getContext().getPointerType(Type);
3353*67e74705SXin Li   QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3354*67e74705SXin Li   ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
3355*67e74705SXin Li   ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
3356*67e74705SXin Li   ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
3357*67e74705SXin Li }
3358*67e74705SXin Li 
EmitFundamentalRTTIDescriptors()3359*67e74705SXin Li void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
3360*67e74705SXin Li   // Types added here must also be added to TypeInfoIsInStandardLibrary.
3361*67e74705SXin Li   QualType FundamentalTypes[] = {
3362*67e74705SXin Li       getContext().VoidTy,             getContext().NullPtrTy,
3363*67e74705SXin Li       getContext().BoolTy,             getContext().WCharTy,
3364*67e74705SXin Li       getContext().CharTy,             getContext().UnsignedCharTy,
3365*67e74705SXin Li       getContext().SignedCharTy,       getContext().ShortTy,
3366*67e74705SXin Li       getContext().UnsignedShortTy,    getContext().IntTy,
3367*67e74705SXin Li       getContext().UnsignedIntTy,      getContext().LongTy,
3368*67e74705SXin Li       getContext().UnsignedLongTy,     getContext().LongLongTy,
3369*67e74705SXin Li       getContext().UnsignedLongLongTy, getContext().Int128Ty,
3370*67e74705SXin Li       getContext().UnsignedInt128Ty,   getContext().HalfTy,
3371*67e74705SXin Li       getContext().FloatTy,            getContext().DoubleTy,
3372*67e74705SXin Li       getContext().LongDoubleTy,       getContext().Float128Ty,
3373*67e74705SXin Li       getContext().Char16Ty,           getContext().Char32Ty
3374*67e74705SXin Li   };
3375*67e74705SXin Li   for (const QualType &FundamentalType : FundamentalTypes)
3376*67e74705SXin Li     EmitFundamentalRTTIDescriptor(FundamentalType);
3377*67e74705SXin Li }
3378*67e74705SXin Li 
3379*67e74705SXin Li /// What sort of uniqueness rules should we use for the RTTI for the
3380*67e74705SXin Li /// given type?
classifyRTTIUniqueness(QualType CanTy,llvm::GlobalValue::LinkageTypes Linkage) const3381*67e74705SXin Li ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3382*67e74705SXin Li     QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3383*67e74705SXin Li   if (shouldRTTIBeUnique())
3384*67e74705SXin Li     return RUK_Unique;
3385*67e74705SXin Li 
3386*67e74705SXin Li   // It's only necessary for linkonce_odr or weak_odr linkage.
3387*67e74705SXin Li   if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3388*67e74705SXin Li       Linkage != llvm::GlobalValue::WeakODRLinkage)
3389*67e74705SXin Li     return RUK_Unique;
3390*67e74705SXin Li 
3391*67e74705SXin Li   // It's only necessary with default visibility.
3392*67e74705SXin Li   if (CanTy->getVisibility() != DefaultVisibility)
3393*67e74705SXin Li     return RUK_Unique;
3394*67e74705SXin Li 
3395*67e74705SXin Li   // If we're not required to publish this symbol, hide it.
3396*67e74705SXin Li   if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3397*67e74705SXin Li     return RUK_NonUniqueHidden;
3398*67e74705SXin Li 
3399*67e74705SXin Li   // If we're required to publish this symbol, as we might be under an
3400*67e74705SXin Li   // explicit instantiation, leave it with default visibility but
3401*67e74705SXin Li   // enable string-comparisons.
3402*67e74705SXin Li   assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3403*67e74705SXin Li   return RUK_NonUniqueVisible;
3404*67e74705SXin Li }
3405*67e74705SXin Li 
3406*67e74705SXin Li // Find out how to codegen the complete destructor and constructor
3407*67e74705SXin Li namespace {
3408*67e74705SXin Li enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3409*67e74705SXin Li }
getCodegenToUse(CodeGenModule & CGM,const CXXMethodDecl * MD)3410*67e74705SXin Li static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3411*67e74705SXin Li                                        const CXXMethodDecl *MD) {
3412*67e74705SXin Li   if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3413*67e74705SXin Li     return StructorCodegen::Emit;
3414*67e74705SXin Li 
3415*67e74705SXin Li   // The complete and base structors are not equivalent if there are any virtual
3416*67e74705SXin Li   // bases, so emit separate functions.
3417*67e74705SXin Li   if (MD->getParent()->getNumVBases())
3418*67e74705SXin Li     return StructorCodegen::Emit;
3419*67e74705SXin Li 
3420*67e74705SXin Li   GlobalDecl AliasDecl;
3421*67e74705SXin Li   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3422*67e74705SXin Li     AliasDecl = GlobalDecl(DD, Dtor_Complete);
3423*67e74705SXin Li   } else {
3424*67e74705SXin Li     const auto *CD = cast<CXXConstructorDecl>(MD);
3425*67e74705SXin Li     AliasDecl = GlobalDecl(CD, Ctor_Complete);
3426*67e74705SXin Li   }
3427*67e74705SXin Li   llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3428*67e74705SXin Li 
3429*67e74705SXin Li   if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3430*67e74705SXin Li     return StructorCodegen::RAUW;
3431*67e74705SXin Li 
3432*67e74705SXin Li   // FIXME: Should we allow available_externally aliases?
3433*67e74705SXin Li   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3434*67e74705SXin Li     return StructorCodegen::RAUW;
3435*67e74705SXin Li 
3436*67e74705SXin Li   if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3437*67e74705SXin Li     // Only ELF supports COMDATs with arbitrary names (C5/D5).
3438*67e74705SXin Li     if (CGM.getTarget().getTriple().isOSBinFormatELF())
3439*67e74705SXin Li       return StructorCodegen::COMDAT;
3440*67e74705SXin Li     return StructorCodegen::Emit;
3441*67e74705SXin Li   }
3442*67e74705SXin Li 
3443*67e74705SXin Li   return StructorCodegen::Alias;
3444*67e74705SXin Li }
3445*67e74705SXin Li 
emitConstructorDestructorAlias(CodeGenModule & CGM,GlobalDecl AliasDecl,GlobalDecl TargetDecl)3446*67e74705SXin Li static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3447*67e74705SXin Li                                            GlobalDecl AliasDecl,
3448*67e74705SXin Li                                            GlobalDecl TargetDecl) {
3449*67e74705SXin Li   llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3450*67e74705SXin Li 
3451*67e74705SXin Li   StringRef MangledName = CGM.getMangledName(AliasDecl);
3452*67e74705SXin Li   llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3453*67e74705SXin Li   if (Entry && !Entry->isDeclaration())
3454*67e74705SXin Li     return;
3455*67e74705SXin Li 
3456*67e74705SXin Li   auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3457*67e74705SXin Li 
3458*67e74705SXin Li   // Create the alias with no name.
3459*67e74705SXin Li   auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
3460*67e74705SXin Li 
3461*67e74705SXin Li   // Switch any previous uses to the alias.
3462*67e74705SXin Li   if (Entry) {
3463*67e74705SXin Li     assert(Entry->getType() == Aliasee->getType() &&
3464*67e74705SXin Li            "declaration exists with different type");
3465*67e74705SXin Li     Alias->takeName(Entry);
3466*67e74705SXin Li     Entry->replaceAllUsesWith(Alias);
3467*67e74705SXin Li     Entry->eraseFromParent();
3468*67e74705SXin Li   } else {
3469*67e74705SXin Li     Alias->setName(MangledName);
3470*67e74705SXin Li   }
3471*67e74705SXin Li 
3472*67e74705SXin Li   // Finally, set up the alias with its proper name and attributes.
3473*67e74705SXin Li   CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
3474*67e74705SXin Li }
3475*67e74705SXin Li 
emitCXXStructor(const CXXMethodDecl * MD,StructorType Type)3476*67e74705SXin Li void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3477*67e74705SXin Li                                     StructorType Type) {
3478*67e74705SXin Li   auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3479*67e74705SXin Li   const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3480*67e74705SXin Li 
3481*67e74705SXin Li   StructorCodegen CGType = getCodegenToUse(CGM, MD);
3482*67e74705SXin Li 
3483*67e74705SXin Li   if (Type == StructorType::Complete) {
3484*67e74705SXin Li     GlobalDecl CompleteDecl;
3485*67e74705SXin Li     GlobalDecl BaseDecl;
3486*67e74705SXin Li     if (CD) {
3487*67e74705SXin Li       CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3488*67e74705SXin Li       BaseDecl = GlobalDecl(CD, Ctor_Base);
3489*67e74705SXin Li     } else {
3490*67e74705SXin Li       CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3491*67e74705SXin Li       BaseDecl = GlobalDecl(DD, Dtor_Base);
3492*67e74705SXin Li     }
3493*67e74705SXin Li 
3494*67e74705SXin Li     if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3495*67e74705SXin Li       emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3496*67e74705SXin Li       return;
3497*67e74705SXin Li     }
3498*67e74705SXin Li 
3499*67e74705SXin Li     if (CGType == StructorCodegen::RAUW) {
3500*67e74705SXin Li       StringRef MangledName = CGM.getMangledName(CompleteDecl);
3501*67e74705SXin Li       auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
3502*67e74705SXin Li       CGM.addReplacement(MangledName, Aliasee);
3503*67e74705SXin Li       return;
3504*67e74705SXin Li     }
3505*67e74705SXin Li   }
3506*67e74705SXin Li 
3507*67e74705SXin Li   // The base destructor is equivalent to the base destructor of its
3508*67e74705SXin Li   // base class if there is exactly one non-virtual base class with a
3509*67e74705SXin Li   // non-trivial destructor, there are no fields with a non-trivial
3510*67e74705SXin Li   // destructor, and the body of the destructor is trivial.
3511*67e74705SXin Li   if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3512*67e74705SXin Li       !CGM.TryEmitBaseDestructorAsAlias(DD))
3513*67e74705SXin Li     return;
3514*67e74705SXin Li 
3515*67e74705SXin Li   llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
3516*67e74705SXin Li 
3517*67e74705SXin Li   if (CGType == StructorCodegen::COMDAT) {
3518*67e74705SXin Li     SmallString<256> Buffer;
3519*67e74705SXin Li     llvm::raw_svector_ostream Out(Buffer);
3520*67e74705SXin Li     if (DD)
3521*67e74705SXin Li       getMangleContext().mangleCXXDtorComdat(DD, Out);
3522*67e74705SXin Li     else
3523*67e74705SXin Li       getMangleContext().mangleCXXCtorComdat(CD, Out);
3524*67e74705SXin Li     llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3525*67e74705SXin Li     Fn->setComdat(C);
3526*67e74705SXin Li   } else {
3527*67e74705SXin Li     CGM.maybeSetTrivialComdat(*MD, *Fn);
3528*67e74705SXin Li   }
3529*67e74705SXin Li }
3530*67e74705SXin Li 
getBeginCatchFn(CodeGenModule & CGM)3531*67e74705SXin Li static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3532*67e74705SXin Li   // void *__cxa_begin_catch(void*);
3533*67e74705SXin Li   llvm::FunctionType *FTy = llvm::FunctionType::get(
3534*67e74705SXin Li       CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3535*67e74705SXin Li 
3536*67e74705SXin Li   return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3537*67e74705SXin Li }
3538*67e74705SXin Li 
getEndCatchFn(CodeGenModule & CGM)3539*67e74705SXin Li static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3540*67e74705SXin Li   // void __cxa_end_catch();
3541*67e74705SXin Li   llvm::FunctionType *FTy =
3542*67e74705SXin Li       llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3543*67e74705SXin Li 
3544*67e74705SXin Li   return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3545*67e74705SXin Li }
3546*67e74705SXin Li 
getGetExceptionPtrFn(CodeGenModule & CGM)3547*67e74705SXin Li static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3548*67e74705SXin Li   // void *__cxa_get_exception_ptr(void*);
3549*67e74705SXin Li   llvm::FunctionType *FTy = llvm::FunctionType::get(
3550*67e74705SXin Li       CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3551*67e74705SXin Li 
3552*67e74705SXin Li   return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3553*67e74705SXin Li }
3554*67e74705SXin Li 
3555*67e74705SXin Li namespace {
3556*67e74705SXin Li   /// A cleanup to call __cxa_end_catch.  In many cases, the caught
3557*67e74705SXin Li   /// exception type lets us state definitively that the thrown exception
3558*67e74705SXin Li   /// type does not have a destructor.  In particular:
3559*67e74705SXin Li   ///   - Catch-alls tell us nothing, so we have to conservatively
3560*67e74705SXin Li   ///     assume that the thrown exception might have a destructor.
3561*67e74705SXin Li   ///   - Catches by reference behave according to their base types.
3562*67e74705SXin Li   ///   - Catches of non-record types will only trigger for exceptions
3563*67e74705SXin Li   ///     of non-record types, which never have destructors.
3564*67e74705SXin Li   ///   - Catches of record types can trigger for arbitrary subclasses
3565*67e74705SXin Li   ///     of the caught type, so we have to assume the actual thrown
3566*67e74705SXin Li   ///     exception type might have a throwing destructor, even if the
3567*67e74705SXin Li   ///     caught type's destructor is trivial or nothrow.
3568*67e74705SXin Li   struct CallEndCatch final : EHScopeStack::Cleanup {
CallEndCatch__anonbf32792c0911::CallEndCatch3569*67e74705SXin Li     CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3570*67e74705SXin Li     bool MightThrow;
3571*67e74705SXin Li 
Emit__anonbf32792c0911::CallEndCatch3572*67e74705SXin Li     void Emit(CodeGenFunction &CGF, Flags flags) override {
3573*67e74705SXin Li       if (!MightThrow) {
3574*67e74705SXin Li         CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3575*67e74705SXin Li         return;
3576*67e74705SXin Li       }
3577*67e74705SXin Li 
3578*67e74705SXin Li       CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3579*67e74705SXin Li     }
3580*67e74705SXin Li   };
3581*67e74705SXin Li }
3582*67e74705SXin Li 
3583*67e74705SXin Li /// Emits a call to __cxa_begin_catch and enters a cleanup to call
3584*67e74705SXin Li /// __cxa_end_catch.
3585*67e74705SXin Li ///
3586*67e74705SXin Li /// \param EndMightThrow - true if __cxa_end_catch might throw
CallBeginCatch(CodeGenFunction & CGF,llvm::Value * Exn,bool EndMightThrow)3587*67e74705SXin Li static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3588*67e74705SXin Li                                    llvm::Value *Exn,
3589*67e74705SXin Li                                    bool EndMightThrow) {
3590*67e74705SXin Li   llvm::CallInst *call =
3591*67e74705SXin Li     CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3592*67e74705SXin Li 
3593*67e74705SXin Li   CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3594*67e74705SXin Li 
3595*67e74705SXin Li   return call;
3596*67e74705SXin Li }
3597*67e74705SXin Li 
3598*67e74705SXin Li /// A "special initializer" callback for initializing a catch
3599*67e74705SXin Li /// parameter during catch initialization.
InitCatchParam(CodeGenFunction & CGF,const VarDecl & CatchParam,Address ParamAddr,SourceLocation Loc)3600*67e74705SXin Li static void InitCatchParam(CodeGenFunction &CGF,
3601*67e74705SXin Li                            const VarDecl &CatchParam,
3602*67e74705SXin Li                            Address ParamAddr,
3603*67e74705SXin Li                            SourceLocation Loc) {
3604*67e74705SXin Li   // Load the exception from where the landing pad saved it.
3605*67e74705SXin Li   llvm::Value *Exn = CGF.getExceptionFromSlot();
3606*67e74705SXin Li 
3607*67e74705SXin Li   CanQualType CatchType =
3608*67e74705SXin Li     CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3609*67e74705SXin Li   llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3610*67e74705SXin Li 
3611*67e74705SXin Li   // If we're catching by reference, we can just cast the object
3612*67e74705SXin Li   // pointer to the appropriate pointer.
3613*67e74705SXin Li   if (isa<ReferenceType>(CatchType)) {
3614*67e74705SXin Li     QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3615*67e74705SXin Li     bool EndCatchMightThrow = CaughtType->isRecordType();
3616*67e74705SXin Li 
3617*67e74705SXin Li     // __cxa_begin_catch returns the adjusted object pointer.
3618*67e74705SXin Li     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3619*67e74705SXin Li 
3620*67e74705SXin Li     // We have no way to tell the personality function that we're
3621*67e74705SXin Li     // catching by reference, so if we're catching a pointer,
3622*67e74705SXin Li     // __cxa_begin_catch will actually return that pointer by value.
3623*67e74705SXin Li     if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3624*67e74705SXin Li       QualType PointeeType = PT->getPointeeType();
3625*67e74705SXin Li 
3626*67e74705SXin Li       // When catching by reference, generally we should just ignore
3627*67e74705SXin Li       // this by-value pointer and use the exception object instead.
3628*67e74705SXin Li       if (!PointeeType->isRecordType()) {
3629*67e74705SXin Li 
3630*67e74705SXin Li         // Exn points to the struct _Unwind_Exception header, which
3631*67e74705SXin Li         // we have to skip past in order to reach the exception data.
3632*67e74705SXin Li         unsigned HeaderSize =
3633*67e74705SXin Li           CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3634*67e74705SXin Li         AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3635*67e74705SXin Li 
3636*67e74705SXin Li       // However, if we're catching a pointer-to-record type that won't
3637*67e74705SXin Li       // work, because the personality function might have adjusted
3638*67e74705SXin Li       // the pointer.  There's actually no way for us to fully satisfy
3639*67e74705SXin Li       // the language/ABI contract here:  we can't use Exn because it
3640*67e74705SXin Li       // might have the wrong adjustment, but we can't use the by-value
3641*67e74705SXin Li       // pointer because it's off by a level of abstraction.
3642*67e74705SXin Li       //
3643*67e74705SXin Li       // The current solution is to dump the adjusted pointer into an
3644*67e74705SXin Li       // alloca, which breaks language semantics (because changing the
3645*67e74705SXin Li       // pointer doesn't change the exception) but at least works.
3646*67e74705SXin Li       // The better solution would be to filter out non-exact matches
3647*67e74705SXin Li       // and rethrow them, but this is tricky because the rethrow
3648*67e74705SXin Li       // really needs to be catchable by other sites at this landing
3649*67e74705SXin Li       // pad.  The best solution is to fix the personality function.
3650*67e74705SXin Li       } else {
3651*67e74705SXin Li         // Pull the pointer for the reference type off.
3652*67e74705SXin Li         llvm::Type *PtrTy =
3653*67e74705SXin Li           cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3654*67e74705SXin Li 
3655*67e74705SXin Li         // Create the temporary and write the adjusted pointer into it.
3656*67e74705SXin Li         Address ExnPtrTmp =
3657*67e74705SXin Li           CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
3658*67e74705SXin Li         llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3659*67e74705SXin Li         CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3660*67e74705SXin Li 
3661*67e74705SXin Li         // Bind the reference to the temporary.
3662*67e74705SXin Li         AdjustedExn = ExnPtrTmp.getPointer();
3663*67e74705SXin Li       }
3664*67e74705SXin Li     }
3665*67e74705SXin Li 
3666*67e74705SXin Li     llvm::Value *ExnCast =
3667*67e74705SXin Li       CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3668*67e74705SXin Li     CGF.Builder.CreateStore(ExnCast, ParamAddr);
3669*67e74705SXin Li     return;
3670*67e74705SXin Li   }
3671*67e74705SXin Li 
3672*67e74705SXin Li   // Scalars and complexes.
3673*67e74705SXin Li   TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3674*67e74705SXin Li   if (TEK != TEK_Aggregate) {
3675*67e74705SXin Li     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3676*67e74705SXin Li 
3677*67e74705SXin Li     // If the catch type is a pointer type, __cxa_begin_catch returns
3678*67e74705SXin Li     // the pointer by value.
3679*67e74705SXin Li     if (CatchType->hasPointerRepresentation()) {
3680*67e74705SXin Li       llvm::Value *CastExn =
3681*67e74705SXin Li         CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3682*67e74705SXin Li 
3683*67e74705SXin Li       switch (CatchType.getQualifiers().getObjCLifetime()) {
3684*67e74705SXin Li       case Qualifiers::OCL_Strong:
3685*67e74705SXin Li         CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3686*67e74705SXin Li         // fallthrough
3687*67e74705SXin Li 
3688*67e74705SXin Li       case Qualifiers::OCL_None:
3689*67e74705SXin Li       case Qualifiers::OCL_ExplicitNone:
3690*67e74705SXin Li       case Qualifiers::OCL_Autoreleasing:
3691*67e74705SXin Li         CGF.Builder.CreateStore(CastExn, ParamAddr);
3692*67e74705SXin Li         return;
3693*67e74705SXin Li 
3694*67e74705SXin Li       case Qualifiers::OCL_Weak:
3695*67e74705SXin Li         CGF.EmitARCInitWeak(ParamAddr, CastExn);
3696*67e74705SXin Li         return;
3697*67e74705SXin Li       }
3698*67e74705SXin Li       llvm_unreachable("bad ownership qualifier!");
3699*67e74705SXin Li     }
3700*67e74705SXin Li 
3701*67e74705SXin Li     // Otherwise, it returns a pointer into the exception object.
3702*67e74705SXin Li 
3703*67e74705SXin Li     llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3704*67e74705SXin Li     llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3705*67e74705SXin Li 
3706*67e74705SXin Li     LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3707*67e74705SXin Li     LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
3708*67e74705SXin Li     switch (TEK) {
3709*67e74705SXin Li     case TEK_Complex:
3710*67e74705SXin Li       CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3711*67e74705SXin Li                              /*init*/ true);
3712*67e74705SXin Li       return;
3713*67e74705SXin Li     case TEK_Scalar: {
3714*67e74705SXin Li       llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3715*67e74705SXin Li       CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3716*67e74705SXin Li       return;
3717*67e74705SXin Li     }
3718*67e74705SXin Li     case TEK_Aggregate:
3719*67e74705SXin Li       llvm_unreachable("evaluation kind filtered out!");
3720*67e74705SXin Li     }
3721*67e74705SXin Li     llvm_unreachable("bad evaluation kind");
3722*67e74705SXin Li   }
3723*67e74705SXin Li 
3724*67e74705SXin Li   assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3725*67e74705SXin Li   auto catchRD = CatchType->getAsCXXRecordDecl();
3726*67e74705SXin Li   CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
3727*67e74705SXin Li 
3728*67e74705SXin Li   llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3729*67e74705SXin Li 
3730*67e74705SXin Li   // Check for a copy expression.  If we don't have a copy expression,
3731*67e74705SXin Li   // that means a trivial copy is okay.
3732*67e74705SXin Li   const Expr *copyExpr = CatchParam.getInit();
3733*67e74705SXin Li   if (!copyExpr) {
3734*67e74705SXin Li     llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3735*67e74705SXin Li     Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3736*67e74705SXin Li                         caughtExnAlignment);
3737*67e74705SXin Li     CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3738*67e74705SXin Li     return;
3739*67e74705SXin Li   }
3740*67e74705SXin Li 
3741*67e74705SXin Li   // We have to call __cxa_get_exception_ptr to get the adjusted
3742*67e74705SXin Li   // pointer before copying.
3743*67e74705SXin Li   llvm::CallInst *rawAdjustedExn =
3744*67e74705SXin Li     CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3745*67e74705SXin Li 
3746*67e74705SXin Li   // Cast that to the appropriate type.
3747*67e74705SXin Li   Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3748*67e74705SXin Li                       caughtExnAlignment);
3749*67e74705SXin Li 
3750*67e74705SXin Li   // The copy expression is defined in terms of an OpaqueValueExpr.
3751*67e74705SXin Li   // Find it and map it to the adjusted expression.
3752*67e74705SXin Li   CodeGenFunction::OpaqueValueMapping
3753*67e74705SXin Li     opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3754*67e74705SXin Li            CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3755*67e74705SXin Li 
3756*67e74705SXin Li   // Call the copy ctor in a terminate scope.
3757*67e74705SXin Li   CGF.EHStack.pushTerminate();
3758*67e74705SXin Li 
3759*67e74705SXin Li   // Perform the copy construction.
3760*67e74705SXin Li   CGF.EmitAggExpr(copyExpr,
3761*67e74705SXin Li                   AggValueSlot::forAddr(ParamAddr, Qualifiers(),
3762*67e74705SXin Li                                         AggValueSlot::IsNotDestructed,
3763*67e74705SXin Li                                         AggValueSlot::DoesNotNeedGCBarriers,
3764*67e74705SXin Li                                         AggValueSlot::IsNotAliased));
3765*67e74705SXin Li 
3766*67e74705SXin Li   // Leave the terminate scope.
3767*67e74705SXin Li   CGF.EHStack.popTerminate();
3768*67e74705SXin Li 
3769*67e74705SXin Li   // Undo the opaque value mapping.
3770*67e74705SXin Li   opaque.pop();
3771*67e74705SXin Li 
3772*67e74705SXin Li   // Finally we can call __cxa_begin_catch.
3773*67e74705SXin Li   CallBeginCatch(CGF, Exn, true);
3774*67e74705SXin Li }
3775*67e74705SXin Li 
3776*67e74705SXin Li /// Begins a catch statement by initializing the catch variable and
3777*67e74705SXin Li /// calling __cxa_begin_catch.
emitBeginCatch(CodeGenFunction & CGF,const CXXCatchStmt * S)3778*67e74705SXin Li void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3779*67e74705SXin Li                                    const CXXCatchStmt *S) {
3780*67e74705SXin Li   // We have to be very careful with the ordering of cleanups here:
3781*67e74705SXin Li   //   C++ [except.throw]p4:
3782*67e74705SXin Li   //     The destruction [of the exception temporary] occurs
3783*67e74705SXin Li   //     immediately after the destruction of the object declared in
3784*67e74705SXin Li   //     the exception-declaration in the handler.
3785*67e74705SXin Li   //
3786*67e74705SXin Li   // So the precise ordering is:
3787*67e74705SXin Li   //   1.  Construct catch variable.
3788*67e74705SXin Li   //   2.  __cxa_begin_catch
3789*67e74705SXin Li   //   3.  Enter __cxa_end_catch cleanup
3790*67e74705SXin Li   //   4.  Enter dtor cleanup
3791*67e74705SXin Li   //
3792*67e74705SXin Li   // We do this by using a slightly abnormal initialization process.
3793*67e74705SXin Li   // Delegation sequence:
3794*67e74705SXin Li   //   - ExitCXXTryStmt opens a RunCleanupsScope
3795*67e74705SXin Li   //     - EmitAutoVarAlloca creates the variable and debug info
3796*67e74705SXin Li   //       - InitCatchParam initializes the variable from the exception
3797*67e74705SXin Li   //       - CallBeginCatch calls __cxa_begin_catch
3798*67e74705SXin Li   //       - CallBeginCatch enters the __cxa_end_catch cleanup
3799*67e74705SXin Li   //     - EmitAutoVarCleanups enters the variable destructor cleanup
3800*67e74705SXin Li   //   - EmitCXXTryStmt emits the code for the catch body
3801*67e74705SXin Li   //   - EmitCXXTryStmt close the RunCleanupsScope
3802*67e74705SXin Li 
3803*67e74705SXin Li   VarDecl *CatchParam = S->getExceptionDecl();
3804*67e74705SXin Li   if (!CatchParam) {
3805*67e74705SXin Li     llvm::Value *Exn = CGF.getExceptionFromSlot();
3806*67e74705SXin Li     CallBeginCatch(CGF, Exn, true);
3807*67e74705SXin Li     return;
3808*67e74705SXin Li   }
3809*67e74705SXin Li 
3810*67e74705SXin Li   // Emit the local.
3811*67e74705SXin Li   CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3812*67e74705SXin Li   InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3813*67e74705SXin Li   CGF.EmitAutoVarCleanups(var);
3814*67e74705SXin Li }
3815*67e74705SXin Li 
3816*67e74705SXin Li /// Get or define the following function:
3817*67e74705SXin Li ///   void @__clang_call_terminate(i8* %exn) nounwind noreturn
3818*67e74705SXin Li /// This code is used only in C++.
getClangCallTerminateFn(CodeGenModule & CGM)3819*67e74705SXin Li static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3820*67e74705SXin Li   llvm::FunctionType *fnTy =
3821*67e74705SXin Li     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3822*67e74705SXin Li   llvm::Constant *fnRef =
3823*67e74705SXin Li     CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
3824*67e74705SXin Li 
3825*67e74705SXin Li   llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3826*67e74705SXin Li   if (fn && fn->empty()) {
3827*67e74705SXin Li     fn->setDoesNotThrow();
3828*67e74705SXin Li     fn->setDoesNotReturn();
3829*67e74705SXin Li 
3830*67e74705SXin Li     // What we really want is to massively penalize inlining without
3831*67e74705SXin Li     // forbidding it completely.  The difference between that and
3832*67e74705SXin Li     // 'noinline' is negligible.
3833*67e74705SXin Li     fn->addFnAttr(llvm::Attribute::NoInline);
3834*67e74705SXin Li 
3835*67e74705SXin Li     // Allow this function to be shared across translation units, but
3836*67e74705SXin Li     // we don't want it to turn into an exported symbol.
3837*67e74705SXin Li     fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3838*67e74705SXin Li     fn->setVisibility(llvm::Function::HiddenVisibility);
3839*67e74705SXin Li     if (CGM.supportsCOMDAT())
3840*67e74705SXin Li       fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
3841*67e74705SXin Li 
3842*67e74705SXin Li     // Set up the function.
3843*67e74705SXin Li     llvm::BasicBlock *entry =
3844*67e74705SXin Li       llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3845*67e74705SXin Li     CGBuilderTy builder(CGM, entry);
3846*67e74705SXin Li 
3847*67e74705SXin Li     // Pull the exception pointer out of the parameter list.
3848*67e74705SXin Li     llvm::Value *exn = &*fn->arg_begin();
3849*67e74705SXin Li 
3850*67e74705SXin Li     // Call __cxa_begin_catch(exn).
3851*67e74705SXin Li     llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3852*67e74705SXin Li     catchCall->setDoesNotThrow();
3853*67e74705SXin Li     catchCall->setCallingConv(CGM.getRuntimeCC());
3854*67e74705SXin Li 
3855*67e74705SXin Li     // Call std::terminate().
3856*67e74705SXin Li     llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
3857*67e74705SXin Li     termCall->setDoesNotThrow();
3858*67e74705SXin Li     termCall->setDoesNotReturn();
3859*67e74705SXin Li     termCall->setCallingConv(CGM.getRuntimeCC());
3860*67e74705SXin Li 
3861*67e74705SXin Li     // std::terminate cannot return.
3862*67e74705SXin Li     builder.CreateUnreachable();
3863*67e74705SXin Li   }
3864*67e74705SXin Li 
3865*67e74705SXin Li   return fnRef;
3866*67e74705SXin Li }
3867*67e74705SXin Li 
3868*67e74705SXin Li llvm::CallInst *
emitTerminateForUnexpectedException(CodeGenFunction & CGF,llvm::Value * Exn)3869*67e74705SXin Li ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3870*67e74705SXin Li                                                    llvm::Value *Exn) {
3871*67e74705SXin Li   // In C++, we want to call __cxa_begin_catch() before terminating.
3872*67e74705SXin Li   if (Exn) {
3873*67e74705SXin Li     assert(CGF.CGM.getLangOpts().CPlusPlus);
3874*67e74705SXin Li     return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3875*67e74705SXin Li   }
3876*67e74705SXin Li   return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
3877*67e74705SXin Li }
3878