Miscompilation.cpp revision 276479
1193323Sed//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements optimizer and code generation miscompilation debugging
11193323Sed// support.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#include "BugDriver.h"
16193323Sed#include "ListReducer.h"
17198090Srdivacky#include "ToolRunner.h"
18249423Sdim#include "llvm/Config/config.h"   // for HAVE_LINK_R
19249423Sdim#include "llvm/IR/Constants.h"
20249423Sdim#include "llvm/IR/DerivedTypes.h"
21249423Sdim#include "llvm/IR/Instructions.h"
22249423Sdim#include "llvm/IR/Module.h"
23276479Sdim#include "llvm/IR/Verifier.h"
24276479Sdim#include "llvm/Linker/Linker.h"
25193323Sed#include "llvm/Pass.h"
26193323Sed#include "llvm/Support/CommandLine.h"
27193323Sed#include "llvm/Support/FileUtilities.h"
28249423Sdim#include "llvm/Transforms/Utils/Cloning.h"
29193323Sedusing namespace llvm;
30193323Sed
31193323Sednamespace llvm {
32198090Srdivacky  extern cl::opt<std::string> OutputPrefix;
33193323Sed  extern cl::list<std::string> InputArgv;
34193323Sed}
35193323Sed
36193323Sednamespace {
37221337Sdim  static llvm::cl::opt<bool>
38221337Sdim    DisableLoopExtraction("disable-loop-extraction",
39193323Sed        cl::desc("Don't extract loops when searching for miscompilations"),
40193323Sed        cl::init(false));
41221337Sdim  static llvm::cl::opt<bool>
42221337Sdim    DisableBlockExtraction("disable-block-extraction",
43198090Srdivacky        cl::desc("Don't extract blocks when searching for miscompilations"),
44198090Srdivacky        cl::init(false));
45193323Sed
46212793Sdim  class ReduceMiscompilingPasses : public ListReducer<std::string> {
47193323Sed    BugDriver &BD;
48193323Sed  public:
49193323Sed    ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
50193323Sed
51276479Sdim    TestResult doTest(std::vector<std::string> &Prefix,
52276479Sdim                      std::vector<std::string> &Suffix,
53276479Sdim                      std::string &Error) override;
54193323Sed  };
55193323Sed}
56193323Sed
57193323Sed/// TestResult - After passes have been split into a test group and a control
58193323Sed/// group, see if they still break the program.
59193323Sed///
60193323SedReduceMiscompilingPasses::TestResult
61212793SdimReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
62212793Sdim                                 std::vector<std::string> &Suffix,
63207618Srdivacky                                 std::string &Error) {
64193323Sed  // First, run the program with just the Suffix passes.  If it is still broken
65193323Sed  // with JUST the kept passes, discard the prefix passes.
66198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Suffix)
67198090Srdivacky         << "' compiles correctly: ";
68193323Sed
69193323Sed  std::string BitcodeResult;
70212793Sdim  if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
71212793Sdim                   true/*quiet*/)) {
72198090Srdivacky    errs() << " Error running this sequence of passes"
73198090Srdivacky           << " on the input program!\n";
74193323Sed    BD.setPassesToRun(Suffix);
75212793Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error",  false);
76193323Sed    exit(BD.debugOptimizerCrash());
77193323Sed  }
78221337Sdim
79193323Sed  // Check to see if the finished program matches the reference output...
80212793Sdim  bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
81212793Sdim                             true /*delete bitcode*/, &Error);
82207618Srdivacky  if (!Error.empty())
83207618Srdivacky    return InternalError;
84207618Srdivacky  if (Diff) {
85198090Srdivacky    outs() << " nope.\n";
86193323Sed    if (Suffix.empty()) {
87198090Srdivacky      errs() << BD.getToolName() << ": I'm confused: the test fails when "
88198090Srdivacky             << "no passes are run, nondeterministic program?\n";
89193323Sed      exit(1);
90193323Sed    }
91193323Sed    return KeepSuffix;         // Miscompilation detected!
92193323Sed  }
93198090Srdivacky  outs() << " yup.\n";      // No miscompilation!
94193323Sed
95193323Sed  if (Prefix.empty()) return NoFailure;
96193323Sed
97193323Sed  // Next, see if the program is broken if we run the "prefix" passes first,
98193323Sed  // then separately run the "kept" passes.
99198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Prefix)
100198090Srdivacky         << "' compiles correctly: ";
101193323Sed
102193323Sed  // If it is not broken with the kept passes, it's possible that the prefix
103193323Sed  // passes must be run before the kept passes to break it.  If the program
104193323Sed  // WORKS after the prefix passes, but then fails if running the prefix AND
105193323Sed  // kept passes, we can update our bitcode file to include the result of the
106193323Sed  // prefix passes, then discard the prefix passes.
107193323Sed  //
108212793Sdim  if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false/*delete*/,
109212793Sdim                   true/*quiet*/)) {
110198090Srdivacky    errs() << " Error running this sequence of passes"
111198090Srdivacky           << " on the input program!\n";
112193323Sed    BD.setPassesToRun(Prefix);
113212793Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error",  false);
114193323Sed    exit(BD.debugOptimizerCrash());
115193323Sed  }
116193323Sed
117193323Sed  // If the prefix maintains the predicate by itself, only keep the prefix!
118212793Sdim  Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
119207618Srdivacky  if (!Error.empty())
120207618Srdivacky    return InternalError;
121207618Srdivacky  if (Diff) {
122198090Srdivacky    outs() << " nope.\n";
123261991Sdim    sys::fs::remove(BitcodeResult);
124193323Sed    return KeepPrefix;
125193323Sed  }
126198090Srdivacky  outs() << " yup.\n";      // No miscompilation!
127193323Sed
128193323Sed  // Ok, so now we know that the prefix passes work, try running the suffix
129193323Sed  // passes on the result of the prefix passes.
130193323Sed  //
131276479Sdim  std::unique_ptr<Module> PrefixOutput(
132276479Sdim      ParseInputFile(BitcodeResult, BD.getContext()));
133261991Sdim  if (!PrefixOutput) {
134198090Srdivacky    errs() << BD.getToolName() << ": Error reading bitcode file '"
135198090Srdivacky           << BitcodeResult << "'!\n";
136193323Sed    exit(1);
137193323Sed  }
138261991Sdim  sys::fs::remove(BitcodeResult);
139193323Sed
140193323Sed  // Don't check if there are no passes in the suffix.
141193323Sed  if (Suffix.empty())
142193323Sed    return NoFailure;
143193323Sed
144198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Suffix)
145193323Sed            << "' passes compile correctly after the '"
146193323Sed            << getPassesString(Prefix) << "' passes: ";
147193323Sed
148276479Sdim  std::unique_ptr<Module> OriginalInput(
149276479Sdim      BD.swapProgramIn(PrefixOutput.release()));
150212793Sdim  if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
151212793Sdim                   true/*quiet*/)) {
152198090Srdivacky    errs() << " Error running this sequence of passes"
153198090Srdivacky           << " on the input program!\n";
154193323Sed    BD.setPassesToRun(Suffix);
155212793Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error",  false);
156193323Sed    exit(BD.debugOptimizerCrash());
157193323Sed  }
158193323Sed
159193323Sed  // Run the result...
160212793Sdim  Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
161212793Sdim                        true /*delete bitcode*/, &Error);
162207618Srdivacky  if (!Error.empty())
163207618Srdivacky    return InternalError;
164207618Srdivacky  if (Diff) {
165198090Srdivacky    outs() << " nope.\n";
166193323Sed    return KeepSuffix;
167193323Sed  }
168193323Sed
169193323Sed  // Otherwise, we must not be running the bad pass anymore.
170198090Srdivacky  outs() << " yup.\n";      // No miscompilation!
171208599Srdivacky  // Restore orig program & free test.
172276479Sdim  delete BD.swapProgramIn(OriginalInput.release());
173193323Sed  return NoFailure;
174193323Sed}
175193323Sed
176193323Sednamespace {
177193323Sed  class ReduceMiscompilingFunctions : public ListReducer<Function*> {
178193323Sed    BugDriver &BD;
179207618Srdivacky    bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
180193323Sed  public:
181193323Sed    ReduceMiscompilingFunctions(BugDriver &bd,
182207618Srdivacky                                bool (*F)(BugDriver &, Module *, Module *,
183207618Srdivacky                                          std::string &))
184193323Sed      : BD(bd), TestFn(F) {}
185193323Sed
186276479Sdim    TestResult doTest(std::vector<Function*> &Prefix,
187276479Sdim                      std::vector<Function*> &Suffix,
188276479Sdim                      std::string &Error) override {
189207618Srdivacky      if (!Suffix.empty()) {
190207618Srdivacky        bool Ret = TestFuncs(Suffix, Error);
191207618Srdivacky        if (!Error.empty())
192207618Srdivacky          return InternalError;
193207618Srdivacky        if (Ret)
194207618Srdivacky          return KeepSuffix;
195207618Srdivacky      }
196207618Srdivacky      if (!Prefix.empty()) {
197207618Srdivacky        bool Ret = TestFuncs(Prefix, Error);
198207618Srdivacky        if (!Error.empty())
199207618Srdivacky          return InternalError;
200207618Srdivacky        if (Ret)
201207618Srdivacky          return KeepPrefix;
202207618Srdivacky      }
203193323Sed      return NoFailure;
204193323Sed    }
205193323Sed
206212793Sdim    bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
207193323Sed  };
208193323Sed}
209193323Sed
210193323Sed/// TestMergedProgram - Given two modules, link them together and run the
211212793Sdim/// program, checking to see if the program matches the diff. If there is
212212793Sdim/// an error, return NULL. If not, return the merged module. The Broken argument
213212793Sdim/// will be set to true if the output is different. If the DeleteInputs
214212793Sdim/// argument is set to true then this function deletes both input
215212793Sdim/// modules before it returns.
216193323Sed///
217212793Sdimstatic Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
218212793Sdim                                 bool DeleteInputs, std::string &Error,
219212793Sdim                                 bool &Broken) {
220193323Sed  // Link the two portions of the program back to together.
221193323Sed  std::string ErrorMsg;
222193323Sed  if (!DeleteInputs) {
223193323Sed    M1 = CloneModule(M1);
224193323Sed    M2 = CloneModule(M2);
225193323Sed  }
226226584Sdim  if (Linker::LinkModules(M1, M2, Linker::DestroySource, &ErrorMsg)) {
227198090Srdivacky    errs() << BD.getToolName() << ": Error linking modules together:"
228198090Srdivacky           << ErrorMsg << '\n';
229193323Sed    exit(1);
230193323Sed  }
231193323Sed  delete M2;   // We are done with this module.
232193323Sed
233212793Sdim  // Execute the program.
234212793Sdim  Broken = BD.diffProgram(M1, "", "", false, &Error);
235207618Srdivacky  if (!Error.empty()) {
236212793Sdim    // Delete the linked module
237212793Sdim    delete M1;
238276479Sdim    return nullptr;
239207618Srdivacky  }
240212793Sdim  return M1;
241193323Sed}
242193323Sed
243193323Sed/// TestFuncs - split functions in a Module into two groups: those that are
244193323Sed/// under consideration for miscompilation vs. those that are not, and test
245193323Sed/// accordingly. Each group of functions becomes a separate Module.
246193323Sed///
247212793Sdimbool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
248212793Sdim                                            std::string &Error) {
249193323Sed  // Test to see if the function is misoptimized if we ONLY run it on the
250193323Sed  // functions listed in Funcs.
251198090Srdivacky  outs() << "Checking to see if the program is misoptimized when "
252198090Srdivacky         << (Funcs.size()==1 ? "this function is" : "these functions are")
253198090Srdivacky         << " run through the pass"
254198090Srdivacky         << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
255193323Sed  PrintFunctionList(Funcs);
256198090Srdivacky  outs() << '\n';
257193323Sed
258212793Sdim  // Create a clone for two reasons:
259212793Sdim  // * If the optimization passes delete any function, the deleted function
260212793Sdim  //   will be in the clone and Funcs will still point to valid memory
261212793Sdim  // * If the optimization passes use interprocedural information to break
262212793Sdim  //   a function, we want to continue with the original function. Otherwise
263212793Sdim  //   we can conclude that a function triggers the bug when in fact one
264212793Sdim  //   needs a larger set of original functions to do so.
265218885Sdim  ValueToValueMapTy VMap;
266212793Sdim  Module *Clone = CloneModule(BD.getProgram(), VMap);
267212793Sdim  Module *Orig = BD.swapProgramIn(Clone);
268212793Sdim
269212793Sdim  std::vector<Function*> FuncsOnClone;
270212793Sdim  for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
271212793Sdim    Function *F = cast<Function>(VMap[Funcs[i]]);
272212793Sdim    FuncsOnClone.push_back(F);
273212793Sdim  }
274212793Sdim
275193323Sed  // Split the module into the two halves of the program we want.
276212793Sdim  VMap.clear();
277210006Srdivacky  Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
278212793Sdim  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
279210006Srdivacky                                                 VMap);
280193323Sed
281193323Sed  // Run the predicate, note that the predicate will delete both input modules.
282212793Sdim  bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
283212793Sdim
284212793Sdim  delete BD.swapProgramIn(Orig);
285212793Sdim
286212793Sdim  return Broken;
287193323Sed}
288193323Sed
289202878Srdivacky/// DisambiguateGlobalSymbols - Give anonymous global values names.
290193323Sed///
291193323Sedstatic void DisambiguateGlobalSymbols(Module *M) {
292193323Sed  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
293202878Srdivacky       I != E; ++I)
294202878Srdivacky    if (!I->hasName())
295202878Srdivacky      I->setName("anon_global");
296202878Srdivacky  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
297202878Srdivacky    if (!I->hasName())
298202878Srdivacky      I->setName("anon_fn");
299193323Sed}
300193323Sed
301193323Sed/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
302193323Sed/// check to see if we can extract the loops in the region without obscuring the
303193323Sed/// bug.  If so, it reduces the amount of code identified.
304193323Sed///
305193323Sedstatic bool ExtractLoops(BugDriver &BD,
306207618Srdivacky                         bool (*TestFn)(BugDriver &, Module *, Module *,
307207618Srdivacky                                        std::string &),
308207618Srdivacky                         std::vector<Function*> &MiscompiledFunctions,
309207618Srdivacky                         std::string &Error) {
310193323Sed  bool MadeChange = false;
311193323Sed  while (1) {
312193323Sed    if (BugpointIsInterrupted) return MadeChange;
313221337Sdim
314218885Sdim    ValueToValueMapTy VMap;
315210006Srdivacky    Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
316193323Sed    Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
317193323Sed                                                   MiscompiledFunctions,
318210006Srdivacky                                                   VMap);
319193323Sed    Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
320193323Sed    if (!ToOptimizeLoopExtracted) {
321193323Sed      // If the loop extractor crashed or if there were no extractible loops,
322193323Sed      // then this chapter of our odyssey is over with.
323193323Sed      delete ToNotOptimize;
324193323Sed      delete ToOptimize;
325193323Sed      return MadeChange;
326193323Sed    }
327193323Sed
328198090Srdivacky    errs() << "Extracted a loop from the breaking portion of the program.\n";
329193323Sed
330193323Sed    // Bugpoint is intentionally not very trusting of LLVM transformations.  In
331193323Sed    // particular, we're not going to assume that the loop extractor works, so
332193323Sed    // we're going to test the newly loop extracted program to make sure nothing
333193323Sed    // has broken.  If something broke, then we'll inform the user and stop
334193323Sed    // extraction.
335193323Sed    AbstractInterpreter *AI = BD.switchToSafeInterpreter();
336212793Sdim    bool Failure;
337212793Sdim    Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize,
338212793Sdim                                    false, Error, Failure);
339212793Sdim    if (!New)
340207618Srdivacky      return false;
341261991Sdim
342212793Sdim    // Delete the original and set the new program.
343261991Sdim    Module *Old = BD.swapProgramIn(New);
344261991Sdim    for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
345261991Sdim      MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
346261991Sdim    delete Old;
347261991Sdim
348207618Srdivacky    if (Failure) {
349193323Sed      BD.switchToInterpreter(AI);
350193323Sed
351193323Sed      // Merged program doesn't work anymore!
352198090Srdivacky      errs() << "  *** ERROR: Loop extraction broke the program. :("
353198090Srdivacky             << " Please report a bug!\n";
354198090Srdivacky      errs() << "      Continuing on with un-loop-extracted version.\n";
355193323Sed
356198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
357198090Srdivacky                            ToNotOptimize);
358198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
359198090Srdivacky                            ToOptimize);
360198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
361193323Sed                            ToOptimizeLoopExtracted);
362193323Sed
363221337Sdim      errs() << "Please submit the "
364198090Srdivacky             << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
365193323Sed      delete ToOptimize;
366193323Sed      delete ToNotOptimize;
367193323Sed      delete ToOptimizeLoopExtracted;
368193323Sed      return MadeChange;
369193323Sed    }
370193323Sed    delete ToOptimize;
371193323Sed    BD.switchToInterpreter(AI);
372193323Sed
373198090Srdivacky    outs() << "  Testing after loop extraction:\n";
374193323Sed    // Clone modules, the tester function will free them.
375261991Sdim    Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted, VMap);
376261991Sdim    Module *TNOBackup  = CloneModule(ToNotOptimize, VMap);
377261991Sdim
378261991Sdim    for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
379261991Sdim      MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
380261991Sdim
381207618Srdivacky    Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
382207618Srdivacky    if (!Error.empty())
383207618Srdivacky      return false;
384261991Sdim
385261991Sdim    ToOptimizeLoopExtracted = TOLEBackup;
386261991Sdim    ToNotOptimize = TNOBackup;
387261991Sdim
388207618Srdivacky    if (!Failure) {
389198090Srdivacky      outs() << "*** Loop extraction masked the problem.  Undoing.\n";
390193323Sed      // If the program is not still broken, then loop extraction did something
391193323Sed      // that masked the error.  Stop loop extraction now.
392261991Sdim
393261991Sdim      std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
394261991Sdim      for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i) {
395261991Sdim        Function *F = MiscompiledFunctions[i];
396261991Sdim        MisCompFunctions.push_back(std::make_pair(F->getName(),
397261991Sdim                                                  F->getFunctionType()));
398261991Sdim      }
399261991Sdim
400261991Sdim      std::string ErrorMsg;
401261991Sdim      if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted,
402261991Sdim                              Linker::DestroySource, &ErrorMsg)){
403261991Sdim        errs() << BD.getToolName() << ": Error linking modules together:"
404261991Sdim               << ErrorMsg << '\n';
405261991Sdim        exit(1);
406261991Sdim      }
407261991Sdim
408261991Sdim      MiscompiledFunctions.clear();
409261991Sdim      for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
410261991Sdim        Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
411261991Sdim
412261991Sdim        assert(NewF && "Function not found??");
413261991Sdim        MiscompiledFunctions.push_back(NewF);
414261991Sdim      }
415261991Sdim
416261991Sdim      delete ToOptimizeLoopExtracted;
417261991Sdim      BD.setNewProgram(ToNotOptimize);
418193323Sed      return MadeChange;
419193323Sed    }
420193323Sed
421198090Srdivacky    outs() << "*** Loop extraction successful!\n";
422193323Sed
423226584Sdim    std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
424193323Sed    for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
425193323Sed           E = ToOptimizeLoopExtracted->end(); I != E; ++I)
426193323Sed      if (!I->isDeclaration())
427193323Sed        MisCompFunctions.push_back(std::make_pair(I->getName(),
428193323Sed                                                  I->getFunctionType()));
429193323Sed
430193323Sed    // Okay, great!  Now we know that we extracted a loop and that loop
431193323Sed    // extraction both didn't break the program, and didn't mask the problem.
432193323Sed    // Replace the current program with the loop extracted version, and try to
433193323Sed    // extract another loop.
434193323Sed    std::string ErrorMsg;
435226584Sdim    if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted,
436226584Sdim                            Linker::DestroySource, &ErrorMsg)){
437198090Srdivacky      errs() << BD.getToolName() << ": Error linking modules together:"
438198090Srdivacky             << ErrorMsg << '\n';
439193323Sed      exit(1);
440193323Sed    }
441193323Sed    delete ToOptimizeLoopExtracted;
442193323Sed
443193323Sed    // All of the Function*'s in the MiscompiledFunctions list are in the old
444193323Sed    // module.  Update this list to include all of the functions in the
445193323Sed    // optimized and loop extracted module.
446193323Sed    MiscompiledFunctions.clear();
447193323Sed    for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
448193323Sed      Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
449221337Sdim
450193323Sed      assert(NewF && "Function not found??");
451193323Sed      MiscompiledFunctions.push_back(NewF);
452193323Sed    }
453193323Sed
454193323Sed    BD.setNewProgram(ToNotOptimize);
455193323Sed    MadeChange = true;
456193323Sed  }
457193323Sed}
458193323Sed
459193323Sednamespace {
460193323Sed  class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
461193323Sed    BugDriver &BD;
462207618Srdivacky    bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
463193323Sed    std::vector<Function*> FunctionsBeingTested;
464193323Sed  public:
465193323Sed    ReduceMiscompiledBlocks(BugDriver &bd,
466207618Srdivacky                            bool (*F)(BugDriver &, Module *, Module *,
467207618Srdivacky                                      std::string &),
468193323Sed                            const std::vector<Function*> &Fns)
469193323Sed      : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
470193323Sed
471276479Sdim    TestResult doTest(std::vector<BasicBlock*> &Prefix,
472276479Sdim                      std::vector<BasicBlock*> &Suffix,
473276479Sdim                      std::string &Error) override {
474207618Srdivacky      if (!Suffix.empty()) {
475207618Srdivacky        bool Ret = TestFuncs(Suffix, Error);
476207618Srdivacky        if (!Error.empty())
477207618Srdivacky          return InternalError;
478207618Srdivacky        if (Ret)
479207618Srdivacky          return KeepSuffix;
480207618Srdivacky      }
481207618Srdivacky      if (!Prefix.empty()) {
482207618Srdivacky        bool Ret = TestFuncs(Prefix, Error);
483207618Srdivacky        if (!Error.empty())
484207618Srdivacky          return InternalError;
485207618Srdivacky        if (Ret)
486207618Srdivacky          return KeepPrefix;
487207618Srdivacky      }
488193323Sed      return NoFailure;
489193323Sed    }
490193323Sed
491207618Srdivacky    bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
492193323Sed  };
493193323Sed}
494193323Sed
495193323Sed/// TestFuncs - Extract all blocks for the miscompiled functions except for the
496193323Sed/// specified blocks.  If the problem still exists, return true.
497193323Sed///
498207618Srdivackybool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
499207618Srdivacky                                        std::string &Error) {
500193323Sed  // Test to see if the function is misoptimized if we ONLY run it on the
501193323Sed  // functions listed in Funcs.
502198090Srdivacky  outs() << "Checking to see if the program is misoptimized when all ";
503193323Sed  if (!BBs.empty()) {
504198090Srdivacky    outs() << "but these " << BBs.size() << " blocks are extracted: ";
505193323Sed    for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
506198090Srdivacky      outs() << BBs[i]->getName() << " ";
507198090Srdivacky    if (BBs.size() > 10) outs() << "...";
508193323Sed  } else {
509198090Srdivacky    outs() << "blocks are extracted.";
510193323Sed  }
511198090Srdivacky  outs() << '\n';
512193323Sed
513193323Sed  // Split the module into the two halves of the program we want.
514218885Sdim  ValueToValueMapTy VMap;
515212793Sdim  Module *Clone = CloneModule(BD.getProgram(), VMap);
516212793Sdim  Module *Orig = BD.swapProgramIn(Clone);
517212793Sdim  std::vector<Function*> FuncsOnClone;
518212793Sdim  std::vector<BasicBlock*> BBsOnClone;
519212793Sdim  for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
520212793Sdim    Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
521212793Sdim    FuncsOnClone.push_back(F);
522212793Sdim  }
523212793Sdim  for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
524212793Sdim    BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
525212793Sdim    BBsOnClone.push_back(BB);
526212793Sdim  }
527212793Sdim  VMap.clear();
528212793Sdim
529210006Srdivacky  Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
530193323Sed  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
531212793Sdim                                                 FuncsOnClone,
532210006Srdivacky                                                 VMap);
533193323Sed
534193323Sed  // Try the extraction.  If it doesn't work, then the block extractor crashed
535193323Sed  // or something, in which case bugpoint can't chase down this possibility.
536212793Sdim  if (Module *New = BD.ExtractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
537193323Sed    delete ToOptimize;
538212793Sdim    // Run the predicate,
539212793Sdim    // note that the predicate will delete both input modules.
540212793Sdim    bool Ret = TestFn(BD, New, ToNotOptimize, Error);
541212793Sdim    delete BD.swapProgramIn(Orig);
542212793Sdim    return Ret;
543193323Sed  }
544212793Sdim  delete BD.swapProgramIn(Orig);
545193323Sed  delete ToOptimize;
546193323Sed  delete ToNotOptimize;
547193323Sed  return false;
548193323Sed}
549193323Sed
550193323Sed
551193323Sed/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
552193323Sed/// extract as many basic blocks from the region as possible without obscuring
553193323Sed/// the bug.
554193323Sed///
555193323Sedstatic bool ExtractBlocks(BugDriver &BD,
556207618Srdivacky                          bool (*TestFn)(BugDriver &, Module *, Module *,
557207618Srdivacky                                         std::string &),
558207618Srdivacky                          std::vector<Function*> &MiscompiledFunctions,
559207618Srdivacky                          std::string &Error) {
560193323Sed  if (BugpointIsInterrupted) return false;
561221337Sdim
562193323Sed  std::vector<BasicBlock*> Blocks;
563193323Sed  for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
564193323Sed    for (Function::iterator I = MiscompiledFunctions[i]->begin(),
565193323Sed           E = MiscompiledFunctions[i]->end(); I != E; ++I)
566193323Sed      Blocks.push_back(I);
567193323Sed
568193323Sed  // Use the list reducer to identify blocks that can be extracted without
569193323Sed  // obscuring the bug.  The Blocks list will end up containing blocks that must
570193323Sed  // be retained from the original program.
571193323Sed  unsigned OldSize = Blocks.size();
572193323Sed
573193323Sed  // Check to see if all blocks are extractible first.
574207618Srdivacky  bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
575207618Srdivacky                                  .TestFuncs(std::vector<BasicBlock*>(), Error);
576207618Srdivacky  if (!Error.empty())
577207618Srdivacky    return false;
578207618Srdivacky  if (Ret) {
579193323Sed    Blocks.clear();
580193323Sed  } else {
581207618Srdivacky    ReduceMiscompiledBlocks(BD, TestFn,
582207618Srdivacky                            MiscompiledFunctions).reduceList(Blocks, Error);
583207618Srdivacky    if (!Error.empty())
584207618Srdivacky      return false;
585193323Sed    if (Blocks.size() == OldSize)
586193323Sed      return false;
587193323Sed  }
588193323Sed
589218885Sdim  ValueToValueMapTy VMap;
590210006Srdivacky  Module *ProgClone = CloneModule(BD.getProgram(), VMap);
591193323Sed  Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
592193323Sed                                                MiscompiledFunctions,
593210006Srdivacky                                                VMap);
594193323Sed  Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
595276479Sdim  if (!Extracted) {
596193323Sed    // Weird, extraction should have worked.
597198090Srdivacky    errs() << "Nondeterministic problem extracting blocks??\n";
598193323Sed    delete ProgClone;
599193323Sed    delete ToExtract;
600193323Sed    return false;
601193323Sed  }
602193323Sed
603193323Sed  // Otherwise, block extraction succeeded.  Link the two program fragments back
604193323Sed  // together.
605193323Sed  delete ToExtract;
606193323Sed
607226584Sdim  std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
608193323Sed  for (Module::iterator I = Extracted->begin(), E = Extracted->end();
609193323Sed       I != E; ++I)
610193323Sed    if (!I->isDeclaration())
611193323Sed      MisCompFunctions.push_back(std::make_pair(I->getName(),
612193323Sed                                                I->getFunctionType()));
613193323Sed
614193323Sed  std::string ErrorMsg;
615226584Sdim  if (Linker::LinkModules(ProgClone, Extracted, Linker::DestroySource,
616226584Sdim                          &ErrorMsg)) {
617198090Srdivacky    errs() << BD.getToolName() << ": Error linking modules together:"
618198090Srdivacky           << ErrorMsg << '\n';
619193323Sed    exit(1);
620193323Sed  }
621193323Sed  delete Extracted;
622193323Sed
623193323Sed  // Set the new program and delete the old one.
624193323Sed  BD.setNewProgram(ProgClone);
625193323Sed
626193323Sed  // Update the list of miscompiled functions.
627193323Sed  MiscompiledFunctions.clear();
628193323Sed
629193323Sed  for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
630193323Sed    Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
631193323Sed    assert(NewF && "Function not found??");
632193323Sed    MiscompiledFunctions.push_back(NewF);
633193323Sed  }
634193323Sed
635193323Sed  return true;
636193323Sed}
637193323Sed
638193323Sed
639193323Sed/// DebugAMiscompilation - This is a generic driver to narrow down
640193323Sed/// miscompilations, either in an optimization or a code generator.
641193323Sed///
642193323Sedstatic std::vector<Function*>
643193323SedDebugAMiscompilation(BugDriver &BD,
644207618Srdivacky                     bool (*TestFn)(BugDriver &, Module *, Module *,
645207618Srdivacky                                    std::string &),
646207618Srdivacky                     std::string &Error) {
647193323Sed  // Okay, now that we have reduced the list of passes which are causing the
648193323Sed  // failure, see if we can pin down which functions are being
649193323Sed  // miscompiled... first build a list of all of the non-external functions in
650193323Sed  // the program.
651193323Sed  std::vector<Function*> MiscompiledFunctions;
652193323Sed  Module *Prog = BD.getProgram();
653193323Sed  for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
654193323Sed    if (!I->isDeclaration())
655193323Sed      MiscompiledFunctions.push_back(I);
656193323Sed
657193323Sed  // Do the reduction...
658193323Sed  if (!BugpointIsInterrupted)
659207618Srdivacky    ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
660207618Srdivacky                                                       Error);
661223013Sdim  if (!Error.empty()) {
662223013Sdim    errs() << "\n***Cannot reduce functions: ";
663207618Srdivacky    return MiscompiledFunctions;
664223013Sdim  }
665198090Srdivacky  outs() << "\n*** The following function"
666198090Srdivacky         << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
667198090Srdivacky         << " being miscompiled: ";
668193323Sed  PrintFunctionList(MiscompiledFunctions);
669198090Srdivacky  outs() << '\n';
670193323Sed
671193323Sed  // See if we can rip any loops out of the miscompiled functions and still
672193323Sed  // trigger the problem.
673193323Sed
674207618Srdivacky  if (!BugpointIsInterrupted && !DisableLoopExtraction) {
675207618Srdivacky    bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
676207618Srdivacky    if (!Error.empty())
677207618Srdivacky      return MiscompiledFunctions;
678207618Srdivacky    if (Ret) {
679207618Srdivacky      // Okay, we extracted some loops and the problem still appears.  See if
680207618Srdivacky      // we can eliminate some of the created functions from being candidates.
681207618Srdivacky      DisambiguateGlobalSymbols(BD.getProgram());
682193323Sed
683207618Srdivacky      // Do the reduction...
684207618Srdivacky      if (!BugpointIsInterrupted)
685207618Srdivacky        ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
686207618Srdivacky                                                           Error);
687207618Srdivacky      if (!Error.empty())
688207618Srdivacky        return MiscompiledFunctions;
689193323Sed
690207618Srdivacky      outs() << "\n*** The following function"
691207618Srdivacky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
692207618Srdivacky             << " being miscompiled: ";
693207618Srdivacky      PrintFunctionList(MiscompiledFunctions);
694207618Srdivacky      outs() << '\n';
695207618Srdivacky    }
696193323Sed  }
697193323Sed
698207618Srdivacky  if (!BugpointIsInterrupted && !DisableBlockExtraction) {
699207618Srdivacky    bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
700207618Srdivacky    if (!Error.empty())
701207618Srdivacky      return MiscompiledFunctions;
702207618Srdivacky    if (Ret) {
703207618Srdivacky      // Okay, we extracted some blocks and the problem still appears.  See if
704207618Srdivacky      // we can eliminate some of the created functions from being candidates.
705207618Srdivacky      DisambiguateGlobalSymbols(BD.getProgram());
706193323Sed
707207618Srdivacky      // Do the reduction...
708207618Srdivacky      ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
709207618Srdivacky                                                         Error);
710207618Srdivacky      if (!Error.empty())
711207618Srdivacky        return MiscompiledFunctions;
712193323Sed
713207618Srdivacky      outs() << "\n*** The following function"
714207618Srdivacky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
715207618Srdivacky             << " being miscompiled: ";
716207618Srdivacky      PrintFunctionList(MiscompiledFunctions);
717207618Srdivacky      outs() << '\n';
718207618Srdivacky    }
719193323Sed  }
720193323Sed
721193323Sed  return MiscompiledFunctions;
722193323Sed}
723193323Sed
724193323Sed/// TestOptimizer - This is the predicate function used to check to see if the
725193323Sed/// "Test" portion of the program is misoptimized.  If so, return true.  In any
726193323Sed/// case, both module arguments are deleted.
727193323Sed///
728207618Srdivackystatic bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
729207618Srdivacky                          std::string &Error) {
730193323Sed  // Run the optimization passes on ToOptimize, producing a transformed version
731193323Sed  // of the functions being tested.
732198090Srdivacky  outs() << "  Optimizing functions being tested: ";
733193323Sed  Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
734193323Sed                                     /*AutoDebugCrashes*/true);
735198090Srdivacky  outs() << "done.\n";
736193323Sed  delete Test;
737193323Sed
738198090Srdivacky  outs() << "  Checking to see if the merged program executes correctly: ";
739212793Sdim  bool Broken;
740212793Sdim  Module *New = TestMergedProgram(BD, Optimized, Safe, true, Error, Broken);
741212793Sdim  if (New) {
742212793Sdim    outs() << (Broken ? " nope.\n" : " yup.\n");
743212793Sdim    // Delete the original and set the new program.
744212793Sdim    delete BD.swapProgramIn(New);
745212793Sdim  }
746193323Sed  return Broken;
747193323Sed}
748193323Sed
749193323Sed
750193323Sed/// debugMiscompilation - This method is used when the passes selected are not
751193323Sed/// crashing, but the generated output is semantically different from the
752193323Sed/// input.
753193323Sed///
754207618Srdivackyvoid BugDriver::debugMiscompilation(std::string *Error) {
755193323Sed  // Make sure something was miscompiled...
756193323Sed  if (!BugpointIsInterrupted)
757207618Srdivacky    if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
758207618Srdivacky      if (Error->empty())
759207618Srdivacky        errs() << "*** Optimized program matches reference output!  No problem"
760207618Srdivacky               << " detected...\nbugpoint can't help you with your problem!\n";
761207618Srdivacky      return;
762193323Sed    }
763193323Sed
764198090Srdivacky  outs() << "\n*** Found miscompiling pass"
765198090Srdivacky         << (getPassesToRun().size() == 1 ? "" : "es") << ": "
766198090Srdivacky         << getPassesString(getPassesToRun()) << '\n';
767212793Sdim  EmitProgressBitcode(Program, "passinput");
768193323Sed
769221337Sdim  std::vector<Function *> MiscompiledFunctions =
770207618Srdivacky    DebugAMiscompilation(*this, TestOptimizer, *Error);
771207618Srdivacky  if (!Error->empty())
772207618Srdivacky    return;
773193323Sed
774193323Sed  // Output a bunch of bitcode files for the user...
775198090Srdivacky  outs() << "Outputting reduced bitcode files which expose the problem:\n";
776218885Sdim  ValueToValueMapTy VMap;
777210006Srdivacky  Module *ToNotOptimize = CloneModule(getProgram(), VMap);
778193323Sed  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
779193323Sed                                                 MiscompiledFunctions,
780210006Srdivacky                                                 VMap);
781193323Sed
782198090Srdivacky  outs() << "  Non-optimized portion: ";
783212793Sdim  EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
784212793Sdim  delete ToNotOptimize;  // Delete hacked module.
785193323Sed
786198090Srdivacky  outs() << "  Portion that is input to optimizer: ";
787212793Sdim  EmitProgressBitcode(ToOptimize, "tooptimize");
788212793Sdim  delete ToOptimize;      // Delete hacked module.
789193323Sed
790207618Srdivacky  return;
791193323Sed}
792193323Sed
793193323Sed/// CleanupAndPrepareModules - Get the specified modules ready for code
794193323Sed/// generator testing.
795193323Sed///
796193323Sedstatic void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
797193323Sed                                     Module *Safe) {
798193323Sed  // Clean up the modules, removing extra cruft that we don't need anymore...
799193323Sed  Test = BD.performFinalCleanups(Test);
800193323Sed
801193323Sed  // If we are executing the JIT, we have several nasty issues to take care of.
802193323Sed  if (!BD.isExecutingJIT()) return;
803193323Sed
804193323Sed  // First, if the main function is in the Safe module, we must add a stub to
805193323Sed  // the Test module to call into it.  Thus, we create a new function `main'
806193323Sed  // which just calls the old one.
807193323Sed  if (Function *oldMain = Safe->getFunction("main"))
808193323Sed    if (!oldMain->isDeclaration()) {
809193323Sed      // Rename it
810193323Sed      oldMain->setName("llvm_bugpoint_old_main");
811193323Sed      // Create a NEW `main' function with same type in the test module.
812193323Sed      Function *newMain = Function::Create(oldMain->getFunctionType(),
813193323Sed                                           GlobalValue::ExternalLinkage,
814193323Sed                                           "main", Test);
815193323Sed      // Create an `oldmain' prototype in the test module, which will
816193323Sed      // corresponds to the real main function in the same module.
817193323Sed      Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
818193323Sed                                                GlobalValue::ExternalLinkage,
819193323Sed                                                oldMain->getName(), Test);
820193323Sed      // Set up and remember the argument list for the main function.
821193323Sed      std::vector<Value*> args;
822193323Sed      for (Function::arg_iterator
823193323Sed             I = newMain->arg_begin(), E = newMain->arg_end(),
824193323Sed             OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
825193323Sed        I->setName(OI->getName());    // Copy argument names from oldMain
826193323Sed        args.push_back(I);
827193323Sed      }
828193323Sed
829193323Sed      // Call the old main function and return its result
830198090Srdivacky      BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
831224133Sdim      CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
832193323Sed
833193323Sed      // If the type of old function wasn't void, return value of call
834198090Srdivacky      ReturnInst::Create(Safe->getContext(), call, BB);
835193323Sed    }
836193323Sed
837193323Sed  // The second nasty issue we must deal with in the JIT is that the Safe
838193323Sed  // module cannot directly reference any functions defined in the test
839193323Sed  // module.  Instead, we use a JIT API call to dynamically resolve the
840193323Sed  // symbol.
841193323Sed
842193323Sed  // Add the resolver to the Safe module.
843193323Sed  // Prototype: void *getPointerToNamedFunction(const char* Name)
844193323Sed  Constant *resolverFunc =
845193323Sed    Safe->getOrInsertFunction("getPointerToNamedFunction",
846198090Srdivacky                    Type::getInt8PtrTy(Safe->getContext()),
847198090Srdivacky                    Type::getInt8PtrTy(Safe->getContext()),
848276479Sdim                       (Type *)nullptr);
849193323Sed
850193323Sed  // Use the function we just added to get addresses of functions we need.
851193323Sed  for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
852193323Sed    if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
853193323Sed        !F->isIntrinsic() /* ignore intrinsics */) {
854193323Sed      Function *TestFn = Test->getFunction(F->getName());
855193323Sed
856193323Sed      // Don't forward functions which are external in the test module too.
857193323Sed      if (TestFn && !TestFn->isDeclaration()) {
858193323Sed        // 1. Add a string constant with its name to the global file
859234353Sdim        Constant *InitArray =
860234353Sdim          ConstantDataArray::getString(F->getContext(), F->getName());
861193323Sed        GlobalVariable *funcName =
862198090Srdivacky          new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
863193323Sed                             GlobalValue::InternalLinkage, InitArray,
864198090Srdivacky                             F->getName() + "_name");
865193323Sed
866193323Sed        // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
867193323Sed        // sbyte* so it matches the signature of the resolver function.
868193323Sed
869193323Sed        // GetElementPtr *funcName, ulong 0, ulong 0
870198090Srdivacky        std::vector<Constant*> GEPargs(2,
871198090Srdivacky                     Constant::getNullValue(Type::getInt32Ty(F->getContext())));
872226584Sdim        Value *GEP = ConstantExpr::getGetElementPtr(funcName, GEPargs);
873193323Sed        std::vector<Value*> ResolverArgs;
874193323Sed        ResolverArgs.push_back(GEP);
875193323Sed
876193323Sed        // Rewrite uses of F in global initializers, etc. to uses of a wrapper
877193323Sed        // function that dynamically resolves the calls to F via our JIT API
878193323Sed        if (!F->use_empty()) {
879193323Sed          // Create a new global to hold the cached function pointer.
880193323Sed          Constant *NullPtr = ConstantPointerNull::get(F->getType());
881193323Sed          GlobalVariable *Cache =
882221337Sdim            new GlobalVariable(*F->getParent(), F->getType(),
883198090Srdivacky                               false, GlobalValue::InternalLinkage,
884198090Srdivacky                               NullPtr,F->getName()+".fpcache");
885193323Sed
886193323Sed          // Construct a new stub function that will re-route calls to F
887226584Sdim          FunctionType *FuncTy = F->getFunctionType();
888193323Sed          Function *FuncWrapper = Function::Create(FuncTy,
889193323Sed                                                   GlobalValue::InternalLinkage,
890193323Sed                                                   F->getName() + "_wrapper",
891193323Sed                                                   F->getParent());
892198090Srdivacky          BasicBlock *EntryBB  = BasicBlock::Create(F->getContext(),
893198090Srdivacky                                                    "entry", FuncWrapper);
894198090Srdivacky          BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
895198090Srdivacky                                                    "usecache", FuncWrapper);
896198090Srdivacky          BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
897198090Srdivacky                                                    "lookupfp", FuncWrapper);
898193323Sed
899193323Sed          // Check to see if we already looked up the value.
900193323Sed          Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
901198090Srdivacky          Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
902198090Srdivacky                                       NullPtr, "isNull");
903193323Sed          BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
904193323Sed
905193323Sed          // Resolve the call to function F via the JIT API:
906193323Sed          //
907193323Sed          // call resolver(GetElementPtr...)
908193323Sed          CallInst *Resolver =
909224133Sdim            CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
910193323Sed
911193323Sed          // Cast the result from the resolver to correctly-typed function.
912193323Sed          CastInst *CastedResolver =
913193323Sed            new BitCastInst(Resolver,
914193323Sed                            PointerType::getUnqual(F->getFunctionType()),
915193323Sed                            "resolverCast", LookupBB);
916193323Sed
917193323Sed          // Save the value in our cache.
918193323Sed          new StoreInst(CastedResolver, Cache, LookupBB);
919193323Sed          BranchInst::Create(DoCallBB, LookupBB);
920193323Sed
921221337Sdim          PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
922193323Sed                                             "fp", DoCallBB);
923193323Sed          FuncPtr->addIncoming(CastedResolver, LookupBB);
924193323Sed          FuncPtr->addIncoming(CachedVal, EntryBB);
925193323Sed
926193323Sed          // Save the argument list.
927193323Sed          std::vector<Value*> Args;
928193323Sed          for (Function::arg_iterator i = FuncWrapper->arg_begin(),
929193323Sed                 e = FuncWrapper->arg_end(); i != e; ++i)
930193323Sed            Args.push_back(i);
931193323Sed
932193323Sed          // Pass on the arguments to the real function, return its result
933210006Srdivacky          if (F->getReturnType()->isVoidTy()) {
934224133Sdim            CallInst::Create(FuncPtr, Args, "", DoCallBB);
935198090Srdivacky            ReturnInst::Create(F->getContext(), DoCallBB);
936193323Sed          } else {
937224133Sdim            CallInst *Call = CallInst::Create(FuncPtr, Args,
938193323Sed                                              "retval", DoCallBB);
939198090Srdivacky            ReturnInst::Create(F->getContext(),Call, DoCallBB);
940193323Sed          }
941193323Sed
942193323Sed          // Use the wrapper function instead of the old function
943193323Sed          F->replaceAllUsesWith(FuncWrapper);
944193323Sed        }
945193323Sed      }
946193323Sed    }
947193323Sed  }
948193323Sed
949193323Sed  if (verifyModule(*Test) || verifyModule(*Safe)) {
950198090Srdivacky    errs() << "Bugpoint has a bug, which corrupted a module!!\n";
951193323Sed    abort();
952193323Sed  }
953193323Sed}
954193323Sed
955193323Sed
956193323Sed
957193323Sed/// TestCodeGenerator - This is the predicate function used to check to see if
958193323Sed/// the "Test" portion of the program is miscompiled by the code generator under
959193323Sed/// test.  If so, return true.  In any case, both module arguments are deleted.
960193323Sed///
961207618Srdivackystatic bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
962207618Srdivacky                              std::string &Error) {
963193323Sed  CleanupAndPrepareModules(BD, Test, Safe);
964193323Sed
965261991Sdim  SmallString<128> TestModuleBC;
966261991Sdim  int TestModuleFD;
967276479Sdim  std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
968276479Sdim                                                    TestModuleFD, TestModuleBC);
969261991Sdim  if (EC) {
970198090Srdivacky    errs() << BD.getToolName() << "Error making unique filename: "
971261991Sdim           << EC.message() << "\n";
972193323Sed    exit(1);
973193323Sed  }
974261991Sdim  if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test)) {
975198090Srdivacky    errs() << "Error writing bitcode to `" << TestModuleBC.str()
976198090Srdivacky           << "'\nExiting.";
977193323Sed    exit(1);
978193323Sed  }
979193323Sed  delete Test;
980193323Sed
981221337Sdim  FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
982210006Srdivacky
983193323Sed  // Make the shared library
984261991Sdim  SmallString<128> SafeModuleBC;
985261991Sdim  int SafeModuleFD;
986261991Sdim  EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
987261991Sdim                                    SafeModuleBC);
988261991Sdim  if (EC) {
989198090Srdivacky    errs() << BD.getToolName() << "Error making unique filename: "
990261991Sdim           << EC.message() << "\n";
991193323Sed    exit(1);
992193323Sed  }
993193323Sed
994261991Sdim  if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe)) {
995198090Srdivacky    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
996198090Srdivacky           << "'\nExiting.";
997193323Sed    exit(1);
998193323Sed  }
999210006Srdivacky
1000221337Sdim  FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
1001210006Srdivacky
1002207618Srdivacky  std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
1003207618Srdivacky  if (!Error.empty())
1004207618Srdivacky    return false;
1005193323Sed  delete Safe;
1006193323Sed
1007221337Sdim  FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
1008210006Srdivacky
1009193323Sed  // Run the code generator on the `Test' code, loading the shared library.
1010193323Sed  // The function returns whether or not the new output differs from reference.
1011212793Sdim  bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
1012212793Sdim                               SharedObject, false, &Error);
1013207618Srdivacky  if (!Error.empty())
1014207618Srdivacky    return false;
1015193323Sed
1016193323Sed  if (Result)
1017198090Srdivacky    errs() << ": still failing!\n";
1018193323Sed  else
1019198090Srdivacky    errs() << ": didn't fail.\n";
1020193323Sed
1021193323Sed  return Result;
1022193323Sed}
1023193323Sed
1024193323Sed
1025193323Sed/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1026193323Sed///
1027207618Srdivackybool BugDriver::debugCodeGenerator(std::string *Error) {
1028193323Sed  if ((void*)SafeInterpreter == (void*)Interpreter) {
1029212793Sdim    std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
1030212793Sdim                                              Error);
1031207618Srdivacky    if (Error->empty()) {
1032207618Srdivacky      outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1033207618Srdivacky             << "the reference diff.  This may be due to a\n    front-end "
1034207618Srdivacky             << "bug or a bug in the original program, but this can also "
1035207618Srdivacky             << "happen if bugpoint isn't running the program with the "
1036207618Srdivacky             << "right flags or input.\n    I left the result of executing "
1037207618Srdivacky             << "the program with the \"safe\" backend in this file for "
1038207618Srdivacky             << "you: '"
1039207618Srdivacky             << Result << "'.\n";
1040207618Srdivacky    }
1041193323Sed    return true;
1042193323Sed  }
1043193323Sed
1044193323Sed  DisambiguateGlobalSymbols(Program);
1045193323Sed
1046207618Srdivacky  std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1047207618Srdivacky                                                      *Error);
1048207618Srdivacky  if (!Error->empty())
1049207618Srdivacky    return true;
1050193323Sed
1051193323Sed  // Split the module into the two halves of the program we want.
1052218885Sdim  ValueToValueMapTy VMap;
1053210006Srdivacky  Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1054210006Srdivacky  Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
1055193323Sed
1056193323Sed  // Condition the modules
1057193323Sed  CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1058193323Sed
1059261991Sdim  SmallString<128> TestModuleBC;
1060261991Sdim  int TestModuleFD;
1061276479Sdim  std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1062276479Sdim                                                    TestModuleFD, TestModuleBC);
1063261991Sdim  if (EC) {
1064198090Srdivacky    errs() << getToolName() << "Error making unique filename: "
1065261991Sdim           << EC.message() << "\n";
1066193323Sed    exit(1);
1067193323Sed  }
1068193323Sed
1069261991Sdim  if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen)) {
1070198090Srdivacky    errs() << "Error writing bitcode to `" << TestModuleBC.str()
1071198090Srdivacky           << "'\nExiting.";
1072193323Sed    exit(1);
1073193323Sed  }
1074193323Sed  delete ToCodeGen;
1075193323Sed
1076193323Sed  // Make the shared library
1077261991Sdim  SmallString<128> SafeModuleBC;
1078261991Sdim  int SafeModuleFD;
1079261991Sdim  EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1080261991Sdim                                    SafeModuleBC);
1081261991Sdim  if (EC) {
1082198090Srdivacky    errs() << getToolName() << "Error making unique filename: "
1083261991Sdim           << EC.message() << "\n";
1084193323Sed    exit(1);
1085193323Sed  }
1086193323Sed
1087261991Sdim  if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, ToNotCodeGen)) {
1088198090Srdivacky    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
1089198090Srdivacky           << "'\nExiting.";
1090193323Sed    exit(1);
1091193323Sed  }
1092207618Srdivacky  std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1093207618Srdivacky  if (!Error->empty())
1094207618Srdivacky    return true;
1095193323Sed  delete ToNotCodeGen;
1096193323Sed
1097198090Srdivacky  outs() << "You can reproduce the problem with the command line: \n";
1098193323Sed  if (isExecutingJIT()) {
1099198090Srdivacky    outs() << "  lli -load " << SharedObject << " " << TestModuleBC.str();
1100193323Sed  } else {
1101207618Srdivacky    outs() << "  llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
1102198090Srdivacky           << ".s\n";
1103198090Srdivacky    outs() << "  gcc " << SharedObject << " " << TestModuleBC.str()
1104198090Srdivacky              << ".s -o " << TestModuleBC.str() << ".exe";
1105193323Sed#if defined (HAVE_LINK_R)
1106198090Srdivacky    outs() << " -Wl,-R.";
1107193323Sed#endif
1108198090Srdivacky    outs() << "\n";
1109198090Srdivacky    outs() << "  " << TestModuleBC.str() << ".exe";
1110193323Sed  }
1111207618Srdivacky  for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1112198090Srdivacky    outs() << " " << InputArgv[i];
1113198090Srdivacky  outs() << '\n';
1114198090Srdivacky  outs() << "The shared object was created with:\n  llc -march=c "
1115198090Srdivacky         << SafeModuleBC.str() << " -o temporary.c\n"
1116198090Srdivacky         << "  gcc -xc temporary.c -O2 -o " << SharedObject;
1117198090Srdivacky  if (TargetTriple.getArch() == Triple::sparc)
1118198090Srdivacky    outs() << " -G";              // Compile a shared library, `-G' for Sparc
1119198090Srdivacky  else
1120198090Srdivacky    outs() << " -fPIC -shared";   // `-shared' for Linux/X86, maybe others
1121193323Sed
1122198090Srdivacky  outs() << " -fno-strict-aliasing\n";
1123198090Srdivacky
1124193323Sed  return false;
1125193323Sed}
1126