1 //===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
3 // Unified name mangler for CWriter and assembly backends.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Support/Mangler.h"
8 #include "llvm/Module.h"
10 #include "Support/StringExtras.h"
12 /// makeNameProper - We don't want identifier names with ., space, or
13 /// - in them, so we mangle these characters into the strings "d_",
14 /// "s_", and "D_", respectively.
16 std::string Mangler::makeNameProper(const std::string &x) {
18 for (std::string::const_iterator sI = x.begin(), sEnd = x.end();
21 case '.': tmp += "d_"; break;
22 case ' ': tmp += "s_"; break;
23 case '-': tmp += "D_"; break;
29 std::string Mangler::getValueName(const Value *V) {
30 // Check to see whether we've already named V.
31 ValueMap::iterator VI = Memo.find(V);
32 if (VI != Memo.end()) {
33 return VI->second; // Return the old name for V.
37 if (V->hasName()) { // Print out the label if it exists...
38 // Name mangling occurs as follows:
39 // - If V is not a global, mangling always occurs.
40 // - Otherwise, mangling occurs when any of the following are true:
41 // 1) V has internal linkage
42 // 2) V's name would collide if it is not mangled.
44 const GlobalValue* gv = dyn_cast<GlobalValue>(V);
45 if (gv && !gv->hasInternalLinkage() && !MangledGlobals.count(gv)) {
46 name = makeNameProper(gv->getName());
47 if (AddUnderscorePrefix) name = "_" + name;
49 // Non-global, or global with internal linkage / colliding name
51 name = "l" + utostr(V->getType()->getUniqueID()) + "_" +
52 makeNameProper(V->getName());
55 name = "ltmp_" + utostr(Count++) + "_"
56 + utostr(V->getType()->getUniqueID());
63 Mangler::Mangler(Module &m, bool addUnderscorePrefix)
64 : M(m), AddUnderscorePrefix(addUnderscorePrefix) {
65 // Calculate which global values have names that will collide when we throw
66 // away type information.
67 std::set<std::string> FoundNames;
68 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
69 if (I->hasName()) // If the global has a name...
70 if (FoundNames.count(I->getName())) // And the name is already used
71 MangledGlobals.insert(I); // Mangle the name
73 FoundNames.insert(I->getName()); // Otherwise, keep track of name
75 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
76 if (I->hasName()) // If the global has a name...
77 if (FoundNames.count(I->getName())) // And the name is already used
78 MangledGlobals.insert(I); // Mangle the name
80 FoundNames.insert(I->getName()); // Otherwise, keep track of name