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