Don't bother forwarding function references which are external to the program entirely
[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 "ListReducer.h"
9 #include "llvm/Constants.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/GlobalValue.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iOther.h"
15 #include "llvm/Module.h"
16 #include "llvm/Pass.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Support/Mangler.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #include "llvm/Transforms/Utils/Cloning.h"
21 #include "llvm/Transforms/Utils/Linker.h"
22 #include "Support/CommandLine.h"
23 #include "Support/Debug.h"
24 #include "Support/StringExtras.h"
25 #include "Support/FileUtilities.h"
26 #include <algorithm>
27 #include <set>
28
29 extern cl::list<std::string> InputArgv;
30
31 class ReduceMisCodegenFunctions : public ListReducer<Function*> {
32   BugDriver &BD;
33 public:
34   ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}
35
36   virtual TestResult doTest(std::vector<Function*> &Prefix,
37                             std::vector<Function*> &Suffix) {
38     if (!Prefix.empty() && TestFuncs(Prefix))
39       return KeepPrefix;
40     if (!Suffix.empty() && TestFuncs(Suffix))
41       return KeepSuffix;
42     return NoFailure;
43   }
44   
45   bool TestFuncs(const std::vector<Function*> &CodegenTest,
46                  bool KeepFiles = false);
47 };
48
49
50 bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
51                                           bool KeepFiles) {
52   std::cout << "Testing functions: ";
53   BD.PrintFunctionList(Funcs);
54   std::cout << "\t";
55
56   // Clone the module for the two halves of the program we want.
57   Module *SafeModule = CloneModule(BD.Program);
58
59   // Make sure functions & globals are all external so that linkage
60   // between the two modules will work.
61   for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)
62     I->setLinkage(GlobalValue::ExternalLinkage);
63   for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)
64     I->setLinkage(GlobalValue::ExternalLinkage);
65
66   Module *TestModule = CloneModule(SafeModule);
67
68   // Make sure global initializers exist only in the safe module (CBE->.so)
69   for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)
70     I->setInitializer(0);  // Delete the initializer to make it external
71
72   // Remove the Test functions from the Safe module
73   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
74     Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),
75                                              Funcs[i]->getFunctionType());
76     DEBUG(std::cerr << "Removing function " << Funcs[i]->getName() << "\n");
77     assert(TNOF && "Function doesn't exist in module!");
78     DeleteFunctionBody(TNOF);       // Function is now external in this module!
79   }
80
81   // Remove the Safe functions from the Test module
82   for (Module::iterator I=TestModule->begin(),E=TestModule->end(); I!=E; ++I) {
83     bool funcFound = false;
84     for (std::vector<Function*>::const_iterator F=Funcs.begin(),Fe=Funcs.end();
85          F != Fe; ++F)
86       if (I->getName() == (*F)->getName()) funcFound = true;
87
88     if (!funcFound && !(BD.isExecutingJIT() && I->getName() == "main"))
89       DeleteFunctionBody(I);
90   }
91
92   // This is only applicable if we are debugging the JIT:
93   // Find all external functions in the Safe modules that are actually used
94   // (called or taken address of), and make them call the JIT wrapper instead
95   if (BD.isExecutingJIT()) {
96     // Must delete `main' from Safe module if it has it
97     Function *safeMain = SafeModule->getNamedFunction("main");
98     assert(safeMain && "`main' function not found in safe module!");
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           F->getIntrinsicID() == 0 /* ignore intrinsics */ &&
117           // Don't forward functions which are external in the test module too.
118           !TestModule->getNamedFunction(F->getName())->isExternal()) {
119         // If it has a non-zero use list,
120         // 1. Add a string constant with its name to the global file
121         // The correct type is `const [ NUM x sbyte ]' where NUM is length of
122         // function name + 1
123         const std::string &Name = F->getName();
124         GlobalVariable *funcName =
125           new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),
126                              true /* isConstant */,
127                              GlobalValue::InternalLinkage,
128                              ConstantArray::get(Name),
129                              Name + "_name",
130                              SafeModule);
131
132         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
133         // sbyte* so it matches the signature of the resolver function.
134         std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::LongTy));
135
136         // 3. Replace all uses of `func' with calls to resolver by:
137         // (a) Iterating through the list of uses of this function
138         // (b) Insert a cast instruction in front of each use
139         // (c) Replace use of old call with new call
140
141         // GetElementPtr *funcName, ulong 0, ulong 0
142         Value *GEP =
143           ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
144                                          GEPargs);
145         std::vector<Value*> ResolverArgs;
146         ResolverArgs.push_back(GEP);
147
148         // Insert code at the beginning of the function
149         while (!F->use_empty())
150           if (Instruction *Inst = dyn_cast<Instruction>(F->use_back())) {
151             // call resolver(GetElementPtr...)
152             CallInst *resolve = new CallInst(resolverFunc, ResolverArgs, 
153                                              "resolver", Inst);
154             // cast the result from the resolver to correctly-typed function
155             CastInst *castResolver =
156               new CastInst(resolve, PointerType::get(F->getFunctionType()),
157                            "resolverCast", Inst);
158             // actually use the resolved function
159             Inst->replaceUsesOfWith(F, castResolver);
160           } else {
161             // FIXME: need to take care of cases where a function is used that
162             // is not an instruction, e.g. global variable initializer...
163             std::cerr << "Non-instruction is using an external function!\n";
164             abort();
165           }
166       }
167     }
168   }
169
170   if (verifyModule(*SafeModule) || verifyModule(*TestModule)) {
171     std::cerr << "Bugpoint has a bug, an corrupted a module!!\n";
172     abort();
173   }
174
175   DEBUG(std::cerr << "Safe module:\n";
176         typedef Module::iterator MI;
177         typedef Module::giterator MGI;
178
179         for (MI I = SafeModule->begin(), E = SafeModule->end(); I != E; ++I)
180           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
181         for (MGI I = SafeModule->gbegin(), E = SafeModule->gend(); I!=E; ++I)
182           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
183
184         std::cerr << "Test module:\n";
185         for (MI I = TestModule->begin(), E = TestModule->end(); I != E; ++I)
186           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
187         for (MGI I=TestModule->gbegin(),E = TestModule->gend(); I!= E; ++I)
188           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
189         );
190
191   // Write out the bytecode to be sent to CBE
192   std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
193
194   if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
195     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
196     exit(1);
197   }
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
218   // Clean up the modules, removing extra cruft that we don't need anymore...
219   SafeModule = BD.performFinalCleanups(SafeModule);
220   TestModule = BD.performFinalCleanups(TestModule);
221
222   if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
223     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
224     exit(1);
225   }
226
227   // Make a shared library
228   std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
229
230   delete SafeModule;
231   delete TestModule;
232
233   // Run the code generator on the `Test' code, loading the shared library.
234   // The function returns whether or not the new output differs from reference.
235   int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
236
237   if (Result)
238     std::cerr << ": still failing!\n";
239   else
240     std::cerr << ": didn't fail.\n";
241     
242   if (KeepFiles) {
243     std::cout << "You can reproduce the problem with the command line: \n";
244     if (BD.isExecutingJIT()) {
245       std::cout << "  lli -load " << SharedObject << " " << TestModuleBC;
246     } else {
247       std::cout << "  llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
248       std::cout << "  gcc " << SharedObject << " " << TestModuleBC
249                 << ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
250       std::cout << "  " << TestModuleBC << ".exe";
251     }
252     for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
253       std::cout << " " << InputArgv[i];
254     std::cout << "\n";
255     std::cout << "The shared object was created with:\n  llvm-dis -c "
256               << SafeModuleBC << " -o temporary.c\n"
257               << "  gcc -xc temporary.c -O2 -o " << SharedObject
258 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
259               << " -G"            // Compile a shared library, `-G' for Sparc
260 #else
261               << " -shared"       // `-shared' for Linux/X86, maybe others
262 #endif
263               << " -fno-strict-aliasing\n";
264   } else {
265     removeFile(TestModuleBC);
266     removeFile(SafeModuleBC);
267     removeFile(SharedObject);
268   }
269   return Result;
270 }
271
272 namespace {
273   struct Disambiguator {
274     std::set<std::string>  SymbolNames;
275     std::set<GlobalValue*> Symbols;
276     uint64_t uniqueCounter;
277     bool externalOnly;
278   public:
279     Disambiguator() : uniqueCounter(0), externalOnly(true) {}
280     void setExternalOnly(bool value) { externalOnly = value; }
281     void add(GlobalValue &V) {
282       // If we're only processing externals and this isn't external, bail
283       if (externalOnly && !V.isExternal()) return;
284       // If we're already processed this symbol, don't add it again
285       if (Symbols.count(&V) != 0) return;
286       // Ignore intrinsic functions
287       if (Function *F = dyn_cast<Function>(&V))
288         if (F->getIntrinsicID() != 0)
289           return;
290
291       std::string SymName = V.getName();
292
293       // Use the Mangler facility to make symbol names that will be valid in
294       // shared objects.
295       SymName = Mangler::makeNameProper(SymName);
296       V.setName(SymName);
297
298       if (SymbolNames.count(SymName) == 0) {
299         DEBUG(std::cerr << "Disambiguator: adding " << SymName
300                         << ", no conflicts.\n");
301         SymbolNames.insert(SymName);
302       } else { 
303         // Mangle name before adding
304         std::string newName;
305         do {
306           newName = SymName + "_" + utostr(uniqueCounter);
307           if (SymbolNames.count(newName) == 0) break;
308           else ++uniqueCounter;
309         } while (1);
310         //while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);
311         DEBUG(std::cerr << "Disambiguator: conflict: " << SymName
312                         << ", adding: " << newName << "\n");
313         V.setName(newName);
314         SymbolNames.insert(newName);
315       }
316       Symbols.insert(&V);
317     }
318   };
319 }
320
321 void DisambiguateGlobalSymbols(Module *M) {
322   // First, try not to cause collisions by minimizing chances of renaming an
323   // already-external symbol, so take in external globals and functions as-is.
324   Disambiguator D;
325   DEBUG(std::cerr << "Disambiguating globals (external-only)\n");
326   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
327   DEBUG(std::cerr << "Disambiguating functions (external-only)\n");
328   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I) D.add(*I);
329
330   // Now just rename functions and globals as necessary, keeping what's already
331   // in the set unique.
332   D.setExternalOnly(false);
333   DEBUG(std::cerr << "Disambiguating globals\n");
334   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
335   DEBUG(std::cerr << "Disambiguating globals\n");
336   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I) D.add(*I);
337 }
338
339
340 bool BugDriver::debugCodeGenerator() {
341   // See if we can pin down which functions are being miscompiled...
342   //First, build a list of all of the non-external functions in the program.
343   std::vector<Function*> MisCodegenFunctions;
344   for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
345     if (!I->isExternal())
346       MisCodegenFunctions.push_back(I);
347
348   // If we are executing the JIT, we *must* keep the function `main' in the
349   // module that is passed in, and not the shared library. However, we still
350   // want to be able to debug the `main' function alone. Thus, we create a new
351   // function `main' which just calls the old one.
352   if (isExecutingJIT()) {
353     // Get the `main' function
354     Function *oldMain = Program->getNamedFunction("main");
355     assert(oldMain && "`main' function not found in program!");
356     // Rename it
357     oldMain->setName("llvm_old_main");
358     // Create a NEW `main' function with same type
359     Function *newMain = new Function(oldMain->getFunctionType(), 
360                                      GlobalValue::ExternalLinkage,
361                                      "main", Program);
362     // Call the old main function and return its result
363     BasicBlock *BB = new BasicBlock("entry", newMain);
364     std::vector<Value*> args;
365     for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
366            OI = oldMain->abegin(); I != E; ++I, ++OI) {
367       I->setName(OI->getName());    // Copy argument names from oldMain
368       args.push_back(I);
369     }
370     CallInst *call = new CallInst(oldMain, args);
371     BB->getInstList().push_back(call);
372     
373     // if the type of old function wasn't void, return value of call
374     ReturnInst *ret;
375     if (oldMain->getReturnType() != Type::VoidTy) {
376       ret = new ReturnInst(call);
377     } else {
378       ret = new ReturnInst();
379     }
380
381     // Add the return instruction to the BasicBlock
382     BB->getInstList().push_back(ret);
383   }
384
385   DisambiguateGlobalSymbols(Program);
386
387   // Do the reduction...
388   if (!ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions)) {
389     std::cerr << "*** Execution matches reference output! "
390               << "bugpoint can't help you with your problem!\n";
391     return false;
392   }
393
394   std::cout << "\n*** The following functions are being miscompiled: ";
395   PrintFunctionList(MisCodegenFunctions);
396   std::cout << "\n";
397
398   // Output a bunch of bytecode files for the user...
399   ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);
400
401   return false;
402 }