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