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