change Mangler::makeNameProper to return its result in a SmallVector
[oota-llvm.git] / lib / VMCore / Mangler.cpp
1 //===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Unified name mangler for CWriter and assembly backends.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/Mangler.h"
15 #include "llvm/Function.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/raw_ostream.h"
21 using namespace llvm;
22
23 static char HexDigit(int V) {
24   return V < 10 ? V+'0' : V+'A'-10;
25 }
26
27 static void MangleLetter(SmallVectorImpl<char> &OutName, unsigned char C) {
28   OutName.push_back('_');
29   OutName.push_back(HexDigit(C >> 4));
30   OutName.push_back(HexDigit(C & 15));
31   OutName.push_back('_');
32 }
33
34 /// makeNameProper - We don't want identifier names non-C-identifier characters
35 /// in them, so mangle them as appropriate.
36 ///
37 void Mangler::makeNameProper(SmallVectorImpl<char> &OutName,
38                              const Twine &TheName,
39                              ManglerPrefixTy PrefixTy) {
40   SmallString<256> TmpData;
41   TheName.toVector(TmpData);
42   StringRef X = TmpData.str();
43   assert(!X.empty() && "Cannot mangle empty strings");
44   
45   if (!UseQuotes) {
46     // If X does not start with (char)1, add the prefix.
47     StringRef::iterator I = X.begin();
48     if (*I == 1) {
49       ++I;  // Skip over the no-prefix marker.
50     } else {
51       if (PrefixTy == Mangler::Private)
52         OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
53       else if (PrefixTy == Mangler::LinkerPrivate)
54         OutName.append(LinkerPrivatePrefix,
55                        LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));
56       OutName.append(Prefix, Prefix+strlen(Prefix));
57     }
58     
59     // Mangle the first letter specially, don't allow numbers unless the target
60     // explicitly allows them.
61     if (!SymbolsCanStartWithDigit && *I >= '0' && *I <= '9')
62       MangleLetter(OutName, *I++);
63
64     for (StringRef::iterator E = X.end(); I != E; ++I) {
65       if (!isCharAcceptable(*I))
66         MangleLetter(OutName, *I);
67       else
68         OutName.push_back(*I);
69     }
70     return;
71   }
72
73   bool NeedPrefix = true;
74   bool NeedQuotes = false;
75   StringRef::iterator I = X.begin();
76   if (*I == 1) {
77     NeedPrefix = false;
78     ++I;  // Skip over the marker.
79   }
80
81   // If the first character is a number, we need quotes.
82   if (*I >= '0' && *I <= '9')
83     NeedQuotes = true;
84     
85   // Do an initial scan of the string, checking to see if we need quotes or
86   // to escape a '"' or not.
87   if (!NeedQuotes)
88     for (StringRef::iterator E = X.end(); I != E; ++I)
89       if (!isCharAcceptable(*I)) {
90         NeedQuotes = true;
91         break;
92       }
93     
94   // In the common case, we don't need quotes.  Handle this quickly.
95   if (!NeedQuotes) {
96     if (!NeedPrefix) {
97       OutName.append(X.begin()+1, X.end());   // Strip off the \001.
98       return;
99     }
100
101     if (PrefixTy == Mangler::Private)
102       OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
103     else if (PrefixTy == Mangler::LinkerPrivate)
104       OutName.append(LinkerPrivatePrefix,
105                      LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));
106     
107     if (Prefix[0] == 0)
108       ; // Common noop, no prefix.
109     else if (Prefix[1] == 0)
110       OutName.push_back(Prefix[0]);  // Common, one character prefix.
111     else
112       OutName.append(Prefix, Prefix+strlen(Prefix)); // Arbitrary prefix.
113     OutName.append(X.begin(), X.end());
114     return;
115   }
116
117   // Add leading quote.
118   OutName.push_back('"');
119   
120   // Add prefixes unless disabled.
121   if (NeedPrefix) {
122     if (PrefixTy == Mangler::Private)
123       OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
124     else if (PrefixTy == Mangler::LinkerPrivate)
125       OutName.append(LinkerPrivatePrefix,
126                      LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));
127     OutName.append(Prefix, Prefix+strlen(Prefix));
128   }
129   
130   // Add the piece that we already scanned through.
131   OutName.append(X.begin(), I);
132   
133   // Otherwise, construct the string the expensive way.
134   for (StringRef::iterator E = X.end(); I != E; ++I) {
135     if (*I == '"') {
136       const char *Quote = "_QQ_";
137       OutName.append(Quote, Quote+4);
138     } else if (*I == '\n') {
139       const char *Newline = "_NL_";
140       OutName.append(Newline, Newline+4);
141     } else
142       OutName.push_back(*I);
143   }
144
145   // Add trailing quote.
146   OutName.push_back('"');
147 }
148
149 /// getMangledName - Returns the mangled name of V, an LLVM Value,
150 /// in the current module.  If 'Suffix' is specified, the name ends with the
151 /// specified suffix.  If 'ForcePrivate' is specified, the label is specified
152 /// to have a private label prefix.
153 ///
154 std::string Mangler::getMangledName(const GlobalValue *GV, const char *Suffix,
155                                     bool ForcePrivate) {
156   assert((!isa<Function>(GV) || !cast<Function>(GV)->isIntrinsic()) &&
157          "Intrinsic functions cannot be mangled by Mangler");
158
159   ManglerPrefixTy PrefixTy =
160     (GV->hasPrivateLinkage() || ForcePrivate) ? Mangler::Private :
161       GV->hasLinkerPrivateLinkage() ? Mangler::LinkerPrivate : Mangler::Default;
162
163   SmallString<128> Result;
164   if (GV->hasName()) {
165     makeNameProper(Result, GV->getNameStr() + Suffix, PrefixTy);
166     return Result.str().str();
167   }
168   
169   // Get the ID for the global, assigning a new one if we haven't got one
170   // already.
171   unsigned &ID = AnonGlobalIDs[GV];
172   if (ID == 0) ID = NextAnonGlobalID++;
173   
174   // Must mangle the global into a unique ID.
175   makeNameProper(Result, "__unnamed_" + utostr(ID) + Suffix, PrefixTy);
176   return Result.str().str();
177 }
178
179
180 /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
181 /// and the specified global variable's name.  If the global variable doesn't
182 /// have a name, this fills in a unique name for the global.
183 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
184                                 const GlobalValue *GV,
185                                 bool isImplicitlyPrivate) {
186    
187   // If the global is anonymous or not led with \1, then add the appropriate
188   // prefix.
189   if (!GV->hasName() || GV->getName()[0] != '\1') {
190     if (GV->hasPrivateLinkage() || isImplicitlyPrivate)
191       OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
192     else if (GV->hasLinkerPrivateLinkage())
193       OutName.append(LinkerPrivatePrefix,
194                      LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));;
195     OutName.append(Prefix, Prefix+strlen(Prefix));
196   }
197
198   // If the global has a name, just append it now.
199   if (GV->hasName()) {
200     StringRef Name = GV->getName();
201     
202     // Strip off the prefix marker if present.
203     if (Name[0] != '\1')
204       OutName.append(Name.begin(), Name.end());
205     else
206       OutName.append(Name.begin()+1, Name.end());
207     return;
208   }
209   
210   // If the global variable doesn't have a name, return a unique name for the
211   // global based on a numbering.
212   
213   // Get the ID for the global, assigning a new one if we haven't got one
214   // already.
215   unsigned &ID = AnonGlobalIDs[GV];
216   if (ID == 0) ID = NextAnonGlobalID++;
217   
218   // Must mangle the global into a unique ID.
219   raw_svector_ostream(OutName) << "__unnamed_" << ID;
220 }
221
222
223 Mangler::Mangler(Module &M, const char *prefix, const char *privatePrefix,
224                  const char *linkerPrivatePrefix)
225   : Prefix(prefix), PrivatePrefix(privatePrefix),
226     LinkerPrivatePrefix(linkerPrivatePrefix), UseQuotes(false),
227     SymbolsCanStartWithDigit(false), NextAnonGlobalID(1) {
228   std::fill(AcceptableChars, array_endof(AcceptableChars), 0);
229
230   // Letters and numbers are acceptable.
231   for (unsigned char X = 'a'; X <= 'z'; ++X)
232     markCharAcceptable(X);
233   for (unsigned char X = 'A'; X <= 'Z'; ++X)
234     markCharAcceptable(X);
235   for (unsigned char X = '0'; X <= '9'; ++X)
236     markCharAcceptable(X);
237   
238   // These chars are acceptable.
239   markCharAcceptable('_');
240   markCharAcceptable('$');
241   markCharAcceptable('.');
242   markCharAcceptable('@');
243 }