clang 24.0.0git
Mangle.cpp
Go to the documentation of this file.
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/Mangle.h"
14#include "clang/AST/Attr.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ExprCXX.h"
22#include "clang/Basic/ABI.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Mangler.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/Format.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace clang;
33
34void clang::mangleObjCMethodName(raw_ostream &OS, bool includePrefixByte,
35 bool isInstanceMethod, StringRef ClassName,
36 std::optional<StringRef> CategoryName,
37 StringRef MethodName, bool useDirectABI) {
38 assert(
39 !(includePrefixByte && useDirectABI) &&
40 "includePrefixByte and useDirectABI shouldn't be set at the same time");
41 // \01+[ContainerName(CategoryName) SelectorName]
42 // Or for direct ABI: +[ContainerName(CategoryName) SelectorName]D
43 if (includePrefixByte)
44 OS << "\01";
45 OS << (isInstanceMethod ? '-' : '+');
46 OS << '[';
47 OS << ClassName;
48 if (CategoryName)
49 OS << "(" << *CategoryName << ")";
50 OS << " ";
51 OS << MethodName;
52 OS << ']';
53 if (useDirectABI)
54 OS << 'D';
55}
56
57// FIXME: For blocks we currently mimic GCC's mangling scheme, which leaves
58// much to be desired. Come up with a better mangling scheme.
59
61 StringRef Outer,
62 const BlockDecl *BD,
63 raw_ostream &Out) {
64 unsigned discriminator = Context.getBlockId(BD, true);
65 if (discriminator == 0)
66 Out << "__" << Outer << "_block_invoke";
67 else
68 Out << "__" << Outer << "_block_invoke_" << discriminator+1;
69}
70
71void MangleContext::anchor() { }
72
81
82static bool isExternC(const NamedDecl *ND) {
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
84 return FD->isExternC();
85 if (const VarDecl *VD = dyn_cast<VarDecl>(ND))
86 return VD->isExternC();
87 return false;
88}
89
91 const NamedDecl *ND) {
92 const TargetInfo &TI = Context.getTargetInfo();
93 const llvm::Triple &Triple = TI.getTriple();
94
95 // On wasm, the argc/argv form of "main" is renamed so that the startup code
96 // can call it with the correct function signature.
97 if (Triple.isWasm())
98 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
99 if (FD->isMain() && FD->getNumParams() == 2)
101
103 return CCM_Other;
104
105 if (Context.getLangOpts().CPlusPlus && !isExternC(ND) &&
106 TI.getCXXABI() == TargetCXXABI::Microsoft)
107 return CCM_Other;
108
109 const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
110 if (!FD)
111 return CCM_Other;
112 QualType T = FD->getType();
113
114 const FunctionType *FT = T->castAs<FunctionType>();
115
116 CallingConv CC = FT->getCallConv();
117 switch (CC) {
118 default:
119 return CCM_Other;
120 case CC_X86FastCall:
121 return CCM_Fast;
122 case CC_X86StdCall:
123 return CCM_Std;
124 case CC_X86VectorCall:
125 return CCM_Vector;
126 }
127}
128
130 // Any decl can be declared with __asm("foo") on it, and this takes precedence
131 // over all other naming in the .o file.
132 if (D->hasAttr<AsmLabelAttr>())
133 return true;
134
136}
137
140
142 if (CC != CCM_Other)
143 return true;
144
145 // If the declaration has an owning module for linkage purposes that needs to
146 // be mangled, we must mangle its name.
148 return true;
149
150 // C functions with internal linkage have to be mangled with option
151 // -funique-internal-linkage-names.
152 if (!getASTContext().getLangOpts().CPlusPlus &&
154 return true;
155
156 // In C, functions with no attributes never need to be mangled. Fastpath them.
157 if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
158 return false;
159
160 // Declarations that don't have identifier names always need to be mangled.
161 if (isa<MSGuidDecl>(D))
162 return true;
163
164 return shouldMangleCXXName(D);
165}
166
167namespace {
168// Visits a function body looking for a direct call back to the symbol the
169// function will link as. Detects both asm-label aliases and __builtin_*
170// wrappers (PR9614 / glibc btowc pattern).
171struct FunctionIsDirectlyRecursive
172 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
173 const StringRef Name;
174 const Builtin::Context &BI;
175 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
176 : Name(N), BI(C) {}
177
178 bool VisitCallExpr(const CallExpr *E) {
179 const FunctionDecl *FD = E->getDirectCallee();
180 if (!FD)
181 return false;
182 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
183 if (Attr && Name == Attr->getLabel())
184 return true;
185 unsigned BuiltinID = FD->getBuiltinID();
186 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
187 return false;
188 std::string BuiltinNameStr = BI.getName(BuiltinID);
189 StringRef BuiltinName = BuiltinNameStr;
190 return BuiltinName.consume_front("__builtin_") && Name == BuiltinName;
191 }
192
193 bool VisitStmt(const Stmt *S) {
194 for (const Stmt *Child : S->children())
195 if (Child && this->Visit(Child))
196 return true;
197 return false;
198 }
199};
200} // namespace
201
203 StringRef Name;
204 if (shouldMangleDeclName(FD)) {
205 // C++-mangled functions can only recurse into themselves through an
206 // asm label that bypasses the mangled name.
207 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
208 if (!Attr)
209 return false;
210 Name = Attr->getLabel();
211 } else {
212 Name = FD->getName();
213 }
214
215 FunctionIsDirectlyRecursive Walker(Name, FD->getASTContext().BuiltinInfo);
216 const Stmt *Body = FD->getBody();
217 return Body ? Walker.Visit(Body) : false;
218}
219
220/// Given an LLDB function call label, this function prints the label
221/// into \c Out, together with the structor type of \c GD (if the
222/// decl is a constructor/destructor). LLDB knows how to handle mangled
223/// names with this encoding.
224///
225/// Example input label:
226/// $__lldb_func::123:456:~Foo
227///
228/// Example output:
229/// $__lldb_func:D1:123:456:~Foo
230///
231static void emitLLDBAsmLabel(llvm::StringRef label, GlobalDecl GD,
232 llvm::raw_ostream &Out) {
233 assert(label.starts_with(LLDBManglingABI::FunctionLabelPrefix));
234
236
237 if (auto *Ctor = llvm::dyn_cast<clang::CXXConstructorDecl>(GD.getDecl())) {
238 Out << "C";
239 if (Ctor->getInheritedConstructor().getConstructor())
240 Out << "I";
241 Out << GD.getCtorType();
242 } else if (llvm::isa<clang::CXXDestructorDecl>(GD.getDecl())) {
243 Out << "D" << GD.getDtorType();
244 }
245
246 Out << label.substr(LLDBManglingABI::FunctionLabelPrefix.size());
247}
248
249void MangleContext::mangleName(GlobalDecl GD, raw_ostream &Out) {
250 const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
251
252 // Any decl can be declared with __asm("foo") on it, and this takes precedence
253 // over all other naming in the .o file.
254 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
255 // If we have an asm name, then we use it as the mangling.
256
257 // If the label is an alias for an LLVM intrinsic,
258 // do not add a "\01" prefix.
259 if (ALA->getLabel().starts_with("llvm.")) {
260 Out << ALA->getLabel();
261 return;
262 }
263
264 // Adding the prefix can cause problems when one file has a "foo" and
265 // another has a "\01foo". That is known to happen on ELF with the
266 // tricks normally used for producing aliases (PR9177). Fortunately the
267 // llvm mangler on ELF is a nop, so we can just avoid adding the \01
268 // marker.
269 StringRef UserLabelPrefix =
271#ifndef NDEBUG
272 char GlobalPrefix =
273 llvm::DataLayout(getASTContext().getTargetInfo().getDataLayoutString())
274 .getGlobalPrefix();
275 assert((UserLabelPrefix.empty() && !GlobalPrefix) ||
276 (UserLabelPrefix.size() == 1 && UserLabelPrefix[0] == GlobalPrefix));
277#endif
278 if (!UserLabelPrefix.empty())
279 Out << '\01'; // LLVM IR Marker for __asm("foo")
280
281 if (ALA->getLabel().starts_with(LLDBManglingABI::FunctionLabelPrefix))
282 emitLLDBAsmLabel(ALA->getLabel(), GD, Out);
283 else
284 Out << ALA->getLabel();
285
286 return;
287 }
288
290}
291
293 raw_ostream &Out) {
295 const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
296
297 if (auto *GD = dyn_cast<MSGuidDecl>(D))
298 return mangleMSGuidDecl(GD, Out);
299
301
302 if (CC == CCM_WasmMainArgcArgv) {
303 Out << "__main_argc_argv";
304 return;
305 }
306
307 bool MCXX = shouldMangleCXXName(D);
308 const TargetInfo &TI = Context.getTargetInfo();
309 if (CC == CCM_Other || (MCXX && TI.getCXXABI() == TargetCXXABI::Microsoft)) {
310 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
312 else
313 mangleCXXName(GD, Out);
314 return;
315 }
316
317 Out << '\01';
318 if (CC == CCM_Std)
319 Out << '_';
320 else if (CC == CCM_Fast)
321 Out << '@';
322 else if (CC == CCM_RegCall) {
323 if (getASTContext().getLangOpts().RegCall4)
324 Out << "__regcall4__";
325 else
326 Out << "__regcall3__";
327 }
328
329 if (!MCXX)
330 Out << D->getIdentifier()->getName();
331 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
333 else
334 mangleCXXName(GD, Out);
335
336 const FunctionDecl *FD = cast<FunctionDecl>(D);
337 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
338 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT);
339 if (CC == CCM_Vector)
340 Out << '@';
341 Out << '@';
342 if (!Proto) {
343 Out << '0';
344 return;
345 }
346 assert(!Proto->isVariadic());
347 unsigned ArgWords = 0;
348 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
349 if (MD->isImplicitObjectMemberFunction())
350 ++ArgWords;
351 uint64_t DefaultPtrWidth = TI.getPointerWidth(LangAS::Default);
352 for (const auto &AT : Proto->param_types()) {
353 // If an argument type is incomplete there is no way to get its size to
354 // correctly encode into the mangling scheme.
355 // Follow GCCs behaviour by simply breaking out of the loop.
356 if (AT->isIncompleteType())
357 break;
358 // Size should be aligned to pointer size.
359 ArgWords += llvm::alignTo(ASTContext.getTypeSize(AT), DefaultPtrWidth) /
360 DefaultPtrWidth;
361 }
362 Out << ((DefaultPtrWidth / 8) * ArgWords);
363}
364
366 raw_ostream &Out) const {
367 // For now, follow the MSVC naming convention for GUID objects on all
368 // targets.
369 MSGuidDecl::Parts P = GD->getParts();
370 Out << llvm::format("_GUID_%08" PRIx32 "_%04" PRIx32 "_%04" PRIx32 "_",
371 P.Part1, P.Part2, P.Part3);
372 unsigned I = 0;
373 for (uint8_t C : P.Part4And5) {
374 Out << llvm::format("%02" PRIx8, C);
375 if (++I == 2)
376 Out << "_";
377 }
378}
379
381 const NamedDecl *ID,
382 raw_ostream &Out) {
383 unsigned discriminator = getBlockId(BD, false);
384 if (ID) {
385 if (shouldMangleDeclName(ID))
386 mangleName(ID, Out);
387 else {
388 Out << ID->getIdentifier()->getName();
389 }
390 }
391 if (discriminator == 0)
392 Out << "_block_invoke";
393 else
394 Out << "_block_invoke_" << discriminator+1;
395}
396
398 CXXCtorType CT, const BlockDecl *BD,
399 raw_ostream &ResStream) {
400 SmallString<64> Buffer;
401 llvm::raw_svector_ostream Out(Buffer);
402 mangleName(GlobalDecl(CD, CT), Out);
403 mangleFunctionBlock(*this, Buffer, BD, ResStream);
404}
405
407 CXXDtorType DT, const BlockDecl *BD,
408 raw_ostream &ResStream) {
409 SmallString<64> Buffer;
410 llvm::raw_svector_ostream Out(Buffer);
411 mangleName(GlobalDecl(DD, DT), Out);
412 mangleFunctionBlock(*this, Buffer, BD, ResStream);
413}
414
416 raw_ostream &Out) {
418
419 SmallString<64> Buffer;
420 llvm::raw_svector_ostream Stream(Buffer);
421 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
423 } else {
424 assert((isa<NamedDecl>(DC) || isa<BlockDecl>(DC)) &&
425 "expected a NamedDecl or BlockDecl");
426 for (; isa_and_nonnull<BlockDecl>(DC); DC = DC->getParent())
427 (void)getBlockId(cast<BlockDecl>(DC), true);
428 assert((isa<TranslationUnitDecl>(DC) || isa<NamedDecl>(DC)) &&
429 "expected a TranslationUnitDecl or a NamedDecl");
430 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
431 mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
432 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
433 mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
434 else if (auto ND = dyn_cast<NamedDecl>(DC)) {
435 if (!shouldMangleDeclName(ND) && ND->getIdentifier())
436 Stream << ND->getIdentifier()->getName();
437 else {
438 // FIXME: We were doing a mangleUnqualifiedName() before, but that's
439 // a private member of a class that will soon itself be private to the
440 // Itanium C++ ABI object. What should we do now? Right now, I'm just
441 // calling the mangleName() method on the MangleContext; is there a
442 // better way?
443 mangleName(ND, Stream);
444 }
445 }
446 }
447 mangleFunctionBlock(*this, Buffer, BD, Out);
448}
449
451 raw_ostream &OS,
452 bool includePrefixByte,
453 bool includeCategoryNamespace,
454 bool useDirectABI) const {
455 if (getASTContext().getLangOpts().ObjCRuntime.isGNUFamily()) {
456 // This is the mangling we've always used on the GNU runtimes, but it
457 // has obvious collisions in the face of underscores within class
458 // names, category names, and selectors; maybe we should improve it.
459
460 OS << (MD->isClassMethod() ? "_c_" : "_i_")
461 << MD->getClassInterface()->getName() << '_';
462
463 if (includeCategoryNamespace) {
464 if (auto category = MD->getCategory())
465 OS << category->getName();
466 }
467 OS << '_';
468
469 auto selector = MD->getSelector();
470 for (unsigned slotIndex = 0,
471 numArgs = selector.getNumArgs(),
472 slotEnd = std::max(numArgs, 1U);
473 slotIndex != slotEnd; ++slotIndex) {
474 if (auto name = selector.getIdentifierInfoForSlot(slotIndex))
475 OS << name->getName();
476
477 // Replace all the positions that would've been ':' with '_'.
478 // That's after each slot except that a unary selector doesn't
479 // end in ':'.
480 if (numArgs)
481 OS << '_';
482 }
483
484 return;
485 }
486
487 // \01+[ContainerName(CategoryName) SelectorName]
488 auto CategoryName = std::optional<StringRef>();
489 StringRef ClassName = "";
490 if (const auto *CID = MD->getCategory()) {
491 if (const auto *CI = CID->getClassInterface()) {
492 ClassName = CI->getName();
493 if (includeCategoryNamespace) {
494 CategoryName = CID->getName();
495 }
496 }
497 } else if (const auto *CD =
498 dyn_cast<ObjCContainerDecl>(MD->getDeclContext())) {
499 ClassName = CD->getName();
500 } else {
501 llvm_unreachable("Unexpected ObjC method decl context");
502 }
503 std::string MethodName;
504 llvm::raw_string_ostream MethodNameOS(MethodName);
505 MD->getSelector().print(MethodNameOS);
506 // Normal methods always have internal linkage, and we prefix them with '\01'
507 // for reasons that are somewhat lost to time. We suppress this for direct
508 // methods because they have non-internal linkage and we don't want to make it
509 // unnecessarily difficult to refer to them, e.g. in things like export lists.
510 // Direct methods also have a distinct ABI, so we add a suffix to make them
511 // obvious to tools like debuggers and to elevate incompatible uses into
512 // linker errors.
513 clang::mangleObjCMethodName(OS, includePrefixByte && !useDirectABI,
514 MD->isInstanceMethod(), ClassName, CategoryName,
515 MethodName, useDirectABI);
516}
517
519 raw_ostream &Out) const {
520 SmallString<64> Name;
521 llvm::raw_svector_ostream OS(Name);
522
523 mangleObjCMethodName(MD, OS, /*includePrefixByte=*/false,
524 /*includeCategoryNamespace=*/true);
525 Out << OS.str().size() << OS.str();
526}
527
529 std::unique_ptr<MangleContext> MC;
530 llvm::DataLayout DL;
531
532public:
534 : MC(Ctx.createMangleContext()),
535 DL(Ctx.getTargetInfo().getDataLayoutString()) {}
536
537 bool writeName(const Decl *D, raw_ostream &OS) {
538 // First apply frontend mangling.
539 SmallString<128> FrontendBuf;
540 llvm::raw_svector_ostream FrontendBufOS(FrontendBuf);
541 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
542 if (FD->isDependentContext())
543 return true;
544 if (writeFuncOrVarName(FD, FrontendBufOS))
545 return true;
546 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
547 if (writeFuncOrVarName(VD, FrontendBufOS))
548 return true;
549 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
550 MC->mangleObjCMethodName(MD, OS, /*includePrefixByte=*/false,
551 /*includeCategoryNamespace=*/true);
552 return false;
553 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
554 writeObjCClassName(ID, FrontendBufOS);
555 } else {
556 return true;
557 }
558
559 // Now apply backend mangling.
560 llvm::Mangler::getNameWithPrefix(OS, FrontendBufOS.str(), DL);
561 return false;
562 }
563
564 std::string getName(const Decl *D) {
565 std::string Name;
566 {
567 llvm::raw_string_ostream OS(Name);
568 writeName(D, OS);
569 }
570 return Name;
571 }
572
577
578 static StringRef getClassSymbolPrefix(ObjCKind Kind,
579 const ASTContext &Context) {
580 if (Context.getLangOpts().ObjCRuntime.isGNUFamily())
581 return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_";
582 return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_";
583 }
584
585 std::vector<std::string> getAllManglings(const ObjCContainerDecl *OCD) {
586 StringRef ClassName;
587 if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
588 ClassName = OID->getObjCRuntimeNameAsString();
589 else if (const auto *OID = dyn_cast<ObjCImplementationDecl>(OCD))
590 ClassName = OID->getObjCRuntimeNameAsString();
591
592 if (ClassName.empty())
593 return {};
594
595 auto Mangle = [&](ObjCKind Kind, StringRef ClassName) -> std::string {
596 SmallString<40> Mangled;
597 auto Prefix = getClassSymbolPrefix(Kind, OCD->getASTContext());
598 llvm::Mangler::getNameWithPrefix(Mangled, Prefix + ClassName, DL);
599 return std::string(Mangled);
600 };
601
602 return {
603 Mangle(ObjCClass, ClassName),
604 Mangle(ObjCMetaclass, ClassName),
605 };
606 }
607
608 std::vector<std::string> getAllManglings(const Decl *D) {
609 if (const auto *OCD = dyn_cast<ObjCContainerDecl>(D))
610 return getAllManglings(OCD);
611
613 return {};
614
615 const NamedDecl *ND = cast<NamedDecl>(D);
616
617 ASTContext &Ctx = ND->getASTContext();
618 std::unique_ptr<MangleContext> M(Ctx.createMangleContext());
619
620 std::vector<std::string> Manglings;
621
622 auto hasDefaultCXXMethodCC = [](ASTContext &C, const CXXMethodDecl *MD) {
623 auto DefaultCC = C.getDefaultCallingConvention(/*IsVariadic=*/false,
624 /*IsCXXMethod=*/true);
625 auto CC = MD->getType()->castAs<FunctionProtoType>()->getCallConv();
626 return CC == DefaultCC;
627 };
628
629 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND)) {
630 Manglings.emplace_back(getMangledStructor(CD, Ctor_Base));
631
633 if (!CD->getParent()->isAbstract())
634 Manglings.emplace_back(getMangledStructor(CD, Ctor_Complete));
635
636 if (Ctx.getTargetInfo().getCXXABI().isMicrosoft())
637 if (CD->hasAttr<DLLExportAttr>() && CD->isDefaultConstructor())
638 if (!(hasDefaultCXXMethodCC(Ctx, CD) && CD->getNumParams() == 0))
639 Manglings.emplace_back(getMangledStructor(CD, Ctor_DefaultClosure));
640 } else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND)) {
641 Manglings.emplace_back(getMangledStructor(DD, Dtor_Base));
643 Manglings.emplace_back(getMangledStructor(DD, Dtor_Complete));
644 if (DD->isVirtual())
645 Manglings.emplace_back(getMangledStructor(DD, Dtor_Deleting));
646 }
647 } else if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(ND)) {
648 Manglings.emplace_back(getName(ND));
649 if (MD->isVirtual()) {
650 if (const auto *TIV = Ctx.getVTableContext()->getThunkInfo(MD)) {
651 for (const auto &T : *TIV) {
652 std::string ThunkName;
653 std::string ContextualizedName =
654 getMangledThunk(MD, T, /* ElideOverrideInfo */ false);
655 if (Ctx.useAbbreviatedThunkName(MD, ContextualizedName))
656 ThunkName = getMangledThunk(MD, T, /* ElideOverrideInfo */ true);
657 else
658 ThunkName = ContextualizedName;
659 Manglings.emplace_back(ThunkName);
660 }
661 }
662 }
663 }
664
665 return Manglings;
666 }
667
668private:
669 bool writeFuncOrVarName(const NamedDecl *D, raw_ostream &OS) {
670 if (MC->shouldMangleDeclName(D)) {
671 GlobalDecl GD;
672 if (const auto *CtorD = dyn_cast<CXXConstructorDecl>(D))
673 GD = GlobalDecl(CtorD, Ctor_Complete);
674 else if (const auto *DtorD = dyn_cast<CXXDestructorDecl>(D))
675 GD = GlobalDecl(DtorD, Dtor_Complete);
676 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
677 GD = FD->isReferenceableKernel() ? GlobalDecl(FD) : GlobalDecl(D);
678 } else
679 GD = GlobalDecl(D);
680 MC->mangleName(GD, OS);
681 return false;
682 } else {
683 IdentifierInfo *II = D->getIdentifier();
684 if (!II)
685 return true;
686 OS << II->getName();
687 return false;
688 }
689 }
690
691 void writeObjCClassName(const ObjCInterfaceDecl *D, raw_ostream &OS) {
694 }
695
696 std::string getMangledStructor(const NamedDecl *ND, unsigned StructorType) {
697 std::string FrontendBuf;
698 llvm::raw_string_ostream FOS(FrontendBuf);
699
700 GlobalDecl GD;
701 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND))
702 GD = GlobalDecl(CD, static_cast<CXXCtorType>(StructorType));
703 else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND))
704 GD = GlobalDecl(DD, static_cast<CXXDtorType>(StructorType));
705 MC->mangleName(GD, FOS);
706
707 std::string BackendBuf;
708 llvm::raw_string_ostream BOS(BackendBuf);
709
710 llvm::Mangler::getNameWithPrefix(BOS, FrontendBuf, DL);
711
712 return BackendBuf;
713 }
714
715 std::string getMangledThunk(const CXXMethodDecl *MD, const ThunkInfo &T,
716 bool ElideOverrideInfo) {
717 std::string FrontendBuf;
718 llvm::raw_string_ostream FOS(FrontendBuf);
719
720 MC->mangleThunk(MD, T, ElideOverrideInfo, FOS);
721
722 std::string BackendBuf;
723 llvm::raw_string_ostream BOS(BackendBuf);
724
725 llvm::Mangler::getNameWithPrefix(BOS, FrontendBuf, DL);
726
727 return BackendBuf;
728 }
729};
730
732 : Impl(std::make_unique<Implementation>(Ctx)) {}
733
735
736bool ASTNameGenerator::writeName(const Decl *D, raw_ostream &OS) {
737 return Impl->writeName(D, OS);
738}
739
740std::string ASTNameGenerator::getName(const Decl *D) {
741 return Impl->getName(D);
742}
743
744std::vector<std::string> ASTNameGenerator::getAllManglings(const Decl *D) {
745 return Impl->getAllManglings(D);
746}
Enums/classes describing ABI related information about constructors, destructors and thunks.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static bool hasDefaultCXXMethodCC(ASTContext &Context, const CXXMethodDecl *MD)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
CCMangling
Definition Mangle.cpp:73
@ CCM_Fast
Definition Mangle.cpp:75
@ CCM_Vector
Definition Mangle.cpp:77
@ CCM_Std
Definition Mangle.cpp:78
@ CCM_WasmMainArgcArgv
Definition Mangle.cpp:79
@ CCM_RegCall
Definition Mangle.cpp:76
@ CCM_Other
Definition Mangle.cpp:74
static void emitLLDBAsmLabel(llvm::StringRef label, GlobalDecl GD, llvm::raw_ostream &Out)
Given an LLDB function call label, this function prints the label into Out, together with the structo...
Definition Mangle.cpp:231
static void mangleFunctionBlock(MangleContext &Context, StringRef Outer, const BlockDecl *BD, raw_ostream &Out)
Definition Mangle.cpp:60
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:82
static CCMangling getCallingConvMangling(const ASTContext &Context, const NamedDecl *ND)
Definition Mangle.cpp:90
std::string getName(const Decl *D)
Definition Mangle.cpp:564
std::vector< std::string > getAllManglings(const Decl *D)
Definition Mangle.cpp:608
static StringRef getClassSymbolPrefix(ObjCKind Kind, const ASTContext &Context)
Definition Mangle.cpp:578
bool writeName(const Decl *D, raw_ostream &OS)
Definition Mangle.cpp:537
std::vector< std::string > getAllManglings(const ObjCContainerDecl *OCD)
Definition Mangle.cpp:585
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:854
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
VTableContextBase * getVTableContext()
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
std::string getName(const Decl *D)
Definition Mangle.cpp:740
ASTNameGenerator(ASTContext &Ctx)
Definition Mangle.cpp:731
bool writeName(const Decl *D, raw_ostream &OS)
Writes name for D to OS.
Definition Mangle.cpp:736
std::vector< std::string > getAllManglings(const Decl *D)
Definition Mangle.cpp:744
Attr - This represents one attribute.
Definition Attr.h:46
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4814
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:237
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
Definition Builtins.h:311
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2991
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3174
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1468
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:583
bool hasAttrs() const
Definition DeclBase.h:528
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
DeclContext * getDeclContext()
Definition DeclBase.h:458
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1638
bool hasAttr() const
Definition DeclBase.h:587
Represents a function declaration or definition.
Definition Decl.h:2059
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3269
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3807
bool isReferenceableKernel() const
Definition Decl.cpp:5724
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
CallingConv getCallConv() const
Definition TypeBase.h:4967
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
CXXCtorType getCtorType() const
Definition GlobalDecl.h:117
CXXDtorType getDtorType() const
Definition GlobalDecl.h:122
const Decl * getDecl() const
Definition GlobalDecl.h:115
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
A global _GUID constant.
Definition DeclCXX.h:4451
Parts getParts() const
Get the decomposed parts of this declaration.
Definition DeclCXX.h:4481
MSGuidDeclParts Parts
Definition DeclCXX.h:4453
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:56
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
Definition Mangle.cpp:415
unsigned getBlockId(const BlockDecl *BD, bool Local)
Definition Mangle.h:92
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
Definition Mangle.cpp:397
ASTContext & getASTContext() const
Definition Mangle.h:86
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
Definition Mangle.cpp:380
void mangleObjCMethodName(const ObjCMethodDecl *MD, raw_ostream &OS, bool includePrefixByte=true, bool includeCategoryNamespace=true, bool useDirectABI=false) const
Definition Mangle.cpp:450
virtual bool isUniqueInternalLinkageDecl(const NamedDecl *ND)
Definition Mangle.h:141
bool isTriviallyRecursive(const FunctionDecl *FD)
Return true if FD's body contains a direct call back to the symbol it links as, through an asm label ...
Definition Mangle.cpp:202
bool shouldMangleDeclName(const NamedDecl *D)
Definition Mangle.cpp:129
virtual void mangleMSGuidDecl(const MSGuidDecl *GD, raw_ostream &) const
Definition Mangle.cpp:365
void mangleName(GlobalDecl GD, raw_ostream &)
Definition Mangle.cpp:249
void mangleNameIgnoringAsmLabel(GlobalDecl GD, raw_ostream &)
Definition Mangle.cpp:292
virtual void mangleCXXName(GlobalDecl GD, raw_ostream &)=0
bool shouldMangleDeclNameIgnoringAsmLabel(const NamedDecl *D)
Definition Mangle.cpp:138
virtual bool shouldMangleCXXName(const NamedDecl *D)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Definition Mangle.cpp:406
void mangleObjCMethodNameAsSourceName(const ObjCMethodDecl *MD, raw_ostream &) const
Definition Mangle.cpp:518
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:430
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:954
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Selector getSelector() const
Definition DeclObjC.h:330
bool isInstanceMethod() const
Definition DeclObjC.h:429
ObjCCategoryDecl * getCategory()
If this method is declared or implemented in a category, return that category.
bool isClassMethod() const
Definition DeclObjC.h:437
ObjCInterfaceDecl * getClassInterface()
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
A (possibly-)qualified type.
Definition TypeBase.h:938
void print(llvm::raw_ostream &OS) const
Prints the full selector name (e.g. "foo:bar:").
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Exposes information about the current target.
Definition TargetInfo.h:228
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:497
const char * getUserLabelPrefix() const
Returns the default value of the USER_LABEL_PREFIX macro, which is the prefix given to user symbols b...
Definition TargetInfo.h:925
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool shouldUseMicrosoftCCforMangling() const
Should the Microsoft mangling scheme be used for C Calling Convention.
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
virtual const ThunkInfoVectorTy * getThunkInfo(GlobalDecl GD)
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
Defines the clang::TargetInfo interface.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
Top level wrappers for InstallAPI frontend operations.
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_Complete
Complete object ctor.
Definition ABI.h:25
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
bool isInstanceMethod(const Decl *D)
Definition Attr.h:158
void mangleObjCMethodName(raw_ostream &OS, bool includePrefixByte, bool isInstanceMethod, StringRef ClassName, std::optional< StringRef > CategoryName, StringRef MethodName, bool useDirectABI)
Extract mangling function name from MangleContext such that swift can call it to prepare for ObjCDire...
Definition Mangle.cpp:34
const FunctionProtoType * T
CXXDtorType
C++ destructor types.
Definition ABI.h:34
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
@ Dtor_Deleting
Deleting dtor.
Definition ABI.h:35
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_X86VectorCall
Definition Specifiers.h:287
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
U cast(CodeGen::Address addr)
Definition Address.h:327
static constexpr llvm::StringLiteral FunctionLabelPrefix
Definition Mangle.h:338
uint16_t Part2
...-89ab-...
Definition DeclCXX.h:4430
uint32_t Part1
{01234567-...
Definition DeclCXX.h:4428
uint16_t Part3
...-cdef-...
Definition DeclCXX.h:4432
uint8_t Part4And5[8]
...-0123-456789abcdef}
Definition DeclCXX.h:4434