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