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 // Win64 passes objects with non-trivial copy ctors indirectly.
823 if (RD->hasNonTrivialCopyConstructor())
826 // If an object has a destructor, we'd really like to pass it indirectly
827 // because it allows us to elide copies. Unfortunately, MSVC makes that
828 // impossible for small types, which it will pass in a single register or
829 // stack slot. Most objects with dtors are large-ish, so handle that early.
830 // We can't call out all large objects as being indirect because there are
831 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
832 // how we pass large POD types.
833 if (RD->hasNonTrivialDestructor() &&
834 getContext().getTypeSize(RD->getTypeForDecl()) > 64)
837 // If this is true, the implicit copy constructor that Sema would have
838 // created would not be deleted. FIXME: We should provide a more direct way
839 // for CodeGen to ask whether the constructor was deleted.
840 if (!RD->hasUserDeclaredCopyConstructor() &&
841 !RD->hasUserDeclaredMoveConstructor() &&
842 !RD->needsOverloadResolutionForMoveConstructor() &&
843 !RD->hasUserDeclaredMoveAssignment() &&
844 !RD->needsOverloadResolutionForMoveAssignment())
847 // Otherwise, Sema should have created an implicit copy constructor if
849 assert(!RD->needsImplicitCopyConstructor());
851 // We have to make sure the trivial copy constructor isn't deleted.
852 for (const CXXConstructorDecl *CD : RD->ctors()) {
853 if (CD->isCopyConstructor()) {
854 assert(CD->isTrivial());
855 // We had at least one undeleted trivial copy ctor. Return directly.
856 if (!CD->isDeleted())
861 // The trivial copy constructor was deleted. Return indirectly.
865 llvm_unreachable("invalid enum");
868 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
869 const CXXDeleteExpr *DE,
871 QualType ElementType,
872 const CXXDestructorDecl *Dtor) {
873 // FIXME: Provide a source location here even though there's no
874 // CXXMemberCallExpr for dtor call.
875 bool UseGlobalDelete = DE->isGlobalDelete();
876 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
877 llvm::Value *MDThis =
878 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
880 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
883 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
884 llvm::Value *Args[] = {
885 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
886 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
887 auto *Fn = getThrowFn();
889 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
891 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
895 struct CatchRetScope final : EHScopeStack::Cleanup {
896 llvm::CatchPadInst *CPI;
898 CatchRetScope(llvm::CatchPadInst *CPI) : CPI(CPI) {}
900 void Emit(CodeGenFunction &CGF, Flags flags) override {
901 llvm::BasicBlock *BB = CGF.createBasicBlock("catchret.dest");
902 CGF.Builder.CreateCatchRet(CPI, BB);
908 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
909 const CXXCatchStmt *S) {
910 // In the MS ABI, the runtime handles the copy, and the catch handler is
911 // responsible for destruction.
912 VarDecl *CatchParam = S->getExceptionDecl();
913 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
914 llvm::CatchPadInst *CPI =
915 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
916 CGF.CurrentFuncletPad = CPI;
918 // If this is a catch-all or the catch parameter is unnamed, we don't need to
919 // emit an alloca to the object.
920 if (!CatchParam || !CatchParam->getDeclName()) {
921 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
925 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
926 CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
927 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
928 CGF.EmitAutoVarCleanups(var);
931 /// We need to perform a generic polymorphic operation (like a typeid
932 /// or a cast), which requires an object with a vfptr. Adjust the
933 /// address to point to an object with a vfptr.
934 std::pair<Address, llvm::Value *>
935 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
936 QualType SrcRecordTy) {
937 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
938 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
939 const ASTContext &Context = getContext();
941 // If the class itself has a vfptr, great. This check implicitly
942 // covers non-virtual base subobjects: a class with its own virtual
943 // functions would be a candidate to be a primary base.
944 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
945 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
947 // Okay, one of the vbases must have a vfptr, or else this isn't
948 // actually a polymorphic class.
949 const CXXRecordDecl *PolymorphicBase = nullptr;
950 for (auto &Base : SrcDecl->vbases()) {
951 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
952 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
953 PolymorphicBase = BaseDecl;
957 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
959 llvm::Value *Offset =
960 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
961 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(Value.getPointer(), Offset);
962 CharUnits VBaseAlign =
963 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
964 return std::make_pair(Address(Ptr, VBaseAlign), Offset);
967 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
968 QualType SrcRecordTy) {
969 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
971 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
974 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
975 llvm::Value *Argument) {
976 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
977 llvm::FunctionType *FTy =
978 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
979 llvm::Value *Args[] = {Argument};
980 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
981 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
984 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
985 llvm::CallSite Call =
986 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
987 Call.setDoesNotReturn();
988 CGF.Builder.CreateUnreachable();
991 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
992 QualType SrcRecordTy,
994 llvm::Type *StdTypeInfoPtrTy) {
995 std::tie(ThisPtr, std::ignore) =
996 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
997 auto Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer()).getInstruction();
998 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
1001 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1002 QualType SrcRecordTy) {
1003 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1005 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1008 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
1009 CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
1010 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1011 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1013 llvm::Value *SrcRTTI =
1014 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1015 llvm::Value *DestRTTI =
1016 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1018 llvm::Value *Offset;
1019 std::tie(This, Offset) = performBaseAdjustment(CGF, This, SrcRecordTy);
1020 llvm::Value *ThisPtr = This.getPointer();
1021 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1023 // PVOID __RTDynamicCast(
1027 // PVOID TargetType,
1028 // BOOL isReference)
1029 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1030 CGF.Int8PtrTy, CGF.Int32Ty};
1031 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
1032 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1034 llvm::Value *Args[] = {
1035 ThisPtr, Offset, SrcRTTI, DestRTTI,
1036 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1037 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
1038 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1042 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1043 QualType SrcRecordTy,
1045 std::tie(Value, std::ignore) = performBaseAdjustment(CGF, Value, SrcRecordTy);
1047 // PVOID __RTCastToVoid(
1049 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1050 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
1051 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1053 llvm::Value *Args[] = {Value.getPointer()};
1054 return CGF.EmitRuntimeCall(Function, Args);
1057 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1061 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1062 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1063 const CXXRecordDecl *BaseClassDecl) {
1064 const ASTContext &Context = getContext();
1065 int64_t VBPtrChars =
1066 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1067 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1068 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1069 CharUnits VBTableChars =
1071 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1072 llvm::Value *VBTableOffset =
1073 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1075 llvm::Value *VBPtrToNewBase =
1076 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1078 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1079 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1082 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1083 return isa<CXXConstructorDecl>(GD.getDecl());
1086 static bool isDeletingDtor(GlobalDecl GD) {
1087 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1088 GD.getDtorType() == Dtor_Deleting;
1091 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1092 return isDeletingDtor(GD);
1095 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1096 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1100 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1101 if (FI.isInstanceMethod()) {
1102 // If it's an instance method, aggregates are always returned indirectly via
1103 // the second parameter.
1104 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1105 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1107 } else if (!RD->isPOD()) {
1108 // If it's a free function, non-POD types are returned indirectly.
1109 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1113 // Otherwise, use the C ABI rules.
1118 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1119 const CXXRecordDecl *RD) {
1120 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1121 assert(IsMostDerivedClass &&
1122 "ctor for a class with virtual bases must have an implicit parameter");
1123 llvm::Value *IsCompleteObject =
1124 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1126 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1127 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1128 CGF.Builder.CreateCondBr(IsCompleteObject,
1129 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1131 CGF.EmitBlock(CallVbaseCtorsBB);
1133 // Fill in the vbtable pointers here.
1134 EmitVBPtrStores(CGF, RD);
1136 // CGF will put the base ctor calls in this basic block for us later.
1138 return SkipVbaseCtorsBB;
1142 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1143 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1144 assert(IsMostDerivedClass &&
1145 "ctor for a class with virtual bases must have an implicit parameter");
1146 llvm::Value *IsCompleteObject =
1147 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1149 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1150 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1151 CGF.Builder.CreateCondBr(IsCompleteObject,
1152 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1154 CGF.EmitBlock(CallVbaseDtorsBB);
1155 // CGF will put the base dtor calls in this basic block for us later.
1157 return SkipVbaseDtorsBB;
1160 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1161 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1162 // In most cases, an override for a vbase virtual method can adjust
1163 // the "this" parameter by applying a constant offset.
1164 // However, this is not enough while a constructor or a destructor of some
1165 // class X is being executed if all the following conditions are met:
1166 // - X has virtual bases, (1)
1167 // - X overrides a virtual method M of a vbase Y, (2)
1168 // - X itself is a vbase of the most derived class.
1170 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1171 // which holds the extra amount of "this" adjustment we must do when we use
1172 // the X vftables (i.e. during X ctor or dtor).
1173 // Outside the ctors and dtors, the values of vtorDisps are zero.
1175 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1176 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1177 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1178 CGBuilderTy &Builder = CGF.Builder;
1180 unsigned AS = getThisAddress(CGF).getAddressSpace();
1181 llvm::Value *Int8This = nullptr; // Initialize lazily.
1183 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
1185 if (!I->second.hasVtorDisp())
1188 llvm::Value *VBaseOffset =
1189 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
1190 uint64_t ConstantVBaseOffset =
1191 Layout.getVBaseClassOffset(I->first).getQuantity();
1193 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1194 llvm::Value *VtorDispValue = Builder.CreateSub(
1195 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1197 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1200 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1201 CGF.Int8Ty->getPointerTo(AS));
1202 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
1203 // vtorDisp is always the 32-bits before the vbase in the class layout.
1204 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1205 VtorDispPtr = Builder.CreateBitCast(
1206 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1208 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1209 CharUnits::fromQuantity(4));
1213 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1214 const CXXMethodDecl *MD) {
1215 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1216 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1217 CallingConv ActualCallingConv =
1218 MD->getType()->getAs<FunctionProtoType>()->getCallConv();
1219 return ExpectedCallingConv == ActualCallingConv;
1222 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1223 // There's only one constructor type in this ABI.
1224 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1226 // Exported default constructors either have a simple call-site where they use
1227 // the typical calling convention and have a single 'this' pointer for an
1228 // argument -or- they get a wrapper function which appropriately thunks to the
1229 // real default constructor. This thunk is the default constructor closure.
1230 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor())
1231 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1232 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1233 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1234 Fn->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1238 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1239 const CXXRecordDecl *RD) {
1240 Address This = getThisAddress(CGF);
1241 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1242 const ASTContext &Context = getContext();
1243 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1245 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1246 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1247 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1248 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1249 const ASTRecordLayout &SubobjectLayout =
1250 Context.getASTRecordLayout(VBT->IntroducingObject);
1251 CharUnits Offs = VBT->NonVirtualOffset;
1252 Offs += SubobjectLayout.getVBPtrOffset();
1253 if (VBT->getVBaseWithVPtr())
1254 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1255 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1256 llvm::Value *GVPtr =
1257 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1258 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1259 "vbptr." + VBT->ObjectWithVPtr->getName());
1260 CGF.Builder.CreateStore(GVPtr, VBPtr);
1264 CGCXXABI::AddedStructorArgs
1265 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1266 SmallVectorImpl<CanQualType> &ArgTys) {
1267 AddedStructorArgs Added;
1268 // TODO: 'for base' flag
1269 if (T == StructorType::Deleting) {
1270 // The scalar deleting destructor takes an implicit int parameter.
1271 ArgTys.push_back(getContext().IntTy);
1274 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
1278 // All parameters are already in place except is_most_derived, which goes
1279 // after 'this' if it's variadic and last if it's not.
1281 const CXXRecordDecl *Class = CD->getParent();
1282 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1283 if (Class->getNumVBases()) {
1284 if (FPT->isVariadic()) {
1285 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1288 ArgTys.push_back(getContext().IntTy);
1296 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1297 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1298 // other destructor variants are delegating thunks.
1299 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1303 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1304 GD = GD.getCanonicalDecl();
1305 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1307 GlobalDecl LookupGD = GD;
1308 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1309 // Complete destructors take a pointer to the complete object as a
1310 // parameter, thus don't need this adjustment.
1311 if (GD.getDtorType() == Dtor_Complete)
1314 // There's no Dtor_Base in vftable but it shares the this adjustment with
1315 // the deleting one, so look it up instead.
1316 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1319 MicrosoftVTableContext::MethodVFTableLocation ML =
1320 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1321 CharUnits Adjustment = ML.VFPtrOffset;
1323 // Normal virtual instance methods need to adjust from the vfptr that first
1324 // defined the virtual method to the virtual base subobject, but destructors
1325 // do not. The vector deleting destructor thunk applies this adjustment for
1327 if (isa<CXXDestructorDecl>(MD))
1328 Adjustment = CharUnits::Zero();
1331 const ASTRecordLayout &DerivedLayout =
1332 getContext().getASTRecordLayout(MD->getParent());
1333 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1339 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1340 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1343 // If the call of a virtual function is not virtual, we just have to
1344 // compensate for the adjustment the virtual function does in its prologue.
1345 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1346 if (Adjustment.isZero())
1349 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1350 assert(Adjustment.isPositive());
1351 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1354 GD = GD.getCanonicalDecl();
1355 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1357 GlobalDecl LookupGD = GD;
1358 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1359 // Complete dtors take a pointer to the complete object,
1360 // thus don't need adjustment.
1361 if (GD.getDtorType() == Dtor_Complete)
1364 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1365 // with the base one, so look up the deleting one instead.
1366 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1368 MicrosoftVTableContext::MethodVFTableLocation ML =
1369 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1371 CharUnits StaticOffset = ML.VFPtrOffset;
1373 // Base destructors expect 'this' to point to the beginning of the base
1374 // subobject, not the first vfptr that happens to contain the virtual dtor.
1375 // However, we still need to apply the virtual base adjustment.
1376 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1377 StaticOffset = CharUnits::Zero();
1379 Address Result = This;
1381 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1383 const CXXRecordDecl *Derived = MD->getParent();
1384 const CXXRecordDecl *VBase = ML.VBase;
1385 llvm::Value *VBaseOffset =
1386 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1387 llvm::Value *VBasePtr =
1388 CGF.Builder.CreateInBoundsGEP(Result.getPointer(), VBaseOffset);
1389 CharUnits VBaseAlign =
1390 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1391 Result = Address(VBasePtr, VBaseAlign);
1393 if (!StaticOffset.isZero()) {
1394 assert(StaticOffset.isPositive());
1395 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1397 // Non-virtual adjustment might result in a pointer outside the allocated
1398 // object, e.g. if the final overrider class is laid out after the virtual
1399 // base that declares a method in the most derived class.
1400 // FIXME: Update the code that emits this adjustment in thunks prologues.
1401 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1403 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1409 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1411 FunctionArgList &Params) {
1412 ASTContext &Context = getContext();
1413 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1414 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1415 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1416 auto *IsMostDerived = ImplicitParamDecl::Create(
1417 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1418 &Context.Idents.get("is_most_derived"), Context.IntTy,
1419 ImplicitParamDecl::Other);
1420 // The 'most_derived' parameter goes second if the ctor is variadic and last
1421 // if it's not. Dtors can't be variadic.
1422 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1423 if (FPT->isVariadic())
1424 Params.insert(Params.begin() + 1, IsMostDerived);
1426 Params.push_back(IsMostDerived);
1427 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1428 } else if (isDeletingDtor(CGF.CurGD)) {
1429 auto *ShouldDelete = ImplicitParamDecl::Create(
1430 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1431 &Context.Idents.get("should_call_delete"), Context.IntTy,
1432 ImplicitParamDecl::Other);
1433 Params.push_back(ShouldDelete);
1434 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1438 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1439 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1440 // In this ABI, every virtual function takes a pointer to one of the
1441 // subobjects that first defines it as the 'this' parameter, rather than a
1442 // pointer to the final overrider subobject. Thus, we need to adjust it back
1443 // to the final overrider subobject before use.
1444 // See comments in the MicrosoftVFTableContext implementation for the details.
1445 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1446 if (Adjustment.isZero())
1449 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1450 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1451 *thisTy = This->getType();
1453 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1454 assert(Adjustment.isPositive());
1455 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1456 -Adjustment.getQuantity());
1457 return CGF.Builder.CreateBitCast(This, thisTy);
1460 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1461 // Naked functions have no prolog.
1462 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1467 /// If this is a function that the ABI specifies returns 'this', initialize
1468 /// the return slot to 'this' at the start of the function.
1470 /// Unlike the setting of return types, this is done within the ABI
1471 /// implementation instead of by clients of CGCXXABI because:
1472 /// 1) getThisValue is currently protected
1473 /// 2) in theory, an ABI could implement 'this' returns some other way;
1474 /// HasThisReturn only specifies a contract, not the implementation
1475 if (HasThisReturn(CGF.CurGD))
1476 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1477 else if (hasMostDerivedReturn(CGF.CurGD))
1478 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1481 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1482 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1483 assert(getStructorImplicitParamDecl(CGF) &&
1484 "no implicit parameter for a constructor with virtual bases?");
1485 getStructorImplicitParamValue(CGF)
1486 = CGF.Builder.CreateLoad(
1487 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1491 if (isDeletingDtor(CGF.CurGD)) {
1492 assert(getStructorImplicitParamDecl(CGF) &&
1493 "no implicit parameter for a deleting destructor?");
1494 getStructorImplicitParamValue(CGF)
1495 = CGF.Builder.CreateLoad(
1496 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1497 "should_call_delete");
1501 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::addImplicitConstructorArgs(
1502 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1503 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1504 assert(Type == Ctor_Complete || Type == Ctor_Base);
1506 // Check if we need a 'most_derived' parameter.
1507 if (!D->getParent()->getNumVBases())
1508 return AddedStructorArgs{};
1510 // Add the 'most_derived' argument second if we are variadic or last if not.
1511 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1512 llvm::Value *MostDerivedArg;
1514 MostDerivedArg = getStructorImplicitParamValue(CGF);
1516 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1518 RValue RV = RValue::get(MostDerivedArg);
1519 if (FPT->isVariadic()) {
1520 Args.insert(Args.begin() + 1,
1521 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1522 return AddedStructorArgs::prefix(1);
1524 Args.add(RV, getContext().IntTy);
1525 return AddedStructorArgs::suffix(1);
1528 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1529 const CXXDestructorDecl *DD,
1530 CXXDtorType Type, bool ForVirtualBase,
1531 bool Delegating, Address This) {
1532 CGCallee Callee = CGCallee::forDirect(
1533 CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1536 if (DD->isVirtual()) {
1537 assert(Type != CXXDtorType::Dtor_Deleting &&
1538 "The deleting destructor should only be called via a virtual call");
1539 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1543 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1544 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1545 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1548 CGF.EmitCXXDestructorCall(DD, Callee, This.getPointer(),
1549 /*ImplicitParam=*/nullptr,
1550 /*ImplicitParamTy=*/QualType(), nullptr,
1551 getFromDtorType(Type));
1552 if (BaseDtorEndBB) {
1553 // Complete object handler should continue to be the remaining
1554 CGF.Builder.CreateBr(BaseDtorEndBB);
1555 CGF.EmitBlock(BaseDtorEndBB);
1559 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1560 const CXXRecordDecl *RD,
1561 llvm::GlobalVariable *VTable) {
1562 if (!CGM.getCodeGenOpts().LTOUnit)
1565 // The location of the first virtual function pointer in the virtual table,
1566 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1567 // disabled, or sizeof(void*) if RTTI is enabled.
1568 CharUnits AddressPoint =
1569 getContext().getLangOpts().RTTIData
1570 ? getContext().toCharUnitsFromBits(
1571 getContext().getTargetInfo().getPointerWidth(0))
1572 : CharUnits::Zero();
1574 if (Info.PathToIntroducingObject.empty()) {
1575 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1579 // Add a bitset entry for the least derived base belonging to this vftable.
1580 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1581 Info.PathToIntroducingObject.back());
1583 // Add a bitset entry for each derived class that is laid out at the same
1584 // offset as the least derived base.
1585 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1586 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1587 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1589 const ASTRecordLayout &Layout =
1590 getContext().getASTRecordLayout(DerivedRD);
1592 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1593 if (VBI == Layout.getVBaseOffsetsMap().end())
1594 Offset = Layout.getBaseClassOffset(BaseRD);
1596 Offset = VBI->second.VBaseOffset;
1597 if (!Offset.isZero())
1599 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1602 // Finally do the same for the most derived class.
1603 if (Info.FullOffsetInMDC.isZero())
1604 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1607 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1608 const CXXRecordDecl *RD) {
1609 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1610 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1612 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1613 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1614 if (VTable->hasInitializer())
1617 const VTableLayout &VTLayout =
1618 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1620 llvm::Constant *RTTI = nullptr;
1621 if (any_of(VTLayout.vtable_components(),
1622 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1623 RTTI = getMSCompleteObjectLocator(RD, *Info);
1625 ConstantInitBuilder Builder(CGM);
1626 auto Components = Builder.beginStruct();
1627 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1628 Components.finishAndSetAsInitializer(VTable);
1630 emitVTableTypeMetadata(*Info, RD, VTable);
1634 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1635 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1636 return Vptr.NearestVBase != nullptr;
1639 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1640 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1641 const CXXRecordDecl *NearestVBase) {
1642 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1643 if (!VTableAddressPoint) {
1644 assert(Base.getBase()->getNumVBases() &&
1645 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1647 return VTableAddressPoint;
1650 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1651 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1652 SmallString<256> &Name) {
1653 llvm::raw_svector_ostream Out(Name);
1654 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1658 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1659 const CXXRecordDecl *VTableClass) {
1660 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1661 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1662 return VFTablesMap[ID];
1665 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1666 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1667 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1668 assert(VFTable && "Couldn't find a vftable for the given base?");
1672 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1673 CharUnits VPtrOffset) {
1674 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1675 // shouldn't be used in the given record type. We want to cache this result in
1676 // VFTablesMap, thus a simple zero check is not sufficient.
1678 VFTableIdTy ID(RD, VPtrOffset);
1679 VTablesMapTy::iterator I;
1681 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1685 llvm::GlobalVariable *&VTable = I->second;
1687 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1688 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1690 if (DeferredVFTables.insert(RD).second) {
1691 // We haven't processed this record type before.
1692 // Queue up this vtable for possible deferred emission.
1693 CGM.addDeferredVTable(RD);
1696 // Create all the vftables at once in order to make sure each vftable has
1697 // a unique mangled name.
1698 llvm::StringSet<> ObservedMangledNames;
1699 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1700 SmallString<256> Name;
1701 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1702 if (!ObservedMangledNames.insert(Name.str()).second)
1703 llvm_unreachable("Already saw this mangling before?");
1708 const std::unique_ptr<VPtrInfo> *VFPtrI = std::find_if(
1709 VFPtrs.begin(), VFPtrs.end(), [&](const std::unique_ptr<VPtrInfo>& VPI) {
1710 return VPI->FullOffsetInMDC == VPtrOffset;
1712 if (VFPtrI == VFPtrs.end()) {
1713 VFTablesMap[ID] = nullptr;
1716 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1718 SmallString<256> VFTableName;
1719 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1721 // Classes marked __declspec(dllimport) need vftables generated on the
1722 // import-side in order to support features like constexpr. No other
1723 // translation unit relies on the emission of the local vftable, translation
1724 // units are expected to generate them as needed.
1726 // Because of this unique behavior, we maintain this logic here instead of
1727 // getVTableLinkage.
1728 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1729 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1730 : CGM.getVTableLinkage(RD);
1731 bool VFTableComesFromAnotherTU =
1732 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1733 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1734 bool VTableAliasIsRequred =
1735 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1737 if (llvm::GlobalValue *VFTable =
1738 CGM.getModule().getNamedGlobal(VFTableName)) {
1739 VFTablesMap[ID] = VFTable;
1740 VTable = VTableAliasIsRequred
1741 ? cast<llvm::GlobalVariable>(
1742 cast<llvm::GlobalAlias>(VFTable)->getBaseObject())
1743 : cast<llvm::GlobalVariable>(VFTable);
1747 const VTableLayout &VTLayout =
1748 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1749 llvm::GlobalValue::LinkageTypes VTableLinkage =
1750 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1752 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1754 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1756 // Create a backing variable for the contents of VTable. The VTable may
1757 // or may not include space for a pointer to RTTI data.
1758 llvm::GlobalValue *VFTable;
1759 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1760 /*isConstant=*/true, VTableLinkage,
1761 /*Initializer=*/nullptr, VTableName);
1762 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1764 llvm::Comdat *C = nullptr;
1765 if (!VFTableComesFromAnotherTU &&
1766 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1767 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1768 VTableAliasIsRequred)))
1769 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1771 // Only insert a pointer into the VFTable for RTTI data if we are not
1772 // importing it. We never reference the RTTI data directly so there is no
1773 // need to make room for it.
1774 if (VTableAliasIsRequred) {
1775 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1776 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1777 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1778 // Create a GEP which points just after the first entry in the VFTable,
1779 // this should be the location of the first virtual method.
1780 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1781 VTable->getValueType(), VTable, GEPIndices);
1782 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1783 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1785 C->setSelectionKind(llvm::Comdat::Largest);
1787 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1788 /*AddressSpace=*/0, VFTableLinkage,
1789 VFTableName.str(), VTableGEP,
1791 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1793 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1794 // be referencing any RTTI data.
1795 // The GlobalVariable will end up being an appropriate definition of the
1800 VTable->setComdat(C);
1802 if (RD->hasAttr<DLLExportAttr>())
1803 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1805 VFTablesMap[ID] = VFTable;
1809 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1813 SourceLocation Loc) {
1814 GD = GD.getCanonicalDecl();
1815 CGBuilderTy &Builder = CGF.Builder;
1817 Ty = Ty->getPointerTo()->getPointerTo();
1819 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1821 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1822 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty, MethodDecl->getParent());
1824 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1825 MicrosoftVTableContext::MethodVFTableLocation ML =
1826 VFTContext.getMethodVFTableLocation(GD);
1828 // Compute the identity of the most derived class whose virtual table is
1829 // located at the MethodVFTableLocation ML.
1830 auto getObjectWithVPtr = [&] {
1831 return llvm::find_if(VFTContext.getVFPtrOffsets(
1832 ML.VBase ? ML.VBase : MethodDecl->getParent()),
1833 [&](const std::unique_ptr<VPtrInfo> &Info) {
1834 return Info->FullOffsetInMDC == ML.VFPtrOffset;
1841 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1842 VFunc = CGF.EmitVTableTypeCheckedLoad(
1843 getObjectWithVPtr(), VTable,
1844 ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1846 if (CGM.getCodeGenOpts().PrepareForLTO)
1847 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1849 llvm::Value *VFuncPtr =
1850 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1851 VFunc = Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1854 CGCallee Callee(MethodDecl, VFunc);
1858 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1859 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1860 Address This, const CXXMemberCallExpr *CE) {
1861 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1862 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1864 // We have only one destructor in the vftable but can get both behaviors
1865 // by passing an implicit int parameter.
1866 GlobalDecl GD(Dtor, Dtor_Deleting);
1867 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1868 Dtor, StructorType::Deleting);
1869 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1870 CGCallee Callee = getVirtualFunctionPointer(
1871 CGF, GD, This, Ty, CE ? CE->getLocStart() : SourceLocation());
1873 ASTContext &Context = getContext();
1874 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1875 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1876 DtorType == Dtor_Deleting);
1878 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1880 CGF.EmitCXXDestructorCall(Dtor, Callee, This.getPointer(), ImplicitParam,
1881 Context.IntTy, CE, StructorType::Deleting);
1882 return RV.getScalarVal();
1885 const VBTableGlobals &
1886 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1887 // At this layer, we can key the cache off of a single class, which is much
1888 // easier than caching each vbtable individually.
1889 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1891 std::tie(Entry, Added) =
1892 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1893 VBTableGlobals &VBGlobals = Entry->second;
1897 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1898 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1900 // Cache the globals for all vbtables so we don't have to recompute the
1902 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1903 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1904 E = VBGlobals.VBTables->end();
1906 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1912 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1913 const CXXMethodDecl *MD,
1914 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1915 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1916 "can't form pointers to ctors or virtual dtors");
1918 // Calculate the mangled name.
1919 SmallString<256> ThunkName;
1920 llvm::raw_svector_ostream Out(ThunkName);
1921 getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1923 // If the thunk has been generated previously, just return it.
1924 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1925 return cast<llvm::Function>(GV);
1927 // Create the llvm::Function.
1928 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD);
1929 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1930 llvm::Function *ThunkFn =
1931 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1932 ThunkName.str(), &CGM.getModule());
1933 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1935 ThunkFn->setLinkage(MD->isExternallyVisible()
1936 ? llvm::GlobalValue::LinkOnceODRLinkage
1937 : llvm::GlobalValue::InternalLinkage);
1938 if (MD->isExternallyVisible())
1939 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
1941 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1942 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1944 // Add the "thunk" attribute so that LLVM knows that the return type is
1945 // meaningless. These thunks can be used to call functions with differing
1946 // return types, and the caller is required to cast the prototype
1947 // appropriately to extract the correct value.
1948 ThunkFn->addFnAttr("thunk");
1950 // These thunks can be compared, so they are not unnamed.
1951 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
1954 CodeGenFunction CGF(CGM);
1955 CGF.CurGD = GlobalDecl(MD);
1956 CGF.CurFuncIsThunk = true;
1958 // Build FunctionArgs, but only include the implicit 'this' parameter
1960 FunctionArgList FunctionArgs;
1961 buildThisParam(CGF, FunctionArgs);
1963 // Start defining the function.
1964 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
1965 FunctionArgs, MD->getLocation(), SourceLocation());
1968 // Load the vfptr and then callee from the vftable. The callee should have
1969 // adjusted 'this' so that the vfptr is at offset zero.
1970 llvm::Value *VTable = CGF.GetVTablePtr(
1971 getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent());
1973 llvm::Value *VFuncPtr =
1974 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1975 llvm::Value *Callee =
1976 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1978 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee);
1983 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1984 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1985 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1986 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
1987 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1988 if (GV->isDeclaration())
1989 emitVBTableDefinition(*VBT, RD, GV);
1993 llvm::GlobalVariable *
1994 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1995 llvm::GlobalVariable::LinkageTypes Linkage) {
1996 SmallString<256> OutName;
1997 llvm::raw_svector_ostream Out(OutName);
1998 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1999 StringRef Name = OutName.str();
2001 llvm::ArrayType *VBTableType =
2002 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2004 assert(!CGM.getModule().getNamedGlobal(Name) &&
2005 "vbtable with this name already exists: mangling bug?");
2006 llvm::GlobalVariable *GV =
2007 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
2008 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2010 if (RD->hasAttr<DLLImportAttr>())
2011 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2012 else if (RD->hasAttr<DLLExportAttr>())
2013 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2015 if (!GV->hasExternalLinkage())
2016 emitVBTableDefinition(VBT, RD, GV);
2021 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2022 const CXXRecordDecl *RD,
2023 llvm::GlobalVariable *GV) const {
2024 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2026 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2027 "should only emit vbtables for classes with vbtables");
2029 const ASTRecordLayout &BaseLayout =
2030 getContext().getASTRecordLayout(VBT.IntroducingObject);
2031 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2033 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2036 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2037 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2038 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2040 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2041 for (const auto &I : ObjectWithVPtr->vbases()) {
2042 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2043 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2044 assert(!Offset.isNegative());
2046 // Make it relative to the subobject vbptr.
2047 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2048 if (VBT.getVBaseWithVPtr())
2049 CompleteVBPtrOffset +=
2050 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2051 Offset -= CompleteVBPtrOffset;
2053 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2054 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2055 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2058 assert(Offsets.size() ==
2059 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
2060 ->getElementType())->getNumElements());
2061 llvm::ArrayType *VBTableType =
2062 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2063 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2064 GV->setInitializer(Init);
2066 if (RD->hasAttr<DLLImportAttr>())
2067 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2070 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2072 const ThisAdjustment &TA) {
2074 return This.getPointer();
2076 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2079 if (TA.Virtual.isEmpty()) {
2080 V = This.getPointer();
2082 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2083 // Adjust the this argument based on the vtordisp value.
2084 Address VtorDispPtr =
2085 CGF.Builder.CreateConstInBoundsByteGEP(This,
2086 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2087 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2088 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2089 V = CGF.Builder.CreateGEP(This.getPointer(),
2090 CGF.Builder.CreateNeg(VtorDisp));
2092 // Unfortunately, having applied the vtordisp means that we no
2093 // longer really have a known alignment for the vbptr step.
2094 // We'll assume the vbptr is pointer-aligned.
2096 if (TA.Virtual.Microsoft.VBPtrOffset) {
2097 // If the final overrider is defined in a virtual base other than the one
2098 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2099 // the vbtable of the derived class.
2100 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2101 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2103 llvm::Value *VBaseOffset =
2104 GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
2105 -TA.Virtual.Microsoft.VBPtrOffset,
2106 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2107 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2111 if (TA.NonVirtual) {
2112 // Non-virtual adjustment might result in a pointer outside the allocated
2113 // object, e.g. if the final overrider class is laid out after the virtual
2114 // base that declares a method in the most derived class.
2115 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
2118 // Don't need to bitcast back, the call CodeGen will handle this.
2123 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2124 const ReturnAdjustment &RA) {
2126 return Ret.getPointer();
2128 auto OrigTy = Ret.getType();
2129 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2131 llvm::Value *V = Ret.getPointer();
2132 if (RA.Virtual.Microsoft.VBIndex) {
2133 assert(RA.Virtual.Microsoft.VBIndex > 0);
2134 int32_t IntSize = CGF.getIntSize().getQuantity();
2136 llvm::Value *VBaseOffset =
2137 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2138 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2139 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2143 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2145 // Cast back to the original type.
2146 return CGF.Builder.CreateBitCast(V, OrigTy);
2149 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2150 QualType elementType) {
2151 // Microsoft seems to completely ignore the possibility of a
2152 // two-argument usual deallocation function.
2153 return elementType.isDestructedType();
2156 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2157 // Microsoft seems to completely ignore the possibility of a
2158 // two-argument usual deallocation function.
2159 return expr->getAllocatedType().isDestructedType();
2162 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2163 // The array cookie is always a size_t; we then pad that out to the
2164 // alignment of the element type.
2165 ASTContext &Ctx = getContext();
2166 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2167 Ctx.getTypeAlignInChars(type));
2170 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2172 CharUnits cookieSize) {
2173 Address numElementsPtr =
2174 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2175 return CGF.Builder.CreateLoad(numElementsPtr);
2178 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2180 llvm::Value *numElements,
2181 const CXXNewExpr *expr,
2182 QualType elementType) {
2183 assert(requiresArrayCookie(expr));
2185 // The size of the cookie.
2186 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2188 // Compute an offset to the cookie.
2189 Address cookiePtr = newPtr;
2191 // Write the number of elements into the appropriate slot.
2192 Address numElementsPtr
2193 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2194 CGF.Builder.CreateStore(numElements, numElementsPtr);
2196 // Finally, compute a pointer to the actual data buffer by skipping
2197 // over the cookie completely.
2198 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2201 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2202 llvm::Constant *Dtor,
2203 llvm::Constant *Addr) {
2204 // Create a function which calls the destructor.
2205 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2207 // extern "C" int __tlregdtor(void (*f)(void));
2208 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2209 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
2211 llvm::Constant *TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2212 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2213 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor))
2214 TLRegDtorFn->setDoesNotThrow();
2216 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2219 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2220 llvm::Constant *Dtor,
2221 llvm::Constant *Addr) {
2223 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2225 // The default behavior is to use atexit.
2226 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2229 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2230 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2231 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2232 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2233 if (CXXThreadLocalInits.empty())
2236 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2238 ? "/include:___dyn_tls_init@12"
2239 : "/include:__dyn_tls_init");
2241 // This will create a GV in the .CRT$XDU section. It will point to our
2242 // initialization function. The CRT will call all of these function
2243 // pointers at start-up time and, eventually, at thread-creation time.
2244 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2245 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2246 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
2247 llvm::GlobalVariable::InternalLinkage, InitFunc,
2248 Twine(InitFunc->getName(), "$initializer$"));
2249 InitFuncPtr->setSection(".CRT$XDU");
2250 // This variable has discardable linkage, we have to add it to @llvm.used to
2251 // ensure it won't get discarded.
2252 CGM.addUsedGlobal(InitFuncPtr);
2256 std::vector<llvm::Function *> NonComdatInits;
2257 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2258 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2259 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2260 llvm::Function *F = CXXThreadLocalInits[I];
2262 // If the GV is already in a comdat group, then we have to join it.
2263 if (llvm::Comdat *C = GV->getComdat())
2264 AddToXDU(F)->setComdat(C);
2266 NonComdatInits.push_back(F);
2269 if (!NonComdatInits.empty()) {
2270 llvm::FunctionType *FTy =
2271 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2272 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
2273 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2274 SourceLocation(), /*TLS=*/true);
2275 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2281 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2283 QualType LValType) {
2284 CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
2288 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2289 StringRef VarName("_Init_thread_epoch");
2290 CharUnits Align = CGM.getIntAlign();
2291 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2292 return ConstantAddress(GV, Align);
2293 auto *GV = new llvm::GlobalVariable(
2294 CGM.getModule(), CGM.IntTy,
2295 /*Constant=*/false, llvm::GlobalVariable::ExternalLinkage,
2296 /*Initializer=*/nullptr, VarName,
2297 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2298 GV->setAlignment(Align.getQuantity());
2299 return ConstantAddress(GV, Align);
2302 static llvm::Constant *getInitThreadHeaderFn(CodeGenModule &CGM) {
2303 llvm::FunctionType *FTy =
2304 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2305 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2306 return CGM.CreateRuntimeFunction(
2307 FTy, "_Init_thread_header",
2308 llvm::AttributeList::get(CGM.getLLVMContext(),
2309 llvm::AttributeList::FunctionIndex,
2310 llvm::Attribute::NoUnwind),
2314 static llvm::Constant *getInitThreadFooterFn(CodeGenModule &CGM) {
2315 llvm::FunctionType *FTy =
2316 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2317 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2318 return CGM.CreateRuntimeFunction(
2319 FTy, "_Init_thread_footer",
2320 llvm::AttributeList::get(CGM.getLLVMContext(),
2321 llvm::AttributeList::FunctionIndex,
2322 llvm::Attribute::NoUnwind),
2326 static llvm::Constant *getInitThreadAbortFn(CodeGenModule &CGM) {
2327 llvm::FunctionType *FTy =
2328 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2329 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2330 return CGM.CreateRuntimeFunction(
2331 FTy, "_Init_thread_abort",
2332 llvm::AttributeList::get(CGM.getLLVMContext(),
2333 llvm::AttributeList::FunctionIndex,
2334 llvm::Attribute::NoUnwind),
2339 struct ResetGuardBit final : EHScopeStack::Cleanup {
2342 ResetGuardBit(Address Guard, unsigned GuardNum)
2343 : Guard(Guard), GuardNum(GuardNum) {}
2345 void Emit(CodeGenFunction &CGF, Flags flags) override {
2346 // Reset the bit in the mask so that the static variable may be
2348 CGBuilderTy &Builder = CGF.Builder;
2349 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2350 llvm::ConstantInt *Mask =
2351 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2352 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2356 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2358 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2360 void Emit(CodeGenFunction &CGF, Flags flags) override {
2361 // Calling _Init_thread_abort will reset the guard's state.
2362 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2367 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2368 llvm::GlobalVariable *GV,
2370 // MSVC only uses guards for static locals.
2371 if (!D.isStaticLocal()) {
2372 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2373 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2374 llvm::Function *F = CGF.CurFn;
2375 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2376 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2377 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2381 bool ThreadlocalStatic = D.getTLSKind();
2382 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2384 // Thread-safe static variables which aren't thread-specific have a
2385 // per-variable guard.
2386 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2388 CGBuilderTy &Builder = CGF.Builder;
2389 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2390 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2391 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2393 // Get the guard variable for this function if we have one already.
2394 GuardInfo *GI = nullptr;
2395 if (ThreadlocalStatic)
2396 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2397 else if (!ThreadsafeStatic)
2398 GI = &GuardVariableMap[D.getDeclContext()];
2400 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2402 if (D.isExternallyVisible()) {
2403 // Externally visible variables have to be numbered in Sema to properly
2404 // handle unreachable VarDecls.
2405 GuardNum = getContext().getStaticLocalNumber(&D);
2406 assert(GuardNum > 0);
2408 } else if (HasPerVariableGuard) {
2409 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2411 // Non-externally visible variables are numbered here in CodeGen.
2412 GuardNum = GI->BitIndex++;
2415 if (!HasPerVariableGuard && GuardNum >= 32) {
2416 if (D.isExternallyVisible())
2417 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2423 // Mangle the name for the guard.
2424 SmallString<256> GuardName;
2426 llvm::raw_svector_ostream Out(GuardName);
2427 if (HasPerVariableGuard)
2428 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2431 getMangleContext().mangleStaticGuardVariable(&D, Out);
2434 // Create the guard variable with a zero-initializer. Just absorb linkage,
2435 // visibility and dll storage class from the guarded variable.
2437 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2438 GV->getLinkage(), Zero, GuardName.str());
2439 GuardVar->setVisibility(GV->getVisibility());
2440 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2441 GuardVar->setAlignment(GuardAlign.getQuantity());
2442 if (GuardVar->isWeakForLinker())
2443 GuardVar->setComdat(
2444 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2446 GuardVar->setThreadLocal(true);
2447 if (GI && !HasPerVariableGuard)
2448 GI->Guard = GuardVar;
2451 ConstantAddress GuardAddr(GuardVar, GuardAlign);
2453 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2454 "static local from the same function had different linkage");
2456 if (!HasPerVariableGuard) {
2457 // Pseudo code for the test:
2458 // if (!(GuardVar & MyGuardBit)) {
2459 // GuardVar |= MyGuardBit;
2460 // ... initialize the object ...;
2463 // Test our bit from the guard variable.
2464 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2465 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2466 llvm::Value *IsInitialized =
2467 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
2468 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2469 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2470 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
2472 // Set our bit in the guard variable and emit the initializer and add a global
2473 // destructor if appropriate.
2474 CGF.EmitBlock(InitBlock);
2475 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2476 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2477 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2478 CGF.PopCleanupBlock();
2479 Builder.CreateBr(EndBlock);
2482 CGF.EmitBlock(EndBlock);
2484 // Pseudo code for the test:
2485 // if (TSS > _Init_thread_epoch) {
2486 // _Init_thread_header(&TSS);
2488 // ... initialize the object ...;
2489 // _Init_thread_footer(&TSS);
2493 // The algorithm is almost identical to what can be found in the appendix
2496 // This BasicBLock determines whether or not we have any work to do.
2497 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2498 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2499 llvm::LoadInst *InitThreadEpoch =
2500 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2501 llvm::Value *IsUninitialized =
2502 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2503 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2504 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2505 Builder.CreateCondBr(IsUninitialized, AttemptInitBlock, EndBlock);
2507 // This BasicBlock attempts to determine whether or not this thread is
2508 // responsible for doing the initialization.
2509 CGF.EmitBlock(AttemptInitBlock);
2510 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2511 GuardAddr.getPointer());
2512 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2513 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2514 llvm::Value *ShouldDoInit =
2515 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2516 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2517 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2519 // Ok, we ended up getting selected as the initializing thread.
2520 CGF.EmitBlock(InitBlock);
2521 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2522 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2523 CGF.PopCleanupBlock();
2524 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2525 GuardAddr.getPointer());
2526 Builder.CreateBr(EndBlock);
2528 CGF.EmitBlock(EndBlock);
2532 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2533 // Null-ness for function memptrs only depends on the first field, which is
2534 // the function pointer. The rest don't matter, so we can zero initialize.
2535 if (MPT->isMemberFunctionPointer())
2538 // The virtual base adjustment field is always -1 for null, so if we have one
2539 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2540 // valid field offset.
2541 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2542 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2543 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
2544 RD->nullFieldOffsetIsZero());
2548 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2549 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2550 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2551 llvm::SmallVector<llvm::Type *, 4> fields;
2552 if (MPT->isMemberFunctionPointer())
2553 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2555 fields.push_back(CGM.IntTy); // FieldOffset
2557 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2559 fields.push_back(CGM.IntTy);
2560 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2561 fields.push_back(CGM.IntTy);
2562 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2563 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2565 if (fields.size() == 1)
2567 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2570 void MicrosoftCXXABI::
2571 GetNullMemberPointerFields(const MemberPointerType *MPT,
2572 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2573 assert(fields.empty());
2574 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2575 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2576 if (MPT->isMemberFunctionPointer()) {
2577 // FunctionPointerOrVirtualThunk
2578 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2580 if (RD->nullFieldOffsetIsZero())
2581 fields.push_back(getZeroInt()); // FieldOffset
2583 fields.push_back(getAllOnesInt()); // FieldOffset
2586 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2588 fields.push_back(getZeroInt());
2589 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2590 fields.push_back(getZeroInt());
2591 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2592 fields.push_back(getAllOnesInt());
2596 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2597 llvm::SmallVector<llvm::Constant *, 4> fields;
2598 GetNullMemberPointerFields(MPT, fields);
2599 if (fields.size() == 1)
2601 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2602 assert(Res->getType() == ConvertMemberPointerType(MPT));
2607 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2608 bool IsMemberFunction,
2609 const CXXRecordDecl *RD,
2610 CharUnits NonVirtualBaseAdjustment,
2611 unsigned VBTableIndex) {
2612 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2614 // Single inheritance class member pointer are represented as scalars instead
2616 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2619 llvm::SmallVector<llvm::Constant *, 4> fields;
2620 fields.push_back(FirstField);
2622 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2623 fields.push_back(llvm::ConstantInt::get(
2624 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2626 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2627 CharUnits Offs = CharUnits::Zero();
2629 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2630 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2633 // The rest of the fields are adjusted by conversions to a more derived class.
2634 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2635 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2637 return llvm::ConstantStruct::getAnon(fields);
2641 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2643 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2644 if (RD->getMSInheritanceModel() ==
2645 MSInheritanceAttr::Keyword_virtual_inheritance)
2646 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2647 llvm::Constant *FirstField =
2648 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2649 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2650 CharUnits::Zero(), /*VBTableIndex=*/0);
2653 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2655 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2656 const ValueDecl *MPD = MP.getMemberPointerDecl();
2658 return EmitNullMemberPointer(DstTy);
2660 ASTContext &Ctx = getContext();
2661 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2665 C = EmitMemberFunctionPointer(MD);
2667 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2668 C = EmitMemberDataPointer(DstTy, FieldOffset);
2671 if (!MemberPointerPath.empty()) {
2672 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2673 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2674 const MemberPointerType *SrcTy =
2675 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2676 ->castAs<MemberPointerType>();
2678 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2679 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2680 const CXXRecordDecl *PrevRD = SrcRD;
2681 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2682 const CXXRecordDecl *Base = nullptr;
2683 const CXXRecordDecl *Derived = nullptr;
2684 if (DerivedMember) {
2691 for (const CXXBaseSpecifier &BS : Derived->bases())
2692 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2693 Base->getCanonicalDecl())
2694 DerivedToBasePath.push_back(&BS);
2697 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2699 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2700 : CK_BaseToDerivedMemberPointer;
2701 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2702 DerivedToBasePath.end(), C);
2708 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2709 assert(MD->isInstance() && "Member function must not be static!");
2711 MD = MD->getCanonicalDecl();
2712 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2713 const CXXRecordDecl *RD = MD->getParent()->getMostRecentDecl();
2714 CodeGenTypes &Types = CGM.getTypes();
2716 unsigned VBTableIndex = 0;
2717 llvm::Constant *FirstField;
2718 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2719 if (!MD->isVirtual()) {
2721 // Check whether the function has a computable LLVM signature.
2722 if (Types.isFuncTypeConvertible(FPT)) {
2723 // The function has a computable LLVM signature; use the correct type.
2724 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2726 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2727 // function type is incomplete.
2730 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2732 auto &VTableContext = CGM.getMicrosoftVTableContext();
2733 MicrosoftVTableContext::MethodVFTableLocation ML =
2734 VTableContext.getMethodVFTableLocation(MD);
2735 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2736 // Include the vfptr adjustment if the method is in a non-primary vftable.
2737 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2739 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2742 if (VBTableIndex == 0 &&
2743 RD->getMSInheritanceModel() ==
2744 MSInheritanceAttr::Keyword_virtual_inheritance)
2745 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2747 // The rest of the fields are common with data member pointers.
2748 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2749 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2750 NonVirtualBaseAdjustment, VBTableIndex);
2753 /// Member pointers are the same if they're either bitwise identical *or* both
2754 /// null. Null-ness for function members is determined by the first field,
2755 /// while for data member pointers we must compare all fields.
2757 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2760 const MemberPointerType *MPT,
2762 CGBuilderTy &Builder = CGF.Builder;
2764 // Handle != comparisons by switching the sense of all boolean operations.
2765 llvm::ICmpInst::Predicate Eq;
2766 llvm::Instruction::BinaryOps And, Or;
2768 Eq = llvm::ICmpInst::ICMP_NE;
2769 And = llvm::Instruction::Or;
2770 Or = llvm::Instruction::And;
2772 Eq = llvm::ICmpInst::ICMP_EQ;
2773 And = llvm::Instruction::And;
2774 Or = llvm::Instruction::Or;
2777 // If this is a single field member pointer (single inheritance), this is a
2779 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2780 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2781 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2783 return Builder.CreateICmp(Eq, L, R);
2785 // Compare the first field.
2786 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2787 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2788 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2790 // Compare everything other than the first field.
2791 llvm::Value *Res = nullptr;
2792 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2793 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2794 llvm::Value *LF = Builder.CreateExtractValue(L, I);
2795 llvm::Value *RF = Builder.CreateExtractValue(R, I);
2796 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2798 Res = Builder.CreateBinOp(And, Res, Cmp);
2803 // Check if the first field is 0 if this is a function pointer.
2804 if (MPT->isMemberFunctionPointer()) {
2805 // (l1 == r1 && ...) || l0 == 0
2806 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2807 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2808 Res = Builder.CreateBinOp(Or, Res, IsZero);
2811 // Combine the comparison of the first field, which must always be true for
2812 // this comparison to succeeed.
2813 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2817 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2818 llvm::Value *MemPtr,
2819 const MemberPointerType *MPT) {
2820 CGBuilderTy &Builder = CGF.Builder;
2821 llvm::SmallVector<llvm::Constant *, 4> fields;
2822 // We only need one field for member functions.
2823 if (MPT->isMemberFunctionPointer())
2824 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2826 GetNullMemberPointerFields(MPT, fields);
2827 assert(!fields.empty());
2828 llvm::Value *FirstField = MemPtr;
2829 if (MemPtr->getType()->isStructTy())
2830 FirstField = Builder.CreateExtractValue(MemPtr, 0);
2831 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2833 // For function member pointers, we only need to test the function pointer
2834 // field. The other fields if any can be garbage.
2835 if (MPT->isMemberFunctionPointer())
2838 // Otherwise, emit a series of compares and combine the results.
2839 for (int I = 1, E = fields.size(); I < E; ++I) {
2840 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2841 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2842 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2847 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2848 llvm::Constant *Val) {
2849 // Function pointers are null if the pointer in the first field is null.
2850 if (MPT->isMemberFunctionPointer()) {
2851 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2852 Val->getAggregateElement(0U) : Val;
2853 return FirstField->isNullValue();
2856 // If it's not a function pointer and it's zero initializable, we can easily
2858 if (isZeroInitializable(MPT) && Val->isNullValue())
2861 // Otherwise, break down all the fields for comparison. Hopefully these
2862 // little Constants are reused, while a big null struct might not be.
2863 llvm::SmallVector<llvm::Constant *, 4> Fields;
2864 GetNullMemberPointerFields(MPT, Fields);
2865 if (Fields.size() == 1) {
2866 assert(Val->getType()->isIntegerTy());
2867 return Val == Fields[0];
2871 for (I = 0, E = Fields.size(); I != E; ++I) {
2872 if (Val->getAggregateElement(I) != Fields[I])
2879 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2881 llvm::Value *VBPtrOffset,
2882 llvm::Value *VBTableOffset,
2883 llvm::Value **VBPtrOut) {
2884 CGBuilderTy &Builder = CGF.Builder;
2885 // Load the vbtable pointer from the vbptr in the instance.
2886 This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
2887 llvm::Value *VBPtr =
2888 Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr");
2889 if (VBPtrOut) *VBPtrOut = VBPtr;
2890 VBPtr = Builder.CreateBitCast(VBPtr,
2891 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
2893 CharUnits VBPtrAlign;
2894 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
2895 VBPtrAlign = This.getAlignment().alignmentAtOffset(
2896 CharUnits::fromQuantity(CI->getSExtValue()));
2898 VBPtrAlign = CGF.getPointerAlign();
2901 llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable");
2903 // Translate from byte offset to table index. It improves analyzability.
2904 llvm::Value *VBTableIndex = Builder.CreateAShr(
2905 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2906 "vbtindex", /*isExact=*/true);
2908 // Load an i32 offset from the vb-table.
2909 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2910 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2911 return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4),
2915 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2917 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2918 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2919 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2920 CGBuilderTy &Builder = CGF.Builder;
2921 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
2922 llvm::BasicBlock *OriginalBB = nullptr;
2923 llvm::BasicBlock *SkipAdjustBB = nullptr;
2924 llvm::BasicBlock *VBaseAdjustBB = nullptr;
2926 // In the unspecified inheritance model, there might not be a vbtable at all,
2927 // in which case we need to skip the virtual base lookup. If there is a
2928 // vbtable, the first entry is a no-op entry that gives back the original
2929 // base, so look for a virtual base adjustment offset of zero.
2931 OriginalBB = Builder.GetInsertBlock();
2932 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2933 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2934 llvm::Value *IsVirtual =
2935 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2937 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2938 CGF.EmitBlock(VBaseAdjustBB);
2941 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2942 // know the vbptr offset.
2944 CharUnits offs = CharUnits::Zero();
2945 if (!RD->hasDefinition()) {
2946 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2947 unsigned DiagID = Diags.getCustomDiagID(
2948 DiagnosticsEngine::Error,
2949 "member pointer representation requires a "
2950 "complete class type for %0 to perform this expression");
2951 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2952 } else if (RD->getNumVBases())
2953 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2954 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2956 llvm::Value *VBPtr = nullptr;
2957 llvm::Value *VBaseOffs =
2958 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2959 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2961 // Merge control flow with the case where we didn't have to adjust.
2962 if (VBaseAdjustBB) {
2963 Builder.CreateBr(SkipAdjustBB);
2964 CGF.EmitBlock(SkipAdjustBB);
2965 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2966 Phi->addIncoming(Base.getPointer(), OriginalBB);
2967 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2970 return AdjustedBase;
2973 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2974 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
2975 const MemberPointerType *MPT) {
2976 assert(MPT->isMemberDataPointer());
2977 unsigned AS = Base.getAddressSpace();
2979 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2980 CGBuilderTy &Builder = CGF.Builder;
2981 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2982 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2984 // Extract the fields we need, regardless of model. We'll apply them if we
2986 llvm::Value *FieldOffset = MemPtr;
2987 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2988 llvm::Value *VBPtrOffset = nullptr;
2989 if (MemPtr->getType()->isStructTy()) {
2990 // We need to extract values.
2992 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2993 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2994 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2995 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2996 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3000 if (VirtualBaseAdjustmentOffset) {
3001 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3004 Addr = Base.getPointer();
3008 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3010 // Apply the offset, which we assume is non-null.
3011 Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset");
3013 // Cast the address to the appropriate pointer type, adopting the address
3014 // space of the base pointer.
3015 return Builder.CreateBitCast(Addr, PType);
3019 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3022 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3023 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3024 E->getCastKind() == CK_ReinterpretMemberPointer);
3026 // Use constant emission if we can.
3027 if (isa<llvm::Constant>(Src))
3028 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3030 // We may be adding or dropping fields from the member pointer, so we need
3031 // both types and the inheritance models of both records.
3032 const MemberPointerType *SrcTy =
3033 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3034 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3035 bool IsFunc = SrcTy->isMemberFunctionPointer();
3037 // If the classes use the same null representation, reinterpret_cast is a nop.
3038 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3039 if (IsReinterpret && IsFunc)
3042 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3043 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3044 if (IsReinterpret &&
3045 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3048 CGBuilderTy &Builder = CGF.Builder;
3050 // Branch past the conversion if Src is null.
3051 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3052 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3054 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3055 // pointer value of the destination type.
3056 if (IsReinterpret) {
3057 // For reinterpret casts, sema ensures that src and dst are both functions
3058 // or data and have the same size, which means the LLVM types should match.
3059 assert(Src->getType() == DstNull->getType());
3060 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3063 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3064 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3065 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3066 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3067 CGF.EmitBlock(ConvertBB);
3069 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3070 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3073 Builder.CreateBr(ContinueBB);
3075 // In the continuation, choose between DstNull and Dst.
3076 CGF.EmitBlock(ContinueBB);
3077 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3078 Phi->addIncoming(DstNull, OriginalBB);
3079 Phi->addIncoming(Dst, ConvertBB);
3083 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3084 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3085 CastExpr::path_const_iterator PathBegin,
3086 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3087 CGBuilderTy &Builder) {
3088 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3089 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3090 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
3091 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
3092 bool IsFunc = SrcTy->isMemberFunctionPointer();
3093 bool IsConstant = isa<llvm::Constant>(Src);
3096 llvm::Value *FirstField = Src;
3097 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3098 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3099 llvm::Value *VBPtrOffset = getZeroInt();
3100 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
3101 // We need to extract values.
3103 FirstField = Builder.CreateExtractValue(Src, I++);
3104 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
3105 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3106 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
3107 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3108 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
3109 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3112 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3113 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3114 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3116 // For data pointers, we adjust the field offset directly. For functions, we
3117 // have a separate field.
3118 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3120 // The virtual inheritance model has a quirk: the virtual base table is always
3121 // referenced when dereferencing a member pointer even if the member pointer
3122 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3123 // to point backwards to the top of the MDC from the first VBase. Undo this
3124 // adjustment to normalize the member pointer.
3125 llvm::Value *SrcVBIndexEqZero =
3126 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3127 if (SrcInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3128 if (int64_t SrcOffsetToFirstVBase =
3129 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3130 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3132 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3134 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3138 // A non-zero vbindex implies that we are dealing with a source member in a
3139 // floating virtual base in addition to some non-virtual offset. If the
3140 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3141 // fixed, base. The difference between these two cases is that the vbindex +
3142 // nvoffset *always* point to the member regardless of what context they are
3143 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3144 // base requires explicit nv adjustment.
3145 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3147 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3150 llvm::Value *NVDisp;
3151 if (IsDerivedToBase)
3152 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3154 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3156 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3158 // Update the vbindex to an appropriate value in the destination because
3159 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3160 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3161 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance) &&
3162 MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) {
3163 if (llvm::GlobalVariable *VDispMap =
3164 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3165 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3166 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3168 llvm::Constant *Mapping = VDispMap->getInitializer();
3169 VirtualBaseAdjustmentOffset =
3170 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3172 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3173 VirtualBaseAdjustmentOffset =
3174 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs),
3175 CharUnits::fromQuantity(4));
3179 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3183 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3184 // it to the offset of the vbptr.
3185 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) {
3186 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3188 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3190 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3193 // Likewise, apply a similar adjustment so that dereferencing the member
3194 // pointer correctly accounts for the distance between the start of the first
3195 // virtual base and the top of the MDC.
3196 if (DstInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3197 if (int64_t DstOffsetToFirstVBase =
3198 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3199 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3201 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3203 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3207 // Recompose dst from the null struct and the adjusted fields from src.
3209 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
3212 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3214 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3215 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
3216 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3217 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
3218 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3219 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
3220 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3226 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3227 llvm::Constant *Src) {
3228 const MemberPointerType *SrcTy =
3229 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3230 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3232 CastKind CK = E->getCastKind();
3234 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3235 E->path_end(), Src);
3238 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3239 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3240 CastExpr::path_const_iterator PathBegin,
3241 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3242 assert(CK == CK_DerivedToBaseMemberPointer ||
3243 CK == CK_BaseToDerivedMemberPointer ||
3244 CK == CK_ReinterpretMemberPointer);
3245 // If src is null, emit a new null for dst. We can't return src because dst
3246 // might have a new representation.
3247 if (MemberPointerConstantIsNull(SrcTy, Src))
3248 return EmitNullMemberPointer(DstTy);
3250 // We don't need to do anything for reinterpret_casts of non-null member
3251 // pointers. We should only get here when the two type representations have
3253 if (CK == CK_ReinterpretMemberPointer)
3256 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3257 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3258 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3263 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3264 CodeGenFunction &CGF, const Expr *E, Address This,
3265 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3266 const MemberPointerType *MPT) {
3267 assert(MPT->isMemberFunctionPointer());
3268 const FunctionProtoType *FPT =
3269 MPT->getPointeeType()->castAs<FunctionProtoType>();
3270 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3271 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3272 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3273 CGBuilderTy &Builder = CGF.Builder;
3275 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
3277 // Extract the fields we need, regardless of model. We'll apply them if we
3279 llvm::Value *FunctionPointer = MemPtr;
3280 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3281 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3282 llvm::Value *VBPtrOffset = nullptr;
3283 if (MemPtr->getType()->isStructTy()) {
3284 // We need to extract values.
3286 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3287 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
3288 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3289 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
3290 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3291 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
3292 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3295 if (VirtualBaseAdjustmentOffset) {
3296 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3297 VirtualBaseAdjustmentOffset, VBPtrOffset);
3299 ThisPtrForCall = This.getPointer();
3302 if (NonVirtualBaseAdjustment) {
3303 // Apply the adjustment and cast back to the original struct type.
3304 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3305 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
3306 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3311 Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3312 CGCallee Callee(FPT, FunctionPointer);
3316 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3317 return new MicrosoftCXXABI(CGM);
3320 // MS RTTI Overview:
3321 // The run time type information emitted by cl.exe contains 5 distinct types of
3322 // structures. Many of them reference each other.
3324 // TypeInfo: Static classes that are returned by typeid.
3326 // CompleteObjectLocator: Referenced by vftables. They contain information
3327 // required for dynamic casting, including OffsetFromTop. They also contain
3328 // a reference to the TypeInfo for the type and a reference to the
3329 // CompleteHierarchyDescriptor for the type.
3331 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
3332 // Used during dynamic_cast to walk a class hierarchy. References a base
3333 // class array and the size of said array.
3335 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3336 // somewhat of a misnomer because the most derived class is also in the list
3337 // as well as multiple copies of virtual bases (if they occur multiple times
3338 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for
3339 // every path in the hierarchy, in pre-order depth first order. Note, we do
3340 // not declare a specific llvm type for BaseClassArray, it's merely an array
3341 // of BaseClassDescriptor pointers.
3343 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3344 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3345 // BaseClassArray is. It contains information about a class within a
3346 // hierarchy such as: is this base is ambiguous and what is its offset in the
3347 // vbtable. The names of the BaseClassDescriptors have all of their fields
3348 // mangled into them so they can be aggressively deduplicated by the linker.
3350 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3351 StringRef MangledName("\01??_7type_info@@6B@");
3352 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3354 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3356 llvm::GlobalVariable::ExternalLinkage,
3357 /*Initializer=*/nullptr, MangledName);
3362 /// \brief A Helper struct that stores information about a class in a class
3363 /// hierarchy. The information stored in these structs struct is used during
3364 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3365 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3366 // implicit depth first pre-order tree connectivity. getFirstChild and
3367 // getNextSibling allow us to walk the tree efficiently.
3368 struct MSRTTIClass {
3370 IsPrivateOnPath = 1 | 8,
3374 HasHierarchyDescriptor = 64
3376 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3377 uint32_t initialize(const MSRTTIClass *Parent,
3378 const CXXBaseSpecifier *Specifier);
3380 MSRTTIClass *getFirstChild() { return this + 1; }
3381 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3382 return Child + 1 + Child->NumBases;
3385 const CXXRecordDecl *RD, *VirtualRoot;
3386 uint32_t Flags, NumBases, OffsetInVBase;
3389 /// \brief Recursively initialize the base class array.
3390 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3391 const CXXBaseSpecifier *Specifier) {
3392 Flags = HasHierarchyDescriptor;
3394 VirtualRoot = nullptr;
3397 if (Specifier->getAccessSpecifier() != AS_public)
3398 Flags |= IsPrivate | IsPrivateOnPath;
3399 if (Specifier->isVirtual()) {
3404 if (Parent->Flags & IsPrivateOnPath)
3405 Flags |= IsPrivateOnPath;
3406 VirtualRoot = Parent->VirtualRoot;
3407 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3408 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3412 MSRTTIClass *Child = getFirstChild();
3413 for (const CXXBaseSpecifier &Base : RD->bases()) {
3414 NumBases += Child->initialize(this, &Base) + 1;
3415 Child = getNextChild(Child);
3420 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3421 switch (Ty->getLinkage()) {
3423 case InternalLinkage:
3424 case UniqueExternalLinkage:
3425 return llvm::GlobalValue::InternalLinkage;
3427 case VisibleNoLinkage:
3428 case ModuleInternalLinkage:
3430 case ExternalLinkage:
3431 return llvm::GlobalValue::LinkOnceODRLinkage;
3433 llvm_unreachable("Invalid linkage!");
3436 /// \brief An ephemeral helper class for building MS RTTI types. It caches some
3437 /// calls to the module and information about the most derived class in a
3439 struct MSRTTIBuilder {
3441 HasBranchingHierarchy = 1,
3442 HasVirtualBranchingHierarchy = 2,
3443 HasAmbiguousBases = 4
3446 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3447 : CGM(ABI.CGM), Context(CGM.getContext()),
3448 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3449 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3452 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3453 llvm::GlobalVariable *
3454 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3455 llvm::GlobalVariable *getClassHierarchyDescriptor();
3456 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3459 ASTContext &Context;
3460 llvm::LLVMContext &VMContext;
3461 llvm::Module &Module;
3462 const CXXRecordDecl *RD;
3463 llvm::GlobalVariable::LinkageTypes Linkage;
3464 MicrosoftCXXABI &ABI;
3469 /// \brief Recursively serializes a class hierarchy in pre-order depth first
3471 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3472 const CXXRecordDecl *RD) {
3473 Classes.push_back(MSRTTIClass(RD));
3474 for (const CXXBaseSpecifier &Base : RD->bases())
3475 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3478 /// \brief Find ambiguity among base classes.
3480 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3481 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3482 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3483 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3484 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3485 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3486 !VirtualBases.insert(Class->RD).second) {
3487 Class = MSRTTIClass::getNextChild(Class);
3490 if (!UniqueBases.insert(Class->RD).second)
3491 AmbiguousBases.insert(Class->RD);
3494 if (AmbiguousBases.empty())
3496 for (MSRTTIClass &Class : Classes)
3497 if (AmbiguousBases.count(Class.RD))
3498 Class.Flags |= MSRTTIClass::IsAmbiguous;
3501 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3502 SmallString<256> MangledName;
3504 llvm::raw_svector_ostream Out(MangledName);
3505 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3508 // Check to see if we've already declared this ClassHierarchyDescriptor.
3509 if (auto CHD = Module.getNamedGlobal(MangledName))
3512 // Serialize the class hierarchy and initialize the CHD Fields.
3513 SmallVector<MSRTTIClass, 8> Classes;
3514 serializeClassHierarchy(Classes, RD);
3515 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3516 detectAmbiguousBases(Classes);
3518 for (auto Class : Classes) {
3519 if (Class.RD->getNumBases() > 1)
3520 Flags |= HasBranchingHierarchy;
3521 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3522 // believe the field isn't actually used.
3523 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3524 Flags |= HasAmbiguousBases;
3526 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3527 Flags |= HasVirtualBranchingHierarchy;
3528 // These gep indices are used to get the address of the first element of the
3529 // base class array.
3530 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3531 llvm::ConstantInt::get(CGM.IntTy, 0)};
3533 // Forward-declare the class hierarchy descriptor
3534 auto Type = ABI.getClassHierarchyDescriptorType();
3535 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3536 /*Initializer=*/nullptr,
3538 if (CHD->isWeakForLinker())
3539 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3541 auto *Bases = getBaseClassArray(Classes);
3543 // Initialize the base class ClassHierarchyDescriptor.
3544 llvm::Constant *Fields[] = {
3545 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3546 llvm::ConstantInt::get(CGM.IntTy, Flags),
3547 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3548 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3549 Bases->getValueType(), Bases,
3550 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3552 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3556 llvm::GlobalVariable *
3557 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3558 SmallString<256> MangledName;
3560 llvm::raw_svector_ostream Out(MangledName);
3561 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3564 // Forward-declare the base class array.
3565 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3566 // mode) bytes of padding. We provide a pointer sized amount of padding by
3567 // adding +1 to Classes.size(). The sections have pointer alignment and are
3568 // marked pick-any so it shouldn't matter.
3569 llvm::Type *PtrType = ABI.getImageRelativeType(
3570 ABI.getBaseClassDescriptorType()->getPointerTo());
3571 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3573 new llvm::GlobalVariable(Module, ArrType,
3574 /*Constant=*/true, Linkage,
3575 /*Initializer=*/nullptr, MangledName);
3576 if (BCA->isWeakForLinker())
3577 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3579 // Initialize the BaseClassArray.
3580 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3581 for (MSRTTIClass &Class : Classes)
3582 BaseClassArrayData.push_back(
3583 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3584 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3585 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3589 llvm::GlobalVariable *
3590 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3591 // Compute the fields for the BaseClassDescriptor. They are computed up front
3592 // because they are mangled into the name of the object.
3593 uint32_t OffsetInVBTable = 0;
3594 int32_t VBPtrOffset = -1;
3595 if (Class.VirtualRoot) {
3596 auto &VTableContext = CGM.getMicrosoftVTableContext();
3597 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3598 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3601 SmallString<256> MangledName;
3603 llvm::raw_svector_ostream Out(MangledName);
3604 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3605 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3609 // Check to see if we've already declared this object.
3610 if (auto BCD = Module.getNamedGlobal(MangledName))
3613 // Forward-declare the base class descriptor.
3614 auto Type = ABI.getBaseClassDescriptorType();
3616 new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3617 /*Initializer=*/nullptr, MangledName);
3618 if (BCD->isWeakForLinker())
3619 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3621 // Initialize the BaseClassDescriptor.
3622 llvm::Constant *Fields[] = {
3623 ABI.getImageRelativeConstant(
3624 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3625 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3626 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3627 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3628 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3629 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3630 ABI.getImageRelativeConstant(
3631 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3633 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3637 llvm::GlobalVariable *
3638 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3639 SmallString<256> MangledName;
3641 llvm::raw_svector_ostream Out(MangledName);
3642 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3645 // Check to see if we've already computed this complete object locator.
3646 if (auto COL = Module.getNamedGlobal(MangledName))
3649 // Compute the fields of the complete object locator.
3650 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3651 int VFPtrOffset = 0;
3652 // The offset includes the vtordisp if one exists.
3653 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3654 if (Context.getASTRecordLayout(RD)
3655 .getVBaseOffsetsMap()
3657 ->second.hasVtorDisp())
3658 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3660 // Forward-declare the complete object locator.
3661 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3662 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3663 /*Initializer=*/nullptr, MangledName);
3665 // Initialize the CompleteObjectLocator.
3666 llvm::Constant *Fields[] = {
3667 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3668 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3669 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3670 ABI.getImageRelativeConstant(
3671 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3672 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3673 ABI.getImageRelativeConstant(COL),
3675 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3676 if (!ABI.isImageRelative())
3677 FieldsRef = FieldsRef.drop_back();
3678 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3679 if (COL->isWeakForLinker())
3680 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3684 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3685 bool &IsConst, bool &IsVolatile,
3686 bool &IsUnaligned) {
3687 T = Context.getExceptionObjectType(T);
3689 // C++14 [except.handle]p3:
3690 // A handler is a match for an exception object of type E if [...]
3691 // - the handler is of type cv T or const T& where T is a pointer type and
3692 // E is a pointer type that can be converted to T by [...]
3693 // - a qualification conversion
3696 IsUnaligned = false;
3697 QualType PointeeType = T->getPointeeType();
3698 if (!PointeeType.isNull()) {
3699 IsConst = PointeeType.isConstQualified();
3700 IsVolatile = PointeeType.isVolatileQualified();
3701 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3704 // Member pointer types like "const int A::*" are represented by having RTTI
3705 // for "int A::*" and separately storing the const qualifier.
3706 if (const auto *MPTy = T->getAs<MemberPointerType>())
3707 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3710 // Pointer types like "const int * const *" are represented by having RTTI
3711 // for "const int **" and separately storing the const qualifier.
3712 if (T->isPointerType())
3713 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3719 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3720 QualType CatchHandlerType) {
3721 // TypeDescriptors for exceptions never have qualified pointer types,
3722 // qualifiers are stored separately in order to support qualification
3724 bool IsConst, IsVolatile, IsUnaligned;
3726 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3728 bool IsReference = CatchHandlerType->isReferenceType();
3740 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3744 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3745 /// llvm::GlobalVariable * because different type descriptors have different
3746 /// types, and need to be abstracted. They are abstracting by casting the
3747 /// address to an Int8PtrTy.
3748 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3749 SmallString<256> MangledName;
3751 llvm::raw_svector_ostream Out(MangledName);
3752 getMangleContext().mangleCXXRTTI(Type, Out);
3755 // Check to see if we've already declared this TypeDescriptor.
3756 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3757 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3759 // Note for the future: If we would ever like to do deferred emission of
3760 // RTTI, check if emitting vtables opportunistically need any adjustment.
3762 // Compute the fields for the TypeDescriptor.
3763 SmallString<256> TypeInfoString;
3765 llvm::raw_svector_ostream Out(TypeInfoString);
3766 getMangleContext().mangleCXXRTTIName(Type, Out);
3769 // Declare and initialize the TypeDescriptor.
3770 llvm::Constant *Fields[] = {
3771 getTypeInfoVTable(CGM), // VFPtr
3772 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3773 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3774 llvm::StructType *TypeDescriptorType =
3775 getTypeDescriptorType(TypeInfoString);
3776 auto *Var = new llvm::GlobalVariable(
3777 CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3778 getLinkageForRTTI(Type),
3779 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3781 if (Var->isWeakForLinker())
3782 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3783 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3786 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
3787 llvm::GlobalVariable *
3788 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3789 const VPtrInfo &Info) {
3790 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3793 static void emitCXXConstructor(CodeGenModule &CGM,
3794 const CXXConstructorDecl *ctor,
3795 StructorType ctorType) {
3796 // There are no constructor variants, always emit the complete destructor.
3797 llvm::Function *Fn = CGM.codegenCXXStructor(ctor, StructorType::Complete);
3798 CGM.maybeSetTrivialComdat(*ctor, *Fn);
3801 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3802 StructorType dtorType) {
3803 // The complete destructor is equivalent to the base destructor for
3804 // classes with no virtual bases, so try to emit it as an alias.
3805 if (!dtor->getParent()->getNumVBases() &&
3806 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3807 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3808 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3809 if (ProducedAlias) {
3810 if (dtorType == StructorType::Complete)
3812 if (dtor->isVirtual())
3813 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3817 // The base destructor is equivalent to the base destructor of its
3818 // base class if there is exactly one non-virtual base class with a
3819 // non-trivial destructor, there are no fields with a non-trivial
3820 // destructor, and the body of the destructor is trivial.
3821 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3824 llvm::Function *Fn = CGM.codegenCXXStructor(dtor, dtorType);
3825 if (Fn->isWeakForLinker())
3826 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3829 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3830 StructorType Type) {
3831 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3832 emitCXXConstructor(CGM, CD, Type);
3835 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);
3839 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
3841 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
3843 // Calculate the mangled name.
3844 SmallString<256> ThunkName;
3845 llvm::raw_svector_ostream Out(ThunkName);
3846 getMangleContext().mangleCXXCtor(CD, CT, Out);
3848 // If the thunk has been generated previously, just return it.
3849 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
3850 return cast<llvm::Function>(GV);
3852 // Create the llvm::Function.
3853 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
3854 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3855 const CXXRecordDecl *RD = CD->getParent();
3856 QualType RecordTy = getContext().getRecordType(RD);
3857 llvm::Function *ThunkFn = llvm::Function::Create(
3858 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
3859 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
3860 FnInfo.getEffectiveCallingConvention()));
3861 if (ThunkFn->isWeakForLinker())
3862 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
3863 bool IsCopy = CT == Ctor_CopyingClosure;
3866 CodeGenFunction CGF(CGM);
3867 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
3869 // Build FunctionArgs.
3870 FunctionArgList FunctionArgs;
3872 // A constructor always starts with a 'this' pointer as its first argument.
3873 buildThisParam(CGF, FunctionArgs);
3875 // Following the 'this' pointer is a reference to the source object that we
3876 // are copying from.
3877 ImplicitParamDecl SrcParam(
3878 getContext(), /*DC=*/nullptr, SourceLocation(),
3879 &getContext().Idents.get("src"),
3880 getContext().getLValueReferenceType(RecordTy,
3881 /*SpelledAsLValue=*/true),
3882 ImplicitParamDecl::Other);
3884 FunctionArgs.push_back(&SrcParam);
3886 // Constructors for classes which utilize virtual bases have an additional
3887 // parameter which indicates whether or not it is being delegated to by a more
3888 // derived constructor.
3889 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
3891 &getContext().Idents.get("is_most_derived"),
3892 getContext().IntTy, ImplicitParamDecl::Other);
3893 // Only add the parameter to the list if thie class has virtual bases.
3894 if (RD->getNumVBases() > 0)
3895 FunctionArgs.push_back(&IsMostDerived);
3897 // Start defining the function.
3898 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
3899 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3900 FunctionArgs, CD->getLocation(), SourceLocation());
3901 // Create a scope with an artificial location for the body of this function.
3902 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
3904 llvm::Value *This = getThisValue(CGF);
3906 llvm::Value *SrcVal =
3907 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
3912 // Push the this ptr.
3913 Args.add(RValue::get(This), CD->getThisType(getContext()));
3915 // Push the src ptr.
3917 Args.add(RValue::get(SrcVal), SrcParam.getType());
3919 // Add the rest of the default arguments.
3920 SmallVector<const Stmt *, 4> ArgVec;
3921 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
3922 for (const ParmVarDecl *PD : params) {
3923 assert(PD->hasDefaultArg() && "ctor closure lacks default args");
3924 ArgVec.push_back(PD->getDefaultArg());
3927 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
3929 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
3930 CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
3932 // Insert any ABI-specific implicit constructor arguments.
3933 AddedStructorArgs ExtraArgs =
3934 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
3935 /*ForVirtualBase=*/false,
3936 /*Delegating=*/false, Args);
3937 // Call the destructor with our arguments.
3938 llvm::Constant *CalleePtr =
3939 CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3940 CGCallee Callee = CGCallee::forDirect(CalleePtr, CD);
3941 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
3942 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
3943 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
3945 Cleanups.ForceCleanup();
3947 // Emit the ret instruction, remove any temporary instructions created for the
3949 CGF.FinishFunction(SourceLocation());
3954 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
3956 int32_t VBPtrOffset,
3958 assert(!T->isReferenceType());
3960 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
3961 const CXXConstructorDecl *CD =
3962 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
3963 CXXCtorType CT = Ctor_Complete;
3965 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
3966 CT = Ctor_CopyingClosure;
3968 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
3969 SmallString<256> MangledName;
3971 llvm::raw_svector_ostream Out(MangledName);
3972 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
3973 VBPtrOffset, VBIndex, Out);
3975 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3976 return getImageRelativeConstant(GV);
3978 // The TypeDescriptor is used by the runtime to determine if a catch handler
3979 // is appropriate for the exception object.
3980 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
3982 // The runtime is responsible for calling the copy constructor if the
3983 // exception is caught by value.
3984 llvm::Constant *CopyCtor;
3986 if (CT == Ctor_CopyingClosure)
3987 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
3989 CopyCtor = CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3991 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
3993 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
3995 CopyCtor = getImageRelativeConstant(CopyCtor);
3997 bool IsScalar = !RD;
3998 bool HasVirtualBases = false;
3999 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4000 QualType PointeeType = T;
4001 if (T->isPointerType())
4002 PointeeType = T->getPointeeType();
4003 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4004 HasVirtualBases = RD->getNumVBases() > 0;
4005 if (IdentifierInfo *II = RD->getIdentifier())
4006 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4009 // Encode the relevant CatchableType properties into the Flags bitfield.
4010 // FIXME: Figure out how bits 2 or 8 can get set.
4014 if (HasVirtualBases)
4019 llvm::Constant *Fields[] = {
4020 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4021 TD, // TypeDescriptor
4022 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4023 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4024 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4025 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4026 CopyCtor // CopyCtor
4028 llvm::StructType *CTType = getCatchableTypeType();
4029 auto *GV = new llvm::GlobalVariable(
4030 CGM.getModule(), CTType, /*Constant=*/true, getLinkageForRTTI(T),
4031 llvm::ConstantStruct::get(CTType, Fields), MangledName);
4032 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4033 GV->setSection(".xdata");
4034 if (GV->isWeakForLinker())
4035 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4036 return getImageRelativeConstant(GV);
4039 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4040 assert(!T->isReferenceType());
4042 // See if we've already generated a CatchableTypeArray for this type before.
4043 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4047 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4048 // using a SmallSetVector. Duplicates may arise due to virtual bases
4049 // occurring more than once in the hierarchy.
4050 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4052 // C++14 [except.handle]p3:
4053 // A handler is a match for an exception object of type E if [...]
4054 // - the handler is of type cv T or cv T& and T is an unambiguous public
4055 // base class of E, or
4056 // - the handler is of type cv T or const T& where T is a pointer type and
4057 // E is a pointer type that can be converted to T by [...]
4058 // - a standard pointer conversion (4.10) not involving conversions to
4059 // pointers to private or protected or ambiguous classes
4060 const CXXRecordDecl *MostDerivedClass = nullptr;
4061 bool IsPointer = T->isPointerType();
4063 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4065 MostDerivedClass = T->getAsCXXRecordDecl();
4067 // Collect all the unambiguous public bases of the MostDerivedClass.
4068 if (MostDerivedClass) {
4069 const ASTContext &Context = getContext();
4070 const ASTRecordLayout &MostDerivedLayout =
4071 Context.getASTRecordLayout(MostDerivedClass);
4072 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4073 SmallVector<MSRTTIClass, 8> Classes;
4074 serializeClassHierarchy(Classes, MostDerivedClass);
4075 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4076 detectAmbiguousBases(Classes);
4077 for (const MSRTTIClass &Class : Classes) {
4078 // Skip any ambiguous or private bases.
4080 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4082 // Write down how to convert from a derived pointer to a base pointer.
4083 uint32_t OffsetInVBTable = 0;
4084 int32_t VBPtrOffset = -1;
4085 if (Class.VirtualRoot) {
4087 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4088 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4091 // Turn our record back into a pointer if the exception object is a
4093 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4095 RTTITy = Context.getPointerType(RTTITy);
4096 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4097 VBPtrOffset, OffsetInVBTable));
4101 // C++14 [except.handle]p3:
4102 // A handler is a match for an exception object of type E if
4103 // - The handler is of type cv T or cv T& and E and T are the same type
4104 // (ignoring the top-level cv-qualifiers)
4105 CatchableTypes.insert(getCatchableType(T));
4107 // C++14 [except.handle]p3:
4108 // A handler is a match for an exception object of type E if
4109 // - the handler is of type cv T or const T& where T is a pointer type and
4110 // E is a pointer type that can be converted to T by [...]
4111 // - a standard pointer conversion (4.10) not involving conversions to
4112 // pointers to private or protected or ambiguous classes
4114 // C++14 [conv.ptr]p2:
4115 // A prvalue of type "pointer to cv T," where T is an object type, can be
4116 // converted to a prvalue of type "pointer to cv void".
4117 if (IsPointer && T->getPointeeType()->isObjectType())
4118 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4120 // C++14 [except.handle]p3:
4121 // A handler is a match for an exception object of type E if [...]
4122 // - the handler is of type cv T or const T& where T is a pointer or
4123 // pointer to member type and E is std::nullptr_t.
4125 // We cannot possibly list all possible pointer types here, making this
4126 // implementation incompatible with the standard. However, MSVC includes an
4127 // entry for pointer-to-void in this case. Let's do the same.
4128 if (T->isNullPtrType())
4129 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4131 uint32_t NumEntries = CatchableTypes.size();
4132 llvm::Type *CTType =
4133 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4134 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4135 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4136 llvm::Constant *Fields[] = {
4137 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4138 llvm::ConstantArray::get(
4139 AT, llvm::makeArrayRef(CatchableTypes.begin(),
4140 CatchableTypes.end())) // CatchableTypes
4142 SmallString<256> MangledName;
4144 llvm::raw_svector_ostream Out(MangledName);
4145 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4147 CTA = new llvm::GlobalVariable(
4148 CGM.getModule(), CTAType, /*Constant=*/true, getLinkageForRTTI(T),
4149 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4150 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4151 CTA->setSection(".xdata");
4152 if (CTA->isWeakForLinker())
4153 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4157 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4158 bool IsConst, IsVolatile, IsUnaligned;
4159 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4161 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4162 // the exception object may be caught as.
4163 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4164 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4165 // This is used as a component of the mangled name which means that we need to
4166 // know what it is in order to see if we have previously generated the
4168 uint32_t NumEntries =
4169 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4170 ->getLimitedValue();
4172 SmallString<256> MangledName;
4174 llvm::raw_svector_ostream Out(MangledName);
4175 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4179 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4181 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4184 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4185 // be at least as CV qualified. Encode this requirement into the Flags
4195 // The cleanup-function (a destructor) must be called when the exception
4196 // object's lifetime ends.
4197 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4198 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4199 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4200 if (!DtorD->isTrivial())
4201 CleanupFn = llvm::ConstantExpr::getBitCast(
4202 CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete),
4204 // This is unused as far as we can tell, initialize it to null.
4205 llvm::Constant *ForwardCompat =
4206 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4207 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4208 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4209 llvm::StructType *TIType = getThrowInfoType();
4210 llvm::Constant *Fields[] = {
4211 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4212 getImageRelativeConstant(CleanupFn), // CleanupFn
4213 ForwardCompat, // ForwardCompat
4214 PointerToCatchableTypes // CatchableTypeArray
4216 auto *GV = new llvm::GlobalVariable(
4217 CGM.getModule(), TIType, /*Constant=*/true, getLinkageForRTTI(T),
4218 llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
4219 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4220 GV->setSection(".xdata");
4221 if (GV->isWeakForLinker())
4222 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4226 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4227 const Expr *SubExpr = E->getSubExpr();
4228 QualType ThrowType = SubExpr->getType();
4229 // The exception object lives on the stack and it's address is passed to the
4230 // runtime function.
4231 Address AI = CGF.CreateMemTemp(ThrowType);
4232 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4235 // The so-called ThrowInfo is used to describe how the exception object may be
4237 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4239 // Call into the runtime to throw the exception.
4240 llvm::Value *Args[] = {
4241 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4244 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);