LLVM  10.0.0svn
Mangler.cpp
Go to the documentation of this file.
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"
22 using namespace llvm;
23 
24 namespace {
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 
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)
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 
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 
69  const DataLayout &DL) {
70  return getNameWithPrefixImpl(OS, GVName, DL, Default);
71 }
72 
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 
81  switch (CC) {
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.
93 static void addByteCountSuffix(raw_ostream &OS, const Function *F,
94  const DataLayout &DL) {
95  // Calculate arguments size total.
96  unsigned ArgWords = 0;
97  for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
98  AI != AE; ++AI) {
99  Type *Ty = AI->getType();
100  // 'Dereference' type in case of byval or inalloca parameter attribute.
101  if (AI->hasByValOrInAllocaAttr())
102  Ty = cast<PointerType>(Ty)->getElementType();
103  // Size should be aligned to pointer size.
104  unsigned PtrSize = DL.getPointerSize();
105  ArgWords += alignTo(DL.getTypeAllocSize(Ty), PtrSize);
106  }
107 
108  OS << '@' << ArgWords;
109 }
110 
112  bool CannotUsePrivateLabel) const {
113  ManglerPrefixTy PrefixTy = Default;
114  if (GV->hasPrivateLinkage()) {
115  if (CannotUsePrivateLabel)
116  PrefixTy = LinkerPrivate;
117  else
118  PrefixTy = Private;
119  }
120 
121  const DataLayout &DL = GV->getParent()->getDataLayout();
122  if (!GV->hasName()) {
123  // Get the ID for the global, assigning a new one if we haven't got one
124  // already.
125  unsigned &ID = AnonGlobalIDs[GV];
126  if (ID == 0)
127  ID = AnonGlobalIDs.size();
128 
129  // Must mangle the global into a unique ID.
130  getNameWithPrefixImpl(OS, "__unnamed_" + Twine(ID), DL, PrefixTy);
131  return;
132  }
133 
134  StringRef Name = GV->getName();
135  char Prefix = DL.getGlobalPrefix();
136 
137  // Mangle functions with Microsoft calling conventions specially. Only do
138  // this mangling for x86_64 vectorcall and 32-bit x86.
139  const Function *MSFunc = dyn_cast<Function>(GV);
140 
141  // Don't add byte count suffixes when '\01' or '?' are in the first
142  // character.
143  if (Name.startswith("\01") ||
144  (DL.doNotMangleLeadingQuestionMark() && Name.startswith("?")))
145  MSFunc = nullptr;
146 
147  CallingConv::ID CC =
148  MSFunc ? MSFunc->getCallingConv() : (unsigned)CallingConv::C;
151  MSFunc = nullptr;
152  if (MSFunc) {
153  if (CC == CallingConv::X86_FastCall)
154  Prefix = '@'; // fastcall functions have an @ prefix instead of _.
155  else if (CC == CallingConv::X86_VectorCall)
156  Prefix = '\0'; // vectorcall functions have no prefix.
157  }
158 
159  getNameWithPrefixImpl(OS, Name, PrefixTy, DL, Prefix);
160 
161  if (!MSFunc)
162  return;
163 
164  // If we are supposed to add a microsoft-style suffix for stdcall, fastcall,
165  // or vectorcall, add it. These functions have a suffix of @N where N is the
166  // cumulative byte size of all of the parameters to the function in decimal.
167  if (CC == CallingConv::X86_VectorCall)
168  OS << '@'; // vectorcall functions use a double @ suffix.
169  FunctionType *FT = MSFunc->getFunctionType();
170  if (hasByteCountSuffix(CC) &&
171  // "Pure" variadic functions do not receive @0 suffix.
172  (!FT->isVarArg() || FT->getNumParams() == 0 ||
173  (FT->getNumParams() == 1 && MSFunc->hasStructRetAttr())))
174  addByteCountSuffix(OS, MSFunc, DL);
175 }
176 
178  const GlobalValue *GV,
179  bool CannotUsePrivateLabel) const {
180  raw_svector_ostream OS(OutName);
181  getNameWithPrefix(OS, GV, CannotUsePrivateLabel);
182 }
183 
185  const Triple &TT, Mangler &Mangler) {
186  if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
187  return;
188 
189  if (TT.isWindowsMSVCEnvironment())
190  OS << " /EXPORT:";
191  else
192  OS << " -export:";
193 
195  std::string Flag;
196  raw_string_ostream FlagOS(Flag);
197  Mangler.getNameWithPrefix(FlagOS, GV, false);
198  FlagOS.flush();
199  if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
200  OS << Flag.substr(1);
201  else
202  OS << Flag;
203  } else {
204  Mangler.getNameWithPrefix(OS, GV, false);
205  }
206 
207  if (!GV->getValueType()->isFunctionTy()) {
208  if (TT.isWindowsMSVCEnvironment())
209  OS << ",DATA";
210  else
211  OS << ",data";
212  }
213 }
214 
216  const Triple &T, Mangler &M) {
217  if (!T.isWindowsMSVCEnvironment())
218  return;
219 
220  OS << " /INCLUDE:";
221  M.getNameWithPrefix(OS, GV, false);
222 }
223 
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
bool hasDLLExportStorageClass() const
Definition: GlobalValue.h:268
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
bool hasPrivateLinkage() const
Definition: GlobalValue.h:444
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This class represents lattice values for constants.
Definition: AllocatorList.h:23
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:317
static void addByteCountSuffix(raw_ostream &OS, const Function *F, const DataLayout &DL)
Microsoft fastcall and stdcall functions require a suffix on their name indicating the number of word...
Definition: Mangler.cpp:93
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:455
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:530
arg_iterator arg_end()
Definition: Function.h:704
F(f)
char getGlobalPrefix() const
Definition: DataLayout.h:303
bool isWindowsCygwinEnvironment() const
Definition: Triple.h:561
StringRef getLinkerPrivateGlobalPrefix() const
Definition: DataLayout.h:297
bool hasStructRetAttr() const
Determine if the function returns a structure through first or second pointer argument.
Definition: Function.h:600
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:578
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
Class to represent function types.
Definition: DerivedTypes.h:103
bool isVarArg() const
Definition: DerivedTypes.h:123
bool isWindowsGNUEnvironment() const
Definition: Triple.h:565
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:131
bool hasName() const
Definition: Value.h:251
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
X86_FastCall - &#39;fast&#39; analog of X86_StdCall.
Definition: CallingConv.h:91
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:651
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:184
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
Definition: CallingConv.h:157
arg_iterator arg_begin()
Definition: Function.h:695
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
ManglerPrefixTy
Definition: Mangler.cpp:25
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:212
Module.h This file contains the declarations for the Module class.
bool hasMicrosoftFastStdCallMangling() const
Definition: DataLayout.h:285
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:163
static bool hasByteCountSuffix(CallingConv::ID CC)
Definition: Mangler.cpp:80
static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName, ManglerPrefixTy PrefixTy, const DataLayout &DL, char Prefix)
Definition: Mangler.cpp:32
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:470
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:126
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:214
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
Definition: CallingConv.h:86
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Type * getValueType() const
Definition: GlobalValue.h:279
void emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &T, Mangler &M)
Definition: Mangler.cpp:215
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:503
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:111
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
bool isWindowsMSVCEnvironment() const
Checks if the environment could be MSVC.
Definition: Triple.h:548
bool doNotMangleLeadingQuestionMark() const
Returns true if symbols with leading question marks should not receive IR mangling.
Definition: DataLayout.h:291