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