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