OSDN Git Service

Remove always true flag.
[android-x86/external-llvm.git] / lib / Target / 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 assembly backends.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/Mangler.h"
15 #include "llvm/ADT/SmallString.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/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
25
26 static bool isAcceptableChar(char C, bool AllowPeriod) {
27   if ((C < 'a' || C > 'z') &&
28       (C < 'A' || C > 'Z') &&
29       (C < '0' || C > '9') &&
30       C != '_' && C != '$' && C != '@' &&
31       !(AllowPeriod && C == '.') &&
32       !(C & 0x80))
33     return false;
34   return true;
35 }
36
37 static char HexDigit(int V) {
38   return V < 10 ? V+'0' : V+'A'-10;
39 }
40
41 static void MangleLetter(SmallVectorImpl<char> &OutName, unsigned char C) {
42   OutName.push_back('_');
43   OutName.push_back(HexDigit(C >> 4));
44   OutName.push_back(HexDigit(C & 15));
45   OutName.push_back('_');
46 }
47
48 /// NameNeedsEscaping - Return true if the identifier \p Str needs quotes
49 /// for this assembler.
50 static bool NameNeedsEscaping(StringRef Str, const MCAsmInfo *MAI) {
51   assert(!Str.empty() && "Cannot create an empty MCSymbol");
52   
53   // If the first character is a number and the target does not allow this, we
54   // need quotes.
55   if (!MAI->doesAllowNameToStartWithDigit() && Str[0] >= '0' && Str[0] <= '9')
56     return true;
57   
58   // If any of the characters in the string is an unacceptable character, force
59   // quotes.
60   bool AllowPeriod = MAI->doesAllowPeriodsInName();
61   for (unsigned i = 0, e = Str.size(); i != e; ++i)
62     if (!isAcceptableChar(Str[i], AllowPeriod))
63       return true;
64   return false;
65 }
66
67 /// appendMangledName - Add the specified string in mangled form if it uses
68 /// any unusual characters.
69 static void appendMangledName(SmallVectorImpl<char> &OutName, StringRef Str,
70                               const MCAsmInfo *MAI) {
71   // The first character is not allowed to be a number unless the target
72   // explicitly allows it.
73   if (!MAI->doesAllowNameToStartWithDigit() && Str[0] >= '0' && Str[0] <= '9') {
74     MangleLetter(OutName, Str[0]);
75     Str = Str.substr(1);
76   }
77
78   bool AllowPeriod = MAI->doesAllowPeriodsInName();
79   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
80     if (!isAcceptableChar(Str[i], AllowPeriod))
81       MangleLetter(OutName, Str[i]);
82     else
83       OutName.push_back(Str[i]);
84   }
85 }
86
87
88 /// appendMangledQuotedName - On systems that support quoted symbols, we still
89 /// have to escape some (obscure) characters like " and \n which would break the
90 /// assembler's lexing.
91 static void appendMangledQuotedName(SmallVectorImpl<char> &OutName,
92                                    StringRef Str) {
93   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
94     if (Str[i] == '"' || Str[i] == '\n')
95       MangleLetter(OutName, Str[i]);
96     else
97       OutName.push_back(Str[i]);
98   }
99 }
100
101
102 /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
103 /// and the specified name as the global variable name.  GVName must not be
104 /// empty.
105 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
106                                 const Twine &GVName, ManglerPrefixTy PrefixTy,
107                                 bool UseGlobalPrefix) {
108   SmallString<256> TmpData;
109   StringRef Name = GVName.toStringRef(TmpData);
110   assert(!Name.empty() && "getNameWithPrefix requires non-empty name");
111   
112   const MCAsmInfo *MAI = TM->getMCAsmInfo();
113   
114   // If the global name is not led with \1, add the appropriate prefixes.
115   if (Name[0] == '\1') {
116     Name = Name.substr(1);
117   } else {
118     if (PrefixTy == Mangler::Private) {
119       const char *Prefix = MAI->getPrivateGlobalPrefix();
120       OutName.append(Prefix, Prefix+strlen(Prefix));
121     } else if (PrefixTy == Mangler::LinkerPrivate) {
122       const char *Prefix = MAI->getLinkerPrivateGlobalPrefix();
123       OutName.append(Prefix, Prefix+strlen(Prefix));
124     }
125
126     if (UseGlobalPrefix) {
127       const char *Prefix = MAI->getGlobalPrefix();
128       if (Prefix[0] == 0)
129         ; // Common noop, no prefix.
130       else if (Prefix[1] == 0)
131         OutName.push_back(Prefix[0]);  // Common, one character prefix.
132       else
133         // Arbitrary length prefix.
134         OutName.append(Prefix, Prefix+strlen(Prefix));
135     }
136   }
137   
138   // If this is a simple string that doesn't need escaping, just append it.
139   if (!NameNeedsEscaping(Name, MAI) ||
140       // If quotes are supported, they can be used unless the string contains
141       // a quote or newline.
142       (MAI->doesAllowQuotesInName() &&
143        Name.find_first_of("\n\"") == StringRef::npos)) {
144     OutName.append(Name.begin(), Name.end());
145     return;
146   }
147   
148   // On systems that do not allow quoted names, we need to mangle most
149   // strange characters.
150   if (!MAI->doesAllowQuotesInName())
151     return appendMangledName(OutName, Name, MAI);
152   
153   // Okay, the system allows quoted strings.  We can quote most anything, the
154   // only characters that need escaping are " and \n.
155   assert(Name.find_first_of("\n\"") != StringRef::npos);
156   return appendMangledQuotedName(OutName, Name);
157 }
158
159 /// AddFastCallStdCallSuffix - Microsoft fastcall and stdcall functions require
160 /// a suffix on their name indicating the number of words of arguments they
161 /// take.
162 static void AddFastCallStdCallSuffix(SmallVectorImpl<char> &OutName,
163                                      const Function *F, const DataLayout &TD) {
164   // Calculate arguments size total.
165   unsigned ArgWords = 0;
166   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
167        AI != AE; ++AI) {
168     Type *Ty = AI->getType();
169     // 'Dereference' type in case of byval parameter attribute
170     if (AI->hasByValAttr())
171       Ty = cast<PointerType>(Ty)->getElementType();
172     // Size should be aligned to DWORD boundary
173     ArgWords += ((TD.getTypeAllocSize(Ty) + 3)/4)*4;
174   }
175   
176   raw_svector_ostream(OutName) << '@' << ArgWords;
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, bool isImplicitlyPrivate,
185                                 bool UseGlobalPrefix) {
186   ManglerPrefixTy PrefixTy = Mangler::Default;
187   if (GV->hasPrivateLinkage() || isImplicitlyPrivate)
188     PrefixTy = Mangler::Private;
189   else if (GV->hasLinkerPrivateLinkage() || GV->hasLinkerPrivateWeakLinkage())
190     PrefixTy = Mangler::LinkerPrivate;
191   
192   // If this global has a name, handle it simply.
193   if (GV->hasName()) {
194     StringRef Name = GV->getName();
195     getNameWithPrefix(OutName, Name, PrefixTy, UseGlobalPrefix);
196     // No need to do anything else if the global has the special "do not mangle"
197     // flag in the name.
198     if (Name[0] == 1)
199       return;
200   } else {
201     // Get the ID for the global, assigning a new one if we haven't got one
202     // already.
203     unsigned &ID = AnonGlobalIDs[GV];
204     if (ID == 0) ID = NextAnonGlobalID++;
205   
206     // Must mangle the global into a unique ID.
207     getNameWithPrefix(OutName, "__unnamed_" + Twine(ID), PrefixTy,
208                       UseGlobalPrefix);
209   }
210   
211   // If we are supposed to add a microsoft-style suffix for stdcall/fastcall,
212   // add it.
213   if (TM->getMCAsmInfo()->hasMicrosoftFastStdCallMangling()) {
214     if (const Function *F = dyn_cast<Function>(GV)) {
215       CallingConv::ID CC = F->getCallingConv();
216     
217       // fastcall functions need to start with @.
218       // FIXME: This logic seems unlikely to be right.
219       if (CC == CallingConv::X86_FastCall) {
220         if (OutName[0] == '_')
221           OutName[0] = '@';
222         else
223           OutName.insert(OutName.begin(), '@');
224       }
225     
226       // fastcall and stdcall functions usually need @42 at the end to specify
227       // the argument info.
228       FunctionType *FT = F->getFunctionType();
229       if ((CC == CallingConv::X86_FastCall || CC == CallingConv::X86_StdCall) &&
230           // "Pure" variadic functions do not receive @0 suffix.
231           (!FT->isVarArg() || FT->getNumParams() == 0 ||
232            (FT->getNumParams() == 1 && F->hasStructRetAttr())))
233         AddFastCallStdCallSuffix(OutName, F, *TM->getDataLayout());
234     }
235   }
236 }