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