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