1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
10 // The class in this file generates structures that follow the Microsoft
11 // Visual C++ ABI, which is actually not very well documented at all outside
14 //===----------------------------------------------------------------------===//
17 #include "CGCleanup.h"
18 #include "CGVTables.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenTypes.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/VTableBuilder.h"
28 #include "clang/CodeGen/ConstantInitBuilder.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSet.h"
31 #include "llvm/IR/Intrinsics.h"
33 using namespace clang;
34 using namespace CodeGen;
38 /// Holds all the vbtable globals for a given class.
39 struct VBTableGlobals {
40 const VPtrInfoVector *VBTables;
41 SmallVector<llvm::GlobalVariable *, 2> Globals;
44 class MicrosoftCXXABI : public CGCXXABI {
46 MicrosoftCXXABI(CodeGenModule &CGM)
47 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
48 ClassHierarchyDescriptorType(nullptr),
49 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
50 ThrowInfoType(nullptr) {}
52 bool HasThisReturn(GlobalDecl GD) const override;
53 bool hasMostDerivedReturn(GlobalDecl GD) const override;
55 bool classifyReturnType(CGFunctionInfo &FI) const override;
57 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
59 bool isSRetParameterAfterThis() const override { return true; }
61 bool isThisCompleteObject(GlobalDecl GD) const override {
62 // The Microsoft ABI doesn't use separate complete-object vs.
63 // base-object variants of constructors, but it does of destructors.
64 if (isa<CXXDestructorDecl>(GD.getDecl())) {
65 switch (GD.getDtorType()) {
73 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
75 llvm_unreachable("bad dtor kind");
82 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
83 FunctionArgList &Args) const override {
84 assert(Args.size() >= 2 &&
85 "expected the arglist to have at least two args!");
86 // The 'most_derived' parameter goes second if the ctor is variadic and
88 if (CD->getParent()->getNumVBases() > 0 &&
89 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
94 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
95 std::vector<CharUnits> VBPtrOffsets;
96 const ASTContext &Context = getContext();
97 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
99 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
100 for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
101 const ASTRecordLayout &SubobjectLayout =
102 Context.getASTRecordLayout(VBT->IntroducingObject);
103 CharUnits Offs = VBT->NonVirtualOffset;
104 Offs += SubobjectLayout.getVBPtrOffset();
105 if (VBT->getVBaseWithVPtr())
106 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
107 VBPtrOffsets.push_back(Offs);
109 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
113 StringRef GetPureVirtualCallName() override { return "_purecall"; }
114 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
116 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
117 Address Ptr, QualType ElementType,
118 const CXXDestructorDecl *Dtor) override;
120 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
121 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
123 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
125 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
126 const VPtrInfo &Info);
128 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
130 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
132 /// MSVC needs an extra flag to indicate a catchall.
133 CatchTypeInfo getCatchAllTypeInfo() override {
134 // For -EHa catch(...) must handle HW exception
135 // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
136 if (getContext().getLangOpts().EHAsynch)
137 return CatchTypeInfo{nullptr, 0};
139 return CatchTypeInfo{nullptr, 0x40};
142 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
143 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
144 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
146 llvm::Type *StdTypeInfoPtrTy) override;
148 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
149 QualType SrcRecordTy) override;
151 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
152 QualType SrcRecordTy, QualType DestTy,
153 QualType DestRecordTy,
154 llvm::BasicBlock *CastEnd) override;
156 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
157 QualType SrcRecordTy,
158 QualType DestTy) override;
160 bool EmitBadCastCall(CodeGenFunction &CGF) override;
161 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
166 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
167 const CXXRecordDecl *ClassDecl,
168 const CXXRecordDecl *BaseClassDecl) override;
171 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
172 const CXXRecordDecl *RD) override;
175 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
177 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
178 const CXXRecordDecl *RD) override;
180 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
182 // Background on MSVC destructors
183 // ==============================
185 // Both Itanium and MSVC ABIs have destructor variants. The variant names
186 // roughly correspond in the following way:
188 // Base -> no name, just ~Class
189 // Complete -> vbase destructor
190 // Deleting -> scalar deleting destructor
191 // vector deleting destructor
193 // The base and complete destructors are the same as in Itanium, although the
194 // complete destructor does not accept a VTT parameter when there are virtual
195 // bases. A separate mechanism involving vtordisps is used to ensure that
196 // virtual methods of destroyed subobjects are not called.
198 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
199 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
200 // pointer points to an array. The scalar deleting destructor assumes that
201 // bit 2 is zero, and therefore does not contain a loop.
203 // For virtual destructors, only one entry is reserved in the vftable, and it
204 // always points to the vector deleting destructor. The vector deleting
205 // destructor is the most general, so it can be used to destroy objects in
206 // place, delete single heap objects, or delete arrays.
208 // A TU defining a non-inline destructor is only guaranteed to emit a base
209 // destructor, and all of the other variants are emitted on an as-needed basis
210 // in COMDATs. Because a non-base destructor can be emitted in a TU that
211 // lacks a definition for the destructor, non-base destructors must always
212 // delegate to or alias the base destructor.
214 AddedStructorArgCounts
215 buildStructorSignature(GlobalDecl GD,
216 SmallVectorImpl<CanQualType> &ArgTys) override;
218 /// Non-base dtors should be emitted as delegating thunks in this ABI.
219 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
220 CXXDtorType DT) const override {
221 return DT != Dtor_Base;
224 void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
225 const CXXDestructorDecl *Dtor,
226 CXXDtorType DT) const override;
228 llvm::GlobalValue::LinkageTypes
229 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
230 CXXDtorType DT) const override;
232 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
234 const CXXRecordDecl *
235 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
236 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
237 MethodVFTableLocation ML =
238 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
239 // The vbases might be ordered differently in the final overrider object
240 // and the complete object, so the "this" argument may sometimes point to
241 // memory that has no particular type (e.g. past the complete object).
242 // In this case, we just use a generic pointer type.
243 // FIXME: might want to have a more precise type in the non-virtual
244 // multiple inheritance case.
245 if (ML.VBase || !ML.VFPtrOffset.isZero())
248 return MD->getParent();
252 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
254 bool VirtualCall) override;
256 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
257 FunctionArgList &Params) override;
259 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
261 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
262 const CXXConstructorDecl *D,
265 bool Delegating) override;
267 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
268 const CXXDestructorDecl *DD,
271 bool Delegating) override;
273 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
274 CXXDtorType Type, bool ForVirtualBase,
275 bool Delegating, Address This,
276 QualType ThisTy) override;
278 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
279 llvm::GlobalVariable *VTable);
281 void emitVTableDefinitions(CodeGenVTables &CGVT,
282 const CXXRecordDecl *RD) override;
284 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
285 CodeGenFunction::VPtr Vptr) override;
287 /// Don't initialize vptrs if dynamic class
288 /// is marked with with the 'novtable' attribute.
289 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
290 return !VTableClass->hasAttr<MSNoVTableAttr>();
294 getVTableAddressPoint(BaseSubobject Base,
295 const CXXRecordDecl *VTableClass) override;
297 llvm::Value *getVTableAddressPointInStructor(
298 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
299 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
302 getVTableAddressPointForConstExpr(BaseSubobject Base,
303 const CXXRecordDecl *VTableClass) override;
305 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
306 CharUnits VPtrOffset) override;
308 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
309 Address This, llvm::Type *Ty,
310 SourceLocation Loc) override;
312 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
313 const CXXDestructorDecl *Dtor,
314 CXXDtorType DtorType, Address This,
315 DeleteOrMemberCallExpr E) override;
317 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
318 CallArgList &CallArgs) override {
319 assert(GD.getDtorType() == Dtor_Deleting &&
320 "Only deleting destructor thunks are available in this ABI");
321 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
325 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
327 llvm::GlobalVariable *
328 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
329 llvm::GlobalVariable::LinkageTypes Linkage);
331 llvm::GlobalVariable *
332 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
333 const CXXRecordDecl *DstRD) {
334 SmallString<256> OutName;
335 llvm::raw_svector_ostream Out(OutName);
336 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
337 StringRef MangledName = OutName.str();
339 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
342 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
343 unsigned NumEntries = 1 + SrcRD->getNumVBases();
344 SmallVector<llvm::Constant *, 4> Map(NumEntries,
345 llvm::UndefValue::get(CGM.IntTy));
346 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
347 bool AnyDifferent = false;
348 for (const auto &I : SrcRD->vbases()) {
349 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
350 if (!DstRD->isVirtuallyDerivedFrom(VBase))
353 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
354 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
355 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
356 AnyDifferent |= SrcVBIndex != DstVBIndex;
358 // This map would be useless, don't use it.
362 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
363 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
364 llvm::GlobalValue::LinkageTypes Linkage =
365 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
366 ? llvm::GlobalValue::LinkOnceODRLinkage
367 : llvm::GlobalValue::InternalLinkage;
368 auto *VDispMap = new llvm::GlobalVariable(
369 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
370 /*Initializer=*/Init, MangledName);
374 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
375 llvm::GlobalVariable *GV) const;
377 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
378 GlobalDecl GD, bool ReturnAdjustment) override {
380 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
382 if (Linkage == GVA_Internal)
383 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
384 else if (ReturnAdjustment)
385 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
387 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
390 bool exportThunk() override { return false; }
392 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
393 const ThisAdjustment &TA) override;
395 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
396 const ReturnAdjustment &RA) override;
398 void EmitThreadLocalInitFuncs(
399 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
400 ArrayRef<llvm::Function *> CXXThreadLocalInits,
401 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
403 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
404 return getContext().getLangOpts().isCompatibleWithMSVC(
405 LangOptions::MSVC2019_5) &&
406 (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
408 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
409 QualType LValType) override;
411 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
412 llvm::GlobalVariable *DeclPtr,
413 bool PerformInit) override;
414 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
415 llvm::FunctionCallee Dtor,
416 llvm::Constant *Addr) override;
418 // ==== Notes on array cookies =========
420 // MSVC seems to only use cookies when the class has a destructor; a
421 // two-argument usual array deallocation function isn't sufficient.
423 // For example, this code prints "100" and "1":
426 // void *operator new[](size_t sz) {
427 // printf("%u\n", sz);
428 // return malloc(sz);
430 // void operator delete[](void *p, size_t sz) {
431 // printf("%u\n", sz);
436 // A *p = new A[100];
439 // Whereas it prints "104" and "104" if you give A a destructor.
441 bool requiresArrayCookie(const CXXDeleteExpr *expr,
442 QualType elementType) override;
443 bool requiresArrayCookie(const CXXNewExpr *expr) override;
444 CharUnits getArrayCookieSizeImpl(QualType type) override;
445 Address InitializeArrayCookie(CodeGenFunction &CGF,
447 llvm::Value *NumElements,
448 const CXXNewExpr *expr,
449 QualType ElementType) override;
450 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
452 CharUnits cookieSize) override;
454 friend struct MSRTTIBuilder;
456 bool isImageRelative() const {
457 return CGM.getTarget().getPointerWidth(/*AddrSpace=*/0) == 64;
460 // 5 routines for constructing the llvm types for MS RTTI structs.
461 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
462 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
463 TDTypeName += llvm::utostr(TypeInfoString.size());
464 llvm::StructType *&TypeDescriptorType =
465 TypeDescriptorTypeMap[TypeInfoString.size()];
466 if (TypeDescriptorType)
467 return TypeDescriptorType;
468 llvm::Type *FieldTypes[] = {
471 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
473 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
474 return TypeDescriptorType;
477 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
478 if (!isImageRelative())
483 llvm::StructType *getBaseClassDescriptorType() {
484 if (BaseClassDescriptorType)
485 return BaseClassDescriptorType;
486 llvm::Type *FieldTypes[] = {
487 getImageRelativeType(CGM.Int8PtrTy),
493 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
495 BaseClassDescriptorType = llvm::StructType::create(
496 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
497 return BaseClassDescriptorType;
500 llvm::StructType *getClassHierarchyDescriptorType() {
501 if (ClassHierarchyDescriptorType)
502 return ClassHierarchyDescriptorType;
503 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
504 ClassHierarchyDescriptorType = llvm::StructType::create(
505 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
506 llvm::Type *FieldTypes[] = {
510 getImageRelativeType(
511 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
513 ClassHierarchyDescriptorType->setBody(FieldTypes);
514 return ClassHierarchyDescriptorType;
517 llvm::StructType *getCompleteObjectLocatorType() {
518 if (CompleteObjectLocatorType)
519 return CompleteObjectLocatorType;
520 CompleteObjectLocatorType = llvm::StructType::create(
521 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
522 llvm::Type *FieldTypes[] = {
526 getImageRelativeType(CGM.Int8PtrTy),
527 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
528 getImageRelativeType(CompleteObjectLocatorType),
530 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
531 if (!isImageRelative())
532 FieldTypesRef = FieldTypesRef.drop_back();
533 CompleteObjectLocatorType->setBody(FieldTypesRef);
534 return CompleteObjectLocatorType;
537 llvm::GlobalVariable *getImageBase() {
538 StringRef Name = "__ImageBase";
539 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
542 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
544 llvm::GlobalValue::ExternalLinkage,
545 /*Initializer=*/nullptr, Name);
550 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
551 if (!isImageRelative())
554 if (PtrVal->isNullValue())
555 return llvm::Constant::getNullValue(CGM.IntTy);
557 llvm::Constant *ImageBaseAsInt =
558 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
559 llvm::Constant *PtrValAsInt =
560 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
561 llvm::Constant *Diff =
562 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
563 /*HasNUW=*/true, /*HasNSW=*/true);
564 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
568 MicrosoftMangleContext &getMangleContext() {
569 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
572 llvm::Constant *getZeroInt() {
573 return llvm::ConstantInt::get(CGM.IntTy, 0);
576 llvm::Constant *getAllOnesInt() {
577 return llvm::Constant::getAllOnesValue(CGM.IntTy);
580 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
583 GetNullMemberPointerFields(const MemberPointerType *MPT,
584 llvm::SmallVectorImpl<llvm::Constant *> &fields);
586 /// Shared code for virtual base adjustment. Returns the offset from
587 /// the vbptr to the virtual base. Optionally returns the address of the
589 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
591 llvm::Value *VBPtrOffset,
592 llvm::Value *VBTableOffset,
593 llvm::Value **VBPtr = nullptr);
595 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
598 int32_t VBTableOffset,
599 llvm::Value **VBPtr = nullptr) {
600 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
601 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
602 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
603 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
606 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
607 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
608 QualType SrcRecordTy);
610 /// Performs a full virtual base adjustment. Used to dereference
611 /// pointers to members of virtual bases.
612 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
613 const CXXRecordDecl *RD, Address Base,
614 llvm::Value *VirtualBaseAdjustmentOffset,
615 llvm::Value *VBPtrOffset /* optional */);
617 /// Emits a full member pointer with the fields common to data and
618 /// function member pointers.
619 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
620 bool IsMemberFunction,
621 const CXXRecordDecl *RD,
622 CharUnits NonVirtualBaseAdjustment,
623 unsigned VBTableIndex);
625 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
628 /// - Initialize all vbptrs of 'this' with RD as the complete type.
629 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
631 /// Caching wrapper around VBTableBuilder::enumerateVBTables().
632 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
634 /// Generate a thunk for calling a virtual member function MD.
635 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
636 const MethodVFTableLocation &ML);
638 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
642 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
644 bool isZeroInitializable(const MemberPointerType *MPT) override;
646 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
647 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
648 return RD->hasAttr<MSInheritanceAttr>();
651 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
653 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
654 CharUnits offset) override;
655 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
656 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
658 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
661 const MemberPointerType *MPT,
662 bool Inequality) override;
664 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
666 const MemberPointerType *MPT) override;
669 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
670 Address Base, llvm::Value *MemPtr,
671 const MemberPointerType *MPT) override;
673 llvm::Value *EmitNonNullMemberPointerConversion(
674 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
675 CastKind CK, CastExpr::path_const_iterator PathBegin,
676 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
677 CGBuilderTy &Builder);
679 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
681 llvm::Value *Src) override;
683 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
684 llvm::Constant *Src) override;
686 llvm::Constant *EmitMemberPointerConversion(
687 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
688 CastKind CK, CastExpr::path_const_iterator PathBegin,
689 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
692 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
693 Address This, llvm::Value *&ThisPtrForCall,
695 const MemberPointerType *MPT) override;
697 void emitCXXStructor(GlobalDecl GD) override;
699 llvm::StructType *getCatchableTypeType() {
700 if (CatchableTypeType)
701 return CatchableTypeType;
702 llvm::Type *FieldTypes[] = {
704 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
705 CGM.IntTy, // NonVirtualAdjustment
706 CGM.IntTy, // OffsetToVBPtr
707 CGM.IntTy, // VBTableIndex
709 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
711 CatchableTypeType = llvm::StructType::create(
712 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
713 return CatchableTypeType;
716 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
717 llvm::StructType *&CatchableTypeArrayType =
718 CatchableTypeArrayTypeMap[NumEntries];
719 if (CatchableTypeArrayType)
720 return CatchableTypeArrayType;
722 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
723 CTATypeName += llvm::utostr(NumEntries);
725 getImageRelativeType(getCatchableTypeType()->getPointerTo());
726 llvm::Type *FieldTypes[] = {
727 CGM.IntTy, // NumEntries
728 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
730 CatchableTypeArrayType =
731 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
732 return CatchableTypeArrayType;
735 llvm::StructType *getThrowInfoType() {
737 return ThrowInfoType;
738 llvm::Type *FieldTypes[] = {
740 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
741 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
742 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
744 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
746 return ThrowInfoType;
749 llvm::FunctionCallee getThrowFn() {
750 // _CxxThrowException is passed an exception object and a ThrowInfo object
751 // which describes the exception.
752 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
753 llvm::FunctionType *FTy =
754 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
755 llvm::FunctionCallee Throw =
756 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
757 // _CxxThrowException is stdcall on 32-bit x86 platforms.
758 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
759 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
760 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
765 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
768 llvm::Constant *getCatchableType(QualType T,
769 uint32_t NVOffset = 0,
770 int32_t VBPtrOffset = -1,
771 uint32_t VBIndex = 0);
773 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
775 llvm::GlobalVariable *getThrowInfo(QualType T) override;
777 std::pair<llvm::Value *, const CXXRecordDecl *>
778 LoadVTablePtr(CodeGenFunction &CGF, Address This,
779 const CXXRecordDecl *RD) override;
782 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
785 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
786 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
787 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
788 /// All the vftables that have been referenced.
789 VFTablesMapTy VFTablesMap;
790 VTablesMapTy VTablesMap;
792 /// This set holds the record decls we've deferred vtable emission for.
793 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
796 /// All the vbtables which have been referenced.
797 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
799 /// Info on the global variable used to guard initialization of static locals.
800 /// The BitIndex field is only used for externally invisible declarations.
802 GuardInfo() : Guard(nullptr), BitIndex(0) {}
803 llvm::GlobalVariable *Guard;
807 /// Map from DeclContext to the current guard variable. We assume that the
808 /// AST is visited in source code order.
809 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
810 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
811 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
813 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
814 llvm::StructType *BaseClassDescriptorType;
815 llvm::StructType *ClassHierarchyDescriptorType;
816 llvm::StructType *CompleteObjectLocatorType;
818 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
820 llvm::StructType *CatchableTypeType;
821 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
822 llvm::StructType *ThrowInfoType;
827 CGCXXABI::RecordArgABI
828 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
829 // Use the default C calling convention rules for things that can be passed in
830 // registers, i.e. non-trivially copyable records or records marked with
832 if (RD->canPassInRegisters())
835 switch (CGM.getTarget().getTriple().getArch()) {
837 // FIXME: Implement for other architectures.
840 case llvm::Triple::thumb:
841 // Pass things indirectly for now because it is simple.
842 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
846 case llvm::Triple::x86: {
847 // If the argument has *required* alignment greater than four bytes, pass
848 // it indirectly. Prior to MSVC version 19.14, passing overaligned
849 // arguments was not supported and resulted in a compiler error. In 19.14
850 // and later versions, such arguments are now passed indirectly.
851 TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
852 if (Info.isAlignRequired() && Info.Align > 4)
855 // If C++ prohibits us from making a copy, construct the arguments directly
856 // into argument memory.
857 return RAA_DirectInMemory;
860 case llvm::Triple::x86_64:
861 case llvm::Triple::aarch64:
865 llvm_unreachable("invalid enum");
868 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
869 const CXXDeleteExpr *DE,
871 QualType ElementType,
872 const CXXDestructorDecl *Dtor) {
873 // FIXME: Provide a source location here even though there's no
874 // CXXMemberCallExpr for dtor call.
875 bool UseGlobalDelete = DE->isGlobalDelete();
876 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
877 llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
879 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
882 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
883 llvm::Value *Args[] = {
884 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
885 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
886 llvm::FunctionCallee Fn = getThrowFn();
888 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
890 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
893 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
894 const CXXCatchStmt *S) {
895 // In the MS ABI, the runtime handles the copy, and the catch handler is
896 // responsible for destruction.
897 VarDecl *CatchParam = S->getExceptionDecl();
898 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
899 llvm::CatchPadInst *CPI =
900 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
901 CGF.CurrentFuncletPad = CPI;
903 // If this is a catch-all or the catch parameter is unnamed, we don't need to
904 // emit an alloca to the object.
905 if (!CatchParam || !CatchParam->getDeclName()) {
906 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
910 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
911 CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
912 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
913 CGF.EmitAutoVarCleanups(var);
916 /// We need to perform a generic polymorphic operation (like a typeid
917 /// or a cast), which requires an object with a vfptr. Adjust the
918 /// address to point to an object with a vfptr.
919 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
920 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
921 QualType SrcRecordTy) {
922 Value = CGF.Builder.CreateElementBitCast(Value, CGF.Int8Ty);
923 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
924 const ASTContext &Context = getContext();
926 // If the class itself has a vfptr, great. This check implicitly
927 // covers non-virtual base subobjects: a class with its own virtual
928 // functions would be a candidate to be a primary base.
929 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
930 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
933 // Okay, one of the vbases must have a vfptr, or else this isn't
934 // actually a polymorphic class.
935 const CXXRecordDecl *PolymorphicBase = nullptr;
936 for (auto &Base : SrcDecl->vbases()) {
937 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
938 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
939 PolymorphicBase = BaseDecl;
943 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
945 llvm::Value *Offset =
946 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
947 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
948 Value.getElementType(), Value.getPointer(), Offset);
949 CharUnits VBaseAlign =
950 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
951 return std::make_tuple(Address(Ptr, VBaseAlign), Offset, PolymorphicBase);
954 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
955 QualType SrcRecordTy) {
956 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
958 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
961 static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
962 llvm::Value *Argument) {
963 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
964 llvm::FunctionType *FTy =
965 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
966 llvm::Value *Args[] = {Argument};
967 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
968 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
971 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
972 llvm::CallBase *Call =
973 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
974 Call->setDoesNotReturn();
975 CGF.Builder.CreateUnreachable();
978 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
979 QualType SrcRecordTy,
981 llvm::Type *StdTypeInfoPtrTy) {
982 std::tie(ThisPtr, std::ignore, std::ignore) =
983 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
984 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
985 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
988 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
989 QualType SrcRecordTy) {
990 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
992 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
995 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
996 CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
997 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
998 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1000 llvm::Value *SrcRTTI =
1001 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1002 llvm::Value *DestRTTI =
1003 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1005 llvm::Value *Offset;
1006 std::tie(This, Offset, std::ignore) =
1007 performBaseAdjustment(CGF, This, SrcRecordTy);
1008 llvm::Value *ThisPtr = This.getPointer();
1009 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1011 // PVOID __RTDynamicCast(
1015 // PVOID TargetType,
1016 // BOOL isReference)
1017 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1018 CGF.Int8PtrTy, CGF.Int32Ty};
1019 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1020 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1022 llvm::Value *Args[] = {
1023 ThisPtr, Offset, SrcRTTI, DestRTTI,
1024 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1025 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
1026 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1030 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1031 QualType SrcRecordTy,
1033 std::tie(Value, std::ignore, std::ignore) =
1034 performBaseAdjustment(CGF, Value, SrcRecordTy);
1036 // PVOID __RTCastToVoid(
1038 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1039 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1040 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1042 llvm::Value *Args[] = {Value.getPointer()};
1043 return CGF.EmitRuntimeCall(Function, Args);
1046 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1050 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1051 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1052 const CXXRecordDecl *BaseClassDecl) {
1053 const ASTContext &Context = getContext();
1054 int64_t VBPtrChars =
1055 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1056 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1057 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1058 CharUnits VBTableChars =
1060 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1061 llvm::Value *VBTableOffset =
1062 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1064 llvm::Value *VBPtrToNewBase =
1065 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1067 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1068 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1071 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1072 return isa<CXXConstructorDecl>(GD.getDecl());
1075 static bool isDeletingDtor(GlobalDecl GD) {
1076 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1077 GD.getDtorType() == Dtor_Deleting;
1080 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1081 return isDeletingDtor(GD);
1084 static bool isTrivialForAArch64MSVC(const CXXRecordDecl *RD) {
1085 // For AArch64, we use the C++14 definition of an aggregate, so we also
1087 // No private or protected non static data members.
1089 // No virtual functions
1090 // Additionally, we need to ensure that there is a trivial copy assignment
1091 // operator, a trivial destructor and no user-provided constructors.
1092 if (RD->hasProtectedFields() || RD->hasPrivateFields())
1094 if (RD->getNumBases() > 0)
1096 if (RD->isPolymorphic())
1098 if (RD->hasNonTrivialCopyAssignment())
1100 for (const CXXConstructorDecl *Ctor : RD->ctors())
1101 if (Ctor->isUserProvided())
1103 if (RD->hasNonTrivialDestructor())
1108 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1109 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1113 // Normally, the C++ concept of "is trivially copyable" is used to determine
1114 // if a struct can be returned directly. However, as MSVC and the language
1115 // have evolved, the definition of "trivially copyable" has changed, while the
1116 // ABI must remain stable. AArch64 uses the C++14 concept of an "aggregate",
1117 // while other ISAs use the older concept of "plain old data".
1118 bool isTrivialForABI = RD->isPOD();
1119 bool isAArch64 = CGM.getTarget().getTriple().isAArch64();
1121 isTrivialForABI = RD->canPassInRegisters() && isTrivialForAArch64MSVC(RD);
1123 // MSVC always returns structs indirectly from C++ instance methods.
1124 bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
1126 if (isIndirectReturn) {
1127 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1128 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1130 // MSVC always passes `this` before the `sret` parameter.
1131 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1133 // On AArch64, use the `inreg` attribute if the object is considered to not
1134 // be trivially copyable, or if this is an instance method struct return.
1135 FI.getReturnInfo().setInReg(isAArch64);
1140 // Otherwise, use the C ABI rules.
1145 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1146 const CXXRecordDecl *RD) {
1147 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1148 assert(IsMostDerivedClass &&
1149 "ctor for a class with virtual bases must have an implicit parameter");
1150 llvm::Value *IsCompleteObject =
1151 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1153 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1154 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1155 CGF.Builder.CreateCondBr(IsCompleteObject,
1156 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1158 CGF.EmitBlock(CallVbaseCtorsBB);
1160 // Fill in the vbtable pointers here.
1161 EmitVBPtrStores(CGF, RD);
1163 // CGF will put the base ctor calls in this basic block for us later.
1165 return SkipVbaseCtorsBB;
1169 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1170 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1171 assert(IsMostDerivedClass &&
1172 "ctor for a class with virtual bases must have an implicit parameter");
1173 llvm::Value *IsCompleteObject =
1174 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1176 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1177 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1178 CGF.Builder.CreateCondBr(IsCompleteObject,
1179 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1181 CGF.EmitBlock(CallVbaseDtorsBB);
1182 // CGF will put the base dtor calls in this basic block for us later.
1184 return SkipVbaseDtorsBB;
1187 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1188 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1189 // In most cases, an override for a vbase virtual method can adjust
1190 // the "this" parameter by applying a constant offset.
1191 // However, this is not enough while a constructor or a destructor of some
1192 // class X is being executed if all the following conditions are met:
1193 // - X has virtual bases, (1)
1194 // - X overrides a virtual method M of a vbase Y, (2)
1195 // - X itself is a vbase of the most derived class.
1197 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1198 // which holds the extra amount of "this" adjustment we must do when we use
1199 // the X vftables (i.e. during X ctor or dtor).
1200 // Outside the ctors and dtors, the values of vtorDisps are zero.
1202 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1203 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1204 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1205 CGBuilderTy &Builder = CGF.Builder;
1207 unsigned AS = getThisAddress(CGF).getAddressSpace();
1208 llvm::Value *Int8This = nullptr; // Initialize lazily.
1210 for (const CXXBaseSpecifier &S : RD->vbases()) {
1211 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1212 auto I = VBaseMap.find(VBase);
1213 assert(I != VBaseMap.end());
1214 if (!I->second.hasVtorDisp())
1217 llvm::Value *VBaseOffset =
1218 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1219 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1221 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1222 llvm::Value *VtorDispValue = Builder.CreateSub(
1223 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1225 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1228 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1229 CGF.Int8Ty->getPointerTo(AS));
1230 llvm::Value *VtorDispPtr =
1231 Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
1232 // vtorDisp is always the 32-bits before the vbase in the class layout.
1233 VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
1234 VtorDispPtr = Builder.CreateBitCast(
1235 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1237 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1238 CharUnits::fromQuantity(4));
1242 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1243 const CXXMethodDecl *MD) {
1244 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1245 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1246 CallingConv ActualCallingConv =
1247 MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1248 return ExpectedCallingConv == ActualCallingConv;
1251 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1252 // There's only one constructor type in this ABI.
1253 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1255 // Exported default constructors either have a simple call-site where they use
1256 // the typical calling convention and have a single 'this' pointer for an
1257 // argument -or- they get a wrapper function which appropriately thunks to the
1258 // real default constructor. This thunk is the default constructor closure.
1259 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
1261 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1262 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1263 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1264 CGM.setGVProperties(Fn, D);
1269 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1270 const CXXRecordDecl *RD) {
1271 Address This = getThisAddress(CGF);
1272 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1273 const ASTContext &Context = getContext();
1274 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1276 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1277 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1278 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1279 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1280 const ASTRecordLayout &SubobjectLayout =
1281 Context.getASTRecordLayout(VBT->IntroducingObject);
1282 CharUnits Offs = VBT->NonVirtualOffset;
1283 Offs += SubobjectLayout.getVBPtrOffset();
1284 if (VBT->getVBaseWithVPtr())
1285 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1286 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1287 llvm::Value *GVPtr =
1288 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1289 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1290 "vbptr." + VBT->ObjectWithVPtr->getName());
1291 CGF.Builder.CreateStore(GVPtr, VBPtr);
1295 CGCXXABI::AddedStructorArgCounts
1296 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1297 SmallVectorImpl<CanQualType> &ArgTys) {
1298 AddedStructorArgCounts Added;
1299 // TODO: 'for base' flag
1300 if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1301 GD.getDtorType() == Dtor_Deleting) {
1302 // The scalar deleting destructor takes an implicit int parameter.
1303 ArgTys.push_back(getContext().IntTy);
1306 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1310 // All parameters are already in place except is_most_derived, which goes
1311 // after 'this' if it's variadic and last if it's not.
1313 const CXXRecordDecl *Class = CD->getParent();
1314 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1315 if (Class->getNumVBases()) {
1316 if (FPT->isVariadic()) {
1317 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1320 ArgTys.push_back(getContext().IntTy);
1328 void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1329 const CXXDestructorDecl *Dtor,
1330 CXXDtorType DT) const {
1331 // Deleting destructor variants are never imported or exported. Give them the
1332 // default storage class.
1333 if (DT == Dtor_Deleting) {
1334 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1336 const NamedDecl *ND = Dtor;
1337 CGM.setDLLImportDLLExport(GV, ND);
1341 llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1342 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1343 // Internal things are always internal, regardless of attributes. After this,
1344 // we know the thunk is externally visible.
1345 if (Linkage == GVA_Internal)
1346 return llvm::GlobalValue::InternalLinkage;
1350 // The base destructor most closely tracks the user-declared constructor, so
1351 // we delegate back to the normal declarator case.
1352 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
1353 /*IsConstantVariable=*/false);
1355 // The complete destructor is like an inline function, but it may be
1356 // imported and therefore must be exported as well. This requires changing
1357 // the linkage if a DLL attribute is present.
1358 if (Dtor->hasAttr<DLLExportAttr>())
1359 return llvm::GlobalValue::WeakODRLinkage;
1360 if (Dtor->hasAttr<DLLImportAttr>())
1361 return llvm::GlobalValue::AvailableExternallyLinkage;
1362 return llvm::GlobalValue::LinkOnceODRLinkage;
1364 // Deleting destructors are like inline functions. They have vague linkage
1365 // and are emitted everywhere they are used. They are internal if the class
1367 return llvm::GlobalValue::LinkOnceODRLinkage;
1369 llvm_unreachable("MS C++ ABI does not support comdat dtors");
1371 llvm_unreachable("invalid dtor type");
1374 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1375 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1376 // other destructor variants are delegating thunks.
1377 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1379 // If the class is dllexported, emit the complete (vbase) destructor wherever
1380 // the base dtor is emitted.
1381 // FIXME: To match MSVC, this should only be done when the class is exported
1382 // with -fdllexport-inlines enabled.
1383 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
1384 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1388 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1389 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1391 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1392 // Complete destructors take a pointer to the complete object as a
1393 // parameter, thus don't need this adjustment.
1394 if (GD.getDtorType() == Dtor_Complete)
1397 // There's no Dtor_Base in vftable but it shares the this adjustment with
1398 // the deleting one, so look it up instead.
1399 GD = GlobalDecl(DD, Dtor_Deleting);
1402 MethodVFTableLocation ML =
1403 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1404 CharUnits Adjustment = ML.VFPtrOffset;
1406 // Normal virtual instance methods need to adjust from the vfptr that first
1407 // defined the virtual method to the virtual base subobject, but destructors
1408 // do not. The vector deleting destructor thunk applies this adjustment for
1410 if (isa<CXXDestructorDecl>(MD))
1411 Adjustment = CharUnits::Zero();
1414 const ASTRecordLayout &DerivedLayout =
1415 getContext().getASTRecordLayout(MD->getParent());
1416 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1422 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1423 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1426 // If the call of a virtual function is not virtual, we just have to
1427 // compensate for the adjustment the virtual function does in its prologue.
1428 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1429 if (Adjustment.isZero())
1432 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1433 assert(Adjustment.isPositive());
1434 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1437 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1439 GlobalDecl LookupGD = GD;
1440 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1441 // Complete dtors take a pointer to the complete object,
1442 // thus don't need adjustment.
1443 if (GD.getDtorType() == Dtor_Complete)
1446 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1447 // with the base one, so look up the deleting one instead.
1448 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1450 MethodVFTableLocation ML =
1451 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1453 CharUnits StaticOffset = ML.VFPtrOffset;
1455 // Base destructors expect 'this' to point to the beginning of the base
1456 // subobject, not the first vfptr that happens to contain the virtual dtor.
1457 // However, we still need to apply the virtual base adjustment.
1458 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1459 StaticOffset = CharUnits::Zero();
1461 Address Result = This;
1463 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1465 const CXXRecordDecl *Derived = MD->getParent();
1466 const CXXRecordDecl *VBase = ML.VBase;
1467 llvm::Value *VBaseOffset =
1468 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1469 llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
1470 Result.getElementType(), Result.getPointer(), VBaseOffset);
1471 CharUnits VBaseAlign =
1472 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1473 Result = Address(VBasePtr, VBaseAlign);
1475 if (!StaticOffset.isZero()) {
1476 assert(StaticOffset.isPositive());
1477 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1479 // Non-virtual adjustment might result in a pointer outside the allocated
1480 // object, e.g. if the final overrider class is laid out after the virtual
1481 // base that declares a method in the most derived class.
1482 // FIXME: Update the code that emits this adjustment in thunks prologues.
1483 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1485 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1491 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1493 FunctionArgList &Params) {
1494 ASTContext &Context = getContext();
1495 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1496 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1497 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1498 auto *IsMostDerived = ImplicitParamDecl::Create(
1499 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1500 &Context.Idents.get("is_most_derived"), Context.IntTy,
1501 ImplicitParamDecl::Other);
1502 // The 'most_derived' parameter goes second if the ctor is variadic and last
1503 // if it's not. Dtors can't be variadic.
1504 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1505 if (FPT->isVariadic())
1506 Params.insert(Params.begin() + 1, IsMostDerived);
1508 Params.push_back(IsMostDerived);
1509 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1510 } else if (isDeletingDtor(CGF.CurGD)) {
1511 auto *ShouldDelete = ImplicitParamDecl::Create(
1512 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1513 &Context.Idents.get("should_call_delete"), Context.IntTy,
1514 ImplicitParamDecl::Other);
1515 Params.push_back(ShouldDelete);
1516 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1520 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1521 // Naked functions have no prolog.
1522 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1525 // Overridden virtual methods of non-primary bases need to adjust the incoming
1526 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1527 // sizeof(void*) to adjust from B* to C*:
1528 // struct A { virtual void a(); };
1529 // struct B { virtual void b(); };
1530 // struct C : A, B { virtual void b(); };
1532 // Leave the value stored in the 'this' alloca unadjusted, so that the
1533 // debugger sees the unadjusted value. Microsoft debuggers require this, and
1534 // will apply the ThisAdjustment in the method type information.
1535 // FIXME: Do something better for DWARF debuggers, which won't expect this,
1536 // without making our codegen depend on debug info settings.
1537 llvm::Value *This = loadIncomingCXXThis(CGF);
1538 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1539 if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1540 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1541 if (!Adjustment.isZero()) {
1542 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1543 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1544 *thisTy = This->getType();
1545 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1546 assert(Adjustment.isPositive());
1547 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1548 -Adjustment.getQuantity());
1549 This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
1552 setCXXABIThisValue(CGF, This);
1554 // If this is a function that the ABI specifies returns 'this', initialize
1555 // the return slot to 'this' at the start of the function.
1557 // Unlike the setting of return types, this is done within the ABI
1558 // implementation instead of by clients of CGCXXABI because:
1559 // 1) getThisValue is currently protected
1560 // 2) in theory, an ABI could implement 'this' returns some other way;
1561 // HasThisReturn only specifies a contract, not the implementation
1562 if (HasThisReturn(CGF.CurGD))
1563 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1564 else if (hasMostDerivedReturn(CGF.CurGD))
1565 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1568 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1569 assert(getStructorImplicitParamDecl(CGF) &&
1570 "no implicit parameter for a constructor with virtual bases?");
1571 getStructorImplicitParamValue(CGF)
1572 = CGF.Builder.CreateLoad(
1573 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1577 if (isDeletingDtor(CGF.CurGD)) {
1578 assert(getStructorImplicitParamDecl(CGF) &&
1579 "no implicit parameter for a deleting destructor?");
1580 getStructorImplicitParamValue(CGF)
1581 = CGF.Builder.CreateLoad(
1582 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1583 "should_call_delete");
1587 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1588 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1589 bool ForVirtualBase, bool Delegating) {
1590 assert(Type == Ctor_Complete || Type == Ctor_Base);
1592 // Check if we need a 'most_derived' parameter.
1593 if (!D->getParent()->getNumVBases())
1594 return AddedStructorArgs{};
1596 // Add the 'most_derived' argument second if we are variadic or last if not.
1597 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1598 llvm::Value *MostDerivedArg;
1600 MostDerivedArg = getStructorImplicitParamValue(CGF);
1602 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1604 if (FPT->isVariadic()) {
1605 return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1607 return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1610 llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1611 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
1612 bool ForVirtualBase, bool Delegating) {
1616 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1617 const CXXDestructorDecl *DD,
1618 CXXDtorType Type, bool ForVirtualBase,
1619 bool Delegating, Address This,
1621 // Use the base destructor variant in place of the complete destructor variant
1622 // if the class has no virtual bases. This effectively implements some of the
1623 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1624 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
1627 GlobalDecl GD(DD, Type);
1628 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1630 if (DD->isVirtual()) {
1631 assert(Type != CXXDtorType::Dtor_Deleting &&
1632 "The deleting destructor should only be called via a virtual call");
1633 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1637 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1638 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1639 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1642 llvm::Value *Implicit =
1643 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1644 Delegating); // = nullptr
1645 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1646 /*ImplicitParam=*/Implicit,
1647 /*ImplicitParamTy=*/QualType(), nullptr);
1648 if (BaseDtorEndBB) {
1649 // Complete object handler should continue to be the remaining
1650 CGF.Builder.CreateBr(BaseDtorEndBB);
1651 CGF.EmitBlock(BaseDtorEndBB);
1655 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1656 const CXXRecordDecl *RD,
1657 llvm::GlobalVariable *VTable) {
1658 if (!CGM.getCodeGenOpts().LTOUnit)
1661 // TODO: Should VirtualFunctionElimination also be supported here?
1662 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1663 if (CGM.getCodeGenOpts().WholeProgramVTables) {
1664 llvm::DenseSet<const CXXRecordDecl *> Visited;
1665 llvm::GlobalObject::VCallVisibility TypeVis =
1666 CGM.GetVCallVisibilityLevel(RD, Visited);
1667 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1668 VTable->setVCallVisibilityMetadata(TypeVis);
1671 // The location of the first virtual function pointer in the virtual table,
1672 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1673 // disabled, or sizeof(void*) if RTTI is enabled.
1674 CharUnits AddressPoint =
1675 getContext().getLangOpts().RTTIData
1676 ? getContext().toCharUnitsFromBits(
1677 getContext().getTargetInfo().getPointerWidth(0))
1678 : CharUnits::Zero();
1680 if (Info.PathToIntroducingObject.empty()) {
1681 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1685 // Add a bitset entry for the least derived base belonging to this vftable.
1686 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1687 Info.PathToIntroducingObject.back());
1689 // Add a bitset entry for each derived class that is laid out at the same
1690 // offset as the least derived base.
1691 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1692 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1693 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1695 const ASTRecordLayout &Layout =
1696 getContext().getASTRecordLayout(DerivedRD);
1698 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1699 if (VBI == Layout.getVBaseOffsetsMap().end())
1700 Offset = Layout.getBaseClassOffset(BaseRD);
1702 Offset = VBI->second.VBaseOffset;
1703 if (!Offset.isZero())
1705 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1708 // Finally do the same for the most derived class.
1709 if (Info.FullOffsetInMDC.isZero())
1710 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1713 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1714 const CXXRecordDecl *RD) {
1715 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1716 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1718 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1719 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1720 if (VTable->hasInitializer())
1723 const VTableLayout &VTLayout =
1724 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1726 llvm::Constant *RTTI = nullptr;
1727 if (any_of(VTLayout.vtable_components(),
1728 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1729 RTTI = getMSCompleteObjectLocator(RD, *Info);
1731 ConstantInitBuilder builder(CGM);
1732 auto components = builder.beginStruct();
1733 CGVT.createVTableInitializer(components, VTLayout, RTTI,
1734 VTable->hasLocalLinkage());
1735 components.finishAndSetAsInitializer(VTable);
1737 emitVTableTypeMetadata(*Info, RD, VTable);
1741 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1742 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1743 return Vptr.NearestVBase != nullptr;
1746 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1747 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1748 const CXXRecordDecl *NearestVBase) {
1749 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1750 if (!VTableAddressPoint) {
1751 assert(Base.getBase()->getNumVBases() &&
1752 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1754 return VTableAddressPoint;
1757 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1758 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1759 SmallString<256> &Name) {
1760 llvm::raw_svector_ostream Out(Name);
1761 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1765 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1766 const CXXRecordDecl *VTableClass) {
1767 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1768 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1769 return VFTablesMap[ID];
1772 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1773 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1774 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1775 assert(VFTable && "Couldn't find a vftable for the given base?");
1779 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1780 CharUnits VPtrOffset) {
1781 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1782 // shouldn't be used in the given record type. We want to cache this result in
1783 // VFTablesMap, thus a simple zero check is not sufficient.
1785 VFTableIdTy ID(RD, VPtrOffset);
1786 VTablesMapTy::iterator I;
1788 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1792 llvm::GlobalVariable *&VTable = I->second;
1794 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1795 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1797 if (DeferredVFTables.insert(RD).second) {
1798 // We haven't processed this record type before.
1799 // Queue up this vtable for possible deferred emission.
1800 CGM.addDeferredVTable(RD);
1803 // Create all the vftables at once in order to make sure each vftable has
1804 // a unique mangled name.
1805 llvm::StringSet<> ObservedMangledNames;
1806 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1807 SmallString<256> Name;
1808 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1809 if (!ObservedMangledNames.insert(Name.str()).second)
1810 llvm_unreachable("Already saw this mangling before?");
1815 const std::unique_ptr<VPtrInfo> *VFPtrI =
1816 llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
1817 return VPI->FullOffsetInMDC == VPtrOffset;
1819 if (VFPtrI == VFPtrs.end()) {
1820 VFTablesMap[ID] = nullptr;
1823 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1825 SmallString<256> VFTableName;
1826 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1828 // Classes marked __declspec(dllimport) need vftables generated on the
1829 // import-side in order to support features like constexpr. No other
1830 // translation unit relies on the emission of the local vftable, translation
1831 // units are expected to generate them as needed.
1833 // Because of this unique behavior, we maintain this logic here instead of
1834 // getVTableLinkage.
1835 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1836 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1837 : CGM.getVTableLinkage(RD);
1838 bool VFTableComesFromAnotherTU =
1839 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1840 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1841 bool VTableAliasIsRequred =
1842 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1844 if (llvm::GlobalValue *VFTable =
1845 CGM.getModule().getNamedGlobal(VFTableName)) {
1846 VFTablesMap[ID] = VFTable;
1847 VTable = VTableAliasIsRequred
1848 ? cast<llvm::GlobalVariable>(
1849 cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
1850 : cast<llvm::GlobalVariable>(VFTable);
1854 const VTableLayout &VTLayout =
1855 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1856 llvm::GlobalValue::LinkageTypes VTableLinkage =
1857 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1859 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1861 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1863 // Create a backing variable for the contents of VTable. The VTable may
1864 // or may not include space for a pointer to RTTI data.
1865 llvm::GlobalValue *VFTable;
1866 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1867 /*isConstant=*/true, VTableLinkage,
1868 /*Initializer=*/nullptr, VTableName);
1869 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1871 llvm::Comdat *C = nullptr;
1872 if (!VFTableComesFromAnotherTU &&
1873 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1874 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1875 VTableAliasIsRequred)))
1876 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1878 // Only insert a pointer into the VFTable for RTTI data if we are not
1879 // importing it. We never reference the RTTI data directly so there is no
1880 // need to make room for it.
1881 if (VTableAliasIsRequred) {
1882 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1883 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1884 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1885 // Create a GEP which points just after the first entry in the VFTable,
1886 // this should be the location of the first virtual method.
1887 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1888 VTable->getValueType(), VTable, GEPIndices);
1889 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1890 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1892 C->setSelectionKind(llvm::Comdat::Largest);
1894 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1895 /*AddressSpace=*/0, VFTableLinkage,
1896 VFTableName.str(), VTableGEP,
1898 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1900 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1901 // be referencing any RTTI data.
1902 // The GlobalVariable will end up being an appropriate definition of the
1907 VTable->setComdat(C);
1909 if (RD->hasAttr<DLLExportAttr>())
1910 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1912 VFTablesMap[ID] = VFTable;
1916 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1920 SourceLocation Loc) {
1921 CGBuilderTy &Builder = CGF.Builder;
1923 Ty = Ty->getPointerTo();
1925 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1927 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1928 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
1929 MethodDecl->getParent());
1931 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1932 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
1934 // Compute the identity of the most derived class whose virtual table is
1935 // located at the MethodVFTableLocation ML.
1936 auto getObjectWithVPtr = [&] {
1937 return llvm::find_if(VFTContext.getVFPtrOffsets(
1938 ML.VBase ? ML.VBase : MethodDecl->getParent()),
1939 [&](const std::unique_ptr<VPtrInfo> &Info) {
1940 return Info->FullOffsetInMDC == ML.VFPtrOffset;
1947 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1948 VFunc = CGF.EmitVTableTypeCheckedLoad(
1949 getObjectWithVPtr(), VTable,
1950 ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1952 if (CGM.getCodeGenOpts().PrepareForLTO)
1953 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1955 llvm::Value *VFuncPtr =
1956 Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
1957 VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
1960 CGCallee Callee(GD, VFunc);
1964 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1965 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1966 Address This, DeleteOrMemberCallExpr E) {
1967 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1968 auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1969 assert((CE != nullptr) ^ (D != nullptr));
1970 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1971 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1973 // We have only one destructor in the vftable but can get both behaviors
1974 // by passing an implicit int parameter.
1975 GlobalDecl GD(Dtor, Dtor_Deleting);
1976 const CGFunctionInfo *FInfo =
1977 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
1978 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1979 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
1981 ASTContext &Context = getContext();
1982 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1983 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1984 DtorType == Dtor_Deleting);
1988 ThisTy = CE->getObjectType();
1990 ThisTy = D->getDestroyedType();
1993 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1994 RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1995 ImplicitParam, Context.IntTy, CE);
1996 return RV.getScalarVal();
1999 const VBTableGlobals &
2000 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
2001 // At this layer, we can key the cache off of a single class, which is much
2002 // easier than caching each vbtable individually.
2003 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
2005 std::tie(Entry, Added) =
2006 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
2007 VBTableGlobals &VBGlobals = Entry->second;
2011 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2012 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
2014 // Cache the globals for all vbtables so we don't have to recompute the
2016 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2017 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
2018 E = VBGlobals.VBTables->end();
2020 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
2027 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
2028 const MethodVFTableLocation &ML) {
2029 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
2030 "can't form pointers to ctors or virtual dtors");
2032 // Calculate the mangled name.
2033 SmallString<256> ThunkName;
2034 llvm::raw_svector_ostream Out(ThunkName);
2035 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
2037 // If the thunk has been generated previously, just return it.
2038 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
2039 return cast<llvm::Function>(GV);
2041 // Create the llvm::Function.
2042 const CGFunctionInfo &FnInfo =
2043 CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
2044 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2045 llvm::Function *ThunkFn =
2046 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2047 ThunkName.str(), &CGM.getModule());
2048 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2050 ThunkFn->setLinkage(MD->isExternallyVisible()
2051 ? llvm::GlobalValue::LinkOnceODRLinkage
2052 : llvm::GlobalValue::InternalLinkage);
2053 if (MD->isExternallyVisible())
2054 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2056 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
2057 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
2059 // Add the "thunk" attribute so that LLVM knows that the return type is
2060 // meaningless. These thunks can be used to call functions with differing
2061 // return types, and the caller is required to cast the prototype
2062 // appropriately to extract the correct value.
2063 ThunkFn->addFnAttr("thunk");
2065 // These thunks can be compared, so they are not unnamed.
2066 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2069 CodeGenFunction CGF(CGM);
2070 CGF.CurGD = GlobalDecl(MD);
2071 CGF.CurFuncIsThunk = true;
2073 // Build FunctionArgs, but only include the implicit 'this' parameter
2075 FunctionArgList FunctionArgs;
2076 buildThisParam(CGF, FunctionArgs);
2078 // Start defining the function.
2079 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2080 FunctionArgs, MD->getLocation(), SourceLocation());
2081 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2083 // Load the vfptr and then callee from the vftable. The callee should have
2084 // adjusted 'this' so that the vfptr is at offset zero.
2085 llvm::Type *ThunkPtrTy = ThunkTy->getPointerTo();
2086 llvm::Value *VTable = CGF.GetVTablePtr(
2087 getThisAddress(CGF), ThunkPtrTy->getPointerTo(), MD->getParent());
2089 llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2090 ThunkPtrTy, VTable, ML.Index, "vfn");
2091 llvm::Value *Callee =
2092 CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
2094 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2099 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2100 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2101 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2102 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2103 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2104 if (GV->isDeclaration())
2105 emitVBTableDefinition(*VBT, RD, GV);
2109 llvm::GlobalVariable *
2110 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2111 llvm::GlobalVariable::LinkageTypes Linkage) {
2112 SmallString<256> OutName;
2113 llvm::raw_svector_ostream Out(OutName);
2114 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2115 StringRef Name = OutName.str();
2117 llvm::ArrayType *VBTableType =
2118 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2120 assert(!CGM.getModule().getNamedGlobal(Name) &&
2121 "vbtable with this name already exists: mangling bug?");
2122 CharUnits Alignment =
2123 CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
2124 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2125 Name, VBTableType, Linkage, Alignment.getQuantity());
2126 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2128 if (RD->hasAttr<DLLImportAttr>())
2129 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2130 else if (RD->hasAttr<DLLExportAttr>())
2131 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2133 if (!GV->hasExternalLinkage())
2134 emitVBTableDefinition(VBT, RD, GV);
2139 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2140 const CXXRecordDecl *RD,
2141 llvm::GlobalVariable *GV) const {
2142 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2144 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2145 "should only emit vbtables for classes with vbtables");
2147 const ASTRecordLayout &BaseLayout =
2148 getContext().getASTRecordLayout(VBT.IntroducingObject);
2149 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2151 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2154 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2155 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2156 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2158 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2159 for (const auto &I : ObjectWithVPtr->vbases()) {
2160 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2161 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2162 assert(!Offset.isNegative());
2164 // Make it relative to the subobject vbptr.
2165 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2166 if (VBT.getVBaseWithVPtr())
2167 CompleteVBPtrOffset +=
2168 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2169 Offset -= CompleteVBPtrOffset;
2171 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2172 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2173 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2176 assert(Offsets.size() ==
2177 cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
2178 llvm::ArrayType *VBTableType =
2179 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2180 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2181 GV->setInitializer(Init);
2183 if (RD->hasAttr<DLLImportAttr>())
2184 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2187 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2189 const ThisAdjustment &TA) {
2191 return This.getPointer();
2193 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2196 if (TA.Virtual.isEmpty()) {
2197 V = This.getPointer();
2199 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2200 // Adjust the this argument based on the vtordisp value.
2201 Address VtorDispPtr =
2202 CGF.Builder.CreateConstInBoundsByteGEP(This,
2203 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2204 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2205 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2206 V = CGF.Builder.CreateGEP(This.getElementType(), This.getPointer(),
2207 CGF.Builder.CreateNeg(VtorDisp));
2209 // Unfortunately, having applied the vtordisp means that we no
2210 // longer really have a known alignment for the vbptr step.
2211 // We'll assume the vbptr is pointer-aligned.
2213 if (TA.Virtual.Microsoft.VBPtrOffset) {
2214 // If the final overrider is defined in a virtual base other than the one
2215 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2216 // the vbtable of the derived class.
2217 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2218 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2220 llvm::Value *VBaseOffset =
2221 GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
2222 -TA.Virtual.Microsoft.VBPtrOffset,
2223 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2224 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2228 if (TA.NonVirtual) {
2229 // Non-virtual adjustment might result in a pointer outside the allocated
2230 // object, e.g. if the final overrider class is laid out after the virtual
2231 // base that declares a method in the most derived class.
2232 V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
2235 // Don't need to bitcast back, the call CodeGen will handle this.
2240 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2241 const ReturnAdjustment &RA) {
2243 return Ret.getPointer();
2245 auto OrigTy = Ret.getType();
2246 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2248 llvm::Value *V = Ret.getPointer();
2249 if (RA.Virtual.Microsoft.VBIndex) {
2250 assert(RA.Virtual.Microsoft.VBIndex > 0);
2251 int32_t IntSize = CGF.getIntSize().getQuantity();
2253 llvm::Value *VBaseOffset =
2254 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2255 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2256 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2260 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2262 // Cast back to the original type.
2263 return CGF.Builder.CreateBitCast(V, OrigTy);
2266 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2267 QualType elementType) {
2268 // Microsoft seems to completely ignore the possibility of a
2269 // two-argument usual deallocation function.
2270 return elementType.isDestructedType();
2273 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2274 // Microsoft seems to completely ignore the possibility of a
2275 // two-argument usual deallocation function.
2276 return expr->getAllocatedType().isDestructedType();
2279 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2280 // The array cookie is always a size_t; we then pad that out to the
2281 // alignment of the element type.
2282 ASTContext &Ctx = getContext();
2283 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2284 Ctx.getTypeAlignInChars(type));
2287 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2289 CharUnits cookieSize) {
2290 Address numElementsPtr =
2291 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2292 return CGF.Builder.CreateLoad(numElementsPtr);
2295 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2297 llvm::Value *numElements,
2298 const CXXNewExpr *expr,
2299 QualType elementType) {
2300 assert(requiresArrayCookie(expr));
2302 // The size of the cookie.
2303 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2305 // Compute an offset to the cookie.
2306 Address cookiePtr = newPtr;
2308 // Write the number of elements into the appropriate slot.
2309 Address numElementsPtr
2310 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2311 CGF.Builder.CreateStore(numElements, numElementsPtr);
2313 // Finally, compute a pointer to the actual data buffer by skipping
2314 // over the cookie completely.
2315 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2318 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2319 llvm::FunctionCallee Dtor,
2320 llvm::Constant *Addr) {
2321 // Create a function which calls the destructor.
2322 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2324 // extern "C" int __tlregdtor(void (*f)(void));
2325 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2326 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2328 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2329 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2330 if (llvm::Function *TLRegDtorFn =
2331 dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2332 TLRegDtorFn->setDoesNotThrow();
2334 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2337 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2338 llvm::FunctionCallee Dtor,
2339 llvm::Constant *Addr) {
2340 if (D.isNoDestroy(CGM.getContext()))
2344 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2346 // The default behavior is to use atexit.
2347 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2350 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2351 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2352 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2353 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2354 if (CXXThreadLocalInits.empty())
2357 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2359 ? "/include:___dyn_tls_init@12"
2360 : "/include:__dyn_tls_init");
2362 // This will create a GV in the .CRT$XDU section. It will point to our
2363 // initialization function. The CRT will call all of these function
2364 // pointers at start-up time and, eventually, at thread-creation time.
2365 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2366 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2367 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2368 llvm::GlobalVariable::InternalLinkage, InitFunc,
2369 Twine(InitFunc->getName(), "$initializer$"));
2370 InitFuncPtr->setSection(".CRT$XDU");
2371 // This variable has discardable linkage, we have to add it to @llvm.used to
2372 // ensure it won't get discarded.
2373 CGM.addUsedGlobal(InitFuncPtr);
2377 std::vector<llvm::Function *> NonComdatInits;
2378 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2379 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2380 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2381 llvm::Function *F = CXXThreadLocalInits[I];
2383 // If the GV is already in a comdat group, then we have to join it.
2384 if (llvm::Comdat *C = GV->getComdat())
2385 AddToXDU(F)->setComdat(C);
2387 NonComdatInits.push_back(F);
2390 if (!NonComdatInits.empty()) {
2391 llvm::FunctionType *FTy =
2392 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2393 llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
2394 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2395 SourceLocation(), /*TLS=*/true);
2396 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2402 static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
2403 // __tls_guard comes from the MSVC runtime and reflects
2404 // whether TLS has been initialized for a particular thread.
2405 // It is set from within __dyn_tls_init by the runtime.
2406 // Every library and executable has its own variable.
2407 llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
2408 llvm::Constant *TlsGuardConstant =
2409 CGM.CreateRuntimeVariable(VTy, "__tls_guard");
2410 llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
2412 TlsGuard->setThreadLocal(true);
2417 static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
2418 // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
2419 // dynamic TLS initialization by calling __dyn_tls_init internally.
2420 llvm::FunctionType *FTy =
2421 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
2422 /*isVarArg=*/false);
2423 return CGM.CreateRuntimeFunction(
2424 FTy, "__dyn_tls_on_demand_init",
2425 llvm::AttributeList::get(CGM.getLLVMContext(),
2426 llvm::AttributeList::FunctionIndex,
2427 llvm::Attribute::NoUnwind),
2431 static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
2432 llvm::BasicBlock *DynInitBB,
2433 llvm::BasicBlock *ContinueBB) {
2434 llvm::LoadInst *TlsGuardValue =
2435 CGF.Builder.CreateLoad(Address(TlsGuard, CharUnits::One()));
2436 llvm::Value *CmpResult =
2437 CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
2438 CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
2441 static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,
2442 llvm::GlobalValue *TlsGuard,
2443 llvm::BasicBlock *ContinueBB) {
2444 llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
2445 llvm::Function *InitializerFunction =
2446 cast<llvm::Function>(Initializer.getCallee());
2447 llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
2448 CallVal->setCallingConv(InitializerFunction->getCallingConv());
2450 CGF.Builder.CreateBr(ContinueBB);
2453 static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {
2454 llvm::BasicBlock *DynInitBB =
2455 CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
2456 llvm::BasicBlock *ContinueBB =
2457 CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
2459 llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
2461 emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
2462 CGF.Builder.SetInsertPoint(DynInitBB);
2463 emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
2464 CGF.Builder.SetInsertPoint(ContinueBB);
2467 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2469 QualType LValType) {
2470 // Dynamic TLS initialization works by checking the state of a
2471 // guard variable (__tls_guard) to see whether TLS initialization
2472 // for a thread has happend yet.
2473 // If not, the initialization is triggered on-demand
2474 // by calling __dyn_tls_on_demand_init.
2475 emitDynamicTlsInitialization(CGF);
2477 // Emit the variable just like any regular global variable.
2479 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2480 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2482 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2483 V = CGF.Builder.CreateBitCast(V, RealVarTy->getPointerTo(AS));
2485 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2486 Address Addr(V, Alignment);
2488 LValue LV = VD->getType()->isReferenceType()
2489 ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2490 AlignmentSource::Decl)
2491 : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
2495 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2496 StringRef VarName("_Init_thread_epoch");
2497 CharUnits Align = CGM.getIntAlign();
2498 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2499 return ConstantAddress(GV, GV->getValueType(), Align);
2500 auto *GV = new llvm::GlobalVariable(
2501 CGM.getModule(), CGM.IntTy,
2502 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2503 /*Initializer=*/nullptr, VarName,
2504 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2505 GV->setAlignment(Align.getAsAlign());
2506 return ConstantAddress(GV, GV->getValueType(), Align);
2509 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2510 llvm::FunctionType *FTy =
2511 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2512 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2513 return CGM.CreateRuntimeFunction(
2514 FTy, "_Init_thread_header",
2515 llvm::AttributeList::get(CGM.getLLVMContext(),
2516 llvm::AttributeList::FunctionIndex,
2517 llvm::Attribute::NoUnwind),
2521 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2522 llvm::FunctionType *FTy =
2523 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2524 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2525 return CGM.CreateRuntimeFunction(
2526 FTy, "_Init_thread_footer",
2527 llvm::AttributeList::get(CGM.getLLVMContext(),
2528 llvm::AttributeList::FunctionIndex,
2529 llvm::Attribute::NoUnwind),
2533 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2534 llvm::FunctionType *FTy =
2535 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2536 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2537 return CGM.CreateRuntimeFunction(
2538 FTy, "_Init_thread_abort",
2539 llvm::AttributeList::get(CGM.getLLVMContext(),
2540 llvm::AttributeList::FunctionIndex,
2541 llvm::Attribute::NoUnwind),
2546 struct ResetGuardBit final : EHScopeStack::Cleanup {
2549 ResetGuardBit(Address Guard, unsigned GuardNum)
2550 : Guard(Guard), GuardNum(GuardNum) {}
2552 void Emit(CodeGenFunction &CGF, Flags flags) override {
2553 // Reset the bit in the mask so that the static variable may be
2555 CGBuilderTy &Builder = CGF.Builder;
2556 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2557 llvm::ConstantInt *Mask =
2558 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2559 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2563 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2565 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2567 void Emit(CodeGenFunction &CGF, Flags flags) override {
2568 // Calling _Init_thread_abort will reset the guard's state.
2569 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2574 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2575 llvm::GlobalVariable *GV,
2577 // MSVC only uses guards for static locals.
2578 if (!D.isStaticLocal()) {
2579 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2580 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2581 llvm::Function *F = CGF.CurFn;
2582 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2583 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2584 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2588 bool ThreadlocalStatic = D.getTLSKind();
2589 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2591 // Thread-safe static variables which aren't thread-specific have a
2592 // per-variable guard.
2593 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2595 CGBuilderTy &Builder = CGF.Builder;
2596 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2597 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2598 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2600 // Get the guard variable for this function if we have one already.
2601 GuardInfo *GI = nullptr;
2602 if (ThreadlocalStatic)
2603 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2604 else if (!ThreadsafeStatic)
2605 GI = &GuardVariableMap[D.getDeclContext()];
2607 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2609 if (D.isExternallyVisible()) {
2610 // Externally visible variables have to be numbered in Sema to properly
2611 // handle unreachable VarDecls.
2612 GuardNum = getContext().getStaticLocalNumber(&D);
2613 assert(GuardNum > 0);
2615 } else if (HasPerVariableGuard) {
2616 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2618 // Non-externally visible variables are numbered here in CodeGen.
2619 GuardNum = GI->BitIndex++;
2622 if (!HasPerVariableGuard && GuardNum >= 32) {
2623 if (D.isExternallyVisible())
2624 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2630 // Mangle the name for the guard.
2631 SmallString<256> GuardName;
2633 llvm::raw_svector_ostream Out(GuardName);
2634 if (HasPerVariableGuard)
2635 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2638 getMangleContext().mangleStaticGuardVariable(&D, Out);
2641 // Create the guard variable with a zero-initializer. Just absorb linkage,
2642 // visibility and dll storage class from the guarded variable.
2644 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2645 GV->getLinkage(), Zero, GuardName.str());
2646 GuardVar->setVisibility(GV->getVisibility());
2647 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2648 GuardVar->setAlignment(GuardAlign.getAsAlign());
2649 if (GuardVar->isWeakForLinker())
2650 GuardVar->setComdat(
2651 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2653 CGM.setTLSMode(GuardVar, D);
2654 if (GI && !HasPerVariableGuard)
2655 GI->Guard = GuardVar;
2658 ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
2660 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2661 "static local from the same function had different linkage");
2663 if (!HasPerVariableGuard) {
2664 // Pseudo code for the test:
2665 // if (!(GuardVar & MyGuardBit)) {
2666 // GuardVar |= MyGuardBit;
2667 // ... initialize the object ...;
2670 // Test our bit from the guard variable.
2671 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2672 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2673 llvm::Value *NeedsInit =
2674 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2675 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2676 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2677 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2678 CodeGenFunction::GuardKind::VariableGuard, &D);
2680 // Set our bit in the guard variable and emit the initializer and add a global
2681 // destructor if appropriate.
2682 CGF.EmitBlock(InitBlock);
2683 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2684 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2685 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2686 CGF.PopCleanupBlock();
2687 Builder.CreateBr(EndBlock);
2690 CGF.EmitBlock(EndBlock);
2692 // Pseudo code for the test:
2693 // if (TSS > _Init_thread_epoch) {
2694 // _Init_thread_header(&TSS);
2696 // ... initialize the object ...;
2697 // _Init_thread_footer(&TSS);
2701 // The algorithm is almost identical to what can be found in the appendix
2704 // This BasicBLock determines whether or not we have any work to do.
2705 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2706 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2707 llvm::LoadInst *InitThreadEpoch =
2708 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2709 llvm::Value *IsUninitialized =
2710 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2711 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2712 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2713 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2714 CodeGenFunction::GuardKind::VariableGuard, &D);
2716 // This BasicBlock attempts to determine whether or not this thread is
2717 // responsible for doing the initialization.
2718 CGF.EmitBlock(AttemptInitBlock);
2719 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2720 GuardAddr.getPointer());
2721 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2722 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2723 llvm::Value *ShouldDoInit =
2724 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2725 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2726 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2728 // Ok, we ended up getting selected as the initializing thread.
2729 CGF.EmitBlock(InitBlock);
2730 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2731 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2732 CGF.PopCleanupBlock();
2733 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2734 GuardAddr.getPointer());
2735 Builder.CreateBr(EndBlock);
2737 CGF.EmitBlock(EndBlock);
2741 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2742 // Null-ness for function memptrs only depends on the first field, which is
2743 // the function pointer. The rest don't matter, so we can zero initialize.
2744 if (MPT->isMemberFunctionPointer())
2747 // The virtual base adjustment field is always -1 for null, so if we have one
2748 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2749 // valid field offset.
2750 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2751 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2752 return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2753 RD->nullFieldOffsetIsZero());
2757 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2758 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2759 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2760 llvm::SmallVector<llvm::Type *, 4> fields;
2761 if (MPT->isMemberFunctionPointer())
2762 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2764 fields.push_back(CGM.IntTy); // FieldOffset
2766 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2768 fields.push_back(CGM.IntTy);
2769 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2770 fields.push_back(CGM.IntTy);
2771 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2772 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2774 if (fields.size() == 1)
2776 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2779 void MicrosoftCXXABI::
2780 GetNullMemberPointerFields(const MemberPointerType *MPT,
2781 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2782 assert(fields.empty());
2783 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2784 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2785 if (MPT->isMemberFunctionPointer()) {
2786 // FunctionPointerOrVirtualThunk
2787 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2789 if (RD->nullFieldOffsetIsZero())
2790 fields.push_back(getZeroInt()); // FieldOffset
2792 fields.push_back(getAllOnesInt()); // FieldOffset
2795 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2797 fields.push_back(getZeroInt());
2798 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2799 fields.push_back(getZeroInt());
2800 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2801 fields.push_back(getAllOnesInt());
2805 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2806 llvm::SmallVector<llvm::Constant *, 4> fields;
2807 GetNullMemberPointerFields(MPT, fields);
2808 if (fields.size() == 1)
2810 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2811 assert(Res->getType() == ConvertMemberPointerType(MPT));
2816 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2817 bool IsMemberFunction,
2818 const CXXRecordDecl *RD,
2819 CharUnits NonVirtualBaseAdjustment,
2820 unsigned VBTableIndex) {
2821 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2823 // Single inheritance class member pointer are represented as scalars instead
2825 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2828 llvm::SmallVector<llvm::Constant *, 4> fields;
2829 fields.push_back(FirstField);
2831 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2832 fields.push_back(llvm::ConstantInt::get(
2833 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2835 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2836 CharUnits Offs = CharUnits::Zero();
2838 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2839 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2842 // The rest of the fields are adjusted by conversions to a more derived class.
2843 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2844 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2846 return llvm::ConstantStruct::getAnon(fields);
2850 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2852 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2855 llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2857 if (RD->getMSInheritanceModel() ==
2858 MSInheritanceModel::Virtual)
2859 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2860 llvm::Constant *FirstField =
2861 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2862 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2863 CharUnits::Zero(), /*VBTableIndex=*/0);
2866 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2868 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2869 const ValueDecl *MPD = MP.getMemberPointerDecl();
2871 return EmitNullMemberPointer(DstTy);
2873 ASTContext &Ctx = getContext();
2874 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2877 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2878 C = EmitMemberFunctionPointer(MD);
2880 // For a pointer to data member, start off with the offset of the field in
2881 // the class in which it was declared, and convert from there if necessary.
2882 // For indirect field decls, get the outermost anonymous field and use the
2884 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2885 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2887 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2888 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2889 RD = RD->getMostRecentNonInjectedDecl();
2890 C = EmitMemberDataPointer(RD, FieldOffset);
2893 if (!MemberPointerPath.empty()) {
2894 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2895 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2896 const MemberPointerType *SrcTy =
2897 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2898 ->castAs<MemberPointerType>();
2900 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2901 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2902 const CXXRecordDecl *PrevRD = SrcRD;
2903 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2904 const CXXRecordDecl *Base = nullptr;
2905 const CXXRecordDecl *Derived = nullptr;
2906 if (DerivedMember) {
2913 for (const CXXBaseSpecifier &BS : Derived->bases())
2914 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2915 Base->getCanonicalDecl())
2916 DerivedToBasePath.push_back(&BS);
2919 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2921 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2922 : CK_BaseToDerivedMemberPointer;
2923 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2924 DerivedToBasePath.end(), C);
2930 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2931 assert(MD->isInstance() && "Member function must not be static!");
2933 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2934 const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
2935 CodeGenTypes &Types = CGM.getTypes();
2937 unsigned VBTableIndex = 0;
2938 llvm::Constant *FirstField;
2939 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2940 if (!MD->isVirtual()) {
2942 // Check whether the function has a computable LLVM signature.
2943 if (Types.isFuncTypeConvertible(FPT)) {
2944 // The function has a computable LLVM signature; use the correct type.
2945 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2947 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2948 // function type is incomplete.
2951 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2953 auto &VTableContext = CGM.getMicrosoftVTableContext();
2954 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2955 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2956 // Include the vfptr adjustment if the method is in a non-primary vftable.
2957 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2959 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2962 if (VBTableIndex == 0 &&
2963 RD->getMSInheritanceModel() ==
2964 MSInheritanceModel::Virtual)
2965 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2967 // The rest of the fields are common with data member pointers.
2968 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2969 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2970 NonVirtualBaseAdjustment, VBTableIndex);
2973 /// Member pointers are the same if they're either bitwise identical *or* both
2974 /// null. Null-ness for function members is determined by the first field,
2975 /// while for data member pointers we must compare all fields.
2977 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2980 const MemberPointerType *MPT,
2982 CGBuilderTy &Builder = CGF.Builder;
2984 // Handle != comparisons by switching the sense of all boolean operations.
2985 llvm::ICmpInst::Predicate Eq;
2986 llvm::Instruction::BinaryOps And, Or;
2988 Eq = llvm::ICmpInst::ICMP_NE;
2989 And = llvm::Instruction::Or;
2990 Or = llvm::Instruction::And;
2992 Eq = llvm::ICmpInst::ICMP_EQ;
2993 And = llvm::Instruction::And;
2994 Or = llvm::Instruction::Or;
2997 // If this is a single field member pointer (single inheritance), this is a
2999 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3000 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3001 if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
3003 return Builder.CreateICmp(Eq, L, R);
3005 // Compare the first field.
3006 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
3007 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
3008 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
3010 // Compare everything other than the first field.
3011 llvm::Value *Res = nullptr;
3012 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
3013 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
3014 llvm::Value *LF = Builder.CreateExtractValue(L, I);
3015 llvm::Value *RF = Builder.CreateExtractValue(R, I);
3016 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
3018 Res = Builder.CreateBinOp(And, Res, Cmp);
3023 // Check if the first field is 0 if this is a function pointer.
3024 if (MPT->isMemberFunctionPointer()) {
3025 // (l1 == r1 && ...) || l0 == 0
3026 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
3027 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
3028 Res = Builder.CreateBinOp(Or, Res, IsZero);
3031 // Combine the comparison of the first field, which must always be true for
3032 // this comparison to succeeed.
3033 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
3037 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
3038 llvm::Value *MemPtr,
3039 const MemberPointerType *MPT) {
3040 CGBuilderTy &Builder = CGF.Builder;
3041 llvm::SmallVector<llvm::Constant *, 4> fields;
3042 // We only need one field for member functions.
3043 if (MPT->isMemberFunctionPointer())
3044 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
3046 GetNullMemberPointerFields(MPT, fields);
3047 assert(!fields.empty());
3048 llvm::Value *FirstField = MemPtr;
3049 if (MemPtr->getType()->isStructTy())
3050 FirstField = Builder.CreateExtractValue(MemPtr, 0);
3051 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
3053 // For function member pointers, we only need to test the function pointer
3054 // field. The other fields if any can be garbage.
3055 if (MPT->isMemberFunctionPointer())
3058 // Otherwise, emit a series of compares and combine the results.
3059 for (int I = 1, E = fields.size(); I < E; ++I) {
3060 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
3061 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
3062 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
3067 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
3068 llvm::Constant *Val) {
3069 // Function pointers are null if the pointer in the first field is null.
3070 if (MPT->isMemberFunctionPointer()) {
3071 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
3072 Val->getAggregateElement(0U) : Val;
3073 return FirstField->isNullValue();
3076 // If it's not a function pointer and it's zero initializable, we can easily
3078 if (isZeroInitializable(MPT) && Val->isNullValue())
3081 // Otherwise, break down all the fields for comparison. Hopefully these
3082 // little Constants are reused, while a big null struct might not be.
3083 llvm::SmallVector<llvm::Constant *, 4> Fields;
3084 GetNullMemberPointerFields(MPT, Fields);
3085 if (Fields.size() == 1) {
3086 assert(Val->getType()->isIntegerTy());
3087 return Val == Fields[0];
3091 for (I = 0, E = Fields.size(); I != E; ++I) {
3092 if (Val->getAggregateElement(I) != Fields[I])
3099 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
3101 llvm::Value *VBPtrOffset,
3102 llvm::Value *VBTableOffset,
3103 llvm::Value **VBPtrOut) {
3104 CGBuilderTy &Builder = CGF.Builder;
3105 // Load the vbtable pointer from the vbptr in the instance.
3106 This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
3107 llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
3108 This.getElementType(), This.getPointer(), VBPtrOffset, "vbptr");
3109 if (VBPtrOut) *VBPtrOut = VBPtr;
3110 VBPtr = Builder.CreateBitCast(VBPtr,
3111 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
3113 CharUnits VBPtrAlign;
3114 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
3115 VBPtrAlign = This.getAlignment().alignmentAtOffset(
3116 CharUnits::fromQuantity(CI->getSExtValue()));
3118 VBPtrAlign = CGF.getPointerAlign();
3121 llvm::Value *VBTable = Builder.CreateAlignedLoad(
3122 CGM.Int32Ty->getPointerTo(0), VBPtr, VBPtrAlign, "vbtable");
3124 // Translate from byte offset to table index. It improves analyzability.
3125 llvm::Value *VBTableIndex = Builder.CreateAShr(
3126 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
3127 "vbtindex", /*isExact=*/true);
3129 // Load an i32 offset from the vb-table.
3130 llvm::Value *VBaseOffs =
3131 Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
3132 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
3133 return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
3134 CharUnits::fromQuantity(4), "vbase_offs");
3137 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
3139 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3140 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3141 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3142 CGBuilderTy &Builder = CGF.Builder;
3143 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
3144 llvm::BasicBlock *OriginalBB = nullptr;
3145 llvm::BasicBlock *SkipAdjustBB = nullptr;
3146 llvm::BasicBlock *VBaseAdjustBB = nullptr;
3148 // In the unspecified inheritance model, there might not be a vbtable at all,
3149 // in which case we need to skip the virtual base lookup. If there is a
3150 // vbtable, the first entry is a no-op entry that gives back the original
3151 // base, so look for a virtual base adjustment offset of zero.
3153 OriginalBB = Builder.GetInsertBlock();
3154 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3155 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3156 llvm::Value *IsVirtual =
3157 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3159 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3160 CGF.EmitBlock(VBaseAdjustBB);
3163 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3164 // know the vbptr offset.
3166 CharUnits offs = CharUnits::Zero();
3167 if (!RD->hasDefinition()) {
3168 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3169 unsigned DiagID = Diags.getCustomDiagID(
3170 DiagnosticsEngine::Error,
3171 "member pointer representation requires a "
3172 "complete class type for %0 to perform this expression");
3173 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3174 } else if (RD->getNumVBases())
3175 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3176 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3178 llvm::Value *VBPtr = nullptr;
3179 llvm::Value *VBaseOffs =
3180 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3181 llvm::Value *AdjustedBase =
3182 Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
3184 // Merge control flow with the case where we didn't have to adjust.
3185 if (VBaseAdjustBB) {
3186 Builder.CreateBr(SkipAdjustBB);
3187 CGF.EmitBlock(SkipAdjustBB);
3188 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3189 Phi->addIncoming(Base.getPointer(), OriginalBB);
3190 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3193 return AdjustedBase;
3196 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3197 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3198 const MemberPointerType *MPT) {
3199 assert(MPT->isMemberDataPointer());
3200 unsigned AS = Base.getAddressSpace();
3202 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
3203 CGBuilderTy &Builder = CGF.Builder;
3204 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3205 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3207 // Extract the fields we need, regardless of model. We'll apply them if we
3209 llvm::Value *FieldOffset = MemPtr;
3210 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3211 llvm::Value *VBPtrOffset = nullptr;
3212 if (MemPtr->getType()->isStructTy()) {
3213 // We need to extract values.
3215 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3216 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3217 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3218 if (inheritanceModelHasVBTableOffsetField(Inheritance))
3219 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3223 if (VirtualBaseAdjustmentOffset) {
3224 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3227 Addr = Base.getPointer();
3231 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3233 // Apply the offset, which we assume is non-null.
3234 Addr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
3237 // Cast the address to the appropriate pointer type, adopting the address
3238 // space of the base pointer.
3239 return Builder.CreateBitCast(Addr, PType);
3243 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3246 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3247 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3248 E->getCastKind() == CK_ReinterpretMemberPointer);
3250 // Use constant emission if we can.
3251 if (isa<llvm::Constant>(Src))
3252 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3254 // We may be adding or dropping fields from the member pointer, so we need
3255 // both types and the inheritance models of both records.
3256 const MemberPointerType *SrcTy =
3257 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3258 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3259 bool IsFunc = SrcTy->isMemberFunctionPointer();
3261 // If the classes use the same null representation, reinterpret_cast is a nop.
3262 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3263 if (IsReinterpret && IsFunc)
3266 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3267 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3268 if (IsReinterpret &&
3269 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3272 CGBuilderTy &Builder = CGF.Builder;
3274 // Branch past the conversion if Src is null.
3275 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3276 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3278 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3279 // pointer value of the destination type.
3280 if (IsReinterpret) {
3281 // For reinterpret casts, sema ensures that src and dst are both functions
3282 // or data and have the same size, which means the LLVM types should match.
3283 assert(Src->getType() == DstNull->getType());
3284 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3287 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3288 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3289 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3290 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3291 CGF.EmitBlock(ConvertBB);
3293 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3294 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3297 Builder.CreateBr(ContinueBB);
3299 // In the continuation, choose between DstNull and Dst.
3300 CGF.EmitBlock(ContinueBB);
3301 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3302 Phi->addIncoming(DstNull, OriginalBB);
3303 Phi->addIncoming(Dst, ConvertBB);
3307 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3308 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3309 CastExpr::path_const_iterator PathBegin,
3310 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3311 CGBuilderTy &Builder) {
3312 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3313 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3314 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3315 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3316 bool IsFunc = SrcTy->isMemberFunctionPointer();
3317 bool IsConstant = isa<llvm::Constant>(Src);
3320 llvm::Value *FirstField = Src;
3321 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3322 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3323 llvm::Value *VBPtrOffset = getZeroInt();
3324 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3325 // We need to extract values.
3327 FirstField = Builder.CreateExtractValue(Src, I++);
3328 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3329 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3330 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3331 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3332 if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3333 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3336 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3337 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3338 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3340 // For data pointers, we adjust the field offset directly. For functions, we
3341 // have a separate field.
3342 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3344 // The virtual inheritance model has a quirk: the virtual base table is always
3345 // referenced when dereferencing a member pointer even if the member pointer
3346 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3347 // to point backwards to the top of the MDC from the first VBase. Undo this
3348 // adjustment to normalize the member pointer.
3349 llvm::Value *SrcVBIndexEqZero =
3350 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3351 if (SrcInheritance == MSInheritanceModel::Virtual) {
3352 if (int64_t SrcOffsetToFirstVBase =
3353 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3354 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3356 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3358 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3362 // A non-zero vbindex implies that we are dealing with a source member in a
3363 // floating virtual base in addition to some non-virtual offset. If the
3364 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3365 // fixed, base. The difference between these two cases is that the vbindex +
3366 // nvoffset *always* point to the member regardless of what context they are
3367 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3368 // base requires explicit nv adjustment.
3369 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3371 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3374 llvm::Value *NVDisp;
3375 if (IsDerivedToBase)
3376 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3378 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3380 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3382 // Update the vbindex to an appropriate value in the destination because
3383 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3384 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3385 if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3386 inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3387 if (llvm::GlobalVariable *VDispMap =
3388 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3389 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3390 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3392 llvm::Constant *Mapping = VDispMap->getInitializer();
3393 VirtualBaseAdjustmentOffset =
3394 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3396 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3397 VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
3398 CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
3400 CharUnits::fromQuantity(4));
3404 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3408 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3409 // it to the offset of the vbptr.
3410 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3411 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3413 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3415 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3418 // Likewise, apply a similar adjustment so that dereferencing the member
3419 // pointer correctly accounts for the distance between the start of the first
3420 // virtual base and the top of the MDC.
3421 if (DstInheritance == MSInheritanceModel::Virtual) {
3422 if (int64_t DstOffsetToFirstVBase =
3423 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3424 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3426 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3428 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3432 // Recompose dst from the null struct and the adjusted fields from src.
3434 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3437 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3439 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3440 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3441 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3442 if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3443 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3444 if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3445 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3451 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3452 llvm::Constant *Src) {
3453 const MemberPointerType *SrcTy =
3454 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3455 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3457 CastKind CK = E->getCastKind();
3459 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3460 E->path_end(), Src);
3463 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3464 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3465 CastExpr::path_const_iterator PathBegin,
3466 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3467 assert(CK == CK_DerivedToBaseMemberPointer ||
3468 CK == CK_BaseToDerivedMemberPointer ||
3469 CK == CK_ReinterpretMemberPointer);
3470 // If src is null, emit a new null for dst. We can't return src because dst
3471 // might have a new representation.
3472 if (MemberPointerConstantIsNull(SrcTy, Src))
3473 return EmitNullMemberPointer(DstTy);
3475 // We don't need to do anything for reinterpret_casts of non-null member
3476 // pointers. We should only get here when the two type representations have
3478 if (CK == CK_ReinterpretMemberPointer)
3481 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3482 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3483 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3488 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3489 CodeGenFunction &CGF, const Expr *E, Address This,
3490 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3491 const MemberPointerType *MPT) {
3492 assert(MPT->isMemberFunctionPointer());
3493 const FunctionProtoType *FPT =
3494 MPT->getPointeeType()->castAs<FunctionProtoType>();
3495 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3496 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3497 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3498 CGBuilderTy &Builder = CGF.Builder;
3500 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3502 // Extract the fields we need, regardless of model. We'll apply them if we
3504 llvm::Value *FunctionPointer = MemPtr;
3505 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3506 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3507 llvm::Value *VBPtrOffset = nullptr;
3508 if (MemPtr->getType()->isStructTy()) {
3509 // We need to extract values.
3511 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3512 if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3513 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3514 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3515 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3516 if (inheritanceModelHasVBTableOffsetField(Inheritance))
3517 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3520 if (VirtualBaseAdjustmentOffset) {
3521 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3522 VirtualBaseAdjustmentOffset, VBPtrOffset);
3524 ThisPtrForCall = This.getPointer();
3527 if (NonVirtualBaseAdjustment) {
3528 // Apply the adjustment and cast back to the original struct type.
3529 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3530 Ptr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Ptr, NonVirtualBaseAdjustment);
3531 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3536 Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3537 CGCallee Callee(FPT, FunctionPointer);
3541 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3542 return new MicrosoftCXXABI(CGM);
3545 // MS RTTI Overview:
3546 // The run time type information emitted by cl.exe contains 5 distinct types of
3547 // structures. Many of them reference each other.
3549 // TypeInfo: Static classes that are returned by typeid.
3551 // CompleteObjectLocator: Referenced by vftables. They contain information
3552 // required for dynamic casting, including OffsetFromTop. They also contain
3553 // a reference to the TypeInfo for the type and a reference to the
3554 // CompleteHierarchyDescriptor for the type.
3556 // ClassHierarchyDescriptor: Contains information about a class hierarchy.
3557 // Used during dynamic_cast to walk a class hierarchy. References a base
3558 // class array and the size of said array.
3560 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3561 // somewhat of a misnomer because the most derived class is also in the list
3562 // as well as multiple copies of virtual bases (if they occur multiple times
3563 // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
3564 // every path in the hierarchy, in pre-order depth first order. Note, we do
3565 // not declare a specific llvm type for BaseClassArray, it's merely an array
3566 // of BaseClassDescriptor pointers.
3568 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3569 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3570 // BaseClassArray is. It contains information about a class within a
3571 // hierarchy such as: is this base is ambiguous and what is its offset in the
3572 // vbtable. The names of the BaseClassDescriptors have all of their fields
3573 // mangled into them so they can be aggressively deduplicated by the linker.
3575 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3576 StringRef MangledName("??_7type_info@@6B@");
3577 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3579 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3580 /*isConstant=*/true,
3581 llvm::GlobalVariable::ExternalLinkage,
3582 /*Initializer=*/nullptr, MangledName);
3587 /// A Helper struct that stores information about a class in a class
3588 /// hierarchy. The information stored in these structs struct is used during
3589 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3590 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3591 // implicit depth first pre-order tree connectivity. getFirstChild and
3592 // getNextSibling allow us to walk the tree efficiently.
3593 struct MSRTTIClass {
3595 IsPrivateOnPath = 1 | 8,
3599 HasHierarchyDescriptor = 64
3601 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3602 uint32_t initialize(const MSRTTIClass *Parent,
3603 const CXXBaseSpecifier *Specifier);
3605 MSRTTIClass *getFirstChild() { return this + 1; }
3606 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3607 return Child + 1 + Child->NumBases;
3610 const CXXRecordDecl *RD, *VirtualRoot;
3611 uint32_t Flags, NumBases, OffsetInVBase;
3614 /// Recursively initialize the base class array.
3615 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3616 const CXXBaseSpecifier *Specifier) {
3617 Flags = HasHierarchyDescriptor;
3619 VirtualRoot = nullptr;
3622 if (Specifier->getAccessSpecifier() != AS_public)
3623 Flags |= IsPrivate | IsPrivateOnPath;
3624 if (Specifier->isVirtual()) {
3629 if (Parent->Flags & IsPrivateOnPath)
3630 Flags |= IsPrivateOnPath;
3631 VirtualRoot = Parent->VirtualRoot;
3632 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3633 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3637 MSRTTIClass *Child = getFirstChild();
3638 for (const CXXBaseSpecifier &Base : RD->bases()) {
3639 NumBases += Child->initialize(this, &Base) + 1;
3640 Child = getNextChild(Child);
3645 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3646 switch (Ty->getLinkage()) {
3648 case InternalLinkage:
3649 case UniqueExternalLinkage:
3650 return llvm::GlobalValue::InternalLinkage;
3652 case VisibleNoLinkage:
3653 case ModuleInternalLinkage:
3655 case ExternalLinkage:
3656 return llvm::GlobalValue::LinkOnceODRLinkage;
3658 llvm_unreachable("Invalid linkage!");
3661 /// An ephemeral helper class for building MS RTTI types. It caches some
3662 /// calls to the module and information about the most derived class in a
3664 struct MSRTTIBuilder {
3666 HasBranchingHierarchy = 1,
3667 HasVirtualBranchingHierarchy = 2,
3668 HasAmbiguousBases = 4
3671 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3672 : CGM(ABI.CGM), Context(CGM.getContext()),
3673 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3674 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3677 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3678 llvm::GlobalVariable *
3679 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3680 llvm::GlobalVariable *getClassHierarchyDescriptor();
3681 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3684 ASTContext &Context;
3685 llvm::LLVMContext &VMContext;
3686 llvm::Module &Module;
3687 const CXXRecordDecl *RD;
3688 llvm::GlobalVariable::LinkageTypes Linkage;
3689 MicrosoftCXXABI &ABI;
3694 /// Recursively serializes a class hierarchy in pre-order depth first
3696 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3697 const CXXRecordDecl *RD) {
3698 Classes.push_back(MSRTTIClass(RD));
3699 for (const CXXBaseSpecifier &Base : RD->bases())
3700 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3703 /// Find ambiguity among base classes.
3705 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3706 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3707 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3708 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3709 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3710 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3711 !VirtualBases.insert(Class->RD).second) {
3712 Class = MSRTTIClass::getNextChild(Class);
3715 if (!UniqueBases.insert(Class->RD).second)
3716 AmbiguousBases.insert(Class->RD);
3719 if (AmbiguousBases.empty())
3721 for (MSRTTIClass &Class : Classes)
3722 if (AmbiguousBases.count(Class.RD))
3723 Class.Flags |= MSRTTIClass::IsAmbiguous;
3726 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3727 SmallString<256> MangledName;
3729 llvm::raw_svector_ostream Out(MangledName);
3730 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3733 // Check to see if we've already declared this ClassHierarchyDescriptor.
3734 if (auto CHD = Module.getNamedGlobal(MangledName))
3737 // Serialize the class hierarchy and initialize the CHD Fields.
3738 SmallVector<MSRTTIClass, 8> Classes;
3739 serializeClassHierarchy(Classes, RD);
3740 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3741 detectAmbiguousBases(Classes);
3743 for (auto Class : Classes) {
3744 if (Class.RD->getNumBases() > 1)
3745 Flags |= HasBranchingHierarchy;
3746 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3747 // believe the field isn't actually used.
3748 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3749 Flags |= HasAmbiguousBases;
3751 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3752 Flags |= HasVirtualBranchingHierarchy;
3753 // These gep indices are used to get the address of the first element of the
3754 // base class array.
3755 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3756 llvm::ConstantInt::get(CGM.IntTy, 0)};
3758 // Forward-declare the class hierarchy descriptor
3759 auto Type = ABI.getClassHierarchyDescriptorType();
3760 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3761 /*Initializer=*/nullptr,
3763 if (CHD->isWeakForLinker())
3764 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3766 auto *Bases = getBaseClassArray(Classes);
3768 // Initialize the base class ClassHierarchyDescriptor.
3769 llvm::Constant *Fields[] = {
3770 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3771 llvm::ConstantInt::get(CGM.IntTy, Flags),
3772 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3773 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3774 Bases->getValueType(), Bases,
3775 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3777 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3781 llvm::GlobalVariable *
3782 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3783 SmallString<256> MangledName;
3785 llvm::raw_svector_ostream Out(MangledName);
3786 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3789 // Forward-declare the base class array.
3790 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3791 // mode) bytes of padding. We provide a pointer sized amount of padding by
3792 // adding +1 to Classes.size(). The sections have pointer alignment and are
3793 // marked pick-any so it shouldn't matter.
3794 llvm::Type *PtrType = ABI.getImageRelativeType(
3795 ABI.getBaseClassDescriptorType()->getPointerTo());
3796 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3798 new llvm::GlobalVariable(Module, ArrType,
3799 /*isConstant=*/true, Linkage,
3800 /*Initializer=*/nullptr, MangledName);
3801 if (BCA->isWeakForLinker())
3802 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3804 // Initialize the BaseClassArray.
3805 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3806 for (MSRTTIClass &Class : Classes)
3807 BaseClassArrayData.push_back(
3808 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3809 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3810 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3814 llvm::GlobalVariable *
3815 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3816 // Compute the fields for the BaseClassDescriptor. They are computed up front
3817 // because they are mangled into the name of the object.
3818 uint32_t OffsetInVBTable = 0;
3819 int32_t VBPtrOffset = -1;
3820 if (Class.VirtualRoot) {
3821 auto &VTableContext = CGM.getMicrosoftVTableContext();
3822 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3823 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3826 SmallString<256> MangledName;
3828 llvm::raw_svector_ostream Out(MangledName);
3829 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3830 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3834 // Check to see if we've already declared this object.
3835 if (auto BCD = Module.getNamedGlobal(MangledName))
3838 // Forward-declare the base class descriptor.
3839 auto Type = ABI.getBaseClassDescriptorType();
3841 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3842 /*Initializer=*/nullptr, MangledName);
3843 if (BCD->isWeakForLinker())
3844 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3846 // Initialize the BaseClassDescriptor.
3847 llvm::Constant *Fields[] = {
3848 ABI.getImageRelativeConstant(
3849 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3850 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3851 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3852 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3853 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3854 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3855 ABI.getImageRelativeConstant(
3856 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3858 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3862 llvm::GlobalVariable *
3863 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3864 SmallString<256> MangledName;
3866 llvm::raw_svector_ostream Out(MangledName);
3867 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3870 // Check to see if we've already computed this complete object locator.
3871 if (auto COL = Module.getNamedGlobal(MangledName))
3874 // Compute the fields of the complete object locator.
3875 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3876 int VFPtrOffset = 0;
3877 // The offset includes the vtordisp if one exists.
3878 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3879 if (Context.getASTRecordLayout(RD)
3880 .getVBaseOffsetsMap()
3882 ->second.hasVtorDisp())
3883 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3885 // Forward-declare the complete object locator.
3886 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3887 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3888 /*Initializer=*/nullptr, MangledName);
3890 // Initialize the CompleteObjectLocator.
3891 llvm::Constant *Fields[] = {
3892 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3893 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3894 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3895 ABI.getImageRelativeConstant(
3896 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3897 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3898 ABI.getImageRelativeConstant(COL),
3900 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3901 if (!ABI.isImageRelative())
3902 FieldsRef = FieldsRef.drop_back();
3903 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3904 if (COL->isWeakForLinker())
3905 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3909 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3910 bool &IsConst, bool &IsVolatile,
3911 bool &IsUnaligned) {
3912 T = Context.getExceptionObjectType(T);
3914 // C++14 [except.handle]p3:
3915 // A handler is a match for an exception object of type E if [...]
3916 // - the handler is of type cv T or const T& where T is a pointer type and
3917 // E is a pointer type that can be converted to T by [...]
3918 // - a qualification conversion
3921 IsUnaligned = false;
3922 QualType PointeeType = T->getPointeeType();
3923 if (!PointeeType.isNull()) {
3924 IsConst = PointeeType.isConstQualified();
3925 IsVolatile = PointeeType.isVolatileQualified();
3926 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3929 // Member pointer types like "const int A::*" are represented by having RTTI
3930 // for "int A::*" and separately storing the const qualifier.
3931 if (const auto *MPTy = T->getAs<MemberPointerType>())
3932 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3935 // Pointer types like "const int * const *" are represented by having RTTI
3936 // for "const int **" and separately storing the const qualifier.
3937 if (T->isPointerType())
3938 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3944 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3945 QualType CatchHandlerType) {
3946 // TypeDescriptors for exceptions never have qualified pointer types,
3947 // qualifiers are stored separately in order to support qualification
3949 bool IsConst, IsVolatile, IsUnaligned;
3951 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3953 bool IsReference = CatchHandlerType->isReferenceType();
3965 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3969 /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3970 /// llvm::GlobalVariable * because different type descriptors have different
3971 /// types, and need to be abstracted. They are abstracting by casting the
3972 /// address to an Int8PtrTy.
3973 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3974 SmallString<256> MangledName;
3976 llvm::raw_svector_ostream Out(MangledName);
3977 getMangleContext().mangleCXXRTTI(Type, Out);
3980 // Check to see if we've already declared this TypeDescriptor.
3981 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3982 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3984 // Note for the future: If we would ever like to do deferred emission of
3985 // RTTI, check if emitting vtables opportunistically need any adjustment.
3987 // Compute the fields for the TypeDescriptor.
3988 SmallString<256> TypeInfoString;
3990 llvm::raw_svector_ostream Out(TypeInfoString);
3991 getMangleContext().mangleCXXRTTIName(Type, Out);
3994 // Declare and initialize the TypeDescriptor.
3995 llvm::Constant *Fields[] = {
3996 getTypeInfoVTable(CGM), // VFPtr
3997 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3998 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3999 llvm::StructType *TypeDescriptorType =
4000 getTypeDescriptorType(TypeInfoString);
4001 auto *Var = new llvm::GlobalVariable(
4002 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
4003 getLinkageForRTTI(Type),
4004 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
4006 if (Var->isWeakForLinker())
4007 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
4008 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
4011 /// Gets or a creates a Microsoft CompleteObjectLocator.
4012 llvm::GlobalVariable *
4013 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
4014 const VPtrInfo &Info) {
4015 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
4018 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
4019 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
4020 // There are no constructor variants, always emit the complete destructor.
4021 llvm::Function *Fn =
4022 CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
4023 CGM.maybeSetTrivialComdat(*ctor, *Fn);
4027 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
4029 // Emit the base destructor if the base and complete (vbase) destructors are
4030 // equivalent. This effectively implements -mconstructor-aliases as part of
4032 if (GD.getDtorType() == Dtor_Complete &&
4033 dtor->getParent()->getNumVBases() == 0)
4034 GD = GD.getWithDtorType(Dtor_Base);
4036 // The base destructor is equivalent to the base destructor of its
4037 // base class if there is exactly one non-virtual base class with a
4038 // non-trivial destructor, there are no fields with a non-trivial
4039 // destructor, and the body of the destructor is trivial.
4040 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
4043 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4044 if (Fn->isWeakForLinker())
4045 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
4049 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
4051 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
4053 // Calculate the mangled name.
4054 SmallString<256> ThunkName;
4055 llvm::raw_svector_ostream Out(ThunkName);
4056 getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
4058 // If the thunk has been generated previously, just return it.
4059 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
4060 return cast<llvm::Function>(GV);
4062 // Create the llvm::Function.
4063 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
4064 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
4065 const CXXRecordDecl *RD = CD->getParent();
4066 QualType RecordTy = getContext().getRecordType(RD);
4067 llvm::Function *ThunkFn = llvm::Function::Create(
4068 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
4069 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
4070 FnInfo.getEffectiveCallingConvention()));
4071 if (ThunkFn->isWeakForLinker())
4072 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
4073 bool IsCopy = CT == Ctor_CopyingClosure;
4076 CodeGenFunction CGF(CGM);
4077 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
4079 // Build FunctionArgs.
4080 FunctionArgList FunctionArgs;
4082 // A constructor always starts with a 'this' pointer as its first argument.
4083 buildThisParam(CGF, FunctionArgs);
4085 // Following the 'this' pointer is a reference to the source object that we
4086 // are copying from.
4087 ImplicitParamDecl SrcParam(
4088 getContext(), /*DC=*/nullptr, SourceLocation(),
4089 &getContext().Idents.get("src"),
4090 getContext().getLValueReferenceType(RecordTy,
4091 /*SpelledAsLValue=*/true),
4092 ImplicitParamDecl::Other);
4094 FunctionArgs.push_back(&SrcParam);
4096 // Constructors for classes which utilize virtual bases have an additional
4097 // parameter which indicates whether or not it is being delegated to by a more
4098 // derived constructor.
4099 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
4101 &getContext().Idents.get("is_most_derived"),
4102 getContext().IntTy, ImplicitParamDecl::Other);
4103 // Only add the parameter to the list if the class has virtual bases.
4104 if (RD->getNumVBases() > 0)
4105 FunctionArgs.push_back(&IsMostDerived);
4107 // Start defining the function.
4108 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4109 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
4110 FunctionArgs, CD->getLocation(), SourceLocation());
4111 // Create a scope with an artificial location for the body of this function.
4112 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
4113 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
4114 llvm::Value *This = getThisValue(CGF);
4116 llvm::Value *SrcVal =
4117 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
4122 // Push the this ptr.
4123 Args.add(RValue::get(This), CD->getThisType());
4125 // Push the src ptr.
4127 Args.add(RValue::get(SrcVal), SrcParam.getType());
4129 // Add the rest of the default arguments.
4130 SmallVector<const Stmt *, 4> ArgVec;
4131 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
4132 for (const ParmVarDecl *PD : params) {
4133 assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4134 ArgVec.push_back(PD->getDefaultArg());
4137 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4139 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4140 CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
4142 // Insert any ABI-specific implicit constructor arguments.
4143 AddedStructorArgCounts ExtraArgs =
4144 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4145 /*ForVirtualBase=*/false,
4146 /*Delegating=*/false, Args);
4147 // Call the destructor with our arguments.
4148 llvm::Constant *CalleePtr =
4149 CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4151 CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
4152 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4153 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4154 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4156 Cleanups.ForceCleanup();
4158 // Emit the ret instruction, remove any temporary instructions created for the
4160 CGF.FinishFunction(SourceLocation());
4165 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4167 int32_t VBPtrOffset,
4169 assert(!T->isReferenceType());
4171 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4172 const CXXConstructorDecl *CD =
4173 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
4174 CXXCtorType CT = Ctor_Complete;
4176 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4177 CT = Ctor_CopyingClosure;
4179 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4180 SmallString<256> MangledName;
4182 llvm::raw_svector_ostream Out(MangledName);
4183 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4184 VBPtrOffset, VBIndex, Out);
4186 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4187 return getImageRelativeConstant(GV);
4189 // The TypeDescriptor is used by the runtime to determine if a catch handler
4190 // is appropriate for the exception object.
4191 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4193 // The runtime is responsible for calling the copy constructor if the
4194 // exception is caught by value.
4195 llvm::Constant *CopyCtor;
4197 if (CT == Ctor_CopyingClosure)
4198 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4200 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4202 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
4204 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4206 CopyCtor = getImageRelativeConstant(CopyCtor);
4208 bool IsScalar = !RD;
4209 bool HasVirtualBases = false;
4210 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4211 QualType PointeeType = T;
4212 if (T->isPointerType())
4213 PointeeType = T->getPointeeType();
4214 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4215 HasVirtualBases = RD->getNumVBases() > 0;
4216 if (IdentifierInfo *II = RD->getIdentifier())
4217 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4220 // Encode the relevant CatchableType properties into the Flags bitfield.
4221 // FIXME: Figure out how bits 2 or 8 can get set.
4225 if (HasVirtualBases)
4230 llvm::Constant *Fields[] = {
4231 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4232 TD, // TypeDescriptor
4233 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4234 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4235 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4236 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4237 CopyCtor // CopyCtor
4239 llvm::StructType *CTType = getCatchableTypeType();
4240 auto *GV = new llvm::GlobalVariable(
4241 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4242 llvm::ConstantStruct::get(CTType, Fields), MangledName);
4243 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4244 GV->setSection(".xdata");
4245 if (GV->isWeakForLinker())
4246 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4247 return getImageRelativeConstant(GV);
4250 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4251 assert(!T->isReferenceType());
4253 // See if we've already generated a CatchableTypeArray for this type before.
4254 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4258 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4259 // using a SmallSetVector. Duplicates may arise due to virtual bases
4260 // occurring more than once in the hierarchy.
4261 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4263 // C++14 [except.handle]p3:
4264 // A handler is a match for an exception object of type E if [...]
4265 // - the handler is of type cv T or cv T& and T is an unambiguous public
4266 // base class of E, or
4267 // - the handler is of type cv T or const T& where T is a pointer type and
4268 // E is a pointer type that can be converted to T by [...]
4269 // - a standard pointer conversion (4.10) not involving conversions to
4270 // pointers to private or protected or ambiguous classes
4271 const CXXRecordDecl *MostDerivedClass = nullptr;
4272 bool IsPointer = T->isPointerType();
4274 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4276 MostDerivedClass = T->getAsCXXRecordDecl();
4278 // Collect all the unambiguous public bases of the MostDerivedClass.
4279 if (MostDerivedClass) {
4280 const ASTContext &Context = getContext();
4281 const ASTRecordLayout &MostDerivedLayout =
4282 Context.getASTRecordLayout(MostDerivedClass);
4283 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4284 SmallVector<MSRTTIClass, 8> Classes;
4285 serializeClassHierarchy(Classes, MostDerivedClass);
4286 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4287 detectAmbiguousBases(Classes);
4288 for (const MSRTTIClass &Class : Classes) {
4289 // Skip any ambiguous or private bases.
4291 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4293 // Write down how to convert from a derived pointer to a base pointer.
4294 uint32_t OffsetInVBTable = 0;
4295 int32_t VBPtrOffset = -1;
4296 if (Class.VirtualRoot) {
4298 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4299 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4302 // Turn our record back into a pointer if the exception object is a
4304 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4306 RTTITy = Context.getPointerType(RTTITy);
4307 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4308 VBPtrOffset, OffsetInVBTable));
4312 // C++14 [except.handle]p3:
4313 // A handler is a match for an exception object of type E if
4314 // - The handler is of type cv T or cv T& and E and T are the same type
4315 // (ignoring the top-level cv-qualifiers)
4316 CatchableTypes.insert(getCatchableType(T));
4318 // C++14 [except.handle]p3:
4319 // A handler is a match for an exception object of type E if
4320 // - the handler is of type cv T or const T& where T is a pointer type and
4321 // E is a pointer type that can be converted to T by [...]
4322 // - a standard pointer conversion (4.10) not involving conversions to
4323 // pointers to private or protected or ambiguous classes
4325 // C++14 [conv.ptr]p2:
4326 // A prvalue of type "pointer to cv T," where T is an object type, can be
4327 // converted to a prvalue of type "pointer to cv void".
4328 if (IsPointer && T->getPointeeType()->isObjectType())
4329 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4331 // C++14 [except.handle]p3:
4332 // A handler is a match for an exception object of type E if [...]
4333 // - the handler is of type cv T or const T& where T is a pointer or
4334 // pointer to member type and E is std::nullptr_t.
4336 // We cannot possibly list all possible pointer types here, making this
4337 // implementation incompatible with the standard. However, MSVC includes an
4338 // entry for pointer-to-void in this case. Let's do the same.
4339 if (T->isNullPtrType())
4340 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4342 uint32_t NumEntries = CatchableTypes.size();
4343 llvm::Type *CTType =
4344 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4345 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4346 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4347 llvm::Constant *Fields[] = {
4348 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4349 llvm::ConstantArray::get(
4350 AT, llvm::makeArrayRef(CatchableTypes.begin(),
4351 CatchableTypes.end())) // CatchableTypes
4353 SmallString<256> MangledName;
4355 llvm::raw_svector_ostream Out(MangledName);
4356 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4358 CTA = new llvm::GlobalVariable(
4359 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4360 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4361 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4362 CTA->setSection(".xdata");
4363 if (CTA->isWeakForLinker())
4364 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4368 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4369 bool IsConst, IsVolatile, IsUnaligned;
4370 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4372 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4373 // the exception object may be caught as.
4374 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4375 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4376 // This is used as a component of the mangled name which means that we need to
4377 // know what it is in order to see if we have previously generated the
4379 uint32_t NumEntries =
4380 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4381 ->getLimitedValue();
4383 SmallString<256> MangledName;
4385 llvm::raw_svector_ostream Out(MangledName);
4386 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4390 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4392 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4395 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4396 // be at least as CV qualified. Encode this requirement into the Flags
4406 // The cleanup-function (a destructor) must be called when the exception
4407 // object's lifetime ends.
4408 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4409 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4410 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4411 if (!DtorD->isTrivial())
4412 CleanupFn = llvm::ConstantExpr::getBitCast(
4413 CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
4415 // This is unused as far as we can tell, initialize it to null.
4416 llvm::Constant *ForwardCompat =
4417 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4418 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4419 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4420 llvm::StructType *TIType = getThrowInfoType();
4421 llvm::Constant *Fields[] = {
4422 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4423 getImageRelativeConstant(CleanupFn), // CleanupFn
4424 ForwardCompat, // ForwardCompat
4425 PointerToCatchableTypes // CatchableTypeArray
4427 auto *GV = new llvm::GlobalVariable(
4428 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4429 llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
4430 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4431 GV->setSection(".xdata");
4432 if (GV->isWeakForLinker())
4433 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4437 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4438 const Expr *SubExpr = E->getSubExpr();
4439 assert(SubExpr && "SubExpr cannot be null");
4440 QualType ThrowType = SubExpr->getType();
4441 // The exception object lives on the stack and it's address is passed to the
4442 // runtime function.
4443 Address AI = CGF.CreateMemTemp(ThrowType);
4444 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4447 // The so-called ThrowInfo is used to describe how the exception object may be
4449 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4451 // Call into the runtime to throw the exception.
4452 llvm::Value *Args[] = {
4453 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4456 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
4459 std::pair<llvm::Value *, const CXXRecordDecl *>
4460 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4461 const CXXRecordDecl *RD) {
4462 std::tie(This, std::ignore, RD) =
4463 performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4464 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4467 bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
4468 const CXXRecordDecl *CXXRD) const {
4469 // MSVC Windows on Arm64 considers a type not HFA if it is not an
4470 // aggregate according to the C++14 spec. This is not consistent with the
4471 // AAPCS64, but is defacto spec on that platform.
4472 return !CGM.getTarget().getTriple().isAArch64() ||
4473 isTrivialForAArch64MSVC(CXXRD);