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