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