1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
11 // The class in this file generates structures that follow the Microsoft
12 // Visual C++ ABI, which is actually not very well documented at all outside
15 //===----------------------------------------------------------------------===//
18 #include "CGCleanup.h"
19 #include "CGVTables.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenTypes.h"
22 #include "TargetInfo.h"
23 #include "clang/CodeGen/ConstantInitBuilder.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 "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSet.h"
30 #include "llvm/IR/CallSite.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 return CatchTypeInfo{nullptr, 0x40};
137 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
138 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
139 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
141 llvm::Type *StdTypeInfoPtrTy) override;
143 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
144 QualType SrcRecordTy) override;
146 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
147 QualType SrcRecordTy, QualType DestTy,
148 QualType DestRecordTy,
149 llvm::BasicBlock *CastEnd) override;
151 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
152 QualType SrcRecordTy,
153 QualType DestTy) override;
155 bool EmitBadCastCall(CodeGenFunction &CGF) override;
156 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
161 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
162 const CXXRecordDecl *ClassDecl,
163 const CXXRecordDecl *BaseClassDecl) override;
166 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
167 const CXXRecordDecl *RD) override;
170 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
172 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
173 const CXXRecordDecl *RD) override;
175 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
177 // Background on MSVC destructors
178 // ==============================
180 // Both Itanium and MSVC ABIs have destructor variants. The variant names
181 // roughly correspond in the following way:
183 // Base -> no name, just ~Class
184 // Complete -> vbase destructor
185 // Deleting -> scalar deleting destructor
186 // vector deleting destructor
188 // The base and complete destructors are the same as in Itanium, although the
189 // complete destructor does not accept a VTT parameter when there are virtual
190 // bases. A separate mechanism involving vtordisps is used to ensure that
191 // virtual methods of destroyed subobjects are not called.
193 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
194 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
195 // pointer points to an array. The scalar deleting destructor assumes that
196 // bit 2 is zero, and therefore does not contain a loop.
198 // For virtual destructors, only one entry is reserved in the vftable, and it
199 // always points to the vector deleting destructor. The vector deleting
200 // destructor is the most general, so it can be used to destroy objects in
201 // place, delete single heap objects, or delete arrays.
203 // A TU defining a non-inline destructor is only guaranteed to emit a base
204 // destructor, and all of the other variants are emitted on an as-needed basis
205 // in COMDATs. Because a non-base destructor can be emitted in a TU that
206 // lacks a definition for the destructor, non-base destructors must always
207 // delegate to or alias the base destructor.
210 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
211 SmallVectorImpl<CanQualType> &ArgTys) override;
213 /// Non-base dtors should be emitted as delegating thunks in this ABI.
214 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
215 CXXDtorType DT) const override {
216 return DT != Dtor_Base;
219 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
221 const CXXRecordDecl *
222 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
223 MD = MD->getCanonicalDecl();
224 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
225 MicrosoftVTableContext::MethodVFTableLocation ML =
226 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
227 // The vbases might be ordered differently in the final overrider object
228 // and the complete object, so the "this" argument may sometimes point to
229 // memory that has no particular type (e.g. past the complete object).
230 // In this case, we just use a generic pointer type.
231 // FIXME: might want to have a more precise type in the non-virtual
232 // multiple inheritance case.
233 if (ML.VBase || !ML.VFPtrOffset.isZero())
236 return MD->getParent();
240 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
242 bool VirtualCall) override;
244 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
245 FunctionArgList &Params) override;
247 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
248 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
250 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
253 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
254 CXXCtorType Type, bool ForVirtualBase,
255 bool Delegating, CallArgList &Args) override;
257 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
258 CXXDtorType Type, bool ForVirtualBase,
259 bool Delegating, Address This) override;
261 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
262 llvm::GlobalVariable *VTable);
264 void emitVTableDefinitions(CodeGenVTables &CGVT,
265 const CXXRecordDecl *RD) override;
267 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
268 CodeGenFunction::VPtr Vptr) override;
270 /// Don't initialize vptrs if dynamic class
271 /// is marked with with the 'novtable' attribute.
272 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
273 return !VTableClass->hasAttr<MSNoVTableAttr>();
277 getVTableAddressPoint(BaseSubobject Base,
278 const CXXRecordDecl *VTableClass) override;
280 llvm::Value *getVTableAddressPointInStructor(
281 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
282 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
285 getVTableAddressPointForConstExpr(BaseSubobject Base,
286 const CXXRecordDecl *VTableClass) override;
288 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
289 CharUnits VPtrOffset) override;
291 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
292 Address This, llvm::Type *Ty,
293 SourceLocation Loc) override;
295 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
296 const CXXDestructorDecl *Dtor,
297 CXXDtorType DtorType,
299 const CXXMemberCallExpr *CE) override;
301 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
302 CallArgList &CallArgs) override {
303 assert(GD.getDtorType() == Dtor_Deleting &&
304 "Only deleting destructor thunks are available in this ABI");
305 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
309 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
311 llvm::GlobalVariable *
312 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
313 llvm::GlobalVariable::LinkageTypes Linkage);
315 llvm::GlobalVariable *
316 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
317 const CXXRecordDecl *DstRD) {
318 SmallString<256> OutName;
319 llvm::raw_svector_ostream Out(OutName);
320 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
321 StringRef MangledName = OutName.str();
323 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
326 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
327 unsigned NumEntries = 1 + SrcRD->getNumVBases();
328 SmallVector<llvm::Constant *, 4> Map(NumEntries,
329 llvm::UndefValue::get(CGM.IntTy));
330 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
331 bool AnyDifferent = false;
332 for (const auto &I : SrcRD->vbases()) {
333 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
334 if (!DstRD->isVirtuallyDerivedFrom(VBase))
337 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
338 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
339 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
340 AnyDifferent |= SrcVBIndex != DstVBIndex;
342 // This map would be useless, don't use it.
346 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
347 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
348 llvm::GlobalValue::LinkageTypes Linkage =
349 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
350 ? llvm::GlobalValue::LinkOnceODRLinkage
351 : llvm::GlobalValue::InternalLinkage;
352 auto *VDispMap = new llvm::GlobalVariable(
353 CGM.getModule(), VDispMapTy, /*Constant=*/true, Linkage,
354 /*Initializer=*/Init, MangledName);
358 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
359 llvm::GlobalVariable *GV) const;
361 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
362 GlobalDecl GD, bool ReturnAdjustment) override {
363 // Never dllimport/dllexport thunks.
364 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
367 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
369 if (Linkage == GVA_Internal)
370 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
371 else if (ReturnAdjustment)
372 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
374 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
377 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
378 const ThisAdjustment &TA) override;
380 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
381 const ReturnAdjustment &RA) override;
383 void EmitThreadLocalInitFuncs(
384 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
385 ArrayRef<llvm::Function *> CXXThreadLocalInits,
386 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
388 bool usesThreadWrapperFunction() const override { return false; }
389 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
390 QualType LValType) override;
392 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
393 llvm::GlobalVariable *DeclPtr,
394 bool PerformInit) override;
395 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
396 llvm::Constant *Dtor, llvm::Constant *Addr) override;
398 // ==== Notes on array cookies =========
400 // MSVC seems to only use cookies when the class has a destructor; a
401 // two-argument usual array deallocation function isn't sufficient.
403 // For example, this code prints "100" and "1":
406 // void *operator new[](size_t sz) {
407 // printf("%u\n", sz);
408 // return malloc(sz);
410 // void operator delete[](void *p, size_t sz) {
411 // printf("%u\n", sz);
416 // A *p = new A[100];
419 // Whereas it prints "104" and "104" if you give A a destructor.
421 bool requiresArrayCookie(const CXXDeleteExpr *expr,
422 QualType elementType) override;
423 bool requiresArrayCookie(const CXXNewExpr *expr) override;
424 CharUnits getArrayCookieSizeImpl(QualType type) override;
425 Address InitializeArrayCookie(CodeGenFunction &CGF,
427 llvm::Value *NumElements,
428 const CXXNewExpr *expr,
429 QualType ElementType) override;
430 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
432 CharUnits cookieSize) override;
434 friend struct MSRTTIBuilder;
436 bool isImageRelative() const {
437 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64;
440 // 5 routines for constructing the llvm types for MS RTTI structs.
441 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
442 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
443 TDTypeName += llvm::utostr(TypeInfoString.size());
444 llvm::StructType *&TypeDescriptorType =
445 TypeDescriptorTypeMap[TypeInfoString.size()];
446 if (TypeDescriptorType)
447 return TypeDescriptorType;
448 llvm::Type *FieldTypes[] = {
451 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
453 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
454 return TypeDescriptorType;
457 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
458 if (!isImageRelative())
463 llvm::StructType *getBaseClassDescriptorType() {
464 if (BaseClassDescriptorType)
465 return BaseClassDescriptorType;
466 llvm::Type *FieldTypes[] = {
467 getImageRelativeType(CGM.Int8PtrTy),
473 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
475 BaseClassDescriptorType = llvm::StructType::create(
476 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
477 return BaseClassDescriptorType;
480 llvm::StructType *getClassHierarchyDescriptorType() {
481 if (ClassHierarchyDescriptorType)
482 return ClassHierarchyDescriptorType;
483 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
484 ClassHierarchyDescriptorType = llvm::StructType::create(
485 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
486 llvm::Type *FieldTypes[] = {
490 getImageRelativeType(
491 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
493 ClassHierarchyDescriptorType->setBody(FieldTypes);
494 return ClassHierarchyDescriptorType;
497 llvm::StructType *getCompleteObjectLocatorType() {
498 if (CompleteObjectLocatorType)
499 return CompleteObjectLocatorType;
500 CompleteObjectLocatorType = llvm::StructType::create(
501 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
502 llvm::Type *FieldTypes[] = {
506 getImageRelativeType(CGM.Int8PtrTy),
507 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
508 getImageRelativeType(CompleteObjectLocatorType),
510 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
511 if (!isImageRelative())
512 FieldTypesRef = FieldTypesRef.drop_back();
513 CompleteObjectLocatorType->setBody(FieldTypesRef);
514 return CompleteObjectLocatorType;
517 llvm::GlobalVariable *getImageBase() {
518 StringRef Name = "__ImageBase";
519 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
522 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
524 llvm::GlobalValue::ExternalLinkage,
525 /*Initializer=*/nullptr, Name);
528 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
529 if (!isImageRelative())
532 if (PtrVal->isNullValue())
533 return llvm::Constant::getNullValue(CGM.IntTy);
535 llvm::Constant *ImageBaseAsInt =
536 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
537 llvm::Constant *PtrValAsInt =
538 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
539 llvm::Constant *Diff =
540 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
541 /*HasNUW=*/true, /*HasNSW=*/true);
542 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
546 MicrosoftMangleContext &getMangleContext() {
547 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
550 llvm::Constant *getZeroInt() {
551 return llvm::ConstantInt::get(CGM.IntTy, 0);
554 llvm::Constant *getAllOnesInt() {
555 return llvm::Constant::getAllOnesValue(CGM.IntTy);
558 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
561 GetNullMemberPointerFields(const MemberPointerType *MPT,
562 llvm::SmallVectorImpl<llvm::Constant *> &fields);
564 /// \brief Shared code for virtual base adjustment. Returns the offset from
565 /// the vbptr to the virtual base. Optionally returns the address of the
567 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
569 llvm::Value *VBPtrOffset,
570 llvm::Value *VBTableOffset,
571 llvm::Value **VBPtr = nullptr);
573 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
576 int32_t VBTableOffset,
577 llvm::Value **VBPtr = nullptr) {
578 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
579 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
580 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
581 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
584 std::pair<Address, llvm::Value *>
585 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
586 QualType SrcRecordTy);
588 /// \brief Performs a full virtual base adjustment. Used to dereference
589 /// pointers to members of virtual bases.
590 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
591 const CXXRecordDecl *RD, Address Base,
592 llvm::Value *VirtualBaseAdjustmentOffset,
593 llvm::Value *VBPtrOffset /* optional */);
595 /// \brief Emits a full member pointer with the fields common to data and
596 /// function member pointers.
597 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
598 bool IsMemberFunction,
599 const CXXRecordDecl *RD,
600 CharUnits NonVirtualBaseAdjustment,
601 unsigned VBTableIndex);
603 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
606 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
607 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
609 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
610 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
612 /// \brief Generate a thunk for calling a virtual member function MD.
613 llvm::Function *EmitVirtualMemPtrThunk(
614 const CXXMethodDecl *MD,
615 const MicrosoftVTableContext::MethodVFTableLocation &ML);
618 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
620 bool isZeroInitializable(const MemberPointerType *MPT) override;
622 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
623 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
624 return RD->hasAttr<MSInheritanceAttr>();
627 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
629 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
630 CharUnits offset) override;
631 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
632 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
634 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
637 const MemberPointerType *MPT,
638 bool Inequality) override;
640 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
642 const MemberPointerType *MPT) override;
645 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
646 Address Base, llvm::Value *MemPtr,
647 const MemberPointerType *MPT) override;
649 llvm::Value *EmitNonNullMemberPointerConversion(
650 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
651 CastKind CK, CastExpr::path_const_iterator PathBegin,
652 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
653 CGBuilderTy &Builder);
655 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
657 llvm::Value *Src) override;
659 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
660 llvm::Constant *Src) override;
662 llvm::Constant *EmitMemberPointerConversion(
663 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
664 CastKind CK, CastExpr::path_const_iterator PathBegin,
665 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
668 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
669 Address This, llvm::Value *&ThisPtrForCall,
671 const MemberPointerType *MPT) override;
673 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
675 llvm::StructType *getCatchableTypeType() {
676 if (CatchableTypeType)
677 return CatchableTypeType;
678 llvm::Type *FieldTypes[] = {
680 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
681 CGM.IntTy, // NonVirtualAdjustment
682 CGM.IntTy, // OffsetToVBPtr
683 CGM.IntTy, // VBTableIndex
685 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
687 CatchableTypeType = llvm::StructType::create(
688 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
689 return CatchableTypeType;
692 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
693 llvm::StructType *&CatchableTypeArrayType =
694 CatchableTypeArrayTypeMap[NumEntries];
695 if (CatchableTypeArrayType)
696 return CatchableTypeArrayType;
698 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
699 CTATypeName += llvm::utostr(NumEntries);
701 getImageRelativeType(getCatchableTypeType()->getPointerTo());
702 llvm::Type *FieldTypes[] = {
703 CGM.IntTy, // NumEntries
704 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
706 CatchableTypeArrayType =
707 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
708 return CatchableTypeArrayType;
711 llvm::StructType *getThrowInfoType() {
713 return ThrowInfoType;
714 llvm::Type *FieldTypes[] = {
716 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
717 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
718 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
720 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
722 return ThrowInfoType;
725 llvm::Constant *getThrowFn() {
726 // _CxxThrowException is passed an exception object and a ThrowInfo object
727 // which describes the exception.
728 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
729 llvm::FunctionType *FTy =
730 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
731 auto *Fn = cast<llvm::Function>(
732 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"));
733 // _CxxThrowException is stdcall on 32-bit x86 platforms.
734 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86)
735 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
739 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
742 llvm::Constant *getCatchableType(QualType T,
743 uint32_t NVOffset = 0,
744 int32_t VBPtrOffset = -1,
745 uint32_t VBIndex = 0);
747 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
749 llvm::GlobalVariable *getThrowInfo(QualType T) override;
752 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
753 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
754 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
755 /// \brief All the vftables that have been referenced.
756 VFTablesMapTy VFTablesMap;
757 VTablesMapTy VTablesMap;
759 /// \brief This set holds the record decls we've deferred vtable emission for.
760 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
763 /// \brief All the vbtables which have been referenced.
764 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
766 /// Info on the global variable used to guard initialization of static locals.
767 /// The BitIndex field is only used for externally invisible declarations.
769 GuardInfo() : Guard(nullptr), BitIndex(0) {}
770 llvm::GlobalVariable *Guard;
774 /// Map from DeclContext to the current guard variable. We assume that the
775 /// AST is visited in source code order.
776 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
777 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
778 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
780 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
781 llvm::StructType *BaseClassDescriptorType;
782 llvm::StructType *ClassHierarchyDescriptorType;
783 llvm::StructType *CompleteObjectLocatorType;
785 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
787 llvm::StructType *CatchableTypeType;
788 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
789 llvm::StructType *ThrowInfoType;
794 CGCXXABI::RecordArgABI
795 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
796 switch (CGM.getTarget().getTriple().getArch()) {
798 // FIXME: Implement for other architectures.
801 case llvm::Triple::thumb:
802 // Use the simple Itanium rules for now.
803 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
805 return !canCopyArgument(RD) ? RAA_Indirect : RAA_Default;
807 case llvm::Triple::x86:
808 // All record arguments are passed in memory on x86. Decide whether to
809 // construct the object directly in argument memory, or to construct the
810 // argument elsewhere and copy the bytes during the call.
812 // If C++ prohibits us from making a copy, construct the arguments directly
813 // into argument memory.
814 if (!canCopyArgument(RD))
815 return RAA_DirectInMemory;
817 // Otherwise, construct the argument into a temporary and copy the bytes
818 // into the outgoing argument memory.
821 case llvm::Triple::x86_64:
822 // If a class has a destructor, we'd really like to pass it indirectly
823 // because it allows us to elide copies. Unfortunately, MSVC makes that
824 // impossible for small types, which it will pass in a single register or
825 // stack slot. Most objects with dtors are large-ish, so handle that early.
826 // We can't call out all large objects as being indirect because there are
827 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
828 // how we pass large POD types.
830 // Note: This permits small classes with nontrivial destructors to be
831 // passed in registers, which is non-conforming.
832 if (RD->hasNonTrivialDestructor() &&
833 getContext().getTypeSize(RD->getTypeForDecl()) > 64)
836 // If a class has at least one non-deleted, trivial copy constructor, it
837 // is passed according to the C ABI. Otherwise, it is passed indirectly.
839 // Note: This permits classes with non-trivial copy or move ctors to be
840 // passed in registers, so long as they *also* have a trivial copy ctor,
841 // which is non-conforming.
842 if (RD->needsImplicitCopyConstructor()) {
843 // If the copy ctor has not yet been declared, we can read its triviality
845 if (!RD->defaultedCopyConstructorIsDeleted() &&
846 RD->hasTrivialCopyConstructor())
849 // Otherwise, we need to find the copy constructor(s) and ask.
850 for (const CXXConstructorDecl *CD : RD->ctors()) {
851 if (CD->isCopyConstructor()) {
852 // We had at least one nondeleted trivial copy ctor. Return directly.
853 if (!CD->isDeleted() && CD->isTrivial())
859 // We have no trivial, non-deleted copy constructor.
863 llvm_unreachable("invalid enum");
866 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
867 const CXXDeleteExpr *DE,
869 QualType ElementType,
870 const CXXDestructorDecl *Dtor) {
871 // FIXME: Provide a source location here even though there's no
872 // CXXMemberCallExpr for dtor call.
873 bool UseGlobalDelete = DE->isGlobalDelete();
874 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
875 llvm::Value *MDThis =
876 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
878 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
881 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
882 llvm::Value *Args[] = {
883 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
884 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
885 auto *Fn = getThrowFn();
887 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
889 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
893 struct CatchRetScope final : EHScopeStack::Cleanup {
894 llvm::CatchPadInst *CPI;
896 CatchRetScope(llvm::CatchPadInst *CPI) : CPI(CPI) {}
898 void Emit(CodeGenFunction &CGF, Flags flags) override {
899 llvm::BasicBlock *BB = CGF.createBasicBlock("catchret.dest");
900 CGF.Builder.CreateCatchRet(CPI, BB);
906 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
907 const CXXCatchStmt *S) {
908 // In the MS ABI, the runtime handles the copy, and the catch handler is
909 // responsible for destruction.
910 VarDecl *CatchParam = S->getExceptionDecl();
911 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
912 llvm::CatchPadInst *CPI =
913 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
914 CGF.CurrentFuncletPad = CPI;
916 // If this is a catch-all or the catch parameter is unnamed, we don't need to
917 // emit an alloca to the object.
918 if (!CatchParam || !CatchParam->getDeclName()) {
919 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
923 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
924 CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
925 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
926 CGF.EmitAutoVarCleanups(var);
929 /// We need to perform a generic polymorphic operation (like a typeid
930 /// or a cast), which requires an object with a vfptr. Adjust the
931 /// address to point to an object with a vfptr.
932 std::pair<Address, llvm::Value *>
933 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
934 QualType SrcRecordTy) {
935 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
936 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
937 const ASTContext &Context = getContext();
939 // If the class itself has a vfptr, great. This check implicitly
940 // covers non-virtual base subobjects: a class with its own virtual
941 // functions would be a candidate to be a primary base.
942 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
943 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
945 // Okay, one of the vbases must have a vfptr, or else this isn't
946 // actually a polymorphic class.
947 const CXXRecordDecl *PolymorphicBase = nullptr;
948 for (auto &Base : SrcDecl->vbases()) {
949 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
950 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
951 PolymorphicBase = BaseDecl;
955 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
957 llvm::Value *Offset =
958 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
959 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(Value.getPointer(), Offset);
960 CharUnits VBaseAlign =
961 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
962 return std::make_pair(Address(Ptr, VBaseAlign), Offset);
965 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
966 QualType SrcRecordTy) {
967 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
969 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
972 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
973 llvm::Value *Argument) {
974 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
975 llvm::FunctionType *FTy =
976 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
977 llvm::Value *Args[] = {Argument};
978 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
979 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
982 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
983 llvm::CallSite Call =
984 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
985 Call.setDoesNotReturn();
986 CGF.Builder.CreateUnreachable();
989 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
990 QualType SrcRecordTy,
992 llvm::Type *StdTypeInfoPtrTy) {
993 std::tie(ThisPtr, std::ignore) =
994 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
995 auto Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer()).getInstruction();
996 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
999 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1000 QualType SrcRecordTy) {
1001 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1003 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1006 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
1007 CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
1008 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1009 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1011 llvm::Value *SrcRTTI =
1012 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1013 llvm::Value *DestRTTI =
1014 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1016 llvm::Value *Offset;
1017 std::tie(This, Offset) = performBaseAdjustment(CGF, This, SrcRecordTy);
1018 llvm::Value *ThisPtr = This.getPointer();
1019 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1021 // PVOID __RTDynamicCast(
1025 // PVOID TargetType,
1026 // BOOL isReference)
1027 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1028 CGF.Int8PtrTy, CGF.Int32Ty};
1029 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
1030 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1032 llvm::Value *Args[] = {
1033 ThisPtr, Offset, SrcRTTI, DestRTTI,
1034 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1035 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
1036 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1040 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1041 QualType SrcRecordTy,
1043 std::tie(Value, std::ignore) = performBaseAdjustment(CGF, Value, SrcRecordTy);
1045 // PVOID __RTCastToVoid(
1047 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1048 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
1049 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1051 llvm::Value *Args[] = {Value.getPointer()};
1052 return CGF.EmitRuntimeCall(Function, Args);
1055 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1059 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1060 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1061 const CXXRecordDecl *BaseClassDecl) {
1062 const ASTContext &Context = getContext();
1063 int64_t VBPtrChars =
1064 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1065 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1066 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1067 CharUnits VBTableChars =
1069 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1070 llvm::Value *VBTableOffset =
1071 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1073 llvm::Value *VBPtrToNewBase =
1074 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1076 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1077 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1080 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1081 return isa<CXXConstructorDecl>(GD.getDecl());
1084 static bool isDeletingDtor(GlobalDecl GD) {
1085 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1086 GD.getDtorType() == Dtor_Deleting;
1089 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1090 return isDeletingDtor(GD);
1093 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1094 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1098 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1099 if (FI.isInstanceMethod()) {
1100 // If it's an instance method, aggregates are always returned indirectly via
1101 // the second parameter.
1102 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1103 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1105 } else if (!RD->isPOD()) {
1106 // If it's a free function, non-POD types are returned indirectly.
1107 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1111 // Otherwise, use the C ABI rules.
1116 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1117 const CXXRecordDecl *RD) {
1118 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1119 assert(IsMostDerivedClass &&
1120 "ctor for a class with virtual bases must have an implicit parameter");
1121 llvm::Value *IsCompleteObject =
1122 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1124 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1125 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1126 CGF.Builder.CreateCondBr(IsCompleteObject,
1127 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1129 CGF.EmitBlock(CallVbaseCtorsBB);
1131 // Fill in the vbtable pointers here.
1132 EmitVBPtrStores(CGF, RD);
1134 // CGF will put the base ctor calls in this basic block for us later.
1136 return SkipVbaseCtorsBB;
1140 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1141 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1142 assert(IsMostDerivedClass &&
1143 "ctor for a class with virtual bases must have an implicit parameter");
1144 llvm::Value *IsCompleteObject =
1145 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1147 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1148 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1149 CGF.Builder.CreateCondBr(IsCompleteObject,
1150 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1152 CGF.EmitBlock(CallVbaseDtorsBB);
1153 // CGF will put the base dtor calls in this basic block for us later.
1155 return SkipVbaseDtorsBB;
1158 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1159 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1160 // In most cases, an override for a vbase virtual method can adjust
1161 // the "this" parameter by applying a constant offset.
1162 // However, this is not enough while a constructor or a destructor of some
1163 // class X is being executed if all the following conditions are met:
1164 // - X has virtual bases, (1)
1165 // - X overrides a virtual method M of a vbase Y, (2)
1166 // - X itself is a vbase of the most derived class.
1168 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1169 // which holds the extra amount of "this" adjustment we must do when we use
1170 // the X vftables (i.e. during X ctor or dtor).
1171 // Outside the ctors and dtors, the values of vtorDisps are zero.
1173 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1174 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1175 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1176 CGBuilderTy &Builder = CGF.Builder;
1178 unsigned AS = getThisAddress(CGF).getAddressSpace();
1179 llvm::Value *Int8This = nullptr; // Initialize lazily.
1181 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
1183 if (!I->second.hasVtorDisp())
1186 llvm::Value *VBaseOffset =
1187 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
1188 uint64_t ConstantVBaseOffset =
1189 Layout.getVBaseClassOffset(I->first).getQuantity();
1191 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1192 llvm::Value *VtorDispValue = Builder.CreateSub(
1193 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1195 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1198 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1199 CGF.Int8Ty->getPointerTo(AS));
1200 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
1201 // vtorDisp is always the 32-bits before the vbase in the class layout.
1202 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1203 VtorDispPtr = Builder.CreateBitCast(
1204 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1206 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1207 CharUnits::fromQuantity(4));
1211 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1212 const CXXMethodDecl *MD) {
1213 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1214 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1215 CallingConv ActualCallingConv =
1216 MD->getType()->getAs<FunctionProtoType>()->getCallConv();
1217 return ExpectedCallingConv == ActualCallingConv;
1220 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1221 // There's only one constructor type in this ABI.
1222 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1224 // Exported default constructors either have a simple call-site where they use
1225 // the typical calling convention and have a single 'this' pointer for an
1226 // argument -or- they get a wrapper function which appropriately thunks to the
1227 // real default constructor. This thunk is the default constructor closure.
1228 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor())
1229 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1230 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1231 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1232 Fn->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1236 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1237 const CXXRecordDecl *RD) {
1238 Address This = getThisAddress(CGF);
1239 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1240 const ASTContext &Context = getContext();
1241 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1243 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1244 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1245 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1246 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1247 const ASTRecordLayout &SubobjectLayout =
1248 Context.getASTRecordLayout(VBT->IntroducingObject);
1249 CharUnits Offs = VBT->NonVirtualOffset;
1250 Offs += SubobjectLayout.getVBPtrOffset();
1251 if (VBT->getVBaseWithVPtr())
1252 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1253 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1254 llvm::Value *GVPtr =
1255 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1256 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1257 "vbptr." + VBT->ObjectWithVPtr->getName());
1258 CGF.Builder.CreateStore(GVPtr, VBPtr);
1262 CGCXXABI::AddedStructorArgs
1263 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1264 SmallVectorImpl<CanQualType> &ArgTys) {
1265 AddedStructorArgs Added;
1266 // TODO: 'for base' flag
1267 if (T == StructorType::Deleting) {
1268 // The scalar deleting destructor takes an implicit int parameter.
1269 ArgTys.push_back(getContext().IntTy);
1272 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
1276 // All parameters are already in place except is_most_derived, which goes
1277 // after 'this' if it's variadic and last if it's not.
1279 const CXXRecordDecl *Class = CD->getParent();
1280 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1281 if (Class->getNumVBases()) {
1282 if (FPT->isVariadic()) {
1283 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1286 ArgTys.push_back(getContext().IntTy);
1294 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1295 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1296 // other destructor variants are delegating thunks.
1297 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1301 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1302 GD = GD.getCanonicalDecl();
1303 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1305 GlobalDecl LookupGD = GD;
1306 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1307 // Complete destructors take a pointer to the complete object as a
1308 // parameter, thus don't need this adjustment.
1309 if (GD.getDtorType() == Dtor_Complete)
1312 // There's no Dtor_Base in vftable but it shares the this adjustment with
1313 // the deleting one, so look it up instead.
1314 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1317 MicrosoftVTableContext::MethodVFTableLocation ML =
1318 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1319 CharUnits Adjustment = ML.VFPtrOffset;
1321 // Normal virtual instance methods need to adjust from the vfptr that first
1322 // defined the virtual method to the virtual base subobject, but destructors
1323 // do not. The vector deleting destructor thunk applies this adjustment for
1325 if (isa<CXXDestructorDecl>(MD))
1326 Adjustment = CharUnits::Zero();
1329 const ASTRecordLayout &DerivedLayout =
1330 getContext().getASTRecordLayout(MD->getParent());
1331 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1337 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1338 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1341 // If the call of a virtual function is not virtual, we just have to
1342 // compensate for the adjustment the virtual function does in its prologue.
1343 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1344 if (Adjustment.isZero())
1347 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1348 assert(Adjustment.isPositive());
1349 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1352 GD = GD.getCanonicalDecl();
1353 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1355 GlobalDecl LookupGD = GD;
1356 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1357 // Complete dtors take a pointer to the complete object,
1358 // thus don't need adjustment.
1359 if (GD.getDtorType() == Dtor_Complete)
1362 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1363 // with the base one, so look up the deleting one instead.
1364 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1366 MicrosoftVTableContext::MethodVFTableLocation ML =
1367 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1369 CharUnits StaticOffset = ML.VFPtrOffset;
1371 // Base destructors expect 'this' to point to the beginning of the base
1372 // subobject, not the first vfptr that happens to contain the virtual dtor.
1373 // However, we still need to apply the virtual base adjustment.
1374 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1375 StaticOffset = CharUnits::Zero();
1377 Address Result = This;
1379 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1381 const CXXRecordDecl *Derived = MD->getParent();
1382 const CXXRecordDecl *VBase = ML.VBase;
1383 llvm::Value *VBaseOffset =
1384 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1385 llvm::Value *VBasePtr =
1386 CGF.Builder.CreateInBoundsGEP(Result.getPointer(), VBaseOffset);
1387 CharUnits VBaseAlign =
1388 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1389 Result = Address(VBasePtr, VBaseAlign);
1391 if (!StaticOffset.isZero()) {
1392 assert(StaticOffset.isPositive());
1393 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1395 // Non-virtual adjustment might result in a pointer outside the allocated
1396 // object, e.g. if the final overrider class is laid out after the virtual
1397 // base that declares a method in the most derived class.
1398 // FIXME: Update the code that emits this adjustment in thunks prologues.
1399 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1401 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1407 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1409 FunctionArgList &Params) {
1410 ASTContext &Context = getContext();
1411 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1412 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1413 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1414 auto *IsMostDerived = ImplicitParamDecl::Create(
1415 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1416 &Context.Idents.get("is_most_derived"), Context.IntTy,
1417 ImplicitParamDecl::Other);
1418 // The 'most_derived' parameter goes second if the ctor is variadic and last
1419 // if it's not. Dtors can't be variadic.
1420 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1421 if (FPT->isVariadic())
1422 Params.insert(Params.begin() + 1, IsMostDerived);
1424 Params.push_back(IsMostDerived);
1425 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1426 } else if (isDeletingDtor(CGF.CurGD)) {
1427 auto *ShouldDelete = ImplicitParamDecl::Create(
1428 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1429 &Context.Idents.get("should_call_delete"), Context.IntTy,
1430 ImplicitParamDecl::Other);
1431 Params.push_back(ShouldDelete);
1432 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1436 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1437 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1438 // In this ABI, every virtual function takes a pointer to one of the
1439 // subobjects that first defines it as the 'this' parameter, rather than a
1440 // pointer to the final overrider subobject. Thus, we need to adjust it back
1441 // to the final overrider subobject before use.
1442 // See comments in the MicrosoftVFTableContext implementation for the details.
1443 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1444 if (Adjustment.isZero())
1447 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1448 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1449 *thisTy = This->getType();
1451 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1452 assert(Adjustment.isPositive());
1453 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1454 -Adjustment.getQuantity());
1455 return CGF.Builder.CreateBitCast(This, thisTy);
1458 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1459 // Naked functions have no prolog.
1460 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1465 /// If this is a function that the ABI specifies returns 'this', initialize
1466 /// the return slot to 'this' at the start of the function.
1468 /// Unlike the setting of return types, this is done within the ABI
1469 /// implementation instead of by clients of CGCXXABI because:
1470 /// 1) getThisValue is currently protected
1471 /// 2) in theory, an ABI could implement 'this' returns some other way;
1472 /// HasThisReturn only specifies a contract, not the implementation
1473 if (HasThisReturn(CGF.CurGD))
1474 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1475 else if (hasMostDerivedReturn(CGF.CurGD))
1476 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1479 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1480 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1481 assert(getStructorImplicitParamDecl(CGF) &&
1482 "no implicit parameter for a constructor with virtual bases?");
1483 getStructorImplicitParamValue(CGF)
1484 = CGF.Builder.CreateLoad(
1485 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1489 if (isDeletingDtor(CGF.CurGD)) {
1490 assert(getStructorImplicitParamDecl(CGF) &&
1491 "no implicit parameter for a deleting destructor?");
1492 getStructorImplicitParamValue(CGF)
1493 = CGF.Builder.CreateLoad(
1494 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1495 "should_call_delete");
1499 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::addImplicitConstructorArgs(
1500 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1501 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1502 assert(Type == Ctor_Complete || Type == Ctor_Base);
1504 // Check if we need a 'most_derived' parameter.
1505 if (!D->getParent()->getNumVBases())
1506 return AddedStructorArgs{};
1508 // Add the 'most_derived' argument second if we are variadic or last if not.
1509 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1510 llvm::Value *MostDerivedArg;
1512 MostDerivedArg = getStructorImplicitParamValue(CGF);
1514 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1516 RValue RV = RValue::get(MostDerivedArg);
1517 if (FPT->isVariadic()) {
1518 Args.insert(Args.begin() + 1,
1519 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1520 return AddedStructorArgs::prefix(1);
1522 Args.add(RV, getContext().IntTy);
1523 return AddedStructorArgs::suffix(1);
1526 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1527 const CXXDestructorDecl *DD,
1528 CXXDtorType Type, bool ForVirtualBase,
1529 bool Delegating, Address This) {
1530 CGCallee Callee = CGCallee::forDirect(
1531 CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1534 if (DD->isVirtual()) {
1535 assert(Type != CXXDtorType::Dtor_Deleting &&
1536 "The deleting destructor should only be called via a virtual call");
1537 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1541 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1542 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1543 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1546 CGF.EmitCXXDestructorCall(DD, Callee, This.getPointer(),
1547 /*ImplicitParam=*/nullptr,
1548 /*ImplicitParamTy=*/QualType(), nullptr,
1549 getFromDtorType(Type));
1550 if (BaseDtorEndBB) {
1551 // Complete object handler should continue to be the remaining
1552 CGF.Builder.CreateBr(BaseDtorEndBB);
1553 CGF.EmitBlock(BaseDtorEndBB);
1557 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1558 const CXXRecordDecl *RD,
1559 llvm::GlobalVariable *VTable) {
1560 if (!CGM.getCodeGenOpts().LTOUnit)
1563 // The location of the first virtual function pointer in the virtual table,
1564 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1565 // disabled, or sizeof(void*) if RTTI is enabled.
1566 CharUnits AddressPoint =
1567 getContext().getLangOpts().RTTIData
1568 ? getContext().toCharUnitsFromBits(
1569 getContext().getTargetInfo().getPointerWidth(0))
1570 : CharUnits::Zero();
1572 if (Info.PathToIntroducingObject.empty()) {
1573 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1577 // Add a bitset entry for the least derived base belonging to this vftable.
1578 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1579 Info.PathToIntroducingObject.back());
1581 // Add a bitset entry for each derived class that is laid out at the same
1582 // offset as the least derived base.
1583 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1584 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1585 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1587 const ASTRecordLayout &Layout =
1588 getContext().getASTRecordLayout(DerivedRD);
1590 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1591 if (VBI == Layout.getVBaseOffsetsMap().end())
1592 Offset = Layout.getBaseClassOffset(BaseRD);
1594 Offset = VBI->second.VBaseOffset;
1595 if (!Offset.isZero())
1597 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1600 // Finally do the same for the most derived class.
1601 if (Info.FullOffsetInMDC.isZero())
1602 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1605 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1606 const CXXRecordDecl *RD) {
1607 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1608 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1610 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1611 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1612 if (VTable->hasInitializer())
1615 const VTableLayout &VTLayout =
1616 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1618 llvm::Constant *RTTI = nullptr;
1619 if (any_of(VTLayout.vtable_components(),
1620 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1621 RTTI = getMSCompleteObjectLocator(RD, *Info);
1623 ConstantInitBuilder Builder(CGM);
1624 auto Components = Builder.beginStruct();
1625 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1626 Components.finishAndSetAsInitializer(VTable);
1628 emitVTableTypeMetadata(*Info, RD, VTable);
1632 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1633 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1634 return Vptr.NearestVBase != nullptr;
1637 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1638 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1639 const CXXRecordDecl *NearestVBase) {
1640 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1641 if (!VTableAddressPoint) {
1642 assert(Base.getBase()->getNumVBases() &&
1643 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1645 return VTableAddressPoint;
1648 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1649 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1650 SmallString<256> &Name) {
1651 llvm::raw_svector_ostream Out(Name);
1652 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1656 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1657 const CXXRecordDecl *VTableClass) {
1658 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1659 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1660 return VFTablesMap[ID];
1663 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1664 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1665 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1666 assert(VFTable && "Couldn't find a vftable for the given base?");
1670 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1671 CharUnits VPtrOffset) {
1672 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1673 // shouldn't be used in the given record type. We want to cache this result in
1674 // VFTablesMap, thus a simple zero check is not sufficient.
1676 VFTableIdTy ID(RD, VPtrOffset);
1677 VTablesMapTy::iterator I;
1679 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1683 llvm::GlobalVariable *&VTable = I->second;
1685 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1686 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1688 if (DeferredVFTables.insert(RD).second) {
1689 // We haven't processed this record type before.
1690 // Queue up this vtable for possible deferred emission.
1691 CGM.addDeferredVTable(RD);
1694 // Create all the vftables at once in order to make sure each vftable has
1695 // a unique mangled name.
1696 llvm::StringSet<> ObservedMangledNames;
1697 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1698 SmallString<256> Name;
1699 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1700 if (!ObservedMangledNames.insert(Name.str()).second)
1701 llvm_unreachable("Already saw this mangling before?");
1706 const std::unique_ptr<VPtrInfo> *VFPtrI = std::find_if(
1707 VFPtrs.begin(), VFPtrs.end(), [&](const std::unique_ptr<VPtrInfo>& VPI) {
1708 return VPI->FullOffsetInMDC == VPtrOffset;
1710 if (VFPtrI == VFPtrs.end()) {
1711 VFTablesMap[ID] = nullptr;
1714 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1716 SmallString<256> VFTableName;
1717 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1719 // Classes marked __declspec(dllimport) need vftables generated on the
1720 // import-side in order to support features like constexpr. No other
1721 // translation unit relies on the emission of the local vftable, translation
1722 // units are expected to generate them as needed.
1724 // Because of this unique behavior, we maintain this logic here instead of
1725 // getVTableLinkage.
1726 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1727 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1728 : CGM.getVTableLinkage(RD);
1729 bool VFTableComesFromAnotherTU =
1730 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1731 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1732 bool VTableAliasIsRequred =
1733 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1735 if (llvm::GlobalValue *VFTable =
1736 CGM.getModule().getNamedGlobal(VFTableName)) {
1737 VFTablesMap[ID] = VFTable;
1738 VTable = VTableAliasIsRequred
1739 ? cast<llvm::GlobalVariable>(
1740 cast<llvm::GlobalAlias>(VFTable)->getBaseObject())
1741 : cast<llvm::GlobalVariable>(VFTable);
1745 const VTableLayout &VTLayout =
1746 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1747 llvm::GlobalValue::LinkageTypes VTableLinkage =
1748 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1750 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1752 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1754 // Create a backing variable for the contents of VTable. The VTable may
1755 // or may not include space for a pointer to RTTI data.
1756 llvm::GlobalValue *VFTable;
1757 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1758 /*isConstant=*/true, VTableLinkage,
1759 /*Initializer=*/nullptr, VTableName);
1760 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1762 llvm::Comdat *C = nullptr;
1763 if (!VFTableComesFromAnotherTU &&
1764 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1765 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1766 VTableAliasIsRequred)))
1767 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1769 // Only insert a pointer into the VFTable for RTTI data if we are not
1770 // importing it. We never reference the RTTI data directly so there is no
1771 // need to make room for it.
1772 if (VTableAliasIsRequred) {
1773 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1774 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1775 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1776 // Create a GEP which points just after the first entry in the VFTable,
1777 // this should be the location of the first virtual method.
1778 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1779 VTable->getValueType(), VTable, GEPIndices);
1780 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1781 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1783 C->setSelectionKind(llvm::Comdat::Largest);
1785 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1786 /*AddressSpace=*/0, VFTableLinkage,
1787 VFTableName.str(), VTableGEP,
1789 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1791 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1792 // be referencing any RTTI data.
1793 // The GlobalVariable will end up being an appropriate definition of the
1798 VTable->setComdat(C);
1800 if (RD->hasAttr<DLLExportAttr>())
1801 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1803 VFTablesMap[ID] = VFTable;
1807 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1811 SourceLocation Loc) {
1812 GD = GD.getCanonicalDecl();
1813 CGBuilderTy &Builder = CGF.Builder;
1815 Ty = Ty->getPointerTo()->getPointerTo();
1817 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1819 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1820 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty, MethodDecl->getParent());
1822 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1823 MicrosoftVTableContext::MethodVFTableLocation ML =
1824 VFTContext.getMethodVFTableLocation(GD);
1826 // Compute the identity of the most derived class whose virtual table is
1827 // located at the MethodVFTableLocation ML.
1828 auto getObjectWithVPtr = [&] {
1829 return llvm::find_if(VFTContext.getVFPtrOffsets(
1830 ML.VBase ? ML.VBase : MethodDecl->getParent()),
1831 [&](const std::unique_ptr<VPtrInfo> &Info) {
1832 return Info->FullOffsetInMDC == ML.VFPtrOffset;
1839 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1840 VFunc = CGF.EmitVTableTypeCheckedLoad(
1841 getObjectWithVPtr(), VTable,
1842 ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1844 if (CGM.getCodeGenOpts().PrepareForLTO)
1845 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1847 llvm::Value *VFuncPtr =
1848 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1849 VFunc = Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1852 CGCallee Callee(MethodDecl, VFunc);
1856 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1857 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1858 Address This, const CXXMemberCallExpr *CE) {
1859 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1860 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1862 // We have only one destructor in the vftable but can get both behaviors
1863 // by passing an implicit int parameter.
1864 GlobalDecl GD(Dtor, Dtor_Deleting);
1865 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1866 Dtor, StructorType::Deleting);
1867 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1868 CGCallee Callee = getVirtualFunctionPointer(
1869 CGF, GD, This, Ty, CE ? CE->getLocStart() : SourceLocation());
1871 ASTContext &Context = getContext();
1872 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1873 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1874 DtorType == Dtor_Deleting);
1876 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1878 CGF.EmitCXXDestructorCall(Dtor, Callee, This.getPointer(), ImplicitParam,
1879 Context.IntTy, CE, StructorType::Deleting);
1880 return RV.getScalarVal();
1883 const VBTableGlobals &
1884 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1885 // At this layer, we can key the cache off of a single class, which is much
1886 // easier than caching each vbtable individually.
1887 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1889 std::tie(Entry, Added) =
1890 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1891 VBTableGlobals &VBGlobals = Entry->second;
1895 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1896 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1898 // Cache the globals for all vbtables so we don't have to recompute the
1900 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1901 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1902 E = VBGlobals.VBTables->end();
1904 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1910 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1911 const CXXMethodDecl *MD,
1912 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1913 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1914 "can't form pointers to ctors or virtual dtors");
1916 // Calculate the mangled name.
1917 SmallString<256> ThunkName;
1918 llvm::raw_svector_ostream Out(ThunkName);
1919 getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1921 // If the thunk has been generated previously, just return it.
1922 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1923 return cast<llvm::Function>(GV);
1925 // Create the llvm::Function.
1926 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD);
1927 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1928 llvm::Function *ThunkFn =
1929 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1930 ThunkName.str(), &CGM.getModule());
1931 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1933 ThunkFn->setLinkage(MD->isExternallyVisible()
1934 ? llvm::GlobalValue::LinkOnceODRLinkage
1935 : llvm::GlobalValue::InternalLinkage);
1936 if (MD->isExternallyVisible())
1937 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
1939 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1940 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1942 // Add the "thunk" attribute so that LLVM knows that the return type is
1943 // meaningless. These thunks can be used to call functions with differing
1944 // return types, and the caller is required to cast the prototype
1945 // appropriately to extract the correct value.
1946 ThunkFn->addFnAttr("thunk");
1948 // These thunks can be compared, so they are not unnamed.
1949 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
1952 CodeGenFunction CGF(CGM);
1953 CGF.CurGD = GlobalDecl(MD);
1954 CGF.CurFuncIsThunk = true;
1956 // Build FunctionArgs, but only include the implicit 'this' parameter
1958 FunctionArgList FunctionArgs;
1959 buildThisParam(CGF, FunctionArgs);
1961 // Start defining the function.
1962 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
1963 FunctionArgs, MD->getLocation(), SourceLocation());
1966 // Load the vfptr and then callee from the vftable. The callee should have
1967 // adjusted 'this' so that the vfptr is at offset zero.
1968 llvm::Value *VTable = CGF.GetVTablePtr(
1969 getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent());
1971 llvm::Value *VFuncPtr =
1972 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1973 llvm::Value *Callee =
1974 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1976 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee);
1981 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1982 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1983 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1984 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
1985 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1986 if (GV->isDeclaration())
1987 emitVBTableDefinition(*VBT, RD, GV);
1991 llvm::GlobalVariable *
1992 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1993 llvm::GlobalVariable::LinkageTypes Linkage) {
1994 SmallString<256> OutName;
1995 llvm::raw_svector_ostream Out(OutName);
1996 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1997 StringRef Name = OutName.str();
1999 llvm::ArrayType *VBTableType =
2000 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2002 assert(!CGM.getModule().getNamedGlobal(Name) &&
2003 "vbtable with this name already exists: mangling bug?");
2004 llvm::GlobalVariable *GV =
2005 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
2006 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2008 if (RD->hasAttr<DLLImportAttr>())
2009 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2010 else if (RD->hasAttr<DLLExportAttr>())
2011 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2013 if (!GV->hasExternalLinkage())
2014 emitVBTableDefinition(VBT, RD, GV);
2019 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2020 const CXXRecordDecl *RD,
2021 llvm::GlobalVariable *GV) const {
2022 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2024 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2025 "should only emit vbtables for classes with vbtables");
2027 const ASTRecordLayout &BaseLayout =
2028 getContext().getASTRecordLayout(VBT.IntroducingObject);
2029 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2031 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2034 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2035 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2036 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2038 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2039 for (const auto &I : ObjectWithVPtr->vbases()) {
2040 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2041 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2042 assert(!Offset.isNegative());
2044 // Make it relative to the subobject vbptr.
2045 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2046 if (VBT.getVBaseWithVPtr())
2047 CompleteVBPtrOffset +=
2048 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2049 Offset -= CompleteVBPtrOffset;
2051 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2052 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2053 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2056 assert(Offsets.size() ==
2057 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
2058 ->getElementType())->getNumElements());
2059 llvm::ArrayType *VBTableType =
2060 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2061 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2062 GV->setInitializer(Init);
2064 if (RD->hasAttr<DLLImportAttr>())
2065 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2068 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2070 const ThisAdjustment &TA) {
2072 return This.getPointer();
2074 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2077 if (TA.Virtual.isEmpty()) {
2078 V = This.getPointer();
2080 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2081 // Adjust the this argument based on the vtordisp value.
2082 Address VtorDispPtr =
2083 CGF.Builder.CreateConstInBoundsByteGEP(This,
2084 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2085 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2086 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2087 V = CGF.Builder.CreateGEP(This.getPointer(),
2088 CGF.Builder.CreateNeg(VtorDisp));
2090 // Unfortunately, having applied the vtordisp means that we no
2091 // longer really have a known alignment for the vbptr step.
2092 // We'll assume the vbptr is pointer-aligned.
2094 if (TA.Virtual.Microsoft.VBPtrOffset) {
2095 // If the final overrider is defined in a virtual base other than the one
2096 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2097 // the vbtable of the derived class.
2098 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2099 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2101 llvm::Value *VBaseOffset =
2102 GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
2103 -TA.Virtual.Microsoft.VBPtrOffset,
2104 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2105 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2109 if (TA.NonVirtual) {
2110 // Non-virtual adjustment might result in a pointer outside the allocated
2111 // object, e.g. if the final overrider class is laid out after the virtual
2112 // base that declares a method in the most derived class.
2113 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
2116 // Don't need to bitcast back, the call CodeGen will handle this.
2121 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2122 const ReturnAdjustment &RA) {
2124 return Ret.getPointer();
2126 auto OrigTy = Ret.getType();
2127 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2129 llvm::Value *V = Ret.getPointer();
2130 if (RA.Virtual.Microsoft.VBIndex) {
2131 assert(RA.Virtual.Microsoft.VBIndex > 0);
2132 int32_t IntSize = CGF.getIntSize().getQuantity();
2134 llvm::Value *VBaseOffset =
2135 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2136 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2137 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2141 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2143 // Cast back to the original type.
2144 return CGF.Builder.CreateBitCast(V, OrigTy);
2147 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2148 QualType elementType) {
2149 // Microsoft seems to completely ignore the possibility of a
2150 // two-argument usual deallocation function.
2151 return elementType.isDestructedType();
2154 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2155 // Microsoft seems to completely ignore the possibility of a
2156 // two-argument usual deallocation function.
2157 return expr->getAllocatedType().isDestructedType();
2160 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2161 // The array cookie is always a size_t; we then pad that out to the
2162 // alignment of the element type.
2163 ASTContext &Ctx = getContext();
2164 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2165 Ctx.getTypeAlignInChars(type));
2168 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2170 CharUnits cookieSize) {
2171 Address numElementsPtr =
2172 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2173 return CGF.Builder.CreateLoad(numElementsPtr);
2176 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2178 llvm::Value *numElements,
2179 const CXXNewExpr *expr,
2180 QualType elementType) {
2181 assert(requiresArrayCookie(expr));
2183 // The size of the cookie.
2184 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2186 // Compute an offset to the cookie.
2187 Address cookiePtr = newPtr;
2189 // Write the number of elements into the appropriate slot.
2190 Address numElementsPtr
2191 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2192 CGF.Builder.CreateStore(numElements, numElementsPtr);
2194 // Finally, compute a pointer to the actual data buffer by skipping
2195 // over the cookie completely.
2196 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2199 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2200 llvm::Constant *Dtor,
2201 llvm::Constant *Addr) {
2202 // Create a function which calls the destructor.
2203 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2205 // extern "C" int __tlregdtor(void (*f)(void));
2206 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2207 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
2209 llvm::Constant *TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2210 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2211 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor))
2212 TLRegDtorFn->setDoesNotThrow();
2214 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2217 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2218 llvm::Constant *Dtor,
2219 llvm::Constant *Addr) {
2221 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2223 // The default behavior is to use atexit.
2224 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2227 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2228 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2229 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2230 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2231 if (CXXThreadLocalInits.empty())
2234 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2236 ? "/include:___dyn_tls_init@12"
2237 : "/include:__dyn_tls_init");
2239 // This will create a GV in the .CRT$XDU section. It will point to our
2240 // initialization function. The CRT will call all of these function
2241 // pointers at start-up time and, eventually, at thread-creation time.
2242 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2243 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2244 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
2245 llvm::GlobalVariable::InternalLinkage, InitFunc,
2246 Twine(InitFunc->getName(), "$initializer$"));
2247 InitFuncPtr->setSection(".CRT$XDU");
2248 // This variable has discardable linkage, we have to add it to @llvm.used to
2249 // ensure it won't get discarded.
2250 CGM.addUsedGlobal(InitFuncPtr);
2254 std::vector<llvm::Function *> NonComdatInits;
2255 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2256 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2257 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2258 llvm::Function *F = CXXThreadLocalInits[I];
2260 // If the GV is already in a comdat group, then we have to join it.
2261 if (llvm::Comdat *C = GV->getComdat())
2262 AddToXDU(F)->setComdat(C);
2264 NonComdatInits.push_back(F);
2267 if (!NonComdatInits.empty()) {
2268 llvm::FunctionType *FTy =
2269 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2270 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
2271 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2272 SourceLocation(), /*TLS=*/true);
2273 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2279 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2281 QualType LValType) {
2282 CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
2286 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2287 StringRef VarName("_Init_thread_epoch");
2288 CharUnits Align = CGM.getIntAlign();
2289 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2290 return ConstantAddress(GV, Align);
2291 auto *GV = new llvm::GlobalVariable(
2292 CGM.getModule(), CGM.IntTy,
2293 /*Constant=*/false, llvm::GlobalVariable::ExternalLinkage,
2294 /*Initializer=*/nullptr, VarName,
2295 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2296 GV->setAlignment(Align.getQuantity());
2297 return ConstantAddress(GV, Align);
2300 static llvm::Constant *getInitThreadHeaderFn(CodeGenModule &CGM) {
2301 llvm::FunctionType *FTy =
2302 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2303 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2304 return CGM.CreateRuntimeFunction(
2305 FTy, "_Init_thread_header",
2306 llvm::AttributeList::get(CGM.getLLVMContext(),
2307 llvm::AttributeList::FunctionIndex,
2308 llvm::Attribute::NoUnwind),
2312 static llvm::Constant *getInitThreadFooterFn(CodeGenModule &CGM) {
2313 llvm::FunctionType *FTy =
2314 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2315 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2316 return CGM.CreateRuntimeFunction(
2317 FTy, "_Init_thread_footer",
2318 llvm::AttributeList::get(CGM.getLLVMContext(),
2319 llvm::AttributeList::FunctionIndex,
2320 llvm::Attribute::NoUnwind),
2324 static llvm::Constant *getInitThreadAbortFn(CodeGenModule &CGM) {
2325 llvm::FunctionType *FTy =
2326 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2327 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2328 return CGM.CreateRuntimeFunction(
2329 FTy, "_Init_thread_abort",
2330 llvm::AttributeList::get(CGM.getLLVMContext(),
2331 llvm::AttributeList::FunctionIndex,
2332 llvm::Attribute::NoUnwind),
2337 struct ResetGuardBit final : EHScopeStack::Cleanup {
2340 ResetGuardBit(Address Guard, unsigned GuardNum)
2341 : Guard(Guard), GuardNum(GuardNum) {}
2343 void Emit(CodeGenFunction &CGF, Flags flags) override {
2344 // Reset the bit in the mask so that the static variable may be
2346 CGBuilderTy &Builder = CGF.Builder;
2347 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2348 llvm::ConstantInt *Mask =
2349 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2350 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2354 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2356 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2358 void Emit(CodeGenFunction &CGF, Flags flags) override {
2359 // Calling _Init_thread_abort will reset the guard's state.
2360 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2365 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2366 llvm::GlobalVariable *GV,
2368 // MSVC only uses guards for static locals.
2369 if (!D.isStaticLocal()) {
2370 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2371 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2372 llvm::Function *F = CGF.CurFn;
2373 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2374 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2375 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2379 bool ThreadlocalStatic = D.getTLSKind();
2380 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2382 // Thread-safe static variables which aren't thread-specific have a
2383 // per-variable guard.
2384 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2386 CGBuilderTy &Builder = CGF.Builder;
2387 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2388 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2389 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2391 // Get the guard variable for this function if we have one already.
2392 GuardInfo *GI = nullptr;
2393 if (ThreadlocalStatic)
2394 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2395 else if (!ThreadsafeStatic)
2396 GI = &GuardVariableMap[D.getDeclContext()];
2398 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2400 if (D.isExternallyVisible()) {
2401 // Externally visible variables have to be numbered in Sema to properly
2402 // handle unreachable VarDecls.
2403 GuardNum = getContext().getStaticLocalNumber(&D);
2404 assert(GuardNum > 0);
2406 } else if (HasPerVariableGuard) {
2407 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2409 // Non-externally visible variables are numbered here in CodeGen.
2410 GuardNum = GI->BitIndex++;
2413 if (!HasPerVariableGuard && GuardNum >= 32) {
2414 if (D.isExternallyVisible())
2415 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2421 // Mangle the name for the guard.
2422 SmallString<256> GuardName;
2424 llvm::raw_svector_ostream Out(GuardName);
2425 if (HasPerVariableGuard)
2426 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2429 getMangleContext().mangleStaticGuardVariable(&D, Out);
2432 // Create the guard variable with a zero-initializer. Just absorb linkage,
2433 // visibility and dll storage class from the guarded variable.
2435 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2436 GV->getLinkage(), Zero, GuardName.str());
2437 GuardVar->setVisibility(GV->getVisibility());
2438 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2439 GuardVar->setAlignment(GuardAlign.getQuantity());
2440 if (GuardVar->isWeakForLinker())
2441 GuardVar->setComdat(
2442 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2444 GuardVar->setThreadLocal(true);
2445 if (GI && !HasPerVariableGuard)
2446 GI->Guard = GuardVar;
2449 ConstantAddress GuardAddr(GuardVar, GuardAlign);
2451 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2452 "static local from the same function had different linkage");
2454 if (!HasPerVariableGuard) {
2455 // Pseudo code for the test:
2456 // if (!(GuardVar & MyGuardBit)) {
2457 // GuardVar |= MyGuardBit;
2458 // ... initialize the object ...;
2461 // Test our bit from the guard variable.
2462 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2463 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2464 llvm::Value *IsInitialized =
2465 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
2466 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2467 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2468 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
2470 // Set our bit in the guard variable and emit the initializer and add a global
2471 // destructor if appropriate.
2472 CGF.EmitBlock(InitBlock);
2473 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2474 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2475 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2476 CGF.PopCleanupBlock();
2477 Builder.CreateBr(EndBlock);
2480 CGF.EmitBlock(EndBlock);
2482 // Pseudo code for the test:
2483 // if (TSS > _Init_thread_epoch) {
2484 // _Init_thread_header(&TSS);
2486 // ... initialize the object ...;
2487 // _Init_thread_footer(&TSS);
2491 // The algorithm is almost identical to what can be found in the appendix
2494 // This BasicBLock determines whether or not we have any work to do.
2495 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2496 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2497 llvm::LoadInst *InitThreadEpoch =
2498 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2499 llvm::Value *IsUninitialized =
2500 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2501 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2502 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2503 Builder.CreateCondBr(IsUninitialized, AttemptInitBlock, EndBlock);
2505 // This BasicBlock attempts to determine whether or not this thread is
2506 // responsible for doing the initialization.
2507 CGF.EmitBlock(AttemptInitBlock);
2508 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2509 GuardAddr.getPointer());
2510 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2511 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2512 llvm::Value *ShouldDoInit =
2513 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2514 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2515 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2517 // Ok, we ended up getting selected as the initializing thread.
2518 CGF.EmitBlock(InitBlock);
2519 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2520 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2521 CGF.PopCleanupBlock();
2522 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2523 GuardAddr.getPointer());
2524 Builder.CreateBr(EndBlock);
2526 CGF.EmitBlock(EndBlock);
2530 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2531 // Null-ness for function memptrs only depends on the first field, which is
2532 // the function pointer. The rest don't matter, so we can zero initialize.
2533 if (MPT->isMemberFunctionPointer())
2536 // The virtual base adjustment field is always -1 for null, so if we have one
2537 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2538 // valid field offset.
2539 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2540 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2541 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
2542 RD->nullFieldOffsetIsZero());
2546 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2547 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2548 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2549 llvm::SmallVector<llvm::Type *, 4> fields;
2550 if (MPT->isMemberFunctionPointer())
2551 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2553 fields.push_back(CGM.IntTy); // FieldOffset
2555 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2557 fields.push_back(CGM.IntTy);
2558 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2559 fields.push_back(CGM.IntTy);
2560 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2561 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2563 if (fields.size() == 1)
2565 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2568 void MicrosoftCXXABI::
2569 GetNullMemberPointerFields(const MemberPointerType *MPT,
2570 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2571 assert(fields.empty());
2572 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2573 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2574 if (MPT->isMemberFunctionPointer()) {
2575 // FunctionPointerOrVirtualThunk
2576 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2578 if (RD->nullFieldOffsetIsZero())
2579 fields.push_back(getZeroInt()); // FieldOffset
2581 fields.push_back(getAllOnesInt()); // FieldOffset
2584 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2586 fields.push_back(getZeroInt());
2587 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2588 fields.push_back(getZeroInt());
2589 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2590 fields.push_back(getAllOnesInt());
2594 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2595 llvm::SmallVector<llvm::Constant *, 4> fields;
2596 GetNullMemberPointerFields(MPT, fields);
2597 if (fields.size() == 1)
2599 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2600 assert(Res->getType() == ConvertMemberPointerType(MPT));
2605 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2606 bool IsMemberFunction,
2607 const CXXRecordDecl *RD,
2608 CharUnits NonVirtualBaseAdjustment,
2609 unsigned VBTableIndex) {
2610 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2612 // Single inheritance class member pointer are represented as scalars instead
2614 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2617 llvm::SmallVector<llvm::Constant *, 4> fields;
2618 fields.push_back(FirstField);
2620 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2621 fields.push_back(llvm::ConstantInt::get(
2622 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2624 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2625 CharUnits Offs = CharUnits::Zero();
2627 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2628 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2631 // The rest of the fields are adjusted by conversions to a more derived class.
2632 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2633 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2635 return llvm::ConstantStruct::getAnon(fields);
2639 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2641 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2642 if (RD->getMSInheritanceModel() ==
2643 MSInheritanceAttr::Keyword_virtual_inheritance)
2644 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2645 llvm::Constant *FirstField =
2646 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2647 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2648 CharUnits::Zero(), /*VBTableIndex=*/0);
2651 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2653 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2654 const ValueDecl *MPD = MP.getMemberPointerDecl();
2656 return EmitNullMemberPointer(DstTy);
2658 ASTContext &Ctx = getContext();
2659 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2662 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2663 C = EmitMemberFunctionPointer(MD);
2665 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2666 C = EmitMemberDataPointer(DstTy, FieldOffset);
2669 if (!MemberPointerPath.empty()) {
2670 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2671 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2672 const MemberPointerType *SrcTy =
2673 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2674 ->castAs<MemberPointerType>();
2676 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2677 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2678 const CXXRecordDecl *PrevRD = SrcRD;
2679 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2680 const CXXRecordDecl *Base = nullptr;
2681 const CXXRecordDecl *Derived = nullptr;
2682 if (DerivedMember) {
2689 for (const CXXBaseSpecifier &BS : Derived->bases())
2690 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2691 Base->getCanonicalDecl())
2692 DerivedToBasePath.push_back(&BS);
2695 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2697 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2698 : CK_BaseToDerivedMemberPointer;
2699 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2700 DerivedToBasePath.end(), C);
2706 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2707 assert(MD->isInstance() && "Member function must not be static!");
2709 MD = MD->getCanonicalDecl();
2710 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2711 const CXXRecordDecl *RD = MD->getParent()->getMostRecentDecl();
2712 CodeGenTypes &Types = CGM.getTypes();
2714 unsigned VBTableIndex = 0;
2715 llvm::Constant *FirstField;
2716 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2717 if (!MD->isVirtual()) {
2719 // Check whether the function has a computable LLVM signature.
2720 if (Types.isFuncTypeConvertible(FPT)) {
2721 // The function has a computable LLVM signature; use the correct type.
2722 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2724 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2725 // function type is incomplete.
2728 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2730 auto &VTableContext = CGM.getMicrosoftVTableContext();
2731 MicrosoftVTableContext::MethodVFTableLocation ML =
2732 VTableContext.getMethodVFTableLocation(MD);
2733 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2734 // Include the vfptr adjustment if the method is in a non-primary vftable.
2735 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2737 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2740 if (VBTableIndex == 0 &&
2741 RD->getMSInheritanceModel() ==
2742 MSInheritanceAttr::Keyword_virtual_inheritance)
2743 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2745 // The rest of the fields are common with data member pointers.
2746 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2747 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2748 NonVirtualBaseAdjustment, VBTableIndex);
2751 /// Member pointers are the same if they're either bitwise identical *or* both
2752 /// null. Null-ness for function members is determined by the first field,
2753 /// while for data member pointers we must compare all fields.
2755 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2758 const MemberPointerType *MPT,
2760 CGBuilderTy &Builder = CGF.Builder;
2762 // Handle != comparisons by switching the sense of all boolean operations.
2763 llvm::ICmpInst::Predicate Eq;
2764 llvm::Instruction::BinaryOps And, Or;
2766 Eq = llvm::ICmpInst::ICMP_NE;
2767 And = llvm::Instruction::Or;
2768 Or = llvm::Instruction::And;
2770 Eq = llvm::ICmpInst::ICMP_EQ;
2771 And = llvm::Instruction::And;
2772 Or = llvm::Instruction::Or;
2775 // If this is a single field member pointer (single inheritance), this is a
2777 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2778 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2779 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2781 return Builder.CreateICmp(Eq, L, R);
2783 // Compare the first field.
2784 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2785 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2786 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2788 // Compare everything other than the first field.
2789 llvm::Value *Res = nullptr;
2790 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2791 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2792 llvm::Value *LF = Builder.CreateExtractValue(L, I);
2793 llvm::Value *RF = Builder.CreateExtractValue(R, I);
2794 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2796 Res = Builder.CreateBinOp(And, Res, Cmp);
2801 // Check if the first field is 0 if this is a function pointer.
2802 if (MPT->isMemberFunctionPointer()) {
2803 // (l1 == r1 && ...) || l0 == 0
2804 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2805 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2806 Res = Builder.CreateBinOp(Or, Res, IsZero);
2809 // Combine the comparison of the first field, which must always be true for
2810 // this comparison to succeeed.
2811 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2815 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2816 llvm::Value *MemPtr,
2817 const MemberPointerType *MPT) {
2818 CGBuilderTy &Builder = CGF.Builder;
2819 llvm::SmallVector<llvm::Constant *, 4> fields;
2820 // We only need one field for member functions.
2821 if (MPT->isMemberFunctionPointer())
2822 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2824 GetNullMemberPointerFields(MPT, fields);
2825 assert(!fields.empty());
2826 llvm::Value *FirstField = MemPtr;
2827 if (MemPtr->getType()->isStructTy())
2828 FirstField = Builder.CreateExtractValue(MemPtr, 0);
2829 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2831 // For function member pointers, we only need to test the function pointer
2832 // field. The other fields if any can be garbage.
2833 if (MPT->isMemberFunctionPointer())
2836 // Otherwise, emit a series of compares and combine the results.
2837 for (int I = 1, E = fields.size(); I < E; ++I) {
2838 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2839 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2840 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2845 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2846 llvm::Constant *Val) {
2847 // Function pointers are null if the pointer in the first field is null.
2848 if (MPT->isMemberFunctionPointer()) {
2849 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2850 Val->getAggregateElement(0U) : Val;
2851 return FirstField->isNullValue();
2854 // If it's not a function pointer and it's zero initializable, we can easily
2856 if (isZeroInitializable(MPT) && Val->isNullValue())
2859 // Otherwise, break down all the fields for comparison. Hopefully these
2860 // little Constants are reused, while a big null struct might not be.
2861 llvm::SmallVector<llvm::Constant *, 4> Fields;
2862 GetNullMemberPointerFields(MPT, Fields);
2863 if (Fields.size() == 1) {
2864 assert(Val->getType()->isIntegerTy());
2865 return Val == Fields[0];
2869 for (I = 0, E = Fields.size(); I != E; ++I) {
2870 if (Val->getAggregateElement(I) != Fields[I])
2877 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2879 llvm::Value *VBPtrOffset,
2880 llvm::Value *VBTableOffset,
2881 llvm::Value **VBPtrOut) {
2882 CGBuilderTy &Builder = CGF.Builder;
2883 // Load the vbtable pointer from the vbptr in the instance.
2884 This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
2885 llvm::Value *VBPtr =
2886 Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr");
2887 if (VBPtrOut) *VBPtrOut = VBPtr;
2888 VBPtr = Builder.CreateBitCast(VBPtr,
2889 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
2891 CharUnits VBPtrAlign;
2892 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
2893 VBPtrAlign = This.getAlignment().alignmentAtOffset(
2894 CharUnits::fromQuantity(CI->getSExtValue()));
2896 VBPtrAlign = CGF.getPointerAlign();
2899 llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable");
2901 // Translate from byte offset to table index. It improves analyzability.
2902 llvm::Value *VBTableIndex = Builder.CreateAShr(
2903 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2904 "vbtindex", /*isExact=*/true);
2906 // Load an i32 offset from the vb-table.
2907 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2908 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2909 return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4),
2913 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2915 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2916 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2917 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2918 CGBuilderTy &Builder = CGF.Builder;
2919 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
2920 llvm::BasicBlock *OriginalBB = nullptr;
2921 llvm::BasicBlock *SkipAdjustBB = nullptr;
2922 llvm::BasicBlock *VBaseAdjustBB = nullptr;
2924 // In the unspecified inheritance model, there might not be a vbtable at all,
2925 // in which case we need to skip the virtual base lookup. If there is a
2926 // vbtable, the first entry is a no-op entry that gives back the original
2927 // base, so look for a virtual base adjustment offset of zero.
2929 OriginalBB = Builder.GetInsertBlock();
2930 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2931 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2932 llvm::Value *IsVirtual =
2933 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2935 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2936 CGF.EmitBlock(VBaseAdjustBB);
2939 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2940 // know the vbptr offset.
2942 CharUnits offs = CharUnits::Zero();
2943 if (!RD->hasDefinition()) {
2944 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2945 unsigned DiagID = Diags.getCustomDiagID(
2946 DiagnosticsEngine::Error,
2947 "member pointer representation requires a "
2948 "complete class type for %0 to perform this expression");
2949 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2950 } else if (RD->getNumVBases())
2951 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2952 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2954 llvm::Value *VBPtr = nullptr;
2955 llvm::Value *VBaseOffs =
2956 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2957 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2959 // Merge control flow with the case where we didn't have to adjust.
2960 if (VBaseAdjustBB) {
2961 Builder.CreateBr(SkipAdjustBB);
2962 CGF.EmitBlock(SkipAdjustBB);
2963 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2964 Phi->addIncoming(Base.getPointer(), OriginalBB);
2965 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2968 return AdjustedBase;
2971 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2972 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
2973 const MemberPointerType *MPT) {
2974 assert(MPT->isMemberDataPointer());
2975 unsigned AS = Base.getAddressSpace();
2977 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2978 CGBuilderTy &Builder = CGF.Builder;
2979 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2980 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2982 // Extract the fields we need, regardless of model. We'll apply them if we
2984 llvm::Value *FieldOffset = MemPtr;
2985 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2986 llvm::Value *VBPtrOffset = nullptr;
2987 if (MemPtr->getType()->isStructTy()) {
2988 // We need to extract values.
2990 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2991 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2992 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2993 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2994 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2998 if (VirtualBaseAdjustmentOffset) {
2999 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3002 Addr = Base.getPointer();
3006 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3008 // Apply the offset, which we assume is non-null.
3009 Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset");
3011 // Cast the address to the appropriate pointer type, adopting the address
3012 // space of the base pointer.
3013 return Builder.CreateBitCast(Addr, PType);
3017 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3020 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3021 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3022 E->getCastKind() == CK_ReinterpretMemberPointer);
3024 // Use constant emission if we can.
3025 if (isa<llvm::Constant>(Src))
3026 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3028 // We may be adding or dropping fields from the member pointer, so we need
3029 // both types and the inheritance models of both records.
3030 const MemberPointerType *SrcTy =
3031 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3032 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3033 bool IsFunc = SrcTy->isMemberFunctionPointer();
3035 // If the classes use the same null representation, reinterpret_cast is a nop.
3036 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3037 if (IsReinterpret && IsFunc)
3040 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3041 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3042 if (IsReinterpret &&
3043 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3046 CGBuilderTy &Builder = CGF.Builder;
3048 // Branch past the conversion if Src is null.
3049 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3050 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3052 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3053 // pointer value of the destination type.
3054 if (IsReinterpret) {
3055 // For reinterpret casts, sema ensures that src and dst are both functions
3056 // or data and have the same size, which means the LLVM types should match.
3057 assert(Src->getType() == DstNull->getType());
3058 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3061 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3062 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3063 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3064 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3065 CGF.EmitBlock(ConvertBB);
3067 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3068 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3071 Builder.CreateBr(ContinueBB);
3073 // In the continuation, choose between DstNull and Dst.
3074 CGF.EmitBlock(ContinueBB);
3075 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3076 Phi->addIncoming(DstNull, OriginalBB);
3077 Phi->addIncoming(Dst, ConvertBB);
3081 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3082 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3083 CastExpr::path_const_iterator PathBegin,
3084 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3085 CGBuilderTy &Builder) {
3086 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3087 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3088 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
3089 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
3090 bool IsFunc = SrcTy->isMemberFunctionPointer();
3091 bool IsConstant = isa<llvm::Constant>(Src);
3094 llvm::Value *FirstField = Src;
3095 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3096 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3097 llvm::Value *VBPtrOffset = getZeroInt();
3098 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
3099 // We need to extract values.
3101 FirstField = Builder.CreateExtractValue(Src, I++);
3102 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
3103 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3104 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
3105 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3106 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
3107 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3110 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3111 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3112 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3114 // For data pointers, we adjust the field offset directly. For functions, we
3115 // have a separate field.
3116 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3118 // The virtual inheritance model has a quirk: the virtual base table is always
3119 // referenced when dereferencing a member pointer even if the member pointer
3120 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3121 // to point backwards to the top of the MDC from the first VBase. Undo this
3122 // adjustment to normalize the member pointer.
3123 llvm::Value *SrcVBIndexEqZero =
3124 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3125 if (SrcInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3126 if (int64_t SrcOffsetToFirstVBase =
3127 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3128 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3130 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3132 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3136 // A non-zero vbindex implies that we are dealing with a source member in a
3137 // floating virtual base in addition to some non-virtual offset. If the
3138 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3139 // fixed, base. The difference between these two cases is that the vbindex +
3140 // nvoffset *always* point to the member regardless of what context they are
3141 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3142 // base requires explicit nv adjustment.
3143 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3145 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3148 llvm::Value *NVDisp;
3149 if (IsDerivedToBase)
3150 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3152 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3154 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3156 // Update the vbindex to an appropriate value in the destination because
3157 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3158 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3159 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance) &&
3160 MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) {
3161 if (llvm::GlobalVariable *VDispMap =
3162 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3163 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3164 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3166 llvm::Constant *Mapping = VDispMap->getInitializer();
3167 VirtualBaseAdjustmentOffset =
3168 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3170 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3171 VirtualBaseAdjustmentOffset =
3172 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs),
3173 CharUnits::fromQuantity(4));
3177 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3181 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3182 // it to the offset of the vbptr.
3183 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) {
3184 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3186 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3188 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3191 // Likewise, apply a similar adjustment so that dereferencing the member
3192 // pointer correctly accounts for the distance between the start of the first
3193 // virtual base and the top of the MDC.
3194 if (DstInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3195 if (int64_t DstOffsetToFirstVBase =
3196 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3197 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3199 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3201 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3205 // Recompose dst from the null struct and the adjusted fields from src.
3207 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
3210 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3212 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3213 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
3214 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3215 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
3216 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3217 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
3218 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3224 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3225 llvm::Constant *Src) {
3226 const MemberPointerType *SrcTy =
3227 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3228 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3230 CastKind CK = E->getCastKind();
3232 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3233 E->path_end(), Src);
3236 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3237 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3238 CastExpr::path_const_iterator PathBegin,
3239 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3240 assert(CK == CK_DerivedToBaseMemberPointer ||
3241 CK == CK_BaseToDerivedMemberPointer ||
3242 CK == CK_ReinterpretMemberPointer);
3243 // If src is null, emit a new null for dst. We can't return src because dst
3244 // might have a new representation.
3245 if (MemberPointerConstantIsNull(SrcTy, Src))
3246 return EmitNullMemberPointer(DstTy);
3248 // We don't need to do anything for reinterpret_casts of non-null member
3249 // pointers. We should only get here when the two type representations have
3251 if (CK == CK_ReinterpretMemberPointer)
3254 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3255 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3256 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3261 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3262 CodeGenFunction &CGF, const Expr *E, Address This,
3263 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3264 const MemberPointerType *MPT) {
3265 assert(MPT->isMemberFunctionPointer());
3266 const FunctionProtoType *FPT =
3267 MPT->getPointeeType()->castAs<FunctionProtoType>();
3268 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3269 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3270 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3271 CGBuilderTy &Builder = CGF.Builder;
3273 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
3275 // Extract the fields we need, regardless of model. We'll apply them if we
3277 llvm::Value *FunctionPointer = MemPtr;
3278 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3279 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3280 llvm::Value *VBPtrOffset = nullptr;
3281 if (MemPtr->getType()->isStructTy()) {
3282 // We need to extract values.
3284 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3285 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
3286 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3287 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
3288 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3289 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
3290 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3293 if (VirtualBaseAdjustmentOffset) {
3294 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3295 VirtualBaseAdjustmentOffset, VBPtrOffset);
3297 ThisPtrForCall = This.getPointer();
3300 if (NonVirtualBaseAdjustment) {
3301 // Apply the adjustment and cast back to the original struct type.
3302 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3303 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
3304 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3309 Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3310 CGCallee Callee(FPT, FunctionPointer);
3314 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3315 return new MicrosoftCXXABI(CGM);
3318 // MS RTTI Overview:
3319 // The run time type information emitted by cl.exe contains 5 distinct types of
3320 // structures. Many of them reference each other.
3322 // TypeInfo: Static classes that are returned by typeid.
3324 // CompleteObjectLocator: Referenced by vftables. They contain information
3325 // required for dynamic casting, including OffsetFromTop. They also contain
3326 // a reference to the TypeInfo for the type and a reference to the
3327 // CompleteHierarchyDescriptor for the type.
3329 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
3330 // Used during dynamic_cast to walk a class hierarchy. References a base
3331 // class array and the size of said array.
3333 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3334 // somewhat of a misnomer because the most derived class is also in the list
3335 // as well as multiple copies of virtual bases (if they occur multiple times
3336 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for
3337 // every path in the hierarchy, in pre-order depth first order. Note, we do
3338 // not declare a specific llvm type for BaseClassArray, it's merely an array
3339 // of BaseClassDescriptor pointers.
3341 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3342 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3343 // BaseClassArray is. It contains information about a class within a
3344 // hierarchy such as: is this base is ambiguous and what is its offset in the
3345 // vbtable. The names of the BaseClassDescriptors have all of their fields
3346 // mangled into them so they can be aggressively deduplicated by the linker.
3348 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3349 StringRef MangledName("\01??_7type_info@@6B@");
3350 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3352 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3354 llvm::GlobalVariable::ExternalLinkage,
3355 /*Initializer=*/nullptr, MangledName);
3360 /// \brief A Helper struct that stores information about a class in a class
3361 /// hierarchy. The information stored in these structs struct is used during
3362 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3363 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3364 // implicit depth first pre-order tree connectivity. getFirstChild and
3365 // getNextSibling allow us to walk the tree efficiently.
3366 struct MSRTTIClass {
3368 IsPrivateOnPath = 1 | 8,
3372 HasHierarchyDescriptor = 64
3374 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3375 uint32_t initialize(const MSRTTIClass *Parent,
3376 const CXXBaseSpecifier *Specifier);
3378 MSRTTIClass *getFirstChild() { return this + 1; }
3379 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3380 return Child + 1 + Child->NumBases;
3383 const CXXRecordDecl *RD, *VirtualRoot;
3384 uint32_t Flags, NumBases, OffsetInVBase;
3387 /// \brief Recursively initialize the base class array.
3388 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3389 const CXXBaseSpecifier *Specifier) {
3390 Flags = HasHierarchyDescriptor;
3392 VirtualRoot = nullptr;
3395 if (Specifier->getAccessSpecifier() != AS_public)
3396 Flags |= IsPrivate | IsPrivateOnPath;
3397 if (Specifier->isVirtual()) {
3402 if (Parent->Flags & IsPrivateOnPath)
3403 Flags |= IsPrivateOnPath;
3404 VirtualRoot = Parent->VirtualRoot;
3405 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3406 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3410 MSRTTIClass *Child = getFirstChild();
3411 for (const CXXBaseSpecifier &Base : RD->bases()) {
3412 NumBases += Child->initialize(this, &Base) + 1;
3413 Child = getNextChild(Child);
3418 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3419 switch (Ty->getLinkage()) {
3421 case InternalLinkage:
3422 case UniqueExternalLinkage:
3423 return llvm::GlobalValue::InternalLinkage;
3425 case VisibleNoLinkage:
3426 case ModuleInternalLinkage:
3428 case ExternalLinkage:
3429 return llvm::GlobalValue::LinkOnceODRLinkage;
3431 llvm_unreachable("Invalid linkage!");
3434 /// \brief An ephemeral helper class for building MS RTTI types. It caches some
3435 /// calls to the module and information about the most derived class in a
3437 struct MSRTTIBuilder {
3439 HasBranchingHierarchy = 1,
3440 HasVirtualBranchingHierarchy = 2,
3441 HasAmbiguousBases = 4
3444 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3445 : CGM(ABI.CGM), Context(CGM.getContext()),
3446 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3447 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3450 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3451 llvm::GlobalVariable *
3452 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3453 llvm::GlobalVariable *getClassHierarchyDescriptor();
3454 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3457 ASTContext &Context;
3458 llvm::LLVMContext &VMContext;
3459 llvm::Module &Module;
3460 const CXXRecordDecl *RD;
3461 llvm::GlobalVariable::LinkageTypes Linkage;
3462 MicrosoftCXXABI &ABI;
3467 /// \brief Recursively serializes a class hierarchy in pre-order depth first
3469 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3470 const CXXRecordDecl *RD) {
3471 Classes.push_back(MSRTTIClass(RD));
3472 for (const CXXBaseSpecifier &Base : RD->bases())
3473 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3476 /// \brief Find ambiguity among base classes.
3478 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3479 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3480 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3481 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3482 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3483 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3484 !VirtualBases.insert(Class->RD).second) {
3485 Class = MSRTTIClass::getNextChild(Class);
3488 if (!UniqueBases.insert(Class->RD).second)
3489 AmbiguousBases.insert(Class->RD);
3492 if (AmbiguousBases.empty())
3494 for (MSRTTIClass &Class : Classes)
3495 if (AmbiguousBases.count(Class.RD))
3496 Class.Flags |= MSRTTIClass::IsAmbiguous;
3499 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3500 SmallString<256> MangledName;
3502 llvm::raw_svector_ostream Out(MangledName);
3503 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3506 // Check to see if we've already declared this ClassHierarchyDescriptor.
3507 if (auto CHD = Module.getNamedGlobal(MangledName))
3510 // Serialize the class hierarchy and initialize the CHD Fields.
3511 SmallVector<MSRTTIClass, 8> Classes;
3512 serializeClassHierarchy(Classes, RD);
3513 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3514 detectAmbiguousBases(Classes);
3516 for (auto Class : Classes) {
3517 if (Class.RD->getNumBases() > 1)
3518 Flags |= HasBranchingHierarchy;
3519 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3520 // believe the field isn't actually used.
3521 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3522 Flags |= HasAmbiguousBases;
3524 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3525 Flags |= HasVirtualBranchingHierarchy;
3526 // These gep indices are used to get the address of the first element of the
3527 // base class array.
3528 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3529 llvm::ConstantInt::get(CGM.IntTy, 0)};
3531 // Forward-declare the class hierarchy descriptor
3532 auto Type = ABI.getClassHierarchyDescriptorType();
3533 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3534 /*Initializer=*/nullptr,
3536 if (CHD->isWeakForLinker())
3537 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3539 auto *Bases = getBaseClassArray(Classes);
3541 // Initialize the base class ClassHierarchyDescriptor.
3542 llvm::Constant *Fields[] = {
3543 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3544 llvm::ConstantInt::get(CGM.IntTy, Flags),
3545 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3546 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3547 Bases->getValueType(), Bases,
3548 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3550 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3554 llvm::GlobalVariable *
3555 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3556 SmallString<256> MangledName;
3558 llvm::raw_svector_ostream Out(MangledName);
3559 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3562 // Forward-declare the base class array.
3563 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3564 // mode) bytes of padding. We provide a pointer sized amount of padding by
3565 // adding +1 to Classes.size(). The sections have pointer alignment and are
3566 // marked pick-any so it shouldn't matter.
3567 llvm::Type *PtrType = ABI.getImageRelativeType(
3568 ABI.getBaseClassDescriptorType()->getPointerTo());
3569 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3571 new llvm::GlobalVariable(Module, ArrType,
3572 /*Constant=*/true, Linkage,
3573 /*Initializer=*/nullptr, MangledName);
3574 if (BCA->isWeakForLinker())
3575 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3577 // Initialize the BaseClassArray.
3578 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3579 for (MSRTTIClass &Class : Classes)
3580 BaseClassArrayData.push_back(
3581 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3582 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3583 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3587 llvm::GlobalVariable *
3588 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3589 // Compute the fields for the BaseClassDescriptor. They are computed up front
3590 // because they are mangled into the name of the object.
3591 uint32_t OffsetInVBTable = 0;
3592 int32_t VBPtrOffset = -1;
3593 if (Class.VirtualRoot) {
3594 auto &VTableContext = CGM.getMicrosoftVTableContext();
3595 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3596 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3599 SmallString<256> MangledName;
3601 llvm::raw_svector_ostream Out(MangledName);
3602 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3603 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3607 // Check to see if we've already declared this object.
3608 if (auto BCD = Module.getNamedGlobal(MangledName))
3611 // Forward-declare the base class descriptor.
3612 auto Type = ABI.getBaseClassDescriptorType();
3614 new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3615 /*Initializer=*/nullptr, MangledName);
3616 if (BCD->isWeakForLinker())
3617 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3619 // Initialize the BaseClassDescriptor.
3620 llvm::Constant *Fields[] = {
3621 ABI.getImageRelativeConstant(
3622 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3623 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3624 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3625 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3626 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3627 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3628 ABI.getImageRelativeConstant(
3629 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3631 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3635 llvm::GlobalVariable *
3636 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3637 SmallString<256> MangledName;
3639 llvm::raw_svector_ostream Out(MangledName);
3640 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3643 // Check to see if we've already computed this complete object locator.
3644 if (auto COL = Module.getNamedGlobal(MangledName))
3647 // Compute the fields of the complete object locator.
3648 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3649 int VFPtrOffset = 0;
3650 // The offset includes the vtordisp if one exists.
3651 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3652 if (Context.getASTRecordLayout(RD)
3653 .getVBaseOffsetsMap()
3655 ->second.hasVtorDisp())
3656 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3658 // Forward-declare the complete object locator.
3659 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3660 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3661 /*Initializer=*/nullptr, MangledName);
3663 // Initialize the CompleteObjectLocator.
3664 llvm::Constant *Fields[] = {
3665 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3666 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3667 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3668 ABI.getImageRelativeConstant(
3669 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3670 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3671 ABI.getImageRelativeConstant(COL),
3673 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3674 if (!ABI.isImageRelative())
3675 FieldsRef = FieldsRef.drop_back();
3676 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3677 if (COL->isWeakForLinker())
3678 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3682 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3683 bool &IsConst, bool &IsVolatile,
3684 bool &IsUnaligned) {
3685 T = Context.getExceptionObjectType(T);
3687 // C++14 [except.handle]p3:
3688 // A handler is a match for an exception object of type E if [...]
3689 // - the handler is of type cv T or const T& where T is a pointer type and
3690 // E is a pointer type that can be converted to T by [...]
3691 // - a qualification conversion
3694 IsUnaligned = false;
3695 QualType PointeeType = T->getPointeeType();
3696 if (!PointeeType.isNull()) {
3697 IsConst = PointeeType.isConstQualified();
3698 IsVolatile = PointeeType.isVolatileQualified();
3699 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3702 // Member pointer types like "const int A::*" are represented by having RTTI
3703 // for "int A::*" and separately storing the const qualifier.
3704 if (const auto *MPTy = T->getAs<MemberPointerType>())
3705 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3708 // Pointer types like "const int * const *" are represented by having RTTI
3709 // for "const int **" and separately storing the const qualifier.
3710 if (T->isPointerType())
3711 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3717 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3718 QualType CatchHandlerType) {
3719 // TypeDescriptors for exceptions never have qualified pointer types,
3720 // qualifiers are stored separately in order to support qualification
3722 bool IsConst, IsVolatile, IsUnaligned;
3724 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3726 bool IsReference = CatchHandlerType->isReferenceType();
3738 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3742 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3743 /// llvm::GlobalVariable * because different type descriptors have different
3744 /// types, and need to be abstracted. They are abstracting by casting the
3745 /// address to an Int8PtrTy.
3746 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3747 SmallString<256> MangledName;
3749 llvm::raw_svector_ostream Out(MangledName);
3750 getMangleContext().mangleCXXRTTI(Type, Out);
3753 // Check to see if we've already declared this TypeDescriptor.
3754 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3755 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3757 // Note for the future: If we would ever like to do deferred emission of
3758 // RTTI, check if emitting vtables opportunistically need any adjustment.
3760 // Compute the fields for the TypeDescriptor.
3761 SmallString<256> TypeInfoString;
3763 llvm::raw_svector_ostream Out(TypeInfoString);
3764 getMangleContext().mangleCXXRTTIName(Type, Out);
3767 // Declare and initialize the TypeDescriptor.
3768 llvm::Constant *Fields[] = {
3769 getTypeInfoVTable(CGM), // VFPtr
3770 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3771 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3772 llvm::StructType *TypeDescriptorType =
3773 getTypeDescriptorType(TypeInfoString);
3774 auto *Var = new llvm::GlobalVariable(
3775 CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3776 getLinkageForRTTI(Type),
3777 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3779 if (Var->isWeakForLinker())
3780 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3781 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3784 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
3785 llvm::GlobalVariable *
3786 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3787 const VPtrInfo &Info) {
3788 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3791 static void emitCXXConstructor(CodeGenModule &CGM,
3792 const CXXConstructorDecl *ctor,
3793 StructorType ctorType) {
3794 // There are no constructor variants, always emit the complete destructor.
3795 llvm::Function *Fn = CGM.codegenCXXStructor(ctor, StructorType::Complete);
3796 CGM.maybeSetTrivialComdat(*ctor, *Fn);
3799 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3800 StructorType dtorType) {
3801 // The complete destructor is equivalent to the base destructor for
3802 // classes with no virtual bases, so try to emit it as an alias.
3803 if (!dtor->getParent()->getNumVBases() &&
3804 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3805 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3806 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3807 if (ProducedAlias) {
3808 if (dtorType == StructorType::Complete)
3810 if (dtor->isVirtual())
3811 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3815 // The base destructor is equivalent to the base destructor of its
3816 // base class if there is exactly one non-virtual base class with a
3817 // non-trivial destructor, there are no fields with a non-trivial
3818 // destructor, and the body of the destructor is trivial.
3819 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3822 llvm::Function *Fn = CGM.codegenCXXStructor(dtor, dtorType);
3823 if (Fn->isWeakForLinker())
3824 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3827 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3828 StructorType Type) {
3829 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3830 emitCXXConstructor(CGM, CD, Type);
3833 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);
3837 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
3839 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
3841 // Calculate the mangled name.
3842 SmallString<256> ThunkName;
3843 llvm::raw_svector_ostream Out(ThunkName);
3844 getMangleContext().mangleCXXCtor(CD, CT, Out);
3846 // If the thunk has been generated previously, just return it.
3847 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
3848 return cast<llvm::Function>(GV);
3850 // Create the llvm::Function.
3851 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
3852 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3853 const CXXRecordDecl *RD = CD->getParent();
3854 QualType RecordTy = getContext().getRecordType(RD);
3855 llvm::Function *ThunkFn = llvm::Function::Create(
3856 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
3857 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
3858 FnInfo.getEffectiveCallingConvention()));
3859 if (ThunkFn->isWeakForLinker())
3860 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
3861 bool IsCopy = CT == Ctor_CopyingClosure;
3864 CodeGenFunction CGF(CGM);
3865 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
3867 // Build FunctionArgs.
3868 FunctionArgList FunctionArgs;
3870 // A constructor always starts with a 'this' pointer as its first argument.
3871 buildThisParam(CGF, FunctionArgs);
3873 // Following the 'this' pointer is a reference to the source object that we
3874 // are copying from.
3875 ImplicitParamDecl SrcParam(
3876 getContext(), /*DC=*/nullptr, SourceLocation(),
3877 &getContext().Idents.get("src"),
3878 getContext().getLValueReferenceType(RecordTy,
3879 /*SpelledAsLValue=*/true),
3880 ImplicitParamDecl::Other);
3882 FunctionArgs.push_back(&SrcParam);
3884 // Constructors for classes which utilize virtual bases have an additional
3885 // parameter which indicates whether or not it is being delegated to by a more
3886 // derived constructor.
3887 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
3889 &getContext().Idents.get("is_most_derived"),
3890 getContext().IntTy, ImplicitParamDecl::Other);
3891 // Only add the parameter to the list if thie class has virtual bases.
3892 if (RD->getNumVBases() > 0)
3893 FunctionArgs.push_back(&IsMostDerived);
3895 // Start defining the function.
3896 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
3897 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3898 FunctionArgs, CD->getLocation(), SourceLocation());
3899 // Create a scope with an artificial location for the body of this function.
3900 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
3902 llvm::Value *This = getThisValue(CGF);
3904 llvm::Value *SrcVal =
3905 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
3910 // Push the this ptr.
3911 Args.add(RValue::get(This), CD->getThisType(getContext()));
3913 // Push the src ptr.
3915 Args.add(RValue::get(SrcVal), SrcParam.getType());
3917 // Add the rest of the default arguments.
3918 SmallVector<const Stmt *, 4> ArgVec;
3919 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
3920 for (const ParmVarDecl *PD : params) {
3921 assert(PD->hasDefaultArg() && "ctor closure lacks default args");
3922 ArgVec.push_back(PD->getDefaultArg());
3925 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
3927 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
3928 CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
3930 // Insert any ABI-specific implicit constructor arguments.
3931 AddedStructorArgs ExtraArgs =
3932 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
3933 /*ForVirtualBase=*/false,
3934 /*Delegating=*/false, Args);
3935 // Call the destructor with our arguments.
3936 llvm::Constant *CalleePtr =
3937 CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3938 CGCallee Callee = CGCallee::forDirect(CalleePtr, CD);
3939 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
3940 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
3941 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
3943 Cleanups.ForceCleanup();
3945 // Emit the ret instruction, remove any temporary instructions created for the
3947 CGF.FinishFunction(SourceLocation());
3952 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
3954 int32_t VBPtrOffset,
3956 assert(!T->isReferenceType());
3958 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
3959 const CXXConstructorDecl *CD =
3960 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
3961 CXXCtorType CT = Ctor_Complete;
3963 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
3964 CT = Ctor_CopyingClosure;
3966 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
3967 SmallString<256> MangledName;
3969 llvm::raw_svector_ostream Out(MangledName);
3970 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
3971 VBPtrOffset, VBIndex, Out);
3973 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3974 return getImageRelativeConstant(GV);
3976 // The TypeDescriptor is used by the runtime to determine if a catch handler
3977 // is appropriate for the exception object.
3978 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
3980 // The runtime is responsible for calling the copy constructor if the
3981 // exception is caught by value.
3982 llvm::Constant *CopyCtor;
3984 if (CT == Ctor_CopyingClosure)
3985 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
3987 CopyCtor = CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3989 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
3991 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
3993 CopyCtor = getImageRelativeConstant(CopyCtor);
3995 bool IsScalar = !RD;
3996 bool HasVirtualBases = false;
3997 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
3998 QualType PointeeType = T;
3999 if (T->isPointerType())
4000 PointeeType = T->getPointeeType();
4001 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4002 HasVirtualBases = RD->getNumVBases() > 0;
4003 if (IdentifierInfo *II = RD->getIdentifier())
4004 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4007 // Encode the relevant CatchableType properties into the Flags bitfield.
4008 // FIXME: Figure out how bits 2 or 8 can get set.
4012 if (HasVirtualBases)
4017 llvm::Constant *Fields[] = {
4018 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4019 TD, // TypeDescriptor
4020 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4021 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4022 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4023 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4024 CopyCtor // CopyCtor
4026 llvm::StructType *CTType = getCatchableTypeType();
4027 auto *GV = new llvm::GlobalVariable(
4028 CGM.getModule(), CTType, /*Constant=*/true, getLinkageForRTTI(T),
4029 llvm::ConstantStruct::get(CTType, Fields), MangledName);
4030 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4031 GV->setSection(".xdata");
4032 if (GV->isWeakForLinker())
4033 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4034 return getImageRelativeConstant(GV);
4037 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4038 assert(!T->isReferenceType());
4040 // See if we've already generated a CatchableTypeArray for this type before.
4041 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4045 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4046 // using a SmallSetVector. Duplicates may arise due to virtual bases
4047 // occurring more than once in the hierarchy.
4048 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4050 // C++14 [except.handle]p3:
4051 // A handler is a match for an exception object of type E if [...]
4052 // - the handler is of type cv T or cv T& and T is an unambiguous public
4053 // base class of E, or
4054 // - the handler is of type cv T or const T& where T is a pointer type and
4055 // E is a pointer type that can be converted to T by [...]
4056 // - a standard pointer conversion (4.10) not involving conversions to
4057 // pointers to private or protected or ambiguous classes
4058 const CXXRecordDecl *MostDerivedClass = nullptr;
4059 bool IsPointer = T->isPointerType();
4061 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4063 MostDerivedClass = T->getAsCXXRecordDecl();
4065 // Collect all the unambiguous public bases of the MostDerivedClass.
4066 if (MostDerivedClass) {
4067 const ASTContext &Context = getContext();
4068 const ASTRecordLayout &MostDerivedLayout =
4069 Context.getASTRecordLayout(MostDerivedClass);
4070 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4071 SmallVector<MSRTTIClass, 8> Classes;
4072 serializeClassHierarchy(Classes, MostDerivedClass);
4073 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4074 detectAmbiguousBases(Classes);
4075 for (const MSRTTIClass &Class : Classes) {
4076 // Skip any ambiguous or private bases.
4078 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4080 // Write down how to convert from a derived pointer to a base pointer.
4081 uint32_t OffsetInVBTable = 0;
4082 int32_t VBPtrOffset = -1;
4083 if (Class.VirtualRoot) {
4085 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4086 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4089 // Turn our record back into a pointer if the exception object is a
4091 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4093 RTTITy = Context.getPointerType(RTTITy);
4094 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4095 VBPtrOffset, OffsetInVBTable));
4099 // C++14 [except.handle]p3:
4100 // A handler is a match for an exception object of type E if
4101 // - The handler is of type cv T or cv T& and E and T are the same type
4102 // (ignoring the top-level cv-qualifiers)
4103 CatchableTypes.insert(getCatchableType(T));
4105 // C++14 [except.handle]p3:
4106 // A handler is a match for an exception object of type E if
4107 // - the handler is of type cv T or const T& where T is a pointer type and
4108 // E is a pointer type that can be converted to T by [...]
4109 // - a standard pointer conversion (4.10) not involving conversions to
4110 // pointers to private or protected or ambiguous classes
4112 // C++14 [conv.ptr]p2:
4113 // A prvalue of type "pointer to cv T," where T is an object type, can be
4114 // converted to a prvalue of type "pointer to cv void".
4115 if (IsPointer && T->getPointeeType()->isObjectType())
4116 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4118 // C++14 [except.handle]p3:
4119 // A handler is a match for an exception object of type E if [...]
4120 // - the handler is of type cv T or const T& where T is a pointer or
4121 // pointer to member type and E is std::nullptr_t.
4123 // We cannot possibly list all possible pointer types here, making this
4124 // implementation incompatible with the standard. However, MSVC includes an
4125 // entry for pointer-to-void in this case. Let's do the same.
4126 if (T->isNullPtrType())
4127 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4129 uint32_t NumEntries = CatchableTypes.size();
4130 llvm::Type *CTType =
4131 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4132 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4133 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4134 llvm::Constant *Fields[] = {
4135 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4136 llvm::ConstantArray::get(
4137 AT, llvm::makeArrayRef(CatchableTypes.begin(),
4138 CatchableTypes.end())) // CatchableTypes
4140 SmallString<256> MangledName;
4142 llvm::raw_svector_ostream Out(MangledName);
4143 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4145 CTA = new llvm::GlobalVariable(
4146 CGM.getModule(), CTAType, /*Constant=*/true, getLinkageForRTTI(T),
4147 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4148 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4149 CTA->setSection(".xdata");
4150 if (CTA->isWeakForLinker())
4151 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4155 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4156 bool IsConst, IsVolatile, IsUnaligned;
4157 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4159 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4160 // the exception object may be caught as.
4161 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4162 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4163 // This is used as a component of the mangled name which means that we need to
4164 // know what it is in order to see if we have previously generated the
4166 uint32_t NumEntries =
4167 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4168 ->getLimitedValue();
4170 SmallString<256> MangledName;
4172 llvm::raw_svector_ostream Out(MangledName);
4173 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4177 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4179 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4182 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4183 // be at least as CV qualified. Encode this requirement into the Flags
4193 // The cleanup-function (a destructor) must be called when the exception
4194 // object's lifetime ends.
4195 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4196 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4197 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4198 if (!DtorD->isTrivial())
4199 CleanupFn = llvm::ConstantExpr::getBitCast(
4200 CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete),
4202 // This is unused as far as we can tell, initialize it to null.
4203 llvm::Constant *ForwardCompat =
4204 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4205 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4206 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4207 llvm::StructType *TIType = getThrowInfoType();
4208 llvm::Constant *Fields[] = {
4209 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4210 getImageRelativeConstant(CleanupFn), // CleanupFn
4211 ForwardCompat, // ForwardCompat
4212 PointerToCatchableTypes // CatchableTypeArray
4214 auto *GV = new llvm::GlobalVariable(
4215 CGM.getModule(), TIType, /*Constant=*/true, getLinkageForRTTI(T),
4216 llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
4217 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4218 GV->setSection(".xdata");
4219 if (GV->isWeakForLinker())
4220 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4224 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4225 const Expr *SubExpr = E->getSubExpr();
4226 QualType ThrowType = SubExpr->getType();
4227 // The exception object lives on the stack and it's address is passed to the
4228 // runtime function.
4229 Address AI = CGF.CreateMemTemp(ThrowType);
4230 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4233 // The so-called ThrowInfo is used to describe how the exception object may be
4235 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4237 // Call into the runtime to throw the exception.
4238 llvm::Value *Args[] = {
4239 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4242 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);