1193323Sed//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2193323Sed//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193323Sed//
7193323Sed//===----------------------------------------------------------------------===//
8193323Sed//
9193323Sed// This file implements optimizer and code generation miscompilation debugging
10193323Sed// support.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#include "BugDriver.h"
15193323Sed#include "ListReducer.h"
16198090Srdivacky#include "ToolRunner.h"
17314564Sdim#include "llvm/Config/config.h" // for HAVE_LINK_R
18249423Sdim#include "llvm/IR/Constants.h"
19249423Sdim#include "llvm/IR/DerivedTypes.h"
20249423Sdim#include "llvm/IR/Instructions.h"
21249423Sdim#include "llvm/IR/Module.h"
22276479Sdim#include "llvm/IR/Verifier.h"
23276479Sdim#include "llvm/Linker/Linker.h"
24193323Sed#include "llvm/Pass.h"
25193323Sed#include "llvm/Support/CommandLine.h"
26193323Sed#include "llvm/Support/FileUtilities.h"
27249423Sdim#include "llvm/Transforms/Utils/Cloning.h"
28309124Sdim
29193323Sedusing namespace llvm;
30193323Sed
31193323Sednamespace llvm {
32314564Sdimextern cl::opt<std::string> OutputPrefix;
33314564Sdimextern cl::list<std::string> InputArgv;
34309124Sdim} // end namespace llvm
35193323Sed
36193323Sednamespace {
37314564Sdimstatic llvm::cl::opt<bool> DisableLoopExtraction(
38314564Sdim    "disable-loop-extraction",
39314564Sdim    cl::desc("Don't extract loops when searching for miscompilations"),
40314564Sdim    cl::init(false));
41314564Sdimstatic llvm::cl::opt<bool> DisableBlockExtraction(
42314564Sdim    "disable-block-extraction",
43314564Sdim    cl::desc("Don't extract blocks when searching for miscompilations"),
44314564Sdim    cl::init(false));
45193323Sed
46314564Sdimclass ReduceMiscompilingPasses : public ListReducer<std::string> {
47314564Sdim  BugDriver &BD;
48193323Sed
49314564Sdimpublic:
50314564Sdim  ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
51314564Sdim
52314564Sdim  Expected<TestResult> doTest(std::vector<std::string> &Prefix,
53314564Sdim                              std::vector<std::string> &Suffix) override;
54314564Sdim};
55309124Sdim} // end anonymous namespace
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///
60314564SdimExpected<ReduceMiscompilingPasses::TestResult>
61212793SdimReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
62314564Sdim                                 std::vector<std::string> &Suffix) {
63193323Sed  // First, run the program with just the Suffix passes.  If it is still broken
64193323Sed  // with JUST the kept passes, discard the prefix passes.
65198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Suffix)
66198090Srdivacky         << "' compiles correctly: ";
67193323Sed
68193323Sed  std::string BitcodeResult;
69314564Sdim  if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
70314564Sdim                   true /*quiet*/)) {
71198090Srdivacky    errs() << " Error running this sequence of passes"
72198090Srdivacky           << " on the input program!\n";
73193323Sed    BD.setPassesToRun(Suffix);
74314564Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
75314564Sdim    // TODO: This should propagate the error instead of exiting.
76314564Sdim    if (Error E = BD.debugOptimizerCrash())
77314564Sdim      exit(1);
78314564Sdim    exit(0);
79193323Sed  }
80221337Sdim
81193323Sed  // Check to see if the finished program matches the reference output...
82314564Sdim  Expected<bool> Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
83314564Sdim                                       true /*delete bitcode*/);
84314564Sdim  if (Error E = Diff.takeError())
85314564Sdim    return std::move(E);
86314564Sdim  if (*Diff) {
87198090Srdivacky    outs() << " nope.\n";
88193323Sed    if (Suffix.empty()) {
89198090Srdivacky      errs() << BD.getToolName() << ": I'm confused: the test fails when "
90198090Srdivacky             << "no passes are run, nondeterministic program?\n";
91193323Sed      exit(1);
92193323Sed    }
93314564Sdim    return KeepSuffix; // Miscompilation detected!
94193323Sed  }
95314564Sdim  outs() << " yup.\n"; // No miscompilation!
96193323Sed
97314564Sdim  if (Prefix.empty())
98314564Sdim    return NoFailure;
99193323Sed
100193323Sed  // Next, see if the program is broken if we run the "prefix" passes first,
101193323Sed  // then separately run the "kept" passes.
102198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Prefix)
103198090Srdivacky         << "' compiles correctly: ";
104193323Sed
105193323Sed  // If it is not broken with the kept passes, it's possible that the prefix
106193323Sed  // passes must be run before the kept passes to break it.  If the program
107193323Sed  // WORKS after the prefix passes, but then fails if running the prefix AND
108193323Sed  // kept passes, we can update our bitcode file to include the result of the
109193323Sed  // prefix passes, then discard the prefix passes.
110193323Sed  //
111314564Sdim  if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false /*delete*/,
112314564Sdim                   true /*quiet*/)) {
113198090Srdivacky    errs() << " Error running this sequence of passes"
114198090Srdivacky           << " on the input program!\n";
115193323Sed    BD.setPassesToRun(Prefix);
116314564Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
117314564Sdim    // TODO: This should propagate the error instead of exiting.
118314564Sdim    if (Error E = BD.debugOptimizerCrash())
119314564Sdim      exit(1);
120314564Sdim    exit(0);
121193323Sed  }
122193323Sed
123193323Sed  // If the prefix maintains the predicate by itself, only keep the prefix!
124314564Sdim  Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false);
125314564Sdim  if (Error E = Diff.takeError())
126314564Sdim    return std::move(E);
127314564Sdim  if (*Diff) {
128198090Srdivacky    outs() << " nope.\n";
129261991Sdim    sys::fs::remove(BitcodeResult);
130193323Sed    return KeepPrefix;
131193323Sed  }
132314564Sdim  outs() << " yup.\n"; // No miscompilation!
133193323Sed
134193323Sed  // Ok, so now we know that the prefix passes work, try running the suffix
135193323Sed  // passes on the result of the prefix passes.
136193323Sed  //
137280031Sdim  std::unique_ptr<Module> PrefixOutput =
138280031Sdim      parseInputFile(BitcodeResult, BD.getContext());
139261991Sdim  if (!PrefixOutput) {
140198090Srdivacky    errs() << BD.getToolName() << ": Error reading bitcode file '"
141198090Srdivacky           << BitcodeResult << "'!\n";
142193323Sed    exit(1);
143193323Sed  }
144261991Sdim  sys::fs::remove(BitcodeResult);
145193323Sed
146193323Sed  // Don't check if there are no passes in the suffix.
147193323Sed  if (Suffix.empty())
148193323Sed    return NoFailure;
149193323Sed
150198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Suffix)
151314564Sdim         << "' passes compile correctly after the '" << getPassesString(Prefix)
152314564Sdim         << "' passes: ";
153193323Sed
154341825Sdim  std::unique_ptr<Module> OriginalInput =
155341825Sdim      BD.swapProgramIn(std::move(PrefixOutput));
156314564Sdim  if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
157314564Sdim                   true /*quiet*/)) {
158198090Srdivacky    errs() << " Error running this sequence of passes"
159198090Srdivacky           << " on the input program!\n";
160193323Sed    BD.setPassesToRun(Suffix);
161314564Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
162314564Sdim    // TODO: This should propagate the error instead of exiting.
163314564Sdim    if (Error E = BD.debugOptimizerCrash())
164314564Sdim      exit(1);
165314564Sdim    exit(0);
166193323Sed  }
167193323Sed
168193323Sed  // Run the result...
169212793Sdim  Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
170314564Sdim                        true /*delete bitcode*/);
171314564Sdim  if (Error E = Diff.takeError())
172314564Sdim    return std::move(E);
173314564Sdim  if (*Diff) {
174198090Srdivacky    outs() << " nope.\n";
175193323Sed    return KeepSuffix;
176193323Sed  }
177193323Sed
178193323Sed  // Otherwise, we must not be running the bad pass anymore.
179314564Sdim  outs() << " yup.\n"; // No miscompilation!
180208599Srdivacky  // Restore orig program & free test.
181341825Sdim  BD.setNewProgram(std::move(OriginalInput));
182193323Sed  return NoFailure;
183193323Sed}
184193323Sed
185193323Sednamespace {
186314564Sdimclass ReduceMiscompilingFunctions : public ListReducer<Function *> {
187314564Sdim  BugDriver &BD;
188314564Sdim  Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
189314564Sdim                           std::unique_ptr<Module>);
190296417Sdim
191314564Sdimpublic:
192314564Sdim  ReduceMiscompilingFunctions(BugDriver &bd,
193314564Sdim                              Expected<bool> (*F)(BugDriver &,
194314564Sdim                                                  std::unique_ptr<Module>,
195314564Sdim                                                  std::unique_ptr<Module>))
196314564Sdim      : BD(bd), TestFn(F) {}
197193323Sed
198314564Sdim  Expected<TestResult> doTest(std::vector<Function *> &Prefix,
199314564Sdim                              std::vector<Function *> &Suffix) override {
200314564Sdim    if (!Suffix.empty()) {
201314564Sdim      Expected<bool> Ret = TestFuncs(Suffix);
202314564Sdim      if (Error E = Ret.takeError())
203314564Sdim        return std::move(E);
204314564Sdim      if (*Ret)
205314564Sdim        return KeepSuffix;
206193323Sed    }
207314564Sdim    if (!Prefix.empty()) {
208314564Sdim      Expected<bool> Ret = TestFuncs(Prefix);
209314564Sdim      if (Error E = Ret.takeError())
210314564Sdim        return std::move(E);
211314564Sdim      if (*Ret)
212314564Sdim        return KeepPrefix;
213314564Sdim    }
214314564Sdim    return NoFailure;
215314564Sdim  }
216193323Sed
217314564Sdim  Expected<bool> TestFuncs(const std::vector<Function *> &Prefix);
218314564Sdim};
219309124Sdim} // end anonymous namespace
220193323Sed
221296417Sdim/// Given two modules, link them together and run the program, checking to see
222296417Sdim/// if the program matches the diff. If there is an error, return NULL. If not,
223296417Sdim/// return the merged module. The Broken argument will be set to true if the
224296417Sdim/// output is different. If the DeleteInputs argument is set to true then this
225296417Sdim/// function deletes both input modules before it returns.
226193323Sed///
227321369Sdimstatic Expected<std::unique_ptr<Module>> testMergedProgram(const BugDriver &BD,
228321369Sdim                                                           const Module &M1,
229321369Sdim                                                           const Module &M2,
230321369Sdim                                                           bool &Broken) {
231321369Sdim  // Resulting merge of M1 and M2.
232341825Sdim  auto Merged = CloneModule(M1);
233341825Sdim  if (Linker::linkModules(*Merged, CloneModule(M2)))
234314564Sdim    // TODO: Shouldn't we thread the error up instead of exiting?
235193323Sed    exit(1);
236193323Sed
237212793Sdim  // Execute the program.
238341825Sdim  Expected<bool> Diff = BD.diffProgram(*Merged, "", "", false);
239314564Sdim  if (Error E = Diff.takeError())
240314564Sdim    return std::move(E);
241314564Sdim  Broken = *Diff;
242321369Sdim  return std::move(Merged);
243193323Sed}
244193323Sed
245341825Sdim/// split functions in a Module into two groups: those that are under
246341825Sdim/// consideration for miscompilation vs. those that are not, and test
247193323Sed/// accordingly. Each group of functions becomes a separate Module.
248314564SdimExpected<bool>
249314564SdimReduceMiscompilingFunctions::TestFuncs(const std::vector<Function *> &Funcs) {
250193323Sed  // Test to see if the function is misoptimized if we ONLY run it on the
251193323Sed  // functions listed in Funcs.
252198090Srdivacky  outs() << "Checking to see if the program is misoptimized when "
253314564Sdim         << (Funcs.size() == 1 ? "this function is" : "these functions are")
254198090Srdivacky         << " run through the pass"
255198090Srdivacky         << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
256193323Sed  PrintFunctionList(Funcs);
257198090Srdivacky  outs() << '\n';
258193323Sed
259212793Sdim  // Create a clone for two reasons:
260212793Sdim  // * If the optimization passes delete any function, the deleted function
261212793Sdim  //   will be in the clone and Funcs will still point to valid memory
262212793Sdim  // * If the optimization passes use interprocedural information to break
263212793Sdim  //   a function, we want to continue with the original function. Otherwise
264212793Sdim  //   we can conclude that a function triggers the bug when in fact one
265212793Sdim  //   needs a larger set of original functions to do so.
266218885Sdim  ValueToValueMapTy VMap;
267341825Sdim  std::unique_ptr<Module> Clone = CloneModule(BD.getProgram(), VMap);
268341825Sdim  std::unique_ptr<Module> Orig = BD.swapProgramIn(std::move(Clone));
269212793Sdim
270314564Sdim  std::vector<Function *> FuncsOnClone;
271212793Sdim  for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
272212793Sdim    Function *F = cast<Function>(VMap[Funcs[i]]);
273212793Sdim    FuncsOnClone.push_back(F);
274212793Sdim  }
275212793Sdim
276193323Sed  // Split the module into the two halves of the program we want.
277212793Sdim  VMap.clear();
278296417Sdim  std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
279296417Sdim  std::unique_ptr<Module> ToOptimize =
280296417Sdim      SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
281193323Sed
282314564Sdim  Expected<bool> Broken =
283314564Sdim      TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize));
284212793Sdim
285341825Sdim  BD.setNewProgram(std::move(Orig));
286212793Sdim
287212793Sdim  return Broken;
288193323Sed}
289193323Sed
290341825Sdim/// Give anonymous global values names.
291341825Sdimstatic void DisambiguateGlobalSymbols(Module &M) {
292341825Sdim  for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E;
293341825Sdim       ++I)
294202878Srdivacky    if (!I->hasName())
295202878Srdivacky      I->setName("anon_global");
296341825Sdim  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
297202878Srdivacky    if (!I->hasName())
298202878Srdivacky      I->setName("anon_fn");
299193323Sed}
300193323Sed
301296417Sdim/// Given a reduced list of functions that still exposed the bug, check to see
302296417Sdim/// if we can extract the loops in the region without obscuring the bug.  If so,
303296417Sdim/// it reduces the amount of code identified.
304193323Sed///
305314564Sdimstatic Expected<bool>
306314564SdimExtractLoops(BugDriver &BD,
307314564Sdim             Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
308314564Sdim                                      std::unique_ptr<Module>),
309314564Sdim             std::vector<Function *> &MiscompiledFunctions) {
310193323Sed  bool MadeChange = false;
311193323Sed  while (1) {
312314564Sdim    if (BugpointIsInterrupted)
313314564Sdim      return MadeChange;
314221337Sdim
315218885Sdim    ValueToValueMapTy VMap;
316296417Sdim    std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
317341825Sdim    std::unique_ptr<Module> ToOptimize = SplitFunctionsOutOfModule(
318341825Sdim        ToNotOptimize.get(), MiscompiledFunctions, VMap);
319296417Sdim    std::unique_ptr<Module> ToOptimizeLoopExtracted =
320341825Sdim        BD.extractLoop(ToOptimize.get());
321341825Sdim    if (!ToOptimizeLoopExtracted)
322193323Sed      // If the loop extractor crashed or if there were no extractible loops,
323193323Sed      // then this chapter of our odyssey is over with.
324193323Sed      return MadeChange;
325193323Sed
326198090Srdivacky    errs() << "Extracted a loop from the breaking portion of the program.\n";
327193323Sed
328193323Sed    // Bugpoint is intentionally not very trusting of LLVM transformations.  In
329193323Sed    // particular, we're not going to assume that the loop extractor works, so
330193323Sed    // we're going to test the newly loop extracted program to make sure nothing
331193323Sed    // has broken.  If something broke, then we'll inform the user and stop
332193323Sed    // extraction.
333193323Sed    AbstractInterpreter *AI = BD.switchToSafeInterpreter();
334212793Sdim    bool Failure;
335321369Sdim    Expected<std::unique_ptr<Module>> New = testMergedProgram(
336321369Sdim        BD, *ToOptimizeLoopExtracted, *ToNotOptimize, Failure);
337314564Sdim    if (Error E = New.takeError())
338314564Sdim      return std::move(E);
339314564Sdim    if (!*New)
340207618Srdivacky      return false;
341261991Sdim
342212793Sdim    // Delete the original and set the new program.
343341825Sdim    std::unique_ptr<Module> Old = BD.swapProgramIn(std::move(*New));
344261991Sdim    for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
345261991Sdim      MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
346261991Sdim
347207618Srdivacky    if (Failure) {
348193323Sed      BD.switchToInterpreter(AI);
349193323Sed
350193323Sed      // Merged program doesn't work anymore!
351198090Srdivacky      errs() << "  *** ERROR: Loop extraction broke the program. :("
352198090Srdivacky             << " Please report a bug!\n";
353198090Srdivacky      errs() << "      Continuing on with un-loop-extracted version.\n";
354193323Sed
355198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
356341825Sdim                            *ToNotOptimize);
357198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
358341825Sdim                            *ToOptimize);
359198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
360341825Sdim                            *ToOptimizeLoopExtracted);
361193323Sed
362314564Sdim      errs() << "Please submit the " << OutputPrefix
363314564Sdim             << "-loop-extract-fail-*.bc files.\n";
364193323Sed      return MadeChange;
365193323Sed    }
366193323Sed    BD.switchToInterpreter(AI);
367193323Sed
368198090Srdivacky    outs() << "  Testing after loop extraction:\n";
369193323Sed    // Clone modules, the tester function will free them.
370296417Sdim    std::unique_ptr<Module> TOLEBackup =
371341825Sdim        CloneModule(*ToOptimizeLoopExtracted, VMap);
372341825Sdim    std::unique_ptr<Module> TNOBackup = CloneModule(*ToNotOptimize, VMap);
373261991Sdim
374261991Sdim    for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
375261991Sdim      MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
376261991Sdim
377314564Sdim    Expected<bool> Result = TestFn(BD, std::move(ToOptimizeLoopExtracted),
378314564Sdim                                   std::move(ToNotOptimize));
379314564Sdim    if (Error E = Result.takeError())
380314564Sdim      return std::move(E);
381261991Sdim
382296417Sdim    ToOptimizeLoopExtracted = std::move(TOLEBackup);
383296417Sdim    ToNotOptimize = std::move(TNOBackup);
384261991Sdim
385314564Sdim    if (!*Result) {
386198090Srdivacky      outs() << "*** Loop extraction masked the problem.  Undoing.\n";
387193323Sed      // If the program is not still broken, then loop extraction did something
388193323Sed      // that masked the error.  Stop loop extraction now.
389261991Sdim
390314564Sdim      std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
391288943Sdim      for (Function *F : MiscompiledFunctions) {
392288943Sdim        MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
393261991Sdim      }
394261991Sdim
395296417Sdim      if (Linker::linkModules(*ToNotOptimize,
396296417Sdim                              std::move(ToOptimizeLoopExtracted)))
397261991Sdim        exit(1);
398261991Sdim
399261991Sdim      MiscompiledFunctions.clear();
400261991Sdim      for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
401261991Sdim        Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
402261991Sdim
403261991Sdim        assert(NewF && "Function not found??");
404261991Sdim        MiscompiledFunctions.push_back(NewF);
405261991Sdim      }
406261991Sdim
407341825Sdim      BD.setNewProgram(std::move(ToNotOptimize));
408193323Sed      return MadeChange;
409193323Sed    }
410193323Sed
411198090Srdivacky    outs() << "*** Loop extraction successful!\n";
412193323Sed
413314564Sdim    std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
414193323Sed    for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
415314564Sdim                          E = ToOptimizeLoopExtracted->end();
416314564Sdim         I != E; ++I)
417193323Sed      if (!I->isDeclaration())
418288943Sdim        MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
419193323Sed
420193323Sed    // Okay, great!  Now we know that we extracted a loop and that loop
421193323Sed    // extraction both didn't break the program, and didn't mask the problem.
422193323Sed    // Replace the current program with the loop extracted version, and try to
423193323Sed    // extract another loop.
424296417Sdim    if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
425193323Sed      exit(1);
426280031Sdim
427193323Sed    // All of the Function*'s in the MiscompiledFunctions list are in the old
428193323Sed    // module.  Update this list to include all of the functions in the
429193323Sed    // optimized and loop extracted module.
430193323Sed    MiscompiledFunctions.clear();
431193323Sed    for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
432193323Sed      Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
433221337Sdim
434193323Sed      assert(NewF && "Function not found??");
435193323Sed      MiscompiledFunctions.push_back(NewF);
436193323Sed    }
437193323Sed
438341825Sdim    BD.setNewProgram(std::move(ToNotOptimize));
439193323Sed    MadeChange = true;
440193323Sed  }
441193323Sed}
442193323Sed
443193323Sednamespace {
444314564Sdimclass ReduceMiscompiledBlocks : public ListReducer<BasicBlock *> {
445314564Sdim  BugDriver &BD;
446314564Sdim  Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
447314564Sdim                           std::unique_ptr<Module>);
448314564Sdim  std::vector<Function *> FunctionsBeingTested;
449193323Sed
450314564Sdimpublic:
451314564Sdim  ReduceMiscompiledBlocks(BugDriver &bd,
452314564Sdim                          Expected<bool> (*F)(BugDriver &,
453314564Sdim                                              std::unique_ptr<Module>,
454314564Sdim                                              std::unique_ptr<Module>),
455314564Sdim                          const std::vector<Function *> &Fns)
456314564Sdim      : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
457314564Sdim
458314564Sdim  Expected<TestResult> doTest(std::vector<BasicBlock *> &Prefix,
459314564Sdim                              std::vector<BasicBlock *> &Suffix) override {
460314564Sdim    if (!Suffix.empty()) {
461314564Sdim      Expected<bool> Ret = TestFuncs(Suffix);
462314564Sdim      if (Error E = Ret.takeError())
463314564Sdim        return std::move(E);
464314564Sdim      if (*Ret)
465314564Sdim        return KeepSuffix;
466193323Sed    }
467314564Sdim    if (!Prefix.empty()) {
468314564Sdim      Expected<bool> Ret = TestFuncs(Prefix);
469314564Sdim      if (Error E = Ret.takeError())
470314564Sdim        return std::move(E);
471314564Sdim      if (*Ret)
472314564Sdim        return KeepPrefix;
473314564Sdim    }
474314564Sdim    return NoFailure;
475314564Sdim  }
476193323Sed
477314564Sdim  Expected<bool> TestFuncs(const std::vector<BasicBlock *> &BBs);
478314564Sdim};
479309124Sdim} // end anonymous namespace
480193323Sed
481193323Sed/// TestFuncs - Extract all blocks for the miscompiled functions except for the
482193323Sed/// specified blocks.  If the problem still exists, return true.
483193323Sed///
484314564SdimExpected<bool>
485314564SdimReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock *> &BBs) {
486193323Sed  // Test to see if the function is misoptimized if we ONLY run it on the
487193323Sed  // functions listed in Funcs.
488198090Srdivacky  outs() << "Checking to see if the program is misoptimized when all ";
489193323Sed  if (!BBs.empty()) {
490198090Srdivacky    outs() << "but these " << BBs.size() << " blocks are extracted: ";
491193323Sed    for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
492198090Srdivacky      outs() << BBs[i]->getName() << " ";
493314564Sdim    if (BBs.size() > 10)
494314564Sdim      outs() << "...";
495193323Sed  } else {
496198090Srdivacky    outs() << "blocks are extracted.";
497193323Sed  }
498198090Srdivacky  outs() << '\n';
499193323Sed
500193323Sed  // Split the module into the two halves of the program we want.
501218885Sdim  ValueToValueMapTy VMap;
502341825Sdim  std::unique_ptr<Module> Clone = CloneModule(BD.getProgram(), VMap);
503341825Sdim  std::unique_ptr<Module> Orig = BD.swapProgramIn(std::move(Clone));
504314564Sdim  std::vector<Function *> FuncsOnClone;
505314564Sdim  std::vector<BasicBlock *> BBsOnClone;
506212793Sdim  for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
507212793Sdim    Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
508212793Sdim    FuncsOnClone.push_back(F);
509212793Sdim  }
510212793Sdim  for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
511212793Sdim    BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
512212793Sdim    BBsOnClone.push_back(BB);
513212793Sdim  }
514212793Sdim  VMap.clear();
515212793Sdim
516296417Sdim  std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
517296417Sdim  std::unique_ptr<Module> ToOptimize =
518296417Sdim      SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
519193323Sed
520193323Sed  // Try the extraction.  If it doesn't work, then the block extractor crashed
521193323Sed  // or something, in which case bugpoint can't chase down this possibility.
522280031Sdim  if (std::unique_ptr<Module> New =
523296417Sdim          BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
524314564Sdim    Expected<bool> Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize));
525341825Sdim    BD.setNewProgram(std::move(Orig));
526212793Sdim    return Ret;
527193323Sed  }
528341825Sdim  BD.setNewProgram(std::move(Orig));
529193323Sed  return false;
530193323Sed}
531193323Sed
532296417Sdim/// Given a reduced list of functions that still expose the bug, extract as many
533296417Sdim/// basic blocks from the region as possible without obscuring the bug.
534193323Sed///
535314564Sdimstatic Expected<bool>
536314564SdimExtractBlocks(BugDriver &BD,
537314564Sdim              Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
538314564Sdim                                       std::unique_ptr<Module>),
539314564Sdim              std::vector<Function *> &MiscompiledFunctions) {
540314564Sdim  if (BugpointIsInterrupted)
541314564Sdim    return false;
542221337Sdim
543314564Sdim  std::vector<BasicBlock *> Blocks;
544193323Sed  for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
545296417Sdim    for (BasicBlock &BB : *MiscompiledFunctions[i])
546296417Sdim      Blocks.push_back(&BB);
547193323Sed
548193323Sed  // Use the list reducer to identify blocks that can be extracted without
549193323Sed  // obscuring the bug.  The Blocks list will end up containing blocks that must
550193323Sed  // be retained from the original program.
551193323Sed  unsigned OldSize = Blocks.size();
552193323Sed
553193323Sed  // Check to see if all blocks are extractible first.
554314564Sdim  Expected<bool> Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
555314564Sdim                           .TestFuncs(std::vector<BasicBlock *>());
556314564Sdim  if (Error E = Ret.takeError())
557314564Sdim    return std::move(E);
558314564Sdim  if (*Ret) {
559193323Sed    Blocks.clear();
560193323Sed  } else {
561314564Sdim    Expected<bool> Ret =
562314564Sdim        ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
563314564Sdim            .reduceList(Blocks);
564314564Sdim    if (Error E = Ret.takeError())
565314564Sdim      return std::move(E);
566193323Sed    if (Blocks.size() == OldSize)
567193323Sed      return false;
568193323Sed  }
569193323Sed
570218885Sdim  ValueToValueMapTy VMap;
571341825Sdim  std::unique_ptr<Module> ProgClone = CloneModule(BD.getProgram(), VMap);
572341825Sdim  std::unique_ptr<Module> ToExtract =
573341825Sdim      SplitFunctionsOutOfModule(ProgClone.get(), MiscompiledFunctions, VMap);
574280031Sdim  std::unique_ptr<Module> Extracted =
575341825Sdim      BD.extractMappedBlocksFromModule(Blocks, ToExtract.get());
576276479Sdim  if (!Extracted) {
577193323Sed    // Weird, extraction should have worked.
578198090Srdivacky    errs() << "Nondeterministic problem extracting blocks??\n";
579193323Sed    return false;
580193323Sed  }
581193323Sed
582193323Sed  // Otherwise, block extraction succeeded.  Link the two program fragments back
583193323Sed  // together.
584193323Sed
585314564Sdim  std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
586314564Sdim  for (Module::iterator I = Extracted->begin(), E = Extracted->end(); I != E;
587314564Sdim       ++I)
588193323Sed    if (!I->isDeclaration())
589288943Sdim      MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
590193323Sed
591296417Sdim  if (Linker::linkModules(*ProgClone, std::move(Extracted)))
592193323Sed    exit(1);
593193323Sed
594193323Sed  // Update the list of miscompiled functions.
595193323Sed  MiscompiledFunctions.clear();
596193323Sed
597193323Sed  for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
598193323Sed    Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
599193323Sed    assert(NewF && "Function not found??");
600193323Sed    MiscompiledFunctions.push_back(NewF);
601193323Sed  }
602193323Sed
603353358Sdim  // Set the new program and delete the old one.
604353358Sdim  BD.setNewProgram(std::move(ProgClone));
605353358Sdim
606193323Sed  return true;
607193323Sed}
608193323Sed
609296417Sdim/// This is a generic driver to narrow down miscompilations, either in an
610296417Sdim/// optimization or a code generator.
611193323Sed///
612314564Sdimstatic Expected<std::vector<Function *>> DebugAMiscompilation(
613314564Sdim    BugDriver &BD,
614314564Sdim    Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
615314564Sdim                             std::unique_ptr<Module>)) {
616193323Sed  // Okay, now that we have reduced the list of passes which are causing the
617193323Sed  // failure, see if we can pin down which functions are being
618193323Sed  // miscompiled... first build a list of all of the non-external functions in
619193323Sed  // the program.
620314564Sdim  std::vector<Function *> MiscompiledFunctions;
621341825Sdim  Module &Prog = BD.getProgram();
622341825Sdim  for (Function &F : Prog)
623296417Sdim    if (!F.isDeclaration())
624296417Sdim      MiscompiledFunctions.push_back(&F);
625193323Sed
626193323Sed  // Do the reduction...
627314564Sdim  if (!BugpointIsInterrupted) {
628314564Sdim    Expected<bool> Ret = ReduceMiscompilingFunctions(BD, TestFn)
629314564Sdim                             .reduceList(MiscompiledFunctions);
630314564Sdim    if (Error E = Ret.takeError()) {
631314564Sdim      errs() << "\n***Cannot reduce functions: ";
632314564Sdim      return std::move(E);
633314564Sdim    }
634223013Sdim  }
635198090Srdivacky  outs() << "\n*** The following function"
636198090Srdivacky         << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
637198090Srdivacky         << " being miscompiled: ";
638193323Sed  PrintFunctionList(MiscompiledFunctions);
639198090Srdivacky  outs() << '\n';
640193323Sed
641193323Sed  // See if we can rip any loops out of the miscompiled functions and still
642193323Sed  // trigger the problem.
643193323Sed
644207618Srdivacky  if (!BugpointIsInterrupted && !DisableLoopExtraction) {
645314564Sdim    Expected<bool> Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions);
646314564Sdim    if (Error E = Ret.takeError())
647314564Sdim      return std::move(E);
648314564Sdim    if (*Ret) {
649207618Srdivacky      // Okay, we extracted some loops and the problem still appears.  See if
650207618Srdivacky      // we can eliminate some of the created functions from being candidates.
651207618Srdivacky      DisambiguateGlobalSymbols(BD.getProgram());
652193323Sed
653207618Srdivacky      // Do the reduction...
654207618Srdivacky      if (!BugpointIsInterrupted)
655314564Sdim        Ret = ReduceMiscompilingFunctions(BD, TestFn)
656314564Sdim                  .reduceList(MiscompiledFunctions);
657314564Sdim      if (Error E = Ret.takeError())
658314564Sdim        return std::move(E);
659193323Sed
660207618Srdivacky      outs() << "\n*** The following function"
661207618Srdivacky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
662207618Srdivacky             << " being miscompiled: ";
663207618Srdivacky      PrintFunctionList(MiscompiledFunctions);
664207618Srdivacky      outs() << '\n';
665207618Srdivacky    }
666193323Sed  }
667193323Sed
668207618Srdivacky  if (!BugpointIsInterrupted && !DisableBlockExtraction) {
669314564Sdim    Expected<bool> Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions);
670314564Sdim    if (Error E = Ret.takeError())
671314564Sdim      return std::move(E);
672314564Sdim    if (*Ret) {
673207618Srdivacky      // Okay, we extracted some blocks and the problem still appears.  See if
674207618Srdivacky      // we can eliminate some of the created functions from being candidates.
675207618Srdivacky      DisambiguateGlobalSymbols(BD.getProgram());
676193323Sed
677207618Srdivacky      // Do the reduction...
678314564Sdim      Ret = ReduceMiscompilingFunctions(BD, TestFn)
679314564Sdim                .reduceList(MiscompiledFunctions);
680314564Sdim      if (Error E = Ret.takeError())
681314564Sdim        return std::move(E);
682193323Sed
683207618Srdivacky      outs() << "\n*** The following function"
684207618Srdivacky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
685207618Srdivacky             << " being miscompiled: ";
686207618Srdivacky      PrintFunctionList(MiscompiledFunctions);
687207618Srdivacky      outs() << '\n';
688207618Srdivacky    }
689193323Sed  }
690193323Sed
691193323Sed  return MiscompiledFunctions;
692193323Sed}
693193323Sed
694296417Sdim/// This is the predicate function used to check to see if the "Test" portion of
695296417Sdim/// the program is misoptimized.  If so, return true.  In any case, both module
696296417Sdim/// arguments are deleted.
697193323Sed///
698314564Sdimstatic Expected<bool> TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
699314564Sdim                                    std::unique_ptr<Module> Safe) {
700193323Sed  // Run the optimization passes on ToOptimize, producing a transformed version
701193323Sed  // of the functions being tested.
702198090Srdivacky  outs() << "  Optimizing functions being tested: ";
703296417Sdim  std::unique_ptr<Module> Optimized =
704309124Sdim      BD.runPassesOn(Test.get(), BD.getPassesToRun());
705309124Sdim  if (!Optimized) {
706309124Sdim    errs() << " Error running this sequence of passes"
707309124Sdim           << " on the input program!\n";
708353358Sdim    BD.EmitProgressBitcode(*Test, "pass-error", false);
709341825Sdim    BD.setNewProgram(std::move(Test));
710314564Sdim    if (Error E = BD.debugOptimizerCrash())
711314564Sdim      return std::move(E);
712314564Sdim    return false;
713309124Sdim  }
714198090Srdivacky  outs() << "done.\n";
715193323Sed
716198090Srdivacky  outs() << "  Checking to see if the merged program executes correctly: ";
717212793Sdim  bool Broken;
718321369Sdim  auto Result = testMergedProgram(BD, *Optimized, *Safe, Broken);
719314564Sdim  if (Error E = Result.takeError())
720314564Sdim    return std::move(E);
721314564Sdim  if (auto New = std::move(*Result)) {
722212793Sdim    outs() << (Broken ? " nope.\n" : " yup.\n");
723212793Sdim    // Delete the original and set the new program.
724341825Sdim    BD.setNewProgram(std::move(New));
725212793Sdim  }
726193323Sed  return Broken;
727193323Sed}
728193323Sed
729193323Sed/// debugMiscompilation - This method is used when the passes selected are not
730193323Sed/// crashing, but the generated output is semantically different from the
731193323Sed/// input.
732193323Sed///
733314564SdimError BugDriver::debugMiscompilation() {
734193323Sed  // Make sure something was miscompiled...
735314564Sdim  if (!BugpointIsInterrupted) {
736314564Sdim    Expected<bool> Result =
737314564Sdim        ReduceMiscompilingPasses(*this).reduceList(PassesToRun);
738314564Sdim    if (Error E = Result.takeError())
739314564Sdim      return E;
740314564Sdim    if (!*Result)
741314564Sdim      return make_error<StringError>(
742314564Sdim          "*** Optimized program matches reference output!  No problem"
743314564Sdim          " detected...\nbugpoint can't help you with your problem!\n",
744314564Sdim          inconvertibleErrorCode());
745314564Sdim  }
746193323Sed
747198090Srdivacky  outs() << "\n*** Found miscompiling pass"
748198090Srdivacky         << (getPassesToRun().size() == 1 ? "" : "es") << ": "
749198090Srdivacky         << getPassesString(getPassesToRun()) << '\n';
750341825Sdim  EmitProgressBitcode(*Program, "passinput");
751193323Sed
752314564Sdim  Expected<std::vector<Function *>> MiscompiledFunctions =
753314564Sdim      DebugAMiscompilation(*this, TestOptimizer);
754314564Sdim  if (Error E = MiscompiledFunctions.takeError())
755314564Sdim    return E;
756193323Sed
757193323Sed  // Output a bunch of bitcode files for the user...
758198090Srdivacky  outs() << "Outputting reduced bitcode files which expose the problem:\n";
759218885Sdim  ValueToValueMapTy VMap;
760296417Sdim  Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
761296417Sdim  Module *ToOptimize =
762314564Sdim      SplitFunctionsOutOfModule(ToNotOptimize, *MiscompiledFunctions, VMap)
763296417Sdim          .release();
764193323Sed
765198090Srdivacky  outs() << "  Non-optimized portion: ";
766341825Sdim  EmitProgressBitcode(*ToNotOptimize, "tonotoptimize", true);
767314564Sdim  delete ToNotOptimize; // Delete hacked module.
768193323Sed
769198090Srdivacky  outs() << "  Portion that is input to optimizer: ";
770341825Sdim  EmitProgressBitcode(*ToOptimize, "tooptimize");
771314564Sdim  delete ToOptimize; // Delete hacked module.
772314564Sdim
773314564Sdim  return Error::success();
774193323Sed}
775193323Sed
776296417Sdim/// Get the specified modules ready for code generator testing.
777193323Sed///
778341825Sdimstatic std::unique_ptr<Module>
779341825SdimCleanupAndPrepareModules(BugDriver &BD, std::unique_ptr<Module> Test,
780341825Sdim                         Module *Safe) {
781193323Sed  // Clean up the modules, removing extra cruft that we don't need anymore...
782341825Sdim  Test = BD.performFinalCleanups(std::move(Test));
783193323Sed
784193323Sed  // If we are executing the JIT, we have several nasty issues to take care of.
785314564Sdim  if (!BD.isExecutingJIT())
786341825Sdim    return Test;
787193323Sed
788193323Sed  // First, if the main function is in the Safe module, we must add a stub to
789193323Sed  // the Test module to call into it.  Thus, we create a new function `main'
790193323Sed  // which just calls the old one.
791193323Sed  if (Function *oldMain = Safe->getFunction("main"))
792193323Sed    if (!oldMain->isDeclaration()) {
793193323Sed      // Rename it
794193323Sed      oldMain->setName("llvm_bugpoint_old_main");
795193323Sed      // Create a NEW `main' function with same type in the test module.
796296417Sdim      Function *newMain =
797296417Sdim          Function::Create(oldMain->getFunctionType(),
798296417Sdim                           GlobalValue::ExternalLinkage, "main", Test.get());
799193323Sed      // Create an `oldmain' prototype in the test module, which will
800193323Sed      // corresponds to the real main function in the same module.
801193323Sed      Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
802193323Sed                                                GlobalValue::ExternalLinkage,
803296417Sdim                                                oldMain->getName(), Test.get());
804193323Sed      // Set up and remember the argument list for the main function.
805314564Sdim      std::vector<Value *> args;
806314564Sdim      for (Function::arg_iterator I = newMain->arg_begin(),
807314564Sdim                                  E = newMain->arg_end(),
808314564Sdim                                  OI = oldMain->arg_begin();
809314564Sdim           I != E; ++I, ++OI) {
810314564Sdim        I->setName(OI->getName()); // Copy argument names from oldMain
811296417Sdim        args.push_back(&*I);
812193323Sed      }
813193323Sed
814193323Sed      // Call the old main function and return its result
815198090Srdivacky      BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
816224133Sdim      CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
817193323Sed
818193323Sed      // If the type of old function wasn't void, return value of call
819198090Srdivacky      ReturnInst::Create(Safe->getContext(), call, BB);
820193323Sed    }
821193323Sed
822193323Sed  // The second nasty issue we must deal with in the JIT is that the Safe
823193323Sed  // module cannot directly reference any functions defined in the test
824193323Sed  // module.  Instead, we use a JIT API call to dynamically resolve the
825193323Sed  // symbol.
826193323Sed
827193323Sed  // Add the resolver to the Safe module.
828193323Sed  // Prototype: void *getPointerToNamedFunction(const char* Name)
829353358Sdim  FunctionCallee resolverFunc = Safe->getOrInsertFunction(
830314564Sdim      "getPointerToNamedFunction", Type::getInt8PtrTy(Safe->getContext()),
831321369Sdim      Type::getInt8PtrTy(Safe->getContext()));
832193323Sed
833193323Sed  // Use the function we just added to get addresses of functions we need.
834193323Sed  for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
835353358Sdim    if (F->isDeclaration() && !F->use_empty() &&
836353358Sdim        &*F != resolverFunc.getCallee() &&
837193323Sed        !F->isIntrinsic() /* ignore intrinsics */) {
838193323Sed      Function *TestFn = Test->getFunction(F->getName());
839193323Sed
840193323Sed      // Don't forward functions which are external in the test module too.
841193323Sed      if (TestFn && !TestFn->isDeclaration()) {
842193323Sed        // 1. Add a string constant with its name to the global file
843234353Sdim        Constant *InitArray =
844314564Sdim            ConstantDataArray::getString(F->getContext(), F->getName());
845314564Sdim        GlobalVariable *funcName = new GlobalVariable(
846314564Sdim            *Safe, InitArray->getType(), true /*isConstant*/,
847314564Sdim            GlobalValue::InternalLinkage, InitArray, F->getName() + "_name");
848193323Sed
849193323Sed        // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
850193323Sed        // sbyte* so it matches the signature of the resolver function.
851193323Sed
852193323Sed        // GetElementPtr *funcName, ulong 0, ulong 0
853314564Sdim        std::vector<Constant *> GEPargs(
854314564Sdim            2, Constant::getNullValue(Type::getInt32Ty(F->getContext())));
855288943Sdim        Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
856288943Sdim                                                    funcName, GEPargs);
857314564Sdim        std::vector<Value *> ResolverArgs;
858193323Sed        ResolverArgs.push_back(GEP);
859193323Sed
860193323Sed        // Rewrite uses of F in global initializers, etc. to uses of a wrapper
861193323Sed        // function that dynamically resolves the calls to F via our JIT API
862193323Sed        if (!F->use_empty()) {
863193323Sed          // Create a new global to hold the cached function pointer.
864193323Sed          Constant *NullPtr = ConstantPointerNull::get(F->getType());
865314564Sdim          GlobalVariable *Cache = new GlobalVariable(
866314564Sdim              *F->getParent(), F->getType(), false,
867314564Sdim              GlobalValue::InternalLinkage, NullPtr, F->getName() + ".fpcache");
868193323Sed
869193323Sed          // Construct a new stub function that will re-route calls to F
870226584Sdim          FunctionType *FuncTy = F->getFunctionType();
871314564Sdim          Function *FuncWrapper =
872314564Sdim              Function::Create(FuncTy, GlobalValue::InternalLinkage,
873314564Sdim                               F->getName() + "_wrapper", F->getParent());
874314564Sdim          BasicBlock *EntryBB =
875314564Sdim              BasicBlock::Create(F->getContext(), "entry", FuncWrapper);
876314564Sdim          BasicBlock *DoCallBB =
877314564Sdim              BasicBlock::Create(F->getContext(), "usecache", FuncWrapper);
878314564Sdim          BasicBlock *LookupBB =
879314564Sdim              BasicBlock::Create(F->getContext(), "lookupfp", FuncWrapper);
880193323Sed
881193323Sed          // Check to see if we already looked up the value.
882353358Sdim          Value *CachedVal =
883353358Sdim              new LoadInst(F->getType(), Cache, "fpcache", EntryBB);
884198090Srdivacky          Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
885198090Srdivacky                                       NullPtr, "isNull");
886193323Sed          BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
887193323Sed
888193323Sed          // Resolve the call to function F via the JIT API:
889193323Sed          //
890193323Sed          // call resolver(GetElementPtr...)
891314564Sdim          CallInst *Resolver = CallInst::Create(resolverFunc, ResolverArgs,
892314564Sdim                                                "resolver", LookupBB);
893193323Sed
894193323Sed          // Cast the result from the resolver to correctly-typed function.
895314564Sdim          CastInst *CastedResolver = new BitCastInst(
896314564Sdim              Resolver, PointerType::getUnqual(F->getFunctionType()),
897314564Sdim              "resolverCast", LookupBB);
898193323Sed
899193323Sed          // Save the value in our cache.
900193323Sed          new StoreInst(CastedResolver, Cache, LookupBB);
901193323Sed          BranchInst::Create(DoCallBB, LookupBB);
902193323Sed
903314564Sdim          PHINode *FuncPtr =
904314564Sdim              PHINode::Create(NullPtr->getType(), 2, "fp", DoCallBB);
905193323Sed          FuncPtr->addIncoming(CastedResolver, LookupBB);
906193323Sed          FuncPtr->addIncoming(CachedVal, EntryBB);
907193323Sed
908193323Sed          // Save the argument list.
909314564Sdim          std::vector<Value *> Args;
910296417Sdim          for (Argument &A : FuncWrapper->args())
911296417Sdim            Args.push_back(&A);
912193323Sed
913193323Sed          // Pass on the arguments to the real function, return its result
914210006Srdivacky          if (F->getReturnType()->isVoidTy()) {
915353358Sdim            CallInst::Create(FuncTy, FuncPtr, Args, "", DoCallBB);
916198090Srdivacky            ReturnInst::Create(F->getContext(), DoCallBB);
917193323Sed          } else {
918314564Sdim            CallInst *Call =
919353358Sdim                CallInst::Create(FuncTy, FuncPtr, Args, "retval", DoCallBB);
920314564Sdim            ReturnInst::Create(F->getContext(), Call, DoCallBB);
921193323Sed          }
922193323Sed
923193323Sed          // Use the wrapper function instead of the old function
924193323Sed          F->replaceAllUsesWith(FuncWrapper);
925193323Sed        }
926193323Sed      }
927193323Sed    }
928193323Sed  }
929193323Sed
930193323Sed  if (verifyModule(*Test) || verifyModule(*Safe)) {
931198090Srdivacky    errs() << "Bugpoint has a bug, which corrupted a module!!\n";
932193323Sed    abort();
933193323Sed  }
934341825Sdim
935341825Sdim  return Test;
936193323Sed}
937193323Sed
938296417Sdim/// This is the predicate function used to check to see if the "Test" portion of
939296417Sdim/// the program is miscompiled by the code generator under test.  If so, return
940296417Sdim/// true.  In any case, both module arguments are deleted.
941193323Sed///
942314564Sdimstatic Expected<bool> TestCodeGenerator(BugDriver &BD,
943314564Sdim                                        std::unique_ptr<Module> Test,
944314564Sdim                                        std::unique_ptr<Module> Safe) {
945341825Sdim  Test = CleanupAndPrepareModules(BD, std::move(Test), Safe.get());
946193323Sed
947261991Sdim  SmallString<128> TestModuleBC;
948261991Sdim  int TestModuleFD;
949276479Sdim  std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
950276479Sdim                                                    TestModuleFD, TestModuleBC);
951261991Sdim  if (EC) {
952314564Sdim    errs() << BD.getToolName()
953314564Sdim           << "Error making unique filename: " << EC.message() << "\n";
954193323Sed    exit(1);
955193323Sed  }
956341825Sdim  if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, *Test)) {
957198090Srdivacky    errs() << "Error writing bitcode to `" << TestModuleBC.str()
958198090Srdivacky           << "'\nExiting.";
959193323Sed    exit(1);
960193323Sed  }
961193323Sed
962221337Sdim  FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
963210006Srdivacky
964193323Sed  // Make the shared library
965261991Sdim  SmallString<128> SafeModuleBC;
966261991Sdim  int SafeModuleFD;
967261991Sdim  EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
968261991Sdim                                    SafeModuleBC);
969261991Sdim  if (EC) {
970314564Sdim    errs() << BD.getToolName()
971314564Sdim           << "Error making unique filename: " << EC.message() << "\n";
972193323Sed    exit(1);
973193323Sed  }
974193323Sed
975341825Sdim  if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, *Safe)) {
976314564Sdim    errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
977193323Sed    exit(1);
978193323Sed  }
979210006Srdivacky
980221337Sdim  FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
981210006Srdivacky
982314564Sdim  Expected<std::string> SharedObject =
983314564Sdim      BD.compileSharedObject(SafeModuleBC.str());
984314564Sdim  if (Error E = SharedObject.takeError())
985314564Sdim    return std::move(E);
986193323Sed
987314564Sdim  FileRemover SharedObjectRemover(*SharedObject, !SaveTemps);
988210006Srdivacky
989193323Sed  // Run the code generator on the `Test' code, loading the shared library.
990193323Sed  // The function returns whether or not the new output differs from reference.
991314564Sdim  Expected<bool> Result =
992314564Sdim      BD.diffProgram(BD.getProgram(), TestModuleBC.str(), *SharedObject, false);
993314564Sdim  if (Error E = Result.takeError())
994314564Sdim    return std::move(E);
995193323Sed
996314564Sdim  if (*Result)
997198090Srdivacky    errs() << ": still failing!\n";
998193323Sed  else
999198090Srdivacky    errs() << ": didn't fail.\n";
1000193323Sed
1001193323Sed  return Result;
1002193323Sed}
1003193323Sed
1004193323Sed/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1005193323Sed///
1006314564SdimError BugDriver::debugCodeGenerator() {
1007314564Sdim  if ((void *)SafeInterpreter == (void *)Interpreter) {
1008314564Sdim    Expected<std::string> Result =
1009341825Sdim        executeProgramSafely(*Program, "bugpoint.safe.out");
1010314564Sdim    if (Result) {
1011207618Srdivacky      outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1012207618Srdivacky             << "the reference diff.  This may be due to a\n    front-end "
1013207618Srdivacky             << "bug or a bug in the original program, but this can also "
1014207618Srdivacky             << "happen if bugpoint isn't running the program with the "
1015207618Srdivacky             << "right flags or input.\n    I left the result of executing "
1016207618Srdivacky             << "the program with the \"safe\" backend in this file for "
1017314564Sdim             << "you: '" << *Result << "'.\n";
1018207618Srdivacky    }
1019314564Sdim    return Error::success();
1020193323Sed  }
1021193323Sed
1022341825Sdim  DisambiguateGlobalSymbols(*Program);
1023193323Sed
1024314564Sdim  Expected<std::vector<Function *>> Funcs =
1025314564Sdim      DebugAMiscompilation(*this, TestCodeGenerator);
1026314564Sdim  if (Error E = Funcs.takeError())
1027314564Sdim    return E;
1028193323Sed
1029193323Sed  // Split the module into the two halves of the program we want.
1030218885Sdim  ValueToValueMapTy VMap;
1031296417Sdim  std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1032296417Sdim  std::unique_ptr<Module> ToCodeGen =
1033314564Sdim      SplitFunctionsOutOfModule(ToNotCodeGen.get(), *Funcs, VMap);
1034193323Sed
1035193323Sed  // Condition the modules
1036341825Sdim  ToCodeGen =
1037341825Sdim      CleanupAndPrepareModules(*this, std::move(ToCodeGen), ToNotCodeGen.get());
1038193323Sed
1039261991Sdim  SmallString<128> TestModuleBC;
1040261991Sdim  int TestModuleFD;
1041276479Sdim  std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1042276479Sdim                                                    TestModuleFD, TestModuleBC);
1043261991Sdim  if (EC) {
1044314564Sdim    errs() << getToolName() << "Error making unique filename: " << EC.message()
1045314564Sdim           << "\n";
1046193323Sed    exit(1);
1047193323Sed  }
1048193323Sed
1049341825Sdim  if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, *ToCodeGen)) {
1050314564Sdim    errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
1051193323Sed    exit(1);
1052193323Sed  }
1053193323Sed
1054193323Sed  // Make the shared library
1055261991Sdim  SmallString<128> SafeModuleBC;
1056261991Sdim  int SafeModuleFD;
1057261991Sdim  EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1058261991Sdim                                    SafeModuleBC);
1059261991Sdim  if (EC) {
1060314564Sdim    errs() << getToolName() << "Error making unique filename: " << EC.message()
1061314564Sdim           << "\n";
1062193323Sed    exit(1);
1063193323Sed  }
1064193323Sed
1065341825Sdim  if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, *ToNotCodeGen)) {
1066314564Sdim    errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
1067193323Sed    exit(1);
1068193323Sed  }
1069314564Sdim  Expected<std::string> SharedObject = compileSharedObject(SafeModuleBC.str());
1070314564Sdim  if (Error E = SharedObject.takeError())
1071314564Sdim    return E;
1072193323Sed
1073198090Srdivacky  outs() << "You can reproduce the problem with the command line: \n";
1074193323Sed  if (isExecutingJIT()) {
1075314564Sdim    outs() << "  lli -load " << *SharedObject << " " << TestModuleBC;
1076193323Sed  } else {
1077314564Sdim    outs() << "  llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
1078314564Sdim    outs() << "  cc " << *SharedObject << " " << TestModuleBC.str() << ".s -o "
1079314564Sdim           << TestModuleBC << ".exe\n";
1080314564Sdim    outs() << "  ./" << TestModuleBC << ".exe";
1081193323Sed  }
1082207618Srdivacky  for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1083198090Srdivacky    outs() << " " << InputArgv[i];
1084198090Srdivacky  outs() << '\n';
1085198090Srdivacky  outs() << "The shared object was created with:\n  llc -march=c "
1086198090Srdivacky         << SafeModuleBC.str() << " -o temporary.c\n"
1087314564Sdim         << "  cc -xc temporary.c -O2 -o " << *SharedObject;
1088198090Srdivacky  if (TargetTriple.getArch() == Triple::sparc)
1089314564Sdim    outs() << " -G"; // Compile a shared library, `-G' for Sparc
1090198090Srdivacky  else
1091314564Sdim    outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1092193323Sed
1093198090Srdivacky  outs() << " -fno-strict-aliasing\n";
1094198090Srdivacky
1095314564Sdim  return Error::success();
1096193323Sed}
1097