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