Miscompilation.cpp revision 9adc0abad3c3ed40a268ccbcee0c74cb9e1359fe
1//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements optimizer and code generation miscompilation debugging
11// support.
12//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
16#include "ListReducer.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Linker.h"
21#include "llvm/Module.h"
22#include "llvm/Pass.h"
23#include "llvm/Analysis/Verifier.h"
24#include "llvm/Support/Mangler.h"
25#include "llvm/Transforms/Utils/Cloning.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
28#include "llvm/Config/config.h"   // for HAVE_LINK_R
29using namespace llvm;
30
31namespace llvm {
32  extern cl::list<std::string> InputArgv;
33}
34
35namespace {
36  static llvm::cl::opt<bool>
37    DisableLoopExtraction("disable-loop-extraction",
38        cl::desc("Don't extract loops when searching for miscompilations"),
39        cl::init(false));
40
41  class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
42    BugDriver &BD;
43  public:
44    ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
45
46    virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
47                              std::vector<const PassInfo*> &Suffix);
48  };
49}
50
51/// TestResult - After passes have been split into a test group and a control
52/// group, see if they still break the program.
53///
54ReduceMiscompilingPasses::TestResult
55ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
56                                 std::vector<const PassInfo*> &Suffix) {
57  // First, run the program with just the Suffix passes.  If it is still broken
58  // with JUST the kept passes, discard the prefix passes.
59  std::cout << "Checking to see if '" << getPassesString(Suffix)
60            << "' compiles correctly: ";
61
62  std::string BitcodeResult;
63  if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
64    std::cerr << " Error running this sequence of passes"
65              << " on the input program!\n";
66    BD.setPassesToRun(Suffix);
67    BD.EmitProgressBitcode("pass-error",  false);
68    exit(BD.debugOptimizerCrash());
69  }
70
71  // Check to see if the finished program matches the reference output...
72  if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
73    std::cout << " nope.\n";
74    if (Suffix.empty()) {
75      std::cerr << BD.getToolName() << ": I'm confused: the test fails when "
76                << "no passes are run, nondeterministic program?\n";
77      exit(1);
78    }
79    return KeepSuffix;         // Miscompilation detected!
80  }
81  std::cout << " yup.\n";      // No miscompilation!
82
83  if (Prefix.empty()) return NoFailure;
84
85  // Next, see if the program is broken if we run the "prefix" passes first,
86  // then separately run the "kept" passes.
87  std::cout << "Checking to see if '" << getPassesString(Prefix)
88            << "' compiles correctly: ";
89
90  // If it is not broken with the kept passes, it's possible that the prefix
91  // passes must be run before the kept passes to break it.  If the program
92  // WORKS after the prefix passes, but then fails if running the prefix AND
93  // kept passes, we can update our bitcode file to include the result of the
94  // prefix passes, then discard the prefix passes.
95  //
96  if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
97    std::cerr << " Error running this sequence of passes"
98              << " on the input program!\n";
99    BD.setPassesToRun(Prefix);
100    BD.EmitProgressBitcode("pass-error",  false);
101    exit(BD.debugOptimizerCrash());
102  }
103
104  // If the prefix maintains the predicate by itself, only keep the prefix!
105  if (BD.diffProgram(BitcodeResult)) {
106    std::cout << " nope.\n";
107    sys::Path(BitcodeResult).eraseFromDisk();
108    return KeepPrefix;
109  }
110  std::cout << " yup.\n";      // No miscompilation!
111
112  // Ok, so now we know that the prefix passes work, try running the suffix
113  // passes on the result of the prefix passes.
114  //
115  Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
116  if (PrefixOutput == 0) {
117    std::cerr << BD.getToolName() << ": Error reading bitcode file '"
118              << BitcodeResult << "'!\n";
119    exit(1);
120  }
121  sys::Path(BitcodeResult).eraseFromDisk();  // No longer need the file on disk
122
123  // Don't check if there are no passes in the suffix.
124  if (Suffix.empty())
125    return NoFailure;
126
127  std::cout << "Checking to see if '" << getPassesString(Suffix)
128            << "' passes compile correctly after the '"
129            << getPassesString(Prefix) << "' passes: ";
130
131  Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
132  if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
133    std::cerr << " Error running this sequence of passes"
134              << " on the input program!\n";
135    BD.setPassesToRun(Suffix);
136    BD.EmitProgressBitcode("pass-error",  false);
137    exit(BD.debugOptimizerCrash());
138  }
139
140  // Run the result...
141  if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
142    std::cout << " nope.\n";
143    delete OriginalInput;     // We pruned down the original input...
144    return KeepSuffix;
145  }
146
147  // Otherwise, we must not be running the bad pass anymore.
148  std::cout << " yup.\n";      // No miscompilation!
149  delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
150  return NoFailure;
151}
152
153namespace {
154  class ReduceMiscompilingFunctions : public ListReducer<Function*> {
155    BugDriver &BD;
156    bool (*TestFn)(BugDriver &, Module *, Module *);
157  public:
158    ReduceMiscompilingFunctions(BugDriver &bd,
159                                bool (*F)(BugDriver &, Module *, Module *))
160      : BD(bd), TestFn(F) {}
161
162    virtual TestResult doTest(std::vector<Function*> &Prefix,
163                              std::vector<Function*> &Suffix) {
164      if (!Suffix.empty() && TestFuncs(Suffix))
165        return KeepSuffix;
166      if (!Prefix.empty() && TestFuncs(Prefix))
167        return KeepPrefix;
168      return NoFailure;
169    }
170
171    bool TestFuncs(const std::vector<Function*> &Prefix);
172  };
173}
174
175/// TestMergedProgram - Given two modules, link them together and run the
176/// program, checking to see if the program matches the diff.  If the diff
177/// matches, return false, otherwise return true.  If the DeleteInputs argument
178/// is set to true then this function deletes both input modules before it
179/// returns.
180///
181static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
182                              bool DeleteInputs) {
183  // Link the two portions of the program back to together.
184  std::string ErrorMsg;
185  if (!DeleteInputs) {
186    M1 = CloneModule(M1);
187    M2 = CloneModule(M2);
188  }
189  if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
190    std::cerr << BD.getToolName() << ": Error linking modules together:"
191              << ErrorMsg << '\n';
192    exit(1);
193  }
194  delete M2;   // We are done with this module.
195
196  Module *OldProgram = BD.swapProgramIn(M1);
197
198  // Execute the program.  If it does not match the expected output, we must
199  // return true.
200  bool Broken = BD.diffProgram();
201
202  // Delete the linked module & restore the original
203  BD.swapProgramIn(OldProgram);
204  delete M1;
205  return Broken;
206}
207
208/// TestFuncs - split functions in a Module into two groups: those that are
209/// under consideration for miscompilation vs. those that are not, and test
210/// accordingly. Each group of functions becomes a separate Module.
211///
212bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
213  // Test to see if the function is misoptimized if we ONLY run it on the
214  // functions listed in Funcs.
215  std::cout << "Checking to see if the program is misoptimized when "
216            << (Funcs.size()==1 ? "this function is" : "these functions are")
217            << " run through the pass"
218            << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
219  PrintFunctionList(Funcs);
220  std::cout << '\n';
221
222  // Split the module into the two halves of the program we want.
223  DenseMap<const Value*, Value*> ValueMap;
224  Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
225  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
226                                                 ValueMap);
227
228  // Run the predicate, note that the predicate will delete both input modules.
229  return TestFn(BD, ToOptimize, ToNotOptimize);
230}
231
232/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
233/// modifying predominantly internal symbols rather than external ones.
234///
235static void DisambiguateGlobalSymbols(Module *M) {
236  // Try not to cause collisions by minimizing chances of renaming an
237  // already-external symbol, so take in external globals and functions as-is.
238  // The code should work correctly without disambiguation (assuming the same
239  // mangler is used by the two code generators), but having symbols with the
240  // same name causes warnings to be emitted by the code generator.
241  Mangler Mang(*M);
242  // Agree with the CBE on symbol naming
243  Mang.markCharUnacceptable('.');
244  Mang.setPreserveAsmNames(true);
245  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
246       I != E; ++I)
247    I->setName(Mang.getMangledName(I));
248  for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I)
249    I->setName(Mang.getMangledName(I));
250}
251
252/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
253/// check to see if we can extract the loops in the region without obscuring the
254/// bug.  If so, it reduces the amount of code identified.
255///
256static bool ExtractLoops(BugDriver &BD,
257                         bool (*TestFn)(BugDriver &, Module *, Module *),
258                         std::vector<Function*> &MiscompiledFunctions) {
259  bool MadeChange = false;
260  while (1) {
261    if (BugpointIsInterrupted) return MadeChange;
262
263    DenseMap<const Value*, Value*> ValueMap;
264    Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
265    Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
266                                                   MiscompiledFunctions,
267                                                   ValueMap);
268    Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
269    if (!ToOptimizeLoopExtracted) {
270      // If the loop extractor crashed or if there were no extractible loops,
271      // then this chapter of our odyssey is over with.
272      delete ToNotOptimize;
273      delete ToOptimize;
274      return MadeChange;
275    }
276
277    std::cerr << "Extracted a loop from the breaking portion of the program.\n";
278
279    // Bugpoint is intentionally not very trusting of LLVM transformations.  In
280    // particular, we're not going to assume that the loop extractor works, so
281    // we're going to test the newly loop extracted program to make sure nothing
282    // has broken.  If something broke, then we'll inform the user and stop
283    // extraction.
284    AbstractInterpreter *AI = BD.switchToSafeInterpreter();
285    if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
286      BD.switchToInterpreter(AI);
287
288      // Merged program doesn't work anymore!
289      std::cerr << "  *** ERROR: Loop extraction broke the program. :("
290                << " Please report a bug!\n";
291      std::cerr << "      Continuing on with un-loop-extracted version.\n";
292
293      BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
294      BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
295      BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
296                            ToOptimizeLoopExtracted);
297
298      std::cerr << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
299      delete ToOptimize;
300      delete ToNotOptimize;
301      delete ToOptimizeLoopExtracted;
302      return MadeChange;
303    }
304    delete ToOptimize;
305    BD.switchToInterpreter(AI);
306
307    std::cout << "  Testing after loop extraction:\n";
308    // Clone modules, the tester function will free them.
309    Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
310    Module *TNOBackup  = CloneModule(ToNotOptimize);
311    if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
312      std::cout << "*** Loop extraction masked the problem.  Undoing.\n";
313      // If the program is not still broken, then loop extraction did something
314      // that masked the error.  Stop loop extraction now.
315      delete TOLEBackup;
316      delete TNOBackup;
317      return MadeChange;
318    }
319    ToOptimizeLoopExtracted = TOLEBackup;
320    ToNotOptimize = TNOBackup;
321
322    std::cout << "*** Loop extraction successful!\n";
323
324    std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
325    for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
326           E = ToOptimizeLoopExtracted->end(); I != E; ++I)
327      if (!I->isDeclaration())
328        MisCompFunctions.push_back(std::make_pair(I->getName(),
329                                                  I->getFunctionType()));
330
331    // Okay, great!  Now we know that we extracted a loop and that loop
332    // extraction both didn't break the program, and didn't mask the problem.
333    // Replace the current program with the loop extracted version, and try to
334    // extract another loop.
335    std::string ErrorMsg;
336    if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
337      std::cerr << BD.getToolName() << ": Error linking modules together:"
338                << ErrorMsg << '\n';
339      exit(1);
340    }
341    delete ToOptimizeLoopExtracted;
342
343    // All of the Function*'s in the MiscompiledFunctions list are in the old
344    // module.  Update this list to include all of the functions in the
345    // optimized and loop extracted module.
346    MiscompiledFunctions.clear();
347    for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
348      Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
349
350      assert(NewF && "Function not found??");
351      assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
352             "found wrong function type?");
353      MiscompiledFunctions.push_back(NewF);
354    }
355
356    BD.setNewProgram(ToNotOptimize);
357    MadeChange = true;
358  }
359}
360
361namespace {
362  class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
363    BugDriver &BD;
364    bool (*TestFn)(BugDriver &, Module *, Module *);
365    std::vector<Function*> FunctionsBeingTested;
366  public:
367    ReduceMiscompiledBlocks(BugDriver &bd,
368                            bool (*F)(BugDriver &, Module *, Module *),
369                            const std::vector<Function*> &Fns)
370      : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
371
372    virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
373                              std::vector<BasicBlock*> &Suffix) {
374      if (!Suffix.empty() && TestFuncs(Suffix))
375        return KeepSuffix;
376      if (TestFuncs(Prefix))
377        return KeepPrefix;
378      return NoFailure;
379    }
380
381    bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
382  };
383}
384
385/// TestFuncs - Extract all blocks for the miscompiled functions except for the
386/// specified blocks.  If the problem still exists, return true.
387///
388bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
389  // Test to see if the function is misoptimized if we ONLY run it on the
390  // functions listed in Funcs.
391  std::cout << "Checking to see if the program is misoptimized when all ";
392  if (!BBs.empty()) {
393    std::cout << "but these " << BBs.size() << " blocks are extracted: ";
394    for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
395      std::cout << BBs[i]->getName() << " ";
396    if (BBs.size() > 10) std::cout << "...";
397  } else {
398    std::cout << "blocks are extracted.";
399  }
400  std::cout << '\n';
401
402  // Split the module into the two halves of the program we want.
403  DenseMap<const Value*, Value*> ValueMap;
404  Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
405  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
406                                                 FunctionsBeingTested,
407                                                 ValueMap);
408
409  // Try the extraction.  If it doesn't work, then the block extractor crashed
410  // or something, in which case bugpoint can't chase down this possibility.
411  if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
412    delete ToOptimize;
413    // Run the predicate, not that the predicate will delete both input modules.
414    return TestFn(BD, New, ToNotOptimize);
415  }
416  delete ToOptimize;
417  delete ToNotOptimize;
418  return false;
419}
420
421
422/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
423/// extract as many basic blocks from the region as possible without obscuring
424/// the bug.
425///
426static bool ExtractBlocks(BugDriver &BD,
427                          bool (*TestFn)(BugDriver &, Module *, Module *),
428                          std::vector<Function*> &MiscompiledFunctions) {
429  if (BugpointIsInterrupted) return false;
430
431  std::vector<BasicBlock*> Blocks;
432  for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
433    for (Function::iterator I = MiscompiledFunctions[i]->begin(),
434           E = MiscompiledFunctions[i]->end(); I != E; ++I)
435      Blocks.push_back(I);
436
437  // Use the list reducer to identify blocks that can be extracted without
438  // obscuring the bug.  The Blocks list will end up containing blocks that must
439  // be retained from the original program.
440  unsigned OldSize = Blocks.size();
441
442  // Check to see if all blocks are extractible first.
443  if (ReduceMiscompiledBlocks(BD, TestFn,
444                  MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
445    Blocks.clear();
446  } else {
447    ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
448    if (Blocks.size() == OldSize)
449      return false;
450  }
451
452  DenseMap<const Value*, Value*> ValueMap;
453  Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
454  Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
455                                                MiscompiledFunctions,
456                                                ValueMap);
457  Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
458  if (Extracted == 0) {
459    // Weird, extraction should have worked.
460    std::cerr << "Nondeterministic problem extracting blocks??\n";
461    delete ProgClone;
462    delete ToExtract;
463    return false;
464  }
465
466  // Otherwise, block extraction succeeded.  Link the two program fragments back
467  // together.
468  delete ToExtract;
469
470  std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
471  for (Module::iterator I = Extracted->begin(), E = Extracted->end();
472       I != E; ++I)
473    if (!I->isDeclaration())
474      MisCompFunctions.push_back(std::make_pair(I->getName(),
475                                                I->getFunctionType()));
476
477  std::string ErrorMsg;
478  if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
479    std::cerr << BD.getToolName() << ": Error linking modules together:"
480              << ErrorMsg << '\n';
481    exit(1);
482  }
483  delete Extracted;
484
485  // Set the new program and delete the old one.
486  BD.setNewProgram(ProgClone);
487
488  // Update the list of miscompiled functions.
489  MiscompiledFunctions.clear();
490
491  for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
492    Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
493    assert(NewF && "Function not found??");
494    assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
495           "Function has wrong type??");
496    MiscompiledFunctions.push_back(NewF);
497  }
498
499  return true;
500}
501
502
503/// DebugAMiscompilation - This is a generic driver to narrow down
504/// miscompilations, either in an optimization or a code generator.
505///
506static std::vector<Function*>
507DebugAMiscompilation(BugDriver &BD,
508                     bool (*TestFn)(BugDriver &, Module *, Module *)) {
509  // Okay, now that we have reduced the list of passes which are causing the
510  // failure, see if we can pin down which functions are being
511  // miscompiled... first build a list of all of the non-external functions in
512  // the program.
513  std::vector<Function*> MiscompiledFunctions;
514  Module *Prog = BD.getProgram();
515  for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
516    if (!I->isDeclaration())
517      MiscompiledFunctions.push_back(I);
518
519  // Do the reduction...
520  if (!BugpointIsInterrupted)
521    ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
522
523  std::cout << "\n*** The following function"
524            << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
525            << " being miscompiled: ";
526  PrintFunctionList(MiscompiledFunctions);
527  std::cout << '\n';
528
529  // See if we can rip any loops out of the miscompiled functions and still
530  // trigger the problem.
531
532  if (!BugpointIsInterrupted && !DisableLoopExtraction &&
533      ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
534    // Okay, we extracted some loops and the problem still appears.  See if we
535    // can eliminate some of the created functions from being candidates.
536
537    // Loop extraction can introduce functions with the same name (foo_code).
538    // Make sure to disambiguate the symbols so that when the program is split
539    // apart that we can link it back together again.
540    DisambiguateGlobalSymbols(BD.getProgram());
541
542    // Do the reduction...
543    if (!BugpointIsInterrupted)
544      ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
545
546    std::cout << "\n*** The following function"
547              << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
548              << " being miscompiled: ";
549    PrintFunctionList(MiscompiledFunctions);
550    std::cout << '\n';
551  }
552
553  if (!BugpointIsInterrupted &&
554      ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
555    // Okay, we extracted some blocks and the problem still appears.  See if we
556    // can eliminate some of the created functions from being candidates.
557
558    // Block extraction can introduce functions with the same name (foo_code).
559    // Make sure to disambiguate the symbols so that when the program is split
560    // apart that we can link it back together again.
561    DisambiguateGlobalSymbols(BD.getProgram());
562
563    // Do the reduction...
564    ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
565
566    std::cout << "\n*** The following function"
567              << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
568              << " being miscompiled: ";
569    PrintFunctionList(MiscompiledFunctions);
570    std::cout << '\n';
571  }
572
573  return MiscompiledFunctions;
574}
575
576/// TestOptimizer - This is the predicate function used to check to see if the
577/// "Test" portion of the program is misoptimized.  If so, return true.  In any
578/// case, both module arguments are deleted.
579///
580static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
581  // Run the optimization passes on ToOptimize, producing a transformed version
582  // of the functions being tested.
583  std::cout << "  Optimizing functions being tested: ";
584  Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
585                                     /*AutoDebugCrashes*/true);
586  std::cout << "done.\n";
587  delete Test;
588
589  std::cout << "  Checking to see if the merged program executes correctly: ";
590  bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
591  std::cout << (Broken ? " nope.\n" : " yup.\n");
592  return Broken;
593}
594
595
596/// debugMiscompilation - This method is used when the passes selected are not
597/// crashing, but the generated output is semantically different from the
598/// input.
599///
600bool BugDriver::debugMiscompilation() {
601  // Make sure something was miscompiled...
602  if (!BugpointIsInterrupted)
603    if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
604      std::cerr << "*** Optimized program matches reference output!  No problem"
605                << " detected...\nbugpoint can't help you with your problem!\n";
606      return false;
607    }
608
609  std::cout << "\n*** Found miscompiling pass"
610            << (getPassesToRun().size() == 1 ? "" : "es") << ": "
611            << getPassesString(getPassesToRun()) << '\n';
612  EmitProgressBitcode("passinput");
613
614  std::vector<Function*> MiscompiledFunctions =
615    DebugAMiscompilation(*this, TestOptimizer);
616
617  // Output a bunch of bitcode files for the user...
618  std::cout << "Outputting reduced bitcode files which expose the problem:\n";
619  DenseMap<const Value*, Value*> ValueMap;
620  Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
621  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
622                                                 MiscompiledFunctions,
623                                                 ValueMap);
624
625  std::cout << "  Non-optimized portion: ";
626  ToNotOptimize = swapProgramIn(ToNotOptimize);
627  EmitProgressBitcode("tonotoptimize", true);
628  setNewProgram(ToNotOptimize);   // Delete hacked module.
629
630  std::cout << "  Portion that is input to optimizer: ";
631  ToOptimize = swapProgramIn(ToOptimize);
632  EmitProgressBitcode("tooptimize");
633  setNewProgram(ToOptimize);      // Delete hacked module.
634
635  return false;
636}
637
638/// CleanupAndPrepareModules - Get the specified modules ready for code
639/// generator testing.
640///
641static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
642                                     Module *Safe) {
643  LLVMContext &Context = BD.getContext();
644
645  // Clean up the modules, removing extra cruft that we don't need anymore...
646  Test = BD.performFinalCleanups(Test);
647
648  // If we are executing the JIT, we have several nasty issues to take care of.
649  if (!BD.isExecutingJIT()) return;
650
651  // First, if the main function is in the Safe module, we must add a stub to
652  // the Test module to call into it.  Thus, we create a new function `main'
653  // which just calls the old one.
654  if (Function *oldMain = Safe->getFunction("main"))
655    if (!oldMain->isDeclaration()) {
656      // Rename it
657      oldMain->setName("llvm_bugpoint_old_main");
658      // Create a NEW `main' function with same type in the test module.
659      Function *newMain = Function::Create(oldMain->getFunctionType(),
660                                           GlobalValue::ExternalLinkage,
661                                           "main", Test);
662      // Create an `oldmain' prototype in the test module, which will
663      // corresponds to the real main function in the same module.
664      Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
665                                                GlobalValue::ExternalLinkage,
666                                                oldMain->getName(), Test);
667      // Set up and remember the argument list for the main function.
668      std::vector<Value*> args;
669      for (Function::arg_iterator
670             I = newMain->arg_begin(), E = newMain->arg_end(),
671             OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
672        I->setName(OI->getName());    // Copy argument names from oldMain
673        args.push_back(I);
674      }
675
676      // Call the old main function and return its result
677      BasicBlock *BB = BasicBlock::Create("entry", newMain);
678      CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
679                                        "", BB);
680
681      // If the type of old function wasn't void, return value of call
682      ReturnInst::Create(call, BB);
683    }
684
685  // The second nasty issue we must deal with in the JIT is that the Safe
686  // module cannot directly reference any functions defined in the test
687  // module.  Instead, we use a JIT API call to dynamically resolve the
688  // symbol.
689
690  // Add the resolver to the Safe module.
691  // Prototype: void *getPointerToNamedFunction(const char* Name)
692  Constant *resolverFunc =
693    Safe->getOrInsertFunction("getPointerToNamedFunction",
694                        Context.getPointerTypeUnqual(Type::Int8Ty),
695                        Context.getPointerTypeUnqual(Type::Int8Ty), (Type *)0);
696
697  // Use the function we just added to get addresses of functions we need.
698  for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
699    if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
700        !F->isIntrinsic() /* ignore intrinsics */) {
701      Function *TestFn = Test->getFunction(F->getName());
702
703      // Don't forward functions which are external in the test module too.
704      if (TestFn && !TestFn->isDeclaration()) {
705        // 1. Add a string constant with its name to the global file
706        Constant *InitArray = Context.getConstantArray(F->getName());
707        GlobalVariable *funcName =
708          new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
709                             GlobalValue::InternalLinkage, InitArray,
710                             F->getName() + "_name");
711
712        // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
713        // sbyte* so it matches the signature of the resolver function.
714
715        // GetElementPtr *funcName, ulong 0, ulong 0
716        std::vector<Constant*> GEPargs(2, Context.getNullValue(Type::Int32Ty));
717        Value *GEP =
718                Context.getConstantExprGetElementPtr(funcName, &GEPargs[0], 2);
719        std::vector<Value*> ResolverArgs;
720        ResolverArgs.push_back(GEP);
721
722        // Rewrite uses of F in global initializers, etc. to uses of a wrapper
723        // function that dynamically resolves the calls to F via our JIT API
724        if (!F->use_empty()) {
725          // Create a new global to hold the cached function pointer.
726          Constant *NullPtr = Context.getConstantPointerNull(F->getType());
727          GlobalVariable *Cache =
728            new GlobalVariable(*F->getParent(), F->getType(),
729                               false, GlobalValue::InternalLinkage,
730                               NullPtr,F->getName()+".fpcache");
731
732          // Construct a new stub function that will re-route calls to F
733          const FunctionType *FuncTy = F->getFunctionType();
734          Function *FuncWrapper = Function::Create(FuncTy,
735                                                   GlobalValue::InternalLinkage,
736                                                   F->getName() + "_wrapper",
737                                                   F->getParent());
738          BasicBlock *EntryBB  = BasicBlock::Create("entry", FuncWrapper);
739          BasicBlock *DoCallBB = BasicBlock::Create("usecache", FuncWrapper);
740          BasicBlock *LookupBB = BasicBlock::Create("lookupfp", FuncWrapper);
741
742          // Check to see if we already looked up the value.
743          Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
744          Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
745                                       NullPtr, "isNull");
746          BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
747
748          // Resolve the call to function F via the JIT API:
749          //
750          // call resolver(GetElementPtr...)
751          CallInst *Resolver =
752            CallInst::Create(resolverFunc, ResolverArgs.begin(),
753                             ResolverArgs.end(), "resolver", LookupBB);
754
755          // Cast the result from the resolver to correctly-typed function.
756          CastInst *CastedResolver =
757            new BitCastInst(Resolver,
758                            Context.getPointerTypeUnqual(F->getFunctionType()),
759                            "resolverCast", LookupBB);
760
761          // Save the value in our cache.
762          new StoreInst(CastedResolver, Cache, LookupBB);
763          BranchInst::Create(DoCallBB, LookupBB);
764
765          PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
766                                             "fp", DoCallBB);
767          FuncPtr->addIncoming(CastedResolver, LookupBB);
768          FuncPtr->addIncoming(CachedVal, EntryBB);
769
770          // Save the argument list.
771          std::vector<Value*> Args;
772          for (Function::arg_iterator i = FuncWrapper->arg_begin(),
773                 e = FuncWrapper->arg_end(); i != e; ++i)
774            Args.push_back(i);
775
776          // Pass on the arguments to the real function, return its result
777          if (F->getReturnType() == Type::VoidTy) {
778            CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
779            ReturnInst::Create(DoCallBB);
780          } else {
781            CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
782                                              "retval", DoCallBB);
783            ReturnInst::Create(Call, DoCallBB);
784          }
785
786          // Use the wrapper function instead of the old function
787          F->replaceAllUsesWith(FuncWrapper);
788        }
789      }
790    }
791  }
792
793  if (verifyModule(*Test) || verifyModule(*Safe)) {
794    std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
795    abort();
796  }
797}
798
799
800
801/// TestCodeGenerator - This is the predicate function used to check to see if
802/// the "Test" portion of the program is miscompiled by the code generator under
803/// test.  If so, return true.  In any case, both module arguments are deleted.
804///
805static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
806  CleanupAndPrepareModules(BD, Test, Safe);
807
808  sys::Path TestModuleBC("bugpoint.test.bc");
809  std::string ErrMsg;
810  if (TestModuleBC.makeUnique(true, &ErrMsg)) {
811    std::cerr << BD.getToolName() << "Error making unique filename: "
812              << ErrMsg << "\n";
813    exit(1);
814  }
815  if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
816    std::cerr << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
817    exit(1);
818  }
819  delete Test;
820
821  // Make the shared library
822  sys::Path SafeModuleBC("bugpoint.safe.bc");
823  if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
824    std::cerr << BD.getToolName() << "Error making unique filename: "
825              << ErrMsg << "\n";
826    exit(1);
827  }
828
829  if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
830    std::cerr << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
831    exit(1);
832  }
833  std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
834  delete Safe;
835
836  // Run the code generator on the `Test' code, loading the shared library.
837  // The function returns whether or not the new output differs from reference.
838  int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
839
840  if (Result)
841    std::cerr << ": still failing!\n";
842  else
843    std::cerr << ": didn't fail.\n";
844  TestModuleBC.eraseFromDisk();
845  SafeModuleBC.eraseFromDisk();
846  sys::Path(SharedObject).eraseFromDisk();
847
848  return Result;
849}
850
851
852/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
853///
854bool BugDriver::debugCodeGenerator() {
855  if ((void*)SafeInterpreter == (void*)Interpreter) {
856    std::string Result = executeProgramSafely("bugpoint.safe.out");
857    std::cout << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
858              << "the reference diff.  This may be due to a\n    front-end "
859              << "bug or a bug in the original program, but this can also "
860              << "happen if bugpoint isn't running the program with the "
861              << "right flags or input.\n    I left the result of executing "
862              << "the program with the \"safe\" backend in this file for "
863              << "you: '"
864              << Result << "'.\n";
865    return true;
866  }
867
868  DisambiguateGlobalSymbols(Program);
869
870  std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
871
872  // Split the module into the two halves of the program we want.
873  DenseMap<const Value*, Value*> ValueMap;
874  Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
875  Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
876
877  // Condition the modules
878  CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
879
880  sys::Path TestModuleBC("bugpoint.test.bc");
881  std::string ErrMsg;
882  if (TestModuleBC.makeUnique(true, &ErrMsg)) {
883    std::cerr << getToolName() << "Error making unique filename: "
884              << ErrMsg << "\n";
885    exit(1);
886  }
887
888  if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
889    std::cerr << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
890    exit(1);
891  }
892  delete ToCodeGen;
893
894  // Make the shared library
895  sys::Path SafeModuleBC("bugpoint.safe.bc");
896  if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
897    std::cerr << getToolName() << "Error making unique filename: "
898              << ErrMsg << "\n";
899    exit(1);
900  }
901
902  if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
903    std::cerr << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
904    exit(1);
905  }
906  std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
907  delete ToNotCodeGen;
908
909  std::cout << "You can reproduce the problem with the command line: \n";
910  if (isExecutingJIT()) {
911    std::cout << "  lli -load " << SharedObject << " " << TestModuleBC;
912  } else {
913    std::cout << "  llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
914    std::cout << "  gcc " << SharedObject << " " << TestModuleBC
915              << ".s -o " << TestModuleBC << ".exe";
916#if defined (HAVE_LINK_R)
917    std::cout << " -Wl,-R.";
918#endif
919    std::cout << "\n";
920    std::cout << "  " << TestModuleBC << ".exe";
921  }
922  for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
923    std::cout << " " << InputArgv[i];
924  std::cout << '\n';
925  std::cout << "The shared object was created with:\n  llc -march=c "
926            << SafeModuleBC << " -o temporary.c\n"
927            << "  gcc -xc temporary.c -O2 -o " << SharedObject
928#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
929            << " -G"            // Compile a shared library, `-G' for Sparc
930#else
931            << " -fPIC -shared"       // `-shared' for Linux/X86, maybe others
932#endif
933            << " -fno-strict-aliasing\n";
934
935  return false;
936}
937