Miscompilation.cpp revision c9c08fb3a7fb5e8ea3e1477a88507704c7a70ba1
14a10645c70199c8d8567fbc46312158c419720abChris Lattner//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
23da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman//
37c0e022c5c4be4b11e199a53f73bbdd84e34aa80John Criswell//                     The LLVM Compiler Infrastructure
47c0e022c5c4be4b11e199a53f73bbdd84e34aa80John Criswell//
521c62da287237d39d0d95004881ea4baae3be6daChris Lattner// This file is distributed under the University of Illinois Open Source
621c62da287237d39d0d95004881ea4baae3be6daChris Lattner// License. See LICENSE.TXT for details.
73da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman//
87c0e022c5c4be4b11e199a53f73bbdd84e34aa80John Criswell//===----------------------------------------------------------------------===//
94a10645c70199c8d8567fbc46312158c419720abChris Lattner//
10a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner// This file implements optimizer and code generation miscompilation debugging
11a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner// support.
124a10645c70199c8d8567fbc46312158c419720abChris Lattner//
134a10645c70199c8d8567fbc46312158c419720abChris Lattner//===----------------------------------------------------------------------===//
144a10645c70199c8d8567fbc46312158c419720abChris Lattner
154a10645c70199c8d8567fbc46312158c419720abChris Lattner#include "BugDriver.h"
16126840f49e8d49156a342e836d4b2adca46dc3baChris Lattner#include "ListReducer.h"
17ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar#include "ToolRunner.h"
18a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner#include "llvm/Constants.h"
19a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner#include "llvm/DerivedTypes.h"
20a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner#include "llvm/Instructions.h"
21605b9e2c5bd1b0c151a0b15d01e6df3aba93d52fReid Spencer#include "llvm/Linker.h"
224a10645c70199c8d8567fbc46312158c419720abChris Lattner#include "llvm/Module.h"
23e49603d79d220a795bd50684c8b1f503ee40f97fMisha Brukman#include "llvm/Pass.h"
24a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner#include "llvm/Analysis/Verifier.h"
25640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner#include "llvm/Transforms/Utils/Cloning.h"
26551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/CommandLine.h"
27551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/FileUtilities.h"
2859615f0f85e2ac99e012cb81934d002faebd405aChris Lattner#include "llvm/Config/config.h"   // for HAVE_LINK_R
29fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattnerusing namespace llvm;
304a10645c70199c8d8567fbc46312158c419720abChris Lattner
31a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattnernamespace llvm {
3268ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar  extern cl::opt<std::string> OutputPrefix;
33a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  extern cl::list<std::string> InputArgv;
34a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner}
35a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
36efdc0b505712d1ca4460def27e51c430f033d58dChris Lattnernamespace {
37dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer  static llvm::cl::opt<bool>
38dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer    DisableLoopExtraction("disable-loop-extraction",
39dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer        cl::desc("Don't extract loops when searching for miscompilations"),
40dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer        cl::init(false));
41265d82e4c68fa30b7ff1cb650456249f7068bdd6David Goodwin  static llvm::cl::opt<bool>
42265d82e4c68fa30b7ff1cb650456249f7068bdd6David Goodwin    DisableBlockExtraction("disable-block-extraction",
43265d82e4c68fa30b7ff1cb650456249f7068bdd6David Goodwin        cl::desc("Don't extract blocks when searching for miscompilations"),
44265d82e4c68fa30b7ff1cb650456249f7068bdd6David Goodwin        cl::init(false));
45dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer
468261dfed05e32302469ef707cc881fed2c31f85fRafael Espindola  class ReduceMiscompilingPasses : public ListReducer<std::string> {
47fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    BugDriver &BD;
48fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  public:
49fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
503da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
518261dfed05e32302469ef707cc881fed2c31f85fRafael Espindola    virtual TestResult doTest(std::vector<std::string> &Prefix,
528261dfed05e32302469ef707cc881fed2c31f85fRafael Espindola                              std::vector<std::string> &Suffix,
5322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::string &Error);
54fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  };
55fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner}
56640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
578c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// TestResult - After passes have been split into a test group and a control
588c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// group, see if they still break the program.
598c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
60640f22e66d90439857a97a83896ee68c4f7128c9Chris LattnerReduceMiscompilingPasses::TestResult
618261dfed05e32302469ef707cc881fed2c31f85fRafael EspindolaReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
628261dfed05e32302469ef707cc881fed2c31f85fRafael Espindola                                 std::vector<std::string> &Suffix,
6322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                 std::string &Error) {
6406943add8b2b764e131979cca064eda9f28826c9Chris Lattner  // First, run the program with just the Suffix passes.  If it is still broken
65640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // with JUST the kept passes, discard the prefix passes.
66ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if '" << getPassesString(Suffix)
67ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << "' compiles correctly: ";
68640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
698ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  std::string BitcodeResult;
70ca356afe09454b3378165ded4eda294bd6341428Rafael Espindola  if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
71ca356afe09454b3378165ded4eda294bd6341428Rafael Espindola                   true/*quiet*/)) {
7265f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << " Error running this sequence of passes"
7365f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << " on the input program!\n";
745ef681c19de9c675a265211f8fb0ae49cc3a3a66Chris Lattner    BD.setPassesToRun(Suffix);
75bae1b71cbb930e419df03db209ebc547a0e4ec72Rafael Espindola    BD.EmitProgressBitcode(BD.getProgram(), "pass-error",  false);
76025262692a6710de29a48e2b3905672cd12d13d2Chris Lattner    exit(BD.debugOptimizerCrash());
77640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
789adc0abad3c3ed40a268ccbcee0c74cb9e1359feOwen Anderson
79640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Check to see if the finished program matches the reference output...
8010757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola  bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
8110757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola                             true /*delete bitcode*/, &Error);
8222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
8322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return InternalError;
8422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Diff) {
85ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " nope.\n";
8659615f0f85e2ac99e012cb81934d002faebd405aChris Lattner    if (Suffix.empty()) {
8765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman      errs() << BD.getToolName() << ": I'm confused: the test fails when "
8865f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman             << "no passes are run, nondeterministic program?\n";
8959615f0f85e2ac99e012cb81934d002faebd405aChris Lattner      exit(1);
9059615f0f85e2ac99e012cb81934d002faebd405aChris Lattner    }
91123f8fec94d1f22d876382897231868c62f8eabbMisha Brukman    return KeepSuffix;         // Miscompilation detected!
92640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
93ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << " yup.\n";      // No miscompilation!
94640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
95640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  if (Prefix.empty()) return NoFailure;
96640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
9706943add8b2b764e131979cca064eda9f28826c9Chris Lattner  // Next, see if the program is broken if we run the "prefix" passes first,
98bc0e998c497446f5448425b3cbd7f8f19a458764Misha Brukman  // then separately run the "kept" passes.
99ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if '" << getPassesString(Prefix)
100ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << "' compiles correctly: ";
101640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
102640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // If it is not broken with the kept passes, it's possible that the prefix
103640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // passes must be run before the kept passes to break it.  If the program
104640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // WORKS after the prefix passes, but then fails if running the prefix AND
1058ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  // kept passes, we can update our bitcode file to include the result of the
106640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // prefix passes, then discard the prefix passes.
107640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  //
108ca356afe09454b3378165ded4eda294bd6341428Rafael Espindola  if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false/*delete*/,
109ca356afe09454b3378165ded4eda294bd6341428Rafael Espindola                   true/*quiet*/)) {
11065f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << " Error running this sequence of passes"
11165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << " on the input program!\n";
1129c6cfe1bffd37f29a265457b7515839c445b3e6aChris Lattner    BD.setPassesToRun(Prefix);
113bae1b71cbb930e419df03db209ebc547a0e4ec72Rafael Espindola    BD.EmitProgressBitcode(BD.getProgram(), "pass-error",  false);
114025262692a6710de29a48e2b3905672cd12d13d2Chris Lattner    exit(BD.debugOptimizerCrash());
115640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
116640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
117640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // If the prefix maintains the predicate by itself, only keep the prefix!
11810757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola  Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
11922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
12022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return InternalError;
12122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Diff) {
122ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " nope.\n";
1238ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif    sys::Path(BitcodeResult).eraseFromDisk();
124640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner    return KeepPrefix;
125640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
126ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << " yup.\n";      // No miscompilation!
127640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
128640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Ok, so now we know that the prefix passes work, try running the suffix
129640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // passes on the result of the prefix passes.
130640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  //
1316865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  OwningPtr<Module> PrefixOutput(ParseInputFile(BitcodeResult,
1326865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin                                                BD.getContext()));
133640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  if (PrefixOutput == 0) {
13465f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << ": Error reading bitcode file '"
13565f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << BitcodeResult << "'!\n";
136640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner    exit(1);
137640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
1388ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  sys::Path(BitcodeResult).eraseFromDisk();  // No longer need the file on disk
139f4789e6d04c1fddb40092a1193c4a5eb67387accChris Lattner
140f4789e6d04c1fddb40092a1193c4a5eb67387accChris Lattner  // Don't check if there are no passes in the suffix.
141f4789e6d04c1fddb40092a1193c4a5eb67387accChris Lattner  if (Suffix.empty())
142f4789e6d04c1fddb40092a1193c4a5eb67387accChris Lattner    return NoFailure;
1433da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
144ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if '" << getPassesString(Suffix)
145640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner            << "' passes compile correctly after the '"
146640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner            << getPassesString(Prefix) << "' passes: ";
147640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
1486865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  OwningPtr<Module> OriginalInput(BD.swapProgramIn(PrefixOutput.take()));
149ca356afe09454b3378165ded4eda294bd6341428Rafael Espindola  if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
150ca356afe09454b3378165ded4eda294bd6341428Rafael Espindola                   true/*quiet*/)) {
15165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << " Error running this sequence of passes"
15265f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << " on the input program!\n";
1535ef681c19de9c675a265211f8fb0ae49cc3a3a66Chris Lattner    BD.setPassesToRun(Suffix);
154bae1b71cbb930e419df03db209ebc547a0e4ec72Rafael Espindola    BD.EmitProgressBitcode(BD.getProgram(), "pass-error",  false);
155025262692a6710de29a48e2b3905672cd12d13d2Chris Lattner    exit(BD.debugOptimizerCrash());
156640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
157640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
158640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Run the result...
15910757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola  Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
16010757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola                        true /*delete bitcode*/, &Error);
16122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
16222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return InternalError;
16322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Diff) {
164ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " nope.\n";
16506943add8b2b764e131979cca064eda9f28826c9Chris Lattner    return KeepSuffix;
166640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
167640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
168640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Otherwise, we must not be running the bad pass anymore.
169ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << " yup.\n";      // No miscompilation!
1706865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  // Restore orig program & free test.
1716865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  delete BD.swapProgramIn(OriginalInput.take());
172640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  return NoFailure;
173640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner}
174640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
175efdc0b505712d1ca4460def27e51c430f033d58dChris Lattnernamespace {
176fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  class ReduceMiscompilingFunctions : public ListReducer<Function*> {
177fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    BugDriver &BD;
17822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
179fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  public:
180b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    ReduceMiscompilingFunctions(BugDriver &bd,
18122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                bool (*F)(BugDriver &, Module *, Module *,
18222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                          std::string &))
183b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner      : BD(bd), TestFn(F) {}
1843da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
185fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    virtual TestResult doTest(std::vector<Function*> &Prefix,
18622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::vector<Function*> &Suffix,
18722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::string &Error) {
18822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Suffix.empty()) {
18922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        bool Ret = TestFuncs(Suffix, Error);
19022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (!Error.empty())
19122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return InternalError;
19222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (Ret)
19322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return KeepSuffix;
19422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      }
19522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Prefix.empty()) {
19622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        bool Ret = TestFuncs(Prefix, Error);
19722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (!Error.empty())
19822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return InternalError;
19922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (Ret)
20022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return KeepPrefix;
20122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      }
202fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner      return NoFailure;
203fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    }
2043da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
20584ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola    bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
206fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  };
207fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner}
208640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
209efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner/// TestMergedProgram - Given two modules, link them together and run the
21013793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola/// program, checking to see if the program matches the diff. If there is
21113793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola/// an error, return NULL. If not, return the merged module. The Broken argument
21213793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola/// will be set to true if the output is different. If the DeleteInputs
21313793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola/// argument is set to true then this function deletes both input
21413793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola/// modules before it returns.
2158c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
21613793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindolastatic Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
21713793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola                                 bool DeleteInputs, std::string &Error,
21813793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola                                 bool &Broken) {
219efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  // Link the two portions of the program back to together.
220efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  std::string ErrorMsg;
22190c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  if (!DeleteInputs) {
22290c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    M1 = CloneModule(M1);
22390c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    M2 = CloneModule(M2);
22490c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  }
225e4874029c37c4b14d0646289f18e5f2a1b03fdc2Reid Spencer  if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
22665f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << ": Error linking modules together:"
22765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrorMsg << '\n';
228efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner    exit(1);
229efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  }
23090c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  delete M2;   // We are done with this module.
231efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner
23213793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola  // Execute the program.
23313793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola  Broken = BD.diffProgram(M1, "", "", false, &Error);
23422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty()) {
23510757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola    // Delete the linked module
23610757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola    delete M1;
23713793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    return NULL;
23822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  }
23913793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola  return M1;
240efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner}
241efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner
2428c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// TestFuncs - split functions in a Module into two groups: those that are
2438c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// under consideration for miscompilation vs. those that are not, and test
2448c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// accordingly. Each group of functions becomes a separate Module.
2458c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
24684ae206c976c76761e307e5c45f8170d0b61015fRafael Espindolabool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
24784ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola                                            std::string &Error) {
248640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Test to see if the function is misoptimized if we ONLY run it on the
249640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // functions listed in Funcs.
250ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if the program is misoptimized when "
251ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << (Funcs.size()==1 ? "this function is" : "these functions are")
252ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << " run through the pass"
253ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
254efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  PrintFunctionList(Funcs);
255ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << '\n';
256640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
25784ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  // Create a clone for two reasons:
25884ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  // * If the optimization passes delete any function, the deleted function
25984ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  //   will be in the clone and Funcs will still point to valid memory
26084ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  // * If the optimization passes use interprocedural information to break
26184ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  //   a function, we want to continue with the original function. Otherwise
26284ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  //   we can conclude that a function triggers the bug when in fact one
26384ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  //   needs a larger set of original functions to do so.
2641ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola  ValueToValueMapTy VMap;
26584ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  Module *Clone = CloneModule(BD.getProgram(), VMap);
26684ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  Module *Orig = BD.swapProgramIn(Clone);
26784ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola
26884ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  std::vector<Function*> FuncsOnClone;
26984ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
27084ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola    Function *F = cast<Function>(VMap[Funcs[i]]);
27184ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola    FuncsOnClone.push_back(F);
27284ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  }
27384ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola
27484ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  // Split the module into the two halves of the program we want.
27584ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  VMap.clear();
276e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
27784ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
278e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                 VMap);
279640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
2806fa98b13206583e6eb90b8304758b35548914944Nick Lewycky  // Run the predicate, note that the predicate will delete both input modules.
28184ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
28284ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola
28384ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  delete BD.swapProgramIn(Orig);
28484ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola
28584ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  return Broken;
286640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner}
287640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
2888abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner/// DisambiguateGlobalSymbols - Give anonymous global values names.
2898c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
29036ee07ff9d26a2c6ebf9faf9ba90923644db29c5Chris Lattnerstatic void DisambiguateGlobalSymbols(Module *M) {
29167ef9e43049c28c8fe2c9f70d2ad163045ee5876Chris Lattner  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
2921ffb33d033d3593ded0adb08b05eb455cce59ea8Chris Lattner       I != E; ++I)
2938abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner    if (!I->hasName())
2948abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner      I->setName("anon_global");
2951ffb33d033d3593ded0adb08b05eb455cce59ea8Chris Lattner  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
2968abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner    if (!I->hasName())
2978abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner      I->setName("anon_fn");
29836ee07ff9d26a2c6ebf9faf9ba90923644db29c5Chris Lattner}
29936ee07ff9d26a2c6ebf9faf9ba90923644db29c5Chris Lattner
300a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
301a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// check to see if we can extract the loops in the region without obscuring the
302a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// bug.  If so, it reduces the amount of code identified.
3038c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
304b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattnerstatic bool ExtractLoops(BugDriver &BD,
30522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                         bool (*TestFn)(BugDriver &, Module *, Module *,
30622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                        std::string &),
30722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                         std::vector<Function*> &MiscompiledFunctions,
30822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                         std::string &Error) {
309a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  bool MadeChange = false;
310a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  while (1) {
311aed98fa8861a28e5f7ba7c0659e106f2a441e9ffChris Lattner    if (BugpointIsInterrupted) return MadeChange;
312aed98fa8861a28e5f7ba7c0659e106f2a441e9ffChris Lattner
3131ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola    ValueToValueMapTy VMap;
314e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel    Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
315a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
316d50330cd02b00c8e3de40e8544c45701b9891d87Dan Gohman                                                   MiscompiledFunctions,
317e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                   VMap);
318a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
319a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    if (!ToOptimizeLoopExtracted) {
320a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // If the loop extractor crashed or if there were no extractible loops,
321a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // then this chapter of our odyssey is over with.
322a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      delete ToNotOptimize;
323a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      delete ToOptimize;
324a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      return MadeChange;
325a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    }
326a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
32765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << "Extracted a loop from the breaking portion of the program.\n";
328a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
329a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // Bugpoint is intentionally not very trusting of LLVM transformations.  In
330a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // particular, we're not going to assume that the loop extractor works, so
331a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // we're going to test the newly loop extracted program to make sure nothing
332a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // has broken.  If something broke, then we'll inform the user and stop
333a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // extraction.
33470ef449741da8b1ef035e04a55958652a0200ba1Dan Gohman    AbstractInterpreter *AI = BD.switchToSafeInterpreter();
33513793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    bool Failure;
33613793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize,
33713793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola                                    false, Error, Failure);
33813793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    if (!New)
33922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return false;
34013793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    // Delete the original and set the new program.
34113793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    delete BD.swapProgramIn(New);
34222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (Failure) {
343a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      BD.switchToInterpreter(AI);
344a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
345a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // Merged program doesn't work anymore!
34665f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman      errs() << "  *** ERROR: Loop extraction broke the program. :("
34765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman             << " Please report a bug!\n";
34865f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman      errs() << "      Continuing on with un-loop-extracted version.\n";
34956c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner
35068ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
35168ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar                            ToNotOptimize);
35268ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
35368ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar                            ToOptimize);
35468ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
35556c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner                            ToOptimizeLoopExtracted);
35656c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner
35768ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar      errs() << "Please submit the "
35868ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar             << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
35956c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner      delete ToOptimize;
360a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      delete ToNotOptimize;
361a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      delete ToOptimizeLoopExtracted;
362a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      return MadeChange;
363a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    }
36456c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner    delete ToOptimize;
365a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    BD.switchToInterpreter(AI);
3663da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
367ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "  Testing after loop extraction:\n";
368b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    // Clone modules, the tester function will free them.
369b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
370b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    Module *TNOBackup  = CloneModule(ToNotOptimize);
37122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
37222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
37322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return false;
37422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Failure) {
375ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman      outs() << "*** Loop extraction masked the problem.  Undoing.\n";
376a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // If the program is not still broken, then loop extraction did something
377a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // that masked the error.  Stop loop extraction now.
378b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner      delete TOLEBackup;
379b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner      delete TNOBackup;
380a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      return MadeChange;
381a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    }
382b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    ToOptimizeLoopExtracted = TOLEBackup;
383b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    ToNotOptimize = TNOBackup;
384b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
385ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "*** Loop extraction successful!\n";
386a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
38790c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
38890c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
38990c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner           E = ToOptimizeLoopExtracted->end(); I != E; ++I)
3905cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer      if (!I->isDeclaration())
391fa1af1344910ee975f50ffdddf605c26f80ef016Chris Lattner        MisCompFunctions.push_back(std::make_pair(I->getName(),
392fa1af1344910ee975f50ffdddf605c26f80ef016Chris Lattner                                                  I->getFunctionType()));
39390c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner
394a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // Okay, great!  Now we know that we extracted a loop and that loop
395a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // extraction both didn't break the program, and didn't mask the problem.
396a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // Replace the current program with the loop extracted version, and try to
397a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // extract another loop.
398a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    std::string ErrorMsg;
399e4874029c37c4b14d0646289f18e5f2a1b03fdc2Reid Spencer    if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
40065f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman      errs() << BD.getToolName() << ": Error linking modules together:"
40165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman             << ErrorMsg << '\n';
402a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      exit(1);
403a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    }
40490c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    delete ToOptimizeLoopExtracted;
405d3a533d94dae1e57194001af08763eb3ba199c8fChris Lattner
406d3a533d94dae1e57194001af08763eb3ba199c8fChris Lattner    // All of the Function*'s in the MiscompiledFunctions list are in the old
4075313f23b8c3d22a2028beb731c60fc1a25beb149Chris Lattner    // module.  Update this list to include all of the functions in the
4085313f23b8c3d22a2028beb731c60fc1a25beb149Chris Lattner    // optimized and loop extracted module.
4095313f23b8c3d22a2028beb731c60fc1a25beb149Chris Lattner    MiscompiledFunctions.clear();
41090c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
411ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer      Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
412ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer
41390c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner      assert(NewF && "Function not found??");
414ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer      assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
415ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer             "found wrong function type?");
41690c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner      MiscompiledFunctions.push_back(NewF);
417d3a533d94dae1e57194001af08763eb3ba199c8fChris Lattner    }
418d3a533d94dae1e57194001af08763eb3ba199c8fChris Lattner
419a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    BD.setNewProgram(ToNotOptimize);
420a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    MadeChange = true;
421a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  }
422a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner}
423a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
4245e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattnernamespace {
4255e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
4265e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    BugDriver &BD;
42722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
4285e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    std::vector<Function*> FunctionsBeingTested;
4295e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  public:
4305e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    ReduceMiscompiledBlocks(BugDriver &bd,
43122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                            bool (*F)(BugDriver &, Module *, Module *,
43222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                      std::string &),
4335e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner                            const std::vector<Function*> &Fns)
4345e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner      : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
4353da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
4365e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
43722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::vector<BasicBlock*> &Suffix,
43822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::string &Error) {
43922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Suffix.empty()) {
44022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        bool Ret = TestFuncs(Suffix, Error);
44122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (!Error.empty())
44222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return InternalError;
44322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (Ret)
44422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return KeepSuffix;
44522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      }
44622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Prefix.empty()) {
44722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        bool Ret = TestFuncs(Prefix, Error);
44822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (!Error.empty())
44922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return InternalError;
45022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (Ret)
45122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return KeepPrefix;
45222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      }
4535e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner      return NoFailure;
4545e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    }
4553da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
45622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
4575e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  };
4585e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner}
4595e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
4605e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// TestFuncs - Extract all blocks for the miscompiled functions except for the
4615e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// specified blocks.  If the problem still exists, return true.
4625e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner///
46322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckybool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
46422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                        std::string &Error) {
4655e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // Test to see if the function is misoptimized if we ONLY run it on the
4665e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // functions listed in Funcs.
467ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if the program is misoptimized when all ";
46868bee938e539d884ee89ce4dfebbad777896960eChris Lattner  if (!BBs.empty()) {
469ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "but these " << BBs.size() << " blocks are extracted: ";
47068bee938e539d884ee89ce4dfebbad777896960eChris Lattner    for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
471ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman      outs() << BBs[i]->getName() << " ";
472ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    if (BBs.size() > 10) outs() << "...";
47368bee938e539d884ee89ce4dfebbad777896960eChris Lattner  } else {
474ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "blocks are extracted.";
47568bee938e539d884ee89ce4dfebbad777896960eChris Lattner  }
476ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << '\n';
4775e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
4785e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // Split the module into the two halves of the program we want.
4791ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola  ValueToValueMapTy VMap;
480115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  Module *Clone = CloneModule(BD.getProgram(), VMap);
481115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  Module *Orig = BD.swapProgramIn(Clone);
482115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  std::vector<Function*> FuncsOnClone;
483115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  std::vector<BasicBlock*> BBsOnClone;
484115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
485115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
486115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    FuncsOnClone.push_back(F);
487115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  }
488115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
489115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
490115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    BBsOnClone.push_back(BB);
491115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  }
492115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  VMap.clear();
493115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola
494e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
4955e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
496115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola                                                 FuncsOnClone,
497e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                 VMap);
4985e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
4995e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // Try the extraction.  If it doesn't work, then the block extractor crashed
5005e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // or something, in which case bugpoint can't chase down this possibility.
501115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  if (Module *New = BD.ExtractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
5025e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    delete ToOptimize;
503115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    // Run the predicate,
504115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    // note that the predicate will delete both input modules.
505115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    bool Ret = TestFn(BD, New, ToNotOptimize, Error);
506115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    delete BD.swapProgramIn(Orig);
507115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola    return Ret;
5085e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  }
509115a932eb9e66efd424664dbd532dbed76faa072Rafael Espindola  delete BD.swapProgramIn(Orig);
5105e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  delete ToOptimize;
5115e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  delete ToNotOptimize;
5125e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  return false;
5135e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner}
5145e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5155e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5165e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
5175e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// extract as many basic blocks from the region as possible without obscuring
5185e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// the bug.
5195e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner///
5205e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattnerstatic bool ExtractBlocks(BugDriver &BD,
52122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                          bool (*TestFn)(BugDriver &, Module *, Module *,
52222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                         std::string &),
52322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                          std::vector<Function*> &MiscompiledFunctions,
52422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                          std::string &Error) {
525f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner  if (BugpointIsInterrupted) return false;
526f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner
5275e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  std::vector<BasicBlock*> Blocks;
5285e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
5295e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    for (Function::iterator I = MiscompiledFunctions[i]->begin(),
5305e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner           E = MiscompiledFunctions[i]->end(); I != E; ++I)
5315e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner      Blocks.push_back(I);
5325e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5335e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // Use the list reducer to identify blocks that can be extracted without
5345e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // obscuring the bug.  The Blocks list will end up containing blocks that must
5355e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // be retained from the original program.
5365e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  unsigned OldSize = Blocks.size();
53768bee938e539d884ee89ce4dfebbad777896960eChris Lattner
53868bee938e539d884ee89ce4dfebbad777896960eChris Lattner  // Check to see if all blocks are extractible first.
53922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
54022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                  .TestFuncs(std::vector<BasicBlock*>(), Error);
54122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
54222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return false;
54322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Ret) {
54468bee938e539d884ee89ce4dfebbad777896960eChris Lattner    Blocks.clear();
54568bee938e539d884ee89ce4dfebbad777896960eChris Lattner  } else {
54622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    ReduceMiscompiledBlocks(BD, TestFn,
54722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                            MiscompiledFunctions).reduceList(Blocks, Error);
54822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
54922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return false;
55068bee938e539d884ee89ce4dfebbad777896960eChris Lattner    if (Blocks.size() == OldSize)
55168bee938e539d884ee89ce4dfebbad777896960eChris Lattner      return false;
55268bee938e539d884ee89ce4dfebbad777896960eChris Lattner  }
5535e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5541ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola  ValueToValueMapTy VMap;
555e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ProgClone = CloneModule(BD.getProgram(), VMap);
5562290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
557d50330cd02b00c8e3de40e8544c45701b9891d87Dan Gohman                                                MiscompiledFunctions,
558e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                VMap);
5592290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
5602290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  if (Extracted == 0) {
561da895d63377b421dc50117befb2bec80d2973526Chris Lattner    // Weird, extraction should have worked.
56265f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << "Nondeterministic problem extracting blocks??\n";
5632290e754061f1393bb96b1808ac33dc03399c939Chris Lattner    delete ProgClone;
5642290e754061f1393bb96b1808ac33dc03399c939Chris Lattner    delete ToExtract;
5652290e754061f1393bb96b1808ac33dc03399c939Chris Lattner    return false;
5662290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  }
5675e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5682290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  // Otherwise, block extraction succeeded.  Link the two program fragments back
5692290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  // together.
5702290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  delete ToExtract;
5715e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
57290c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
57390c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  for (Module::iterator I = Extracted->begin(), E = Extracted->end();
57490c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner       I != E; ++I)
5755cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer    if (!I->isDeclaration())
576fa1af1344910ee975f50ffdddf605c26f80ef016Chris Lattner      MisCompFunctions.push_back(std::make_pair(I->getName(),
577fa1af1344910ee975f50ffdddf605c26f80ef016Chris Lattner                                                I->getFunctionType()));
57890c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner
5792290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  std::string ErrorMsg;
580e4874029c37c4b14d0646289f18e5f2a1b03fdc2Reid Spencer  if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
58165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << ": Error linking modules together:"
58265f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrorMsg << '\n';
5832290e754061f1393bb96b1808ac33dc03399c939Chris Lattner    exit(1);
5842290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  }
58590c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  delete Extracted;
5865e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5872290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  // Set the new program and delete the old one.
5882290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  BD.setNewProgram(ProgClone);
5895e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5902290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  // Update the list of miscompiled functions.
5912290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  MiscompiledFunctions.clear();
5925e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
59390c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
594ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer    Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
59590c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    assert(NewF && "Function not found??");
596ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer    assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
597ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer           "Function has wrong type??");
59890c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    MiscompiledFunctions.push_back(NewF);
59990c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  }
6002290e754061f1393bb96b1808ac33dc03399c939Chris Lattner
6012290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  return true;
6025e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner}
6035e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
6045e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
605b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// DebugAMiscompilation - This is a generic driver to narrow down
606b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// miscompilations, either in an optimization or a code generator.
6078c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
608b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattnerstatic std::vector<Function*>
609b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris LattnerDebugAMiscompilation(BugDriver &BD,
61022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                     bool (*TestFn)(BugDriver &, Module *, Module *,
61122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                    std::string &),
61222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                     std::string &Error) {
613640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Okay, now that we have reduced the list of passes which are causing the
614640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // failure, see if we can pin down which functions are being
615640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // miscompiled... first build a list of all of the non-external functions in
616640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // the program.
617640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  std::vector<Function*> MiscompiledFunctions;
618b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  Module *Prog = BD.getProgram();
619b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
6205cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer    if (!I->isDeclaration())
621640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner      MiscompiledFunctions.push_back(I);
6224a10645c70199c8d8567fbc46312158c419720abChris Lattner
623640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Do the reduction...
624f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner  if (!BugpointIsInterrupted)
62522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
62622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                                       Error);
62722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
62822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return MiscompiledFunctions;
629640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
630ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "\n*** The following function"
631ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
632ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << " being miscompiled: ";
633640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  PrintFunctionList(MiscompiledFunctions);
634ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << '\n';
6354a10645c70199c8d8567fbc46312158c419720abChris Lattner
636a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  // See if we can rip any loops out of the miscompiled functions and still
637a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  // trigger the problem.
638dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer
63922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!BugpointIsInterrupted && !DisableLoopExtraction) {
64022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
64122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
64222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return MiscompiledFunctions;
64322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (Ret) {
64422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // Okay, we extracted some loops and the problem still appears.  See if
64522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // we can eliminate some of the created functions from being candidates.
64622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      DisambiguateGlobalSymbols(BD.getProgram());
64722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky
64822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // Do the reduction...
64922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!BugpointIsInterrupted)
65022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
65122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                                           Error);
65222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Error.empty())
65322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        return MiscompiledFunctions;
65422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky
65522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << "\n*** The following function"
65622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
65722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << " being miscompiled: ";
65822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      PrintFunctionList(MiscompiledFunctions);
65922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << '\n';
66022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    }
6615e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  }
6625e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
66322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!BugpointIsInterrupted && !DisableBlockExtraction) {
66422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
66522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
66622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return MiscompiledFunctions;
66722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (Ret) {
66822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // Okay, we extracted some blocks and the problem still appears.  See if
66922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // we can eliminate some of the created functions from being candidates.
67022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      DisambiguateGlobalSymbols(BD.getProgram());
67122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky
67222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // Do the reduction...
67322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
67422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                                         Error);
67522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Error.empty())
67622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        return MiscompiledFunctions;
67722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky
67822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << "\n*** The following function"
67922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
68022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << " being miscompiled: ";
68122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      PrintFunctionList(MiscompiledFunctions);
68222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << '\n';
68322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    }
684a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  }
685a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
686b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  return MiscompiledFunctions;
687b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner}
688b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
689a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// TestOptimizer - This is the predicate function used to check to see if the
690a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// "Test" portion of the program is misoptimized.  If so, return true.  In any
691a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// case, both module arguments are deleted.
6928c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
69322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckystatic bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
69422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                          std::string &Error) {
695b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  // Run the optimization passes on ToOptimize, producing a transformed version
696b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  // of the functions being tested.
697ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "  Optimizing functions being tested: ";
698b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
699b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner                                     /*AutoDebugCrashes*/true);
700ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "done.\n";
701b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  delete Test;
702b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
703ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "  Checking to see if the merged program executes correctly: ";
70413793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola  bool Broken;
70513793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola  Module *New = TestMergedProgram(BD, Optimized, Safe, true, Error, Broken);
70613793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola  if (New) {
70713793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    outs() << (Broken ? " nope.\n" : " yup.\n");
70813793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    // Delete the original and set the new program.
70913793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola    delete BD.swapProgramIn(New);
71013793264e7cbf58e3b7b0cff3baac8e0b7a11a9dRafael Espindola  }
711b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  return Broken;
712b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner}
713b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
714b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
715b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// debugMiscompilation - This method is used when the passes selected are not
716b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// crashing, but the generated output is semantically different from the
717b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// input.
718b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner///
71922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckyvoid BugDriver::debugMiscompilation(std::string *Error) {
720b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  // Make sure something was miscompiled...
721f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner  if (!BugpointIsInterrupted)
72222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
72322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (Error->empty())
72422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        errs() << "*** Optimized program matches reference output!  No problem"
72522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky               << " detected...\nbugpoint can't help you with your problem!\n";
72622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return;
727f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner    }
728b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
729ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "\n*** Found miscompiling pass"
730ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << (getPassesToRun().size() == 1 ? "" : "es") << ": "
731ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << getPassesString(getPassesToRun()) << '\n';
732bae1b71cbb930e419df03db209ebc547a0e4ec72Rafael Espindola  EmitProgressBitcode(Program, "passinput");
733b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
73422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  std::vector<Function *> MiscompiledFunctions =
73522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    DebugAMiscompilation(*this, TestOptimizer, *Error);
73622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error->empty())
73722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return;
738b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
7398ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  // Output a bunch of bitcode files for the user...
740ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Outputting reduced bitcode files which expose the problem:\n";
7411ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola  ValueToValueMapTy VMap;
742e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToNotOptimize = CloneModule(getProgram(), VMap);
743efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
744d50330cd02b00c8e3de40e8544c45701b9891d87Dan Gohman                                                 MiscompiledFunctions,
745e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                 VMap);
746be21ca54e08339ede5dd4bbb882182d22e274988Chris Lattner
747ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "  Non-optimized portion: ";
748bae1b71cbb930e419df03db209ebc547a0e4ec72Rafael Espindola  EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
749bae1b71cbb930e419df03db209ebc547a0e4ec72Rafael Espindola  delete ToNotOptimize;  // Delete hacked module.
7503da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
751ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "  Portion that is input to optimizer: ";
752bae1b71cbb930e419df03db209ebc547a0e4ec72Rafael Espindola  EmitProgressBitcode(ToOptimize, "tooptimize");
753bae1b71cbb930e419df03db209ebc547a0e4ec72Rafael Espindola  delete ToOptimize;      // Delete hacked module.
7544a10645c70199c8d8567fbc46312158c419720abChris Lattner
75522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  return;
7564a10645c70199c8d8567fbc46312158c419720abChris Lattner}
757d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
758a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// CleanupAndPrepareModules - Get the specified modules ready for code
759a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// generator testing.
7608c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
761a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattnerstatic void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
762a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner                                     Module *Safe) {
763a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Clean up the modules, removing extra cruft that we don't need anymore...
764a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  Test = BD.performFinalCleanups(Test);
765a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
766a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // If we are executing the JIT, we have several nasty issues to take care of.
767a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  if (!BD.isExecutingJIT()) return;
768a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
769a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // First, if the main function is in the Safe module, we must add a stub to
770a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // the Test module to call into it.  Thus, we create a new function `main'
771a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // which just calls the old one.
772688b0490e22eb67623f5aaa24406209be74efcb2Reid Spencer  if (Function *oldMain = Safe->getFunction("main"))
7735cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer    if (!oldMain->isDeclaration()) {
774a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Rename it
775a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      oldMain->setName("llvm_bugpoint_old_main");
776a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Create a NEW `main' function with same type in the test module.
777051a950000e21935165db56695e35bade668193bGabor Greif      Function *newMain = Function::Create(oldMain->getFunctionType(),
778051a950000e21935165db56695e35bade668193bGabor Greif                                           GlobalValue::ExternalLinkage,
779051a950000e21935165db56695e35bade668193bGabor Greif                                           "main", Test);
780a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Create an `oldmain' prototype in the test module, which will
781a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // corresponds to the real main function in the same module.
782051a950000e21935165db56695e35bade668193bGabor Greif      Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
783051a950000e21935165db56695e35bade668193bGabor Greif                                                GlobalValue::ExternalLinkage,
784051a950000e21935165db56695e35bade668193bGabor Greif                                                oldMain->getName(), Test);
785a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Set up and remember the argument list for the main function.
786a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      std::vector<Value*> args;
7875a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos      for (Function::arg_iterator
7885a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos             I = newMain->arg_begin(), E = newMain->arg_end(),
7895a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos             OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
7906bc41e8a74d1756da0003641bfebd02a3d6d9586Owen Anderson        I->setName(OI->getName());    // Copy argument names from oldMain
791a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        args.push_back(I);
792a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      }
793a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
794a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Call the old main function and return its result
7951d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson      BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
796051a950000e21935165db56695e35bade668193bGabor Greif      CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
797051a950000e21935165db56695e35bade668193bGabor Greif                                        "", BB);
7983da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
799a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // If the type of old function wasn't void, return value of call
8001d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson      ReturnInst::Create(Safe->getContext(), call, BB);
801a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    }
802a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
803a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // The second nasty issue we must deal with in the JIT is that the Safe
804a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // module cannot directly reference any functions defined in the test
805a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // module.  Instead, we use a JIT API call to dynamically resolve the
806a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // symbol.
8073da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
808a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Add the resolver to the Safe module.
809a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Prototype: void *getPointerToNamedFunction(const char* Name)
8102db43c864e8372823d961d961ca520ed20edca82Chris Lattner  Constant *resolverFunc =
811a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    Safe->getOrInsertFunction("getPointerToNamedFunction",
812ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands                    Type::getInt8PtrTy(Safe->getContext()),
813ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands                    Type::getInt8PtrTy(Safe->getContext()),
8141d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                       (Type *)0);
8153da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
816a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Use the function we just added to get addresses of functions we need.
817dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman  for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
8185cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer    if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
819a3355ffb3d30d19d226bbb75707991c60f236e37Duncan Sands        !F->isIntrinsic() /* ignore intrinsics */) {
820688b0490e22eb67623f5aaa24406209be74efcb2Reid Spencer      Function *TestFn = Test->getFunction(F->getName());
821a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
822a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Don't forward functions which are external in the test module too.
8235cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer      if (TestFn && !TestFn->isDeclaration()) {
824a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        // 1. Add a string constant with its name to the global file
8251d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
826a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        GlobalVariable *funcName =
827e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson          new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
8283da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman                             GlobalValue::InternalLinkage, InitArray,
829e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson                             F->getName() + "_name");
830a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
831a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
832a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        // sbyte* so it matches the signature of the resolver function.
833a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
834a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        // GetElementPtr *funcName, ulong 0, ulong 0
8351d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        std::vector<Constant*> GEPargs(2,
8361d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                     Constant::getNullValue(Type::getInt32Ty(F->getContext())));
8379adc0abad3c3ed40a268ccbcee0c74cb9e1359feOwen Anderson        Value *GEP =
838baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson                ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
839a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        std::vector<Value*> ResolverArgs;
840a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        ResolverArgs.push_back(GEP);
841a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
842de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman        // Rewrite uses of F in global initializers, etc. to uses of a wrapper
843de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman        // function that dynamically resolves the calls to F via our JIT API
844a3efca16f2688981672deeb718909cf6acbe474eChris Lattner        if (!F->use_empty()) {
845a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          // Create a new global to hold the cached function pointer.
8469e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson          Constant *NullPtr = ConstantPointerNull::get(F->getType());
847a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          GlobalVariable *Cache =
848e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson            new GlobalVariable(*F->getParent(), F->getType(),
849e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson                               false, GlobalValue::InternalLinkage,
850e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson                               NullPtr,F->getName()+".fpcache");
85100b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
852de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          // Construct a new stub function that will re-route calls to F
853dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          const FunctionType *FuncTy = F->getFunctionType();
854051a950000e21935165db56695e35bade668193bGabor Greif          Function *FuncWrapper = Function::Create(FuncTy,
855051a950000e21935165db56695e35bade668193bGabor Greif                                                   GlobalValue::InternalLinkage,
856051a950000e21935165db56695e35bade668193bGabor Greif                                                   F->getName() + "_wrapper",
857051a950000e21935165db56695e35bade668193bGabor Greif                                                   F->getParent());
8581d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          BasicBlock *EntryBB  = BasicBlock::Create(F->getContext(),
8591d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                                    "entry", FuncWrapper);
8601d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
8611d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                                    "usecache", FuncWrapper);
8621d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
8631d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                                    "lookupfp", FuncWrapper);
86400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
865a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          // Check to see if we already looked up the value.
866a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
867333c40096561218bc3597cf153c0a3895274414cOwen Anderson          Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
868333c40096561218bc3597cf153c0a3895274414cOwen Anderson                                       NullPtr, "isNull");
869051a950000e21935165db56695e35bade668193bGabor Greif          BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
87000b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
871de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          // Resolve the call to function F via the JIT API:
872de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          //
873de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          // call resolver(GetElementPtr...)
874b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif          CallInst *Resolver =
875b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif            CallInst::Create(resolverFunc, ResolverArgs.begin(),
876b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif                             ResolverArgs.end(), "resolver", LookupBB);
877b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif
878b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif          // Cast the result from the resolver to correctly-typed function.
879b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif          CastInst *CastedResolver =
880b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif            new BitCastInst(Resolver,
881debcb01b0f0a15f568ca69e8f288fade4bfc7297Owen Anderson                            PointerType::getUnqual(F->getFunctionType()),
882b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif                            "resolverCast", LookupBB);
8833da59db637a887474c1b1346c1f3ccf53b6c4663Reid Spencer
884a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          // Save the value in our cache.
885a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          new StoreInst(CastedResolver, Cache, LookupBB);
886051a950000e21935165db56695e35bade668193bGabor Greif          BranchInst::Create(DoCallBB, LookupBB);
88700b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
8883ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad          PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
889b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif                                             "fp", DoCallBB);
890a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          FuncPtr->addIncoming(CastedResolver, LookupBB);
891a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          FuncPtr->addIncoming(CachedVal, EntryBB);
89200b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
893a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          // Save the argument list.
894dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          std::vector<Value*> Args;
8955a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos          for (Function::arg_iterator i = FuncWrapper->arg_begin(),
8965a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos                 e = FuncWrapper->arg_end(); i != e; ++i)
897dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman            Args.push_back(i);
898dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman
899dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          // Pass on the arguments to the real function, return its result
900e49a13e7260b83ce56d01446f2a165cc9f35da7fDan Gohman          if (F->getReturnType()->isVoidTy()) {
901051a950000e21935165db56695e35bade668193bGabor Greif            CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
9021d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson            ReturnInst::Create(F->getContext(), DoCallBB);
903dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          } else {
904051a950000e21935165db56695e35bade668193bGabor Greif            CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
905051a950000e21935165db56695e35bade668193bGabor Greif                                              "retval", DoCallBB);
9061d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson            ReturnInst::Create(F->getContext(),Call, DoCallBB);
907dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          }
90800b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
909de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          // Use the wrapper function instead of the old function
910de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          F->replaceAllUsesWith(FuncWrapper);
911dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman        }
912a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      }
913a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    }
914a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
915a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
916a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  if (verifyModule(*Test) || verifyModule(*Safe)) {
91765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << "Bugpoint has a bug, which corrupted a module!!\n";
918a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    abort();
919a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
920a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner}
921a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
922a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
923a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
924a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// TestCodeGenerator - This is the predicate function used to check to see if
925a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// the "Test" portion of the program is miscompiled by the code generator under
926a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// test.  If so, return true.  In any case, both module arguments are deleted.
9278c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
92822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckystatic bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
92922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::string &Error) {
930a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  CleanupAndPrepareModules(BD, Test, Safe);
931a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
93297182985d530dbef488696c95a39c14fe56c995bReid Spencer  sys::Path TestModuleBC("bugpoint.test.bc");
93351c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  std::string ErrMsg;
93451c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  if (TestModuleBC.makeUnique(true, &ErrMsg)) {
93565f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << "Error making unique filename: "
93665f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrMsg << "\n";
93751c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer    exit(1);
93851c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  }
93974382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner  if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
94074382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    errs() << "Error writing bitcode to `" << TestModuleBC.str()
94174382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << "'\nExiting.";
942a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    exit(1);
943a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
944a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  delete Test;
945a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
946c9c08fb3a7fb5e8ea3e1477a88507704c7a70ba1Michael J. Spencer  FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
947bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola
948a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Make the shared library
94997182985d530dbef488696c95a39c14fe56c995bReid Spencer  sys::Path SafeModuleBC("bugpoint.safe.bc");
95051c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
95165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << "Error making unique filename: "
95265f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrMsg << "\n";
95351c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer    exit(1);
95451c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  }
955a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
95674382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner  if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
95774382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
95874382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << "'\nExiting.";
959a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    exit(1);
960a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
961bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola
962c9c08fb3a7fb5e8ea3e1477a88507704c7a70ba1Michael J. Spencer  FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
963bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola
96422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
96522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
9662706387d37b30fc191c5b74987dc139e1835c52dBenjamin Kramer    return false;
967a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  delete Safe;
968a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
969c9c08fb3a7fb5e8ea3e1477a88507704c7a70ba1Michael J. Spencer  FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
970bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola
971a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Run the code generator on the `Test' code, loading the shared library.
972a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // The function returns whether or not the new output differs from reference.
97310757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola  bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
97410757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola                               SharedObject, false, &Error);
97522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
97622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return false;
977a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
978a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  if (Result)
97965f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << ": still failing!\n";
980a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  else
98165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << ": didn't fail.\n";
982a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
983a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  return Result;
984a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner}
985a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
986a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
9878c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
9888c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
98922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckybool BugDriver::debugCodeGenerator(std::string *Error) {
99070ef449741da8b1ef035e04a55958652a0200ba1Dan Gohman  if ((void*)SafeInterpreter == (void*)Interpreter) {
99110757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola    std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
99210757dd8e1a66128b205bd04797c8aed0cb7a1bdRafael Espindola                                              Error);
99322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (Error->empty()) {
99422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
99522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "the reference diff.  This may be due to a\n    front-end "
99622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "bug or a bug in the original program, but this can also "
99722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "happen if bugpoint isn't running the program with the "
99822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "right flags or input.\n    I left the result of executing "
99922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "the program with the \"safe\" backend in this file for "
100022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "you: '"
100122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << Result << "'.\n";
100222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    }
1003a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    return true;
1004a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
1005a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1006a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  DisambiguateGlobalSymbols(Program);
1007a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
100822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
100922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                                      *Error);
101022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error->empty())
101122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return true;
1012a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1013a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Split the module into the two halves of the program we want.
10141ed219a9d2279ce5a5bbcf16d9b7ccc05cce638cRafael Espindola  ValueToValueMapTy VMap;
1015e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1016e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
1017a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1018a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Condition the modules
1019a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1020a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
102197182985d530dbef488696c95a39c14fe56c995bReid Spencer  sys::Path TestModuleBC("bugpoint.test.bc");
102251c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  std::string ErrMsg;
102351c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  if (TestModuleBC.makeUnique(true, &ErrMsg)) {
102465f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << getToolName() << "Error making unique filename: "
102565f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrMsg << "\n";
102651c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer    exit(1);
102751c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  }
102897182985d530dbef488696c95a39c14fe56c995bReid Spencer
102974382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner  if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
103074382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    errs() << "Error writing bitcode to `" << TestModuleBC.str()
103174382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << "'\nExiting.";
1032a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    exit(1);
1033a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
1034a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  delete ToCodeGen;
1035a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1036a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Make the shared library
103797182985d530dbef488696c95a39c14fe56c995bReid Spencer  sys::Path SafeModuleBC("bugpoint.safe.bc");
103851c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
103965f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << getToolName() << "Error making unique filename: "
104065f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrMsg << "\n";
104151c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer    exit(1);
104251c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  }
104397182985d530dbef488696c95a39c14fe56c995bReid Spencer
104474382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner  if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
104574382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
104674382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << "'\nExiting.";
1047a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    exit(1);
1048a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
104922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
105022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error->empty())
105122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return true;
1052a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  delete ToNotCodeGen;
1053a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1054ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "You can reproduce the problem with the command line: \n";
1055a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  if (isExecutingJIT()) {
105674382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    outs() << "  lli -load " << SharedObject << " " << TestModuleBC.str();
1057a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  } else {
10588d0e1bcc921c942e979b0925051c663590bd618fNick Lewycky    outs() << "  llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
105974382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << ".s\n";
106074382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    outs() << "  gcc " << SharedObject << " " << TestModuleBC.str()
106174382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner              << ".s -o " << TestModuleBC.str() << ".exe";
106259615f0f85e2ac99e012cb81934d002faebd405aChris Lattner#if defined (HAVE_LINK_R)
1063ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " -Wl,-R.";
106459615f0f85e2ac99e012cb81934d002faebd405aChris Lattner#endif
1065ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "\n";
106674382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    outs() << "  " << TestModuleBC.str() << ".exe";
1067a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
106822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1069ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " " << InputArgv[i];
1070ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << '\n';
1071ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "The shared object was created with:\n  llc -march=c "
107274382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner         << SafeModuleBC.str() << " -o temporary.c\n"
1073ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar         << "  gcc -xc temporary.c -O2 -o " << SharedObject;
1074ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar  if (TargetTriple.getArch() == Triple::sparc)
1075ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar    outs() << " -G";              // Compile a shared library, `-G' for Sparc
1076ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar  else
1077ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar    outs() << " -fPIC -shared";   // `-shared' for Linux/X86, maybe others
1078ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar
1079ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar  outs() << " -fno-strict-aliasing\n";
1080a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1081a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  return false;
1082a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner}
1083