bugpoint doesn't need the mangler at all. DisambiguateGlobalSymbols
[oota-llvm.git] / tools / bugpoint / Miscompilation.cpp
index c021418905aead7c2ea9ba95ab244080e85ccd33..4c184d64a6392a6a9bb17cfc861a75f0e1721891 100644 (file)
@@ -14,6 +14,7 @@
 
 #include "BugDriver.h"
 #include "ListReducer.h"
+#include "ToolRunner.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Instructions.h"
@@ -21,7 +22,6 @@
 #include "llvm/Module.h"
 #include "llvm/Pass.h"
 #include "llvm/Analysis/Verifier.h"
-#include "llvm/Support/Mangler.h"
 #include "llvm/Transforms/Utils/Cloning.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileUtilities.h"
@@ -29,6 +29,7 @@
 using namespace llvm;
 
 namespace llvm {
+  extern cl::opt<std::string> OutputPrefix;
   extern cl::list<std::string> InputArgv;
 }
 
@@ -233,29 +234,18 @@ bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
   return TestFn(BD, ToOptimize, ToNotOptimize);
 }
 
-/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
-/// modifying predominantly internal symbols rather than external ones.
+/// DisambiguateGlobalSymbols - Give anonymous global values names.
 ///
 static void DisambiguateGlobalSymbols(Module *M) {
-  // Try not to cause collisions by minimizing chances of renaming an
-  // already-external symbol, so take in external globals and functions as-is.
-  // The code should work correctly without disambiguation (assuming the same
-  // mangler is used by the two code generators), but having symbols with the
-  // same name causes warnings to be emitted by the code generator.
-  Mangler Mang(*M);
-  // Agree with the CBE on symbol naming
-  Mang.markCharUnacceptable('.');
   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
        I != E; ++I) {
     // Don't mangle asm names.
-    if (!I->hasName() || I->getName()[0] != 1)
-      I->setName(Mang.getMangledName(I));
+    if (!I->hasName())
+      I->setName("anon_global");
   }
   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
-    // Don't mangle asm names or intrinsics.
-    if ((!I->hasName() || I->getName()[0] != 1) &&
-        I->getIntrinsicID() == 0)
-      I->setName(Mang.getMangledName(I));
+    if (!I->hasName())
+      I->setName("anon_fn");
   }
 }
 
@@ -300,12 +290,15 @@ static bool ExtractLoops(BugDriver &BD,
              << " Please report a bug!\n";
       errs() << "      Continuing on with un-loop-extracted version.\n";
 
-      BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
-      BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
-      BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
+      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
+                            ToNotOptimize);
+      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
+                            ToOptimize);
+      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
                             ToOptimizeLoopExtracted);
 
-      errs() << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
+      errs() << "Please submit the " 
+             << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
       delete ToOptimize;
       delete ToNotOptimize;
       delete ToOptimizeLoopExtracted;
@@ -543,10 +536,6 @@ DebugAMiscompilation(BugDriver &BD,
       ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
     // Okay, we extracted some loops and the problem still appears.  See if we
     // can eliminate some of the created functions from being candidates.
-
-    // Loop extraction can introduce functions with the same name (foo_code).
-    // Make sure to disambiguate the symbols so that when the program is split
-    // apart that we can link it back together again.
     DisambiguateGlobalSymbols(BD.getProgram());
 
     // Do the reduction...
@@ -564,10 +553,6 @@ DebugAMiscompilation(BugDriver &BD,
       ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
     // Okay, we extracted some blocks and the problem still appears.  See if we
     // can eliminate some of the created functions from being candidates.
-
-    // Block extraction can introduce functions with the same name (foo_code).
-    // Make sure to disambiguate the symbols so that when the program is split
-    // apart that we can link it back together again.
     DisambiguateGlobalSymbols(BD.getProgram());
 
     // Do the reduction...
@@ -650,8 +635,6 @@ bool BugDriver::debugMiscompilation() {
 ///
 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
                                      Module *Safe) {
-  LLVMContext &Context = BD.getContext(); 
-  
   // Clean up the modules, removing extra cruft that we don't need anymore...
   Test = BD.performFinalCleanups(Test);
 
@@ -684,12 +667,12 @@ static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
       }
 
       // Call the old main function and return its result
-      BasicBlock *BB = BasicBlock::Create("entry", newMain);
+      BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
       CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
                                         "", BB);
 
       // If the type of old function wasn't void, return value of call
-      ReturnInst::Create(call, BB);
+      ReturnInst::Create(Safe->getContext(), call, BB);
     }
 
   // The second nasty issue we must deal with in the JIT is that the Safe
@@ -701,8 +684,9 @@ static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
   // Prototype: void *getPointerToNamedFunction(const char* Name)
   Constant *resolverFunc =
     Safe->getOrInsertFunction("getPointerToNamedFunction",
-                        PointerType::getUnqual(Type::Int8Ty),
-                        PointerType::getUnqual(Type::Int8Ty), (Type *)0);
+                    Type::getInt8PtrTy(Safe->getContext()),
+                    Type::getInt8PtrTy(Safe->getContext()),
+                       (Type *)0);
 
   // Use the function we just added to get addresses of functions we need.
   for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
