clang  16.0.0git
MicrosoftCXXABI.cpp
Go to the documentation of this file.
1 //===------- MicrosoftCXXABI.cpp - AST support for the Microsoft C++ ABI --===//
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++ AST support targeting the Microsoft Visual C++
10 // ABI.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CXXABI.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/Mangle.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/TargetInfo.h"
24 
25 using namespace clang;
26 
27 namespace {
28 
29 /// Numbers things which need to correspond across multiple TUs.
30 /// Typically these are things like static locals, lambdas, or blocks.
31 class MicrosoftNumberingContext : public MangleNumberingContext {
32  llvm::DenseMap<const Type *, unsigned> ManglingNumbers;
33  unsigned LambdaManglingNumber;
34  unsigned StaticLocalNumber;
35  unsigned StaticThreadlocalNumber;
36 
37 public:
38  MicrosoftNumberingContext()
39  : LambdaManglingNumber(0), StaticLocalNumber(0),
40  StaticThreadlocalNumber(0) {}
41 
42  unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
43  return ++LambdaManglingNumber;
44  }
45 
46  unsigned getManglingNumber(const BlockDecl *BD) override {
47  const Type *Ty = nullptr;
48  return ++ManglingNumbers[Ty];
49  }
50 
51  unsigned getStaticLocalNumber(const VarDecl *VD) override {
52  if (VD->getTLSKind())
53  return ++StaticThreadlocalNumber;
54  return ++StaticLocalNumber;
55  }
56 
57  unsigned getManglingNumber(const VarDecl *VD,
58  unsigned MSLocalManglingNumber) override {
59  return MSLocalManglingNumber;
60  }
61 
62  unsigned getManglingNumber(const TagDecl *TD,
63  unsigned MSLocalManglingNumber) override {
64  return MSLocalManglingNumber;
65  }
66 };
67 
68 class MSHIPNumberingContext : public MicrosoftNumberingContext {
69  std::unique_ptr<MangleNumberingContext> DeviceCtx;
70 
71 public:
72  using MicrosoftNumberingContext::getManglingNumber;
73  MSHIPNumberingContext(MangleContext *DeviceMangler) {
74  DeviceCtx = createItaniumNumberingContext(DeviceMangler);
75  }
76 
77  unsigned getDeviceManglingNumber(const CXXMethodDecl *CallOperator) override {
78  return DeviceCtx->getManglingNumber(CallOperator);
79  }
80 
81  unsigned getManglingNumber(const TagDecl *TD,
82  unsigned MSLocalManglingNumber) override {
83  unsigned DeviceN = DeviceCtx->getManglingNumber(TD, MSLocalManglingNumber);
84  unsigned HostN =
85  MicrosoftNumberingContext::getManglingNumber(TD, MSLocalManglingNumber);
86  if (DeviceN > 0xFFFF || HostN > 0xFFFF) {
88  unsigned DiagID = Diags.getCustomDiagID(
89  DiagnosticsEngine::Error, "Mangling number exceeds limit (65535)");
90  Diags.Report(TD->getLocation(), DiagID);
91  }
92  return (DeviceN << 16) | HostN;
93  }
94 };
95 
96 class MSSYCLNumberingContext : public MicrosoftNumberingContext {
97  std::unique_ptr<MangleNumberingContext> DeviceCtx;
98 
99 public:
100  MSSYCLNumberingContext(MangleContext *DeviceMangler) {
101  DeviceCtx = createItaniumNumberingContext(DeviceMangler);
102  }
103 
104  unsigned getDeviceManglingNumber(const CXXMethodDecl *CallOperator) override {
105  return DeviceCtx->getManglingNumber(CallOperator);
106  }
107 };
108 
109 class MicrosoftCXXABI : public CXXABI {
110  ASTContext &Context;
111  llvm::SmallDenseMap<CXXRecordDecl *, CXXConstructorDecl *> RecordToCopyCtor;
112 
113  llvm::SmallDenseMap<TagDecl *, DeclaratorDecl *>
114  UnnamedTagDeclToDeclaratorDecl;
115  llvm::SmallDenseMap<TagDecl *, TypedefNameDecl *>
116  UnnamedTagDeclToTypedefNameDecl;
117 
118  // MangleContext for device numbering context, which is based on Itanium C++
119  // ABI.
120  std::unique_ptr<MangleContext> DeviceMangler;
121 
122 public:
123  MicrosoftCXXABI(ASTContext &Ctx) : Context(Ctx) {
124  if (Context.getLangOpts().CUDA && Context.getAuxTargetInfo()) {
125  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
126  Context.getAuxTargetInfo()->getCXXABI().isItaniumFamily() &&
127  "Unexpected combination of C++ ABIs.");
128  DeviceMangler.reset(
129  Context.createMangleContext(Context.getAuxTargetInfo()));
130  }
131  else if (Context.getLangOpts().isSYCL()) {
132  DeviceMangler.reset(
133  ItaniumMangleContext::create(Context, Context.getDiagnostics()));
134  }
135  }
136 
137  MemberPointerInfo
138  getMemberPointerInfo(const MemberPointerType *MPT) const override;
139 
140  CallingConv getDefaultMethodCallConv(bool isVariadic) const override {
141  if (!isVariadic &&
142  Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
143  return CC_X86ThisCall;
144  return Context.getTargetInfo().getDefaultCallingConv();
145  }
146 
147  bool isNearlyEmpty(const CXXRecordDecl *RD) const override {
148  llvm_unreachable("unapplicable to the MS ABI");
149  }
150 
151  const CXXConstructorDecl *
152  getCopyConstructorForExceptionObject(CXXRecordDecl *RD) override {
153  return RecordToCopyCtor[RD];
154  }
155 
156  void
157  addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
158  CXXConstructorDecl *CD) override {
159  assert(CD != nullptr);
160  assert(RecordToCopyCtor[RD] == nullptr || RecordToCopyCtor[RD] == CD);
161  RecordToCopyCtor[RD] = CD;
162  }
163 
164  void addTypedefNameForUnnamedTagDecl(TagDecl *TD,
165  TypedefNameDecl *DD) override {
166  TD = TD->getCanonicalDecl();
167  DD = DD->getCanonicalDecl();
168  TypedefNameDecl *&I = UnnamedTagDeclToTypedefNameDecl[TD];
169  if (!I)
170  I = DD;
171  }
172 
173  TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD) override {
174  return UnnamedTagDeclToTypedefNameDecl.lookup(
175  const_cast<TagDecl *>(TD->getCanonicalDecl()));
176  }
177 
178  void addDeclaratorForUnnamedTagDecl(TagDecl *TD,
179  DeclaratorDecl *DD) override {
180  TD = TD->getCanonicalDecl();
181  DD = cast<DeclaratorDecl>(DD->getCanonicalDecl());
182  DeclaratorDecl *&I = UnnamedTagDeclToDeclaratorDecl[TD];
183  if (!I)
184  I = DD;
185  }
186 
187  DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD) override {
188  return UnnamedTagDeclToDeclaratorDecl.lookup(
189  const_cast<TagDecl *>(TD->getCanonicalDecl()));
190  }
191 
192  std::unique_ptr<MangleNumberingContext>
193  createMangleNumberingContext() const override {
194  if (Context.getLangOpts().CUDA && Context.getAuxTargetInfo()) {
195  assert(DeviceMangler && "Missing device mangler");
196  return std::make_unique<MSHIPNumberingContext>(DeviceMangler.get());
197  } else if (Context.getLangOpts().isSYCL()) {
198  assert(DeviceMangler && "Missing device mangler");
199  return std::make_unique<MSSYCLNumberingContext>(DeviceMangler.get());
200  }
201 
202  return std::make_unique<MicrosoftNumberingContext>();
203  }
204 };
205 }
206 
207 // getNumBases() seems to only give us the number of direct bases, and not the
208 // total. This function tells us if we inherit from anybody that uses MI, or if
209 // we have a non-primary base class, which uses the multiple inheritance model.
211  while (RD->getNumBases() > 0) {
212  if (RD->getNumBases() > 1)
213  return true;
214  assert(RD->getNumBases() == 1);
215  const CXXRecordDecl *Base =
217  if (RD->isPolymorphic() && !Base->isPolymorphic())
218  return true;
219  RD = Base;
220  }
221  return false;
222 }
223 
227  if (getNumVBases() > 0)
232 }
233 
235  MSInheritanceAttr *IA = getAttr<MSInheritanceAttr>();
236  assert(IA && "Expected MSInheritanceAttr on the CXXRecordDecl!");
237  return IA->getInheritanceModel();
238 }
239 
241  return !inheritanceModelHasOnlyOneField(/*IsMemberFunction=*/false,
243  (hasDefinition() && isPolymorphic());
244 }
245 
247  if (MSVtorDispAttr *VDA = getAttr<MSVtorDispAttr>())
248  return VDA->getVtorDispMode();
249  return getASTContext().getLangOpts().getVtorDispMode();
250 }
251 
252 // Returns the number of pointer and integer slots used to represent a member
253 // pointer in the MS C++ ABI.
254 //
255 // Member function pointers have the following general form; however, fields
256 // are dropped as permitted (under the MSVC interpretation) by the inheritance
257 // model of the actual class.
258 //
259 // struct {
260 // // A pointer to the member function to call. If the member function is
261 // // virtual, this will be a thunk that forwards to the appropriate vftable
262 // // slot.
263 // void *FunctionPointerOrVirtualThunk;
264 //
265 // // An offset to add to the address of the vbtable pointer after
266 // // (possibly) selecting the virtual base but before resolving and calling
267 // // the function.
268 // // Only needed if the class has any virtual bases or bases at a non-zero
269 // // offset.
270 // int NonVirtualBaseAdjustment;
271 //
272 // // The offset of the vb-table pointer within the object. Only needed for
273 // // incomplete types.
274 // int VBPtrOffset;
275 //
276 // // An offset within the vb-table that selects the virtual base containing
277 // // the member. Loading from this offset produces a new offset that is
278 // // added to the address of the vb-table pointer to produce the base.
279 // int VirtualBaseAdjustmentOffset;
280 // };
281 static std::pair<unsigned, unsigned>
283  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
284  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
285  unsigned Ptrs = 0;
286  unsigned Ints = 0;
287  if (MPT->isMemberFunctionPointer())
288  Ptrs = 1;
289  else
290  Ints = 1;
292  Inheritance))
293  Ints++;
294  if (inheritanceModelHasVBPtrOffsetField(Inheritance))
295  Ints++;
296  if (inheritanceModelHasVBTableOffsetField(Inheritance))
297  Ints++;
298  return std::make_pair(Ptrs, Ints);
299 }
300 
301 CXXABI::MemberPointerInfo MicrosoftCXXABI::getMemberPointerInfo(
302  const MemberPointerType *MPT) const {
303  // The nominal struct is laid out with pointers followed by ints and aligned
304  // to a pointer width if any are present and an int width otherwise.
305  const TargetInfo &Target = Context.getTargetInfo();
306  unsigned PtrSize = Target.getPointerWidth(0);
307  unsigned IntSize = Target.getIntWidth();
308 
309  unsigned Ptrs, Ints;
310  std::tie(Ptrs, Ints) = getMSMemberPointerSlots(MPT);
311  MemberPointerInfo MPI;
312  MPI.HasPadding = false;
313  MPI.Width = Ptrs * PtrSize + Ints * IntSize;
314 
315  // When MSVC does x86_32 record layout, it aligns aggregate member pointers to
316  // 8 bytes. However, __alignof usually returns 4 for data memptrs and 8 for
317  // function memptrs.
318  if (Ptrs + Ints > 1 && Target.getTriple().isArch32Bit())
319  MPI.Align = 64;
320  else if (Ptrs)
321  MPI.Align = Target.getPointerAlign(0);
322  else
323  MPI.Align = Target.getIntAlign();
324 
325  if (Target.getTriple().isArch64Bit()) {
326  MPI.Width = llvm::alignTo(MPI.Width, MPI.Align);
327  MPI.HasPadding = MPI.Width != (Ptrs * PtrSize + Ints * IntSize);
328  }
329  return MPI;
330 }
331 
333  return new MicrosoftCXXABI(Ctx);
334 }
clang::Decl::getASTContext
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:428
clang::CXXConstructorDecl
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2436
clang::CXXBaseSpecifier::getType
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:245
clang::VarDecl::getTLSKind
TLSKind getTLSKind() const
Definition: Decl.cpp:2093
clang::CXXABI::MemberPointerInfo
Definition: CXXABI.h:33
clang::MSInheritanceModel::Multiple
@ Multiple
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:138
TargetInfo.h
clang::MultiVersionKind::Target
@ Target
CXXInheritance.h
Attr.h
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1268
clang::TargetCXXABI::isItaniumFamily
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:124
clang::TargetInfo
Exposes information about the current target.
Definition: TargetInfo.h:205
DeclCXX.h
clang::TagDecl::getCanonicalDecl
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4413
clang::ASTContext::getAuxTargetInfo
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:774
clang::ASTContext::createMangleContext
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
Definition: ASTContext.cpp:11886
clang::MemberPointerType::isMemberFunctionPointer
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition: Type.h:2980
clang::CC_X86ThisCall
@ CC_X86ThisCall
Definition: Specifiers.h:270
clang::MSVtorDispMode
MSVtorDispMode
In the Microsoft ABI, this controls the placement of virtual displacement members used to implement v...
Definition: LangOptions.h:54
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1565
clang::MSInheritanceModel::Unspecified
@ Unspecified
clang::TargetInfo::getDefaultCallingConv
virtual CallingConv getDefaultCallingConv() const
Gets the default calling convention for the given target and declaration context.
Definition: TargetInfo.h:1534
clang::MangleContext
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:44
clang::BlockDecl
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4283
clang::CXXRecordDecl::isParsingBaseSpecifiers
bool isParsingBaseSpecifiers() const
Definition: DeclCXX.h:581
clang::inheritanceModelHasVBTableOffsetField
bool inheritanceModelHasVBTableOffsetField(MSInheritanceModel Inheritance)
Definition: CXXInheritance.h:377
clang::CXXRecordDecl::getMSVtorDispMode
MSVtorDispMode getMSVtorDispMode() const
Controls when vtordisps will be emitted if this record is used as a virtual base.
Definition: MicrosoftCXXABI.cpp:246
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:209
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:200
clang::CXXRecordDecl::getNumBases
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:591
clang::TypedefNameDecl::getCanonicalDecl
TypedefNameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this typedef-name.
Definition: Decl.h:3347
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:943
clang::MSInheritanceModel::Single
@ Single
Type.h
ASTContext.h
clang::CallingConv
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:266
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:906
clang::TagDecl
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3423
clang::CXXABI
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
clang::Type::getAsCXXRecordDecl
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1760
Base
clang::CreateMicrosoftCXXABI
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
Definition: MicrosoftCXXABI.cpp:332
clang::CXXRecordDecl::getMSInheritanceModel
MSInheritanceModel getMSInheritanceModel() const
Returns the inheritance model used for this record.
Definition: MicrosoftCXXABI.cpp:234
CXXABI.h
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1195
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
clang::inheritanceModelHasNVOffsetField
bool inheritanceModelHasNVOffsetField(bool IsMemberFunction, MSInheritanceModel Inheritance)
Definition: CXXInheritance.h:371
usesMultipleInheritanceModel
static bool usesMultipleInheritanceModel(const CXXRecordDecl *RD)
Definition: MicrosoftCXXABI.cpp:210
clang::CXXRecordDecl::nullFieldOffsetIsZero
bool nullFieldOffsetIsZero() const
In the Microsoft C++ ABI, use zero for the field offset of a null data member pointer if we can guara...
Definition: MicrosoftCXXABI.cpp:240
clang::CXXRecordDecl::getNumVBases
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:612
clang::DeclaratorDecl
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:758
clang::inheritanceModelHasVBPtrOffsetField
bool inheritanceModelHasVBPtrOffsetField(MSInheritanceModel Inheritance)
Definition: CXXInheritance.h:365
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:773
clang::LangOptions::isSYCL
bool isSYCL() const
Definition: LangOptions.h:619
clang::MSInheritanceModel::Virtual
@ Virtual
clang::MemberPointerType
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2960
getMSMemberPointerSlots
static std::pair< unsigned, unsigned > getMSMemberPointerSlots(const MemberPointerType *MPT)
Definition: MicrosoftCXXABI.cpp:282
clang::MangleNumberingContext
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Definition: MangleNumberingContext.h:29
clang::inheritanceModelHasOnlyOneField
bool inheritanceModelHasOnlyOneField(bool IsMemberFunction, MSInheritanceModel Inheritance)
Definition: CXXInheritance.h:381
clang::ItaniumMangleContext::create
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Definition: ItaniumMangle.cpp:6557
clang::CXXRecordDecl::calculateInheritanceModel
MSInheritanceModel calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
Definition: MicrosoftCXXABI.cpp:224
clang::DiagnosticsEngine::getCustomDiagID
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:868
clang
Definition: CalledOnceCheck.h:17
clang::CXXRecordDecl::bases_begin
base_class_iterator bases_begin()
Definition: DeclCXX.h:604
clang::CXXRecordDecl::hasDefinition
bool hasDefinition() const
Definition: DeclCXX.h:550
clang::MSInheritanceModel
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition: Specifiers.h:374
clang::TypedefNameDecl
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3275
clang::CXXRecordDecl::isPolymorphic
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1171
Mangle.h
clang::MemberPointerType::getMostRecentCXXRecordDecl
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Definition: Type.cpp:4491
MangleNumberingContext.h
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:432
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:791
clang::createItaniumNumberingContext
std::unique_ptr< MangleNumberingContext > createItaniumNumberingContext(MangleContext *)
Definition: ItaniumCXXABI.cpp:297
clang::ASTContext::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: ASTContext.cpp:1505
RecordLayout.h
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1537
clang::CXXMethodDecl
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1983