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