@@ -713,7 +697,7 @@ static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
       // Don't forward functions which are external in the test module too.
       if (TestFn && !TestFn->isDeclaration()) {
         // 1. Add a string constant with its name to the global file
-        Constant *InitArray = ConstantArray::get(F->getName());
+        Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
         GlobalVariable *funcName =
           new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
                              GlobalValue::InternalLinkage, InitArray,
@@ -723,7 +707,8 @@ static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
         // sbyte* so it matches the signature of the resolver function.
 
         // GetElementPtr *funcName, ulong 0, ulong 0
-        std::vector<Constant*> GEPargs(2, Context.getNullValue(Type::Int32Ty));
+        std::vector<Constant*> GEPargs(2,
+                     Constant::getNullValue(Type::getInt32Ty(F->getContext())));
         Value *GEP =
                 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
         std::vector<Value*> ResolverArgs;
@@ -733,7 +718,7 @@ static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
         // function that dynamically resolves the calls to F via our JIT API
         if (!F->use_empty()) {
           // Create a new global to hold the cached function pointer.
-          Constant *NullPtr = Context.getConstantPointerNull(F->getType());
+          Constant *NullPtr = ConstantPointerNull::get(F->getType());
           GlobalVariable *Cache =
             new GlobalVariable(*F->getParent(), F->getType(), 
                                false, GlobalValue::InternalLinkage,
@@ -745,9 +730,12 @@ static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
                                                    GlobalValue::InternalLinkage,
                                                    F->getName() + "_wrapper",
                                                    F->getParent());
-          BasicBlock *EntryBB  = BasicBlock::Create("entry", FuncWrapper);
-          BasicBlock *DoCallBB = BasicBlock::Create("usecache", FuncWrapper);
-          BasicBlock *LookupBB = BasicBlock::Create("lookupfp", FuncWrapper);
+          BasicBlock *EntryBB  = BasicBlock::Create(F->getContext(),
+                                                    "entry", FuncWrapper);
+          BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
+                                                    "usecache", FuncWrapper);
+          BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
+                                                    "lookupfp", FuncWrapper);
 
           // Check to see if we already looked up the value.
           Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
@@ -784,13 +772,13 @@ static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
             Args.push_back(i);
 
           // Pass on the arguments to the real function, return its result
-          if (F->getReturnType() == Type::VoidTy) {
+          if (F->getReturnType() == Type::getVoidTy(F->getContext())) {
             CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
-            ReturnInst::Create(DoCallBB);
+            ReturnInst::Create(F->getContext(), DoCallBB);
           } else {
             CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
                                               "retval", DoCallBB);
-            ReturnInst::Create(Call, DoCallBB);
+            ReturnInst::Create(F->getContext(),Call, DoCallBB);
           }
 
           // Use the wrapper function instead of the old function
@@ -822,8 +810,9 @@ static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
            << ErrMsg << "\n";
     exit(1);
   }
-  if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
-    errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
+  if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
+    errs() << "Error writing bitcode to `" << TestModuleBC.str()
+           << "'\nExiting.";
     exit(1);
   }
   delete Test;
@@ -836,16 +825,17 @@ static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
     exit(1);
   }
 
-  if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
-    errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
+  if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
+    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
+           << "'\nExiting.";
     exit(1);
   }
-  std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
+  std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str());
   delete Safe;
 
   // 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.toString(), SharedObject, false);
+  int Result = BD.diffProgram(TestModuleBC.str(), SharedObject, false);
 
   if (Result)
     errs() << ": still failing!\n";
@@ -895,8 +885,9 @@ bool BugDriver::debugCodeGenerator() {
     exit(1);
   }
 
-  if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
-    errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
+  if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
+    errs() << "Error writing bitcode to `" << TestModuleBC.str()
+           << "'\nExiting.";
     exit(1);
   }
   delete ToCodeGen;
@@ -909,38 +900,40 @@ bool BugDriver::debugCodeGenerator() {
     exit(1);
   }
 
-  if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
-    errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
+  if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
+    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
+           << "'\nExiting.";
     exit(1);
   }
-  std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
+  std::string SharedObject = compileSharedObject(SafeModuleBC.str());
   delete ToNotCodeGen;
 
   outs() << "You can reproduce the problem with the command line: \n";
   if (isExecutingJIT()) {
-    outs() << "  lli -load " << SharedObject << " " << TestModuleBC;
+    outs() << "  lli -load " << SharedObject << " " << TestModuleBC.str();
   } else {
-    outs() << "  llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
-    outs() << "  gcc " << SharedObject << " " << TestModuleBC
-              << ".s -o " << TestModuleBC << ".exe";
+    outs() << "  llc -f " << TestModuleBC.str() << " -o " << TestModuleBC.str()
+           << ".s\n";
+    outs() << "  gcc " << SharedObject << " " << TestModuleBC.str()
+              << ".s -o " << TestModuleBC.str() << ".exe";
 #if defined (HAVE_LINK_R)
     outs() << " -Wl,-R.";
 #endif
     outs() << "\n";
-    outs() << "  " << TestModuleBC << ".exe";
+    outs() << "  " << TestModuleBC.str() << ".exe";
   }
   for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
     outs() << " " << InputArgv[i];
   outs() << '\n';
   outs() << "The shared object was created with:\n  llc -march=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
-         << " -fPIC -shared"       // `-shared' for Linux/X86, maybe others
-#endif
-         << " -fno-strict-aliasing\n";
+         << SafeModuleBC.str() << " -o temporary.c\n"
+         << "  gcc -xc temporary.c -O2 -o " << SharedObject;
+  if (TargetTriple.getArch() == Triple::sparc)
+    outs() << " -G";              // Compile a shared library, `-G' for Sparc
+  else
+    outs() << " -fPIC -shared";   // `-shared' for Linux/X86, maybe others
+
+  outs() << " -fno-strict-aliasing\n";
 
   return false;
 }