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