1 
2 #include "llvm/IR/GlobalVariable.h"
3 #include "llvm/IR/Module.h"
4 #include "llvm/Pass.h"
5 
6 #include "llvm/Support/raw_ostream.h"
7 #include "llvm/Support/Regex.h"
8 
9 using namespace llvm;
10 
11 //#define passLog(M) (errs() << "WeakAliasModuleOverride: " << M << "\n")
12 #define passLog(M) /* nothing */
13 
14 namespace {
15   class WeakAliasModuleOverride : public ModulePass {
16 
17   public:
18     static char ID;
19     WeakAliasModuleOverride() : ModulePass(ID) {
20     }
21 
22     virtual bool runOnModule(Module &M) {
23       const Module::FunctionListType &listFcts = M.getFunctionList();
24       const Module::GlobalListType &listGlobalVars = M.getGlobalList();
25 
26       std::string Asm = M.getModuleInlineAsm();
27 
28       passLog("ASM START\n"
29 	  << Asm
30 	  << "ASM END\n");
31 
32       // Filter out Function symbols
33       for(Module::const_iterator it = listFcts.begin(), end=listFcts.end(); it!= end; ++it)
34       {
35 	if (it->isDeclaration())
36 	  continue;
37 
38 	// Filter out the assembly weak symbol as well as its default value
39         std::string symbolName = it->getName();
40         std::string matchWeak = "(^.weak.* " + symbolName + "\n)";
41         std::string matchAssignement = "(^" + symbolName + " .*=.*\n)";
42 
43         Regex filterWeak(matchWeak, Regex::Newline);
44         Regex filterAssignement(matchAssignement, Regex::Newline);
45 
46         while(filterWeak.match(Asm))
47           Asm = filterWeak.sub("", Asm);
48 
49         while(filterAssignement.match(Asm))
50           Asm = filterAssignement.sub("", Asm);
51       }
52 
53       // Filter out GlobalVariable symbols
54       for(Module::const_global_iterator it = listGlobalVars.begin(), end=listGlobalVars.end(); it!= end; ++it)
55       {
56 	if (! it->hasInitializer())
57 	  continue;
58 
59 	// Filter out the assembly weak symbol as well as its default value
60         std::string symbolName = it->getName();
61         std::string matchWeak = "(^.weak.* " + symbolName + "\n)";
62         std::string matchAssignement = "(^" + symbolName + " .*=.*\n)";
63 
64         Regex filterWeak(matchWeak, Regex::Newline);
65         Regex filterAssignement(matchAssignement, Regex::Newline);
66 
67         while(filterWeak.match(Asm))
68           Asm = filterWeak.sub("", Asm);
69 
70         while(filterAssignement.match(Asm))
71           Asm = filterAssignement.sub("", Asm);
72       }
73 
74       M.setModuleInlineAsm(Asm);
75 
76       passLog("ASM START - registered\n"
77 	  << M.getModuleInlineAsm()
78 	  << "ASM END\n");
79 
80       return true;
81     }
82   };
83 }
84 
85 char WeakAliasModuleOverride::ID = 0;
86 RegisterPass<WeakAliasModuleOverride> WEAK_ALIAS_MODULE_OVERRIDE("weak-alias-module-override", "Fix Weak Alias overrides");
87