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