Miscompilation.cpp revision 202878
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"
18193323Sed#include "llvm/Constants.h"
19193323Sed#include "llvm/DerivedTypes.h"
20193323Sed#include "llvm/Instructions.h"
21193323Sed#include "llvm/Linker.h"
22193323Sed#include "llvm/Module.h"
23193323Sed#include "llvm/Pass.h"
24193323Sed#include "llvm/Analysis/Verifier.h"
25193323Sed#include "llvm/Transforms/Utils/Cloning.h"
26193323Sed#include "llvm/Support/CommandLine.h"
27193323Sed#include "llvm/Support/FileUtilities.h"
28193323Sed#include "llvm/Config/config.h"   // for HAVE_LINK_R
29193323Sedusing namespace llvm;
30193323Sed
31193323Sednamespace llvm {
32198090Srdivacky  extern cl::opt<std::string> OutputPrefix;
33193323Sed  extern cl::list<std::string> InputArgv;
34193323Sed}
35193323Sed
36193323Sednamespace {
37193323Sed  static llvm::cl::opt<bool>
38193323Sed    DisableLoopExtraction("disable-loop-extraction",
39193323Sed        cl::desc("Don't extract loops when searching for miscompilations"),
40193323Sed        cl::init(false));
41198090Srdivacky  static llvm::cl::opt<bool>
42198090Srdivacky    DisableBlockExtraction("disable-block-extraction",
43198090Srdivacky        cl::desc("Don't extract blocks when searching for miscompilations"),
44198090Srdivacky        cl::init(false));
45193323Sed
46193323Sed  class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
47193323Sed    BugDriver &BD;
48193323Sed  public:
49193323Sed    ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
50193323Sed
51193323Sed    virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
52193323Sed                              std::vector<const PassInfo*> &Suffix);
53193323Sed  };
54193323Sed}
55193323Sed
56193323Sed/// TestResult - After passes have been split into a test group and a control
57193323Sed/// group, see if they still break the program.
58193323Sed///
59193323SedReduceMiscompilingPasses::TestResult
60193323SedReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
61193323Sed                                 std::vector<const PassInfo*> &Suffix) {
62193323Sed  // First, run the program with just the Suffix passes.  If it is still broken
63193323Sed  // with JUST the kept passes, discard the prefix passes.
64198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Suffix)
65198090Srdivacky         << "' compiles correctly: ";
66193323Sed
67193323Sed  std::string BitcodeResult;
68193323Sed  if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
69198090Srdivacky    errs() << " Error running this sequence of passes"
70198090Srdivacky           << " on the input program!\n";
71193323Sed    BD.setPassesToRun(Suffix);
72193323Sed    BD.EmitProgressBitcode("pass-error",  false);
73193323Sed    exit(BD.debugOptimizerCrash());
74193323Sed  }
75198090Srdivacky
76193323Sed  // Check to see if the finished program matches the reference output...
77193323Sed  if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
78198090Srdivacky    outs() << " nope.\n";
79193323Sed    if (Suffix.empty()) {
80198090Srdivacky      errs() << BD.getToolName() << ": I'm confused: the test fails when "
81198090Srdivacky             << "no passes are run, nondeterministic program?\n";
82193323Sed      exit(1);
83193323Sed    }
84193323Sed    return KeepSuffix;         // Miscompilation detected!
85193323Sed  }
86198090Srdivacky  outs() << " yup.\n";      // No miscompilation!
87193323Sed
88193323Sed  if (Prefix.empty()) return NoFailure;
89193323Sed
90193323Sed  // Next, see if the program is broken if we run the "prefix" passes first,
91193323Sed  // then separately run the "kept" passes.
92198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Prefix)
93198090Srdivacky         << "' compiles correctly: ";
94193323Sed
95193323Sed  // If it is not broken with the kept passes, it's possible that the prefix
96193323Sed  // passes must be run before the kept passes to break it.  If the program
97193323Sed  // WORKS after the prefix passes, but then fails if running the prefix AND
98193323Sed  // kept passes, we can update our bitcode file to include the result of the
99193323Sed  // prefix passes, then discard the prefix passes.
100193323Sed  //
101193323Sed  if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
102198090Srdivacky    errs() << " Error running this sequence of passes"
103198090Srdivacky           << " on the input program!\n";
104193323Sed    BD.setPassesToRun(Prefix);
105193323Sed    BD.EmitProgressBitcode("pass-error",  false);
106193323Sed    exit(BD.debugOptimizerCrash());
107193323Sed  }
108193323Sed
109193323Sed  // If the prefix maintains the predicate by itself, only keep the prefix!
110193323Sed  if (BD.diffProgram(BitcodeResult)) {
111198090Srdivacky    outs() << " nope.\n";
112193323Sed    sys::Path(BitcodeResult).eraseFromDisk();
113193323Sed    return KeepPrefix;
114193323Sed  }
115198090Srdivacky  outs() << " yup.\n";      // No miscompilation!
116193323Sed
117193323Sed  // Ok, so now we know that the prefix passes work, try running the suffix
118193323Sed  // passes on the result of the prefix passes.
119193323Sed  //
120195340Sed  Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
121193323Sed  if (PrefixOutput == 0) {
122198090Srdivacky    errs() << BD.getToolName() << ": Error reading bitcode file '"
123198090Srdivacky           << BitcodeResult << "'!\n";
124193323Sed    exit(1);
125193323Sed  }
126193323Sed  sys::Path(BitcodeResult).eraseFromDisk();  // No longer need the file on disk
127193323Sed
128193323Sed  // Don't check if there are no passes in the suffix.
129193323Sed  if (Suffix.empty())
130193323Sed    return NoFailure;
131193323Sed
132198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Suffix)
133193323Sed            << "' passes compile correctly after the '"
134193323Sed            << getPassesString(Prefix) << "' passes: ";
135193323Sed
136193323Sed  Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
137193323Sed  if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
138198090Srdivacky    errs() << " Error running this sequence of passes"
139198090Srdivacky           << " on the input program!\n";
140193323Sed    BD.setPassesToRun(Suffix);
141193323Sed    BD.EmitProgressBitcode("pass-error",  false);
142193323Sed    exit(BD.debugOptimizerCrash());
143193323Sed  }
144193323Sed
145193323Sed  // Run the result...
146193323Sed  if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
147198090Srdivacky    outs() << " nope.\n";
148193323Sed    delete OriginalInput;     // We pruned down the original input...
149193323Sed    return KeepSuffix;
150193323Sed  }
151193323Sed
152193323Sed  // Otherwise, we must not be running the bad pass anymore.
153198090Srdivacky  outs() << " yup.\n";      // No miscompilation!
154193323Sed  delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
155193323Sed  return NoFailure;
156193323Sed}
157193323Sed
158193323Sednamespace {
159193323Sed  class ReduceMiscompilingFunctions : public ListReducer<Function*> {
160193323Sed    BugDriver &BD;
161193323Sed    bool (*TestFn)(BugDriver &, Module *, Module *);
162193323Sed  public:
163193323Sed    ReduceMiscompilingFunctions(BugDriver &bd,
164193323Sed                                bool (*F)(BugDriver &, Module *, Module *))
165193323Sed      : BD(bd), TestFn(F) {}
166193323Sed
167193323Sed    virtual TestResult doTest(std::vector<Function*> &Prefix,
168193323Sed                              std::vector<Function*> &Suffix) {
169193323Sed      if (!Suffix.empty() && TestFuncs(Suffix))
170193323Sed        return KeepSuffix;
171193323Sed      if (!Prefix.empty() && TestFuncs(Prefix))
172193323Sed        return KeepPrefix;
173193323Sed      return NoFailure;
174193323Sed    }
175193323Sed
176193323Sed    bool TestFuncs(const std::vector<Function*> &Prefix);
177193323Sed  };
178193323Sed}
179193323Sed
180193323Sed/// TestMergedProgram - Given two modules, link them together and run the
181193323Sed/// program, checking to see if the program matches the diff.  If the diff
182193323Sed/// matches, return false, otherwise return true.  If the DeleteInputs argument
183193323Sed/// is set to true then this function deletes both input modules before it
184193323Sed/// returns.
185193323Sed///
186193323Sedstatic bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
187193323Sed                              bool DeleteInputs) {
188193323Sed  // Link the two portions of the program back to together.
189193323Sed  std::string ErrorMsg;
190193323Sed  if (!DeleteInputs) {
191193323Sed    M1 = CloneModule(M1);
192193323Sed    M2 = CloneModule(M2);
193193323Sed  }
194193323Sed  if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
195198090Srdivacky    errs() << BD.getToolName() << ": Error linking modules together:"
196198090Srdivacky           << ErrorMsg << '\n';
197193323Sed    exit(1);
198193323Sed  }
199193323Sed  delete M2;   // We are done with this module.
200193323Sed
201193323Sed  Module *OldProgram = BD.swapProgramIn(M1);
202193323Sed
203193323Sed  // Execute the program.  If it does not match the expected output, we must
204193323Sed  // return true.
205193323Sed  bool Broken = BD.diffProgram();
206193323Sed
207193323Sed  // Delete the linked module & restore the original
208193323Sed  BD.swapProgramIn(OldProgram);
209193323Sed  delete M1;
210193323Sed  return Broken;
211193323Sed}
212193323Sed
213193323Sed/// TestFuncs - split functions in a Module into two groups: those that are
214193323Sed/// under consideration for miscompilation vs. those that are not, and test
215193323Sed/// accordingly. Each group of functions becomes a separate Module.
216193323Sed///
217193323Sedbool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
218193323Sed  // Test to see if the function is misoptimized if we ONLY run it on the
219193323Sed  // functions listed in Funcs.
220198090Srdivacky  outs() << "Checking to see if the program is misoptimized when "
221198090Srdivacky         << (Funcs.size()==1 ? "this function is" : "these functions are")
222198090Srdivacky         << " run through the pass"
223198090Srdivacky         << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
224193323Sed  PrintFunctionList(Funcs);
225198090Srdivacky  outs() << '\n';
226193323Sed
227193323Sed  // Split the module into the two halves of the program we want.
228193323Sed  DenseMap<const Value*, Value*> ValueMap;
229193323Sed  Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
230193323Sed  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
231193323Sed                                                 ValueMap);
232193323Sed
233193323Sed  // Run the predicate, note that the predicate will delete both input modules.
234193323Sed  return TestFn(BD, ToOptimize, ToNotOptimize);
235193323Sed}
236193323Sed
237202878Srdivacky/// DisambiguateGlobalSymbols - Give anonymous global values names.
238193323Sed///
239193323Sedstatic void DisambiguateGlobalSymbols(Module *M) {
240193323Sed  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
241202878Srdivacky       I != E; ++I)
242202878Srdivacky    if (!I->hasName())
243202878Srdivacky      I->setName("anon_global");
244202878Srdivacky  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
245202878Srdivacky    if (!I->hasName())
246202878Srdivacky      I->setName("anon_fn");
247193323Sed}
248193323Sed
249193323Sed/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
250193323Sed/// check to see if we can extract the loops in the region without obscuring the
251193323Sed/// bug.  If so, it reduces the amount of code identified.
252193323Sed///
253193323Sedstatic bool ExtractLoops(BugDriver &BD,
254193323Sed                         bool (*TestFn)(BugDriver &, Module *, Module *),
255193323Sed                         std::vector<Function*> &MiscompiledFunctions) {
256193323Sed  bool MadeChange = false;
257193323Sed  while (1) {
258193323Sed    if (BugpointIsInterrupted) return MadeChange;
259193323Sed
260193323Sed    DenseMap<const Value*, Value*> ValueMap;
261193323Sed    Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
262193323Sed    Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
263193323Sed                                                   MiscompiledFunctions,
264193323Sed                                                   ValueMap);
265193323Sed    Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
266193323Sed    if (!ToOptimizeLoopExtracted) {
267193323Sed      // If the loop extractor crashed or if there were no extractible loops,
268193323Sed      // then this chapter of our odyssey is over with.
269193323Sed      delete ToNotOptimize;
270193323Sed      delete ToOptimize;
271193323Sed      return MadeChange;
272193323Sed    }
273193323Sed
274198090Srdivacky    errs() << "Extracted a loop from the breaking portion of the program.\n";
275193323Sed
276193323Sed    // Bugpoint is intentionally not very trusting of LLVM transformations.  In
277193323Sed    // particular, we're not going to assume that the loop extractor works, so
278193323Sed    // we're going to test the newly loop extracted program to make sure nothing
279193323Sed    // has broken.  If something broke, then we'll inform the user and stop
280193323Sed    // extraction.
281193323Sed    AbstractInterpreter *AI = BD.switchToSafeInterpreter();
282193323Sed    if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
283193323Sed      BD.switchToInterpreter(AI);
284193323Sed
285193323Sed      // Merged program doesn't work anymore!
286198090Srdivacky      errs() << "  *** ERROR: Loop extraction broke the program. :("
287198090Srdivacky             << " Please report a bug!\n";
288198090Srdivacky      errs() << "      Continuing on with un-loop-extracted version.\n";
289193323Sed
290198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
291198090Srdivacky                            ToNotOptimize);
292198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
293198090Srdivacky                            ToOptimize);
294198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
295193323Sed                            ToOptimizeLoopExtracted);
296193323Sed
297198090Srdivacky      errs() << "Please submit the "
298198090Srdivacky             << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
299193323Sed      delete ToOptimize;
300193323Sed      delete ToNotOptimize;
301193323Sed      delete ToOptimizeLoopExtracted;
302193323Sed      return MadeChange;
303193323Sed    }
304193323Sed    delete ToOptimize;
305193323Sed    BD.switchToInterpreter(AI);
306193323Sed
307198090Srdivacky    outs() << "  Testing after loop extraction:\n";
308193323Sed    // Clone modules, the tester function will free them.
309193323Sed    Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
310193323Sed    Module *TNOBackup  = CloneModule(ToNotOptimize);
311193323Sed    if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
312198090Srdivacky      outs() << "*** Loop extraction masked the problem.  Undoing.\n";
313193323Sed      // If the program is not still broken, then loop extraction did something
314193323Sed      // that masked the error.  Stop loop extraction now.
315193323Sed      delete TOLEBackup;
316193323Sed      delete TNOBackup;
317193323Sed      return MadeChange;
318193323Sed    }
319193323Sed    ToOptimizeLoopExtracted = TOLEBackup;
320193323Sed    ToNotOptimize = TNOBackup;
321193323Sed
322198090Srdivacky    outs() << "*** Loop extraction successful!\n";
323193323Sed
324193323Sed    std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
325193323Sed    for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
326193323Sed           E = ToOptimizeLoopExtracted->end(); I != E; ++I)
327193323Sed      if (!I->isDeclaration())
328193323Sed        MisCompFunctions.push_back(std::make_pair(I->getName(),
329193323Sed                                                  I->getFunctionType()));
330193323Sed
331193323Sed    // Okay, great!  Now we know that we extracted a loop and that loop
332193323Sed    // extraction both didn't break the program, and didn't mask the problem.
333193323Sed    // Replace the current program with the loop extracted version, and try to
334193323Sed    // extract another loop.
335193323Sed    std::string ErrorMsg;
336193323Sed    if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
337198090Srdivacky      errs() << BD.getToolName() << ": Error linking modules together:"
338198090Srdivacky             << ErrorMsg << '\n';
339193323Sed      exit(1);
340193323Sed    }
341193323Sed    delete ToOptimizeLoopExtracted;
342193323Sed
343193323Sed    // All of the Function*'s in the MiscompiledFunctions list are in the old
344193323Sed    // module.  Update this list to include all of the functions in the
345193323Sed    // optimized and loop extracted module.
346193323Sed    MiscompiledFunctions.clear();
347193323Sed    for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
348193323Sed      Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
349193323Sed
350193323Sed      assert(NewF && "Function not found??");
351193323Sed      assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
352193323Sed             "found wrong function type?");
353193323Sed      MiscompiledFunctions.push_back(NewF);
354193323Sed    }
355193323Sed
356193323Sed    BD.setNewProgram(ToNotOptimize);
357193323Sed    MadeChange = true;
358193323Sed  }
359193323Sed}
360193323Sed
361193323Sednamespace {
362193323Sed  class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
363193323Sed    BugDriver &BD;
364193323Sed    bool (*TestFn)(BugDriver &, Module *, Module *);
365193323Sed    std::vector<Function*> FunctionsBeingTested;
366193323Sed  public:
367193323Sed    ReduceMiscompiledBlocks(BugDriver &bd,
368193323Sed                            bool (*F)(BugDriver &, Module *, Module *),
369193323Sed                            const std::vector<Function*> &Fns)
370193323Sed      : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
371193323Sed
372193323Sed    virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
373193323Sed                              std::vector<BasicBlock*> &Suffix) {
374193323Sed      if (!Suffix.empty() && TestFuncs(Suffix))
375193323Sed        return KeepSuffix;
376193323Sed      if (TestFuncs(Prefix))
377193323Sed        return KeepPrefix;
378193323Sed      return NoFailure;
379193323Sed    }
380193323Sed
381193323Sed    bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
382193323Sed  };
383193323Sed}
384193323Sed
385193323Sed/// TestFuncs - Extract all blocks for the miscompiled functions except for the
386193323Sed/// specified blocks.  If the problem still exists, return true.
387193323Sed///
388193323Sedbool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
389193323Sed  // Test to see if the function is misoptimized if we ONLY run it on the
390193323Sed  // functions listed in Funcs.
391198090Srdivacky  outs() << "Checking to see if the program is misoptimized when all ";
392193323Sed  if (!BBs.empty()) {
393198090Srdivacky    outs() << "but these " << BBs.size() << " blocks are extracted: ";
394193323Sed    for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
395198090Srdivacky      outs() << BBs[i]->getName() << " ";
396198090Srdivacky    if (BBs.size() > 10) outs() << "...";
397193323Sed  } else {
398198090Srdivacky    outs() << "blocks are extracted.";
399193323Sed  }
400198090Srdivacky  outs() << '\n';
401193323Sed
402193323Sed  // Split the module into the two halves of the program we want.
403193323Sed  DenseMap<const Value*, Value*> ValueMap;
404193323Sed  Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
405193323Sed  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
406193323Sed                                                 FunctionsBeingTested,
407193323Sed                                                 ValueMap);
408193323Sed
409193323Sed  // Try the extraction.  If it doesn't work, then the block extractor crashed
410193323Sed  // or something, in which case bugpoint can't chase down this possibility.
411193323Sed  if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
412193323Sed    delete ToOptimize;
413193323Sed    // Run the predicate, not that the predicate will delete both input modules.
414193323Sed    return TestFn(BD, New, ToNotOptimize);
415193323Sed  }
416193323Sed  delete ToOptimize;
417193323Sed  delete ToNotOptimize;
418193323Sed  return false;
419193323Sed}
420193323Sed
421193323Sed
422193323Sed/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
423193323Sed/// extract as many basic blocks from the region as possible without obscuring
424193323Sed/// the bug.
425193323Sed///
426193323Sedstatic bool ExtractBlocks(BugDriver &BD,
427193323Sed                          bool (*TestFn)(BugDriver &, Module *, Module *),
428193323Sed                          std::vector<Function*> &MiscompiledFunctions) {
429193323Sed  if (BugpointIsInterrupted) return false;
430193323Sed
431193323Sed  std::vector<BasicBlock*> Blocks;
432193323Sed  for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
433193323Sed    for (Function::iterator I = MiscompiledFunctions[i]->begin(),
434193323Sed           E = MiscompiledFunctions[i]->end(); I != E; ++I)
435193323Sed      Blocks.push_back(I);
436193323Sed
437193323Sed  // Use the list reducer to identify blocks that can be extracted without
438193323Sed  // obscuring the bug.  The Blocks list will end up containing blocks that must
439193323Sed  // be retained from the original program.
440193323Sed  unsigned OldSize = Blocks.size();
441193323Sed
442193323Sed  // Check to see if all blocks are extractible first.
443193323Sed  if (ReduceMiscompiledBlocks(BD, TestFn,
444193323Sed                  MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
445193323Sed    Blocks.clear();
446193323Sed  } else {
447193323Sed    ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
448193323Sed    if (Blocks.size() == OldSize)
449193323Sed      return false;
450193323Sed  }
451193323Sed
452193323Sed  DenseMap<const Value*, Value*> ValueMap;
453193323Sed  Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
454193323Sed  Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
455193323Sed                                                MiscompiledFunctions,
456193323Sed                                                ValueMap);
457193323Sed  Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
458193323Sed  if (Extracted == 0) {
459193323Sed    // Weird, extraction should have worked.
460198090Srdivacky    errs() << "Nondeterministic problem extracting blocks??\n";
461193323Sed    delete ProgClone;
462193323Sed    delete ToExtract;
463193323Sed    return false;
464193323Sed  }
465193323Sed
466193323Sed  // Otherwise, block extraction succeeded.  Link the two program fragments back
467193323Sed  // together.
468193323Sed  delete ToExtract;
469193323Sed
470193323Sed  std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
471193323Sed  for (Module::iterator I = Extracted->begin(), E = Extracted->end();
472193323Sed       I != E; ++I)
473193323Sed    if (!I->isDeclaration())
474193323Sed      MisCompFunctions.push_back(std::make_pair(I->getName(),
475193323Sed                                                I->getFunctionType()));
476193323Sed
477193323Sed  std::string ErrorMsg;
478193323Sed  if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
479198090Srdivacky    errs() << BD.getToolName() << ": Error linking modules together:"
480198090Srdivacky           << ErrorMsg << '\n';
481193323Sed    exit(1);
482193323Sed  }
483193323Sed  delete Extracted;
484193323Sed
485193323Sed  // Set the new program and delete the old one.
486193323Sed  BD.setNewProgram(ProgClone);
487193323Sed
488193323Sed  // Update the list of miscompiled functions.
489193323Sed  MiscompiledFunctions.clear();
490193323Sed
491193323Sed  for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
492193323Sed    Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
493193323Sed    assert(NewF && "Function not found??");
494193323Sed    assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
495193323Sed           "Function has wrong type??");
496193323Sed    MiscompiledFunctions.push_back(NewF);
497193323Sed  }
498193323Sed
499193323Sed  return true;
500193323Sed}
501193323Sed
502193323Sed
503193323Sed/// DebugAMiscompilation - This is a generic driver to narrow down
504193323Sed/// miscompilations, either in an optimization or a code generator.
505193323Sed///
506193323Sedstatic std::vector<Function*>
507193323SedDebugAMiscompilation(BugDriver &BD,
508193323Sed                     bool (*TestFn)(BugDriver &, Module *, Module *)) {
509193323Sed  // Okay, now that we have reduced the list of passes which are causing the
510193323Sed  // failure, see if we can pin down which functions are being
511193323Sed  // miscompiled... first build a list of all of the non-external functions in
512193323Sed  // the program.
513193323Sed  std::vector<Function*> MiscompiledFunctions;
514193323Sed  Module *Prog = BD.getProgram();
515193323Sed  for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
516193323Sed    if (!I->isDeclaration())
517193323Sed      MiscompiledFunctions.push_back(I);
518193323Sed
519193323Sed  // Do the reduction...
520193323Sed  if (!BugpointIsInterrupted)
521193323Sed    ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
522193323Sed
523198090Srdivacky  outs() << "\n*** The following function"
524198090Srdivacky         << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
525198090Srdivacky         << " being miscompiled: ";
526193323Sed  PrintFunctionList(MiscompiledFunctions);
527198090Srdivacky  outs() << '\n';
528193323Sed
529193323Sed  // See if we can rip any loops out of the miscompiled functions and still
530193323Sed  // trigger the problem.
531193323Sed
532193323Sed  if (!BugpointIsInterrupted && !DisableLoopExtraction &&
533193323Sed      ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
534193323Sed    // Okay, we extracted some loops and the problem still appears.  See if we
535193323Sed    // can eliminate some of the created functions from being candidates.
536193323Sed    DisambiguateGlobalSymbols(BD.getProgram());
537193323Sed
538193323Sed    // Do the reduction...
539193323Sed    if (!BugpointIsInterrupted)
540193323Sed      ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
541193323Sed
542198090Srdivacky    outs() << "\n*** The following function"
543198090Srdivacky           << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
544198090Srdivacky           << " being miscompiled: ";
545193323Sed    PrintFunctionList(MiscompiledFunctions);
546198090Srdivacky    outs() << '\n';
547193323Sed  }
548193323Sed
549198090Srdivacky  if (!BugpointIsInterrupted && !DisableBlockExtraction &&
550193323Sed      ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
551193323Sed    // Okay, we extracted some blocks and the problem still appears.  See if we
552193323Sed    // can eliminate some of the created functions from being candidates.
553193323Sed    DisambiguateGlobalSymbols(BD.getProgram());
554193323Sed
555193323Sed    // Do the reduction...
556193323Sed    ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
557193323Sed
558198090Srdivacky    outs() << "\n*** The following function"
559198090Srdivacky           << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
560198090Srdivacky           << " being miscompiled: ";
561193323Sed    PrintFunctionList(MiscompiledFunctions);
562198090Srdivacky    outs() << '\n';
563193323Sed  }
564193323Sed
565193323Sed  return MiscompiledFunctions;
566193323Sed}
567193323Sed
568193323Sed/// TestOptimizer - This is the predicate function used to check to see if the
569193323Sed/// "Test" portion of the program is misoptimized.  If so, return true.  In any
570193323Sed/// case, both module arguments are deleted.
571193323Sed///
572193323Sedstatic bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
573193323Sed  // Run the optimization passes on ToOptimize, producing a transformed version
574193323Sed  // of the functions being tested.
575198090Srdivacky  outs() << "  Optimizing functions being tested: ";
576193323Sed  Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
577193323Sed                                     /*AutoDebugCrashes*/true);
578198090Srdivacky  outs() << "done.\n";
579193323Sed  delete Test;
580193323Sed
581198090Srdivacky  outs() << "  Checking to see if the merged program executes correctly: ";
582193323Sed  bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
583198090Srdivacky  outs() << (Broken ? " nope.\n" : " yup.\n");
584193323Sed  return Broken;
585193323Sed}
586193323Sed
587193323Sed
588193323Sed/// debugMiscompilation - This method is used when the passes selected are not
589193323Sed/// crashing, but the generated output is semantically different from the
590193323Sed/// input.
591193323Sed///
592193323Sedbool BugDriver::debugMiscompilation() {
593193323Sed  // Make sure something was miscompiled...
594193323Sed  if (!BugpointIsInterrupted)
595193323Sed    if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
596198090Srdivacky      errs() << "*** Optimized program matches reference output!  No problem"
597198090Srdivacky             << " detected...\nbugpoint can't help you with your problem!\n";
598193323Sed      return false;
599193323Sed    }
600193323Sed
601198090Srdivacky  outs() << "\n*** Found miscompiling pass"
602198090Srdivacky         << (getPassesToRun().size() == 1 ? "" : "es") << ": "
603198090Srdivacky         << getPassesString(getPassesToRun()) << '\n';
604193323Sed  EmitProgressBitcode("passinput");
605193323Sed
606193323Sed  std::vector<Function*> MiscompiledFunctions =
607193323Sed    DebugAMiscompilation(*this, TestOptimizer);
608193323Sed
609193323Sed  // Output a bunch of bitcode files for the user...
610198090Srdivacky  outs() << "Outputting reduced bitcode files which expose the problem:\n";
611193323Sed  DenseMap<const Value*, Value*> ValueMap;
612193323Sed  Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
613193323Sed  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
614193323Sed                                                 MiscompiledFunctions,
615193323Sed                                                 ValueMap);
616193323Sed
617198090Srdivacky  outs() << "  Non-optimized portion: ";
618193323Sed  ToNotOptimize = swapProgramIn(ToNotOptimize);
619193323Sed  EmitProgressBitcode("tonotoptimize", true);
620193323Sed  setNewProgram(ToNotOptimize);   // Delete hacked module.
621193323Sed
622198090Srdivacky  outs() << "  Portion that is input to optimizer: ";
623193323Sed  ToOptimize = swapProgramIn(ToOptimize);
624193323Sed  EmitProgressBitcode("tooptimize");
625193323Sed  setNewProgram(ToOptimize);      // Delete hacked module.
626193323Sed
627193323Sed  return false;
628193323Sed}
629193323Sed
630193323Sed/// CleanupAndPrepareModules - Get the specified modules ready for code
631193323Sed/// generator testing.
632193323Sed///
633193323Sedstatic void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
634193323Sed                                     Module *Safe) {
635193323Sed  // Clean up the modules, removing extra cruft that we don't need anymore...
636193323Sed  Test = BD.performFinalCleanups(Test);
637193323Sed
638193323Sed  // If we are executing the JIT, we have several nasty issues to take care of.
639193323Sed  if (!BD.isExecutingJIT()) return;
640193323Sed
641193323Sed  // First, if the main function is in the Safe module, we must add a stub to
642193323Sed  // the Test module to call into it.  Thus, we create a new function `main'
643193323Sed  // which just calls the old one.
644193323Sed  if (Function *oldMain = Safe->getFunction("main"))
645193323Sed    if (!oldMain->isDeclaration()) {
646193323Sed      // Rename it
647193323Sed      oldMain->setName("llvm_bugpoint_old_main");
648193323Sed      // Create a NEW `main' function with same type in the test module.
649193323Sed      Function *newMain = Function::Create(oldMain->getFunctionType(),
650193323Sed                                           GlobalValue::ExternalLinkage,
651193323Sed                                           "main", Test);
652193323Sed      // Create an `oldmain' prototype in the test module, which will
653193323Sed      // corresponds to the real main function in the same module.
654193323Sed      Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
655193323Sed                                                GlobalValue::ExternalLinkage,
656193323Sed                                                oldMain->getName(), Test);
657193323Sed      // Set up and remember the argument list for the main function.
658193323Sed      std::vector<Value*> args;
659193323Sed      for (Function::arg_iterator
660193323Sed             I = newMain->arg_begin(), E = newMain->arg_end(),
661193323Sed             OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
662193323Sed        I->setName(OI->getName());    // Copy argument names from oldMain
663193323Sed        args.push_back(I);
664193323Sed      }
665193323Sed
666193323Sed      // Call the old main function and return its result
667198090Srdivacky      BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
668193323Sed      CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
669193323Sed                                        "", BB);
670193323Sed
671193323Sed      // If the type of old function wasn't void, return value of call
672198090Srdivacky      ReturnInst::Create(Safe->getContext(), call, BB);
673193323Sed    }
674193323Sed
675193323Sed  // The second nasty issue we must deal with in the JIT is that the Safe
676193323Sed  // module cannot directly reference any functions defined in the test
677193323Sed  // module.  Instead, we use a JIT API call to dynamically resolve the
678193323Sed  // symbol.
679193323Sed
680193323Sed  // Add the resolver to the Safe module.
681193323Sed  // Prototype: void *getPointerToNamedFunction(const char* Name)
682193323Sed  Constant *resolverFunc =
683193323Sed    Safe->getOrInsertFunction("getPointerToNamedFunction",
684198090Srdivacky                    Type::getInt8PtrTy(Safe->getContext()),
685198090Srdivacky                    Type::getInt8PtrTy(Safe->getContext()),
686198090Srdivacky                       (Type *)0);
687193323Sed
688193323Sed  // Use the function we just added to get addresses of functions we need.
689193323Sed  for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
690193323Sed    if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
691193323Sed        !F->isIntrinsic() /* ignore intrinsics */) {
692193323Sed      Function *TestFn = Test->getFunction(F->getName());
693193323Sed
694193323Sed      // Don't forward functions which are external in the test module too.
695193323Sed      if (TestFn && !TestFn->isDeclaration()) {
696193323Sed        // 1. Add a string constant with its name to the global file
697198090Srdivacky        Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
698193323Sed        GlobalVariable *funcName =
699198090Srdivacky          new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
700193323Sed                             GlobalValue::InternalLinkage, InitArray,
701198090Srdivacky                             F->getName() + "_name");
702193323Sed
703193323Sed        // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
704193323Sed        // sbyte* so it matches the signature of the resolver function.
705193323Sed
706193323Sed        // GetElementPtr *funcName, ulong 0, ulong 0
707198090Srdivacky        std::vector<Constant*> GEPargs(2,
708198090Srdivacky                     Constant::getNullValue(Type::getInt32Ty(F->getContext())));
709198090Srdivacky        Value *GEP =
710198090Srdivacky                ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
711193323Sed        std::vector<Value*> ResolverArgs;
712193323Sed        ResolverArgs.push_back(GEP);
713193323Sed
714193323Sed        // Rewrite uses of F in global initializers, etc. to uses of a wrapper
715193323Sed        // function that dynamically resolves the calls to F via our JIT API
716193323Sed        if (!F->use_empty()) {
717193323Sed          // Create a new global to hold the cached function pointer.
718193323Sed          Constant *NullPtr = ConstantPointerNull::get(F->getType());
719193323Sed          GlobalVariable *Cache =
720198090Srdivacky            new GlobalVariable(*F->getParent(), F->getType(),
721198090Srdivacky                               false, GlobalValue::InternalLinkage,
722198090Srdivacky                               NullPtr,F->getName()+".fpcache");
723193323Sed
724193323Sed          // Construct a new stub function that will re-route calls to F
725193323Sed          const FunctionType *FuncTy = F->getFunctionType();
726193323Sed          Function *FuncWrapper = Function::Create(FuncTy,
727193323Sed                                                   GlobalValue::InternalLinkage,
728193323Sed                                                   F->getName() + "_wrapper",
729193323Sed                                                   F->getParent());
730198090Srdivacky          BasicBlock *EntryBB  = BasicBlock::Create(F->getContext(),
731198090Srdivacky                                                    "entry", FuncWrapper);
732198090Srdivacky          BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
733198090Srdivacky                                                    "usecache", FuncWrapper);
734198090Srdivacky          BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
735198090Srdivacky                                                    "lookupfp", FuncWrapper);
736193323Sed
737193323Sed          // Check to see if we already looked up the value.
738193323Sed          Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
739198090Srdivacky          Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
740198090Srdivacky                                       NullPtr, "isNull");
741193323Sed          BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
742193323Sed
743193323Sed          // Resolve the call to function F via the JIT API:
744193323Sed          //
745193323Sed          // call resolver(GetElementPtr...)
746193323Sed          CallInst *Resolver =
747193323Sed            CallInst::Create(resolverFunc, ResolverArgs.begin(),
748193323Sed                             ResolverArgs.end(), "resolver", LookupBB);
749193323Sed
750193323Sed          // Cast the result from the resolver to correctly-typed function.
751193323Sed          CastInst *CastedResolver =
752193323Sed            new BitCastInst(Resolver,
753193323Sed                            PointerType::getUnqual(F->getFunctionType()),
754193323Sed                            "resolverCast", LookupBB);
755193323Sed
756193323Sed          // Save the value in our cache.
757193323Sed          new StoreInst(CastedResolver, Cache, LookupBB);
758193323Sed          BranchInst::Create(DoCallBB, LookupBB);
759193323Sed
760193323Sed          PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
761193323Sed                                             "fp", DoCallBB);
762193323Sed          FuncPtr->addIncoming(CastedResolver, LookupBB);
763193323Sed          FuncPtr->addIncoming(CachedVal, EntryBB);
764193323Sed
765193323Sed          // Save the argument list.
766193323Sed          std::vector<Value*> Args;
767193323Sed          for (Function::arg_iterator i = FuncWrapper->arg_begin(),
768193323Sed                 e = FuncWrapper->arg_end(); i != e; ++i)
769193323Sed            Args.push_back(i);
770193323Sed
771193323Sed          // Pass on the arguments to the real function, return its result
772198090Srdivacky          if (F->getReturnType() == Type::getVoidTy(F->getContext())) {
773193323Sed            CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
774198090Srdivacky            ReturnInst::Create(F->getContext(), DoCallBB);
775193323Sed          } else {
776193323Sed            CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
777193323Sed                                              "retval", DoCallBB);
778198090Srdivacky            ReturnInst::Create(F->getContext(),Call, DoCallBB);
779193323Sed          }
780193323Sed
781193323Sed          // Use the wrapper function instead of the old function
782193323Sed          F->replaceAllUsesWith(FuncWrapper);
783193323Sed        }
784193323Sed      }
785193323Sed    }
786193323Sed  }
787193323Sed
788193323Sed  if (verifyModule(*Test) || verifyModule(*Safe)) {
789198090Srdivacky    errs() << "Bugpoint has a bug, which corrupted a module!!\n";
790193323Sed    abort();
791193323Sed  }
792193323Sed}
793193323Sed
794193323Sed
795193323Sed
796193323Sed/// TestCodeGenerator - This is the predicate function used to check to see if
797193323Sed/// the "Test" portion of the program is miscompiled by the code generator under
798193323Sed/// test.  If so, return true.  In any case, both module arguments are deleted.
799193323Sed///
800193323Sedstatic bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
801193323Sed  CleanupAndPrepareModules(BD, Test, Safe);
802193323Sed
803193323Sed  sys::Path TestModuleBC("bugpoint.test.bc");
804193323Sed  std::string ErrMsg;
805193323Sed  if (TestModuleBC.makeUnique(true, &ErrMsg)) {
806198090Srdivacky    errs() << BD.getToolName() << "Error making unique filename: "
807198090Srdivacky           << ErrMsg << "\n";
808193323Sed    exit(1);
809193323Sed  }
810198090Srdivacky  if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
811198090Srdivacky    errs() << "Error writing bitcode to `" << TestModuleBC.str()
812198090Srdivacky           << "'\nExiting.";
813193323Sed    exit(1);
814193323Sed  }
815193323Sed  delete Test;
816193323Sed
817193323Sed  // Make the shared library
818193323Sed  sys::Path SafeModuleBC("bugpoint.safe.bc");
819193323Sed  if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
820198090Srdivacky    errs() << BD.getToolName() << "Error making unique filename: "
821198090Srdivacky           << ErrMsg << "\n";
822193323Sed    exit(1);
823193323Sed  }
824193323Sed
825198090Srdivacky  if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
826198090Srdivacky    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
827198090Srdivacky           << "'\nExiting.";
828193323Sed    exit(1);
829193323Sed  }
830198090Srdivacky  std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str());
831193323Sed  delete Safe;
832193323Sed
833193323Sed  // Run the code generator on the `Test' code, loading the shared library.
834193323Sed  // The function returns whether or not the new output differs from reference.
835198090Srdivacky  int Result = BD.diffProgram(TestModuleBC.str(), SharedObject, false);
836193323Sed
837193323Sed  if (Result)
838198090Srdivacky    errs() << ": still failing!\n";
839193323Sed  else
840198090Srdivacky    errs() << ": didn't fail.\n";
841193323Sed  TestModuleBC.eraseFromDisk();
842193323Sed  SafeModuleBC.eraseFromDisk();
843193323Sed  sys::Path(SharedObject).eraseFromDisk();
844193323Sed
845193323Sed  return Result;
846193323Sed}
847193323Sed
848193323Sed
849193323Sed/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
850193323Sed///
851193323Sedbool BugDriver::debugCodeGenerator() {
852193323Sed  if ((void*)SafeInterpreter == (void*)Interpreter) {
853193323Sed    std::string Result = executeProgramSafely("bugpoint.safe.out");
854198090Srdivacky    outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
855198090Srdivacky           << "the reference diff.  This may be due to a\n    front-end "
856198090Srdivacky           << "bug or a bug in the original program, but this can also "
857198090Srdivacky           << "happen if bugpoint isn't running the program with the "
858198090Srdivacky           << "right flags or input.\n    I left the result of executing "
859198090Srdivacky           << "the program with the \"safe\" backend in this file for "
860198090Srdivacky           << "you: '"
861198090Srdivacky           << Result << "'.\n";
862193323Sed    return true;
863193323Sed  }
864193323Sed
865193323Sed  DisambiguateGlobalSymbols(Program);
866193323Sed
867193323Sed  std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
868193323Sed
869193323Sed  // Split the module into the two halves of the program we want.
870193323Sed  DenseMap<const Value*, Value*> ValueMap;
871193323Sed  Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
872193323Sed  Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
873193323Sed
874193323Sed  // Condition the modules
875193323Sed  CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
876193323Sed
877193323Sed  sys::Path TestModuleBC("bugpoint.test.bc");
878193323Sed  std::string ErrMsg;
879193323Sed  if (TestModuleBC.makeUnique(true, &ErrMsg)) {
880198090Srdivacky    errs() << getToolName() << "Error making unique filename: "
881198090Srdivacky           << ErrMsg << "\n";
882193323Sed    exit(1);
883193323Sed  }
884193323Sed
885198090Srdivacky  if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
886198090Srdivacky    errs() << "Error writing bitcode to `" << TestModuleBC.str()
887198090Srdivacky           << "'\nExiting.";
888193323Sed    exit(1);
889193323Sed  }
890193323Sed  delete ToCodeGen;
891193323Sed
892193323Sed  // Make the shared library
893193323Sed  sys::Path SafeModuleBC("bugpoint.safe.bc");
894193323Sed  if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
895198090Srdivacky    errs() << getToolName() << "Error making unique filename: "
896198090Srdivacky           << ErrMsg << "\n";
897193323Sed    exit(1);
898193323Sed  }
899193323Sed
900198090Srdivacky  if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
901198090Srdivacky    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
902198090Srdivacky           << "'\nExiting.";
903193323Sed    exit(1);
904193323Sed  }
905198090Srdivacky  std::string SharedObject = compileSharedObject(SafeModuleBC.str());
906193323Sed  delete ToNotCodeGen;
907193323Sed
908198090Srdivacky  outs() << "You can reproduce the problem with the command line: \n";
909193323Sed  if (isExecutingJIT()) {
910198090Srdivacky    outs() << "  lli -load " << SharedObject << " " << TestModuleBC.str();
911193323Sed  } else {
912198090Srdivacky    outs() << "  llc -f " << TestModuleBC.str() << " -o " << TestModuleBC.str()
913198090Srdivacky           << ".s\n";
914198090Srdivacky    outs() << "  gcc " << SharedObject << " " << TestModuleBC.str()
915198090Srdivacky              << ".s -o " << TestModuleBC.str() << ".exe";
916193323Sed#if defined (HAVE_LINK_R)
917198090Srdivacky    outs() << " -Wl,-R.";
918193323Sed#endif
919198090Srdivacky    outs() << "\n";
920198090Srdivacky    outs() << "  " << TestModuleBC.str() << ".exe";
921193323Sed  }
922193323Sed  for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
923198090Srdivacky    outs() << " " << InputArgv[i];
924198090Srdivacky  outs() << '\n';
925198090Srdivacky  outs() << "The shared object was created with:\n  llc -march=c "
926198090Srdivacky         << SafeModuleBC.str() << " -o temporary.c\n"
927198090Srdivacky         << "  gcc -xc temporary.c -O2 -o " << SharedObject;
928198090Srdivacky  if (TargetTriple.getArch() == Triple::sparc)
929198090Srdivacky    outs() << " -G";              // Compile a shared library, `-G' for Sparc
930198090Srdivacky  else
931198090Srdivacky    outs() << " -fPIC -shared";   // `-shared' for Linux/X86, maybe others
932193323Sed
933198090Srdivacky  outs() << " -fno-strict-aliasing\n";
934198090Srdivacky
935193323Sed  return false;
936193323Sed}
937