Added copyright header to all C++ source files.
[oota-llvm.git] / tools / bugpoint / CodeGeneratorBug.cpp
index 5d60bf22452fca0cb03c7c3af0e82560597fcdb2..60964bcfb3d44c2b184153b7c4d49c3a4f1c493e 100644 (file)
@@ -1,11 +1,18 @@
 //===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===//
+// 
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// 
+//===----------------------------------------------------------------------===//
+// 
 //
 // This file implements program code generation debugging support.
 //
 //===----------------------------------------------------------------------===//
 
 #include "BugDriver.h"
-#include "SystemUtils.h"
 #include "ListReducer.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/Transforms/Utils/Cloning.h"
 #include "llvm/Transforms/Utils/Linker.h"
-#include "Support/Statistic.h"
+#include "Support/CommandLine.h"
+#include "Support/Debug.h"
 #include "Support/StringExtras.h"
+#include "Support/FileUtilities.h"
 #include <algorithm>
 #include <set>
 
+extern cl::list<std::string> InputArgv;
+
 class ReduceMisCodegenFunctions : public ListReducer<Function*> {
   BugDriver &BD;
 public:
@@ -41,18 +52,14 @@ public:
   
   bool TestFuncs(const std::vector<Function*> &CodegenTest,
                  bool KeepFiles = false);
-
-  void DisambiguateGlobalSymbols(Module *M);
 };
 
 
 bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
-                                          bool KeepFiles)
-{
-  DEBUG(std::cerr << "Test functions are:\n");
-  for (std::vector<Function*>::const_iterator I = Funcs.begin(),E = Funcs.end();
-       I != E; ++I)
-    DEBUG(std::cerr << "\t" << (*I)->getName() << "\n");
+                                          bool KeepFiles) {
+  std::cout << "Testing functions: ";
+  BD.PrintFunctionList(Funcs);
+  std::cout << "\t";
 
   // Clone the module for the two halves of the program we want.
   Module *SafeModule = CloneModule(BD.Program);
@@ -64,7 +71,6 @@ bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
   for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)
     I->setLinkage(GlobalValue::ExternalLinkage);
 
-  DisambiguateGlobalSymbols(SafeModule);
   Module *TestModule = CloneModule(SafeModule);
 
   // Make sure global initializers exist only in the safe module (CBE->.so)
@@ -75,6 +81,7 @@ bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
     Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),
                                              Funcs[i]->getFunctionType());
+    DEBUG(std::cerr << "Removing function " << Funcs[i]->getName() << "\n");
     assert(TNOF && "Function doesn't exist in module!");
     DeleteFunctionBody(TNOF);       // Function is now external in this module!
   }
@@ -96,6 +103,7 @@ bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
   if (BD.isExecutingJIT()) {
     // Must delete `main' from Safe module if it has it
     Function *safeMain = SafeModule->getNamedFunction("main");
+    assert(safeMain && "`main' function not found in safe module!");
     DeleteFunctionBody(safeMain);
 
     // Add an external function "getPointerToNamedFunction" that JIT provides
@@ -112,7 +120,10 @@ bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
     // Use the function we just added to get addresses of functions we need
     // Iterate over the global declarations in the Safe module
     for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){
-      if (F->isExternal() && !F->use_empty() && &(*F) != resolverFunc) {
+      if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
+          F->getIntrinsicID() == 0 /* ignore intrinsics */ &&
+          // Don't forward functions which are external in the test module too.
+          !TestModule->getNamedFunction(F->getName())->isExternal()) {
         // If it has a non-zero use list,
         // 1. Add a string constant with its name to the global file
         // The correct type is `const [ NUM x sbyte ]' where NUM is length of
@@ -143,15 +154,15 @@ bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
         ResolverArgs.push_back(GEP);
 
         // Insert code at the beginning of the function
-        for (Value::use_iterator i=F->use_begin(), e=F->use_end(); i!=e; ++i) {
-          if (Instruction* Inst = dyn_cast<Instruction>(*i)) {
+        while (!F->use_empty())
+          if (Instruction *Inst = dyn_cast<Instruction>(F->use_back())) {
             // call resolver(GetElementPtr...)
             CallInst *resolve = new CallInst(resolverFunc, ResolverArgs, 
                                              "resolver", Inst);
             // cast the result from the resolver to correctly-typed function
             CastInst *castResolver =
               new CastInst(resolve, PointerType::get(F->getFunctionType()),
-                           "", Inst);
+                           "resolverCast", Inst);
             // actually use the resolved function
             Inst->replaceUsesOfWith(F, castResolver);
           } else {
@@ -160,11 +171,15 @@ bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
             std::cerr << "Non-instruction is using an external function!\n";
             abort();
           }
-        }
       }
     }
   }
 
+  if (verifyModule(*SafeModule) || verifyModule(*TestModule)) {
+    std::cerr << "Bugpoint has a bug, an corrupted a module!!\n";
+    abort();
+  }
+
   DEBUG(std::cerr << "Safe module:\n";
         typedef Module::iterator MI;
         typedef Module::giterator MGI;
@@ -183,19 +198,12 @@ bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
 
   // Write out the bytecode to be sent to CBE
   std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
-  if (verifyModule(*SafeModule)) {
-    std::cerr << "Bytecode file corrupted!\n";
-    exit(1);
-  }
+
   if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
     exit(1);
   }
 
