Mangler.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. //===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
  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. // Unified name mangler for assembly backends.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Mangler.h"
  13. #include "llvm/ADT/SmallString.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/ADT/Triple.h"
  16. #include "llvm/ADT/Twine.h"
  17. #include "llvm/IR/DataLayout.h"
  18. #include "llvm/IR/DerivedTypes.h"
  19. #include "llvm/IR/Function.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. using namespace llvm;
  23. namespace {
  24. enum ManglerPrefixTy {
  25. Default, ///< Emit default string before each symbol.
  26. Private, ///< Emit "private" prefix before each symbol.
  27. LinkerPrivate ///< Emit "linker private" prefix before each symbol.
  28. };
  29. }
  30. static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName,
  31. ManglerPrefixTy PrefixTy,
  32. const DataLayout &DL, char Prefix) {
  33. SmallString<256> TmpData;
  34. StringRef Name = GVName.toStringRef(TmpData);
  35. assert(!Name.empty() && "getNameWithPrefix requires non-empty name");
  36. // No need to do anything special if the global has the special "do not
  37. // mangle" flag in the name.
  38. if (Name[0] == '\1') {
  39. OS << Name.substr(1);
  40. return;
  41. }
  42. if (DL.doNotMangleLeadingQuestionMark() && Name[0] == '?')
  43. Prefix = '\0';
  44. if (PrefixTy == Private)
  45. OS << DL.getPrivateGlobalPrefix();
  46. else if (PrefixTy == LinkerPrivate)
  47. OS << DL.getLinkerPrivateGlobalPrefix();
  48. if (Prefix != '\0')
  49. OS << Prefix;
  50. // If this is a simple string that doesn't need escaping, just append it.
  51. OS << Name;
  52. }
  53. static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName,
  54. const DataLayout &DL,
  55. ManglerPrefixTy PrefixTy) {
  56. char Prefix = DL.getGlobalPrefix();
  57. return getNameWithPrefixImpl(OS, GVName, PrefixTy, DL, Prefix);
  58. }
  59. void Mangler::getNameWithPrefix(raw_ostream &OS, const Twine &GVName,
  60. const DataLayout &DL) {
  61. return getNameWithPrefixImpl(OS, GVName, DL, Default);
  62. }
  63. void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
  64. const Twine &GVName, const DataLayout &DL) {
  65. raw_svector_ostream OS(OutName);
  66. char Prefix = DL.getGlobalPrefix();
  67. return getNameWithPrefixImpl(OS, GVName, Default, DL, Prefix);
  68. }
  69. static bool hasByteCountSuffix(CallingConv::ID CC) {
  70. switch (CC) {
  71. case CallingConv::X86_FastCall:
  72. case CallingConv::X86_StdCall:
  73. case CallingConv::X86_VectorCall:
  74. return true;
  75. default:
  76. return false;
  77. }
  78. }
  79. /// Microsoft fastcall and stdcall functions require a suffix on their name
  80. /// indicating the number of words of arguments they take.
  81. static void addByteCountSuffix(raw_ostream &OS, const Function *F,
  82. const DataLayout &DL) {
  83. // Calculate arguments size total.
  84. unsigned ArgWords = 0;
  85. const unsigned PtrSize = DL.getPointerSize();
  86. for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
  87. AI != AE; ++AI) {
  88. // 'Dereference' type in case of byval or inalloca parameter attribute.
  89. uint64_t AllocSize = AI->hasPassPointeeByValueCopyAttr() ?
  90. AI->getPassPointeeByValueCopySize(DL) :
  91. DL.getTypeAllocSize(AI->getType());
  92. // Size should be aligned to pointer size.
  93. ArgWords += alignTo(AllocSize, PtrSize);
  94. }
  95. OS << '@' << ArgWords;
  96. }
  97. void Mangler::getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV,
  98. bool CannotUsePrivateLabel) const {
  99. ManglerPrefixTy PrefixTy = Default;
  100. if (GV->hasPrivateLinkage()) {
  101. if (CannotUsePrivateLabel)
  102. PrefixTy = LinkerPrivate;
  103. else
  104. PrefixTy = Private;
  105. }
  106. const DataLayout &DL = GV->getParent()->getDataLayout();
  107. if (!GV->hasName()) {
  108. // Get the ID for the global, assigning a new one if we haven't got one
  109. // already.
  110. unsigned &ID = AnonGlobalIDs[GV];
  111. if (ID == 0)
  112. ID = AnonGlobalIDs.size();
  113. // Must mangle the global into a unique ID.
  114. getNameWithPrefixImpl(OS, "__unnamed_" + Twine(ID), DL, PrefixTy);
  115. return;
  116. }
  117. StringRef Name = GV->getName();
  118. char Prefix = DL.getGlobalPrefix();
  119. // Mangle functions with Microsoft calling conventions specially. Only do
  120. // this mangling for x86_64 vectorcall and 32-bit x86.
  121. const Function *MSFunc = dyn_cast<Function>(GV);
  122. // Don't add byte count suffixes when '\01' or '?' are in the first
  123. // character.
  124. if (Name.startswith("\01") ||
  125. (DL.doNotMangleLeadingQuestionMark() && Name.startswith("?")))
  126. MSFunc = nullptr;
  127. CallingConv::ID CC =
  128. MSFunc ? MSFunc->getCallingConv() : (unsigned)CallingConv::C;
  129. if (!DL.hasMicrosoftFastStdCallMangling() &&
  130. CC != CallingConv::X86_VectorCall)
  131. MSFunc = nullptr;
  132. if (MSFunc) {
  133. if (CC == CallingConv::X86_FastCall)
  134. Prefix = '@'; // fastcall functions have an @ prefix instead of _.
  135. else if (CC == CallingConv::X86_VectorCall)
  136. Prefix = '\0'; // vectorcall functions have no prefix.
  137. }
  138. getNameWithPrefixImpl(OS, Name, PrefixTy, DL, Prefix);
  139. if (!MSFunc)
  140. return;
  141. // If we are supposed to add a microsoft-style suffix for stdcall, fastcall,
  142. // or vectorcall, add it. These functions have a suffix of @N where N is the
  143. // cumulative byte size of all of the parameters to the function in decimal.
  144. if (CC == CallingConv::X86_VectorCall)
  145. OS << '@'; // vectorcall functions use a double @ suffix.
  146. FunctionType *FT = MSFunc->getFunctionType();
  147. if (hasByteCountSuffix(CC) &&
  148. // "Pure" variadic functions do not receive @0 suffix.
  149. (!FT->isVarArg() || FT->getNumParams() == 0 ||
  150. (FT->getNumParams() == 1 && MSFunc->hasStructRetAttr())))
  151. addByteCountSuffix(OS, MSFunc, DL);
  152. }
  153. void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
  154. const GlobalValue *GV,
  155. bool CannotUsePrivateLabel) const {
  156. raw_svector_ostream OS(OutName);
  157. getNameWithPrefix(OS, GV, CannotUsePrivateLabel);
  158. }
  159. // Check if the name needs quotes to be safe for the linker to interpret.
  160. static bool canBeUnquotedInDirective(char C) {
  161. return isAlnum(C) || C == '_' || C == '$' || C == '.' || C == '@';
  162. }
  163. static bool canBeUnquotedInDirective(StringRef Name) {
  164. if (Name.empty())
  165. return false;
  166. // If any of the characters in the string is an unacceptable character, force
  167. // quotes.
  168. for (char C : Name) {
  169. if (!canBeUnquotedInDirective(C))
  170. return false;
  171. }
  172. return true;
  173. }
  174. void llvm::emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV,
  175. const Triple &TT, Mangler &Mangler) {
  176. if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
  177. return;
  178. if (TT.isWindowsMSVCEnvironment())
  179. OS << " /EXPORT:";
  180. else
  181. OS << " -export:";
  182. bool NeedQuotes = GV->hasName() && !canBeUnquotedInDirective(GV->getName());
  183. if (NeedQuotes)
  184. OS << "\"";
  185. if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
  186. std::string Flag;
  187. raw_string_ostream FlagOS(Flag);
  188. Mangler.getNameWithPrefix(FlagOS, GV, false);
  189. FlagOS.flush();
  190. if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
  191. OS << Flag.substr(1);
  192. else
  193. OS << Flag;
  194. } else {
  195. Mangler.getNameWithPrefix(OS, GV, false);
  196. }
  197. if (NeedQuotes)
  198. OS << "\"";
  199. if (!GV->getValueType()->isFunctionTy()) {
  200. if (TT.isWindowsMSVCEnvironment())
  201. OS << ",DATA";
  202. else
  203. OS << ",data";
  204. }
  205. }
  206. void llvm::emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV,
  207. const Triple &T, Mangler &M) {
  208. if (!T.isWindowsMSVCEnvironment())
  209. return;
  210. OS << " /INCLUDE:";
  211. bool NeedQuotes = GV->hasName() && !canBeUnquotedInDirective(GV->getName());
  212. if (NeedQuotes)
  213. OS << "\"";
  214. M.getNameWithPrefix(OS, GV, false);
  215. if (NeedQuotes)
  216. OS << "\"";
  217. }