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 "CGVTables.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenTypes.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/VTableBuilder.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/Intrinsics.h"
31 using namespace clang;
32 using namespace CodeGen;
36 /// Holds all the vbtable globals for a given class.
37 struct VBTableGlobals {
38 const VPtrInfoVector *VBTables;
39 SmallVector<llvm::GlobalVariable *, 2> Globals;
42 class MicrosoftCXXABI : public CGCXXABI {
44 MicrosoftCXXABI(CodeGenModule &CGM)
45 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
46 ClassHierarchyDescriptorType(nullptr),
47 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
48 ThrowInfoType(nullptr) {}
50 bool HasThisReturn(GlobalDecl GD) const override;
51 bool hasMostDerivedReturn(GlobalDecl GD) const override;
53 bool classifyReturnType(CGFunctionInfo &FI) const override;
55 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
57 bool isSRetParameterAfterThis() const override { return true; }
59 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
60 FunctionArgList &Args) const override {
61 assert(Args.size() >= 2 &&
62 "expected the arglist to have at least two args!");
63 // The 'most_derived' parameter goes second if the ctor is variadic and
65 if (CD->getParent()->getNumVBases() > 0 &&
66 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
71 StringRef GetPureVirtualCallName() override { return "_purecall"; }
72 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
74 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
75 llvm::Value *Ptr, QualType ElementType,
76 const CXXDestructorDecl *Dtor) override;
78 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
79 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
81 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
83 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
84 const VPtrInfo *Info);
86 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
88 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
89 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
90 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
92 llvm::Type *StdTypeInfoPtrTy) override;
94 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
95 QualType SrcRecordTy) override;
97 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
98 QualType SrcRecordTy, QualType DestTy,
99 QualType DestRecordTy,
100 llvm::BasicBlock *CastEnd) override;
102 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
103 QualType SrcRecordTy,
104 QualType DestTy) override;
106 bool EmitBadCastCall(CodeGenFunction &CGF) override;
109 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
110 const CXXRecordDecl *ClassDecl,
111 const CXXRecordDecl *BaseClassDecl) override;
114 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
115 const CXXRecordDecl *RD) override;
117 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
118 const CXXRecordDecl *RD) override;
120 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
122 // Background on MSVC destructors
123 // ==============================
125 // Both Itanium and MSVC ABIs have destructor variants. The variant names
126 // roughly correspond in the following way:
128 // Base -> no name, just ~Class
129 // Complete -> vbase destructor
130 // Deleting -> scalar deleting destructor
131 // vector deleting destructor
133 // The base and complete destructors are the same as in Itanium, although the
134 // complete destructor does not accept a VTT parameter when there are virtual
135 // bases. A separate mechanism involving vtordisps is used to ensure that
136 // virtual methods of destroyed subobjects are not called.
138 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
139 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
140 // pointer points to an array. The scalar deleting destructor assumes that
141 // bit 2 is zero, and therefore does not contain a loop.
143 // For virtual destructors, only one entry is reserved in the vftable, and it
144 // always points to the vector deleting destructor. The vector deleting
145 // destructor is the most general, so it can be used to destroy objects in
146 // place, delete single heap objects, or delete arrays.
148 // A TU defining a non-inline destructor is only guaranteed to emit a base
149 // destructor, and all of the other variants are emitted on an as-needed basis
150 // in COMDATs. Because a non-base destructor can be emitted in a TU that
151 // lacks a definition for the destructor, non-base destructors must always
152 // delegate to or alias the base destructor.
154 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
155 SmallVectorImpl<CanQualType> &ArgTys) override;
157 /// Non-base dtors should be emitted as delegating thunks in this ABI.
158 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
159 CXXDtorType DT) const override {
160 return DT != Dtor_Base;
163 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
165 const CXXRecordDecl *
166 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
167 MD = MD->getCanonicalDecl();
168 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
169 MicrosoftVTableContext::MethodVFTableLocation ML =
170 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
171 // The vbases might be ordered differently in the final overrider object
172 // and the complete object, so the "this" argument may sometimes point to
173 // memory that has no particular type (e.g. past the complete object).
174 // In this case, we just use a generic pointer type.
175 // FIXME: might want to have a more precise type in the non-virtual
176 // multiple inheritance case.
177 if (ML.VBase || !ML.VFPtrOffset.isZero())
180 return MD->getParent();
184 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
186 bool VirtualCall) override;
188 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
189 FunctionArgList &Params) override;
191 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
192 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
194 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
196 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
197 const CXXConstructorDecl *D,
198 CXXCtorType Type, bool ForVirtualBase,
200 CallArgList &Args) override;
202 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
203 CXXDtorType Type, bool ForVirtualBase,
204 bool Delegating, llvm::Value *This) override;
206 void emitVTableDefinitions(CodeGenVTables &CGVT,
207 const CXXRecordDecl *RD) override;
209 llvm::Value *getVTableAddressPointInStructor(
210 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
211 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
212 bool &NeedsVirtualOffset) override;
215 getVTableAddressPointForConstExpr(BaseSubobject Base,
216 const CXXRecordDecl *VTableClass) override;
218 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
219 CharUnits VPtrOffset) override;
221 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
223 llvm::Type *Ty) override;
225 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
226 const CXXDestructorDecl *Dtor,
227 CXXDtorType DtorType,
229 const CXXMemberCallExpr *CE) override;
231 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
232 CallArgList &CallArgs) override {
233 assert(GD.getDtorType() == Dtor_Deleting &&
234 "Only deleting destructor thunks are available in this ABI");
235 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
236 CGM.getContext().IntTy);
239 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
241 llvm::GlobalVariable *
242 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
243 llvm::GlobalVariable::LinkageTypes Linkage);
245 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
246 llvm::GlobalVariable *GV) const;
248 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
249 GlobalDecl GD, bool ReturnAdjustment) override {
250 // Never dllimport/dllexport thunks.
251 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
254 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
256 if (Linkage == GVA_Internal)
257 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
258 else if (ReturnAdjustment)
259 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
261 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
264 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
265 const ThisAdjustment &TA) override;
267 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
268 const ReturnAdjustment &RA) override;
270 void EmitThreadLocalInitFuncs(
272 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
274 ArrayRef<llvm::Function *> CXXThreadLocalInits,
275 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
277 bool usesThreadWrapperFunction() const override { return false; }
278 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
279 QualType LValType) override;
281 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
282 llvm::GlobalVariable *DeclPtr,
283 bool PerformInit) override;
284 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
285 llvm::Constant *Dtor, llvm::Constant *Addr) override;
287 // ==== Notes on array cookies =========
289 // MSVC seems to only use cookies when the class has a destructor; a
290 // two-argument usual array deallocation function isn't sufficient.
292 // For example, this code prints "100" and "1":
295 // void *operator new[](size_t sz) {
296 // printf("%u\n", sz);
297 // return malloc(sz);
299 // void operator delete[](void *p, size_t sz) {
300 // printf("%u\n", sz);
305 // A *p = new A[100];
308 // Whereas it prints "104" and "104" if you give A a destructor.
310 bool requiresArrayCookie(const CXXDeleteExpr *expr,
311 QualType elementType) override;
312 bool requiresArrayCookie(const CXXNewExpr *expr) override;
313 CharUnits getArrayCookieSizeImpl(QualType type) override;
314 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
316 llvm::Value *NumElements,
317 const CXXNewExpr *expr,
318 QualType ElementType) override;
319 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
320 llvm::Value *allocPtr,
321 CharUnits cookieSize) override;
323 friend struct MSRTTIBuilder;
325 bool isImageRelative() const {
326 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64;
329 // 5 routines for constructing the llvm types for MS RTTI structs.
330 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
331 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
332 TDTypeName += llvm::utostr(TypeInfoString.size());
333 llvm::StructType *&TypeDescriptorType =
334 TypeDescriptorTypeMap[TypeInfoString.size()];
335 if (TypeDescriptorType)
336 return TypeDescriptorType;
337 llvm::Type *FieldTypes[] = {
340 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
342 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
343 return TypeDescriptorType;
346 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
347 if (!isImageRelative())
352 llvm::StructType *getBaseClassDescriptorType() {
353 if (BaseClassDescriptorType)
354 return BaseClassDescriptorType;
355 llvm::Type *FieldTypes[] = {
356 getImageRelativeType(CGM.Int8PtrTy),
362 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
364 BaseClassDescriptorType = llvm::StructType::create(
365 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
366 return BaseClassDescriptorType;
369 llvm::StructType *getClassHierarchyDescriptorType() {
370 if (ClassHierarchyDescriptorType)
371 return ClassHierarchyDescriptorType;
372 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
373 ClassHierarchyDescriptorType = llvm::StructType::create(
374 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
375 llvm::Type *FieldTypes[] = {
379 getImageRelativeType(
380 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
382 ClassHierarchyDescriptorType->setBody(FieldTypes);
383 return ClassHierarchyDescriptorType;
386 llvm::StructType *getCompleteObjectLocatorType() {
387 if (CompleteObjectLocatorType)
388 return CompleteObjectLocatorType;
389 CompleteObjectLocatorType = llvm::StructType::create(
390 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
391 llvm::Type *FieldTypes[] = {
395 getImageRelativeType(CGM.Int8PtrTy),
396 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
397 getImageRelativeType(CompleteObjectLocatorType),
399 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
400 if (!isImageRelative())
401 FieldTypesRef = FieldTypesRef.drop_back();
402 CompleteObjectLocatorType->setBody(FieldTypesRef);
403 return CompleteObjectLocatorType;
406 llvm::GlobalVariable *getImageBase() {
407 StringRef Name = "__ImageBase";
408 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
411 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
413 llvm::GlobalValue::ExternalLinkage,
414 /*Initializer=*/nullptr, Name);
417 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
418 if (!isImageRelative())
421 if (PtrVal->isNullValue())
422 return llvm::Constant::getNullValue(CGM.IntTy);
424 llvm::Constant *ImageBaseAsInt =
425 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
426 llvm::Constant *PtrValAsInt =
427 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
428 llvm::Constant *Diff =
429 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
430 /*HasNUW=*/true, /*HasNSW=*/true);
431 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
435 MicrosoftMangleContext &getMangleContext() {
436 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
439 llvm::Constant *getZeroInt() {
440 return llvm::ConstantInt::get(CGM.IntTy, 0);
443 llvm::Constant *getAllOnesInt() {
444 return llvm::Constant::getAllOnesValue(CGM.IntTy);
447 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
448 return C ? C : getZeroInt();
451 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
452 return C ? C : getZeroInt();
455 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD);
458 GetNullMemberPointerFields(const MemberPointerType *MPT,
459 llvm::SmallVectorImpl<llvm::Constant *> &fields);
461 /// \brief Shared code for virtual base adjustment. Returns the offset from
462 /// the vbptr to the virtual base. Optionally returns the address of the
464 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
466 llvm::Value *VBPtrOffset,
467 llvm::Value *VBTableOffset,
468 llvm::Value **VBPtr = nullptr);
470 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
473 int32_t VBTableOffset,
474 llvm::Value **VBPtr = nullptr) {
475 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
476 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
477 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
478 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
481 std::pair<llvm::Value *, llvm::Value *>
482 performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value,
483 QualType SrcRecordTy);
485 /// \brief Performs a full virtual base adjustment. Used to dereference
486 /// pointers to members of virtual bases.
487 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
488 const CXXRecordDecl *RD, llvm::Value *Base,
489 llvm::Value *VirtualBaseAdjustmentOffset,
490 llvm::Value *VBPtrOffset /* optional */);
492 /// \brief Emits a full member pointer with the fields common to data and
493 /// function member pointers.
494 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
495 bool IsMemberFunction,
496 const CXXRecordDecl *RD,
497 CharUnits NonVirtualBaseAdjustment);
499 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
500 const CXXMethodDecl *MD,
501 CharUnits NonVirtualBaseAdjustment);
503 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
506 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
507 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
509 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
510 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
512 /// \brief Generate a thunk for calling a virtual member function MD.
513 llvm::Function *EmitVirtualMemPtrThunk(
514 const CXXMethodDecl *MD,
515 const MicrosoftVTableContext::MethodVFTableLocation &ML);
518 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
520 bool isZeroInitializable(const MemberPointerType *MPT) override;
522 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
523 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
524 return RD->hasAttr<MSInheritanceAttr>();
527 bool isTypeInfoCalculable(QualType Ty) const override {
528 if (!CGCXXABI::isTypeInfoCalculable(Ty))
530 if (const auto *MPT = Ty->getAs<MemberPointerType>()) {
531 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
532 if (!RD->hasAttr<MSInheritanceAttr>())
538 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
540 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
541 CharUnits offset) override;
542 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
543 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
545 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
548 const MemberPointerType *MPT,
549 bool Inequality) override;
551 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
553 const MemberPointerType *MPT) override;
556 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
557 llvm::Value *Base, llvm::Value *MemPtr,
558 const MemberPointerType *MPT) override;
560 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
562 llvm::Value *Src) override;
564 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
565 llvm::Constant *Src) override;
568 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
569 llvm::Value *&This, llvm::Value *MemPtr,
570 const MemberPointerType *MPT) override;
572 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
574 llvm::StructType *getCatchableTypeType() {
575 if (CatchableTypeType)
576 return CatchableTypeType;
577 llvm::Type *FieldTypes[] = {
579 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
580 CGM.IntTy, // NonVirtualAdjustment
581 CGM.IntTy, // OffsetToVBPtr
582 CGM.IntTy, // VBTableIndex
584 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
586 CatchableTypeType = llvm::StructType::create(
587 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
588 return CatchableTypeType;
591 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
592 llvm::StructType *&CatchableTypeArrayType =
593 CatchableTypeArrayTypeMap[NumEntries];
594 if (CatchableTypeArrayType)
595 return CatchableTypeArrayType;
597 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
598 CTATypeName += llvm::utostr(NumEntries);
600 getImageRelativeType(getCatchableTypeType()->getPointerTo());
601 llvm::Type *FieldTypes[] = {
602 CGM.IntTy, // NumEntries
603 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
605 CatchableTypeArrayType =
606 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
607 return CatchableTypeArrayType;
610 llvm::StructType *getThrowInfoType() {
612 return ThrowInfoType;
613 llvm::Type *FieldTypes[] = {
615 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
616 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
617 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
619 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
621 return ThrowInfoType;
624 llvm::Constant *getThrowFn() {
625 // _CxxThrowException is passed an exception object and a ThrowInfo object
626 // which describes the exception.
627 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
628 llvm::FunctionType *FTy =
629 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
630 auto *Fn = cast<llvm::Function>(
631 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"));
632 // _CxxThrowException is stdcall on 32-bit x86 platforms.
633 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86)
634 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
638 llvm::Constant *getCatchableType(QualType T,
639 uint32_t NVOffset = 0,
640 int32_t VBPtrOffset = -1,
641 uint32_t VBIndex = 0);
643 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
645 llvm::GlobalVariable *getThrowInfo(QualType T);
648 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
649 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
650 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
651 /// \brief All the vftables that have been referenced.
652 VFTablesMapTy VFTablesMap;
653 VTablesMapTy VTablesMap;
655 /// \brief This set holds the record decls we've deferred vtable emission for.
656 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
659 /// \brief All the vbtables which have been referenced.
660 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
662 /// Info on the global variable used to guard initialization of static locals.
663 /// The BitIndex field is only used for externally invisible declarations.
665 GuardInfo() : Guard(nullptr), BitIndex(0) {}
666 llvm::GlobalVariable *Guard;
670 /// Map from DeclContext to the current guard variable. We assume that the
671 /// AST is visited in source code order.
672 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
674 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
675 llvm::StructType *BaseClassDescriptorType;
676 llvm::StructType *ClassHierarchyDescriptorType;
677 llvm::StructType *CompleteObjectLocatorType;
679 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
681 llvm::StructType *CatchableTypeType;
682 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
683 llvm::StructType *ThrowInfoType;
688 CGCXXABI::RecordArgABI
689 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
690 switch (CGM.getTarget().getTriple().getArch()) {
692 // FIXME: Implement for other architectures.
695 case llvm::Triple::x86:
696 // All record arguments are passed in memory on x86. Decide whether to
697 // construct the object directly in argument memory, or to construct the
698 // argument elsewhere and copy the bytes during the call.
700 // If C++ prohibits us from making a copy, construct the arguments directly
701 // into argument memory.
702 if (!canCopyArgument(RD))
703 return RAA_DirectInMemory;
705 // Otherwise, construct the argument into a temporary and copy the bytes
706 // into the outgoing argument memory.
709 case llvm::Triple::x86_64:
710 // Win64 passes objects with non-trivial copy ctors indirectly.
711 if (RD->hasNonTrivialCopyConstructor())
714 // If an object has a destructor, we'd really like to pass it indirectly
715 // because it allows us to elide copies. Unfortunately, MSVC makes that
716 // impossible for small types, which it will pass in a single register or
717 // stack slot. Most objects with dtors are large-ish, so handle that early.
718 // We can't call out all large objects as being indirect because there are
719 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
720 // how we pass large POD types.
721 if (RD->hasNonTrivialDestructor() &&
722 getContext().getTypeSize(RD->getTypeForDecl()) > 64)
725 // We have a trivial copy constructor or no copy constructors, but we have
726 // to make sure it isn't deleted.
727 bool CopyDeleted = false;
728 for (const CXXConstructorDecl *CD : RD->ctors()) {
729 if (CD->isCopyConstructor()) {
730 assert(CD->isTrivial());
731 // We had at least one undeleted trivial copy ctor. Return directly.
732 if (!CD->isDeleted())
738 // The trivial copy constructor was deleted. Return indirectly.
742 // There were no copy ctors. Return in RAX.
746 llvm_unreachable("invalid enum");
749 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
750 const CXXDeleteExpr *DE,
752 QualType ElementType,
753 const CXXDestructorDecl *Dtor) {
754 // FIXME: Provide a source location here even though there's no
755 // CXXMemberCallExpr for dtor call.
756 bool UseGlobalDelete = DE->isGlobalDelete();
757 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
758 llvm::Value *MDThis =
759 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
761 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
764 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
765 llvm::Value *Args[] = {
766 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
767 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
768 auto *Fn = getThrowFn();
770 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
772 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
776 struct CallEndCatchMSVC : EHScopeStack::Cleanup {
777 CallEndCatchMSVC() {}
778 void Emit(CodeGenFunction &CGF, Flags flags) override {
779 CGF.EmitNounwindRuntimeCall(
780 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_endcatch));
785 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
786 const CXXCatchStmt *S) {
787 // In the MS ABI, the runtime handles the copy, and the catch handler is
788 // responsible for destruction.
789 VarDecl *CatchParam = S->getExceptionDecl();
790 llvm::Value *Exn = CGF.getExceptionFromSlot();
791 llvm::Function *BeginCatch =
792 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_begincatch);
795 llvm::Value *Args[2] = {Exn, llvm::Constant::getNullValue(CGF.Int8PtrTy)};
796 CGF.EmitNounwindRuntimeCall(BeginCatch, Args);
797 CGF.EHStack.pushCleanup<CallEndCatchMSVC>(NormalAndEHCleanup);
801 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
802 llvm::Value *ParamAddr =
803 CGF.Builder.CreateBitCast(var.getObjectAddress(CGF), CGF.Int8PtrTy);
804 llvm::Value *Args[2] = {Exn, ParamAddr};
805 CGF.EmitNounwindRuntimeCall(BeginCatch, Args);
806 // FIXME: Do we really need exceptional endcatch cleanups?
807 CGF.EHStack.pushCleanup<CallEndCatchMSVC>(NormalAndEHCleanup);
808 CGF.EmitAutoVarCleanups(var);
811 std::pair<llvm::Value *, llvm::Value *>
812 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value,
813 QualType SrcRecordTy) {
814 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
815 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
816 const ASTContext &Context = CGF.getContext();
818 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
819 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
821 // Perform a base adjustment.
822 const CXXBaseSpecifier *PolymorphicBase = std::find_if(
823 SrcDecl->vbases_begin(), SrcDecl->vbases_end(),
824 [&](const CXXBaseSpecifier &Base) {
825 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
826 return Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr();
828 llvm::Value *Offset = GetVirtualBaseClassOffset(
829 CGF, Value, SrcDecl, PolymorphicBase->getType()->getAsCXXRecordDecl());
830 Value = CGF.Builder.CreateInBoundsGEP(Value, Offset);
831 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
832 return std::make_pair(Value, Offset);
835 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
836 QualType SrcRecordTy) {
837 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
839 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
842 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
843 llvm::Value *Argument) {
844 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
845 llvm::FunctionType *FTy =
846 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
847 llvm::Value *Args[] = {Argument};
848 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
849 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
852 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
853 llvm::CallSite Call =
854 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
855 Call.setDoesNotReturn();
856 CGF.Builder.CreateUnreachable();
859 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
860 QualType SrcRecordTy,
861 llvm::Value *ThisPtr,
862 llvm::Type *StdTypeInfoPtrTy) {
864 std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
865 return CGF.Builder.CreateBitCast(
866 emitRTtypeidCall(CGF, ThisPtr).getInstruction(), StdTypeInfoPtrTy);
869 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
870 QualType SrcRecordTy) {
871 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
873 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
876 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
877 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
878 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
879 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
881 llvm::Value *SrcRTTI =
882 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
883 llvm::Value *DestRTTI =
884 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
887 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
889 // PVOID __RTDynamicCast(
895 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
896 CGF.Int8PtrTy, CGF.Int32Ty};
897 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
898 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
900 llvm::Value *Args[] = {
901 Value, Offset, SrcRTTI, DestRTTI,
902 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
903 Value = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
904 return CGF.Builder.CreateBitCast(Value, DestLTy);
908 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
909 QualType SrcRecordTy,
912 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
914 // PVOID __RTCastToVoid(
916 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
917 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
918 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
920 llvm::Value *Args[] = {Value};
921 return CGF.EmitRuntimeCall(Function, Args);
924 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
928 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
929 CodeGenFunction &CGF, llvm::Value *This, const CXXRecordDecl *ClassDecl,
930 const CXXRecordDecl *BaseClassDecl) {
932 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
933 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
934 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
935 CharUnits VBTableChars =
937 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
938 llvm::Value *VBTableOffset =
939 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
941 llvm::Value *VBPtrToNewBase =
942 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
944 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
945 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
948 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
949 return isa<CXXConstructorDecl>(GD.getDecl());
952 static bool isDeletingDtor(GlobalDecl GD) {
953 return isa<CXXDestructorDecl>(GD.getDecl()) &&
954 GD.getDtorType() == Dtor_Deleting;
957 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
958 return isDeletingDtor(GD);
961 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
962 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
966 if (FI.isInstanceMethod()) {
967 // If it's an instance method, aggregates are always returned indirectly via
968 // the second parameter.
969 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
970 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
972 } else if (!RD->isPOD()) {
973 // If it's a free function, non-POD types are returned indirectly.
974 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
978 // Otherwise, use the C ABI rules.
983 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
984 const CXXRecordDecl *RD) {
985 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
986 assert(IsMostDerivedClass &&
987 "ctor for a class with virtual bases must have an implicit parameter");
988 llvm::Value *IsCompleteObject =
989 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
991 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
992 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
993 CGF.Builder.CreateCondBr(IsCompleteObject,
994 CallVbaseCtorsBB, SkipVbaseCtorsBB);
996 CGF.EmitBlock(CallVbaseCtorsBB);
998 // Fill in the vbtable pointers here.
999 EmitVBPtrStores(CGF, RD);
1001 // CGF will put the base ctor calls in this basic block for us later.
1003 return SkipVbaseCtorsBB;
1006 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1007 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1008 // In most cases, an override for a vbase virtual method can adjust
1009 // the "this" parameter by applying a constant offset.
1010 // However, this is not enough while a constructor or a destructor of some
1011 // class X is being executed if all the following conditions are met:
1012 // - X has virtual bases, (1)
1013 // - X overrides a virtual method M of a vbase Y, (2)
1014 // - X itself is a vbase of the most derived class.
1016 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1017 // which holds the extra amount of "this" adjustment we must do when we use
1018 // the X vftables (i.e. during X ctor or dtor).
1019 // Outside the ctors and dtors, the values of vtorDisps are zero.
1021 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1022 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1023 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1024 CGBuilderTy &Builder = CGF.Builder;
1027 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
1028 llvm::Value *Int8This = nullptr; // Initialize lazily.
1030 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
1032 if (!I->second.hasVtorDisp())
1035 llvm::Value *VBaseOffset =
1036 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
1037 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
1038 // just to Trunc back immediately.
1039 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
1040 uint64_t ConstantVBaseOffset =
1041 Layout.getVBaseClassOffset(I->first).getQuantity();
1043 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1044 llvm::Value *VtorDispValue = Builder.CreateSub(
1045 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
1049 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1050 CGF.Int8Ty->getPointerTo(AS));
1051 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
1052 // vtorDisp is always the 32-bits before the vbase in the class layout.
1053 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1054 VtorDispPtr = Builder.CreateBitCast(
1055 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1057 Builder.CreateStore(VtorDispValue, VtorDispPtr);
1061 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1062 // There's only one constructor type in this ABI.
1063 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1066 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1067 const CXXRecordDecl *RD) {
1068 llvm::Value *ThisInt8Ptr =
1069 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
1070 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1072 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1073 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1074 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1075 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1076 const ASTRecordLayout &SubobjectLayout =
1077 CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr);
1078 CharUnits Offs = VBT->NonVirtualOffset;
1079 Offs += SubobjectLayout.getVBPtrOffset();
1080 if (VBT->getVBaseWithVPtr())
1081 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1082 llvm::Value *VBPtr =
1083 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
1084 llvm::Value *GVPtr = CGF.Builder.CreateConstInBoundsGEP2_32(GV, 0, 0);
1085 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GVPtr->getType()->getPointerTo(0),
1086 "vbptr." + VBT->ReusingBase->getName());
1087 CGF.Builder.CreateStore(GVPtr, VBPtr);
1092 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1093 SmallVectorImpl<CanQualType> &ArgTys) {
1094 // TODO: 'for base' flag
1095 if (T == StructorType::Deleting) {
1096 // The scalar deleting destructor takes an implicit int parameter.
1097 ArgTys.push_back(CGM.getContext().IntTy);
1099 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
1103 // All parameters are already in place except is_most_derived, which goes
1104 // after 'this' if it's variadic and last if it's not.
1106 const CXXRecordDecl *Class = CD->getParent();
1107 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1108 if (Class->getNumVBases()) {
1109 if (FPT->isVariadic())
1110 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
1112 ArgTys.push_back(CGM.getContext().IntTy);
1116 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1117 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1118 // other destructor variants are delegating thunks.
1119 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1123 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1124 GD = GD.getCanonicalDecl();
1125 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1127 GlobalDecl LookupGD = GD;
1128 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1129 // Complete destructors take a pointer to the complete object as a
1130 // parameter, thus don't need this adjustment.
1131 if (GD.getDtorType() == Dtor_Complete)
1134 // There's no Dtor_Base in vftable but it shares the this adjustment with
1135 // the deleting one, so look it up instead.
1136 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1139 MicrosoftVTableContext::MethodVFTableLocation ML =
1140 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1141 CharUnits Adjustment = ML.VFPtrOffset;
1143 // Normal virtual instance methods need to adjust from the vfptr that first
1144 // defined the virtual method to the virtual base subobject, but destructors
1145 // do not. The vector deleting destructor thunk applies this adjustment for
1147 if (isa<CXXDestructorDecl>(MD))
1148 Adjustment = CharUnits::Zero();
1151 const ASTRecordLayout &DerivedLayout =
1152 CGM.getContext().getASTRecordLayout(MD->getParent());
1153 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1159 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1160 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) {
1162 // If the call of a virtual function is not virtual, we just have to
1163 // compensate for the adjustment the virtual function does in its prologue.
1164 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1165 if (Adjustment.isZero())
1168 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1169 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1170 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1171 assert(Adjustment.isPositive());
1172 return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity());
1175 GD = GD.getCanonicalDecl();
1176 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1178 GlobalDecl LookupGD = GD;
1179 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1180 // Complete dtors take a pointer to the complete object,
1181 // thus don't need adjustment.
1182 if (GD.getDtorType() == Dtor_Complete)
1185 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1186 // with the base one, so look up the deleting one instead.
1187 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1189 MicrosoftVTableContext::MethodVFTableLocation ML =
1190 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1192 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1193 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1194 CharUnits StaticOffset = ML.VFPtrOffset;
1196 // Base destructors expect 'this' to point to the beginning of the base
1197 // subobject, not the first vfptr that happens to contain the virtual dtor.
1198 // However, we still need to apply the virtual base adjustment.
1199 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1200 StaticOffset = CharUnits::Zero();
1203 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1204 llvm::Value *VBaseOffset =
1205 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
1206 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
1208 if (!StaticOffset.isZero()) {
1209 assert(StaticOffset.isPositive());
1210 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1212 // Non-virtual adjustment might result in a pointer outside the allocated
1213 // object, e.g. if the final overrider class is laid out after the virtual
1214 // base that declares a method in the most derived class.
1215 // FIXME: Update the code that emits this adjustment in thunks prologues.
1216 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
1218 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
1219 StaticOffset.getQuantity());
1225 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1227 FunctionArgList &Params) {
1228 ASTContext &Context = getContext();
1229 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1230 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1231 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1232 ImplicitParamDecl *IsMostDerived
1233 = ImplicitParamDecl::Create(Context, nullptr,
1234 CGF.CurGD.getDecl()->getLocation(),
1235 &Context.Idents.get("is_most_derived"),
1237 // The 'most_derived' parameter goes second if the ctor is variadic and last
1238 // if it's not. Dtors can't be variadic.
1239 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1240 if (FPT->isVariadic())
1241 Params.insert(Params.begin() + 1, IsMostDerived);
1243 Params.push_back(IsMostDerived);
1244 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1245 } else if (isDeletingDtor(CGF.CurGD)) {
1246 ImplicitParamDecl *ShouldDelete
1247 = ImplicitParamDecl::Create(Context, nullptr,
1248 CGF.CurGD.getDecl()->getLocation(),
1249 &Context.Idents.get("should_call_delete"),
1251 Params.push_back(ShouldDelete);
1252 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1256 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1257 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1258 // In this ABI, every virtual function takes a pointer to one of the
1259 // subobjects that first defines it as the 'this' parameter, rather than a
1260 // pointer to the final overrider subobject. Thus, we need to adjust it back
1261 // to the final overrider subobject before use.
1262 // See comments in the MicrosoftVFTableContext implementation for the details.
1263 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1264 if (Adjustment.isZero())
1267 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1268 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1269 *thisTy = This->getType();
1271 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1272 assert(Adjustment.isPositive());
1274 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
1275 return CGF.Builder.CreateBitCast(This, thisTy);
1278 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1281 /// If this is a function that the ABI specifies returns 'this', initialize
1282 /// the return slot to 'this' at the start of the function.
1284 /// Unlike the setting of return types, this is done within the ABI
1285 /// implementation instead of by clients of CGCXXABI because:
1286 /// 1) getThisValue is currently protected
1287 /// 2) in theory, an ABI could implement 'this' returns some other way;
1288 /// HasThisReturn only specifies a contract, not the implementation
1289 if (HasThisReturn(CGF.CurGD))
1290 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1291 else if (hasMostDerivedReturn(CGF.CurGD))
1292 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1295 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1296 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1297 assert(getStructorImplicitParamDecl(CGF) &&
1298 "no implicit parameter for a constructor with virtual bases?");
1299 getStructorImplicitParamValue(CGF)
1300 = CGF.Builder.CreateLoad(
1301 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1305 if (isDeletingDtor(CGF.CurGD)) {
1306 assert(getStructorImplicitParamDecl(CGF) &&
1307 "no implicit parameter for a deleting destructor?");
1308 getStructorImplicitParamValue(CGF)
1309 = CGF.Builder.CreateLoad(
1310 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1311 "should_call_delete");
1315 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
1316 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1317 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1318 assert(Type == Ctor_Complete || Type == Ctor_Base);
1320 // Check if we need a 'most_derived' parameter.
1321 if (!D->getParent()->getNumVBases())
1324 // Add the 'most_derived' argument second if we are variadic or last if not.
1325 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1326 llvm::Value *MostDerivedArg =
1327 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1328 RValue RV = RValue::get(MostDerivedArg);
1329 if (MostDerivedArg) {
1330 if (FPT->isVariadic())
1331 Args.insert(Args.begin() + 1,
1332 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1334 Args.add(RV, getContext().IntTy);
1337 return 1; // Added one arg.
1340 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1341 const CXXDestructorDecl *DD,
1342 CXXDtorType Type, bool ForVirtualBase,
1343 bool Delegating, llvm::Value *This) {
1344 llvm::Value *Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
1346 if (DD->isVirtual()) {
1347 assert(Type != CXXDtorType::Dtor_Deleting &&
1348 "The deleting destructor should only be called via a virtual call");
1349 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1353 CGF.EmitCXXStructorCall(DD, Callee, ReturnValueSlot(), This,
1354 /*ImplicitParam=*/nullptr,
1355 /*ImplicitParamTy=*/QualType(), nullptr,
1356 getFromDtorType(Type));
1359 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1360 const CXXRecordDecl *RD) {
1361 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1362 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1364 for (VPtrInfo *Info : VFPtrs) {
1365 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1366 if (VTable->hasInitializer())
1369 llvm::Constant *RTTI = getContext().getLangOpts().RTTIData
1370 ? getMSCompleteObjectLocator(RD, Info)
1373 const VTableLayout &VTLayout =
1374 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1375 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1376 RD, VTLayout.vtable_component_begin(),
1377 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
1378 VTLayout.getNumVTableThunks(), RTTI);
1380 VTable->setInitializer(Init);
1384 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1385 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1386 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1387 NeedsVirtualOffset = (NearestVBase != nullptr);
1389 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1390 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1391 llvm::GlobalValue *VTableAddressPoint = VFTablesMap[ID];
1392 if (!VTableAddressPoint) {
1393 assert(Base.getBase()->getNumVBases() &&
1394 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1396 return VTableAddressPoint;
1399 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1400 const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
1401 SmallString<256> &Name) {
1402 llvm::raw_svector_ostream Out(Name);
1403 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
1406 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1407 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1408 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1409 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1410 llvm::GlobalValue *VFTable = VFTablesMap[ID];
1411 assert(VFTable && "Couldn't find a vftable for the given base?");
1415 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1416 CharUnits VPtrOffset) {
1417 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1418 // shouldn't be used in the given record type. We want to cache this result in
1419 // VFTablesMap, thus a simple zero check is not sufficient.
1420 VFTableIdTy ID(RD, VPtrOffset);
1421 VTablesMapTy::iterator I;
1423 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1427 llvm::GlobalVariable *&VTable = I->second;
1429 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1430 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1432 if (DeferredVFTables.insert(RD).second) {
1433 // We haven't processed this record type before.
1434 // Queue up this v-table for possible deferred emission.
1435 CGM.addDeferredVTable(RD);
1438 // Create all the vftables at once in order to make sure each vftable has
1439 // a unique mangled name.
1440 llvm::StringSet<> ObservedMangledNames;
1441 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1442 SmallString<256> Name;
1443 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
1444 if (!ObservedMangledNames.insert(Name.str()).second)
1445 llvm_unreachable("Already saw this mangling before?");
1450 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1451 if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset)
1453 SmallString<256> VFTableName;
1454 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], VFTableName);
1455 StringRef VTableName = VFTableName;
1457 uint64_t NumVTableSlots =
1458 VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC)
1459 .getNumVTableComponents();
1460 llvm::GlobalValue::LinkageTypes VTableLinkage =
1461 llvm::GlobalValue::ExternalLinkage;
1462 llvm::ArrayType *VTableType =
1463 llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots);
1464 if (getContext().getLangOpts().RTTIData) {
1465 VTableLinkage = llvm::GlobalValue::PrivateLinkage;
1469 VTable = CGM.getModule().getNamedGlobal(VFTableName);
1471 // Create a backing variable for the contents of VTable. The VTable may
1472 // or may not include space for a pointer to RTTI data.
1473 llvm::GlobalValue *VFTable = VTable = new llvm::GlobalVariable(
1474 CGM.getModule(), VTableType, /*isConstant=*/true, VTableLinkage,
1475 /*Initializer=*/nullptr, VTableName);
1476 VTable->setUnnamedAddr(true);
1478 // Only insert a pointer into the VFTable for RTTI data if we are not
1479 // importing it. We never reference the RTTI data directly so there is no
1480 // need to make room for it.
1481 if (getContext().getLangOpts().RTTIData &&
1482 !RD->hasAttr<DLLImportAttr>()) {
1483 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
1484 llvm::ConstantInt::get(CGM.IntTy, 1)};
1485 // Create a GEP which points just after the first entry in the VFTable,
1486 // this should be the location of the first virtual method.
1487 llvm::Constant *VTableGEP =
1488 llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, GEPIndices);
1489 // The symbol for the VFTable is an alias to the GEP. It is
1490 // transparent, to other modules, what the nature of this symbol is; all
1491 // that matters is that the alias be the address of the first virtual
1493 VFTable = llvm::GlobalAlias::create(
1494 cast<llvm::SequentialType>(VTableGEP->getType())->getElementType(),
1495 /*AddressSpace=*/0, llvm::GlobalValue::ExternalLinkage,
1496 VFTableName.str(), VTableGEP, &CGM.getModule());
1498 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1499 // be referencing any RTTI data. The GlobalVariable will end up being
1500 // an appropriate definition of the VFTable.
1501 VTable->setName(VFTableName.str());
1504 VFTable->setUnnamedAddr(true);
1505 if (RD->hasAttr<DLLImportAttr>())
1506 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1507 else if (RD->hasAttr<DLLExportAttr>())
1508 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1510 llvm::GlobalValue::LinkageTypes VFTableLinkage = CGM.getVTableLinkage(RD);
1511 if (VFTable != VTable) {
1512 if (llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage)) {
1513 // AvailableExternally implies that we grabbed the data from another
1514 // executable. No need to stick the alias in a Comdat.
1515 } else if (llvm::GlobalValue::isInternalLinkage(VFTableLinkage) ||
1516 llvm::GlobalValue::isWeakODRLinkage(VFTableLinkage) ||
1517 llvm::GlobalValue::isLinkOnceODRLinkage(VFTableLinkage)) {
1518 // The alias is going to be dropped into a Comdat, no need to make it
1520 if (!llvm::GlobalValue::isInternalLinkage(VFTableLinkage))
1521 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1523 CGM.getModule().getOrInsertComdat(VFTable->getName());
1524 // We must indicate which VFTable is larger to support linking between
1525 // translation units which do and do not have RTTI data. The largest
1526 // VFTable contains the RTTI data; translation units which reference
1527 // the smaller VFTable always reference it relative to the first
1529 C->setSelectionKind(llvm::Comdat::Largest);
1530 VTable->setComdat(C);
1532 llvm_unreachable("unexpected linkage for vftable!");
1535 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage))
1537 CGM.getModule().getOrInsertComdat(VTable->getName()));
1539 VFTable->setLinkage(VFTableLinkage);
1540 CGM.setGlobalVisibility(VFTable, RD);
1541 VFTablesMap[ID] = VFTable;
1549 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1553 GD = GD.getCanonicalDecl();
1554 CGBuilderTy &Builder = CGF.Builder;
1556 Ty = Ty->getPointerTo()->getPointerTo();
1558 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1559 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
1561 MicrosoftVTableContext::MethodVFTableLocation ML =
1562 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1563 llvm::Value *VFuncPtr =
1564 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1565 return Builder.CreateLoad(VFuncPtr);
1568 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1569 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1570 llvm::Value *This, const CXXMemberCallExpr *CE) {
1571 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1572 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1574 // We have only one destructor in the vftable but can get both behaviors
1575 // by passing an implicit int parameter.
1576 GlobalDecl GD(Dtor, Dtor_Deleting);
1577 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1578 Dtor, StructorType::Deleting);
1579 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1580 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
1582 ASTContext &Context = CGF.getContext();
1583 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1584 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1585 DtorType == Dtor_Deleting);
1587 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1588 RValue RV = CGF.EmitCXXStructorCall(Dtor, Callee, ReturnValueSlot(), This,
1589 ImplicitParam, Context.IntTy, CE,
1590 StructorType::Deleting);
1591 return RV.getScalarVal();
1594 const VBTableGlobals &
1595 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1596 // At this layer, we can key the cache off of a single class, which is much
1597 // easier than caching each vbtable individually.
1598 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1600 std::tie(Entry, Added) =
1601 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1602 VBTableGlobals &VBGlobals = Entry->second;
1606 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1607 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1609 // Cache the globals for all vbtables so we don't have to recompute the
1611 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1612 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1613 E = VBGlobals.VBTables->end();
1615 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1621 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1622 const CXXMethodDecl *MD,
1623 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1624 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1625 "can't form pointers to ctors or virtual dtors");
1627 // Calculate the mangled name.
1628 SmallString<256> ThunkName;
1629 llvm::raw_svector_ostream Out(ThunkName);
1630 getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1633 // If the thunk has been generated previously, just return it.
1634 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1635 return cast<llvm::Function>(GV);
1637 // Create the llvm::Function.
1638 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD);
1639 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1640 llvm::Function *ThunkFn =
1641 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1642 ThunkName.str(), &CGM.getModule());
1643 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1645 ThunkFn->setLinkage(MD->isExternallyVisible()
1646 ? llvm::GlobalValue::LinkOnceODRLinkage
1647 : llvm::GlobalValue::InternalLinkage);
1648 if (MD->isExternallyVisible())
1649 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
1651 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1652 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1654 // Add the "thunk" attribute so that LLVM knows that the return type is
1655 // meaningless. These thunks can be used to call functions with differing
1656 // return types, and the caller is required to cast the prototype
1657 // appropriately to extract the correct value.
1658 ThunkFn->addFnAttr("thunk");
1660 // These thunks can be compared, so they are not unnamed.
1661 ThunkFn->setUnnamedAddr(false);
1664 CodeGenFunction CGF(CGM);
1665 CGF.CurGD = GlobalDecl(MD);
1666 CGF.CurFuncIsThunk = true;
1668 // Build FunctionArgs, but only include the implicit 'this' parameter
1670 FunctionArgList FunctionArgs;
1671 buildThisParam(CGF, FunctionArgs);
1673 // Start defining the function.
1674 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
1675 FunctionArgs, MD->getLocation(), SourceLocation());
1678 // Load the vfptr and then callee from the vftable. The callee should have
1679 // adjusted 'this' so that the vfptr is at offset zero.
1680 llvm::Value *VTable = CGF.GetVTablePtr(
1681 getThisValue(CGF), ThunkTy->getPointerTo()->getPointerTo());
1682 llvm::Value *VFuncPtr =
1683 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1684 llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr);
1686 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee);
1691 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1692 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1693 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1694 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1695 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1696 if (GV->isDeclaration())
1697 emitVBTableDefinition(*VBT, RD, GV);
1701 llvm::GlobalVariable *
1702 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1703 llvm::GlobalVariable::LinkageTypes Linkage) {
1704 SmallString<256> OutName;
1705 llvm::raw_svector_ostream Out(OutName);
1706 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1708 StringRef Name = OutName.str();
1710 llvm::ArrayType *VBTableType =
1711 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1713 assert(!CGM.getModule().getNamedGlobal(Name) &&
1714 "vbtable with this name already exists: mangling bug?");
1715 llvm::GlobalVariable *GV =
1716 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1717 GV->setUnnamedAddr(true);
1719 if (RD->hasAttr<DLLImportAttr>())
1720 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1721 else if (RD->hasAttr<DLLExportAttr>())
1722 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1724 if (!GV->hasExternalLinkage())
1725 emitVBTableDefinition(VBT, RD, GV);
1730 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
1731 const CXXRecordDecl *RD,
1732 llvm::GlobalVariable *GV) const {
1733 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1735 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1736 "should only emit vbtables for classes with vbtables");
1738 const ASTRecordLayout &BaseLayout =
1739 CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr);
1740 const ASTRecordLayout &DerivedLayout =
1741 CGM.getContext().getASTRecordLayout(RD);
1743 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(),
1746 // The offset from ReusingBase's vbptr to itself always leads.
1747 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1748 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1750 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1751 for (const auto &I : ReusingBase->vbases()) {
1752 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
1753 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1754 assert(!Offset.isNegative());
1756 // Make it relative to the subobject vbptr.
1757 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1758 if (VBT.getVBaseWithVPtr())
1759 CompleteVBPtrOffset +=
1760 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
1761 Offset -= CompleteVBPtrOffset;
1763 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1764 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
1765 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1768 assert(Offsets.size() ==
1769 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1770 ->getElementType())->getNumElements());
1771 llvm::ArrayType *VBTableType =
1772 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1773 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1774 GV->setInitializer(Init);
1776 // Set the right visibility.
1777 CGM.setGlobalVisibility(GV, RD);
1780 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1782 const ThisAdjustment &TA) {
1786 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1788 if (!TA.Virtual.isEmpty()) {
1789 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1790 // Adjust the this argument based on the vtordisp value.
1791 llvm::Value *VtorDispPtr =
1792 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1794 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1795 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1796 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1798 if (TA.Virtual.Microsoft.VBPtrOffset) {
1799 // If the final overrider is defined in a virtual base other than the one
1800 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1801 // the vbtable of the derived class.
1802 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1803 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1805 llvm::Value *VBaseOffset =
1806 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1807 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1808 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1812 if (TA.NonVirtual) {
1813 // Non-virtual adjustment might result in a pointer outside the allocated
1814 // object, e.g. if the final overrider class is laid out after the virtual
1815 // base that declares a method in the most derived class.
1816 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1819 // Don't need to bitcast back, the call CodeGen will handle this.
1824 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1825 const ReturnAdjustment &RA) {
1829 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1831 if (RA.Virtual.Microsoft.VBIndex) {
1832 assert(RA.Virtual.Microsoft.VBIndex > 0);
1834 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1836 llvm::Value *VBaseOffset =
1837 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1838 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1839 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1843 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1845 // Cast back to the original type.
1846 return CGF.Builder.CreateBitCast(V, Ret->getType());
1849 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1850 QualType elementType) {
1851 // Microsoft seems to completely ignore the possibility of a
1852 // two-argument usual deallocation function.
1853 return elementType.isDestructedType();
1856 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1857 // Microsoft seems to completely ignore the possibility of a
1858 // two-argument usual deallocation function.
1859 return expr->getAllocatedType().isDestructedType();
1862 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1863 // The array cookie is always a size_t; we then pad that out to the
1864 // alignment of the element type.
1865 ASTContext &Ctx = getContext();
1866 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1867 Ctx.getTypeAlignInChars(type));
1870 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1871 llvm::Value *allocPtr,
1872 CharUnits cookieSize) {
1873 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1874 llvm::Value *numElementsPtr =
1875 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1876 return CGF.Builder.CreateLoad(numElementsPtr);
1879 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1880 llvm::Value *newPtr,
1881 llvm::Value *numElements,
1882 const CXXNewExpr *expr,
1883 QualType elementType) {
1884 assert(requiresArrayCookie(expr));
1886 // The size of the cookie.
1887 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1889 // Compute an offset to the cookie.
1890 llvm::Value *cookiePtr = newPtr;
1892 // Write the number of elements into the appropriate slot.
1893 unsigned AS = newPtr->getType()->getPointerAddressSpace();
1894 llvm::Value *numElementsPtr
1895 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1896 CGF.Builder.CreateStore(numElements, numElementsPtr);
1898 // Finally, compute a pointer to the actual data buffer by skipping
1899 // over the cookie completely.
1900 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1901 cookieSize.getQuantity());
1904 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
1905 llvm::Constant *Dtor,
1906 llvm::Constant *Addr) {
1907 // Create a function which calls the destructor.
1908 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
1910 // extern "C" int __tlregdtor(void (*f)(void));
1911 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
1912 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
1914 llvm::Constant *TLRegDtor =
1915 CGF.CGM.CreateRuntimeFunction(TLRegDtorTy, "__tlregdtor");
1916 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor))
1917 TLRegDtorFn->setDoesNotThrow();
1919 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
1922 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
1923 llvm::Constant *Dtor,
1924 llvm::Constant *Addr) {
1926 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
1928 // The default behavior is to use atexit.
1929 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
1932 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
1934 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
1936 ArrayRef<llvm::Function *> CXXThreadLocalInits,
1937 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
1938 // This will create a GV in the .CRT$XDU section. It will point to our
1939 // initialization function. The CRT will call all of these function
1940 // pointers at start-up time and, eventually, at thread-creation time.
1941 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
1942 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
1943 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
1944 llvm::GlobalVariable::InternalLinkage, InitFunc,
1945 Twine(InitFunc->getName(), "$initializer$"));
1946 InitFuncPtr->setSection(".CRT$XDU");
1947 // This variable has discardable linkage, we have to add it to @llvm.used to
1948 // ensure it won't get discarded.
1949 CGM.addUsedGlobal(InitFuncPtr);
1953 std::vector<llvm::Function *> NonComdatInits;
1954 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
1955 llvm::GlobalVariable *GV = CXXThreadLocalInitVars[I];
1956 llvm::Function *F = CXXThreadLocalInits[I];
1958 // If the GV is already in a comdat group, then we have to join it.
1959 if (llvm::Comdat *C = GV->getComdat())
1960 AddToXDU(F)->setComdat(C);
1962 NonComdatInits.push_back(F);
1965 if (!NonComdatInits.empty()) {
1966 llvm::FunctionType *FTy =
1967 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1968 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
1969 FTy, "__tls_init", SourceLocation(),
1971 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
1977 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1979 QualType LValType) {
1980 CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
1984 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
1985 llvm::GlobalVariable *GV,
1987 // MSVC only uses guards for static locals.
1988 if (!D.isStaticLocal()) {
1989 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
1990 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
1991 llvm::Function *F = CGF.CurFn;
1992 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
1993 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
1994 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1998 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1999 // threadsafe. Since the user may be linking in inline functions compiled by
2000 // cl.exe, there's no reason to provide a false sense of security by using
2001 // critical sections here.
2004 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
2006 CGBuilderTy &Builder = CGF.Builder;
2007 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2008 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2010 // Get the guard variable for this function if we have one already.
2011 GuardInfo *GI = &GuardVariableMap[D.getDeclContext()];
2014 if (D.isStaticLocal() && D.isExternallyVisible()) {
2015 // Externally visible variables have to be numbered in Sema to properly
2016 // handle unreachable VarDecls.
2017 BitIndex = getContext().getStaticLocalNumber(&D);
2018 assert(BitIndex > 0);
2021 // Non-externally visible variables are numbered here in CodeGen.
2022 BitIndex = GI->BitIndex++;
2025 if (BitIndex >= 32) {
2026 if (D.isExternallyVisible())
2027 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2029 GI->Guard = nullptr;
2032 // Lazily create the i32 bitfield for this function.
2034 // Mangle the name for the guard.
2035 SmallString<256> GuardName;
2037 llvm::raw_svector_ostream Out(GuardName);
2038 getMangleContext().mangleStaticGuardVariable(&D, Out);
2042 // Create the guard variable with a zero-initializer. Just absorb linkage,
2043 // visibility and dll storage class from the guarded variable.
2045 new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
2046 GV->getLinkage(), Zero, GuardName.str());
2047 GI->Guard->setVisibility(GV->getVisibility());
2048 GI->Guard->setDLLStorageClass(GV->getDLLStorageClass());
2049 if (GI->Guard->isWeakForLinker())
2050 GI->Guard->setComdat(
2051 CGM.getModule().getOrInsertComdat(GI->Guard->getName()));
2053 assert(GI->Guard->getLinkage() == GV->getLinkage() &&
2054 "static local from the same function had different linkage");
2057 // Pseudo code for the test:
2058 // if (!(GuardVar & MyGuardBit)) {
2059 // GuardVar |= MyGuardBit;
2060 // ... initialize the object ...;
2063 // Test our bit from the guard variable.
2064 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
2065 llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard);
2066 llvm::Value *IsInitialized =
2067 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
2068 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2069 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2070 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
2072 // Set our bit in the guard variable and emit the initializer and add a global
2073 // destructor if appropriate.
2074 CGF.EmitBlock(InitBlock);
2075 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard);
2076 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2077 Builder.CreateBr(EndBlock);
2080 CGF.EmitBlock(EndBlock);
2083 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2084 // Null-ness for function memptrs only depends on the first field, which is
2085 // the function pointer. The rest don't matter, so we can zero initialize.
2086 if (MPT->isMemberFunctionPointer())
2089 // The virtual base adjustment field is always -1 for null, so if we have one
2090 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2091 // valid field offset.
2092 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2093 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2094 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
2095 RD->nullFieldOffsetIsZero());
2099 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2100 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2101 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2102 llvm::SmallVector<llvm::Type *, 4> fields;
2103 if (MPT->isMemberFunctionPointer())
2104 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2106 fields.push_back(CGM.IntTy); // FieldOffset
2108 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2110 fields.push_back(CGM.IntTy);
2111 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2112 fields.push_back(CGM.IntTy);
2113 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2114 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2116 if (fields.size() == 1)
2118 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2121 void MicrosoftCXXABI::
2122 GetNullMemberPointerFields(const MemberPointerType *MPT,
2123 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2124 assert(fields.empty());
2125 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2126 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2127 if (MPT->isMemberFunctionPointer()) {
2128 // FunctionPointerOrVirtualThunk
2129 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2131 if (RD->nullFieldOffsetIsZero())
2132 fields.push_back(getZeroInt()); // FieldOffset
2134 fields.push_back(getAllOnesInt()); // FieldOffset
2137 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2139 fields.push_back(getZeroInt());
2140 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2141 fields.push_back(getZeroInt());
2142 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2143 fields.push_back(getAllOnesInt());
2147 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2148 llvm::SmallVector<llvm::Constant *, 4> fields;
2149 GetNullMemberPointerFields(MPT, fields);
2150 if (fields.size() == 1)
2152 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2153 assert(Res->getType() == ConvertMemberPointerType(MPT));
2158 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2159 bool IsMemberFunction,
2160 const CXXRecordDecl *RD,
2161 CharUnits NonVirtualBaseAdjustment)
2163 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2165 // Single inheritance class member pointer are represented as scalars instead
2167 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2170 llvm::SmallVector<llvm::Constant *, 4> fields;
2171 fields.push_back(FirstField);
2173 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2174 fields.push_back(llvm::ConstantInt::get(
2175 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2177 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2178 CharUnits Offs = CharUnits::Zero();
2179 if (RD->getNumVBases())
2180 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2181 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2184 // The rest of the fields are adjusted by conversions to a more derived class.
2185 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2186 fields.push_back(getZeroInt());
2188 return llvm::ConstantStruct::getAnon(fields);
2192 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2194 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2195 llvm::Constant *FirstField =
2196 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2197 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2201 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
2202 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
2205 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2207 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
2208 const ValueDecl *MPD = MP.getMemberPointerDecl();
2210 return EmitNullMemberPointer(MPT);
2212 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
2214 // FIXME PR15713: Support virtual inheritance paths.
2216 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
2217 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
2220 CharUnits FieldOffset =
2221 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
2222 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
2226 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
2227 const CXXMethodDecl *MD,
2228 CharUnits NonVirtualBaseAdjustment) {
2229 assert(MD->isInstance() && "Member function must not be static!");
2230 MD = MD->getCanonicalDecl();
2231 RD = RD->getMostRecentDecl();
2232 CodeGenTypes &Types = CGM.getTypes();
2234 llvm::Constant *FirstField;
2235 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2236 if (!MD->isVirtual()) {
2238 // Check whether the function has a computable LLVM signature.
2239 if (Types.isFuncTypeConvertible(FPT)) {
2240 // The function has a computable LLVM signature; use the correct type.
2241 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2243 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2244 // function type is incomplete.
2247 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2248 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2250 MicrosoftVTableContext::MethodVFTableLocation ML =
2251 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
2252 if (!CGM.getTypes().isFuncTypeConvertible(
2253 MD->getType()->castAs<FunctionType>())) {
2254 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
2255 "incomplete return or parameter type");
2256 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2257 } else if (FPT->getCallConv() == CC_X86FastCall) {
2258 CGM.ErrorUnsupported(MD, "pointer to fastcall virtual member function");
2259 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2260 } else if (ML.VBase) {
2261 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
2262 "member function in virtual base class");
2263 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2265 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
2266 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
2267 // Include the vfptr adjustment if the method is in a non-primary vftable.
2268 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2272 // The rest of the fields are common with data member pointers.
2273 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2274 NonVirtualBaseAdjustment);
2277 /// Member pointers are the same if they're either bitwise identical *or* both
2278 /// null. Null-ness for function members is determined by the first field,
2279 /// while for data member pointers we must compare all fields.
2281 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2284 const MemberPointerType *MPT,
2286 CGBuilderTy &Builder = CGF.Builder;
2288 // Handle != comparisons by switching the sense of all boolean operations.
2289 llvm::ICmpInst::Predicate Eq;
2290 llvm::Instruction::BinaryOps And, Or;
2292 Eq = llvm::ICmpInst::ICMP_NE;
2293 And = llvm::Instruction::Or;
2294 Or = llvm::Instruction::And;
2296 Eq = llvm::ICmpInst::ICMP_EQ;
2297 And = llvm::Instruction::And;
2298 Or = llvm::Instruction::Or;
2301 // If this is a single field member pointer (single inheritance), this is a
2303 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2304 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2305 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2307 return Builder.CreateICmp(Eq, L, R);
2309 // Compare the first field.
2310 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2311 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2312 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2314 // Compare everything other than the first field.
2315 llvm::Value *Res = nullptr;
2316 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2317 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2318 llvm::Value *LF = Builder.CreateExtractValue(L, I);
2319 llvm::Value *RF = Builder.CreateExtractValue(R, I);
2320 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2322 Res = Builder.CreateBinOp(And, Res, Cmp);
2327 // Check if the first field is 0 if this is a function pointer.
2328 if (MPT->isMemberFunctionPointer()) {
2329 // (l1 == r1 && ...) || l0 == 0
2330 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2331 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2332 Res = Builder.CreateBinOp(Or, Res, IsZero);
2335 // Combine the comparison of the first field, which must always be true for
2336 // this comparison to succeeed.
2337 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2341 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2342 llvm::Value *MemPtr,
2343 const MemberPointerType *MPT) {
2344 CGBuilderTy &Builder = CGF.Builder;
2345 llvm::SmallVector<llvm::Constant *, 4> fields;
2346 // We only need one field for member functions.
2347 if (MPT->isMemberFunctionPointer())
2348 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2350 GetNullMemberPointerFields(MPT, fields);
2351 assert(!fields.empty());
2352 llvm::Value *FirstField = MemPtr;
2353 if (MemPtr->getType()->isStructTy())
2354 FirstField = Builder.CreateExtractValue(MemPtr, 0);
2355 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2357 // For function member pointers, we only need to test the function pointer
2358 // field. The other fields if any can be garbage.
2359 if (MPT->isMemberFunctionPointer())
2362 // Otherwise, emit a series of compares and combine the results.
2363 for (int I = 1, E = fields.size(); I < E; ++I) {
2364 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2365 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2366 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2371 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2372 llvm::Constant *Val) {
2373 // Function pointers are null if the pointer in the first field is null.
2374 if (MPT->isMemberFunctionPointer()) {
2375 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2376 Val->getAggregateElement(0U) : Val;
2377 return FirstField->isNullValue();
2380 // If it's not a function pointer and it's zero initializable, we can easily
2382 if (isZeroInitializable(MPT) && Val->isNullValue())
2385 // Otherwise, break down all the fields for comparison. Hopefully these
2386 // little Constants are reused, while a big null struct might not be.
2387 llvm::SmallVector<llvm::Constant *, 4> Fields;
2388 GetNullMemberPointerFields(MPT, Fields);
2389 if (Fields.size() == 1) {
2390 assert(Val->getType()->isIntegerTy());
2391 return Val == Fields[0];
2395 for (I = 0, E = Fields.size(); I != E; ++I) {
2396 if (Val->getAggregateElement(I) != Fields[I])
2403 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2405 llvm::Value *VBPtrOffset,
2406 llvm::Value *VBTableOffset,
2407 llvm::Value **VBPtrOut) {
2408 CGBuilderTy &Builder = CGF.Builder;
2409 // Load the vbtable pointer from the vbptr in the instance.
2410 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
2411 llvm::Value *VBPtr =
2412 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
2413 if (VBPtrOut) *VBPtrOut = VBPtr;
2414 VBPtr = Builder.CreateBitCast(VBPtr,
2415 CGM.Int32Ty->getPointerTo(0)->getPointerTo(0));
2416 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
2418 // Translate from byte offset to table index. It improves analyzability.
2419 llvm::Value *VBTableIndex = Builder.CreateAShr(
2420 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2421 "vbtindex", /*isExact=*/true);
2423 // Load an i32 offset from the vb-table.
2424 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2425 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2426 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
2429 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2431 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2432 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2433 llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2434 CGBuilderTy &Builder = CGF.Builder;
2435 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
2436 llvm::BasicBlock *OriginalBB = nullptr;
2437 llvm::BasicBlock *SkipAdjustBB = nullptr;
2438 llvm::BasicBlock *VBaseAdjustBB = nullptr;
2440 // In the unspecified inheritance model, there might not be a vbtable at all,
2441 // in which case we need to skip the virtual base lookup. If there is a
2442 // vbtable, the first entry is a no-op entry that gives back the original
2443 // base, so look for a virtual base adjustment offset of zero.
2445 OriginalBB = Builder.GetInsertBlock();
2446 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2447 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2448 llvm::Value *IsVirtual =
2449 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2451 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2452 CGF.EmitBlock(VBaseAdjustBB);
2455 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2456 // know the vbptr offset.
2458 CharUnits offs = CharUnits::Zero();
2459 if (!RD->hasDefinition()) {
2460 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2461 unsigned DiagID = Diags.getCustomDiagID(
2462 DiagnosticsEngine::Error,
2463 "member pointer representation requires a "
2464 "complete class type for %0 to perform this expression");
2465 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2466 } else if (RD->getNumVBases())
2467 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2468 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2470 llvm::Value *VBPtr = nullptr;
2471 llvm::Value *VBaseOffs =
2472 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2473 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2475 // Merge control flow with the case where we didn't have to adjust.
2476 if (VBaseAdjustBB) {
2477 Builder.CreateBr(SkipAdjustBB);
2478 CGF.EmitBlock(SkipAdjustBB);
2479 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2480 Phi->addIncoming(Base, OriginalBB);
2481 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2484 return AdjustedBase;
2487 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2488 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
2489 const MemberPointerType *MPT) {
2490 assert(MPT->isMemberDataPointer());
2491 unsigned AS = Base->getType()->getPointerAddressSpace();
2493 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2494 CGBuilderTy &Builder = CGF.Builder;
2495 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2496 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2498 // Extract the fields we need, regardless of model. We'll apply them if we
2500 llvm::Value *FieldOffset = MemPtr;
2501 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2502 llvm::Value *VBPtrOffset = nullptr;
2503 if (MemPtr->getType()->isStructTy()) {
2504 // We need to extract values.
2506 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2507 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2508 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2509 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2510 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2513 if (VirtualBaseAdjustmentOffset) {
2514 Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
2519 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
2521 // Apply the offset, which we assume is non-null.
2523 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
2525 // Cast the address to the appropriate pointer type, adopting the address
2526 // space of the base pointer.
2527 return Builder.CreateBitCast(Addr, PType);
2530 static MSInheritanceAttr::Spelling
2531 getInheritanceFromMemptr(const MemberPointerType *MPT) {
2532 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
2536 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
2539 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
2540 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
2541 E->getCastKind() == CK_ReinterpretMemberPointer);
2543 // Use constant emission if we can.
2544 if (isa<llvm::Constant>(Src))
2545 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
2547 // We may be adding or dropping fields from the member pointer, so we need
2548 // both types and the inheritance models of both records.
2549 const MemberPointerType *SrcTy =
2550 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2551 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2552 bool IsFunc = SrcTy->isMemberFunctionPointer();
2554 // If the classes use the same null representation, reinterpret_cast is a nop.
2555 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
2556 if (IsReinterpret && IsFunc)
2559 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
2560 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
2561 if (IsReinterpret &&
2562 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
2565 CGBuilderTy &Builder = CGF.Builder;
2567 // Branch past the conversion if Src is null.
2568 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
2569 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
2571 // C++ 5.2.10p9: The null member pointer value is converted to the null member
2572 // pointer value of the destination type.
2573 if (IsReinterpret) {
2574 // For reinterpret casts, sema ensures that src and dst are both functions
2575 // or data and have the same size, which means the LLVM types should match.
2576 assert(Src->getType() == DstNull->getType());
2577 return Builder.CreateSelect(IsNotNull, Src, DstNull);
2580 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
2581 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
2582 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
2583 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
2584 CGF.EmitBlock(ConvertBB);
2587 llvm::Value *FirstField = Src;
2588 llvm::Value *NonVirtualBaseAdjustment = nullptr;
2589 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2590 llvm::Value *VBPtrOffset = nullptr;
2591 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
2592 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2593 // We need to extract values.
2595 FirstField = Builder.CreateExtractValue(Src, I++);
2596 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2597 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
2598 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2599 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
2600 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2601 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
2604 // For data pointers, we adjust the field offset directly. For functions, we
2605 // have a separate field.
2606 llvm::Constant *Adj = getMemberPointerAdjustment(E);
2608 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2609 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
2610 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2611 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
2612 NVAdjustField = getZeroInt();
2613 if (isDerivedToBase)
2614 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
2616 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
2619 // FIXME PR15713: Support conversions through virtually derived classes.
2621 // Recompose dst from the null struct and the adjusted fields from src.
2622 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
2624 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
2627 Dst = llvm::UndefValue::get(DstNull->getType());
2629 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
2630 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2631 Dst = Builder.CreateInsertValue(
2632 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
2633 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2634 Dst = Builder.CreateInsertValue(
2635 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
2636 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2637 Dst = Builder.CreateInsertValue(
2638 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
2640 Builder.CreateBr(ContinueBB);
2642 // In the continuation, choose between DstNull and Dst.
2643 CGF.EmitBlock(ContinueBB);
2644 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
2645 Phi->addIncoming(DstNull, OriginalBB);
2646 Phi->addIncoming(Dst, ConvertBB);
2651 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
2652 llvm::Constant *Src) {
2653 const MemberPointerType *SrcTy =
2654 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2655 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2657 // If src is null, emit a new null for dst. We can't return src because dst
2658 // might have a new representation.
2659 if (MemberPointerConstantIsNull(SrcTy, Src))
2660 return EmitNullMemberPointer(DstTy);
2662 // We don't need to do anything for reinterpret_casts of non-null member
2663 // pointers. We should only get here when the two type representations have
2665 if (E->getCastKind() == CK_ReinterpretMemberPointer)
2668 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
2669 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
2672 llvm::Constant *FirstField = Src;
2673 llvm::Constant *NonVirtualBaseAdjustment = nullptr;
2674 llvm::Constant *VirtualBaseAdjustmentOffset = nullptr;
2675 llvm::Constant *VBPtrOffset = nullptr;
2676 bool IsFunc = SrcTy->isMemberFunctionPointer();
2677 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2678 // We need to extract values.
2680 FirstField = Src->getAggregateElement(I++);
2681 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2682 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
2683 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2684 VBPtrOffset = Src->getAggregateElement(I++);
2685 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2686 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
2689 // For data pointers, we adjust the field offset directly. For functions, we
2690 // have a separate field.
2691 llvm::Constant *Adj = getMemberPointerAdjustment(E);
2693 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2694 llvm::Constant *&NVAdjustField =
2695 IsFunc ? NonVirtualBaseAdjustment : FirstField;
2696 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2697 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
2698 NVAdjustField = getZeroInt();
2699 if (IsDerivedToBase)
2700 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
2702 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
2705 // FIXME PR15713: Support conversions through virtually derived classes.
2707 // Recompose dst from the null struct and the adjusted fields from src.
2708 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance))
2711 llvm::SmallVector<llvm::Constant *, 4> Fields;
2712 Fields.push_back(FirstField);
2713 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2714 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
2715 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2716 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
2717 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2718 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2719 return llvm::ConstantStruct::getAnon(Fields);
2722 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
2723 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
2724 llvm::Value *MemPtr, const MemberPointerType *MPT) {
2725 assert(MPT->isMemberFunctionPointer());
2726 const FunctionProtoType *FPT =
2727 MPT->getPointeeType()->castAs<FunctionProtoType>();
2728 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2729 llvm::FunctionType *FTy =
2730 CGM.getTypes().GetFunctionType(
2731 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2732 CGBuilderTy &Builder = CGF.Builder;
2734 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2736 // Extract the fields we need, regardless of model. We'll apply them if we
2738 llvm::Value *FunctionPointer = MemPtr;
2739 llvm::Value *NonVirtualBaseAdjustment = nullptr;
2740 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2741 llvm::Value *VBPtrOffset = nullptr;
2742 if (MemPtr->getType()->isStructTy()) {
2743 // We need to extract values.
2745 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
2746 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
2747 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
2748 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2749 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2750 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2751 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2754 if (VirtualBaseAdjustmentOffset) {
2755 This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset,
2759 if (NonVirtualBaseAdjustment) {
2760 // Apply the adjustment and cast back to the original struct type.
2761 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2762 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2763 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2766 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2769 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
2770 return new MicrosoftCXXABI(CGM);
2773 // MS RTTI Overview:
2774 // The run time type information emitted by cl.exe contains 5 distinct types of
2775 // structures. Many of them reference each other.
2777 // TypeInfo: Static classes that are returned by typeid.
2779 // CompleteObjectLocator: Referenced by vftables. They contain information
2780 // required for dynamic casting, including OffsetFromTop. They also contain
2781 // a reference to the TypeInfo for the type and a reference to the
2782 // CompleteHierarchyDescriptor for the type.
2784 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
2785 // Used during dynamic_cast to walk a class hierarchy. References a base
2786 // class array and the size of said array.
2788 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
2789 // somewhat of a misnomer because the most derived class is also in the list
2790 // as well as multiple copies of virtual bases (if they occur multiple times
2791 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for
2792 // every path in the hierarchy, in pre-order depth first order. Note, we do
2793 // not declare a specific llvm type for BaseClassArray, it's merely an array
2794 // of BaseClassDescriptor pointers.
2796 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
2797 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
2798 // BaseClassArray is. It contains information about a class within a
2799 // hierarchy such as: is this base is ambiguous and what is its offset in the
2800 // vbtable. The names of the BaseClassDescriptors have all of their fields
2801 // mangled into them so they can be aggressively deduplicated by the linker.
2803 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
2804 StringRef MangledName("\01??_7type_info@@6B@");
2805 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
2807 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2809 llvm::GlobalVariable::ExternalLinkage,
2810 /*Initializer=*/nullptr, MangledName);
2815 /// \brief A Helper struct that stores information about a class in a class
2816 /// hierarchy. The information stored in these structs struct is used during
2817 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
2818 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
2819 // implicit depth first pre-order tree connectivity. getFirstChild and
2820 // getNextSibling allow us to walk the tree efficiently.
2821 struct MSRTTIClass {
2823 IsPrivateOnPath = 1 | 8,
2827 HasHierarchyDescriptor = 64
2829 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
2830 uint32_t initialize(const MSRTTIClass *Parent,
2831 const CXXBaseSpecifier *Specifier);
2833 MSRTTIClass *getFirstChild() { return this + 1; }
2834 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
2835 return Child + 1 + Child->NumBases;
2838 const CXXRecordDecl *RD, *VirtualRoot;
2839 uint32_t Flags, NumBases, OffsetInVBase;
2842 /// \brief Recursively initialize the base class array.
2843 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
2844 const CXXBaseSpecifier *Specifier) {
2845 Flags = HasHierarchyDescriptor;
2847 VirtualRoot = nullptr;
2850 if (Specifier->getAccessSpecifier() != AS_public)
2851 Flags |= IsPrivate | IsPrivateOnPath;
2852 if (Specifier->isVirtual()) {
2857 if (Parent->Flags & IsPrivateOnPath)
2858 Flags |= IsPrivateOnPath;
2859 VirtualRoot = Parent->VirtualRoot;
2860 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
2861 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
2865 MSRTTIClass *Child = getFirstChild();
2866 for (const CXXBaseSpecifier &Base : RD->bases()) {
2867 NumBases += Child->initialize(this, &Base) + 1;
2868 Child = getNextChild(Child);
2873 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
2874 switch (Ty->getLinkage()) {
2876 case InternalLinkage:
2877 case UniqueExternalLinkage:
2878 return llvm::GlobalValue::InternalLinkage;
2880 case VisibleNoLinkage:
2881 case ExternalLinkage:
2882 return llvm::GlobalValue::LinkOnceODRLinkage;
2884 llvm_unreachable("Invalid linkage!");
2887 /// \brief An ephemeral helper class for building MS RTTI types. It caches some
2888 /// calls to the module and information about the most derived class in a
2890 struct MSRTTIBuilder {
2892 HasBranchingHierarchy = 1,
2893 HasVirtualBranchingHierarchy = 2,
2894 HasAmbiguousBases = 4
2897 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
2898 : CGM(ABI.CGM), Context(CGM.getContext()),
2899 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
2900 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
2903 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
2904 llvm::GlobalVariable *
2905 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
2906 llvm::GlobalVariable *getClassHierarchyDescriptor();
2907 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info);
2910 ASTContext &Context;
2911 llvm::LLVMContext &VMContext;
2912 llvm::Module &Module;
2913 const CXXRecordDecl *RD;
2914 llvm::GlobalVariable::LinkageTypes Linkage;
2915 MicrosoftCXXABI &ABI;
2920 /// \brief Recursively serializes a class hierarchy in pre-order depth first
2922 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
2923 const CXXRecordDecl *RD) {
2924 Classes.push_back(MSRTTIClass(RD));
2925 for (const CXXBaseSpecifier &Base : RD->bases())
2926 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
2929 /// \brief Find ambiguity among base classes.
2931 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
2932 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
2933 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
2934 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
2935 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
2936 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
2937 !VirtualBases.insert(Class->RD).second) {
2938 Class = MSRTTIClass::getNextChild(Class);
2941 if (!UniqueBases.insert(Class->RD).second)
2942 AmbiguousBases.insert(Class->RD);
2945 if (AmbiguousBases.empty())
2947 for (MSRTTIClass &Class : Classes)
2948 if (AmbiguousBases.count(Class.RD))
2949 Class.Flags |= MSRTTIClass::IsAmbiguous;
2952 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
2953 SmallString<256> MangledName;
2955 llvm::raw_svector_ostream Out(MangledName);
2956 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
2959 // Check to see if we've already declared this ClassHierarchyDescriptor.
2960 if (auto CHD = Module.getNamedGlobal(MangledName))
2963 // Serialize the class hierarchy and initialize the CHD Fields.
2964 SmallVector<MSRTTIClass, 8> Classes;
2965 serializeClassHierarchy(Classes, RD);
2966 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
2967 detectAmbiguousBases(Classes);
2969 for (auto Class : Classes) {
2970 if (Class.RD->getNumBases() > 1)
2971 Flags |= HasBranchingHierarchy;
2972 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
2973 // believe the field isn't actually used.
2974 if (Class.Flags & MSRTTIClass::IsAmbiguous)
2975 Flags |= HasAmbiguousBases;
2977 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
2978 Flags |= HasVirtualBranchingHierarchy;
2979 // These gep indices are used to get the address of the first element of the
2980 // base class array.
2981 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
2982 llvm::ConstantInt::get(CGM.IntTy, 0)};
2984 // Forward-declare the class hierarchy descriptor
2985 auto Type = ABI.getClassHierarchyDescriptorType();
2986 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2987 /*Initializer=*/nullptr,
2988 StringRef(MangledName));
2989 if (CHD->isWeakForLinker())
2990 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
2992 // Initialize the base class ClassHierarchyDescriptor.
2993 llvm::Constant *Fields[] = {
2994 llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown
2995 llvm::ConstantInt::get(CGM.IntTy, Flags),
2996 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
2997 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
2998 getBaseClassArray(Classes),
2999 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3001 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3005 llvm::GlobalVariable *
3006 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3007 SmallString<256> MangledName;
3009 llvm::raw_svector_ostream Out(MangledName);
3010 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3013 // Forward-declare the base class array.
3014 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3015 // mode) bytes of padding. We provide a pointer sized amount of padding by
3016 // adding +1 to Classes.size(). The sections have pointer alignment and are
3017 // marked pick-any so it shouldn't matter.
3018 llvm::Type *PtrType = ABI.getImageRelativeType(
3019 ABI.getBaseClassDescriptorType()->getPointerTo());
3020 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3022 new llvm::GlobalVariable(Module, ArrType,
3023 /*Constant=*/true, Linkage,
3024 /*Initializer=*/nullptr, StringRef(MangledName));
3025 if (BCA->isWeakForLinker())
3026 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3028 // Initialize the BaseClassArray.
3029 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3030 for (MSRTTIClass &Class : Classes)
3031 BaseClassArrayData.push_back(
3032 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3033 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3034 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3038 llvm::GlobalVariable *
3039 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3040 // Compute the fields for the BaseClassDescriptor. They are computed up front
3041 // because they are mangled into the name of the object.
3042 uint32_t OffsetInVBTable = 0;
3043 int32_t VBPtrOffset = -1;
3044 if (Class.VirtualRoot) {
3045 auto &VTableContext = CGM.getMicrosoftVTableContext();
3046 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3047 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3050 SmallString<256> MangledName;
3052 llvm::raw_svector_ostream Out(MangledName);
3053 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3054 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3058 // Check to see if we've already declared this object.
3059 if (auto BCD = Module.getNamedGlobal(MangledName))
3062 // Forward-declare the base class descriptor.
3063 auto Type = ABI.getBaseClassDescriptorType();
3065 new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3066 /*Initializer=*/nullptr, StringRef(MangledName));
3067 if (BCD->isWeakForLinker())
3068 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3070 // Initialize the BaseClassDescriptor.
3071 llvm::Constant *Fields[] = {
3072 ABI.getImageRelativeConstant(
3073 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3074 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3075 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3076 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3077 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3078 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3079 ABI.getImageRelativeConstant(
3080 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3082 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3086 llvm::GlobalVariable *
3087 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) {
3088 SmallString<256> MangledName;
3090 llvm::raw_svector_ostream Out(MangledName);
3091 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out);
3094 // Check to see if we've already computed this complete object locator.
3095 if (auto COL = Module.getNamedGlobal(MangledName))
3098 // Compute the fields of the complete object locator.
3099 int OffsetToTop = Info->FullOffsetInMDC.getQuantity();
3100 int VFPtrOffset = 0;
3101 // The offset includes the vtordisp if one exists.
3102 if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr())
3103 if (Context.getASTRecordLayout(RD)
3104 .getVBaseOffsetsMap()
3106 ->second.hasVtorDisp())
3107 VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4;
3109 // Forward-declare the complete object locator.
3110 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3111 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3112 /*Initializer=*/nullptr, StringRef(MangledName));
3114 // Initialize the CompleteObjectLocator.
3115 llvm::Constant *Fields[] = {
3116 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3117 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3118 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3119 ABI.getImageRelativeConstant(
3120 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3121 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3122 ABI.getImageRelativeConstant(COL),
3124 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3125 if (!ABI.isImageRelative())
3126 FieldsRef = FieldsRef.drop_back();
3127 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3128 if (COL->isWeakForLinker())
3129 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3133 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3134 /// llvm::GlobalVariable * because different type descriptors have different
3135 /// types, and need to be abstracted. They are abstracting by casting the
3136 /// address to an Int8PtrTy.
3137 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3138 SmallString<256> MangledName, TypeInfoString;
3140 llvm::raw_svector_ostream Out(MangledName);
3141 getMangleContext().mangleCXXRTTI(Type, Out);
3144 // Check to see if we've already declared this TypeDescriptor.
3145 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3146 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3148 // Compute the fields for the TypeDescriptor.
3150 llvm::raw_svector_ostream Out(TypeInfoString);
3151 getMangleContext().mangleCXXRTTIName(Type, Out);
3154 // Declare and initialize the TypeDescriptor.
3155 llvm::Constant *Fields[] = {
3156 getTypeInfoVTable(CGM), // VFPtr
3157 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3158 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3159 llvm::StructType *TypeDescriptorType =
3160 getTypeDescriptorType(TypeInfoString);
3161 auto *Var = new llvm::GlobalVariable(
3162 CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3163 getLinkageForRTTI(Type),
3164 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3165 StringRef(MangledName));
3166 if (Var->isWeakForLinker())
3167 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3168 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3171 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
3172 llvm::GlobalVariable *
3173 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3174 const VPtrInfo *Info) {
3175 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3178 static void emitCXXConstructor(CodeGenModule &CGM,
3179 const CXXConstructorDecl *ctor,
3180 StructorType ctorType) {
3181 // There are no constructor variants, always emit the complete destructor.
3182 llvm::Function *Fn = CGM.codegenCXXStructor(ctor, StructorType::Complete);
3183 CGM.maybeSetTrivialComdat(*ctor, *Fn);
3186 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3187 StructorType dtorType) {
3188 // The complete destructor is equivalent to the base destructor for
3189 // classes with no virtual bases, so try to emit it as an alias.
3190 if (!dtor->getParent()->getNumVBases() &&
3191 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3192 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3193 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3194 if (ProducedAlias) {
3195 if (dtorType == StructorType::Complete)
3197 if (dtor->isVirtual())
3198 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3202 // The base destructor is equivalent to the base destructor of its
3203 // base class if there is exactly one non-virtual base class with a
3204 // non-trivial destructor, there are no fields with a non-trivial
3205 // destructor, and the body of the destructor is trivial.
3206 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3209 llvm::Function *Fn = CGM.codegenCXXStructor(dtor, dtorType);
3210 if (Fn->isWeakForLinker())
3211 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3214 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3215 StructorType Type) {
3216 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3217 emitCXXConstructor(CGM, CD, Type);
3220 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);
3223 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
3225 int32_t VBPtrOffset,
3227 assert(!T->isReferenceType());
3229 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
3230 const CXXConstructorDecl *CD =
3231 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
3232 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
3233 SmallString<256> MangledName;
3235 llvm::raw_svector_ostream Out(MangledName);
3236 getMangleContext().mangleCXXCatchableType(T, CD, Size, Out);
3238 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3239 return getImageRelativeConstant(GV);
3241 // The TypeDescriptor is used by the runtime to determine of a catch handler
3242 // is appropriate for the exception object.
3243 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
3245 // The runtime is responsible for calling the copy constructor if the
3246 // exception is caught by value.
3247 llvm::Constant *CopyCtor =
3248 CD ? llvm::ConstantExpr::getBitCast(
3249 CGM.getAddrOfCXXStructor(CD, StructorType::Complete),
3251 : llvm::Constant::getNullValue(CGM.Int8PtrTy);
3252 CopyCtor = getImageRelativeConstant(CopyCtor);
3254 bool IsScalar = !RD;
3255 bool HasVirtualBases = false;
3256 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
3257 QualType PointeeType = T;
3258 if (T->isPointerType())
3259 PointeeType = T->getPointeeType();
3260 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
3261 HasVirtualBases = RD->getNumVBases() > 0;
3262 if (IdentifierInfo *II = RD->getIdentifier())
3263 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
3266 // Encode the relevant CatchableType properties into the Flags bitfield.
3267 // FIXME: Figure out how bits 2 or 8 can get set.
3271 if (HasVirtualBases)
3276 llvm::Constant *Fields[] = {
3277 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
3278 TD, // TypeDescriptor
3279 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
3280 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
3281 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
3282 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
3283 CopyCtor // CopyCtor
3285 llvm::StructType *CTType = getCatchableTypeType();
3286 auto *GV = new llvm::GlobalVariable(
3287 CGM.getModule(), CTType, /*Constant=*/true, getLinkageForRTTI(T),
3288 llvm::ConstantStruct::get(CTType, Fields), StringRef(MangledName));
3289 if (GV->isWeakForLinker())
3290 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
3291 GV->setUnnamedAddr(true);
3292 return getImageRelativeConstant(GV);
3295 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
3296 assert(!T->isReferenceType());
3298 // See if we've already generated a CatchableTypeArray for this type before.
3299 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
3303 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
3304 // using a SmallSetVector. Duplicates may arise due to virtual bases
3305 // occurring more than once in the hierarchy.
3306 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
3308 // C++14 [except.handle]p3:
3309 // A handler is a match for an exception object of type E if [...]
3310 // - the handler is of type cv T or cv T& and T is an unambiguous public
3311 // base class of E, or
3312 // - the handler is of type cv T or const T& where T is a pointer type and
3313 // E is a pointer type that can be converted to T by [...]
3314 // - a standard pointer conversion (4.10) not involving conversions to
3315 // pointers to private or protected or ambiguous classes
3316 const CXXRecordDecl *MostDerivedClass = nullptr;
3317 bool IsPointer = T->isPointerType();
3319 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
3321 MostDerivedClass = T->getAsCXXRecordDecl();
3323 // Collect all the unambiguous public bases of the MostDerivedClass.
3324 if (MostDerivedClass) {
3325 const ASTContext &Context = CGM.getContext();
3326 const ASTRecordLayout &MostDerivedLayout =
3327 Context.getASTRecordLayout(MostDerivedClass);
3328 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
3329 SmallVector<MSRTTIClass, 8> Classes;
3330 serializeClassHierarchy(Classes, MostDerivedClass);
3331 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3332 detectAmbiguousBases(Classes);
3333 for (const MSRTTIClass &Class : Classes) {
3334 // Skip any ambiguous or private bases.
3336 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
3338 // Write down how to convert from a derived pointer to a base pointer.
3339 uint32_t OffsetInVBTable = 0;
3340 int32_t VBPtrOffset = -1;
3341 if (Class.VirtualRoot) {
3343 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
3344 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
3347 // Turn our record back into a pointer if the exception object is a
3349 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
3351 RTTITy = Context.getPointerType(RTTITy);
3352 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
3353 VBPtrOffset, OffsetInVBTable));
3357 // C++14 [except.handle]p3:
3358 // A handler is a match for an exception object of type E if
3359 // - The handler is of type cv T or cv T& and E and T are the same type
3360 // (ignoring the top-level cv-qualifiers)
3361 CatchableTypes.insert(getCatchableType(T));
3363 // C++14 [except.handle]p3:
3364 // A handler is a match for an exception object of type E if
3365 // - the handler is of type cv T or const T& where T is a pointer type and
3366 // E is a pointer type that can be converted to T by [...]
3367 // - a standard pointer conversion (4.10) not involving conversions to
3368 // pointers to private or protected or ambiguous classes
3370 // All pointers are convertible to pointer-to-void so ensure that it is in the
3371 // CatchableTypeArray.
3373 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
3375 uint32_t NumEntries = CatchableTypes.size();
3376 llvm::Type *CTType =
3377 getImageRelativeType(getCatchableTypeType()->getPointerTo());
3378 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
3379 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
3380 llvm::Constant *Fields[] = {
3381 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
3382 llvm::ConstantArray::get(
3383 AT, llvm::makeArrayRef(CatchableTypes.begin(),
3384 CatchableTypes.end())) // CatchableTypes
3386 SmallString<256> MangledName;
3388 llvm::raw_svector_ostream Out(MangledName);
3389 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
3391 CTA = new llvm::GlobalVariable(
3392 CGM.getModule(), CTAType, /*Constant=*/true, getLinkageForRTTI(T),
3393 llvm::ConstantStruct::get(CTAType, Fields), StringRef(MangledName));
3394 if (CTA->isWeakForLinker())
3395 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
3396 CTA->setUnnamedAddr(true);
3400 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
3401 T = getContext().getExceptionObjectType(T);
3403 // C++14 [except.handle]p3:
3404 // A handler is a match for an exception object of type E if [...]
3405 // - the handler is of type cv T or const T& where T is a pointer type and
3406 // E is a pointer type that can be converted to T by [...]
3407 // - a qualification conversion
3408 bool IsConst = false, IsVolatile = false;
3409 QualType PointeeType = T->getPointeeType();
3410 if (!PointeeType.isNull()) {
3411 IsConst = PointeeType.isConstQualified();
3412 IsVolatile = PointeeType.isVolatileQualified();
3415 // Member pointer types like "const int A::*" are represented by having RTTI
3416 // for "int A::*" and separately storing the const qualifier.
3417 if (const auto *MPTy = T->getAs<MemberPointerType>())
3418 T = getContext().getMemberPointerType(PointeeType.getUnqualifiedType(),
3421 // Pointer types like "const int * const *" are represented by having RTTI
3422 // for "const int **" and separately storing the const qualifier.
3423 if (T->isPointerType())
3424 T = getContext().getPointerType(PointeeType.getUnqualifiedType());
3426 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
3427 // the exception object may be caught as.
3428 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
3429 // The first field in a CatchableTypeArray is the number of CatchableTypes.
3430 // This is used as a component of the mangled name which means that we need to
3431 // know what it is in order to see if we have previously generated the
3433 uint32_t NumEntries =
3434 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
3435 ->getLimitedValue();
3437 SmallString<256> MangledName;
3439 llvm::raw_svector_ostream Out(MangledName);
3440 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, NumEntries,
3444 // Reuse a previously generated ThrowInfo if we have generated an appropriate
3446 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3449 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
3450 // be at least as CV qualified. Encode this requirement into the Flags
3458 // The cleanup-function (a destructor) must be called when the exception
3459 // object's lifetime ends.
3460 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
3461 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3462 if (CXXDestructorDecl *DtorD = RD->getDestructor())
3463 if (!DtorD->isTrivial())
3464 CleanupFn = llvm::ConstantExpr::getBitCast(
3465 CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete),
3467 // This is unused as far as we can tell, initialize it to null.
3468 llvm::Constant *ForwardCompat =
3469 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
3470 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
3471 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
3472 llvm::StructType *TIType = getThrowInfoType();
3473 llvm::Constant *Fields[] = {
3474 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
3475 getImageRelativeConstant(CleanupFn), // CleanupFn
3476 ForwardCompat, // ForwardCompat
3477 PointerToCatchableTypes // CatchableTypeArray
3479 auto *GV = new llvm::GlobalVariable(
3480 CGM.getModule(), TIType, /*Constant=*/true, getLinkageForRTTI(T),
3481 llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
3482 if (GV->isWeakForLinker())
3483 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
3484 GV->setUnnamedAddr(true);
3488 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
3489 const Expr *SubExpr = E->getSubExpr();
3490 QualType ThrowType = SubExpr->getType();
3491 // The exception object lives on the stack and it's address is passed to the
3492 // runtime function.
3493 llvm::AllocaInst *AI = CGF.CreateMemTemp(ThrowType);
3494 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
3497 // The so-called ThrowInfo is used to describe how the exception object may be
3499 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
3501 // Call into the runtime to throw the exception.
3502 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(AI, CGM.Int8PtrTy), TI};
3503 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);