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