1//===------- ItaniumCXXABI.cpp - AST support for the Itanium 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 Itanium C++ ABI, which is
10// documented at:
11// http://www.codesourcery.com/public/cxx-abi/abi.html
12// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
13//
14// It also supports the closely-related ARM C++ ABI, documented at:
15// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
16//
17//===----------------------------------------------------------------------===//
18
19#include "CXXABI.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/Mangle.h"
23#include "clang/AST/MangleNumberingContext.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/Type.h"
26#include "clang/Basic/TargetInfo.h"
27#include "llvm/ADT/iterator.h"
28#include <optional>
29
30using namespace clang;
31
32namespace {
33
34/// According to Itanium C++ ABI 5.1.2:
35/// the name of an anonymous union is considered to be
36/// the name of the first named data member found by a pre-order,
37/// depth-first, declaration-order walk of the data members of
38/// the anonymous union.
39/// If there is no such data member (i.e., if all of the data members
40/// in the union are unnamed), then there is no way for a program to
41/// refer to the anonymous union, and there is therefore no need to mangle its name.
42///
43/// Returns the name of anonymous union VarDecl or nullptr if it is not found.
44static const IdentifierInfo *findAnonymousUnionVarDeclName(const VarDecl& VD) {
45 const auto *RD = VD.getType()->castAsRecordDecl();
46 assert(RD->isUnion() && "RecordType is expected to be a union.");
47 if (const FieldDecl *FD = RD->findFirstNamedDataMember()) {
48 return FD->getIdentifier();
49 }
50
51 return nullptr;
52}
53
54/// The name of a decomposition declaration.
55struct DecompositionDeclName {
56 using BindingArray = ArrayRef<const BindingDecl*>;
57
58 /// Representative example of a set of bindings with these names.
59 BindingArray Bindings;
60
61 /// Iterators over the sequence of identifiers in the name.
62 struct Iterator
63 : llvm::iterator_adaptor_base<Iterator, BindingArray::const_iterator,
64 std::random_access_iterator_tag,
65 const IdentifierInfo *> {
66 Iterator(BindingArray::const_iterator It) : iterator_adaptor_base(It) {}
67 const IdentifierInfo *operator*() const {
68 return (*this->I)->getIdentifier();
69 }
70 };
71 Iterator begin() const { return Iterator(Bindings.begin()); }
72 Iterator end() const { return Iterator(Bindings.end()); }
73};
74}
75
76namespace llvm {
77template<>
78struct DenseMapInfo<DecompositionDeclName> {
79 using ArrayInfo = llvm::DenseMapInfo<ArrayRef<const BindingDecl*>>;
80 static unsigned getHashValue(DecompositionDeclName Key) {
81 return llvm::hash_combine_range(R&: Key);
82 }
83 static bool isEqual(DecompositionDeclName LHS, DecompositionDeclName RHS) {
84 return LHS.Bindings.size() == RHS.Bindings.size() &&
85 std::equal(first1: LHS.begin(), last1: LHS.end(), first2: RHS.begin());
86 }
87};
88}
89
90namespace {
91
92/// Keeps track of the mangled names of lambda expressions and block
93/// literals within a particular context.
94class ItaniumNumberingContext : public MangleNumberingContext {
95 ItaniumMangleContext *Mangler;
96 llvm::StringMap<unsigned> LambdaManglingNumbers;
97 unsigned BlockManglingNumber = 0;
98 llvm::DenseMap<const IdentifierInfo *, unsigned> VarManglingNumbers;
99 llvm::DenseMap<const IdentifierInfo *, unsigned> TagManglingNumbers;
100 llvm::DenseMap<DecompositionDeclName, unsigned>
101 DecompsitionDeclManglingNumbers;
102
103public:
104 ItaniumNumberingContext(ItaniumMangleContext *Mangler) : Mangler(Mangler) {}
105
106 unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
107 const CXXRecordDecl *Lambda = CallOperator->getParent();
108 assert(Lambda->isLambda());
109
110 // Computation of the <lambda-sig> is non-trivial and subtle. Rather than
111 // duplicating it here, just mangle the <lambda-sig> directly.
112 llvm::SmallString<128> LambdaSig;
113 llvm::raw_svector_ostream Out(LambdaSig);
114 Mangler->mangleLambdaSig(Lambda, Out);
115
116 return ++LambdaManglingNumbers[LambdaSig];
117 }
118
119 unsigned getManglingNumber(const BlockDecl *BD) override {
120 return ++BlockManglingNumber;
121 }
122
123 unsigned getStaticLocalNumber(const VarDecl *VD) override {
124 return 0;
125 }
126
127 /// Variable decls are numbered by identifier.
128 unsigned getManglingNumber(const VarDecl *VD, unsigned) override {
129 if (auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
130 DecompositionDeclName Name{.Bindings: DD->bindings()};
131 return ++DecompsitionDeclManglingNumbers[Name];
132 }
133
134 const IdentifierInfo *Identifier = VD->getIdentifier();
135 if (!Identifier) {
136 // VarDecl without an identifier represents an anonymous union
137 // declaration.
138 Identifier = findAnonymousUnionVarDeclName(VD: *VD);
139 }
140 return ++VarManglingNumbers[Identifier];
141 }
142
143 unsigned getManglingNumber(const TagDecl *TD, unsigned) override {
144 return ++TagManglingNumbers[TD->getIdentifier()];
145 }
146};
147
148// A version of this for SYCL that makes sure that 'device' mangling context
149// matches the lambda mangling number, so that __builtin_sycl_unique_stable_name
150// can be consistently generated between a MS and Itanium host by just referring
151// to the device mangling number.
152class ItaniumSYCLNumberingContext : public ItaniumNumberingContext {
153 llvm::DenseMap<const CXXMethodDecl *, unsigned> ManglingNumbers;
154 using ManglingItr = decltype(ManglingNumbers)::iterator;
155
156public:
157 ItaniumSYCLNumberingContext(ItaniumMangleContext *Mangler)
158 : ItaniumNumberingContext(Mangler) {}
159
160 unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
161 unsigned Number = ItaniumNumberingContext::getManglingNumber(CallOperator);
162 std::pair<ManglingItr, bool> emplace_result =
163 ManglingNumbers.try_emplace(Key: CallOperator, Args&: Number);
164 (void)emplace_result;
165 assert(emplace_result.second && "Lambda number set multiple times?");
166 return Number;
167 }
168
169 using ItaniumNumberingContext::getManglingNumber;
170
171 unsigned getDeviceManglingNumber(const CXXMethodDecl *CallOperator) override {
172 ManglingItr Itr = ManglingNumbers.find(Val: CallOperator);
173 assert(Itr != ManglingNumbers.end() && "Lambda not yet mangled?");
174
175 return Itr->second;
176 }
177};
178
179class ItaniumCXXABI : public CXXABI {
180private:
181 std::unique_ptr<MangleContext> Mangler;
182protected:
183 ASTContext &Context;
184public:
185 ItaniumCXXABI(ASTContext &Ctx)
186 : Mangler(Ctx.createMangleContext()), Context(Ctx) {}
187
188 MemberPointerInfo
189 getMemberPointerInfo(const MemberPointerType *MPT) const override {
190 const TargetInfo &Target = Context.getTargetInfo();
191 TargetInfo::IntType PtrDiff = Target.getPtrDiffType(AddrSpace: LangAS::Default);
192 MemberPointerInfo MPI;
193 MPI.Width = Target.getTypeWidth(T: PtrDiff);
194 MPI.Align = Target.getTypeAlign(T: PtrDiff);
195 MPI.HasPadding = false;
196 if (MPT->isMemberFunctionPointer())
197 MPI.Width *= 2;
198 return MPI;
199 }
200
201 CallingConv getDefaultMethodCallConv(bool isVariadic) const override {
202 const llvm::Triple &T = Context.getTargetInfo().getTriple();
203 if (!isVariadic && T.isWindowsGNUEnvironment() &&
204 T.getArch() == llvm::Triple::x86)
205 return CC_X86ThisCall;
206 return Context.getTargetInfo().getDefaultCallingConv();
207 }
208
209 // We cheat and just check that the class has a vtable pointer, and that it's
210 // only big enough to have a vtable pointer and nothing more (or less).
211 bool isNearlyEmpty(const CXXRecordDecl *RD) const override {
212
213 // Check that the class has a vtable pointer.
214 if (!RD->isDynamicClass())
215 return false;
216
217 const ASTRecordLayout &Layout = Context.getASTRecordLayout(D: RD);
218 CharUnits PointerSize = Context.toCharUnitsFromBits(
219 BitSize: Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default));
220 return Layout.getNonVirtualSize() == PointerSize;
221 }
222
223 const CXXConstructorDecl *
224 getCopyConstructorForExceptionObject(CXXRecordDecl *RD) override {
225 return nullptr;
226 }
227
228 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
229 CXXConstructorDecl *CD) override {}
230
231 void addTypedefNameForUnnamedTagDecl(TagDecl *TD,
232 TypedefNameDecl *DD) override {}
233
234 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD) override {
235 return nullptr;
236 }
237
238 void addDeclaratorForUnnamedTagDecl(TagDecl *TD,
239 DeclaratorDecl *DD) override {}
240
241 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD) override {
242 return nullptr;
243 }
244
245 std::unique_ptr<MangleNumberingContext>
246 createMangleNumberingContext() const override {
247 if (Context.getLangOpts().isSYCL())
248 return std::make_unique<ItaniumSYCLNumberingContext>(
249 args: cast<ItaniumMangleContext>(Val: Mangler.get()));
250 return std::make_unique<ItaniumNumberingContext>(
251 args: cast<ItaniumMangleContext>(Val: Mangler.get()));
252 }
253};
254}
255
256CXXABI *clang::CreateItaniumCXXABI(ASTContext &Ctx) {
257 return new ItaniumCXXABI(Ctx);
258}
259
260std::unique_ptr<MangleNumberingContext>
261clang::createItaniumNumberingContext(MangleContext *Mangler) {
262 return std::make_unique<ItaniumNumberingContext>(
263 args: cast<ItaniumMangleContext>(Val: Mangler));
264}
265