* Disambiguate symbols before we start splitting module by functions
[oota-llvm.git] / tools / bugpoint / CodeGeneratorBug.cpp
1 //===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===//
2 //
3 // This file implements program code generation debugging support.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "BugDriver.h"
8 #include "SystemUtils.h"
9 #include "ListReducer.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/GlobalValue.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/iOther.h"
16 #include "llvm/Module.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Support/Mangler.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Transforms/Utils/Linker.h"
23 #include "Support/Statistic.h"
24 #include "Support/StringExtras.h"
25 #include <algorithm>
26 #include <set>
27
28 class ReduceMisCodegenFunctions : public ListReducer<Function*> {
29   BugDriver &BD;
30 public:
31   ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}
32
33   virtual TestResult doTest(std::vector<Function*> &Prefix,
34                             std::vector<Function*> &Suffix) {
35     if (!Prefix.empty() && TestFuncs(Prefix))
36       return KeepPrefix;
37     if (!Suffix.empty() && TestFuncs(Suffix))
38       return KeepSuffix;
39     return NoFailure;
40   }
41   
42   bool TestFuncs(const std::vector<Function*> &CodegenTest,
43                  bool KeepFiles = false);
44 };
45
46
47 bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
48                                           bool KeepFiles)
49 {
50   DEBUG(std::cerr << "Test functions are:\n");
51   for (std::vector<Function*>::const_iterator I = Funcs.begin(),E = Funcs.end();
52        I != E; ++I)
53     DEBUG(std::cerr << "\t" << (*I)->getName() << "\n");
54
55   // Clone the module for the two halves of the program we want.
56   Module *SafeModule = CloneModule(BD.Program);
57
58   // Make sure functions & globals are all external so that linkage
59   // between the two modules will work.
60   for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)
61     I->setLinkage(GlobalValue::ExternalLinkage);
62   for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)
63     I->setLinkage(GlobalValue::ExternalLinkage);
64
65   Module *TestModule = CloneModule(SafeModule);
66
67   // Make sure global initializers exist only in the safe module (CBE->.so)
68   for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)
69     I->setInitializer(0);  // Delete the initializer to make it external
70
71   // Remove the Test functions from the Safe module
72   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
73     Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),
74                                              Funcs[i]->getFunctionType());
75     DEBUG(std::cerr << "Removing function " << Funcs[i]->getName() << "\n");
76     assert(TNOF && "Function doesn't exist in module!");
77     DeleteFunctionBody(TNOF);       // Function is now external in this module!
78   }
79
80   // Remove the Safe functions from the Test module
81   for (Module::iterator I=TestModule->begin(),E=TestModule->end(); I!=E; ++I) {
82     bool funcFound = false;
83     for (std::vector<Function*>::const_iterator F=Funcs.begin(),Fe=Funcs.end();
84          F != Fe; ++F)
85       if (I->getName() == (*F)->getName()) funcFound = true;
86
87     if (!funcFound && !(BD.isExecutingJIT() && I->getName() == "main"))
88       DeleteFunctionBody(I);
89   }
90
91   // This is only applicable if we are debugging the JIT:
92   // Find all external functions in the Safe modules that are actually used
93   // (called or taken address of), and make them call the JIT wrapper instead
94   if (BD.isExecutingJIT()) {
95     // Must delete `main' from Safe module if it has it
96     Function *safeMain = SafeModule->getNamedFunction("main");
97     assert(safeMain && "`main' function not found in safe module!");
98     DeleteFunctionBody(safeMain);
99
100     // Add an external function "getPointerToNamedFunction" that JIT provides
101     // Prototype: void *getPointerToNamedFunction(const char* Name)
102     std::vector<const Type*> Params;
103     Params.push_back(PointerType::get(Type::SByteTy)); // std::string&
104     FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),
105                                                  Params, false /* isVarArg */);
106     Function *resolverFunc = new Function(resolverTy,
107                                           GlobalValue::ExternalLinkage,
108                                           "getPointerToNamedFunction",
109                                           SafeModule);
110
111     // Use the function we just added to get addresses of functions we need
112     // Iterate over the global declarations in the Safe module
113     for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){
114       if (F->isExternal() && !F->use_empty() && &(*F) != resolverFunc) {
115         // If it has a non-zero use list,
116         // 1. Add a string constant with its name to the global file
117         // The correct type is `const [ NUM x sbyte ]' where NUM is length of
118         // function name + 1
119         const std::string &Name = F->getName();
120         GlobalVariable *funcName =
121           new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),
122                              true /* isConstant */,
123                              GlobalValue::InternalLinkage,
124                              ConstantArray::get(Name),
125                              Name + "_name",
126                              SafeModule);
127
128         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
129         // sbyte* so it matches the signature of the resolver function.
130         std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::LongTy));
131
132         // 3. Replace all uses of `func' with calls to resolver by:
133         // (a) Iterating through the list of uses of this function
134         // (b) Insert a cast instruction in front of each use
135         // (c) Replace use of old call with new call
136
137         // GetElementPtr *funcName, ulong 0, ulong 0
138         Value *GEP =
139           ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
140                                          GEPargs);
141         std::vector<Value*> ResolverArgs;
142         ResolverArgs.push_back(GEP);
143
144         // Insert code at the beginning of the function
145         for (Value::use_iterator i=F->use_begin(), e=F->use_end(); i!=e; ++i) {
146           if (Instruction* Inst = dyn_cast<Instruction>(*i)) {
147             // call resolver(GetElementPtr...)
148             CallInst *resolve = new CallInst(resolverFunc, ResolverArgs, 
149                                              "resolver", Inst);
150             // cast the result from the resolver to correctly-typed function
151             CastInst *castResolver =
152               new CastInst(resolve, PointerType::get(F->getFunctionType()),
153                            "", Inst);
154             // actually use the resolved function
155             Inst->replaceUsesOfWith(F, castResolver);
156           } else {
157             // FIXME: need to take care of cases where a function is used that
158             // is not an instruction, e.g. global variable initializer...
159             std::cerr << "Non-instruction is using an external function!\n";
160             abort();
161           }
162         }
163       }
164     }
165   }
166
167   DEBUG(std::cerr << "Safe module:\n";
168         typedef Module::iterator MI;
169         typedef Module::giterator MGI;
170
171         for (MI I = SafeModule->begin(), E = SafeModule->end(); I != E; ++I)
172           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
173         for (MGI I = SafeModule->gbegin(), E = SafeModule->gend(); I!=E; ++I)
174           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
175
176         std::cerr << "Test module:\n";
177         for (MI I = TestModule->begin(), E = TestModule->end(); I != E; ++I)
178           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
179         for (MGI I=TestModule->gbegin(),E = TestModule->gend(); I!= E; ++I)
180           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
181         );
182
183   // Write out the bytecode to be sent to CBE
184   std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
185   if (verifyModule(*SafeModule)) {
186     std::cerr << "Bytecode file corrupted!\n";
187     exit(1);
188   }
189   if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
190     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
191     exit(1);
192   }
193
194   // Make a shared library
195   std::string SharedObject;
196   BD.compileSharedObject(SafeModuleBC, SharedObject);
197
198   // Remove all functions from the Test module EXCEPT for the ones specified in
199   // Funcs.  We know which ones these are because they are non-external in
200   // ToOptimize, but external in ToNotOptimize.
201   //
202   for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)
203     if (!I->isExternal()) {
204       Function *TNOF = SafeModule->getFunction(I->getName(),
205                                                I->getFunctionType());
206       assert(TNOF && "Function doesn't exist in ToNotOptimize module??");
207       if (!TNOF->isExternal())
208         DeleteFunctionBody(I);
209     }
210
211   std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
212   if (verifyModule(*TestModule)) {
213     std::cerr << "Bytecode file corrupted!\n";
214     exit(1);
215   }
216   if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
217     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
218     exit(1);
219   }
220
221   delete SafeModule;
222   delete TestModule;
223
224   // Run the code generator on the `Test' code, loading the shared library.
225   // The function returns whether or not the new output differs from reference.
226   int Result =  BD.diffProgram(TestModuleBC, SharedObject, false);
227   if (KeepFiles) {
228     std::cout << "You can reproduce the problem with the command line: \n"
229               << (BD.isExecutingJIT() ? "lli" : "llc")
230               << " -load " << SharedObject << " " << TestModuleBC
231               << "\n";
232   } else {
233     removeFile(TestModuleBC);
234     removeFile(SafeModuleBC);
235     removeFile(SharedObject);
236   }
237   return Result;
238 }
239
240 namespace {
241   struct Disambiguator {
242     std::set<std::string>  SymbolNames;
243     std::set<GlobalValue*> Symbols;
244     uint64_t uniqueCounter;
245     bool externalOnly;
246   public:
247     Disambiguator() : uniqueCounter(0), externalOnly(true) {}
248     void setExternalOnly(bool value) { externalOnly = value; }
249     void add(GlobalValue &V) {
250       // If we're only processing externals and this isn't external, bail
251       if (externalOnly && !V.isExternal()) return;
252       // If we're already processed this symbol, don't add it again
253       if (Symbols.count(&V) != 0) return;
254
255       std::string SymName = V.getName();
256
257       // Use the Mangler facility to make symbol names that will be valid in
258       // shared objects.
259       SymName = Mangler::makeNameProper(SymName);
260       V.setName(SymName);
261
262       if (SymbolNames.count(SymName) == 0) {
263         DEBUG(std::cerr << "Disambiguator: adding " << SymName
264                         << ", no conflicts.\n");
265         SymbolNames.insert(SymName);
266       } else { 
267         // Mangle name before adding
268         std::string newName;
269         do {
270           newName = SymName + "_" + utostr(uniqueCounter);
271           if (SymbolNames.count(newName) == 0) break;
272           else ++uniqueCounter;
273         } while (1);
274         //while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);
275         DEBUG(std::cerr << "Disambiguator: conflict: " << SymName
276                         << ", adding: " << newName << "\n");
277         V.setName(newName);
278         SymbolNames.insert(newName);
279       }
280       Symbols.insert(&V);
281     }
282   };
283 }
284
285 void DisambiguateGlobalSymbols(Module *M) {
286   // First, try not to cause collisions by minimizing chances of renaming an
287   // already-external symbol, so take in external globals and functions as-is.
288   Disambiguator D;
289   DEBUG(std::cerr << "Disambiguating globals (external-only)\n");
290   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
291   DEBUG(std::cerr << "Disambiguating functions (external-only)\n");
292   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I) D.add(*I);
293
294   // Now just rename functions and globals as necessary, keeping what's already
295   // in the set unique.
296   D.setExternalOnly(false);
297   DEBUG(std::cerr << "Disambiguating globals\n");
298   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
299   DEBUG(std::cerr << "Disambiguating globals\n");
300   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I) D.add(*I);
301 }
302
303
304 bool BugDriver::debugCodeGenerator() {
305   // See if we can pin down which functions are being miscompiled...
306   //First, build a list of all of the non-external functions in the program.
307   std::vector<Function*> MisCodegenFunctions;
308   for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
309     if (!I->isExternal())
310       MisCodegenFunctions.push_back(I);
311
312   // If we are executing the JIT, we *must* keep the function `main' in the
313   // module that is passed in, and not the shared library. However, we still
314   // want to be able to debug the `main' function alone. Thus, we create a new
315   // function `main' which just calls the old one.
316   if (isExecutingJIT()) {
317     // Get the `main' function
318     Function *oldMain = Program->getNamedFunction("main");
319     assert(oldMain && "`main' function not found in program!");
320     // Rename it
321     oldMain->setName("old_main");
322     // Create a NEW `main' function with same type
323     Function *newMain = new Function(oldMain->getFunctionType(), 
324                                      GlobalValue::ExternalLinkage,
325                                      "main", Program);
326     // Call the old main function and return its result
327     BasicBlock *BB = new BasicBlock("entry", newMain);
328     std::vector<Value*> args;
329     for (Function::aiterator I=newMain->abegin(), E=newMain->aend(); I!=E; ++I)
330       args.push_back(I);
331     CallInst *call = new CallInst(oldMain, args);
332     BB->getInstList().push_back(call);
333     
334     // if the type of old function wasn't void, return value of call
335     ReturnInst *ret;
336     if (oldMain->getReturnType() != Type::VoidTy) {
337       ret = new ReturnInst(call);
338     } else {
339       ret = new ReturnInst();
340     }
341
342     // Add the return instruction to the BasicBlock
343     BB->getInstList().push_back(ret);
344   }
345
346   DisambiguateGlobalSymbols(Program);
347
348   // Do the reduction...
349   ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions);
350
351   std::cout << "\n*** The following functions are being miscompiled: ";
352   PrintFunctionList(MisCodegenFunctions);
353   std::cout << "\n";
354
355   // Output a bunch of bytecode files for the user...
356   ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);
357
358   return false;
359 }