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