Mangle.cpp 16 KB

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