clang 22.0.0git
MicrosoftCXXABI.cpp
Go to the documentation of this file.
1//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
10// The class in this file generates structures that follow the Microsoft
11// Visual C++ ABI, which is actually not very well documented at all outside
12// of Microsoft.
13//
14//===----------------------------------------------------------------------===//
15
16#include "ABIInfo.h"
17#include "CGCXXABI.h"
18#include "CGCleanup.h"
19#include "CGDebugInfo.h"
20#include "CGVTables.h"
21#include "CodeGenModule.h"
22#include "CodeGenTypes.h"
23#include "TargetInfo.h"
24#include "clang/AST/Attr.h"
26#include "clang/AST/Decl.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/StmtCXX.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/ADT/StringSet.h"
33#include "llvm/IR/Intrinsics.h"
34
35using namespace clang;
36using namespace CodeGen;
37
38namespace {
39
40/// Holds all the vbtable globals for a given class.
41struct VBTableGlobals {
42 const VPtrInfoVector *VBTables;
43 SmallVector<llvm::GlobalVariable *, 2> Globals;
44};
45
46class MicrosoftCXXABI : public CGCXXABI {
47public:
48 MicrosoftCXXABI(CodeGenModule &CGM)
49 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
50 ClassHierarchyDescriptorType(nullptr),
51 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
52 ThrowInfoType(nullptr) {
55 "visibility export mapping option unimplemented in this ABI");
56 }
57
58 bool HasThisReturn(GlobalDecl GD) const override;
59 bool hasMostDerivedReturn(GlobalDecl GD) const override;
60
61 bool classifyReturnType(CGFunctionInfo &FI) const override;
62
63 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
64
65 bool isSRetParameterAfterThis() const override { return true; }
66
67 bool isThisCompleteObject(GlobalDecl GD) const override {
68 // The Microsoft ABI doesn't use separate complete-object vs.
69 // base-object variants of constructors, but it does of destructors.
71 switch (GD.getDtorType()) {
72 case Dtor_Complete:
73 case Dtor_Deleting:
75 return true;
76 case Dtor_Base:
77 return false;
78
79 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
80 case Dtor_Unified:
81 llvm_unreachable("unexpected unified dtor type");
82 }
83 llvm_unreachable("bad dtor kind");
84 }
85
86 // No other kinds.
87 return false;
88 }
89
90 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
91 FunctionArgList &Args) const override {
92 assert(Args.size() >= 2 &&
93 "expected the arglist to have at least two args!");
94 // The 'most_derived' parameter goes second if the ctor is variadic and
95 // has v-bases.
96 if (CD->getParent()->getNumVBases() > 0 &&
97 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
98 return 2;
99 return 1;
100 }
101
102 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
103 std::vector<CharUnits> VBPtrOffsets;
104 const ASTContext &Context = getContext();
105 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
106
107 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
108 for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
109 const ASTRecordLayout &SubobjectLayout =
110 Context.getASTRecordLayout(VBT->IntroducingObject);
111 CharUnits Offs = VBT->NonVirtualOffset;
112 Offs += SubobjectLayout.getVBPtrOffset();
113 if (VBT->getVBaseWithVPtr())
114 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
115 VBPtrOffsets.push_back(Offs);
116 }
117 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
118 return VBPtrOffsets;
119 }
120
121 StringRef GetPureVirtualCallName() override { return "_purecall"; }
122 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
123
124 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
125 Address Ptr, QualType ElementType,
126 const CXXDestructorDecl *Dtor) override;
127
128 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
129 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
130
131 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
132
133 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
134 const VPtrInfo &Info);
135
136 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
137 CatchTypeInfo
138 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
139
140 /// MSVC needs an extra flag to indicate a catchall.
141 CatchTypeInfo getCatchAllTypeInfo() override {
142 // For -EHa catch(...) must handle HW exception
143 // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
144 if (getContext().getLangOpts().EHAsynch)
145 return CatchTypeInfo{nullptr, 0};
146 else
147 return CatchTypeInfo{nullptr, 0x40};
148 }
149
150 bool shouldTypeidBeNullChecked(QualType SrcRecordTy) override;
151 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
152 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
153 Address ThisPtr,
154 llvm::Type *StdTypeInfoPtrTy) override;
155
156 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
157 QualType SrcRecordTy) override;
158
159 bool shouldEmitExactDynamicCast(QualType DestRecordTy) override {
160 // TODO: Add support for exact dynamic_casts.
161 return false;
162 }
163 std::optional<ExactDynamicCastInfo>
164 getExactDynamicCastInfo(QualType SrcRecordTy, QualType DestTy,
165 QualType DestRecordTy) override {
166 llvm_unreachable("unsupported");
167 }
168 llvm::Value *emitExactDynamicCast(CodeGenFunction &CGF, Address Value,
169 QualType SrcRecordTy, QualType DestTy,
170 QualType DestRecordTy,
171 const ExactDynamicCastInfo &CastInfo,
172 llvm::BasicBlock *CastSuccess,
173 llvm::BasicBlock *CastFail) override {
174 llvm_unreachable("unsupported");
175 }
176
177 llvm::Value *emitDynamicCastCall(CodeGenFunction &CGF, Address Value,
178 QualType SrcRecordTy, QualType DestTy,
179 QualType DestRecordTy,
180 llvm::BasicBlock *CastEnd) override;
181
182 llvm::Value *emitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
183 QualType SrcRecordTy) override;
184
185 bool EmitBadCastCall(CodeGenFunction &CGF) override;
186 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
187 return false;
188 }
189
190 llvm::Value *
191 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
192 const CXXRecordDecl *ClassDecl,
193 const CXXRecordDecl *BaseClassDecl) override;
194
195 llvm::BasicBlock *
196 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
197 const CXXRecordDecl *RD) override;
198
199 llvm::BasicBlock *
200 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
201
202 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
203 const CXXRecordDecl *RD) override;
204
205 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
206
207 // Background on MSVC destructors
208 // ==============================
209 //
210 // Both Itanium and MSVC ABIs have destructor variants. The variant names
211 // roughly correspond in the following way:
212 // Itanium Microsoft
213 // Base -> no name, just ~Class
214 // Complete -> vbase destructor
215 // Deleting -> scalar deleting destructor
216 // vector deleting destructor
217 //
218 // The base and complete destructors are the same as in Itanium, although the
219 // complete destructor does not accept a VTT parameter when there are virtual
220 // bases. A separate mechanism involving vtordisps is used to ensure that
221 // virtual methods of destroyed subobjects are not called.
222 //
223 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
224 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
225 // pointer points to an array. The scalar deleting destructor assumes that
226 // bit 2 is zero, and therefore does not contain a loop.
227 //
228 // For virtual destructors, only one entry is reserved in the vftable, and it
229 // always points to the vector deleting destructor. The vector deleting
230 // destructor is the most general, so it can be used to destroy objects in
231 // place, delete single heap objects, or delete arrays.
232 //
233 // A TU defining a non-inline destructor is only guaranteed to emit a base
234 // destructor, and all of the other variants are emitted on an as-needed basis
235 // in COMDATs. Because a non-base destructor can be emitted in a TU that
236 // lacks a definition for the destructor, non-base destructors must always
237 // delegate to or alias the base destructor.
238
239 AddedStructorArgCounts
240 buildStructorSignature(GlobalDecl GD,
241 SmallVectorImpl<CanQualType> &ArgTys) override;
242
243 /// Non-base dtors should be emitted as delegating thunks in this ABI.
244 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
245 CXXDtorType DT) const override {
246 return DT != Dtor_Base;
247 }
248
249 void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
250 const CXXDestructorDecl *Dtor,
251 CXXDtorType DT) const override;
252
253 llvm::GlobalValue::LinkageTypes
254 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
255 CXXDtorType DT) const override;
256
257 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
258
259 const CXXRecordDecl *getThisArgumentTypeForMethod(GlobalDecl GD) override {
260 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
261
262 if (MD->isVirtual()) {
263 GlobalDecl LookupGD = GD;
264 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
265 // Complete dtors take a pointer to the complete object,
266 // thus don't need adjustment.
267 if (GD.getDtorType() == Dtor_Complete)
268 return MD->getParent();
269
270 // There's only Dtor_Deleting in vftable but it shares the this
271 // adjustment with the base one, so look up the deleting one instead.
272 LookupGD = GlobalDecl(
274 CGM.getContext().getLangOpts())
276 : Dtor_Deleting);
277 }
278 MethodVFTableLocation ML =
280
281 // The vbases might be ordered differently in the final overrider object
282 // and the complete object, so the "this" argument may sometimes point to
283 // memory that has no particular type (e.g. past the complete object).
284 // In this case, we just use a generic pointer type.
285 // FIXME: might want to have a more precise type in the non-virtual
286 // multiple inheritance case.
287 if (ML.VBase || !ML.VFPtrOffset.isZero())
288 return nullptr;
289 }
290 return MD->getParent();
291 }
292
293 Address
294 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
295 Address This,
296 bool VirtualCall) override;
297
298 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
299 FunctionArgList &Params) override;
300
301 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
302
303 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
304 const CXXConstructorDecl *D,
306 bool ForVirtualBase,
307 bool Delegating) override;
308
309 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
310 const CXXDestructorDecl *DD,
312 bool ForVirtualBase,
313 bool Delegating) override;
314
315 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
316 CXXDtorType Type, bool ForVirtualBase,
317 bool Delegating, Address This,
318 QualType ThisTy) override;
319
320 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
321 llvm::GlobalVariable *VTable);
322
323 void emitVTableDefinitions(CodeGenVTables &CGVT,
324 const CXXRecordDecl *RD) override;
325
326 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
327 CodeGenFunction::VPtr Vptr) override;
328
329 /// Don't initialize vptrs if dynamic class
330 /// is marked with the 'novtable' attribute.
331 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
332 return !VTableClass->hasAttr<MSNoVTableAttr>();
333 }
334
335 llvm::Constant *
336 getVTableAddressPoint(BaseSubobject Base,
337 const CXXRecordDecl *VTableClass) override;
338
339 llvm::Value *getVTableAddressPointInStructor(
340 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
341 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
342
343 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
344 CharUnits VPtrOffset) override;
345
346 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
347 Address This, llvm::Type *Ty,
348 SourceLocation Loc) override;
349
350 llvm::Value *
351 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,
352 CXXDtorType DtorType, Address This,
353 DeleteOrMemberCallExpr E,
354 llvm::CallBase **CallOrInvoke) override;
355
356 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
357 CallArgList &CallArgs) override {
358 assert((GD.getDtorType() == Dtor_VectorDeleting ||
359 GD.getDtorType() == Dtor_Deleting) &&
360 "Only vector deleting destructor thunks are available in this ABI");
361 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
362 getContext().IntTy);
363 }
364
365 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
366
367 llvm::GlobalVariable *
368 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
369 llvm::GlobalVariable::LinkageTypes Linkage);
370
371 llvm::GlobalVariable *
372 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
373 const CXXRecordDecl *DstRD) {
374 SmallString<256> OutName;
375 llvm::raw_svector_ostream Out(OutName);
376 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
377 StringRef MangledName = OutName.str();
378
379 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
380 return VDispMap;
381
382 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
383 unsigned NumEntries = 1 + SrcRD->getNumVBases();
384 SmallVector<llvm::Constant *, 4> Map(NumEntries,
385 llvm::PoisonValue::get(CGM.IntTy));
386 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
387 bool AnyDifferent = false;
388 for (const auto &I : SrcRD->vbases()) {
389 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
390 if (!DstRD->isVirtuallyDerivedFrom(VBase))
391 continue;
392
393 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
394 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
395 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
396 AnyDifferent |= SrcVBIndex != DstVBIndex;
397 }
398 // This map would be useless, don't use it.
399 if (!AnyDifferent)
400 return nullptr;
401
402 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
403 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
404 llvm::GlobalValue::LinkageTypes Linkage =
405 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
406 ? llvm::GlobalValue::LinkOnceODRLinkage
407 : llvm::GlobalValue::InternalLinkage;
408 auto *VDispMap = new llvm::GlobalVariable(
409 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
410 /*Initializer=*/Init, MangledName);
411 return VDispMap;
412 }
413
414 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
415 llvm::GlobalVariable *GV) const;
416
417 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
418 GlobalDecl GD, bool ReturnAdjustment) override {
420 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
421
422 if (Linkage == GVA_Internal)
423 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
424 else if (ReturnAdjustment)
425 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
426 else
427 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
428 }
429
430 bool exportThunk() override { return false; }
431
432 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
433 const CXXRecordDecl * /*UnadjustedClass*/,
434 const ThunkInfo &TI) override;
435
436 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
437 const CXXRecordDecl * /*UnadjustedClass*/,
438 const ReturnAdjustment &RA) override;
439
440 void EmitThreadLocalInitFuncs(
441 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
442 ArrayRef<llvm::Function *> CXXThreadLocalInits,
443 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
444
445 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
446 return getContext().getLangOpts().isCompatibleWithMSVC(
447 LangOptions::MSVC2019_5) &&
448 CGM.getCodeGenOpts().TlsGuards &&
449 (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
450 }
451 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
452 QualType LValType) override;
453
454 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
455 llvm::GlobalVariable *DeclPtr,
456 bool PerformInit) override;
457 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
458 llvm::FunctionCallee Dtor,
459 llvm::Constant *Addr) override;
460
461 // ==== Notes on array cookies =========
462 //
463 // MSVC seems to only use cookies when the class has a destructor; a
464 // two-argument usual array deallocation function isn't sufficient.
465 //
466 // For example, this code prints "100" and "1":
467 // struct A {
468 // char x;
469 // void *operator new[](size_t sz) {
470 // printf("%u\n", sz);
471 // return malloc(sz);
472 // }
473 // void operator delete[](void *p, size_t sz) {
474 // printf("%u\n", sz);
475 // free(p);
476 // }
477 // };
478 // int main() {
479 // A *p = new A[100];
480 // delete[] p;
481 // }
482 // Whereas it prints "104" and "104" if you give A a destructor.
483
484 bool requiresArrayCookie(const CXXDeleteExpr *expr,
485 QualType elementType) override;
486 bool requiresArrayCookie(const CXXNewExpr *expr) override;
487 CharUnits getArrayCookieSizeImpl(QualType type) override;
488 Address InitializeArrayCookie(CodeGenFunction &CGF,
489 Address NewPtr,
490 llvm::Value *NumElements,
491 const CXXNewExpr *expr,
492 QualType ElementType) override;
493 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
494 Address allocPtr,
495 CharUnits cookieSize) override;
496
497 friend struct MSRTTIBuilder;
498
499 bool isImageRelative() const {
500 return CGM.getTarget().getPointerWidth(LangAS::Default) == 64;
501 }
502
503 // 5 routines for constructing the llvm types for MS RTTI structs.
504 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
505 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
506 TDTypeName += llvm::utostr(TypeInfoString.size());
507 llvm::StructType *&TypeDescriptorType =
508 TypeDescriptorTypeMap[TypeInfoString.size()];
509 if (TypeDescriptorType)
510 return TypeDescriptorType;
511 llvm::Type *FieldTypes[] = {
512 CGM.Int8PtrPtrTy,
513 CGM.Int8PtrTy,
514 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
515 TypeDescriptorType =
516 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
517 return TypeDescriptorType;
518 }
519
520 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
521 if (!isImageRelative())
522 return PtrType;
523 return CGM.IntTy;
524 }
525
526 llvm::StructType *getBaseClassDescriptorType() {
527 if (BaseClassDescriptorType)
528 return BaseClassDescriptorType;
529 llvm::Type *FieldTypes[] = {
530 getImageRelativeType(CGM.Int8PtrTy),
531 CGM.IntTy,
532 CGM.IntTy,
533 CGM.IntTy,
534 CGM.IntTy,
535 CGM.IntTy,
536 getImageRelativeType(CGM.DefaultPtrTy),
537 };
538 BaseClassDescriptorType = llvm::StructType::create(
539 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
540 return BaseClassDescriptorType;
541 }
542
543 llvm::StructType *getClassHierarchyDescriptorType() {
544 if (ClassHierarchyDescriptorType)
545 return ClassHierarchyDescriptorType;
546 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
547 llvm::Type *FieldTypes[] = {CGM.IntTy, CGM.IntTy, CGM.IntTy,
548 getImageRelativeType(CGM.DefaultPtrTy)};
549 ClassHierarchyDescriptorType =
550 llvm::StructType::create(FieldTypes, "rtti.ClassHierarchyDescriptor");
551 return ClassHierarchyDescriptorType;
552 }
553
554 llvm::StructType *getCompleteObjectLocatorType() {
555 if (CompleteObjectLocatorType)
556 return CompleteObjectLocatorType;
557 llvm::Type *FieldTypes[] = {
558 CGM.IntTy,
559 CGM.IntTy,
560 CGM.IntTy,
561 getImageRelativeType(CGM.Int8PtrTy),
562 getImageRelativeType(CGM.DefaultPtrTy),
563 getImageRelativeType(CGM.VoidTy),
564 };
565 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
566 if (!isImageRelative())
567 FieldTypesRef = FieldTypesRef.drop_back();
568 CompleteObjectLocatorType =
569 llvm::StructType::create(FieldTypesRef, "rtti.CompleteObjectLocator");
570 return CompleteObjectLocatorType;
571 }
572
573 llvm::GlobalVariable *getImageBase() {
574 StringRef Name = "__ImageBase";
575 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
576 return GV;
577
578 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
579 /*isConstant=*/true,
580 llvm::GlobalValue::ExternalLinkage,
581 /*Initializer=*/nullptr, Name);
582 CGM.setDSOLocal(GV);
583 return GV;
584 }
585
586 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
587 if (!isImageRelative())
588 return PtrVal;
589
590 if (PtrVal->isNullValue())
591 return llvm::Constant::getNullValue(CGM.IntTy);
592
593 llvm::Constant *ImageBaseAsInt =
594 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
595 llvm::Constant *PtrValAsInt =
596 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
597 llvm::Constant *Diff =
598 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
599 /*HasNUW=*/true, /*HasNSW=*/true);
600 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
601 }
602
603private:
604 MicrosoftMangleContext &getMangleContext() {
606 }
607
608 llvm::Constant *getZeroInt() {
609 return llvm::ConstantInt::get(CGM.IntTy, 0);
610 }
611
612 llvm::Constant *getAllOnesInt() {
613 return llvm::Constant::getAllOnesValue(CGM.IntTy);
614 }
615
616 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
617
618 void
619 GetNullMemberPointerFields(const MemberPointerType *MPT,
620 llvm::SmallVectorImpl<llvm::Constant *> &fields);
621
622 /// Shared code for virtual base adjustment. Returns the offset from
623 /// the vbptr to the virtual base. Optionally returns the address of the
624 /// vbptr itself.
625 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
626 Address Base,
627 llvm::Value *VBPtrOffset,
628 llvm::Value *VBTableOffset,
629 llvm::Value **VBPtr = nullptr);
630
631 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
632 Address Base,
633 int32_t VBPtrOffset,
634 int32_t VBTableOffset,
635 llvm::Value **VBPtr = nullptr) {
636 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
637 llvm::Value *VBPOffset =
638 llvm::ConstantInt::getSigned(CGM.IntTy, VBPtrOffset);
639 llvm::Value *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
640 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
641 }
642
643 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
644 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
645 QualType SrcRecordTy);
646
647 /// Performs a full virtual base adjustment. Used to dereference
648 /// pointers to members of virtual bases.
649 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
650 const CXXRecordDecl *RD, Address Base,
651 llvm::Value *VirtualBaseAdjustmentOffset,
652 llvm::Value *VBPtrOffset /* optional */);
653
654 /// Emits a full member pointer with the fields common to data and
655 /// function member pointers.
656 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
657 bool IsMemberFunction,
658 const CXXRecordDecl *RD,
659 CharUnits NonVirtualBaseAdjustment,
660 unsigned VBTableIndex);
661
662 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
663 llvm::Constant *MP);
664
665 /// - Initialize all vbptrs of 'this' with RD as the complete type.
666 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
667
668 /// Caching wrapper around VBTableBuilder::enumerateVBTables().
669 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
670
671 /// Generate a thunk for calling a virtual member function MD.
672 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
673 const MethodVFTableLocation &ML);
674
675 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
676 CharUnits offset);
677
678public:
679 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
680
681 bool isZeroInitializable(const MemberPointerType *MPT) override;
682
683 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
684 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
685 return RD->hasAttr<MSInheritanceAttr>();
686 }
687
688 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
689
690 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
691 CharUnits offset) override;
692 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
693 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
694
695 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
696 llvm::Value *L,
697 llvm::Value *R,
698 const MemberPointerType *MPT,
699 bool Inequality) override;
700
701 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
702 llvm::Value *MemPtr,
703 const MemberPointerType *MPT) override;
704
705 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
706 Address Base, llvm::Value *MemPtr,
707 const MemberPointerType *MPT,
708 bool IsInBounds) override;
709
710 llvm::Value *EmitNonNullMemberPointerConversion(
711 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
713 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
714 CGBuilderTy &Builder);
715
716 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
717 const CastExpr *E,
718 llvm::Value *Src) override;
719
720 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
721 llvm::Constant *Src) override;
722
723 llvm::Constant *EmitMemberPointerConversion(
724 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
726 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
727
728 CGCallee
729 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
730 Address This, llvm::Value *&ThisPtrForCall,
731 llvm::Value *MemPtr,
732 const MemberPointerType *MPT) override;
733
734 void emitCXXStructor(GlobalDecl GD) override;
735
736 llvm::StructType *getCatchableTypeType() {
737 if (CatchableTypeType)
738 return CatchableTypeType;
739 llvm::Type *FieldTypes[] = {
740 CGM.IntTy, // Flags
741 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
742 CGM.IntTy, // NonVirtualAdjustment
743 CGM.IntTy, // OffsetToVBPtr
744 CGM.IntTy, // VBTableIndex
745 CGM.IntTy, // Size
746 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
747 };
748 CatchableTypeType = llvm::StructType::create(
749 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
750 return CatchableTypeType;
751 }
752
753 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
754 llvm::StructType *&CatchableTypeArrayType =
755 CatchableTypeArrayTypeMap[NumEntries];
756 if (CatchableTypeArrayType)
757 return CatchableTypeArrayType;
758
759 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
760 CTATypeName += llvm::utostr(NumEntries);
761 llvm::Type *CTType = getImageRelativeType(CGM.DefaultPtrTy);
762 llvm::Type *FieldTypes[] = {
763 CGM.IntTy, // NumEntries
764 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
765 };
766 CatchableTypeArrayType =
767 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
768 return CatchableTypeArrayType;
769 }
770
771 llvm::StructType *getThrowInfoType() {
772 if (ThrowInfoType)
773 return ThrowInfoType;
774 llvm::Type *FieldTypes[] = {
775 CGM.IntTy, // Flags
776 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
777 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
778 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
779 };
780 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
781 "eh.ThrowInfo");
782 return ThrowInfoType;
783 }
784
785 llvm::FunctionCallee getThrowFn() {
786 // _CxxThrowException is passed an exception object and a ThrowInfo object
787 // which describes the exception.
788 llvm::Type *Args[] = {CGM.Int8PtrTy, CGM.DefaultPtrTy};
789 llvm::FunctionType *FTy =
790 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
791 llvm::FunctionCallee Throw =
792 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
793 // _CxxThrowException is stdcall on 32-bit x86 platforms.
794 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
795 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
796 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
797 }
798 return Throw;
799 }
800
801 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
802 CXXCtorType CT);
803
804 llvm::Constant *getCatchableType(QualType T,
805 uint32_t NVOffset = 0,
806 int32_t VBPtrOffset = -1,
807 uint32_t VBIndex = 0);
808
809 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
810
811 llvm::GlobalVariable *getThrowInfo(QualType T) override;
812
813 std::pair<llvm::Value *, const CXXRecordDecl *>
814 LoadVTablePtr(CodeGenFunction &CGF, Address This,
815 const CXXRecordDecl *RD) override;
816
817 bool
818 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
819
820private:
821 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
822 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
823 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
824 /// All the vftables that have been referenced.
825 VFTablesMapTy VFTablesMap;
826 VTablesMapTy VTablesMap;
827
828 /// This set holds the record decls we've deferred vtable emission for.
829 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
830
831
832 /// All the vbtables which have been referenced.
833 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
834
835 /// Info on the global variable used to guard initialization of static locals.
836 /// The BitIndex field is only used for externally invisible declarations.
837 struct GuardInfo {
838 GuardInfo() = default;
839 llvm::GlobalVariable *Guard = nullptr;
840 unsigned BitIndex = 0;
841 };
842
843 /// Map from DeclContext to the current guard variable. We assume that the
844 /// AST is visited in source code order.
845 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
846 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
847 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
848
849 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
850 llvm::StructType *BaseClassDescriptorType;
851 llvm::StructType *ClassHierarchyDescriptorType;
852 llvm::StructType *CompleteObjectLocatorType;
853
854 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
855
856 llvm::StructType *CatchableTypeType;
857 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
858 llvm::StructType *ThrowInfoType;
859};
860
861}
862
864MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
865 // Use the default C calling convention rules for things that can be passed in
866 // registers, i.e. non-trivially copyable records or records marked with
867 // [[trivial_abi]].
868 if (RD->canPassInRegisters())
869 return RAA_Default;
870
871 switch (CGM.getTarget().getTriple().getArch()) {
872 default:
873 // FIXME: Implement for other architectures.
874 return RAA_Indirect;
875
876 case llvm::Triple::thumb:
877 // Pass things indirectly for now because it is simple.
878 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
879 // copy ctor.
880 return RAA_Indirect;
881
882 case llvm::Triple::x86: {
883 // If the argument has *required* alignment greater than four bytes, pass
884 // it indirectly. Prior to MSVC version 19.14, passing overaligned
885 // arguments was not supported and resulted in a compiler error. In 19.14
886 // and later versions, such arguments are now passed indirectly.
887 TypeInfo Info =
888 getContext().getTypeInfo(getContext().getCanonicalTagType(RD));
889 if (Info.isAlignRequired() && Info.Align > 4)
890 return RAA_Indirect;
891
892 // If C++ prohibits us from making a copy, construct the arguments directly
893 // into argument memory.
894 return RAA_DirectInMemory;
895 }
896
897 case llvm::Triple::x86_64:
898 case llvm::Triple::aarch64:
899 return RAA_Indirect;
900 }
901
902 llvm_unreachable("invalid enum");
903}
904
905void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
906 const CXXDeleteExpr *DE,
907 Address Ptr,
908 QualType ElementType,
909 const CXXDestructorDecl *Dtor) {
910 // FIXME: Provide a source location here even though there's no
911 // CXXMemberCallExpr for dtor call.
912 if (!getContext().getTargetInfo().callGlobalDeleteInDeletingDtor(
913 getContext().getLangOpts())) {
914 bool UseGlobalDelete = DE->isGlobalDelete();
915 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
916 llvm::Value *MDThis =
917 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE,
918 /*CallOrInvoke=*/nullptr);
919 if (UseGlobalDelete)
920 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
921 } else {
922 EmitVirtualDestructorCall(CGF, Dtor, Dtor_Deleting, Ptr, DE,
923 /*CallOrInvoke=*/nullptr);
924 }
925}
926
927void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
928 llvm::Value *Args[] = {llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
929 llvm::ConstantPointerNull::get(CGM.DefaultPtrTy)};
930 llvm::FunctionCallee Fn = getThrowFn();
931 if (isNoReturn)
933 else
934 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
935}
936
937void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
938 const CXXCatchStmt *S) {
939 // In the MS ABI, the runtime handles the copy, and the catch handler is
940 // responsible for destruction.
941 VarDecl *CatchParam = S->getExceptionDecl();
942 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
943 llvm::CatchPadInst *CPI =
944 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHIIt());
945 CGF.CurrentFuncletPad = CPI;
946
947 // If this is a catch-all or the catch parameter is unnamed, we don't need to
948 // emit an alloca to the object.
949 if (!CatchParam || !CatchParam->getDeclName()) {
950 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
951 return;
952 }
953
954 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
955 CPI->setArgOperand(2, var.getObjectAddress(CGF).emitRawPointer(CGF));
956 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
957 CGF.EmitAutoVarCleanups(var);
958}
959
960/// We need to perform a generic polymorphic operation (like a typeid
961/// or a cast), which requires an object with a vfptr. Adjust the
962/// address to point to an object with a vfptr.
963std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
964MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
965 QualType SrcRecordTy) {
966 Value = Value.withElementType(CGF.Int8Ty);
967 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
968 const ASTContext &Context = getContext();
969
970 // If the class itself has a vfptr, great. This check implicitly
971 // covers non-virtual base subobjects: a class with its own virtual
972 // functions would be a candidate to be a primary base.
973 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
974 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
975 SrcDecl);
976
977 // Okay, one of the vbases must have a vfptr, or else this isn't
978 // actually a polymorphic class.
979 const CXXRecordDecl *PolymorphicBase = nullptr;
980 for (auto &Base : SrcDecl->vbases()) {
981 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
982 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
983 PolymorphicBase = BaseDecl;
984 break;
985 }
986 }
987 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
988
989 llvm::Value *Offset =
990 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
991 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
992 Value.getElementType(), Value.emitRawPointer(CGF), Offset);
993 CharUnits VBaseAlign =
994 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
995 return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,
996 PolymorphicBase);
997}
998
999bool MicrosoftCXXABI::shouldTypeidBeNullChecked(QualType SrcRecordTy) {
1000 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1001 return !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1002}
1003
1004static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
1005 llvm::Value *Argument) {
1006 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1007 llvm::FunctionType *FTy =
1008 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
1009 llvm::Value *Args[] = {Argument};
1010 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
1011 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
1012}
1013
1014void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1015 llvm::CallBase *Call =
1016 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
1017 Call->setDoesNotReturn();
1018 CGF.Builder.CreateUnreachable();
1019}
1020
1021llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
1022 QualType SrcRecordTy,
1023 Address ThisPtr,
1024 llvm::Type *StdTypeInfoPtrTy) {
1025 std::tie(ThisPtr, std::ignore, std::ignore) =
1026 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
1027 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.emitRawPointer(CGF));
1028 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
1029}
1030
1031bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1032 QualType SrcRecordTy) {
1033 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1034 return SrcIsPtr &&
1035 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1036}
1037
1038llvm::Value *MicrosoftCXXABI::emitDynamicCastCall(
1039 CodeGenFunction &CGF, Address This, QualType SrcRecordTy, QualType DestTy,
1040 QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1041 llvm::Value *SrcRTTI =
1043 llvm::Value *DestRTTI =
1045
1046 llvm::Value *Offset;
1047 std::tie(This, Offset, std::ignore) =
1048 performBaseAdjustment(CGF, This, SrcRecordTy);
1049 llvm::Value *ThisPtr = This.emitRawPointer(CGF);
1050 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1051
1052 // PVOID __RTDynamicCast(
1053 // PVOID inptr,
1054 // LONG VfDelta,
1055 // PVOID SrcType,
1056 // PVOID TargetType,
1057 // BOOL isReference)
1058 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1059 CGF.Int8PtrTy, CGF.Int32Ty};
1060 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1061 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1062 "__RTDynamicCast");
1063 llvm::Value *Args[] = {
1064 ThisPtr, Offset, SrcRTTI, DestRTTI,
1065 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1066 return CGF.EmitRuntimeCallOrInvoke(Function, Args);
1067}
1068
1069llvm::Value *MicrosoftCXXABI::emitDynamicCastToVoid(CodeGenFunction &CGF,
1070 Address Value,
1071 QualType SrcRecordTy) {
1072 std::tie(Value, std::ignore, std::ignore) =
1073 performBaseAdjustment(CGF, Value, SrcRecordTy);
1074
1075 // PVOID __RTCastToVoid(
1076 // PVOID inptr)
1077 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1078 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1079 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1080 "__RTCastToVoid");
1081 llvm::Value *Args[] = {Value.emitRawPointer(CGF)};
1082 return CGF.EmitRuntimeCall(Function, Args);
1083}
1084
1085bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1086 return false;
1087}
1088
1089llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1090 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1091 const CXXRecordDecl *BaseClassDecl) {
1092 const ASTContext &Context = getContext();
1093 int64_t VBPtrChars =
1094 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1095 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1096 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1097 CharUnits VBTableChars =
1098 IntSize *
1099 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1100 llvm::Value *VBTableOffset =
1101 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1102
1103 llvm::Value *VBPtrToNewBase =
1104 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1105 VBPtrToNewBase =
1106 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1107 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1108}
1109
1110bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1111 return isa<CXXConstructorDecl>(GD.getDecl());
1112}
1113
1115 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1116 (GD.getDtorType() == Dtor_Deleting ||
1118}
1119
1120bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1121 return isDeletingDtor(GD);
1122}
1123
1124static bool isTrivialForMSVC(const CXXRecordDecl *RD, QualType Ty,
1125 CodeGenModule &CGM) {
1126 // On AArch64, HVAs that can be passed in registers can also be returned
1127 // in registers. (Note this is using the MSVC definition of an HVA; see
1128 // isPermittedToBeHomogeneousAggregate().)
1129 const Type *Base = nullptr;
1130 uint64_t NumElts = 0;
1131 if (CGM.getTarget().getTriple().isAArch64() &&
1132 CGM.getABIInfo().isHomogeneousAggregate(Ty, Base, NumElts) &&
1134 return true;
1135 }
1136
1137 // We use the C++14 definition of an aggregate, so we also
1138 // check for:
1139 // No private or protected non static data members.
1140 // No base classes
1141 // No virtual functions
1142 // Additionally, we need to ensure that there is a trivial copy assignment
1143 // operator, a trivial destructor, no user-provided constructors and no
1144 // deleted copy assignment operator.
1145
1146 // We need to cover two cases when checking for a deleted copy assignment
1147 // operator.
1148 //
1149 // struct S { int& r; };
1150 // The above will have an implicit copy assignment operator that is deleted
1151 // and there will not be a `CXXMethodDecl` for the copy assignment operator.
1152 // This is handled by the `needsImplicitCopyAssignment()` check below.
1153 //
1154 // struct S { S& operator=(const S&) = delete; int i; };
1155 // The above will not have an implicit copy assignment operator that is
1156 // deleted but there is a deleted `CXXMethodDecl` for the declared copy
1157 // assignment operator. This is handled by the `isDeleted()` check below.
1158
1159 if (RD->hasProtectedFields() || RD->hasPrivateFields())
1160 return false;
1161 if (RD->getNumBases() > 0)
1162 return false;
1163 if (RD->isPolymorphic())
1164 return false;
1166 return false;
1168 return false;
1169 for (const Decl *D : RD->decls()) {
1170 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1171 if (Ctor->isUserProvided())
1172 return false;
1173 } else if (auto *Template = dyn_cast<FunctionTemplateDecl>(D)) {
1174 if (isa<CXXConstructorDecl>(Template->getTemplatedDecl()))
1175 return false;
1176 } else if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
1177 if (MethodDecl->isCopyAssignmentOperator() && MethodDecl->isDeleted())
1178 return false;
1179 }
1180 }
1181 if (RD->hasNonTrivialDestructor())
1182 return false;
1183 return true;
1184}
1185
1186bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1187 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1188 if (!RD)
1189 return false;
1190
1191 bool isTrivialForABI = RD->canPassInRegisters() &&
1192 isTrivialForMSVC(RD, FI.getReturnType(), CGM);
1193
1194 // MSVC always returns structs indirectly from C++ instance methods.
1195 bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
1196
1197 if (isIndirectReturn) {
1198 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1200 Align, /*AddrSpace=*/CGM.getDataLayout().getAllocaAddrSpace(),
1201 /*ByVal=*/false);
1202
1203 // MSVC always passes `this` before the `sret` parameter.
1205
1206 // On AArch64, use the `inreg` attribute if the object is considered to not
1207 // be trivially copyable, or if this is an instance method struct return.
1208 FI.getReturnInfo().setInReg(CGM.getTarget().getTriple().isAArch64());
1209
1210 return true;
1211 }
1212
1213 // Otherwise, use the C ABI rules.
1214 return false;
1215}
1216
1217llvm::BasicBlock *
1218MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1219 const CXXRecordDecl *RD) {
1220 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1221 assert(IsMostDerivedClass &&
1222 "ctor for a class with virtual bases must have an implicit parameter");
1223 llvm::Value *IsCompleteObject =
1224 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1225
1226 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1227 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1228 CGF.Builder.CreateCondBr(IsCompleteObject,
1229 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1230
1231 CGF.EmitBlock(CallVbaseCtorsBB);
1232
1233 // Fill in the vbtable pointers here.
1234 EmitVBPtrStores(CGF, RD);
1235
1236 // CGF will put the base ctor calls in this basic block for us later.
1237
1238 return SkipVbaseCtorsBB;
1239}
1240
1241llvm::BasicBlock *
1242MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1243 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1244 assert(IsMostDerivedClass &&
1245 "ctor for a class with virtual bases must have an implicit parameter");
1246 llvm::Value *IsCompleteObject =
1247 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1248
1249 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1250 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1251 CGF.Builder.CreateCondBr(IsCompleteObject,
1252 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1253
1254 CGF.EmitBlock(CallVbaseDtorsBB);
1255 // CGF will put the base dtor calls in this basic block for us later.
1256
1257 return SkipVbaseDtorsBB;
1258}
1259
1260void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1261 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1262 // In most cases, an override for a vbase virtual method can adjust
1263 // the "this" parameter by applying a constant offset.
1264 // However, this is not enough while a constructor or a destructor of some
1265 // class X is being executed if all the following conditions are met:
1266 // - X has virtual bases, (1)
1267 // - X overrides a virtual method M of a vbase Y, (2)
1268 // - X itself is a vbase of the most derived class.
1269 //
1270 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1271 // which holds the extra amount of "this" adjustment we must do when we use
1272 // the X vftables (i.e. during X ctor or dtor).
1273 // Outside the ctors and dtors, the values of vtorDisps are zero.
1274
1275 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1276 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1277 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1278 CGBuilderTy &Builder = CGF.Builder;
1279
1280 llvm::Value *Int8This = nullptr; // Initialize lazily.
1281
1282 for (const CXXBaseSpecifier &S : RD->vbases()) {
1283 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1284 auto I = VBaseMap.find(VBase);
1285 assert(I != VBaseMap.end());
1286 if (!I->second.hasVtorDisp())
1287 continue;
1288
1289 llvm::Value *VBaseOffset =
1290 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1291 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1292
1293 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1294 llvm::Value *VtorDispValue = Builder.CreateSub(
1295 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1296 "vtordisp.value");
1297 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1298
1299 if (!Int8This)
1300 Int8This = getThisValue(CGF);
1301
1302 llvm::Value *VtorDispPtr =
1303 Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
1304 // vtorDisp is always the 32-bits before the vbase in the class layout.
1305 VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
1306
1307 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1309 }
1310}
1311
1313 const CXXMethodDecl *MD) {
1314 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1315 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1316 CallingConv ActualCallingConv =
1317 MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1318 return ExpectedCallingConv == ActualCallingConv;
1319}
1320
1321void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1322 // There's only one constructor type in this ABI.
1323 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1324
1325 // Exported default constructors either have a simple call-site where they use
1326 // the typical calling convention and have a single 'this' pointer for an
1327 // argument -or- they get a wrapper function which appropriately thunks to the
1328 // real default constructor. This thunk is the default constructor closure.
1329 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
1330 D->isDefined()) {
1331 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1332 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1333 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1334 CGM.setGVProperties(Fn, D);
1335 }
1336 }
1337}
1338
1339void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1340 const CXXRecordDecl *RD) {
1341 Address This = getThisAddress(CGF);
1342 This = This.withElementType(CGM.Int8Ty);
1343 const ASTContext &Context = getContext();
1344 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1345
1346 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1347 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1348 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1349 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1350 const ASTRecordLayout &SubobjectLayout =
1351 Context.getASTRecordLayout(VBT->IntroducingObject);
1352 CharUnits Offs = VBT->NonVirtualOffset;
1353 Offs += SubobjectLayout.getVBPtrOffset();
1354 if (VBT->getVBaseWithVPtr())
1355 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1356 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1357 llvm::Value *GVPtr =
1358 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1359 VBPtr = VBPtr.withElementType(GVPtr->getType());
1360 CGF.Builder.CreateStore(GVPtr, VBPtr);
1361 }
1362}
1363
1364CGCXXABI::AddedStructorArgCounts
1365MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1366 SmallVectorImpl<CanQualType> &ArgTys) {
1367 AddedStructorArgCounts Added;
1368 // TODO: 'for base' flag
1369 if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1370 (GD.getDtorType() == Dtor_Deleting ||
1372 // The scalar deleting destructor takes an implicit int parameter.
1373 ArgTys.push_back(getContext().IntTy);
1374 ++Added.Suffix;
1375 }
1376 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1377 if (!CD)
1378 return Added;
1379
1380 // All parameters are already in place except is_most_derived, which goes
1381 // after 'this' if it's variadic and last if it's not.
1382
1383 const CXXRecordDecl *Class = CD->getParent();
1384 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1385 if (Class->getNumVBases()) {
1386 if (FPT->isVariadic()) {
1387 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1388 ++Added.Prefix;
1389 } else {
1390 ArgTys.push_back(getContext().IntTy);
1391 ++Added.Suffix;
1392 }
1393 }
1394
1395 return Added;
1396}
1397
1398void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1399 const CXXDestructorDecl *Dtor,
1400 CXXDtorType DT) const {
1401 // Deleting destructor variants are never imported or exported. Give them the
1402 // default storage class.
1403 if (DT == Dtor_Deleting || DT == Dtor_VectorDeleting) {
1404 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1405 } else {
1406 const NamedDecl *ND = Dtor;
1407 CGM.setDLLImportDLLExport(GV, ND);
1408 }
1409}
1410
1411llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1412 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1413 // Internal things are always internal, regardless of attributes. After this,
1414 // we know the thunk is externally visible.
1415 if (Linkage == GVA_Internal)
1416 return llvm::GlobalValue::InternalLinkage;
1417
1418 switch (DT) {
1419 case Dtor_Base:
1420 // The base destructor most closely tracks the user-declared constructor, so
1421 // we delegate back to the normal declarator case.
1422 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage);
1423 case Dtor_Complete:
1424 // The complete destructor is like an inline function, but it may be
1425 // imported and therefore must be exported as well. This requires changing
1426 // the linkage if a DLL attribute is present.
1427 if (Dtor->hasAttr<DLLExportAttr>())
1428 return llvm::GlobalValue::WeakODRLinkage;
1429 if (Dtor->hasAttr<DLLImportAttr>())
1430 return llvm::GlobalValue::AvailableExternallyLinkage;
1431 return llvm::GlobalValue::LinkOnceODRLinkage;
1432 case Dtor_Deleting:
1433 // Deleting destructors are like inline functions. They have vague linkage
1434 // and are emitted everywhere they are used. They are internal if the class
1435 // is internal.
1436 return llvm::GlobalValue::LinkOnceODRLinkage;
1437 case Dtor_Unified:
1438 llvm_unreachable("MS C++ ABI does not support unified dtors");
1440 // Use the weak, non-ODR linkage for vector deleting destructors to block
1441 // inlining. This enables an MS ABI code-size saving optimization that
1442 // allows us to avoid emitting array deletion code when arrays of a given
1443 // type are not allocated within the final linkage unit.
1444 return llvm::GlobalValue::WeakAnyLinkage;
1445 case Dtor_Comdat:
1446 llvm_unreachable("MS C++ ABI does not support comdat dtors");
1447 }
1448 llvm_unreachable("invalid dtor type");
1449}
1450
1451void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1452 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1453 // other destructor variants are delegating thunks.
1454 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1455
1456 // If the class is dllexported, emit the complete (vbase) destructor wherever
1457 // the base dtor is emitted.
1458 // FIXME: To match MSVC, this should only be done when the class is exported
1459 // with -fdllexport-inlines enabled.
1460 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
1461 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1462}
1463
1464CharUnits
1465MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1466 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1467
1468 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1469 // Complete destructors take a pointer to the complete object as a
1470 // parameter, thus don't need this adjustment.
1471 if (GD.getDtorType() == Dtor_Complete)
1472 return CharUnits();
1473
1474 // There's no Dtor_Base in vftable but it shares the this adjustment with
1475 // the deleting one, so look it up instead.
1476 GD =
1477 GlobalDecl(DD, CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
1478 CGM.getContext().getLangOpts())
1480 : Dtor_Deleting);
1481 }
1482
1483 MethodVFTableLocation ML =
1485 CharUnits Adjustment = ML.VFPtrOffset;
1486
1487 // Normal virtual instance methods need to adjust from the vfptr that first
1488 // defined the virtual method to the virtual base subobject, but destructors
1489 // do not. The vector deleting destructor thunk applies this adjustment for
1490 // us if necessary.
1491 if (isa<CXXDestructorDecl>(MD))
1492 Adjustment = CharUnits::Zero();
1493
1494 if (ML.VBase) {
1495 const ASTRecordLayout &DerivedLayout =
1496 getContext().getASTRecordLayout(MD->getParent());
1497 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1498 }
1499
1500 return Adjustment;
1501}
1502
1503Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1504 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1505 bool VirtualCall) {
1506 if (!VirtualCall) {
1507 // If the call of a virtual function is not virtual, we just have to
1508 // compensate for the adjustment the virtual function does in its prologue.
1509 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1510 if (Adjustment.isZero())
1511 return This;
1512
1513 This = This.withElementType(CGF.Int8Ty);
1514 assert(Adjustment.isPositive());
1515 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1516 }
1517
1518 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1519
1520 GlobalDecl LookupGD = GD;
1521 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1522 // Complete dtors take a pointer to the complete object,
1523 // thus don't need adjustment.
1524 if (GD.getDtorType() == Dtor_Complete)
1525 return This;
1526
1527 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1528 // with the base one, so look up the deleting one instead.
1529 LookupGD =
1530 GlobalDecl(DD, CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
1531 CGM.getContext().getLangOpts())
1533 : Dtor_Deleting);
1534 }
1535 MethodVFTableLocation ML =
1537
1538 CharUnits StaticOffset = ML.VFPtrOffset;
1539
1540 // Base destructors expect 'this' to point to the beginning of the base
1541 // subobject, not the first vfptr that happens to contain the virtual dtor.
1542 // However, we still need to apply the virtual base adjustment.
1543 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1544 StaticOffset = CharUnits::Zero();
1545
1546 Address Result = This;
1547 if (ML.VBase) {
1548 Result = Result.withElementType(CGF.Int8Ty);
1549
1550 const CXXRecordDecl *Derived = MD->getParent();
1551 const CXXRecordDecl *VBase = ML.VBase;
1552 llvm::Value *VBaseOffset =
1553 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1554 llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
1555 Result.getElementType(), Result.emitRawPointer(CGF), VBaseOffset);
1556 CharUnits VBaseAlign =
1557 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1558 Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);
1559 }
1560 if (!StaticOffset.isZero()) {
1561 assert(StaticOffset.isPositive());
1562 Result = Result.withElementType(CGF.Int8Ty);
1563 if (ML.VBase) {
1564 // Non-virtual adjustment might result in a pointer outside the allocated
1565 // object, e.g. if the final overrider class is laid out after the virtual
1566 // base that declares a method in the most derived class.
1567 // FIXME: Update the code that emits this adjustment in thunks prologues.
1568 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1569 } else {
1570 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1571 }
1572 }
1573 return Result;
1574}
1575
1576void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1577 QualType &ResTy,
1578 FunctionArgList &Params) {
1579 ASTContext &Context = getContext();
1580 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1582 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1583 auto *IsMostDerived = ImplicitParamDecl::Create(
1584 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1585 &Context.Idents.get("is_most_derived"), Context.IntTy,
1586 ImplicitParamKind::Other);
1587 // The 'most_derived' parameter goes second if the ctor is variadic and last
1588 // if it's not. Dtors can't be variadic.
1589 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1590 if (FPT->isVariadic())
1591 Params.insert(Params.begin() + 1, IsMostDerived);
1592 else
1593 Params.push_back(IsMostDerived);
1594 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1595 } else if (isDeletingDtor(CGF.CurGD)) {
1596 auto *ShouldDelete = ImplicitParamDecl::Create(
1597 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1598 &Context.Idents.get("should_call_delete"), Context.IntTy,
1599 ImplicitParamKind::Other);
1600 Params.push_back(ShouldDelete);
1601 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1602 }
1603}
1604
1605void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1606 // Naked functions have no prolog.
1607 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1608 return;
1609
1610 // Overridden virtual methods of non-primary bases need to adjust the incoming
1611 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1612 // sizeof(void*) to adjust from B* to C*:
1613 // struct A { virtual void a(); };
1614 // struct B { virtual void b(); };
1615 // struct C : A, B { virtual void b(); };
1616 //
1617 // Leave the value stored in the 'this' alloca unadjusted, so that the
1618 // debugger sees the unadjusted value. Microsoft debuggers require this, and
1619 // will apply the ThisAdjustment in the method type information.
1620 // FIXME: Do something better for DWARF debuggers, which won't expect this,
1621 // without making our codegen depend on debug info settings.
1622 llvm::Value *This = loadIncomingCXXThis(CGF);
1623 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1624 if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1625 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1626 if (!Adjustment.isZero()) {
1627 assert(Adjustment.isPositive());
1628 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1629 -Adjustment.getQuantity());
1630 }
1631 }
1632 setCXXABIThisValue(CGF, This);
1633
1634 // If this is a function that the ABI specifies returns 'this', initialize
1635 // the return slot to 'this' at the start of the function.
1636 //
1637 // Unlike the setting of return types, this is done within the ABI
1638 // implementation instead of by clients of CGCXXABI because:
1639 // 1) getThisValue is currently protected
1640 // 2) in theory, an ABI could implement 'this' returns some other way;
1641 // HasThisReturn only specifies a contract, not the implementation
1642 if (HasThisReturn(CGF.CurGD) || hasMostDerivedReturn(CGF.CurGD))
1643 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1644
1645 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1646 assert(getStructorImplicitParamDecl(CGF) &&
1647 "no implicit parameter for a constructor with virtual bases?");
1648 getStructorImplicitParamValue(CGF)
1649 = CGF.Builder.CreateLoad(
1650 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1651 "is_most_derived");
1652 }
1653
1654 if (isDeletingDtor(CGF.CurGD)) {
1655 assert(getStructorImplicitParamDecl(CGF) &&
1656 "no implicit parameter for a deleting destructor?");
1657 getStructorImplicitParamValue(CGF)
1658 = CGF.Builder.CreateLoad(
1659 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1660 "should_call_delete");
1661 }
1662}
1663
1664CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1665 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1666 bool ForVirtualBase, bool Delegating) {
1667 assert(Type == Ctor_Complete || Type == Ctor_Base);
1668
1669 // Check if we need a 'most_derived' parameter.
1670 if (!D->getParent()->getNumVBases())
1671 return AddedStructorArgs{};
1672
1673 // Add the 'most_derived' argument second if we are variadic or last if not.
1674 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1675 llvm::Value *MostDerivedArg;
1676 if (Delegating) {
1677 MostDerivedArg = getStructorImplicitParamValue(CGF);
1678 } else {
1679 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1680 }
1681 if (FPT->isVariadic()) {
1682 return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1683 }
1684 return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1685}
1686
1687llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1688 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
1689 bool ForVirtualBase, bool Delegating) {
1690 return nullptr;
1691}
1692
1693void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1694 const CXXDestructorDecl *DD,
1695 CXXDtorType Type, bool ForVirtualBase,
1696 bool Delegating, Address This,
1697 QualType ThisTy) {
1698 // Use the base destructor variant in place of the complete destructor variant
1699 // if the class has no virtual bases. This effectively implements some of the
1700 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1701 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
1702 Type = Dtor_Base;
1703
1704 GlobalDecl GD(DD, Type);
1705 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1706
1707 if (DD->isVirtual()) {
1708 assert(Type != CXXDtorType::Dtor_Deleting &&
1709 "The deleting destructor should only be called via a virtual call");
1710 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1711 This, false);
1712 }
1713
1714 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1715 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1716 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1717 }
1718
1719 llvm::Value *Implicit =
1720 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1721 Delegating); // = nullptr
1722 CGF.EmitCXXDestructorCall(GD, Callee, CGF.getAsNaturalPointerTo(This, ThisTy),
1723 ThisTy,
1724 /*ImplicitParam=*/Implicit,
1725 /*ImplicitParamTy=*/QualType(), /*E=*/nullptr);
1726 if (BaseDtorEndBB) {
1727 // Complete object handler should continue to be the remaining
1728 CGF.Builder.CreateBr(BaseDtorEndBB);
1729 CGF.EmitBlock(BaseDtorEndBB);
1730 }
1731}
1732
1733void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1734 const CXXRecordDecl *RD,
1735 llvm::GlobalVariable *VTable) {
1736 // Emit type metadata on vtables with LTO or IR instrumentation.
1737 // In IR instrumentation, the type metadata could be used to find out vtable
1738 // definitions (for type profiling) among all global variables.
1739 if (!CGM.getCodeGenOpts().LTOUnit &&
1741 return;
1742
1743 // TODO: Should VirtualFunctionElimination also be supported here?
1744 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1745 if (CGM.getCodeGenOpts().WholeProgramVTables) {
1746 llvm::DenseSet<const CXXRecordDecl *> Visited;
1747 llvm::GlobalObject::VCallVisibility TypeVis =
1748 CGM.GetVCallVisibilityLevel(RD, Visited);
1749 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1750 VTable->setVCallVisibilityMetadata(TypeVis);
1751 }
1752
1753 // The location of the first virtual function pointer in the virtual table,
1754 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1755 // disabled, or sizeof(void*) if RTTI is enabled.
1756 CharUnits AddressPoint =
1757 getContext().getLangOpts().RTTIData
1758 ? getContext().toCharUnitsFromBits(
1759 getContext().getTargetInfo().getPointerWidth(LangAS::Default))
1760 : CharUnits::Zero();
1761
1762 if (Info.PathToIntroducingObject.empty()) {
1763 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1764 return;
1765 }
1766
1767 // Add a bitset entry for the least derived base belonging to this vftable.
1768 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1769 Info.PathToIntroducingObject.back());
1770
1771 // Add a bitset entry for each derived class that is laid out at the same
1772 // offset as the least derived base.
1773 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1774 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1775 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1776
1777 const ASTRecordLayout &Layout =
1778 getContext().getASTRecordLayout(DerivedRD);
1779 CharUnits Offset;
1780 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1781 if (VBI == Layout.getVBaseOffsetsMap().end())
1782 Offset = Layout.getBaseClassOffset(BaseRD);
1783 else
1784 Offset = VBI->second.VBaseOffset;
1785 if (!Offset.isZero())
1786 return;
1787 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1788 }
1789
1790 // Finally do the same for the most derived class.
1791 if (Info.FullOffsetInMDC.isZero())
1792 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1793}
1794
1795void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1796 const CXXRecordDecl *RD) {
1797 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1798 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1799
1800 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1801 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1802 if (VTable->hasInitializer())
1803 continue;
1804
1805 const VTableLayout &VTLayout =
1806 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1807
1808 llvm::Constant *RTTI = nullptr;
1809 if (any_of(VTLayout.vtable_components(),
1810 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1811 RTTI = getMSCompleteObjectLocator(RD, *Info);
1812
1813 ConstantInitBuilder builder(CGM);
1814 auto components = builder.beginStruct();
1815 CGVT.createVTableInitializer(components, VTLayout, RTTI,
1816 VTable->hasLocalLinkage());
1817 components.finishAndSetAsInitializer(VTable);
1818
1819 emitVTableTypeMetadata(*Info, RD, VTable);
1820 }
1821}
1822
1823bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1824 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1825 return Vptr.NearestVBase != nullptr;
1826}
1827
1828llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1829 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1830 const CXXRecordDecl *NearestVBase) {
1831 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1832 if (!VTableAddressPoint) {
1833 assert(Base.getBase()->getNumVBases() &&
1834 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1835 }
1836 return VTableAddressPoint;
1837}
1838
1840 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1841 SmallString<256> &Name) {
1842 llvm::raw_svector_ostream Out(Name);
1843 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1844}
1845
1846llvm::Constant *
1847MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1848 const CXXRecordDecl *VTableClass) {
1849 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1850 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1851 return VFTablesMap[ID];
1852}
1853
1854llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1855 CharUnits VPtrOffset) {
1856 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1857 // shouldn't be used in the given record type. We want to cache this result in
1858 // VFTablesMap, thus a simple zero check is not sufficient.
1859
1860 VFTableIdTy ID(RD, VPtrOffset);
1861 auto [I, Inserted] = VTablesMap.try_emplace(ID);
1862 if (!Inserted)
1863 return I->second;
1864
1865 llvm::GlobalVariable *&VTable = I->second;
1866
1867 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1868 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1869
1870 if (DeferredVFTables.insert(RD).second) {
1871 // We haven't processed this record type before.
1872 // Queue up this vtable for possible deferred emission.
1873 CGM.addDeferredVTable(RD);
1874
1875#ifndef NDEBUG
1876 // Create all the vftables at once in order to make sure each vftable has
1877 // a unique mangled name.
1878 llvm::StringSet<> ObservedMangledNames;
1879 for (const auto &VFPtr : VFPtrs) {
1880 SmallString<256> Name;
1881 mangleVFTableName(getMangleContext(), RD, *VFPtr, Name);
1882 if (!ObservedMangledNames.insert(Name.str()).second)
1883 llvm_unreachable("Already saw this mangling before?");
1884 }
1885#endif
1886 }
1887
1888 const std::unique_ptr<VPtrInfo> *VFPtrI =
1889 llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
1890 return VPI->FullOffsetInMDC == VPtrOffset;
1891 });
1892 if (VFPtrI == VFPtrs.end()) {
1893 VFTablesMap[ID] = nullptr;
1894 return nullptr;
1895 }
1896 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1897
1898 SmallString<256> VFTableName;
1899 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1900
1901 // Classes marked __declspec(dllimport) need vftables generated on the
1902 // import-side in order to support features like constexpr. No other
1903 // translation unit relies on the emission of the local vftable, translation
1904 // units are expected to generate them as needed.
1905 //
1906 // Because of this unique behavior, we maintain this logic here instead of
1907 // getVTableLinkage.
1908 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1909 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1910 : CGM.getVTableLinkage(RD);
1911 bool VFTableComesFromAnotherTU =
1912 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1913 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1914 bool VTableAliasIsRequred =
1915 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1916
1917 if (llvm::GlobalValue *VFTable =
1918 CGM.getModule().getNamedGlobal(VFTableName)) {
1919 VFTablesMap[ID] = VFTable;
1920 VTable = VTableAliasIsRequred
1922 cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
1923 : cast<llvm::GlobalVariable>(VFTable);
1924 return VTable;
1925 }
1926
1927 const VTableLayout &VTLayout =
1928 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1929 llvm::GlobalValue::LinkageTypes VTableLinkage =
1930 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1931
1932 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1933
1934 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1935
1936 // Create a backing variable for the contents of VTable. The VTable may
1937 // or may not include space for a pointer to RTTI data.
1938 llvm::GlobalValue *VFTable;
1939 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1940 /*isConstant=*/true, VTableLinkage,
1941 /*Initializer=*/nullptr, VTableName);
1942 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1943
1944 llvm::Comdat *C = nullptr;
1945 if (!VFTableComesFromAnotherTU &&
1946 llvm::GlobalValue::isWeakForLinker(VFTableLinkage))
1947 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1948
1949 // Only insert a pointer into the VFTable for RTTI data if we are not
1950 // importing it. We never reference the RTTI data directly so there is no
1951 // need to make room for it.
1952 if (VTableAliasIsRequred) {
1953 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1954 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1955 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1956 // Create a GEP which points just after the first entry in the VFTable,
1957 // this should be the location of the first virtual method.
1958 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1959 VTable->getValueType(), VTable, GEPIndices);
1960 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1961 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1962 if (C)
1963 C->setSelectionKind(llvm::Comdat::Largest);
1964 }
1965 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1966 /*AddressSpace=*/0, VFTableLinkage,
1967 VFTableName.str(), VTableGEP,
1968 &CGM.getModule());
1969 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1970 } else {
1971 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1972 // be referencing any RTTI data.
1973 // The GlobalVariable will end up being an appropriate definition of the
1974 // VFTable.
1975 VFTable = VTable;
1976 }
1977 if (C)
1978 VTable->setComdat(C);
1979
1980 if (RD->hasAttr<DLLExportAttr>())
1981 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1982
1983 VFTablesMap[ID] = VFTable;
1984 return VTable;
1985}
1986
1987CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1988 GlobalDecl GD,
1989 Address This,
1990 llvm::Type *Ty,
1991 SourceLocation Loc) {
1992 CGBuilderTy &Builder = CGF.Builder;
1993
1994 Ty = CGF.DefaultPtrTy;
1995 Address VPtr =
1996 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1997
1998 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1999 llvm::Value *VTable =
2000 CGF.GetVTablePtr(VPtr, CGF.DefaultPtrTy, MethodDecl->getParent());
2001
2002 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
2003 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
2004
2005 // Compute the identity of the most derived class whose virtual table is
2006 // located at the MethodVFTableLocation ML.
2007 auto getObjectWithVPtr = [&] {
2008 return llvm::find_if(VFTContext.getVFPtrOffsets(
2009 ML.VBase ? ML.VBase : MethodDecl->getParent()),
2010 [&](const std::unique_ptr<VPtrInfo> &Info) {
2011 return Info->FullOffsetInMDC == ML.VFPtrOffset;
2012 })
2013 ->get()
2014 ->ObjectWithVPtr;
2015 };
2016
2017 llvm::Value *VFunc;
2018 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
2019 VFunc = CGF.EmitVTableTypeCheckedLoad(
2020 getObjectWithVPtr(), VTable, Ty,
2021 ML.Index *
2022 CGM.getContext().getTargetInfo().getPointerWidth(LangAS::Default) /
2023 8);
2024 } else {
2025 if (CGM.getCodeGenOpts().PrepareForLTO)
2026 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
2027
2028 llvm::Value *VFuncPtr =
2029 Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
2030 VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
2031 }
2032
2033 CGCallee Callee(GD, VFunc);
2034 return Callee;
2035}
2036
2037llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
2038 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
2039 Address This, DeleteOrMemberCallExpr E, llvm::CallBase **CallOrInvoke) {
2040 auto *CE = dyn_cast<const CXXMemberCallExpr *>(E);
2041 auto *D = dyn_cast<const CXXDeleteExpr *>(E);
2042 assert((CE != nullptr) ^ (D != nullptr));
2043 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
2044 assert(DtorType == Dtor_VectorDeleting || DtorType == Dtor_Complete ||
2045 DtorType == Dtor_Deleting);
2046
2047 // We have only one destructor in the vftable but can get both behaviors
2048 // by passing an implicit int parameter.
2049 ASTContext &Context = getContext();
2050 bool VectorDeletingDtorsEnabled =
2052 GlobalDecl GD(Dtor, VectorDeletingDtorsEnabled ? Dtor_VectorDeleting
2053 : Dtor_Deleting);
2054 const CGFunctionInfo *FInfo =
2056 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
2057 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
2058
2059 bool IsDeleting = DtorType == Dtor_Deleting;
2060 bool IsArrayDelete = D && D->isArrayForm() && VectorDeletingDtorsEnabled;
2061 bool IsGlobalDelete = D && D->isGlobalDelete() &&
2063 Context.getLangOpts());
2064 llvm::Value *ImplicitParam =
2065 CGF.Builder.getInt32((IsDeleting ? 1 : 0) | (IsGlobalDelete ? 4 : 0) |
2066 (IsArrayDelete ? 2 : 0));
2067
2068 QualType ThisTy;
2069 if (CE) {
2070 ThisTy = CE->getObjectType();
2071 } else {
2072 ThisTy = D->getDestroyedType();
2073 }
2074
2075 while (const ArrayType *ATy = Context.getAsArrayType(ThisTy))
2076 ThisTy = ATy->getElementType();
2077
2078 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
2079 RValue RV =
2080 CGF.EmitCXXDestructorCall(GD, Callee, This.emitRawPointer(CGF), ThisTy,
2081 ImplicitParam, Context.IntTy, CE, CallOrInvoke);
2082 return RV.getScalarVal();
2083}
2084
2085const VBTableGlobals &
2086MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
2087 // At this layer, we can key the cache off of a single class, which is much
2088 // easier than caching each vbtable individually.
2089 auto [Entry, Added] = VBTablesMap.try_emplace(RD);
2090 VBTableGlobals &VBGlobals = Entry->second;
2091 if (!Added)
2092 return VBGlobals;
2093
2094 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2095 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
2096
2097 // Cache the globals for all vbtables so we don't have to recompute the
2098 // mangled names.
2099 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2100 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
2101 E = VBGlobals.VBTables->end();
2102 I != E; ++I) {
2103 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
2104 }
2105
2106 return VBGlobals;
2107}
2108
2109llvm::Function *
2110MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
2111 const MethodVFTableLocation &ML) {
2112 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
2113 "can't form pointers to ctors or virtual dtors");
2114
2115 // Calculate the mangled name.
2116 SmallString<256> ThunkName;
2117 llvm::raw_svector_ostream Out(ThunkName);
2118 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
2119
2120 // If the thunk has been generated previously, just return it.
2121 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
2122 return cast<llvm::Function>(GV);
2123
2124 // Create the llvm::Function.
2125 const CGFunctionInfo &FnInfo =
2127 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2128 llvm::Function *ThunkFn =
2129 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2130 ThunkName.str(), &CGM.getModule());
2131 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2132
2133 ThunkFn->setLinkage(MD->isExternallyVisible()
2134 ? llvm::GlobalValue::LinkOnceODRLinkage
2135 : llvm::GlobalValue::InternalLinkage);
2136 if (MD->isExternallyVisible())
2137 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2138
2139 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
2141
2142 // Add the "thunk" attribute so that LLVM knows that the return type is
2143 // meaningless. These thunks can be used to call functions with differing
2144 // return types, and the caller is required to cast the prototype
2145 // appropriately to extract the correct value.
2146 ThunkFn->addFnAttr("thunk");
2147
2148 // These thunks can be compared, so they are not unnamed.
2149 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2150
2151 // Start codegen.
2152 CodeGenFunction CGF(CGM);
2153 CGF.CurGD = GlobalDecl(MD);
2154 CGF.CurFuncIsThunk = true;
2155
2156 // Build FunctionArgs, but only include the implicit 'this' parameter
2157 // declaration.
2158 FunctionArgList FunctionArgs;
2159 buildThisParam(CGF, FunctionArgs);
2160
2161 // Start defining the function.
2162 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2163 FunctionArgs, MD->getLocation(), SourceLocation());
2164
2165 ApplyDebugLocation AL(CGF, MD->getLocation());
2166 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2167
2168 // Load the vfptr and then callee from the vftable. The callee should have
2169 // adjusted 'this' so that the vfptr is at offset zero.
2170 llvm::Type *ThunkPtrTy = CGF.DefaultPtrTy;
2171 llvm::Value *VTable =
2172 CGF.GetVTablePtr(getThisAddress(CGF), CGF.DefaultPtrTy, MD->getParent());
2173
2174 llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2175 ThunkPtrTy, VTable, ML.Index, "vfn");
2176 llvm::Value *Callee =
2177 CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
2178
2179 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2180
2181 return ThunkFn;
2182}
2183
2184void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2185 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2186 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2187 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2188 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2189 if (GV->isDeclaration())
2190 emitVBTableDefinition(*VBT, RD, GV);
2191 }
2192}
2193
2194llvm::GlobalVariable *
2195MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2196 llvm::GlobalVariable::LinkageTypes Linkage) {
2197 SmallString<256> OutName;
2198 llvm::raw_svector_ostream Out(OutName);
2199 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2200 StringRef Name = OutName.str();
2201
2202 llvm::ArrayType *VBTableType =
2203 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2204
2205 assert(!CGM.getModule().getNamedGlobal(Name) &&
2206 "vbtable with this name already exists: mangling bug?");
2207 CharUnits Alignment =
2209 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2210 Name, VBTableType, Linkage, Alignment.getAsAlign());
2211 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2212
2213 if (RD->hasAttr<DLLImportAttr>())
2214 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2215 else if (RD->hasAttr<DLLExportAttr>())
2216 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2217
2218 if (!GV->hasExternalLinkage())
2219 emitVBTableDefinition(VBT, RD, GV);
2220
2221 return GV;
2222}
2223
2224void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2225 const CXXRecordDecl *RD,
2226 llvm::GlobalVariable *GV) const {
2227 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2228
2229 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2230 "should only emit vbtables for classes with vbtables");
2231
2232 const ASTRecordLayout &BaseLayout =
2233 getContext().getASTRecordLayout(VBT.IntroducingObject);
2234 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2235
2236 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2237 nullptr);
2238
2239 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2240 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2241 Offsets[0] =
2242 llvm::ConstantInt::getSigned(CGM.IntTy, -VBPtrOffset.getQuantity());
2243
2244 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2245 for (const auto &I : ObjectWithVPtr->vbases()) {
2246 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2247 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2248 assert(!Offset.isNegative());
2249
2250 // Make it relative to the subobject vbptr.
2251 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2252 if (VBT.getVBaseWithVPtr())
2253 CompleteVBPtrOffset +=
2254 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2255 Offset -= CompleteVBPtrOffset;
2256
2257 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2258 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2259 Offsets[VBIndex] =
2260 llvm::ConstantInt::getSigned(CGM.IntTy, Offset.getQuantity());
2261 }
2262
2263 assert(Offsets.size() ==
2264 cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
2265 llvm::ArrayType *VBTableType =
2266 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2267 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2268 GV->setInitializer(Init);
2269
2270 if (RD->hasAttr<DLLImportAttr>())
2271 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2272}
2273
2274llvm::Value *MicrosoftCXXABI::performThisAdjustment(
2275 CodeGenFunction &CGF, Address This,
2276 const CXXRecordDecl * /*UnadjustedClass*/, const ThunkInfo &TI) {
2277 const ThisAdjustment &TA = TI.This;
2278 if (TA.isEmpty())
2279 return This.emitRawPointer(CGF);
2280
2281 This = This.withElementType(CGF.Int8Ty);
2282
2283 llvm::Value *V;
2284 if (TA.Virtual.isEmpty()) {
2285 V = This.emitRawPointer(CGF);
2286 } else {
2287 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2288 // Adjust the this argument based on the vtordisp value.
2289 Address VtorDispPtr =
2292 VtorDispPtr = VtorDispPtr.withElementType(CGF.Int32Ty);
2293 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2294 V = CGF.Builder.CreateGEP(This.getElementType(), This.emitRawPointer(CGF),
2295 CGF.Builder.CreateNeg(VtorDisp));
2296
2297 // Unfortunately, having applied the vtordisp means that we no
2298 // longer really have a known alignment for the vbptr step.
2299 // We'll assume the vbptr is pointer-aligned.
2300
2301 if (TA.Virtual.Microsoft.VBPtrOffset) {
2302 // If the final overrider is defined in a virtual base other than the one
2303 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2304 // the vbtable of the derived class.
2305 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2306 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2307 llvm::Value *VBPtr;
2308 llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(
2309 CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),
2311 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2312 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2313 }
2314 }
2315
2316 if (TA.NonVirtual) {
2317 // Non-virtual adjustment might result in a pointer outside the allocated
2318 // object, e.g. if the final overrider class is laid out after the virtual
2319 // base that declares a method in the most derived class.
2320 V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
2321 }
2322
2323 // Don't need to bitcast back, the call CodeGen will handle this.
2324 return V;
2325}
2326
2327llvm::Value *MicrosoftCXXABI::performReturnAdjustment(
2328 CodeGenFunction &CGF, Address Ret,
2329 const CXXRecordDecl * /*UnadjustedClass*/, const ReturnAdjustment &RA) {
2330
2331 if (RA.isEmpty())
2332 return Ret.emitRawPointer(CGF);
2333
2334 Ret = Ret.withElementType(CGF.Int8Ty);
2335
2336 llvm::Value *V = Ret.emitRawPointer(CGF);
2337 if (RA.Virtual.Microsoft.VBIndex) {
2338 assert(RA.Virtual.Microsoft.VBIndex > 0);
2339 int32_t IntSize = CGF.getIntSize().getQuantity();
2340 llvm::Value *VBPtr;
2341 llvm::Value *VBaseOffset =
2342 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2343 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2344 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2345 }
2346
2347 if (RA.NonVirtual)
2348 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2349
2350 return V;
2351}
2352
2353bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2354 QualType elementType) {
2355 // Microsoft seems to completely ignore the possibility of a
2356 // two-argument usual deallocation function.
2357 return elementType.isDestructedType();
2358}
2359
2360bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2361 // Microsoft seems to completely ignore the possibility of a
2362 // two-argument usual deallocation function.
2363 return expr->getAllocatedType().isDestructedType();
2364}
2365
2366CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2367 // The array cookie is always a size_t; we then pad that out to the
2368 // alignment of the element type.
2369 ASTContext &Ctx = getContext();
2370 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2372}
2373
2374llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2375 Address allocPtr,
2376 CharUnits cookieSize) {
2377 Address numElementsPtr = allocPtr.withElementType(CGF.SizeTy);
2378 return CGF.Builder.CreateLoad(numElementsPtr);
2379}
2380
2381Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2382 Address newPtr,
2383 llvm::Value *numElements,
2384 const CXXNewExpr *expr,
2385 QualType elementType) {
2386 assert(requiresArrayCookie(expr));
2387
2388 // The size of the cookie.
2389 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2390
2391 // Compute an offset to the cookie.
2392 Address cookiePtr = newPtr;
2393
2394 // Write the number of elements into the appropriate slot.
2395 Address numElementsPtr = cookiePtr.withElementType(CGF.SizeTy);
2396 CGF.Builder.CreateStore(numElements, numElementsPtr);
2397
2398 // Finally, compute a pointer to the actual data buffer by skipping
2399 // over the cookie completely.
2400 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2401}
2402
2404 llvm::FunctionCallee Dtor,
2405 llvm::Constant *Addr) {
2406 // Create a function which calls the destructor.
2407 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2408
2409 // extern "C" int __tlregdtor(void (*f)(void));
2410 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2411 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2412
2413 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2414 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2415 if (llvm::Function *TLRegDtorFn =
2416 dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2417 TLRegDtorFn->setDoesNotThrow();
2418
2419 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2420}
2421
2422void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2423 llvm::FunctionCallee Dtor,
2424 llvm::Constant *Addr) {
2425 if (D.isNoDestroy(CGM.getContext()))
2426 return;
2427
2428 if (D.getTLSKind())
2429 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2430
2431 // HLSL doesn't support atexit.
2432 if (CGM.getLangOpts().HLSL)
2433 return CGM.AddCXXDtorEntry(Dtor, Addr);
2434
2435 // The default behavior is to use atexit.
2436 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2437}
2438
2439void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2440 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2441 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2442 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2443 if (CXXThreadLocalInits.empty())
2444 return;
2445
2446 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2447 llvm::Triple::x86
2448 ? "/include:___dyn_tls_init@12"
2449 : "/include:__dyn_tls_init");
2450
2451 // This will create a GV in the .CRT$XDU section. It will point to our
2452 // initialization function. The CRT will call all of these function
2453 // pointers at start-up time and, eventually, at thread-creation time.
2454 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2455 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2456 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2457 llvm::GlobalVariable::InternalLinkage, InitFunc,
2458 Twine(InitFunc->getName(), "$initializer$"));
2459 InitFuncPtr->setSection(".CRT$XDU");
2460 // This variable has discardable linkage, we have to add it to @llvm.used to
2461 // ensure it won't get discarded.
2462 CGM.addUsedGlobal(InitFuncPtr);
2463 return InitFuncPtr;
2464 };
2465
2466 std::vector<llvm::Function *> NonComdatInits;
2467 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2468 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2469 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2470 llvm::Function *F = CXXThreadLocalInits[I];
2471
2472 // If the GV is already in a comdat group, then we have to join it.
2473 if (llvm::Comdat *C = GV->getComdat())
2474 AddToXDU(F)->setComdat(C);
2475 else
2476 NonComdatInits.push_back(F);
2477 }
2478
2479 if (!NonComdatInits.empty()) {
2480 llvm::FunctionType *FTy =
2481 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2482 llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
2483 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2484 SourceLocation(), /*TLS=*/true);
2485 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2486
2487 AddToXDU(InitFunc);
2488 }
2489}
2490
2491static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
2492 // __tls_guard comes from the MSVC runtime and reflects
2493 // whether TLS has been initialized for a particular thread.
2494 // It is set from within __dyn_tls_init by the runtime.
2495 // Every library and executable has its own variable.
2496 llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
2497 llvm::Constant *TlsGuardConstant =
2498 CGM.CreateRuntimeVariable(VTy, "__tls_guard");
2499 llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
2500
2501 TlsGuard->setThreadLocal(true);
2502
2503 return TlsGuard;
2504}
2505
2506static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
2507 // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
2508 // dynamic TLS initialization by calling __dyn_tls_init internally.
2509 llvm::FunctionType *FTy =
2510 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
2511 /*isVarArg=*/false);
2512 return CGM.CreateRuntimeFunction(
2513 FTy, "__dyn_tls_on_demand_init",
2514 llvm::AttributeList::get(CGM.getLLVMContext(),
2515 llvm::AttributeList::FunctionIndex,
2516 llvm::Attribute::NoUnwind),
2517 /*Local=*/true);
2518}
2519
2520static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
2521 llvm::BasicBlock *DynInitBB,
2522 llvm::BasicBlock *ContinueBB) {
2523 llvm::LoadInst *TlsGuardValue =
2524 CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));
2525 llvm::Value *CmpResult =
2526 CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
2527 CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
2528}
2529
2531 llvm::GlobalValue *TlsGuard,
2532 llvm::BasicBlock *ContinueBB) {
2533 llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
2534 llvm::Function *InitializerFunction =
2535 cast<llvm::Function>(Initializer.getCallee());
2536 llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
2537 CallVal->setCallingConv(InitializerFunction->getCallingConv());
2538
2539 CGF.Builder.CreateBr(ContinueBB);
2540}
2541
2543 llvm::BasicBlock *DynInitBB =
2544 CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
2545 llvm::BasicBlock *ContinueBB =
2546 CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
2547
2548 llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
2549
2550 emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
2551 CGF.Builder.SetInsertPoint(DynInitBB);
2552 emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
2553 CGF.Builder.SetInsertPoint(ContinueBB);
2554}
2555
2556LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2557 const VarDecl *VD,
2558 QualType LValType) {
2559 // Dynamic TLS initialization works by checking the state of a
2560 // guard variable (__tls_guard) to see whether TLS initialization
2561 // for a thread has happend yet.
2562 // If not, the initialization is triggered on-demand
2563 // by calling __dyn_tls_on_demand_init.
2565
2566 // Emit the variable just like any regular global variable.
2567
2568 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2569 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2570
2571 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2572 Address Addr(V, RealVarTy, Alignment);
2573
2574 LValue LV = VD->getType()->isReferenceType()
2576 AlignmentSource::Decl)
2577 : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
2578 return LV;
2579}
2580
2582 StringRef VarName("_Init_thread_epoch");
2583 CharUnits Align = CGM.getIntAlign();
2584 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2585 return ConstantAddress(GV, GV->getValueType(), Align);
2586 auto *GV = new llvm::GlobalVariable(
2587 CGM.getModule(), CGM.IntTy,
2588 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2589 /*Initializer=*/nullptr, VarName,
2590 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2591 GV->setAlignment(Align.getAsAlign());
2592 return ConstantAddress(GV, GV->getValueType(), Align);
2593}
2594
2595static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2596 llvm::FunctionType *FTy =
2597 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2598 CGM.DefaultPtrTy, /*isVarArg=*/false);
2599 return CGM.CreateRuntimeFunction(
2600 FTy, "_Init_thread_header",
2601 llvm::AttributeList::get(CGM.getLLVMContext(),
2602 llvm::AttributeList::FunctionIndex,
2603 llvm::Attribute::NoUnwind),
2604 /*Local=*/true);
2605}
2606
2607static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2608 llvm::FunctionType *FTy =
2609 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2610 CGM.DefaultPtrTy, /*isVarArg=*/false);
2611 return CGM.CreateRuntimeFunction(
2612 FTy, "_Init_thread_footer",
2613 llvm::AttributeList::get(CGM.getLLVMContext(),
2614 llvm::AttributeList::FunctionIndex,
2615 llvm::Attribute::NoUnwind),
2616 /*Local=*/true);
2617}
2618
2619static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2620 llvm::FunctionType *FTy =
2621 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2622 CGM.DefaultPtrTy, /*isVarArg=*/false);
2623 return CGM.CreateRuntimeFunction(
2624 FTy, "_Init_thread_abort",
2625 llvm::AttributeList::get(CGM.getLLVMContext(),
2626 llvm::AttributeList::FunctionIndex,
2627 llvm::Attribute::NoUnwind),
2628 /*Local=*/true);
2629}
2630
2631namespace {
2632struct ResetGuardBit final : EHScopeStack::Cleanup {
2633 Address Guard;
2634 unsigned GuardNum;
2635 ResetGuardBit(Address Guard, unsigned GuardNum)
2636 : Guard(Guard), GuardNum(GuardNum) {}
2637
2638 void Emit(CodeGenFunction &CGF, Flags flags) override {
2639 // Reset the bit in the mask so that the static variable may be
2640 // reinitialized.
2641 CGBuilderTy &Builder = CGF.Builder;
2642 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2643 llvm::ConstantInt *Mask =
2644 llvm::ConstantInt::getSigned(CGF.IntTy, ~(1ULL << GuardNum));
2645 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2646 }
2647};
2648
2649struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2650 llvm::Value *Guard;
2651 CallInitThreadAbort(RawAddress Guard) : Guard(Guard.getPointer()) {}
2652
2653 void Emit(CodeGenFunction &CGF, Flags flags) override {
2654 // Calling _Init_thread_abort will reset the guard's state.
2656 }
2657};
2658}
2659
2660void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2661 llvm::GlobalVariable *GV,
2662 bool PerformInit) {
2663 // MSVC only uses guards for static locals.
2664 if (!D.isStaticLocal()) {
2665 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2666 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2667 llvm::Function *F = CGF.CurFn;
2668 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2669 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2670 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2671 return;
2672 }
2673
2674 bool ThreadlocalStatic = D.getTLSKind();
2675 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2676
2677 // Thread-safe static variables which aren't thread-specific have a
2678 // per-variable guard.
2679 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2680
2681 CGBuilderTy &Builder = CGF.Builder;
2682 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2683 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2684 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2685
2686 // Get the guard variable for this function if we have one already.
2687 GuardInfo *GI = nullptr;
2688 if (ThreadlocalStatic)
2689 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2690 else if (!ThreadsafeStatic)
2691 GI = &GuardVariableMap[D.getDeclContext()];
2692
2693 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2694 unsigned GuardNum;
2695 if (D.isExternallyVisible()) {
2696 // Externally visible variables have to be numbered in Sema to properly
2697 // handle unreachable VarDecls.
2698 GuardNum = getContext().getStaticLocalNumber(&D);
2699 assert(GuardNum > 0);
2700 GuardNum--;
2701 } else if (HasPerVariableGuard) {
2702 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2703 } else {
2704 // Non-externally visible variables are numbered here in CodeGen.
2705 GuardNum = GI->BitIndex++;
2706 }
2707
2708 if (!HasPerVariableGuard && GuardNum >= 32) {
2709 if (D.isExternallyVisible())
2710 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2711 GuardNum %= 32;
2712 GuardVar = nullptr;
2713 }
2714
2715 if (!GuardVar) {
2716 // Mangle the name for the guard.
2717 SmallString<256> GuardName;
2718 {
2719 llvm::raw_svector_ostream Out(GuardName);
2720 if (HasPerVariableGuard)
2721 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2722 Out);
2723 else
2724 getMangleContext().mangleStaticGuardVariable(&D, Out);
2725 }
2726
2727 // Create the guard variable with a zero-initializer. Just absorb linkage,
2728 // visibility and dll storage class from the guarded variable.
2729 GuardVar =
2730 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2731 GV->getLinkage(), Zero, GuardName.str());
2732 GuardVar->setVisibility(GV->getVisibility());
2733 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2734 GuardVar->setAlignment(GuardAlign.getAsAlign());
2735 if (GuardVar->isWeakForLinker())
2736 GuardVar->setComdat(
2737 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2738 if (D.getTLSKind())
2739 CGM.setTLSMode(GuardVar, D);
2740 if (GI && !HasPerVariableGuard)
2741 GI->Guard = GuardVar;
2742 }
2743
2744 ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
2745
2746 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2747 "static local from the same function had different linkage");
2748
2749 if (!HasPerVariableGuard) {
2750 // Pseudo code for the test:
2751 // if (!(GuardVar & MyGuardBit)) {
2752 // GuardVar |= MyGuardBit;
2753 // ... initialize the object ...;
2754 // }
2755
2756 // Test our bit from the guard variable.
2757 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2758 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2759 llvm::Value *NeedsInit =
2760 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2761 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2762 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2763 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2764 CodeGenFunction::GuardKind::VariableGuard, &D);
2765
2766 // Set our bit in the guard variable and emit the initializer and add a global
2767 // destructor if appropriate.
2768 CGF.EmitBlock(InitBlock);
2769 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2770 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2771 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2772 CGF.PopCleanupBlock();
2773 Builder.CreateBr(EndBlock);
2774
2775 // Continue.
2776 CGF.EmitBlock(EndBlock);
2777 } else {
2778 // Pseudo code for the test:
2779 // if (TSS > _Init_thread_epoch) {
2780 // _Init_thread_header(&TSS);
2781 // if (TSS == -1) {
2782 // ... initialize the object ...;
2783 // _Init_thread_footer(&TSS);
2784 // }
2785 // }
2786 //
2787 // The algorithm is almost identical to what can be found in the appendix
2788 // found in N2325.
2789
2790 // This BasicBLock determines whether or not we have any work to do.
2791 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2792 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2793 llvm::LoadInst *InitThreadEpoch =
2794 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2795 llvm::Value *IsUninitialized =
2796 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2797 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2798 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2799 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2800 CodeGenFunction::GuardKind::VariableGuard, &D);
2801
2802 // This BasicBlock attempts to determine whether or not this thread is
2803 // responsible for doing the initialization.
2804 CGF.EmitBlock(AttemptInitBlock);
2806 GuardAddr.getPointer());
2807 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2808 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2809 llvm::Value *ShouldDoInit =
2810 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2811 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2812 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2813
2814 // Ok, we ended up getting selected as the initializing thread.
2815 CGF.EmitBlock(InitBlock);
2816 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2817 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2818 CGF.PopCleanupBlock();
2820 GuardAddr.getPointer());
2821 Builder.CreateBr(EndBlock);
2822
2823 CGF.EmitBlock(EndBlock);
2824 }
2825}
2826
2827bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2828 // Null-ness for function memptrs only depends on the first field, which is
2829 // the function pointer. The rest don't matter, so we can zero initialize.
2830 if (MPT->isMemberFunctionPointer())
2831 return true;
2832
2833 // The virtual base adjustment field is always -1 for null, so if we have one
2834 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2835 // valid field offset.
2836 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2837 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2838 return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2839 RD->nullFieldOffsetIsZero());
2840}
2841
2842llvm::Type *
2843MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2844 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2845 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2846 llvm::SmallVector<llvm::Type *, 4> fields;
2847 if (MPT->isMemberFunctionPointer())
2848 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2849 else
2850 fields.push_back(CGM.IntTy); // FieldOffset
2851
2853 Inheritance))
2854 fields.push_back(CGM.IntTy);
2855 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2856 fields.push_back(CGM.IntTy);
2858 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2859
2860 if (fields.size() == 1)
2861 return fields[0];
2862 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2863}
2864
2865void MicrosoftCXXABI::
2866GetNullMemberPointerFields(const MemberPointerType *MPT,
2867 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2868 assert(fields.empty());
2869 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2870 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2871 if (MPT->isMemberFunctionPointer()) {
2872 // FunctionPointerOrVirtualThunk
2873 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2874 } else {
2875 if (RD->nullFieldOffsetIsZero())
2876 fields.push_back(getZeroInt()); // FieldOffset
2877 else
2878 fields.push_back(getAllOnesInt()); // FieldOffset
2879 }
2880
2882 Inheritance))
2883 fields.push_back(getZeroInt());
2884 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2885 fields.push_back(getZeroInt());
2887 fields.push_back(getAllOnesInt());
2888}
2889
2890llvm::Constant *
2891MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2892 llvm::SmallVector<llvm::Constant *, 4> fields;
2893 GetNullMemberPointerFields(MPT, fields);
2894 if (fields.size() == 1)
2895 return fields[0];
2896 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2897 assert(Res->getType() == ConvertMemberPointerType(MPT));
2898 return Res;
2899}
2900
2901llvm::Constant *
2902MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2903 bool IsMemberFunction,
2904 const CXXRecordDecl *RD,
2905 CharUnits NonVirtualBaseAdjustment,
2906 unsigned VBTableIndex) {
2907 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2908
2909 // Single inheritance class member pointer are represented as scalars instead
2910 // of aggregates.
2911 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2912 return FirstField;
2913
2914 llvm::SmallVector<llvm::Constant *, 4> fields;
2915 fields.push_back(FirstField);
2916
2917 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2918 fields.push_back(llvm::ConstantInt::getSigned(
2919 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2920
2921 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2922 CharUnits Offs = CharUnits::Zero();
2923 if (VBTableIndex)
2924 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2925 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2926 }
2927
2928 // The rest of the fields are adjusted by conversions to a more derived class.
2930 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2931
2932 return llvm::ConstantStruct::getAnon(fields);
2933}
2934
2935llvm::Constant *
2936MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2937 CharUnits offset) {
2938 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2939}
2940
2941llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2942 CharUnits offset) {
2943 if (RD->getMSInheritanceModel() ==
2944 MSInheritanceModel::Virtual)
2945 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2946 llvm::Constant *FirstField =
2947 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2948 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2949 CharUnits::Zero(), /*VBTableIndex=*/0);
2950}
2951
2952llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2953 QualType MPType) {
2954 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2955 const ValueDecl *MPD = MP.getMemberPointerDecl();
2956 if (!MPD)
2957 return EmitNullMemberPointer(DstTy);
2958
2959 ASTContext &Ctx = getContext();
2960 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2961
2962 llvm::Constant *C;
2963 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2964 C = EmitMemberFunctionPointer(MD);
2965 } else {
2966 // For a pointer to data member, start off with the offset of the field in
2967 // the class in which it was declared, and convert from there if necessary.
2968 // For indirect field decls, get the outermost anonymous field and use the
2969 // parent class.
2970 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2971 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2972 if (!FD)
2973 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2974 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2975 RD = RD->getMostRecentDecl();
2976 C = EmitMemberDataPointer(RD, FieldOffset);
2977 }
2978
2979 if (!MemberPointerPath.empty()) {
2980 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2981 const MemberPointerType *SrcTy =
2983 /*Qualifier=*/std::nullopt, SrcRD)
2984 ->castAs<MemberPointerType>();
2985
2986 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2987 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2988 const CXXRecordDecl *PrevRD = SrcRD;
2989 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2990 const CXXRecordDecl *Base = nullptr;
2991 const CXXRecordDecl *Derived = nullptr;
2992 if (DerivedMember) {
2993 Base = PathElem;
2994 Derived = PrevRD;
2995 } else {
2996 Base = PrevRD;
2997 Derived = PathElem;
2998 }
2999 for (const CXXBaseSpecifier &BS : Derived->bases())
3000 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
3001 Base->getCanonicalDecl())
3002 DerivedToBasePath.push_back(&BS);
3003 PrevRD = PathElem;
3004 }
3005 assert(DerivedToBasePath.size() == MemberPointerPath.size());
3006
3007 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
3008 : CK_BaseToDerivedMemberPointer;
3009 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
3010 DerivedToBasePath.end(), C);
3011 }
3012 return C;
3013}
3014
3015llvm::Constant *
3016MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
3017 assert(MD->isInstance() && "Member function must not be static!");
3018
3019 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
3020 const CXXRecordDecl *RD = MD->getParent()->getMostRecentDecl();
3021 CodeGenTypes &Types = CGM.getTypes();
3022
3023 unsigned VBTableIndex = 0;
3024 llvm::Constant *FirstField;
3025 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
3026 if (!MD->isVirtual()) {
3027 llvm::Type *Ty;
3028 // Check whether the function has a computable LLVM signature.
3029 if (Types.isFuncTypeConvertible(FPT)) {
3030 // The function has a computable LLVM signature; use the correct type.
3031 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
3032 } else {
3033 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
3034 // function type is incomplete.
3035 Ty = CGM.PtrDiffTy;
3036 }
3037 FirstField = CGM.GetAddrOfFunction(MD, Ty);
3038 } else {
3039 auto &VTableContext = CGM.getMicrosoftVTableContext();
3040 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
3041 FirstField = EmitVirtualMemPtrThunk(MD, ML);
3042 // Include the vfptr adjustment if the method is in a non-primary vftable.
3043 NonVirtualBaseAdjustment += ML.VFPtrOffset;
3044 if (ML.VBase)
3045 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
3046 }
3047
3048 if (VBTableIndex == 0 &&
3049 RD->getMSInheritanceModel() ==
3050 MSInheritanceModel::Virtual)
3051 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
3052
3053 // The rest of the fields are common with data member pointers.
3054 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
3055 NonVirtualBaseAdjustment, VBTableIndex);
3056}
3057
3058/// Member pointers are the same if they're either bitwise identical *or* both
3059/// null. Null-ness for function members is determined by the first field,
3060/// while for data member pointers we must compare all fields.
3061llvm::Value *
3062MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
3063 llvm::Value *L,
3064 llvm::Value *R,
3065 const MemberPointerType *MPT,
3066 bool Inequality) {
3067 CGBuilderTy &Builder = CGF.Builder;
3068
3069 // Handle != comparisons by switching the sense of all boolean operations.
3070 llvm::ICmpInst::Predicate Eq;
3071 llvm::Instruction::BinaryOps And, Or;
3072 if (Inequality) {
3073 Eq = llvm::ICmpInst::ICMP_NE;
3074 And = llvm::Instruction::Or;
3075 Or = llvm::Instruction::And;
3076 } else {
3077 Eq = llvm::ICmpInst::ICMP_EQ;
3078 And = llvm::Instruction::And;
3079 Or = llvm::Instruction::Or;
3080 }
3081
3082 // If this is a single field member pointer (single inheritance), this is a
3083 // single icmp.
3084 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3085 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3087 Inheritance))
3088 return Builder.CreateICmp(Eq, L, R);
3089
3090 // Compare the first field.
3091 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
3092 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
3093 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
3094
3095 // Compare everything other than the first field.
3096 llvm::Value *Res = nullptr;
3097 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
3098 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
3099 llvm::Value *LF = Builder.CreateExtractValue(L, I);
3100 llvm::Value *RF = Builder.CreateExtractValue(R, I);
3101 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
3102 if (Res)
3103 Res = Builder.CreateBinOp(And, Res, Cmp);
3104 else
3105 Res = Cmp;
3106 }
3107
3108 // Check if the first field is 0 if this is a function pointer.
3109 if (MPT->isMemberFunctionPointer()) {
3110 // (l1 == r1 && ...) || l0 == 0
3111 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
3112 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
3113 Res = Builder.CreateBinOp(Or, Res, IsZero);
3114 }
3115
3116 // Combine the comparison of the first field, which must always be true for
3117 // this comparison to succeeed.
3118 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
3119}
3120
3121llvm::Value *
3122MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
3123 llvm::Value *MemPtr,
3124 const MemberPointerType *MPT) {
3125 CGBuilderTy &Builder = CGF.Builder;
3126 llvm::SmallVector<llvm::Constant *, 4> fields;
3127 // We only need one field for member functions.
3128 if (MPT->isMemberFunctionPointer())
3129 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
3130 else
3131 GetNullMemberPointerFields(MPT, fields);
3132 assert(!fields.empty());
3133 llvm::Value *FirstField = MemPtr;
3134 if (MemPtr->getType()->isStructTy())
3135 FirstField = Builder.CreateExtractValue(MemPtr, 0);
3136 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
3137
3138 // For function member pointers, we only need to test the function pointer
3139 // field. The other fields if any can be garbage.
3140 if (MPT->isMemberFunctionPointer())
3141 return Res;
3142
3143 // Otherwise, emit a series of compares and combine the results.
3144 for (int I = 1, E = fields.size(); I < E; ++I) {
3145 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
3146 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
3147 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
3148 }
3149 return Res;
3150}
3151
3152bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
3153 llvm::Constant *Val) {
3154 // Function pointers are null if the pointer in the first field is null.
3155 if (MPT->isMemberFunctionPointer()) {
3156 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
3157 Val->getAggregateElement(0U) : Val;
3158 return FirstField->isNullValue();
3159 }
3160
3161 // If it's not a function pointer and it's zero initializable, we can easily
3162 // check zero.
3163 if (isZeroInitializable(MPT) && Val->isNullValue())
3164 return true;
3165
3166 // Otherwise, break down all the fields for comparison. Hopefully these
3167 // little Constants are reused, while a big null struct might not be.
3168 llvm::SmallVector<llvm::Constant *, 4> Fields;
3169 GetNullMemberPointerFields(MPT, Fields);
3170 if (Fields.size() == 1) {
3171 assert(Val->getType()->isIntegerTy());
3172 return Val == Fields[0];
3173 }
3174
3175 unsigned I, E;
3176 for (I = 0, E = Fields.size(); I != E; ++I) {
3177 if (Val->getAggregateElement(I) != Fields[I])
3178 break;
3179 }
3180 return I == E;
3181}
3182
3183llvm::Value *
3184MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
3185 Address This,
3186 llvm::Value *VBPtrOffset,
3187 llvm::Value *VBTableOffset,
3188 llvm::Value **VBPtrOut) {
3189 CGBuilderTy &Builder = CGF.Builder;
3190 // Load the vbtable pointer from the vbptr in the instance.
3191 llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
3192 CGM.Int8Ty, This.emitRawPointer(CGF), VBPtrOffset, "vbptr");
3193 if (VBPtrOut)
3194 *VBPtrOut = VBPtr;
3195
3196 CharUnits VBPtrAlign;
3197 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
3198 VBPtrAlign = This.getAlignment().alignmentAtOffset(
3199 CharUnits::fromQuantity(CI->getSExtValue()));
3200 } else {
3201 VBPtrAlign = CGF.getPointerAlign();
3202 }
3203
3204 llvm::Value *VBTable =
3205 Builder.CreateAlignedLoad(CGM.DefaultPtrTy, VBPtr, VBPtrAlign, "vbtable");
3206
3207 // Translate from byte offset to table index. It improves analyzability.
3208 llvm::Value *VBTableIndex = Builder.CreateAShr(
3209 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
3210 "vbtindex", /*isExact=*/true);
3211
3212 // Load an i32 offset from the vb-table.
3213 llvm::Value *VBaseOffs =
3214 Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
3215 return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
3216 CharUnits::fromQuantity(4), "vbase_offs");
3217}
3218
3219// Returns an adjusted base cast to i8*, since we do more address arithmetic on
3220// it.
3221llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3222 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3223 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3224 CGBuilderTy &Builder = CGF.Builder;
3225 Base = Base.withElementType(CGM.Int8Ty);
3226 llvm::BasicBlock *OriginalBB = nullptr;
3227 llvm::BasicBlock *SkipAdjustBB = nullptr;
3228 llvm::BasicBlock *VBaseAdjustBB = nullptr;
3229
3230 // In the unspecified inheritance model, there might not be a vbtable at all,
3231 // in which case we need to skip the virtual base lookup. If there is a
3232 // vbtable, the first entry is a no-op entry that gives back the original
3233 // base, so look for a virtual base adjustment offset of zero.
3234 if (VBPtrOffset) {
3235 OriginalBB = Builder.GetInsertBlock();
3236 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3237 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3238 llvm::Value *IsVirtual =
3239 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3240 "memptr.is_vbase");
3241 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3242 CGF.EmitBlock(VBaseAdjustBB);
3243 }
3244
3245 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3246 // know the vbptr offset.
3247 if (!VBPtrOffset) {
3248 CharUnits offs = CharUnits::Zero();
3249 if (!RD->hasDefinition()) {
3250 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3251 unsigned DiagID = Diags.getCustomDiagID(
3253 "member pointer representation requires a "
3254 "complete class type for %0 to perform this expression");
3255 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3256 } else if (RD->getNumVBases())
3257 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3258 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3259 }
3260 llvm::Value *VBPtr = nullptr;
3261 llvm::Value *VBaseOffs =
3262 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3263 llvm::Value *AdjustedBase =
3264 Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
3265
3266 // Merge control flow with the case where we didn't have to adjust.
3267 if (VBaseAdjustBB) {
3268 Builder.CreateBr(SkipAdjustBB);
3269 CGF.EmitBlock(SkipAdjustBB);
3270 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3271 Phi->addIncoming(Base.emitRawPointer(CGF), OriginalBB);
3272 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3273 return Phi;
3274 }
3275 return AdjustedBase;
3276}
3277
3278llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3279 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3280 const MemberPointerType *MPT, bool IsInBounds) {
3281 assert(MPT->isMemberDataPointer());
3282 CGBuilderTy &Builder = CGF.Builder;
3283 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3284 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3285
3286 // Extract the fields we need, regardless of model. We'll apply them if we
3287 // have them.
3288 llvm::Value *FieldOffset = MemPtr;
3289 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3290 llvm::Value *VBPtrOffset = nullptr;
3291 if (MemPtr->getType()->isStructTy()) {
3292 // We need to extract values.
3293 unsigned I = 0;
3294 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3295 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3296 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3298 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3299 }
3300
3301 llvm::Value *Addr;
3302 if (VirtualBaseAdjustmentOffset) {
3303 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3304 VBPtrOffset);
3305 } else {
3306 Addr = Base.emitRawPointer(CGF);
3307 }
3308
3309 // Apply the offset.
3310 return Builder.CreateGEP(CGF.Int8Ty, Addr, FieldOffset, "memptr.offset",
3311 IsInBounds ? llvm::GEPNoWrapFlags::inBounds()
3312 : llvm::GEPNoWrapFlags::none());
3313}
3314
3315llvm::Value *
3316MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3317 const CastExpr *E,
3318 llvm::Value *Src) {
3319 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3320 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3321 E->getCastKind() == CK_ReinterpretMemberPointer);
3322
3323 // Use constant emission if we can.
3324 if (isa<llvm::Constant>(Src))
3325 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3326
3327 // We may be adding or dropping fields from the member pointer, so we need
3328 // both types and the inheritance models of both records.
3329 const MemberPointerType *SrcTy =
3330 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3331 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3332 bool IsFunc = SrcTy->isMemberFunctionPointer();
3333
3334 // If the classes use the same null representation, reinterpret_cast is a nop.
3335 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3336 if (IsReinterpret && IsFunc)
3337 return Src;
3338
3339 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3340 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3341 if (IsReinterpret &&
3342 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3343 return Src;
3344
3345 CGBuilderTy &Builder = CGF.Builder;
3346
3347 // Branch past the conversion if Src is null.
3348 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3349 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3350
3351 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3352 // pointer value of the destination type.
3353 if (IsReinterpret) {
3354 // For reinterpret casts, sema ensures that src and dst are both functions
3355 // or data and have the same size, which means the LLVM types should match.
3356 assert(Src->getType() == DstNull->getType());
3357 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3358 }
3359
3360 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3361 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3362 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3363 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3364 CGF.EmitBlock(ConvertBB);
3365
3366 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3367 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3368 Builder);
3369
3370 Builder.CreateBr(ContinueBB);
3371
3372 // In the continuation, choose between DstNull and Dst.
3373 CGF.EmitBlock(ContinueBB);
3374 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3375 Phi->addIncoming(DstNull, OriginalBB);
3376 Phi->addIncoming(Dst, ConvertBB);
3377 return Phi;
3378}
3379
3380llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3381 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3383 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3384 CGBuilderTy &Builder) {
3385 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3386 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3387 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3388 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3389 bool IsFunc = SrcTy->isMemberFunctionPointer();
3390 bool IsConstant = isa<llvm::Constant>(Src);
3391
3392 // Decompose src.
3393 llvm::Value *FirstField = Src;
3394 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3395 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3396 llvm::Value *VBPtrOffset = getZeroInt();
3397 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3398 // We need to extract values.
3399 unsigned I = 0;
3400 FirstField = Builder.CreateExtractValue(Src, I++);
3401 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3402 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3403 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3404 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3405 if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3406 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3407 }
3408
3409 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3410 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3411 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3412
3413 // For data pointers, we adjust the field offset directly. For functions, we
3414 // have a separate field.
3415 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3416
3417 // The virtual inheritance model has a quirk: the virtual base table is always
3418 // referenced when dereferencing a member pointer even if the member pointer
3419 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3420 // to point backwards to the top of the MDC from the first VBase. Undo this
3421 // adjustment to normalize the member pointer.
3422 llvm::Value *SrcVBIndexEqZero =
3423 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3424 if (SrcInheritance == MSInheritanceModel::Virtual) {
3425 if (int64_t SrcOffsetToFirstVBase =
3426 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3427 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3428 SrcVBIndexEqZero,
3429 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3430 getZeroInt());
3431 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3432 }
3433 }
3434
3435 // A non-zero vbindex implies that we are dealing with a source member in a
3436 // floating virtual base in addition to some non-virtual offset. If the
3437 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3438 // fixed, base. The difference between these two cases is that the vbindex +
3439 // nvoffset *always* point to the member regardless of what context they are
3440 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3441 // base requires explicit nv adjustment.
3442 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3443 CGM.IntTy,
3444 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3445 .getQuantity());
3446
3447 llvm::Value *NVDisp;
3448 if (IsDerivedToBase)
3449 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3450 else
3451 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3452
3453 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3454
3455 // Update the vbindex to an appropriate value in the destination because
3456 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3457 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3458 if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3459 inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3460 if (llvm::GlobalVariable *VDispMap =
3461 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3462 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3463 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3464 if (IsConstant) {
3465 llvm::Constant *Mapping = VDispMap->getInitializer();
3466 VirtualBaseAdjustmentOffset =
3467 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3468 } else {
3469 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3470 VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
3471 CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
3472 VDispMap, Idxs),
3474 }
3475
3476 DstVBIndexEqZero =
3477 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3478 }
3479 }
3480
3481 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3482 // it to the offset of the vbptr.
3483 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3484 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::getSigned(
3485 CGM.IntTy,
3486 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3487 VBPtrOffset =
3488 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3489 }
3490
3491 // Likewise, apply a similar adjustment so that dereferencing the member
3492 // pointer correctly accounts for the distance between the start of the first
3493 // virtual base and the top of the MDC.
3494 if (DstInheritance == MSInheritanceModel::Virtual) {
3495 if (int64_t DstOffsetToFirstVBase =
3496 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3497 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3498 DstVBIndexEqZero,
3499 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3500 getZeroInt());
3501 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3502 }
3503 }
3504
3505 // Recompose dst from the null struct and the adjusted fields from src.
3506 llvm::Value *Dst;
3507 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3508 Dst = FirstField;
3509 } else {
3510 Dst = llvm::PoisonValue::get(ConvertMemberPointerType(DstTy));
3511 unsigned Idx = 0;
3512 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3513 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3514 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3515 if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3516 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3517 if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3518 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3519 }
3520 return Dst;
3521}
3522
3523llvm::Constant *
3524MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3525 llvm::Constant *Src) {
3526 const MemberPointerType *SrcTy =
3527 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3528 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3529
3530 CastKind CK = E->getCastKind();
3531
3532 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3533 E->path_end(), Src);
3534}
3535
3536llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3537 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3539 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3540 assert(CK == CK_DerivedToBaseMemberPointer ||
3541 CK == CK_BaseToDerivedMemberPointer ||
3542 CK == CK_ReinterpretMemberPointer);
3543 // If src is null, emit a new null for dst. We can't return src because dst
3544 // might have a new representation.
3545 if (MemberPointerConstantIsNull(SrcTy, Src))
3546 return EmitNullMemberPointer(DstTy);
3547
3548 // We don't need to do anything for reinterpret_casts of non-null member
3549 // pointers. We should only get here when the two type representations have
3550 // the same size.
3551 if (CK == CK_ReinterpretMemberPointer)
3552 return Src;
3553
3554 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3555 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3556 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3557
3558 return Dst;
3559}
3560
3561CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3562 CodeGenFunction &CGF, const Expr *E, Address This,
3563 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3564 const MemberPointerType *MPT) {
3565 assert(MPT->isMemberFunctionPointer());
3566 const FunctionProtoType *FPT =
3567 MPT->getPointeeType()->castAs<FunctionProtoType>();
3568 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3569 CGBuilderTy &Builder = CGF.Builder;
3570
3571 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3572
3573 // Extract the fields we need, regardless of model. We'll apply them if we
3574 // have them.
3575 llvm::Value *FunctionPointer = MemPtr;
3576 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3577 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3578 llvm::Value *VBPtrOffset = nullptr;
3579 if (MemPtr->getType()->isStructTy()) {
3580 // We need to extract values.
3581 unsigned I = 0;
3582 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3583 if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3584 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3585 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3586 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3588 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3589 }
3590
3591 if (VirtualBaseAdjustmentOffset) {
3592 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3593 VirtualBaseAdjustmentOffset, VBPtrOffset);
3594 } else {
3595 ThisPtrForCall = This.emitRawPointer(CGF);
3596 }
3597
3598 if (NonVirtualBaseAdjustment)
3599 ThisPtrForCall = Builder.CreateInBoundsGEP(CGF.Int8Ty, ThisPtrForCall,
3600 NonVirtualBaseAdjustment);
3601
3602 CGCallee Callee(FPT, FunctionPointer);
3603 return Callee;
3604}
3605
3607 return new MicrosoftCXXABI(CGM);
3608}
3609
3610// MS RTTI Overview:
3611// The run time type information emitted by cl.exe contains 5 distinct types of
3612// structures. Many of them reference each other.
3613//
3614// TypeInfo: Static classes that are returned by typeid.
3615//
3616// CompleteObjectLocator: Referenced by vftables. They contain information
3617// required for dynamic casting, including OffsetFromTop. They also contain
3618// a reference to the TypeInfo for the type and a reference to the
3619// CompleteHierarchyDescriptor for the type.
3620//
3621// ClassHierarchyDescriptor: Contains information about a class hierarchy.
3622// Used during dynamic_cast to walk a class hierarchy. References a base
3623// class array and the size of said array.
3624//
3625// BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3626// somewhat of a misnomer because the most derived class is also in the list
3627// as well as multiple copies of virtual bases (if they occur multiple times
3628// in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
3629// every path in the hierarchy, in pre-order depth first order. Note, we do
3630// not declare a specific llvm type for BaseClassArray, it's merely an array
3631// of BaseClassDescriptor pointers.
3632//
3633// BaseClassDescriptor: Contains information about a class in a class hierarchy.
3634// BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3635// BaseClassArray is. It contains information about a class within a
3636// hierarchy such as: is this base is ambiguous and what is its offset in the
3637// vbtable. The names of the BaseClassDescriptors have all of their fields
3638// mangled into them so they can be aggressively deduplicated by the linker.
3639
3640static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3641 StringRef MangledName("??_7type_info@@6B@");
3642 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3643 return VTable;
3644 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3645 /*isConstant=*/true,
3646 llvm::GlobalVariable::ExternalLinkage,
3647 /*Initializer=*/nullptr, MangledName);
3648}
3649
3650namespace {
3651
3652/// A Helper struct that stores information about a class in a class
3653/// hierarchy. The information stored in these structs struct is used during
3654/// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3655// During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3656// implicit depth first pre-order tree connectivity. getFirstChild and
3657// getNextSibling allow us to walk the tree efficiently.
3658struct MSRTTIClass {
3659 enum {
3660 IsPrivateOnPath = 1 | 8,
3661 IsAmbiguous = 2,
3662 IsPrivate = 4,
3663 IsVirtual = 16,
3664 HasHierarchyDescriptor = 64
3665 };
3666 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3667 uint32_t initialize(const MSRTTIClass *Parent,
3668 const CXXBaseSpecifier *Specifier);
3669
3670 MSRTTIClass *getFirstChild() { return this + 1; }
3671 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3672 return Child + 1 + Child->NumBases;
3673 }
3674
3675 const CXXRecordDecl *RD, *VirtualRoot;
3676 uint32_t Flags, NumBases, OffsetInVBase;
3677};
3678
3679/// Recursively initialize the base class array.
3680uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3681 const CXXBaseSpecifier *Specifier) {
3682 Flags = HasHierarchyDescriptor;
3683 if (!Parent) {
3684 VirtualRoot = nullptr;
3685 OffsetInVBase = 0;
3686 } else {
3687 if (Specifier->getAccessSpecifier() != AS_public)
3688 Flags |= IsPrivate | IsPrivateOnPath;
3689 if (Specifier->isVirtual()) {
3690 Flags |= IsVirtual;
3691 VirtualRoot = RD;
3692 OffsetInVBase = 0;
3693 } else {
3694 if (Parent->Flags & IsPrivateOnPath)
3695 Flags |= IsPrivateOnPath;
3696 VirtualRoot = Parent->VirtualRoot;
3697 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3698 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3699 }
3700 }
3701 NumBases = 0;
3702 MSRTTIClass *Child = getFirstChild();
3703 for (const CXXBaseSpecifier &Base : RD->bases()) {
3704 NumBases += Child->initialize(this, &Base) + 1;
3705 Child = getNextChild(Child);
3706 }
3707 return NumBases;
3708}
3709
3710static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3711 switch (Ty->getLinkage()) {
3712 case Linkage::Invalid:
3713 llvm_unreachable("Linkage hasn't been computed!");
3714
3715 case Linkage::None:
3716 case Linkage::Internal:
3717 case Linkage::UniqueExternal:
3718 return llvm::GlobalValue::InternalLinkage;
3719
3720 case Linkage::VisibleNone:
3721 case Linkage::Module:
3722 case Linkage::External:
3723 return llvm::GlobalValue::LinkOnceODRLinkage;
3724 }
3725 llvm_unreachable("Invalid linkage!");
3726}
3727
3728/// An ephemeral helper class for building MS RTTI types. It caches some
3729/// calls to the module and information about the most derived class in a
3730/// hierarchy.
3731struct MSRTTIBuilder {
3732 enum {
3733 HasBranchingHierarchy = 1,
3734 HasVirtualBranchingHierarchy = 2,
3735 HasAmbiguousBases = 4
3736 };
3737
3738 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3739 : CGM(ABI.CGM), Context(CGM.getContext()),
3740 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3741 Linkage(getLinkageForRTTI(CGM.getContext().getCanonicalTagType(RD))),
3742 ABI(ABI) {}
3743
3744 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3745 llvm::GlobalVariable *
3746 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3747 llvm::GlobalVariable *getClassHierarchyDescriptor();
3748 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3749
3750 CodeGenModule &CGM;
3751 ASTContext &Context;
3752 llvm::LLVMContext &VMContext;
3753 llvm::Module &Module;
3754 const CXXRecordDecl *RD;
3755 llvm::GlobalVariable::LinkageTypes Linkage;
3756 MicrosoftCXXABI &ABI;
3757};
3758
3759} // namespace
3760
3761/// Recursively serializes a class hierarchy in pre-order depth first
3762/// order.
3764 const CXXRecordDecl *RD) {
3765 Classes.push_back(MSRTTIClass(RD));
3766 for (const CXXBaseSpecifier &Base : RD->bases())
3767 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3768}
3769
3770/// Find ambiguity among base classes.
3771static void
3776 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3777 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3778 !VirtualBases.insert(Class->RD).second) {
3779 Class = MSRTTIClass::getNextChild(Class);
3780 continue;
3781 }
3782 if (!UniqueBases.insert(Class->RD).second)
3783 AmbiguousBases.insert(Class->RD);
3784 Class++;
3785 }
3786 if (AmbiguousBases.empty())
3787 return;
3788 for (MSRTTIClass &Class : Classes)
3789 if (AmbiguousBases.count(Class.RD))
3790 Class.Flags |= MSRTTIClass::IsAmbiguous;
3791}
3792
3793llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3794 SmallString<256> MangledName;
3795 {
3796 llvm::raw_svector_ostream Out(MangledName);
3797 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3798 }
3799
3800 // Check to see if we've already declared this ClassHierarchyDescriptor.
3801 if (auto CHD = Module.getNamedGlobal(MangledName))
3802 return CHD;
3803
3804 // Serialize the class hierarchy and initialize the CHD Fields.
3805 SmallVector<MSRTTIClass, 8> Classes;
3806 serializeClassHierarchy(Classes, RD);
3807 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3808 detectAmbiguousBases(Classes);
3809 int Flags = 0;
3810 for (const MSRTTIClass &Class : Classes) {
3811 if (Class.RD->getNumBases() > 1)
3812 Flags |= HasBranchingHierarchy;
3813 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3814 // believe the field isn't actually used.
3815 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3816 Flags |= HasAmbiguousBases;
3817 }
3818 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3819 Flags |= HasVirtualBranchingHierarchy;
3820 // These gep indices are used to get the address of the first element of the
3821 // base class array.
3822 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3823 llvm::ConstantInt::get(CGM.IntTy, 0)};
3824
3825 // Forward-declare the class hierarchy descriptor
3826 auto Type = ABI.getClassHierarchyDescriptorType();
3827 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3828 /*Initializer=*/nullptr,
3829 MangledName);
3830 if (CHD->isWeakForLinker())
3831 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3832
3833 auto *Bases = getBaseClassArray(Classes);
3834
3835 // Initialize the base class ClassHierarchyDescriptor.
3836 llvm::Constant *Fields[] = {
3837 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3838 llvm::ConstantInt::get(CGM.IntTy, Flags),
3839 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3840 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3841 Bases->getValueType(), Bases,
3842 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3843 };
3844 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3845 return CHD;
3846}
3847
3848llvm::GlobalVariable *
3849MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3850 SmallString<256> MangledName;
3851 {
3852 llvm::raw_svector_ostream Out(MangledName);
3853 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3854 }
3855
3856 // Forward-declare the base class array.
3857 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3858 // mode) bytes of padding. We provide a pointer sized amount of padding by
3859 // adding +1 to Classes.size(). The sections have pointer alignment and are
3860 // marked pick-any so it shouldn't matter.
3861 llvm::Type *PtrType = ABI.getImageRelativeType(CGM.DefaultPtrTy);
3862 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3863 auto *BCA =
3864 new llvm::GlobalVariable(Module, ArrType,
3865 /*isConstant=*/true, Linkage,
3866 /*Initializer=*/nullptr, MangledName);
3867 if (BCA->isWeakForLinker())
3868 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3869
3870 // Initialize the BaseClassArray.
3871 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3872 for (MSRTTIClass &Class : Classes)
3873 BaseClassArrayData.push_back(
3874 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3875 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3876 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3877 return BCA;
3878}
3879
3880llvm::GlobalVariable *
3881MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3882 // Compute the fields for the BaseClassDescriptor. They are computed up front
3883 // because they are mangled into the name of the object.
3884 uint32_t OffsetInVBTable = 0;
3885 int32_t VBPtrOffset = -1;
3886 if (Class.VirtualRoot) {
3887 auto &VTableContext = CGM.getMicrosoftVTableContext();
3888 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3889 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3890 }
3891
3892 SmallString<256> MangledName;
3893 {
3894 llvm::raw_svector_ostream Out(MangledName);
3895 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3896 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3897 Class.Flags, Out);
3898 }
3899
3900 // Check to see if we've already declared this object.
3901 if (auto BCD = Module.getNamedGlobal(MangledName))
3902 return BCD;
3903
3904 // Forward-declare the base class descriptor.
3905 auto Type = ABI.getBaseClassDescriptorType();
3906 auto BCD =
3907 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3908 /*Initializer=*/nullptr, MangledName);
3909 if (BCD->isWeakForLinker())
3910 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3911
3912 // Initialize the BaseClassDescriptor.
3913 llvm::Constant *Fields[] = {
3914 ABI.getImageRelativeConstant(
3915 ABI.getAddrOfRTTIDescriptor(Context.getCanonicalTagType(Class.RD))),
3916 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3917 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3918 llvm::ConstantInt::getSigned(CGM.IntTy, VBPtrOffset),
3919 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3920 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3921 ABI.getImageRelativeConstant(
3922 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3923 };
3924 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3925 return BCD;
3926}
3927
3928llvm::GlobalVariable *
3929MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3930 SmallString<256> MangledName;
3931 {
3932 llvm::raw_svector_ostream Out(MangledName);
3933 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3934 }
3935
3936 // Check to see if we've already computed this complete object locator.
3937 if (auto COL = Module.getNamedGlobal(MangledName))
3938 return COL;
3939
3940 // Compute the fields of the complete object locator.
3941 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3942 int VFPtrOffset = 0;
3943 // The offset includes the vtordisp if one exists.
3944 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3945 if (Context.getASTRecordLayout(RD)
3947 .find(VBase)
3948 ->second.hasVtorDisp())
3949 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3950
3951 // Forward-declare the complete object locator.
3952 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3953 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3954 /*Initializer=*/nullptr, MangledName);
3955
3956 // Initialize the CompleteObjectLocator.
3957 llvm::Constant *Fields[] = {
3958 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3959 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3960 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3961 ABI.getImageRelativeConstant(
3963 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3964 ABI.getImageRelativeConstant(COL),
3965 };
3966 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3967 if (!ABI.isImageRelative())
3968 FieldsRef = FieldsRef.drop_back();
3969 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3970 if (COL->isWeakForLinker())
3971 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3972 return COL;
3973}
3974
3976 bool &IsConst, bool &IsVolatile,
3977 bool &IsUnaligned) {
3978 T = Context.getExceptionObjectType(T);
3979
3980 // C++14 [except.handle]p3:
3981 // A handler is a match for an exception object of type E if [...]
3982 // - the handler is of type cv T or const T& where T is a pointer type and
3983 // E is a pointer type that can be converted to T by [...]
3984 // - a qualification conversion
3985 IsConst = false;
3986 IsVolatile = false;
3987 IsUnaligned = false;
3988 QualType PointeeType = T->getPointeeType();
3989 if (!PointeeType.isNull()) {
3990 IsConst = PointeeType.isConstQualified();
3991 IsVolatile = PointeeType.isVolatileQualified();
3992 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3993 }
3994
3995 // Member pointer types like "const int A::*" are represented by having RTTI
3996 // for "int A::*" and separately storing the const qualifier.
3997 if (const auto *MPTy = T->getAs<MemberPointerType>())
3998 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3999 MPTy->getQualifier(),
4000 MPTy->getMostRecentCXXRecordDecl());
4001
4002 // Pointer types like "const int * const *" are represented by having RTTI
4003 // for "const int **" and separately storing the const qualifier.
4004 if (T->isPointerType())
4005 T = Context.getPointerType(PointeeType.getUnqualifiedType());
4006
4007 return T;
4008}
4009
4010CatchTypeInfo
4011MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
4012 QualType CatchHandlerType) {
4013 // TypeDescriptors for exceptions never have qualified pointer types,
4014 // qualifiers are stored separately in order to support qualification
4015 // conversions.
4016 bool IsConst, IsVolatile, IsUnaligned;
4017 Type =
4018 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
4019
4020 bool IsReference = CatchHandlerType->isReferenceType();
4021
4022 uint32_t Flags = 0;
4023 if (IsConst)
4024 Flags |= 1;
4025 if (IsVolatile)
4026 Flags |= 2;
4027 if (IsUnaligned)
4028 Flags |= 4;
4029 if (IsReference)
4030 Flags |= 8;
4031
4032 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
4033 Flags};
4034}
4035
4036/// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
4037/// llvm::GlobalVariable * because different type descriptors have different
4038/// types, and need to be abstracted. They are abstracting by casting the
4039/// address to an Int8PtrTy.
4040llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
4041 SmallString<256> MangledName;
4042 {
4043 llvm::raw_svector_ostream Out(MangledName);
4044 getMangleContext().mangleCXXRTTI(Type, Out);
4045 }
4046
4047 // Check to see if we've already declared this TypeDescriptor.
4048 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4049 return GV;
4050
4051 // Note for the future: If we would ever like to do deferred emission of
4052 // RTTI, check if emitting vtables opportunistically need any adjustment.
4053
4054 // Compute the fields for the TypeDescriptor.
4055 SmallString<256> TypeInfoString;
4056 {
4057 llvm::raw_svector_ostream Out(TypeInfoString);
4058 getMangleContext().mangleCXXRTTIName(Type, Out);
4059 }
4060
4061 // Declare and initialize the TypeDescriptor.
4062 llvm::Constant *Fields[] = {
4063 getTypeInfoVTable(CGM), // VFPtr
4064 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
4065 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
4066 llvm::StructType *TypeDescriptorType =
4067 getTypeDescriptorType(TypeInfoString);
4068 auto *Var = new llvm::GlobalVariable(
4069 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
4070 getLinkageForRTTI(Type),
4071 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
4072 MangledName);
4073 if (Var->isWeakForLinker())
4074 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
4075 return Var;
4076}
4077
4078/// Gets or a creates a Microsoft CompleteObjectLocator.
4079llvm::GlobalVariable *
4080MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
4081 const VPtrInfo &Info) {
4082 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
4083}
4084
4085void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
4086 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
4087 // There are no constructor variants, always emit the complete destructor.
4088 llvm::Function *Fn =
4090 CGM.maybeSetTrivialComdat(*ctor, *Fn);
4091 return;
4092 }
4093
4094 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
4095
4096 // Emit the base destructor if the base and complete (vbase) destructors are
4097 // equivalent. This effectively implements -mconstructor-aliases as part of
4098 // the ABI.
4099 if (GD.getDtorType() == Dtor_Complete &&
4100 dtor->getParent()->getNumVBases() == 0)
4101 GD = GD.getWithDtorType(Dtor_Base);
4102
4103 // The base destructor is equivalent to the base destructor of its
4104 // base class if there is exactly one non-virtual base class with a
4105 // non-trivial destructor, there are no fields with a non-trivial
4106 // destructor, and the body of the destructor is trivial.
4107 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
4108 return;
4109
4110 if (GD.getDtorType() == Dtor_VectorDeleting &&
4111 !getContext().classNeedsVectorDeletingDestructor(dtor->getParent())) {
4112 // Create GlobalDecl object with the correct type for the scalar
4113 // deleting destructor.
4114 GlobalDecl ScalarDtorGD(dtor, Dtor_Deleting);
4115
4116 // Emit an alias from the vector deleting destructor to the scalar deleting
4117 // destructor.
4118 CGM.EmitDefinitionAsAlias(GD, ScalarDtorGD);
4119 return;
4120 }
4121
4122 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4123 if (Fn->isWeakForLinker())
4124 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
4125}
4126
4127llvm::Function *
4128MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
4129 CXXCtorType CT) {
4130 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
4131
4132 // Calculate the mangled name.
4133 SmallString<256> ThunkName;
4134 llvm::raw_svector_ostream Out(ThunkName);
4135 getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
4136
4137 // If the thunk has been generated previously, just return it.
4138 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
4139 return cast<llvm::Function>(GV);
4140
4141 // Create the llvm::Function.
4142 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
4143 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
4144 const CXXRecordDecl *RD = CD->getParent();
4145 CanQualType RecordTy = getContext().getCanonicalTagType(RD);
4146 llvm::Function *ThunkFn = llvm::Function::Create(
4147 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
4148 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
4150 if (ThunkFn->isWeakForLinker())
4151 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
4152 bool IsCopy = CT == Ctor_CopyingClosure;
4153
4154 // Start codegen.
4155 CodeGenFunction CGF(CGM);
4156 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
4157
4158 // Build FunctionArgs.
4159 FunctionArgList FunctionArgs;
4160
4161 // A constructor always starts with a 'this' pointer as its first argument.
4162 buildThisParam(CGF, FunctionArgs);
4163
4164 // Following the 'this' pointer is a reference to the source object that we
4165 // are copying from.
4166 ImplicitParamDecl SrcParam(
4167 getContext(), /*DC=*/nullptr, SourceLocation(),
4168 &getContext().Idents.get("src"),
4169 getContext().getLValueReferenceType(RecordTy,
4170 /*SpelledAsLValue=*/true),
4171 ImplicitParamKind::Other);
4172 if (IsCopy)
4173 FunctionArgs.push_back(&SrcParam);
4174
4175 // Constructors for classes which utilize virtual bases have an additional
4176 // parameter which indicates whether or not it is being delegated to by a more
4177 // derived constructor.
4178 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
4179 SourceLocation(),
4180 &getContext().Idents.get("is_most_derived"),
4181 getContext().IntTy, ImplicitParamKind::Other);
4182 // Only add the parameter to the list if the class has virtual bases.
4183 if (RD->getNumVBases() > 0)
4184 FunctionArgs.push_back(&IsMostDerived);
4185
4186 // Start defining the function.
4187 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4188 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
4189 FunctionArgs, CD->getLocation(), SourceLocation());
4190 // Create a scope with an artificial location for the body of this function.
4192 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
4193 llvm::Value *This = getThisValue(CGF);
4194
4195 llvm::Value *SrcVal =
4196 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
4197 : nullptr;
4198
4199 CallArgList Args;
4200
4201 // Push the this ptr.
4202 Args.add(RValue::get(This), CD->getThisType());
4203
4204 // Push the src ptr.
4205 if (SrcVal)
4206 Args.add(RValue::get(SrcVal), SrcParam.getType());
4207
4208 // Add the rest of the default arguments.
4209 SmallVector<const Stmt *, 4> ArgVec;
4210 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
4211 for (const ParmVarDecl *PD : params) {
4212 assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4213 ArgVec.push_back(PD->getDefaultArg());
4214 }
4215
4216 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4217
4218 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4219 CGF.EmitCallArgs(Args, FPT, llvm::ArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
4220
4221 // Insert any ABI-specific implicit constructor arguments.
4222 AddedStructorArgCounts ExtraArgs =
4223 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4224 /*ForVirtualBase=*/false,
4225 /*Delegating=*/false, Args);
4226 // Call the destructor with our arguments.
4227 llvm::Constant *CalleePtr =
4228 CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4229 CGCallee Callee =
4230 CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
4231 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4232 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4233 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4234
4235 Cleanups.ForceCleanup();
4236
4237 // Emit the ret instruction, remove any temporary instructions created for the
4238 // aid of CodeGen.
4239 CGF.FinishFunction(SourceLocation());
4240
4241 return ThunkFn;
4242}
4243
4244llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4245 uint32_t NVOffset,
4246 int32_t VBPtrOffset,
4247 uint32_t VBIndex) {
4248 assert(!T->isReferenceType());
4249
4250 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4251 const CXXConstructorDecl *CD =
4252 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
4254 if (CD)
4255 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4257
4258 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4259 SmallString<256> MangledName;
4260 {
4261 llvm::raw_svector_ostream Out(MangledName);
4262 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4263 VBPtrOffset, VBIndex, Out);
4264 }
4265 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4266 return getImageRelativeConstant(GV);
4267
4268 // The TypeDescriptor is used by the runtime to determine if a catch handler
4269 // is appropriate for the exception object.
4270 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4271
4272 // The runtime is responsible for calling the copy constructor if the
4273 // exception is caught by value.
4274 llvm::Constant *CopyCtor;
4275 if (CD) {
4276 if (CT == Ctor_CopyingClosure)
4277 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4278 else
4279 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4280 } else {
4281 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4282 }
4283 CopyCtor = getImageRelativeConstant(CopyCtor);
4284
4285 bool IsScalar = !RD;
4286 bool HasVirtualBases = false;
4287 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4288 QualType PointeeType = T;
4289 if (T->isPointerType())
4290 PointeeType = T->getPointeeType();
4291 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4292 HasVirtualBases = RD->getNumVBases() > 0;
4293 if (IdentifierInfo *II = RD->getIdentifier())
4294 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4295 }
4296
4297 // Encode the relevant CatchableType properties into the Flags bitfield.
4298 // FIXME: Figure out how bits 2 or 8 can get set.
4299 uint32_t Flags = 0;
4300 if (IsScalar)
4301 Flags |= 1;
4302 if (HasVirtualBases)
4303 Flags |= 4;
4304 if (IsStdBadAlloc)
4305 Flags |= 16;
4306
4307 llvm::Constant *Fields[] = {
4308 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4309 TD, // TypeDescriptor
4310 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4311 llvm::ConstantInt::getSigned(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4312 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4313 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4314 CopyCtor // CopyCtor
4315 };
4316 llvm::StructType *CTType = getCatchableTypeType();
4317 auto *GV = new llvm::GlobalVariable(
4318 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4319 llvm::ConstantStruct::get(CTType, Fields), MangledName);
4320 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4321 GV->setSection(".xdata");
4322 if (GV->isWeakForLinker())
4323 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4324 return getImageRelativeConstant(GV);
4325}
4326
4327llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4328 assert(!T->isReferenceType());
4329
4330 // See if we've already generated a CatchableTypeArray for this type before.
4331 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4332 if (CTA)
4333 return CTA;
4334
4335 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4336 // using a SmallSetVector. Duplicates may arise due to virtual bases
4337 // occurring more than once in the hierarchy.
4338 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4339
4340 // C++14 [except.handle]p3:
4341 // A handler is a match for an exception object of type E if [...]
4342 // - the handler is of type cv T or cv T& and T is an unambiguous public
4343 // base class of E, or
4344 // - the handler is of type cv T or const T& where T is a pointer type and
4345 // E is a pointer type that can be converted to T by [...]
4346 // - a standard pointer conversion (4.10) not involving conversions to
4347 // pointers to private or protected or ambiguous classes
4348 const CXXRecordDecl *MostDerivedClass = nullptr;
4349 bool IsPointer = T->isPointerType();
4350 if (IsPointer)
4351 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4352 else
4353 MostDerivedClass = T->getAsCXXRecordDecl();
4354
4355 // Collect all the unambiguous public bases of the MostDerivedClass.
4356 if (MostDerivedClass) {
4357 const ASTContext &Context = getContext();
4358 const ASTRecordLayout &MostDerivedLayout =
4359 Context.getASTRecordLayout(MostDerivedClass);
4360 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4361 SmallVector<MSRTTIClass, 8> Classes;
4362 serializeClassHierarchy(Classes, MostDerivedClass);
4363 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4364 detectAmbiguousBases(Classes);
4365 for (const MSRTTIClass &Class : Classes) {
4366 // Skip any ambiguous or private bases.
4367 if (Class.Flags &
4368 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4369 continue;
4370 // Write down how to convert from a derived pointer to a base pointer.
4371 uint32_t OffsetInVBTable = 0;
4372 int32_t VBPtrOffset = -1;
4373 if (Class.VirtualRoot) {
4374 OffsetInVBTable =
4375 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4376 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4377 }
4378
4379 // Turn our record back into a pointer if the exception object is a
4380 // pointer.
4381 CanQualType RTTITy = Context.getCanonicalTagType(Class.RD);
4382 if (IsPointer)
4383 RTTITy = Context.getPointerType(RTTITy);
4384 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4385 VBPtrOffset, OffsetInVBTable));
4386 }
4387 }
4388
4389 // C++14 [except.handle]p3:
4390 // A handler is a match for an exception object of type E if
4391 // - The handler is of type cv T or cv T& and E and T are the same type
4392 // (ignoring the top-level cv-qualifiers)
4393 CatchableTypes.insert(getCatchableType(T));
4394
4395 // C++14 [except.handle]p3:
4396 // A handler is a match for an exception object of type E if
4397 // - the handler is of type cv T or const T& where T is a pointer type and
4398 // E is a pointer type that can be converted to T by [...]
4399 // - a standard pointer conversion (4.10) not involving conversions to
4400 // pointers to private or protected or ambiguous classes
4401 //
4402 // C++14 [conv.ptr]p2:
4403 // A prvalue of type "pointer to cv T," where T is an object type, can be
4404 // converted to a prvalue of type "pointer to cv void".
4405 if (IsPointer && T->getPointeeType()->isObjectType())
4406 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4407
4408 // C++14 [except.handle]p3:
4409 // A handler is a match for an exception object of type E if [...]
4410 // - the handler is of type cv T or const T& where T is a pointer or
4411 // pointer to member type and E is std::nullptr_t.
4412 //
4413 // We cannot possibly list all possible pointer types here, making this
4414 // implementation incompatible with the standard. However, MSVC includes an
4415 // entry for pointer-to-void in this case. Let's do the same.
4416 if (T->isNullPtrType())
4417 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4418
4419 uint32_t NumEntries = CatchableTypes.size();
4420 llvm::Type *CTType = getImageRelativeType(CGM.DefaultPtrTy);
4421 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4422 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4423 llvm::Constant *Fields[] = {
4424 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4425 llvm::ConstantArray::get(
4426 AT, llvm::ArrayRef(CatchableTypes.begin(),
4427 CatchableTypes.end())) // CatchableTypes
4428 };
4429 SmallString<256> MangledName;
4430 {
4431 llvm::raw_svector_ostream Out(MangledName);
4432 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4433 }
4434 CTA = new llvm::GlobalVariable(
4435 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4436 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4437 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4438 CTA->setSection(".xdata");
4439 if (CTA->isWeakForLinker())
4440 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4441 return CTA;
4442}
4443
4444llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4445 bool IsConst, IsVolatile, IsUnaligned;
4446 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4447
4448 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4449 // the exception object may be caught as.
4450 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4451 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4452 // This is used as a component of the mangled name which means that we need to
4453 // know what it is in order to see if we have previously generated the
4454 // ThrowInfo.
4455 uint32_t NumEntries =
4456 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4457 ->getLimitedValue();
4458
4459 SmallString<256> MangledName;
4460 {
4461 llvm::raw_svector_ostream Out(MangledName);
4462 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4463 NumEntries, Out);
4464 }
4465
4466 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4467 // one before.
4468 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4469 return GV;
4470
4471 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4472 // be at least as CV qualified. Encode this requirement into the Flags
4473 // bitfield.
4474 uint32_t Flags = 0;
4475 if (IsConst)
4476 Flags |= 1;
4477 if (IsVolatile)
4478 Flags |= 2;
4479 if (IsUnaligned)
4480 Flags |= 4;
4481
4482 // The cleanup-function (a destructor) must be called when the exception
4483 // object's lifetime ends.
4484 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4485 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4486 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4487 if (!DtorD->isTrivial())
4488 CleanupFn = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
4489 // This is unused as far as we can tell, initialize it to null.
4490 llvm::Constant *ForwardCompat =
4491 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4492 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(CTA);
4493 llvm::StructType *TIType = getThrowInfoType();
4494 llvm::Constant *Fields[] = {
4495 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4496 getImageRelativeConstant(CleanupFn), // CleanupFn
4497 ForwardCompat, // ForwardCompat
4498 PointerToCatchableTypes // CatchableTypeArray
4499 };
4500 auto *GV = new llvm::GlobalVariable(
4501 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4502 llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
4503 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4504 GV->setSection(".xdata");
4505 if (GV->isWeakForLinker())
4506 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4507 return GV;
4508}
4509
4510void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4511 const Expr *SubExpr = E->getSubExpr();
4512 assert(SubExpr && "SubExpr cannot be null");
4513 QualType ThrowType = SubExpr->getType();
4514 // The exception object lives on the stack and it's address is passed to the
4515 // runtime function.
4516 Address AI = CGF.CreateMemTemp(ThrowType);
4517 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4518 /*IsInit=*/true);
4519
4520 // The so-called ThrowInfo is used to describe how the exception object may be
4521 // caught.
4522 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4523
4524 // Call into the runtime to throw the exception.
4525 llvm::Value *Args[] = {AI.emitRawPointer(CGF), TI};
4527}
4528
4529std::pair<llvm::Value *, const CXXRecordDecl *>
4530MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4531 const CXXRecordDecl *RD) {
4533 std::tie(This, std::ignore, RD) = performBaseAdjustment(CGF, This, T);
4534 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4535}
4536
4537bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
4538 const CXXRecordDecl *RD) const {
4539 // All aggregates are permitted to be HFA on non-ARM platforms, which mostly
4540 // affects vectorcall on x64/x86.
4541 if (!CGM.getTarget().getTriple().isAArch64())
4542 return true;
4543 // MSVC Windows on Arm64 has its own rules for determining if a type is HFA
4544 // that are inconsistent with the AAPCS64 ABI. The following are our best
4545 // determination of those rules so far, based on observation of MSVC's
4546 // behavior.
4547 if (RD->isEmpty())
4548 return false;
4549 if (RD->isPolymorphic())
4550 return false;
4552 return false;
4553 if (RD->hasNonTrivialDestructor())
4554 return false;
4556 return false;
4557 // These two are somewhat redundant given the caller
4558 // (ABIInfo::isHomogeneousAggregate) checks the bases and fields, but that
4559 // caller doesn't consider empty bases/fields to be non-homogenous, but it
4560 // looks like Microsoft's AArch64 ABI does care about these empty types &
4561 // anything containing/derived from one is non-homogeneous.
4562 // Instead we could add another CXXABI entry point to query this property and
4563 // have ABIInfo::isHomogeneousAggregate use that property.
4564 // I don't think any other of the features listed above could be true of a
4565 // base/field while not true of the outer struct. For example, if you have a
4566 // base/field that has an non-trivial copy assignment/dtor/default ctor, then
4567 // the outer struct's corresponding operation must be non-trivial.
4568 for (const CXXBaseSpecifier &B : RD->bases()) {
4569 if (const CXXRecordDecl *FRD = B.getType()->getAsCXXRecordDecl()) {
4570 if (!isPermittedToBeHomogeneousAggregate(FRD))
4571 return false;
4572 }
4573 }
4574 // empty fields seem to be caught by the ABIInfo::isHomogeneousAggregate
4575 // checking for padding - but maybe there are ways to end up with an empty
4576 // field without padding? Not that I know of, so don't check fields here &
4577 // rely on the padding check.
4578 return true;
4579}
#define V(N, I)
static Address emitDynamicCastToVoid(CIRGenFunction &cgf, mlir::Location loc, QualType srcRecordTy, Address src)
static mlir::Value emitExactDynamicCast(CIRGenItaniumCXXABI &abi, CIRGenFunction &cgf, mlir::Location loc, QualType srcRecordTy, QualType destRecordTy, cir::PointerType destCIRTy, bool isRefCast, Address src)
static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM)
static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard, llvm::BasicBlock *DynInitBB, llvm::BasicBlock *ContinueBB)
static llvm::GlobalVariable * getTypeInfoVTable(CodeGenModule &CGM)
static bool hasDefaultCXXMethodCC(ASTContext &Context, const CXXMethodDecl *MD)
static bool isTrivialForMSVC(const CXXRecordDecl *RD, QualType Ty, CodeGenModule &CGM)
static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM)
static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM)
static llvm::GlobalValue * getTlsGuardVar(CodeGenModule &CGM)
static QualType decomposeTypeForEH(ASTContext &Context, QualType T, bool &IsConst, bool &IsVolatile, bool &IsUnaligned)
static llvm::CallBase * emitRTtypeidCall(CodeGenFunction &CGF, llvm::Value *Argument)
static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM)
static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard, llvm::BasicBlock *ContinueBB)
static void detectAmbiguousBases(SmallVectorImpl< MSRTTIClass > &Classes)
Find ambiguity among base classes.
static void emitDynamicTlsInitialization(CodeGenFunction &CGF)
static void serializeClassHierarchy(SmallVectorImpl< MSRTTIClass > &Classes, const CXXRecordDecl *RD)
Recursively serializes a class hierarchy in pre-order depth first order.
static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM)
static bool isDeletingDtor(GlobalDecl GD)
static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD, llvm::FunctionCallee Dtor, llvm::Constant *Addr)
static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM)
static void mangleVFTableName(MicrosoftMangleContext &MangleContext, const CXXRecordDecl *RD, const VPtrInfo &VFPtr, SmallString< 256 > &Name)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
FormatToken * Next
The next token in the unwrapped line.
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1073
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1080
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
IdentifierTable & Idents
Definition ASTContext.h:790
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
CanQualType IntTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
llvm::DenseMap< const CXXRecordDecl *, VBaseInfo > VBaseOffsetsMapTy
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
const VBaseOffsetsMapTy & getVBaseOffsetsMap() const
bool hasExtendableVFPtr() const
hasVFPtr - Does this class have a virtual function table pointer that can be extended by a derived cl...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
VarDecl * getExceptionDecl() const
Definition StmtCXX.h:49
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:2999
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2665
bool isGlobalDelete() const
Definition ExprCXX.h:2651
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isVirtual() const
Definition DeclCXX.h:2184
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2809
bool isInstance() const
Definition DeclCXX.h:2156
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition DeclCXX.h:1334
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
bool hasPrivateFields() const
Definition DeclCXX.h:1191
base_class_range bases()
Definition DeclCXX.h:608
bool hasProtectedFields() const
Definition DeclCXX.h:1195
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1376
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_range vbases()
Definition DeclCXX.h:625
MSInheritanceModel getMSInheritanceModel() const
Returns the inheritance model used for this record.
bool nullFieldOffsetIsZero() const
In the Microsoft C++ ABI, use zero for the field offset of a null data member pointer if we can guara...
bool hasDefinition() const
Definition DeclCXX.h:561
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2121
bool hasNonTrivialDefaultConstructor() const
Determine whether this class has a non-trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1247
bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is virtually derived from the class Base.
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:925
bool hasSimpleCopyAssignment() const
true if we know for sure that this class has a single, accessible, unambiguous copy assignment operat...
Definition DeclCXX.h:737
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
const Expr * getSubExpr() const
Definition ExprCXX.h:1228
path_iterator path_begin()
Definition Expr.h:3680
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3677
Expr * getSubExpr()
Definition Expr.h:3660
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isNegative() const
isNegative - Test whether the quantity is less than zero.
Definition CharUnits.h:131
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
static ABIArgInfo getIndirect(CharUnits Alignment, unsigned AddrSpace, bool ByVal=true, bool Realign=false, llvm::Type *Padding=nullptr)
void setSRetAfterThis(bool AfterThis)
bool isHomogeneousAggregate(QualType Ty, const Type *&Base, uint64_t &Members) const
isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous aggregate.
Definition ABIInfo.cpp:61
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:140
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition CGBuilder.h:309
Address CreateConstInBoundsGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition CGBuilder.h:329
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:296
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:112
Address CreateConstByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Definition CGBuilder.h:319
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition CGBuilder.h:132
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition CGBuilder.h:350
Implements C++ ABI-specific code generation functions.
Definition CGCXXABI.h:43
RecordArgABI
Specify how one should pass an argument of a record type.
Definition CGCXXABI.h:150
MangleContext & getMangleContext()
Gets the mangle context.
Definition CGCXXABI.h:113
static CGCallee forVirtual(const CallExpr *CE, GlobalDecl MD, Address Addr, llvm::FunctionType *FTy)
Definition CGCall.h:147
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:137
CanQualType getReturnType() const
unsigned getEffectiveCallingConvention() const
getEffectiveCallingConvention - Return the actual calling convention to use, which may depend on the ...
void add(RValue rvalue, QualType type)
Definition CGCall.h:302
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
Definition CGClass.cpp:2856
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
Definition CGExpr.cpp:3154
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
llvm::Constant * createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, llvm::Constant *Addr)
Create a stub function, suitable for being passed to atexit, which passes the given address to the gi...
void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, llvm::FunctionCallee Callee)
Emit a musttail call for a thunk with a potentially adjusted this pointer.
void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args)
Emits a call or invoke to the given noreturn runtime function.
Definition CGCall.cpp:5065
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition CGCall.cpp:5092
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn, llvm::Constant *addr)
Call atexit() with a function that passes the given argument to the given function.
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
EmitAutoVarAlloca - Emit the alloca and debug information for a local variable.
Definition CGDecl.cpp:1482
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
Definition CGClass.cpp:2681
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV, bool PerformInit)
EmitCXXGlobalVarDeclInit - Create the initializer for a C++ variable with global storage.
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, llvm::BasicBlock *InitBlock, llvm::BasicBlock *NoInitBlock, GuardKind Kind, const VarDecl *D)
Emit a branch to select whether or not to perform guarded initialization.
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5248
void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, llvm::Value *VTable, SourceLocation Loc)
If whole-program virtual table optimization is enabled, emit an assumption that VTable is a member of...
Definition CGClass.cpp:2929
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void EmitAutoVarCleanups(const AutoVarEmission &emission)
Definition CGDecl.cpp:2202
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition CGExpr.cpp:295
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, QualType DeleteTy, llvm::Value *NumElements=nullptr, CharUnits CookieSize=CharUnits())
CodeGenTypes & getTypes() const
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:188
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
Definition CGCall.cpp:4688
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
llvm::Value * EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, llvm::Type *VTableTy, uint64_t VTableByteOffset)
Emit a type checked load from the given vtable.
Definition CGClass.cpp:3117
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::Instruction * CurrentFuncletPad
bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD)
Returns whether we should perform a type checked load when loading a virtual function for virtual cal...
Definition CGClass.cpp:3099
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:656
This class organizes the cross-function state that is used while generating LLVM code.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object)
Add a destructor and object to add to the C++ global destructor function.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::GlobalObject::VCallVisibility GetVCallVisibilityLevel(const CXXRecordDecl *RD, llvm::DenseSet< const CXXRecordDecl * > &Visited)
Returns the vcall visibility of the given type.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
CodeGenVTables & getVTables()
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
DiagnosticsEngine & getDiags() const
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D)
Try to emit a base destructor as an alias to its primary base-class destructor.
Definition CGCXX.cpp:32
const llvm::DataLayout & getDataLayout() const
CharUnits computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start, CastExpr::path_const_iterator End)
Definition CGClass.cpp:168
CharUnits getVBaseAlignment(CharUnits DerivedAlign, const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the assumed alignment of a virtual base of a class.
Definition CGClass.cpp:76
void EmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target)
Emit a definition as a global alias for another definition, unconditionally.
Definition CGCXX.cpp:203
llvm::Function * codegenCXXStructor(GlobalDecl GD)
Definition CGCXX.cpp:238
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ASTContext & getContext() const
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
MicrosoftVTableContext & getMicrosoftVTableContext()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void addDeferredVTable(const CXXRecordDecl *RD)
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Function * CreateGlobalInitOrCleanUpFunction(llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI, SourceLocation Loc=SourceLocation(), bool TLS=false, llvm::GlobalVariable::LinkageTypes Linkage=llvm::GlobalVariable::InternalLinkage)
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
Definition CGCall.cpp:374
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1702
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i....
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD)
Arrange a thunk that takes 'this' as the first parameter followed by varargs.
Definition CGCall.cpp:627
const CGFunctionInfo & arrangeCXXConstructorCall(const CallArgList &Args, const CXXConstructorDecl *D, CXXCtorType CtorKind, unsigned ExtraPrefixArgs, unsigned ExtraSuffixArgs, bool PassProtoArgs=true)
Arrange a call to a C++ method, passing the given arguments.
Definition CGCall.cpp:485
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
Definition CGCall.cpp:402
const CGFunctionInfo & arrangeMSCtorClosure(const CXXConstructorDecl *CD, CXXCtorType CT)
Definition CGCall.cpp:636
const CGFunctionInfo & arrangeNullaryFunction()
A nullary function is a freestanding function of type 'void ()'.
Definition CGCall.cpp:788
void createVTableInitializer(ConstantStructBuilder &builder, const VTableLayout &layout, llvm::Constant *rtti, bool vtableHasLocalLinkage)
Add vtable components for the given vtable layout to the given global initializer.
A specialization of Address that requires the address to be an LLVM Constant.
Definition Address.h:296
static RValue get(llvm::Value *V)
Definition CGValue.h:99
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:905
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
QualType getType() const
Definition Expr.h:144
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3822
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3242
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
GlobalDecl getWithCtorType(CXXCtorType Type)
Definition GlobalDecl.h:178
GlobalDecl getWithDtorType(CXXDtorType Type)
Definition GlobalDecl.h:185
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5536
bool isExplicitDefaultVisibilityExportMapping() const
bool isAllDefaultVisibilityExportMapping() const
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5449
QualType getPointeeType() const
Definition TypeBase.h:3672
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3676
bool isMemberDataPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3682
unsigned getVBTableIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the index of VBase in the vbtable of Derived.
MethodVFTableLocation getMethodVFTableLocation(GlobalDecl GD)
const VPtrInfoVector & getVFPtrOffsets(const CXXRecordDecl *RD)
const VTableLayout & getVFTableLayout(const CXXRecordDecl *RD, CharUnits VFPtrOffset)
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
bool isExternallyVisible() const
Definition Decl.h:433
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8377
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8333
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8387
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8366
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool hasUnaligned() const
Definition TypeBase.h:511
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition Decl.h:4458
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool emitVectorDeletingDtors(const LangOptions &) const
Controls whether to emit MSVC vector deleting destructors.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:489
virtual bool callGlobalDeleteInDeletingDtor(const LangOptions &) const
Controls whether global operator delete is called by the deleting destructor or at the point where de...
The base class of the type hierarchy.
Definition TypeBase.h:1833
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isPointerType() const
Definition TypeBase.h:8530
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9179
bool isReferenceType() const
Definition TypeBase.h:8554
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:4891
bool isNullPtrType() const
Definition TypeBase.h:8929
ArrayRef< VTableComponent > vtable_components() const
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
TLSKind getTLSKind() const
Definition Decl.cpp:2175
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2843
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
llvm::Value * getCXXDestructorImplicitParam(CodeGenModule &CGM, llvm::BasicBlock *InsertBlock, llvm::BasicBlock::iterator InsertPoint, const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating)
CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI)
bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info)
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
CGCXXABI * CreateMicrosoftCXXABI(CodeGenModule &CGM)
Creates a Microsoft-family ABI.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
constexpr Variable var(Literal L)
Returns the variable of L.
Definition CNFFormula.h:64
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2802
bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:224
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
Definition ABI.h:24
@ Ctor_Base
Base object ctor.
Definition ABI.h:26
@ Ctor_DefaultClosure
Default closure variant of a ctor.
Definition ABI.h:29
@ Ctor_CopyingClosure
Copying closure variant of a ctor.
Definition ABI.h:28
@ Ctor_Complete
Complete object ctor.
Definition ABI.h:25
bool isa(CodeGen::Address addr)
Definition Address.h:330
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_Internal
Definition Linkage.h:73
void initialize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
bool inheritanceModelHasNVOffsetField(bool IsMemberFunction, MSInheritanceModel Inheritance)
@ AS_public
Definition Specifiers.h:124
bool inheritanceModelHasOnlyOneField(bool IsMemberFunction, MSInheritanceModel Inheritance)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool inheritanceModelHasVBPtrOffsetField(MSInheritanceModel Inheritance)
bool inheritanceModelHasVBTableOffsetField(MSInheritanceModel Inheritance)
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
SmallVector< std::unique_ptr< VPtrInfo >, 2 > VPtrInfoVector
CXXDtorType
C++ destructor types.
Definition ABI.h:34
@ Dtor_VectorDeleting
Vector deleting dtor.
Definition ABI.h:40
@ Dtor_Comdat
The COMDAT used for dtors.
Definition ABI.h:38
@ Dtor_Unified
GCC-style unified dtor.
Definition ABI.h:39
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
@ Dtor_Deleting
Deleting dtor.
Definition ABI.h:35
@ Type
The name was classified as a type.
Definition Sema.h:563
CastKind
CastKind - The kind of operation required for a conversion.
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:410
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
@ Implicit
An implicit conversion.
Definition Sema.h:439
unsigned long uint64_t
long int64_t
unsigned int uint32_t
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
const CXXRecordDecl * VBase
If nonnull, holds the last vbase which contains the vfptr that the method definition is adjusted to.
CharUnits VFPtrOffset
This is the offset of the vfptr from the start of the last vbase, or the complete type if there are n...
uint64_t Index
Method's index in the vftable.
bool isEmpty() const
Definition Thunk.h:70
union clang::ReturnAdjustment::VirtualAdjustment Virtual
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition Thunk.h:30
union clang::ThisAdjustment::VirtualAdjustment Virtual
bool isEmpty() const
Definition Thunk.h:137
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition Thunk.h:95
ThisAdjustment This
The this pointer adjustment.
Definition Thunk.h:159
bool isAlignRequired()
Definition ASTContext.h:199
Holds information about the inheritance path to a virtual base or function table pointer.
CharUnits NonVirtualOffset
IntroducingObject is at this offset from its containing complete object or virtual base.
CharUnits FullOffsetInMDC
Static offset from the top of the most derived class to this vfptr, including any virtual base offset...
const CXXRecordDecl * getVBaseWithVPtr() const
The vptr is stored inside the non-virtual component of this virtual base.
const CXXRecordDecl * IntroducingObject
This is the class that introduced the vptr by declaring new virtual methods or virtual bases.
BasePath MangledPath
The bases from the inheritance path that got used to mangle the vbtable name.
BasePath PathToIntroducingObject
This holds the base classes path from the complete type to the first base with the given vfptr offset...
const CXXRecordDecl * ObjectWithVPtr
This is the most derived class that has this vptr at offset zero.
uint32_t VBPtrOffset
The offset (in bytes) of the vbptr, relative to the beginning of the derived class.
Definition Thunk.h:46
struct clang::ReturnAdjustment::VirtualAdjustment::@167242364125115315334113104006210160165266060257 Microsoft
uint32_t VBIndex
Index of the virtual base in the vbtable.
Definition Thunk.h:49
int32_t VtordispOffset
The offset of the vtordisp (in bytes), relative to the ECX.
Definition Thunk.h:109
struct clang::ThisAdjustment::VirtualAdjustment::@312251255113040203233347230177110330127151157305 Microsoft
int32_t VBOffsetOffset
The offset (in bytes) of the vbase offset in the vbtable.
Definition Thunk.h:116
int32_t VBPtrOffset
The offset of the vbptr of the derived class (in bytes), relative to the ECX after vtordisp adjustmen...
Definition Thunk.h:113