-  // Make a shared library
-  std::string SharedObject;
-  BD.compileSharedObject(SafeModuleBC, SharedObject);
-
   // Remove all functions from the Test module EXCEPT for the ones specified in
   // Funcs.  We know which ones these are because they are non-external in
   // ToOptimize, but external in ToNotOptimize.
@@ -214,22 +222,53 @@ bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
     std::cerr << "Bytecode file corrupted!\n";
     exit(1);
   }
+
+  // Clean up the modules, removing extra cruft that we don't need anymore...
+  SafeModule = BD.performFinalCleanups(SafeModule);
+  TestModule = BD.performFinalCleanups(TestModule);
+
   if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
     exit(1);
   }
 
+  // Make a shared library
+  std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
+
   delete SafeModule;
   delete TestModule;
 
   // Run the code generator on the `Test' code, loading the shared library.
   // The function returns whether or not the new output differs from reference.
-  int Result =  BD.diffProgram(TestModuleBC, SharedObject, false);
+  int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
+
+  if (Result)
+    std::cerr << ": still failing!\n";
+  else
+    std::cerr << ": didn't fail.\n";
+    
   if (KeepFiles) {
-    std::cout << "You can reproduce the problem with the command line: \n"
-              << (BD.isExecutingJIT() ? "lli" : "llc")
-              << " -load " << SharedObject << " " << TestModuleBC
-              << "\n";
+    std::cout << "You can reproduce the problem with the command line: \n";
+    if (BD.isExecutingJIT()) {
+      std::cout << "  lli -load " << SharedObject << " " << TestModuleBC;
+    } else {
+      std::cout << "  llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
+      std::cout << "  gcc " << SharedObject << " " << TestModuleBC
+                << ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
+      std::cout << "  " << TestModuleBC << ".exe";
+    }
+    for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
+      std::cout << " " << InputArgv[i];
+    std::cout << "\n";
+    std::cout << "The shared object was created with:\n  llvm-dis -c "
+              << SafeModuleBC << " -o temporary.c\n"
+              << "  gcc -xc temporary.c -O2 -o " << SharedObject
+#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
+              << " -G"            // Compile a shared library, `-G' for Sparc
+#else
+              << " -shared"       // `-shared' for Linux/X86, maybe others
+#endif
+              << " -fno-strict-aliasing\n";
   } else {
     removeFile(TestModuleBC);
     removeFile(SafeModuleBC);
@@ -252,6 +291,10 @@ namespace {
       if (externalOnly && !V.isExternal()) return;
       // If we're already processed this symbol, don't add it again
       if (Symbols.count(&V) != 0) return;
+      // Ignore intrinsic functions
+      if (Function *F = dyn_cast<Function>(&V))
+        if (F->getIntrinsicID() != 0)
+          return;
 
       std::string SymName = V.getName();
 
@@ -283,7 +326,7 @@ namespace {
   };
 }
 
-void ReduceMisCodegenFunctions::DisambiguateGlobalSymbols(Module *M) {
+void DisambiguateGlobalSymbols(Module *M) {
   // First, try not to cause collisions by minimizing chances of renaming an
   // already-external symbol, so take in external globals and functions as-is.
   Disambiguator D;
@@ -317,8 +360,9 @@ bool BugDriver::debugCodeGenerator() {
   if (isExecutingJIT()) {
     // Get the `main' function
     Function *oldMain = Program->getNamedFunction("main");
+    assert(oldMain && "`main' function not found in program!");
     // Rename it
-    oldMain->setName("old_main");
+    oldMain->setName("llvm_old_main");
     // Create a NEW `main' function with same type
     Function *newMain = new Function(oldMain->getFunctionType(), 
                                      GlobalValue::ExternalLinkage,
@@ -326,8 +370,11 @@ bool BugDriver::debugCodeGenerator() {
     // Call the old main function and return its result
     BasicBlock *BB = new BasicBlock("entry", newMain);
     std::vector<Value*> args;
-    for (Function::aiterator I=newMain->abegin(), E=newMain->aend(); I!=E; ++I)
+    for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
+           OI = oldMain->abegin(); I != E; ++I, ++OI) {
+      I->setName(OI->getName());    // Copy argument names from oldMain
       args.push_back(I);
+    }
     CallInst *call = new CallInst(oldMain, args);
     BB->getInstList().push_back(call);
     
@@ -343,8 +390,14 @@ bool BugDriver::debugCodeGenerator() {
     BB->getInstList().push_back(ret);
   }
 
+  DisambiguateGlobalSymbols(Program);
+
   // Do the reduction...
-  ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions);
+  if (!ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions)) {
+    std::cerr << "*** Execution matches reference output! "
+             << "bugpoint can't help you with your problem!\n";
+    return false;
+  }
 
   std::cout << "\n*** The following functions are being miscompiled: ";
   PrintFunctionList(MisCodegenFunctions);
@@ -355,4 +408,3 @@ bool BugDriver::debugCodeGenerator() {
 
   return false;
 }
-