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