• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Linker.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/Config/config.h"   // for HAVE_LINK_R
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:
ReduceMiscompilingPasses(BugDriver & bd)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
doTest(std::vector<std::string> & Prefix,std::vector<std::string> & Suffix,std::string & Error)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::Path(BitcodeResult).eraseFromDisk();
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 == 0) {
134     errs() << BD.getToolName() << ": Error reading bitcode file '"
135            << BitcodeResult << "'!\n";
136     exit(1);
137   }
138   sys::Path(BitcodeResult).eraseFromDisk();  // No longer need the file on disk
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.take()));
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.take());
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:
ReduceMiscompilingFunctions(BugDriver & bd,bool (* F)(BugDriver &,Module *,Module *,std::string &))180     ReduceMiscompilingFunctions(BugDriver &bd,
181                                 bool (*F)(BugDriver &, Module *, Module *,
182                                           std::string &))
183       : BD(bd), TestFn(F) {}
184 
doTest(std::vector<Function * > & Prefix,std::vector<Function * > & Suffix,std::string & Error)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 ///
TestMergedProgram(const BugDriver & BD,Module * M1,Module * M2,bool DeleteInputs,std::string & Error,bool & Broken)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, &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 ///
TestFuncs(const std::vector<Function * > & Funcs,std::string & Error)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 ///
DisambiguateGlobalSymbols(Module * M)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 ///
ExtractLoops(BugDriver & BD,bool (* TestFn)(BugDriver &,Module *,Module *,std::string &),std::vector<Function * > & MiscompiledFunctions,std::string & Error)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     // Delete the original and set the new program.
341     delete BD.swapProgramIn(New);
342     if (Failure) {
343       BD.switchToInterpreter(AI);
344 
345       // Merged program doesn't work anymore!
346       errs() << "  *** ERROR: Loop extraction broke the program. :("
347              << " Please report a bug!\n";
348       errs() << "      Continuing on with un-loop-extracted version.\n";
349 
350       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
351                             ToNotOptimize);
352       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
353                             ToOptimize);
354       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
355                             ToOptimizeLoopExtracted);
356 
357       errs() << "Please submit the "
358              << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
359       delete ToOptimize;
360       delete ToNotOptimize;
361       delete ToOptimizeLoopExtracted;
362       return MadeChange;
363     }
364     delete ToOptimize;
365     BD.switchToInterpreter(AI);
366 
367     outs() << "  Testing after loop extraction:\n";
368     // Clone modules, the tester function will free them.
369     Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
370     Module *TNOBackup  = CloneModule(ToNotOptimize);
371     Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
372     if (!Error.empty())
373       return false;
374     if (!Failure) {
375       outs() << "*** Loop extraction masked the problem.  Undoing.\n";
376       // If the program is not still broken, then loop extraction did something
377       // that masked the error.  Stop loop extraction now.
378       delete TOLEBackup;
379       delete TNOBackup;
380       return MadeChange;
381     }
382     ToOptimizeLoopExtracted = TOLEBackup;
383     ToNotOptimize = TNOBackup;
384 
385     outs() << "*** Loop extraction successful!\n";
386 
387     std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
388     for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
389            E = ToOptimizeLoopExtracted->end(); I != E; ++I)
390       if (!I->isDeclaration())
391         MisCompFunctions.push_back(std::make_pair(I->getName(),
392                                                   I->getFunctionType()));
393 
394     // Okay, great!  Now we know that we extracted a loop and that loop
395     // extraction both didn't break the program, and didn't mask the problem.
396     // Replace the current program with the loop extracted version, and try to
397     // extract another loop.
398     std::string ErrorMsg;
399     if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
400       errs() << BD.getToolName() << ": Error linking modules together:"
401              << ErrorMsg << '\n';
402       exit(1);
403     }
404     delete ToOptimizeLoopExtracted;
405 
406     // All of the Function*'s in the MiscompiledFunctions list are in the old
407     // module.  Update this list to include all of the functions in the
408     // optimized and loop extracted module.
409     MiscompiledFunctions.clear();
410     for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
411       Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
412 
413       assert(NewF && "Function not found??");
414       assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
415              "found wrong function type?");
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:
ReduceMiscompiledBlocks(BugDriver & bd,bool (* F)(BugDriver &,Module *,Module *,std::string &),const std::vector<Function * > & Fns)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 
doTest(std::vector<BasicBlock * > & Prefix,std::vector<BasicBlock * > & Suffix,std::string & Error)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 ///
TestFuncs(const std::vector<BasicBlock * > & BBs,std::string & Error)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 ///
ExtractBlocks(BugDriver & BD,bool (* TestFn)(BugDriver &,Module *,Module *,std::string &),std::vector<Function * > & MiscompiledFunctions,std::string & Error)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, &ErrorMsg)) {
581     errs() << BD.getToolName() << ": Error linking modules together:"
582            << ErrorMsg << '\n';
583     exit(1);
584   }
585   delete Extracted;
586 
587   // Set the new program and delete the old one.
588   BD.setNewProgram(ProgClone);
589 
590   // Update the list of miscompiled functions.
591   MiscompiledFunctions.clear();
592 
593   for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
594     Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
595     assert(NewF && "Function not found??");
596     assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
597            "Function has wrong type??");
598     MiscompiledFunctions.push_back(NewF);
599   }
600 
601   return true;
602 }
603 
604 
605 /// DebugAMiscompilation - This is a generic driver to narrow down
606 /// miscompilations, either in an optimization or a code generator.
607 ///
608 static std::vector<Function*>
DebugAMiscompilation(BugDriver & BD,bool (* TestFn)(BugDriver &,Module *,Module *,std::string &),std::string & Error)609 DebugAMiscompilation(BugDriver &BD,
610                      bool (*TestFn)(BugDriver &, Module *, Module *,
611                                     std::string &),
612                      std::string &Error) {
613   // Okay, now that we have reduced the list of passes which are causing the
614   // failure, see if we can pin down which functions are being
615   // miscompiled... first build a list of all of the non-external functions in
616   // the program.
617   std::vector<Function*> MiscompiledFunctions;
618   Module *Prog = BD.getProgram();
619   for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
620     if (!I->isDeclaration())
621       MiscompiledFunctions.push_back(I);
622 
623   // Do the reduction...
624   if (!BugpointIsInterrupted)
625     ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
626                                                        Error);
627   if (!Error.empty()) {
628     errs() << "\n***Cannot reduce functions: ";
629     return MiscompiledFunctions;
630   }
631   outs() << "\n*** The following function"
632          << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
633          << " being miscompiled: ";
634   PrintFunctionList(MiscompiledFunctions);
635   outs() << '\n';
636 
637   // See if we can rip any loops out of the miscompiled functions and still
638   // trigger the problem.
639 
640   if (!BugpointIsInterrupted && !DisableLoopExtraction) {
641     bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
642     if (!Error.empty())
643       return MiscompiledFunctions;
644     if (Ret) {
645       // Okay, we extracted some loops and the problem still appears.  See if
646       // we can eliminate some of the created functions from being candidates.
647       DisambiguateGlobalSymbols(BD.getProgram());
648 
649       // Do the reduction...
650       if (!BugpointIsInterrupted)
651         ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
652                                                            Error);
653       if (!Error.empty())
654         return MiscompiledFunctions;
655 
656       outs() << "\n*** The following function"
657              << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
658              << " being miscompiled: ";
659       PrintFunctionList(MiscompiledFunctions);
660       outs() << '\n';
661     }
662   }
663 
664   if (!BugpointIsInterrupted && !DisableBlockExtraction) {
665     bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
666     if (!Error.empty())
667       return MiscompiledFunctions;
668     if (Ret) {
669       // Okay, we extracted some blocks and the problem still appears.  See if
670       // we can eliminate some of the created functions from being candidates.
671       DisambiguateGlobalSymbols(BD.getProgram());
672 
673       // Do the reduction...
674       ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
675                                                          Error);
676       if (!Error.empty())
677         return MiscompiledFunctions;
678 
679       outs() << "\n*** The following function"
680              << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
681              << " being miscompiled: ";
682       PrintFunctionList(MiscompiledFunctions);
683       outs() << '\n';
684     }
685   }
686 
687   return MiscompiledFunctions;
688 }
689 
690 /// TestOptimizer - This is the predicate function used to check to see if the
691 /// "Test" portion of the program is misoptimized.  If so, return true.  In any
692 /// case, both module arguments are deleted.
693 ///
TestOptimizer(BugDriver & BD,Module * Test,Module * Safe,std::string & Error)694 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
695                           std::string &Error) {
696   // Run the optimization passes on ToOptimize, producing a transformed version
697   // of the functions being tested.
698   outs() << "  Optimizing functions being tested: ";
699   Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
700                                      /*AutoDebugCrashes*/true);
701   outs() << "done.\n";
702   delete Test;
703 
704   outs() << "  Checking to see if the merged program executes correctly: ";
705   bool Broken;
706   Module *New = TestMergedProgram(BD, Optimized, Safe, true, Error, Broken);
707   if (New) {
708     outs() << (Broken ? " nope.\n" : " yup.\n");
709     // Delete the original and set the new program.
710     delete BD.swapProgramIn(New);
711   }
712   return Broken;
713 }
714 
715 
716 /// debugMiscompilation - This method is used when the passes selected are not
717 /// crashing, but the generated output is semantically different from the
718 /// input.
719 ///
debugMiscompilation(std::string * Error)720 void BugDriver::debugMiscompilation(std::string *Error) {
721   // Make sure something was miscompiled...
722   if (!BugpointIsInterrupted)
723     if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
724       if (Error->empty())
725         errs() << "*** Optimized program matches reference output!  No problem"
726                << " detected...\nbugpoint can't help you with your problem!\n";
727       return;
728     }
729 
730   outs() << "\n*** Found miscompiling pass"
731          << (getPassesToRun().size() == 1 ? "" : "es") << ": "
732          << getPassesString(getPassesToRun()) << '\n';
733   EmitProgressBitcode(Program, "passinput");
734 
735   std::vector<Function *> MiscompiledFunctions =
736     DebugAMiscompilation(*this, TestOptimizer, *Error);
737   if (!Error->empty())
738     return;
739 
740   // Output a bunch of bitcode files for the user...
741   outs() << "Outputting reduced bitcode files which expose the problem:\n";
742   ValueToValueMapTy VMap;
743   Module *ToNotOptimize = CloneModule(getProgram(), VMap);
744   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
745                                                  MiscompiledFunctions,
746                                                  VMap);
747 
748   outs() << "  Non-optimized portion: ";
749   EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
750   delete ToNotOptimize;  // Delete hacked module.
751 
752   outs() << "  Portion that is input to optimizer: ";
753   EmitProgressBitcode(ToOptimize, "tooptimize");
754   delete ToOptimize;      // Delete hacked module.
755 
756   return;
757 }
758 
759 /// CleanupAndPrepareModules - Get the specified modules ready for code
760 /// generator testing.
761 ///
CleanupAndPrepareModules(BugDriver & BD,Module * & Test,Module * Safe)762 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
763                                      Module *Safe) {
764   // Clean up the modules, removing extra cruft that we don't need anymore...
765   Test = BD.performFinalCleanups(Test);
766 
767   // If we are executing the JIT, we have several nasty issues to take care of.
768   if (!BD.isExecutingJIT()) return;
769 
770   // First, if the main function is in the Safe module, we must add a stub to
771   // the Test module to call into it.  Thus, we create a new function `main'
772   // which just calls the old one.
773   if (Function *oldMain = Safe->getFunction("main"))
774     if (!oldMain->isDeclaration()) {
775       // Rename it
776       oldMain->setName("llvm_bugpoint_old_main");
777       // Create a NEW `main' function with same type in the test module.
778       Function *newMain = Function::Create(oldMain->getFunctionType(),
779                                            GlobalValue::ExternalLinkage,
780                                            "main", Test);
781       // Create an `oldmain' prototype in the test module, which will
782       // corresponds to the real main function in the same module.
783       Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
784                                                 GlobalValue::ExternalLinkage,
785                                                 oldMain->getName(), Test);
786       // Set up and remember the argument list for the main function.
787       std::vector<Value*> args;
788       for (Function::arg_iterator
789              I = newMain->arg_begin(), E = newMain->arg_end(),
790              OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
791         I->setName(OI->getName());    // Copy argument names from oldMain
792         args.push_back(I);
793       }
794 
795       // Call the old main function and return its result
796       BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
797       CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
798 
799       // If the type of old function wasn't void, return value of call
800       ReturnInst::Create(Safe->getContext(), call, BB);
801     }
802 
803   // The second nasty issue we must deal with in the JIT is that the Safe
804   // module cannot directly reference any functions defined in the test
805   // module.  Instead, we use a JIT API call to dynamically resolve the
806   // symbol.
807 
808   // Add the resolver to the Safe module.
809   // Prototype: void *getPointerToNamedFunction(const char* Name)
810   Constant *resolverFunc =
811     Safe->getOrInsertFunction("getPointerToNamedFunction",
812                     Type::getInt8PtrTy(Safe->getContext()),
813                     Type::getInt8PtrTy(Safe->getContext()),
814                        (Type *)0);
815 
816   // Use the function we just added to get addresses of functions we need.
817   for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
818     if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
819         !F->isIntrinsic() /* ignore intrinsics */) {
820       Function *TestFn = Test->getFunction(F->getName());
821 
822       // Don't forward functions which are external in the test module too.
823       if (TestFn && !TestFn->isDeclaration()) {
824         // 1. Add a string constant with its name to the global file
825         Constant *InitArray = ConstantArray::get(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 =
838                 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
839         std::vector<Value*> ResolverArgs;
840         ResolverArgs.push_back(GEP);
841 
842         // Rewrite uses of F in global initializers, etc. to uses of a wrapper
843         // function that dynamically resolves the calls to F via our JIT API
844         if (!F->use_empty()) {
845           // Create a new global to hold the cached function pointer.
846           Constant *NullPtr = ConstantPointerNull::get(F->getType());
847           GlobalVariable *Cache =
848             new GlobalVariable(*F->getParent(), F->getType(),
849                                false, GlobalValue::InternalLinkage,
850                                NullPtr,F->getName()+".fpcache");
851 
852           // Construct a new stub function that will re-route calls to F
853           FunctionType *FuncTy = F->getFunctionType();
854           Function *FuncWrapper = Function::Create(FuncTy,
855                                                    GlobalValue::InternalLinkage,
856                                                    F->getName() + "_wrapper",
857                                                    F->getParent());
858           BasicBlock *EntryBB  = BasicBlock::Create(F->getContext(),
859                                                     "entry", FuncWrapper);
860           BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
861                                                     "usecache", FuncWrapper);
862           BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
863                                                     "lookupfp", FuncWrapper);
864 
865           // Check to see if we already looked up the value.
866           Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
867           Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
868                                        NullPtr, "isNull");
869           BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
870 
871           // Resolve the call to function F via the JIT API:
872           //
873           // call resolver(GetElementPtr...)
874           CallInst *Resolver =
875             CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
876 
877           // Cast the result from the resolver to correctly-typed function.
878           CastInst *CastedResolver =
879             new BitCastInst(Resolver,
880                             PointerType::getUnqual(F->getFunctionType()),
881                             "resolverCast", LookupBB);
882 
883           // Save the value in our cache.
884           new StoreInst(CastedResolver, Cache, LookupBB);
885           BranchInst::Create(DoCallBB, LookupBB);
886 
887           PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
888                                              "fp", DoCallBB);
889           FuncPtr->addIncoming(CastedResolver, LookupBB);
890           FuncPtr->addIncoming(CachedVal, EntryBB);
891 
892           // Save the argument list.
893           std::vector<Value*> Args;
894           for (Function::arg_iterator i = FuncWrapper->arg_begin(),
895                  e = FuncWrapper->arg_end(); i != e; ++i)
896             Args.push_back(i);
897 
898           // Pass on the arguments to the real function, return its result
899           if (F->getReturnType()->isVoidTy()) {
900             CallInst::Create(FuncPtr, Args, "", DoCallBB);
901             ReturnInst::Create(F->getContext(), DoCallBB);
902           } else {
903             CallInst *Call = CallInst::Create(FuncPtr, Args,
904                                               "retval", DoCallBB);
905             ReturnInst::Create(F->getContext(),Call, DoCallBB);
906           }
907 
908           // Use the wrapper function instead of the old function
909           F->replaceAllUsesWith(FuncWrapper);
910         }
911       }
912     }
913   }
914 
915   if (verifyModule(*Test) || verifyModule(*Safe)) {
916     errs() << "Bugpoint has a bug, which corrupted a module!!\n";
917     abort();
918   }
919 }
920 
921 
922 
923 /// TestCodeGenerator - This is the predicate function used to check to see if
924 /// the "Test" portion of the program is miscompiled by the code generator under
925 /// test.  If so, return true.  In any case, both module arguments are deleted.
926 ///
TestCodeGenerator(BugDriver & BD,Module * Test,Module * Safe,std::string & Error)927 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
928                               std::string &Error) {
929   CleanupAndPrepareModules(BD, Test, Safe);
930 
931   sys::Path TestModuleBC("bugpoint.test.bc");
932   std::string ErrMsg;
933   if (TestModuleBC.makeUnique(true, &ErrMsg)) {
934     errs() << BD.getToolName() << "Error making unique filename: "
935            << ErrMsg << "\n";
936     exit(1);
937   }
938   if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
939     errs() << "Error writing bitcode to `" << TestModuleBC.str()
940            << "'\nExiting.";
941     exit(1);
942   }
943   delete Test;
944 
945   FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
946 
947   // Make the shared library
948   sys::Path SafeModuleBC("bugpoint.safe.bc");
949   if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
950     errs() << BD.getToolName() << "Error making unique filename: "
951            << ErrMsg << "\n";
952     exit(1);
953   }
954 
955   if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
956     errs() << "Error writing bitcode to `" << SafeModuleBC.str()
957            << "'\nExiting.";
958     exit(1);
959   }
960 
961   FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
962 
963   std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
964   if (!Error.empty())
965     return false;
966   delete Safe;
967 
968   FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
969 
970   // Run the code generator on the `Test' code, loading the shared library.
971   // The function returns whether or not the new output differs from reference.
972   bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
973                                SharedObject, false, &Error);
974   if (!Error.empty())
975     return false;
976 
977   if (Result)
978     errs() << ": still failing!\n";
979   else
980     errs() << ": didn't fail.\n";
981 
982   return Result;
983 }
984 
985 
986 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
987 ///
debugCodeGenerator(std::string * Error)988 bool BugDriver::debugCodeGenerator(std::string *Error) {
989   if ((void*)SafeInterpreter == (void*)Interpreter) {
990     std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
991                                               Error);
992     if (Error->empty()) {
993       outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
994              << "the reference diff.  This may be due to a\n    front-end "
995              << "bug or a bug in the original program, but this can also "
996              << "happen if bugpoint isn't running the program with the "
997              << "right flags or input.\n    I left the result of executing "
998              << "the program with the \"safe\" backend in this file for "
999              << "you: '"
1000              << Result << "'.\n";
1001     }
1002     return true;
1003   }
1004 
1005   DisambiguateGlobalSymbols(Program);
1006 
1007   std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1008                                                       *Error);
1009   if (!Error->empty())
1010     return true;
1011 
1012   // Split the module into the two halves of the program we want.
1013   ValueToValueMapTy VMap;
1014   Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1015   Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
1016 
1017   // Condition the modules
1018   CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1019 
1020   sys::Path TestModuleBC("bugpoint.test.bc");
1021   std::string ErrMsg;
1022   if (TestModuleBC.makeUnique(true, &ErrMsg)) {
1023     errs() << getToolName() << "Error making unique filename: "
1024            << ErrMsg << "\n";
1025     exit(1);
1026   }
1027 
1028   if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
1029     errs() << "Error writing bitcode to `" << TestModuleBC.str()
1030            << "'\nExiting.";
1031     exit(1);
1032   }
1033   delete ToCodeGen;
1034 
1035   // Make the shared library
1036   sys::Path SafeModuleBC("bugpoint.safe.bc");
1037   if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
1038     errs() << getToolName() << "Error making unique filename: "
1039            << ErrMsg << "\n";
1040     exit(1);
1041   }
1042 
1043   if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
1044     errs() << "Error writing bitcode to `" << SafeModuleBC.str()
1045            << "'\nExiting.";
1046     exit(1);
1047   }
1048   std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1049   if (!Error->empty())
1050     return true;
1051   delete ToNotCodeGen;
1052 
1053   outs() << "You can reproduce the problem with the command line: \n";
1054   if (isExecutingJIT()) {
1055     outs() << "  lli -load " << SharedObject << " " << TestModuleBC.str();
1056   } else {
1057     outs() << "  llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
1058            << ".s\n";
1059     outs() << "  gcc " << SharedObject << " " << TestModuleBC.str()
1060               << ".s -o " << TestModuleBC.str() << ".exe";
1061 #if defined (HAVE_LINK_R)
1062     outs() << " -Wl,-R.";
1063 #endif
1064     outs() << "\n";
1065     outs() << "  " << TestModuleBC.str() << ".exe";
1066   }
1067   for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1068     outs() << " " << InputArgv[i];
1069   outs() << '\n';
1070   outs() << "The shared object was created with:\n  llc -march=c "
1071          << SafeModuleBC.str() << " -o temporary.c\n"
1072          << "  gcc -xc temporary.c -O2 -o " << SharedObject;
1073   if (TargetTriple.getArch() == Triple::sparc)
1074     outs() << " -G";              // Compile a shared library, `-G' for Sparc
1075   else
1076     outs() << " -fPIC -shared";   // `-shared' for Linux/X86, maybe others
1077 
1078   outs() << " -fno-strict-aliasing\n";
1079 
1080   return false;
1081 }
1082