- Replace use of std::map<std::string, ..> with StringMap. Replace use of std::map...
[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/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 using namespace llvm;
21
22 static char HexDigit(int V) {
23   return V < 10 ? V+'0' : V+'A'-10;
24 }
25
26 static std::string MangleLetter(unsigned char C) {
27   char Result[] = { '_', HexDigit(C >> 4), HexDigit(C & 15), '_', 0 };
28   return Result;
29 }
30
31 /// makeNameProper - We don't want identifier names non-C-identifier characters
32 /// in them, so mangle them as appropriate.
33 ///
34 std::string Mangler::makeNameProper(const std::string &X, const char *Prefix) {
35   std::string Result;
36   if (X.empty()) return X;  // Empty names are uniqued by the caller.
37   
38   // If PreserveAsmNames is set, names with asm identifiers are not modified. 
39   if (PreserveAsmNames && X[0] == 1)
40     return X;
41   
42   if (!UseQuotes) {
43     // If X does not start with (char)1, add the prefix.
44     std::string::const_iterator I = X.begin();
45     if (*I != 1)
46       Result = Prefix;
47     else
48       ++I;  // Skip over the marker.
49     
50     // Mangle the first letter specially, don't allow numbers.
51     if (*I >= '0' && *I <= '9')
52       Result += MangleLetter(*I++);
53
54     for (std::string::const_iterator E = X.end(); I != E; ++I) {
55       if (!isCharAcceptable(*I))
56         Result += MangleLetter(*I);
57       else
58         Result += *I;
59     }
60   } else {
61     bool NeedsQuotes = false;
62     
63     std::string::const_iterator I = X.begin();
64     if (*I == 1)
65       ++I;  // Skip over the marker.
66
67     // If the first character is a number, we need quotes.
68     if (*I >= '0' && *I <= '9')
69       NeedsQuotes = true;
70     
71     // Do an initial scan of the string, checking to see if we need quotes or
72     // to escape a '"' or not.
73     if (!NeedsQuotes)
74       for (std::string::const_iterator E = X.end(); I != E; ++I)
75         if (!isCharAcceptable(*I)) {
76           NeedsQuotes = true;
77           break;
78         }
79     
80     // In the common case, we don't need quotes.  Handle this quickly.
81     if (!NeedsQuotes) {
82       if (*X.begin() != 1)
83         return Prefix+X;
84       else
85         return X.substr(1);
86     }
87     
88     // Otherwise, construct the string the expensive way.
89     I = X.begin();
90     
91     // If X does not start with (char)1, add the prefix.
92     if (*I != 1)
93       Result = Prefix;
94     else
95       ++I;   // Skip the marker if present.
96       
97     for (std::string::const_iterator E = X.end(); I != E; ++I) {
98       if (*I == '"')
99         Result += "_QQ_";
100       else if (*I == '\n')
101         Result += "_NL_";
102       else
103         Result += *I;
104     }
105     Result = '"' + Result + '"';
106   }
107   return Result;
108 }
109
110 /// getTypeID - Return a unique ID for the specified LLVM type.
111 ///
112 unsigned Mangler::getTypeID(const Type *Ty) {
113   unsigned &E = TypeMap[Ty];
114   if (E == 0) E = ++TypeCounter;
115   return E;
116 }
117
118 std::string Mangler::getValueName(const Value *V) {
119   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
120     return getValueName(GV);
121   
122   std::string &Name = Memo[V];
123   if (!Name.empty())
124     return Name;       // Return the already-computed name for V.
125   
126   // Always mangle local names.
127   Name = "ltmp_" + utostr(Count++) + "_" + utostr(getTypeID(V->getType()));
128   return Name;
129 }
130
131
132 std::string Mangler::getValueName(const GlobalValue *GV, const char * Suffix) {
133   // Check to see whether we've already named V.
134   std::string &Name = Memo[GV];
135   if (!Name.empty())
136     return Name;       // Return the already-computed name for V.
137
138   // Name mangling occurs as follows:
139   // - If V is an intrinsic function, do not change name at all
140   // - Otherwise, mangling occurs if global collides with existing name.
141   if (isa<Function>(GV) && cast<Function>(GV)->isIntrinsic()) {
142     Name = GV->getNameStart(); // Is an intrinsic function
143   } else if (!GV->hasName()) {
144     // Must mangle the global into a unique ID.
145     unsigned TypeUniqueID = getTypeID(GV->getType());
146     static unsigned GlobalID = 0;
147     Name = "__unnamed_" + utostr(TypeUniqueID) + "_" + utostr(GlobalID++);
148   } else if (!MangledGlobals.count(GV)) {
149     Name = makeNameProper(GV->getName() + Suffix, Prefix);
150   } else {
151     unsigned TypeUniqueID = getTypeID(GV->getType());
152     Name = "l" + utostr(TypeUniqueID) + "_" + makeNameProper(GV->getName());
153   }
154
155   return Name;
156 }
157
158 static void InsertName(GlobalValue *GV, StringMap<GlobalValue*> &Names,
159                        SmallPtrSet<const GlobalValue*, 16> &MangledGlobals) {
160   if (!GV->hasName())   // We must mangle unnamed globals.
161     return;
162
163   // Figure out if this is already used.
164   GlobalValue *&ExistingValue = Names[GV->getNameStart()];
165   if (!ExistingValue) {
166     ExistingValue = GV;
167     return;
168   }
169
170   // If GV is external but the existing one is static, mangle the existing one
171   if ((GV->hasExternalLinkage() || GV->hasDLLImportLinkage()) &&
172       !(ExistingValue->hasExternalLinkage()
173         || ExistingValue->hasDLLImportLinkage())) {
174     MangledGlobals.insert(ExistingValue);
175     ExistingValue = GV;
176   } else if ((GV->hasExternalLinkage() ||
177               GV->hasDLLImportLinkage()) &&
178              (ExistingValue->hasExternalLinkage() ||
179               ExistingValue->hasDLLImportLinkage()) &&
180              GV->isDeclaration() &&
181              ExistingValue->isDeclaration()) {
182     // If the two globals both have external inkage, and are both external,
183     // don't mangle either of them, we just have some silly type mismatch.
184   } else {
185     // Otherwise, mangle GV
186     MangledGlobals.insert(GV);
187   }
188 }
189
190
191 Mangler::Mangler(Module &M, const char *prefix)
192   : Prefix(prefix), UseQuotes(false), PreserveAsmNames(false),
193     Count(0), TypeCounter(0) {
194   std::fill(AcceptableChars, array_endof(AcceptableChars), 0);
195
196   // Letters and numbers are acceptable.
197   for (unsigned char X = 'a'; X <= 'z'; ++X)
198     markCharAcceptable(X);
199   for (unsigned char X = 'A'; X <= 'Z'; ++X)
200     markCharAcceptable(X);
201   for (unsigned char X = '0'; X <= '9'; ++X)
202     markCharAcceptable(X);
203   
204   // These chars are acceptable.
205   markCharAcceptable('_');
206   markCharAcceptable('$');
207   markCharAcceptable('.');
208     
209   // Calculate which global values have names that will collide when we throw
210   // away type information.
211   StringMap<GlobalValue*> Names;
212   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
213     InsertName(I, Names, MangledGlobals);
214   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
215        I != E; ++I)
216     InsertName(I, Names, MangledGlobals);
217 }