xref: /freebsd/contrib/llvm-project/clang/lib/AST/Mangle.cpp (revision a7dea1671b87c07d2d266f836bfa8b58efc7c134)
1 //===--- Mangle.cpp - Mangle C++ Names --------------------------*- C++ -*-===//
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 // Implements generic name mangling support for blocks and Objective-C.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "clang/AST/Attr.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/Mangle.h"
20 #include "clang/AST/VTableBuilder.h"
21 #include "clang/Basic/ABI.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Mangler.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 
30 using namespace clang;
31 
32 // FIXME: For blocks we currently mimic GCC's mangling scheme, which leaves
33 // much to be desired. Come up with a better mangling scheme.
34 
35 static void mangleFunctionBlock(MangleContext &Context,
36                                 StringRef Outer,
37                                 const BlockDecl *BD,
38                                 raw_ostream &Out) {
39   unsigned discriminator = Context.getBlockId(BD, true);
40   if (discriminator == 0)
41     Out << "__" << Outer << "_block_invoke";
42   else
43     Out << "__" << Outer << "_block_invoke_" << discriminator+1;
44 }
45 
46 void MangleContext::anchor() { }
47 
48 enum CCMangling {
49   CCM_Other,
50   CCM_Fast,
51   CCM_RegCall,
52   CCM_Vector,
53   CCM_Std
54 };
55 
56 static bool isExternC(const NamedDecl *ND) {
57   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
58     return FD->isExternC();
59   return cast<VarDecl>(ND)->isExternC();
60 }
61 
62 static CCMangling getCallingConvMangling(const ASTContext &Context,
63                                          const NamedDecl *ND) {
64   const TargetInfo &TI = Context.getTargetInfo();
65   const llvm::Triple &Triple = TI.getTriple();
66   if (!Triple.isOSWindows() ||
67       !(Triple.getArch() == llvm::Triple::x86 ||
68         Triple.getArch() == llvm::Triple::x86_64))
69     return CCM_Other;
70 
71   if (Context.getLangOpts().CPlusPlus && !isExternC(ND) &&
72       TI.getCXXABI() == TargetCXXABI::Microsoft)
73     return CCM_Other;
74 
75   const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
76   if (!FD)
77     return CCM_Other;
78   QualType T = FD->getType();
79 
80   const FunctionType *FT = T->castAs<FunctionType>();
81 
82   CallingConv CC = FT->getCallConv();
83   switch (CC) {
84   default:
85     return CCM_Other;
86   case CC_X86FastCall:
87     return CCM_Fast;
88   case CC_X86StdCall:
89     return CCM_Std;
90   case CC_X86VectorCall:
91     return CCM_Vector;
92   }
93 }
94 
95 bool MangleContext::shouldMangleDeclName(const NamedDecl *D) {
96   const ASTContext &ASTContext = getASTContext();
97 
98   CCMangling CC = getCallingConvMangling(ASTContext, D);
99   if (CC != CCM_Other)
100     return true;
101 
102   // If the declaration has an owning module for linkage purposes that needs to
103   // be mangled, we must mangle its name.
104   if (!D->hasExternalFormalLinkage() && D->getOwningModuleForLinkage())
105     return true;
106 
107   // In C, functions with no attributes never need to be mangled. Fastpath them.
108   if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
109     return false;
110 
111   // Any decl can be declared with __asm("foo") on it, and this takes precedence
112   // over all other naming in the .o file.
113   if (D->hasAttr<AsmLabelAttr>())
114     return true;
115 
116   return shouldMangleCXXName(D);
117 }
118 
119 void MangleContext::mangleName(const NamedDecl *D, raw_ostream &Out) {
120   // Any decl can be declared with __asm("foo") on it, and this takes precedence
121   // over all other naming in the .o file.
122   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
123     // If we have an asm name, then we use it as the mangling.
124 
125     // If the label isn't literal, or if this is an alias for an LLVM intrinsic,
126     // do not add a "\01" prefix.
127     if (!ALA->getIsLiteralLabel() || ALA->getLabel().startswith("llvm.")) {
128       Out << ALA->getLabel();
129       return;
130     }
131 
132     // Adding the prefix can cause problems when one file has a "foo" and
133     // another has a "\01foo". That is known to happen on ELF with the
134     // tricks normally used for producing aliases (PR9177). Fortunately the
135     // llvm mangler on ELF is a nop, so we can just avoid adding the \01
136     // marker.
137     char GlobalPrefix =
138         getASTContext().getTargetInfo().getDataLayout().getGlobalPrefix();
139     if (GlobalPrefix)
140       Out << '\01'; // LLVM IR Marker for __asm("foo")
141 
142     Out << ALA->getLabel();
143     return;
144   }
145 
146   const ASTContext &ASTContext = getASTContext();
147   CCMangling CC = getCallingConvMangling(ASTContext, D);
148   bool MCXX = shouldMangleCXXName(D);
149   const TargetInfo &TI = Context.getTargetInfo();
150   if (CC == CCM_Other || (MCXX && TI.getCXXABI() == TargetCXXABI::Microsoft)) {
151     if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
152       mangleObjCMethodName(OMD, Out);
153     else
154       mangleCXXName(D, Out);
155     return;
156   }
157 
158   Out << '\01';
159   if (CC == CCM_Std)
160     Out << '_';
161   else if (CC == CCM_Fast)
162     Out << '@';
163   else if (CC == CCM_RegCall)
164     Out << "__regcall3__";
165 
166   if (!MCXX)
167     Out << D->getIdentifier()->getName();
168   else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
169     mangleObjCMethodName(OMD, Out);
170   else
171     mangleCXXName(D, Out);
172 
173   const FunctionDecl *FD = cast<FunctionDecl>(D);
174   const FunctionType *FT = FD->getType()->castAs<FunctionType>();
175   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT);
176   if (CC == CCM_Vector)
177     Out << '@';
178   Out << '@';
179   if (!Proto) {
180     Out << '0';
181     return;
182   }
183   assert(!Proto->isVariadic());
184   unsigned ArgWords = 0;
185   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
186     if (!MD->isStatic())
187       ++ArgWords;
188   for (const auto &AT : Proto->param_types())
189     // Size should be aligned to pointer size.
190     ArgWords +=
191         llvm::alignTo(ASTContext.getTypeSize(AT), TI.getPointerWidth(0)) /
192         TI.getPointerWidth(0);
193   Out << ((TI.getPointerWidth(0) / 8) * ArgWords);
194 }
195 
196 void MangleContext::mangleGlobalBlock(const BlockDecl *BD,
197                                       const NamedDecl *ID,
198                                       raw_ostream &Out) {
199   unsigned discriminator = getBlockId(BD, false);
200   if (ID) {
201     if (shouldMangleDeclName(ID))
202       mangleName(ID, Out);
203     else {
204       Out << ID->getIdentifier()->getName();
205     }
206   }
207   if (discriminator == 0)
208     Out << "_block_invoke";
209   else
210     Out << "_block_invoke_" << discriminator+1;
211 }
212 
213 void MangleContext::mangleCtorBlock(const CXXConstructorDecl *CD,
214                                     CXXCtorType CT, const BlockDecl *BD,
215                                     raw_ostream &ResStream) {
216   SmallString<64> Buffer;
217   llvm::raw_svector_ostream Out(Buffer);
218   mangleCXXCtor(CD, CT, Out);
219   mangleFunctionBlock(*this, Buffer, BD, ResStream);
220 }
221 
222 void MangleContext::mangleDtorBlock(const CXXDestructorDecl *DD,
223                                     CXXDtorType DT, const BlockDecl *BD,
224                                     raw_ostream &ResStream) {
225   SmallString<64> Buffer;
226   llvm::raw_svector_ostream Out(Buffer);
227   mangleCXXDtor(DD, DT, Out);
228   mangleFunctionBlock(*this, Buffer, BD, ResStream);
229 }
230 
231 void MangleContext::mangleBlock(const DeclContext *DC, const BlockDecl *BD,
232                                 raw_ostream &Out) {
233   assert(!isa<CXXConstructorDecl>(DC) && !isa<CXXDestructorDecl>(DC));
234 
235   SmallString<64> Buffer;
236   llvm::raw_svector_ostream Stream(Buffer);
237   if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
238     mangleObjCMethodName(Method, Stream);
239   } else {
240     assert((isa<NamedDecl>(DC) || isa<BlockDecl>(DC)) &&
241            "expected a NamedDecl or BlockDecl");
242     if (isa<BlockDecl>(DC))
243       for (; DC && isa<BlockDecl>(DC); DC = DC->getParent())
244         (void) getBlockId(cast<BlockDecl>(DC), true);
245     assert((isa<TranslationUnitDecl>(DC) || isa<NamedDecl>(DC)) &&
246            "expected a TranslationUnitDecl or a NamedDecl");
247     if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
248       mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
249     else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
250       mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
251     else if (auto ND = dyn_cast<NamedDecl>(DC)) {
252       if (!shouldMangleDeclName(ND) && ND->getIdentifier())
253         Stream << ND->getIdentifier()->getName();
254       else {
255         // FIXME: We were doing a mangleUnqualifiedName() before, but that's
256         // a private member of a class that will soon itself be private to the
257         // Itanium C++ ABI object. What should we do now? Right now, I'm just
258         // calling the mangleName() method on the MangleContext; is there a
259         // better way?
260         mangleName(ND, Stream);
261       }
262     }
263   }
264   mangleFunctionBlock(*this, Buffer, BD, Out);
265 }
266 
267 void MangleContext::mangleObjCMethodNameWithoutSize(const ObjCMethodDecl *MD,
268                                                     raw_ostream &OS) {
269   const ObjCContainerDecl *CD =
270   dyn_cast<ObjCContainerDecl>(MD->getDeclContext());
271   assert (CD && "Missing container decl in GetNameForMethod");
272   OS << (MD->isInstanceMethod() ? '-' : '+') << '[';
273   if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(CD)) {
274     OS << CID->getClassInterface()->getName();
275     OS << '(' << *CID << ')';
276   } else {
277     OS << CD->getName();
278   }
279   OS << ' ';
280   MD->getSelector().print(OS);
281   OS << ']';
282 }
283 
284 void MangleContext::mangleObjCMethodName(const ObjCMethodDecl *MD,
285                                          raw_ostream &Out) {
286   SmallString<64> Name;
287   llvm::raw_svector_ostream OS(Name);
288 
289   mangleObjCMethodNameWithoutSize(MD, OS);
290   Out << OS.str().size() << OS.str();
291 }
292 
293 class ASTNameGenerator::Implementation {
294   std::unique_ptr<MangleContext> MC;
295   llvm::DataLayout DL;
296 
297 public:
298   explicit Implementation(ASTContext &Ctx)
299       : MC(Ctx.createMangleContext()), DL(Ctx.getTargetInfo().getDataLayout()) {
300   }
301 
302   bool writeName(const Decl *D, raw_ostream &OS) {
303     // First apply frontend mangling.
304     SmallString<128> FrontendBuf;
305     llvm::raw_svector_ostream FrontendBufOS(FrontendBuf);
306     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
307       if (FD->isDependentContext())
308         return true;
309       if (writeFuncOrVarName(FD, FrontendBufOS))
310         return true;
311     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
312       if (writeFuncOrVarName(VD, FrontendBufOS))
313         return true;
314     } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
315       MC->mangleObjCMethodNameWithoutSize(MD, OS);
316       return false;
317     } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
318       writeObjCClassName(ID, FrontendBufOS);
319     } else {
320       return true;
321     }
322 
323     // Now apply backend mangling.
324     llvm::Mangler::getNameWithPrefix(OS, FrontendBufOS.str(), DL);
325     return false;
326   }
327 
328   std::string getName(const Decl *D) {
329     std::string Name;
330     {
331       llvm::raw_string_ostream OS(Name);
332       writeName(D, OS);
333     }
334     return Name;
335   }
336 
337   enum ObjCKind {
338     ObjCClass,
339     ObjCMetaclass,
340   };
341 
342   static StringRef getClassSymbolPrefix(ObjCKind Kind,
343                                         const ASTContext &Context) {
344     if (Context.getLangOpts().ObjCRuntime.isGNUFamily())
345       return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_";
346     return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_";
347   }
348 
349   std::vector<std::string> getAllManglings(const ObjCContainerDecl *OCD) {
350     StringRef ClassName;
351     if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
352       ClassName = OID->getObjCRuntimeNameAsString();
353     else if (const auto *OID = dyn_cast<ObjCImplementationDecl>(OCD))
354       ClassName = OID->getObjCRuntimeNameAsString();
355 
356     if (ClassName.empty())
357       return {};
358 
359     auto Mangle = [&](ObjCKind Kind, StringRef ClassName) -> std::string {
360       SmallString<40> Mangled;
361       auto Prefix = getClassSymbolPrefix(Kind, OCD->getASTContext());
362       llvm::Mangler::getNameWithPrefix(Mangled, Prefix + ClassName, DL);
363       return Mangled.str();
364     };
365 
366     return {
367         Mangle(ObjCClass, ClassName),
368         Mangle(ObjCMetaclass, ClassName),
369     };
370   }
371 
372   std::vector<std::string> getAllManglings(const Decl *D) {
373     if (const auto *OCD = dyn_cast<ObjCContainerDecl>(D))
374       return getAllManglings(OCD);
375 
376     if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
377       return {};
378 
379     const NamedDecl *ND = cast<NamedDecl>(D);
380 
381     ASTContext &Ctx = ND->getASTContext();
382     std::unique_ptr<MangleContext> M(Ctx.createMangleContext());
383 
384     std::vector<std::string> Manglings;
385 
386     auto hasDefaultCXXMethodCC = [](ASTContext &C, const CXXMethodDecl *MD) {
387       auto DefaultCC = C.getDefaultCallingConvention(/*IsVariadic=*/false,
388                                                      /*IsCXXMethod=*/true);
389       auto CC = MD->getType()->castAs<FunctionProtoType>()->getCallConv();
390       return CC == DefaultCC;
391     };
392 
393     if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND)) {
394       Manglings.emplace_back(getMangledStructor(CD, Ctor_Base));
395 
396       if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily())
397         if (!CD->getParent()->isAbstract())
398           Manglings.emplace_back(getMangledStructor(CD, Ctor_Complete));
399 
400       if (Ctx.getTargetInfo().getCXXABI().isMicrosoft())
401         if (CD->hasAttr<DLLExportAttr>() && CD->isDefaultConstructor())
402           if (!(hasDefaultCXXMethodCC(Ctx, CD) && CD->getNumParams() == 0))
403             Manglings.emplace_back(getMangledStructor(CD, Ctor_DefaultClosure));
404     } else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND)) {
405       Manglings.emplace_back(getMangledStructor(DD, Dtor_Base));
406       if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily()) {
407         Manglings.emplace_back(getMangledStructor(DD, Dtor_Complete));
408         if (DD->isVirtual())
409           Manglings.emplace_back(getMangledStructor(DD, Dtor_Deleting));
410       }
411     } else if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(ND)) {
412       Manglings.emplace_back(getName(ND));
413       if (MD->isVirtual())
414         if (const auto *TIV = Ctx.getVTableContext()->getThunkInfo(MD))
415           for (const auto &T : *TIV)
416             Manglings.emplace_back(getMangledThunk(MD, T));
417     }
418 
419     return Manglings;
420   }
421 
422 private:
423   bool writeFuncOrVarName(const NamedDecl *D, raw_ostream &OS) {
424     if (MC->shouldMangleDeclName(D)) {
425       if (const auto *CtorD = dyn_cast<CXXConstructorDecl>(D))
426         MC->mangleCXXCtor(CtorD, Ctor_Complete, OS);
427       else if (const auto *DtorD = dyn_cast<CXXDestructorDecl>(D))
428         MC->mangleCXXDtor(DtorD, Dtor_Complete, OS);
429       else
430         MC->mangleName(D, OS);
431       return false;
432     } else {
433       IdentifierInfo *II = D->getIdentifier();
434       if (!II)
435         return true;
436       OS << II->getName();
437       return false;
438     }
439   }
440 
441   void writeObjCClassName(const ObjCInterfaceDecl *D, raw_ostream &OS) {
442     OS << getClassSymbolPrefix(ObjCClass, D->getASTContext());
443     OS << D->getObjCRuntimeNameAsString();
444   }
445 
446   std::string getMangledStructor(const NamedDecl *ND, unsigned StructorType) {
447     std::string FrontendBuf;
448     llvm::raw_string_ostream FOS(FrontendBuf);
449 
450     if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND))
451       MC->mangleCXXCtor(CD, static_cast<CXXCtorType>(StructorType), FOS);
452     else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND))
453       MC->mangleCXXDtor(DD, static_cast<CXXDtorType>(StructorType), FOS);
454 
455     std::string BackendBuf;
456     llvm::raw_string_ostream BOS(BackendBuf);
457 
458     llvm::Mangler::getNameWithPrefix(BOS, FOS.str(), DL);
459 
460     return BOS.str();
461   }
462 
463   std::string getMangledThunk(const CXXMethodDecl *MD, const ThunkInfo &T) {
464     std::string FrontendBuf;
465     llvm::raw_string_ostream FOS(FrontendBuf);
466 
467     MC->mangleThunk(MD, T, FOS);
468 
469     std::string BackendBuf;
470     llvm::raw_string_ostream BOS(BackendBuf);
471 
472     llvm::Mangler::getNameWithPrefix(BOS, FOS.str(), DL);
473 
474     return BOS.str();
475   }
476 };
477 
478 ASTNameGenerator::ASTNameGenerator(ASTContext &Ctx)
479     : Impl(std::make_unique<Implementation>(Ctx)) {}
480 
481 ASTNameGenerator::~ASTNameGenerator() {}
482 
483 bool ASTNameGenerator::writeName(const Decl *D, raw_ostream &OS) {
484   return Impl->writeName(D, OS);
485 }
486 
487 std::string ASTNameGenerator::getName(const Decl *D) {
488   return Impl->getName(D);
489 }
490 
491 std::vector<std::string> ASTNameGenerator::getAllManglings(const Decl *D) {
492   return Impl->getAllManglings(D);
493 }
494