wrap long line
[oota-llvm.git] / tools / bugpoint / Miscompilation.cpp
1 //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Linker.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Analysis/Verifier.h"
24 #include "llvm/Support/Mangler.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/Config/config.h"   // for HAVE_LINK_R
29 using namespace llvm;
30
31 namespace llvm {
32   extern cl::list<std::string> InputArgv;
33 }
34
35 namespace {
36   class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
37     BugDriver &BD;
38   public:
39     ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
40
41     virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
42                               std::vector<const PassInfo*> &Suffix);
43   };
44 }
45
46 /// TestResult - After passes have been split into a test group and a control
47 /// group, see if they still break the program.
48 ///
49 ReduceMiscompilingPasses::TestResult
50 ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
51                                  std::vector<const PassInfo*> &Suffix) {
52   // First, run the program with just the Suffix passes.  If it is still broken
53   // with JUST the kept passes, discard the prefix passes.
54   std::cout << "Checking to see if '" << getPassesString(Suffix)
55             << "' compile correctly: ";
56
57   std::string BytecodeResult;
58   if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
59     std::cerr << " Error running this sequence of passes"
60               << " on the input program!\n";
61     BD.setPassesToRun(Suffix);
62     BD.EmitProgressBytecode("pass-error",  false);
63     exit(BD.debugOptimizerCrash());
64   }
65
66   // Check to see if the finished program matches the reference output...
67   if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
68     std::cout << " nope.\n";
69     if (Suffix.empty()) {
70       std::cerr << BD.getToolName() << ": I'm confused: the test fails when "
71                 << "no passes are run, nondeterministic program?\n";
72       exit(1);
73     }
74     return KeepSuffix;         // Miscompilation detected!
75   }
76   std::cout << " yup.\n";      // No miscompilation!
77
78   if (Prefix.empty()) return NoFailure;
79
80   // Next, see if the program is broken if we run the "prefix" passes first,
81   // then separately run the "kept" passes.
82   std::cout << "Checking to see if '" << getPassesString(Prefix)
83             << "' compile correctly: ";
84
85   // If it is not broken with the kept passes, it's possible that the prefix
86   // passes must be run before the kept passes to break it.  If the program
87   // WORKS after the prefix passes, but then fails if running the prefix AND
88   // kept passes, we can update our bytecode file to include the result of the
89   // prefix passes, then discard the prefix passes.
90   //
91   if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
92     std::cerr << " Error running this sequence of passes"
93               << " on the input program!\n";
94     BD.setPassesToRun(Prefix);
95     BD.EmitProgressBytecode("pass-error",  false);
96     exit(BD.debugOptimizerCrash());
97   }
98
99   // If the prefix maintains the predicate by itself, only keep the prefix!
100   if (BD.diffProgram(BytecodeResult)) {
101     std::cout << " nope.\n";
102     sys::Path(BytecodeResult).eraseFromDisk();
103     return KeepPrefix;
104   }
105   std::cout << " yup.\n";      // No miscompilation!
106
107   // Ok, so now we know that the prefix passes work, try running the suffix
108   // passes on the result of the prefix passes.
109   //
110   Module *PrefixOutput = ParseInputFile(BytecodeResult);
111   if (PrefixOutput == 0) {
112     std::cerr << BD.getToolName() << ": Error reading bytecode file '"
113               << BytecodeResult << "'!\n";
114     exit(1);
115   }
116   sys::Path(BytecodeResult).eraseFromDisk();  // No longer need the file on disk
117
118   // Don't check if there are no passes in the suffix.
119   if (Suffix.empty())
120     return NoFailure;
121
122   std::cout << "Checking to see if '" << getPassesString(Suffix)
123             << "' passes compile correctly after the '"
124             << getPassesString(Prefix) << "' passes: ";
125
126   Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
127   if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
128     std::cerr << " Error running this sequence of passes"
129               << " on the input program!\n";
130     BD.setPassesToRun(Suffix);
131     BD.EmitProgressBytecode("pass-error",  false);
132     exit(BD.debugOptimizerCrash());
133   }
134
135   // Run the result...
136   if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
137     std::cout << " nope.\n";
138     delete OriginalInput;     // We pruned down the original input...
139     return KeepSuffix;
140   }
141
142   // Otherwise, we must not be running the bad pass anymore.
143   std::cout << " yup.\n";      // No miscompilation!
144   delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
145   return NoFailure;
146 }
147
148 namespace {
149   class ReduceMiscompilingFunctions : public ListReducer<Function*> {
150     BugDriver &BD;
151     bool (*TestFn)(BugDriver &, Module *, Module *);
152   public:
153     ReduceMiscompilingFunctions(BugDriver &bd,
154                                 bool (*F)(BugDriver &, Module *, Module *))
155       : BD(bd), TestFn(F) {}
156
157     virtual TestResult doTest(std::vector<Function*> &Prefix,
158                               std::vector<Function*> &Suffix) {
159       if (!Suffix.empty() && TestFuncs(Suffix))
160         return KeepSuffix;
161       if (!Prefix.empty() && TestFuncs(Prefix))
162         return KeepPrefix;
163       return NoFailure;
164     }
165
166     bool TestFuncs(const std::vector<Function*> &Prefix);
167   };
168 }
169
170 /// TestMergedProgram - Given two modules, link them together and run the
171 /// program, checking to see if the program matches the diff.  If the diff
172 /// matches, return false, otherwise return true.  If the DeleteInputs argument
173 /// is set to true then this function deletes both input modules before it
174 /// returns.
175 ///
176 static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
177                               bool DeleteInputs) {
178   // Link the two portions of the program back to together.
179   std::string ErrorMsg;
180   if (!DeleteInputs) {
181     M1 = CloneModule(M1);
182     M2 = CloneModule(M2);
183   }
184   if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
185     std::cerr << BD.getToolName() << ": Error linking modules together:"
186               << ErrorMsg << '\n';
187     exit(1);
188   }
189   delete M2;   // We are done with this module.
190
191   Module *OldProgram = BD.swapProgramIn(M1);
192
193   // Execute the program.  If it does not match the expected output, we must
194   // return true.
195   bool Broken = BD.diffProgram();
196
197   // Delete the linked module & restore the original
198   BD.swapProgramIn(OldProgram);
199   delete M1;
200   return Broken;
201 }
202
203 /// TestFuncs - split functions in a Module into two groups: those that are
204 /// under consideration for miscompilation vs. those that are not, and test
205 /// accordingly. Each group of functions becomes a separate Module.
206 ///
207 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
208   // Test to see if the function is misoptimized if we ONLY run it on the
209   // functions listed in Funcs.
210   std::cout << "Checking to see if the program is misoptimized when "
211             << (Funcs.size()==1 ? "this function is" : "these functions are")
212             << " run through the pass"
213             << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
214   PrintFunctionList(Funcs);
215   std::cout << '\n';
216
217   // Split the module into the two halves of the program we want.
218   Module *ToNotOptimize = CloneModule(BD.getProgram());
219   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
220
221   // Run the predicate, not that the predicate will delete both input modules.
222   return TestFn(BD, ToOptimize, ToNotOptimize);
223 }
224
225 /// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
226 /// modifying predominantly internal symbols rather than external ones.
227 ///
228 static void DisambiguateGlobalSymbols(Module *M) {
229   // Try not to cause collisions by minimizing chances of renaming an
230   // already-external symbol, so take in external globals and functions as-is.
231   // The code should work correctly without disambiguation (assuming the same
232   // mangler is used by the two code generators), but having symbols with the
233   // same name causes warnings to be emitted by the code generator.
234   Mangler Mang(*M);
235   // Agree with the CBE on symbol naming
236   Mang.markCharUnacceptable('.');
237   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
238        I != E; ++I)
239     I->setName(Mang.getValueName(I));
240   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I)
241     I->setName(Mang.getValueName(I));
242 }
243
244 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
245 /// check to see if we can extract the loops in the region without obscuring the
246 /// bug.  If so, it reduces the amount of code identified.
247 ///
248 static bool ExtractLoops(BugDriver &BD,
249                          bool (*TestFn)(BugDriver &, Module *, Module *),
250                          std::vector<Function*> &MiscompiledFunctions) {
251   bool MadeChange = false;
252   while (1) {
253     if (BugpointIsInterrupted) return MadeChange;
254     
255     Module *ToNotOptimize = CloneModule(BD.getProgram());
256     Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
257                                                    MiscompiledFunctions);
258     Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
259     if (!ToOptimizeLoopExtracted) {
260       // If the loop extractor crashed or if there were no extractible loops,
261       // then this chapter of our odyssey is over with.
262       delete ToNotOptimize;
263       delete ToOptimize;
264       return MadeChange;
265     }
266
267     std::cerr << "Extracted a loop from the breaking portion of the program.\n";
268
269     // Bugpoint is intentionally not very trusting of LLVM transformations.  In
270     // particular, we're not going to assume that the loop extractor works, so
271     // we're going to test the newly loop extracted program to make sure nothing
272     // has broken.  If something broke, then we'll inform the user and stop
273     // extraction.
274     AbstractInterpreter *AI = BD.switchToCBE();
275     if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
276       BD.switchToInterpreter(AI);
277
278       // Merged program doesn't work anymore!
279       std::cerr << "  *** ERROR: Loop extraction broke the program. :("
280                 << " Please report a bug!\n";
281       std::cerr << "      Continuing on with un-loop-extracted version.\n";
282
283       BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
284       BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
285       BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
286                             ToOptimizeLoopExtracted);
287
288       std::cerr << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
289       delete ToOptimize;
290       delete ToNotOptimize;
291       delete ToOptimizeLoopExtracted;
292       return MadeChange;
293     }
294     delete ToOptimize;
295     BD.switchToInterpreter(AI);
296
297     std::cout << "  Testing after loop extraction:\n";
298     // Clone modules, the tester function will free them.
299     Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
300     Module *TNOBackup  = CloneModule(ToNotOptimize);
301     if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
302       std::cout << "*** Loop extraction masked the problem.  Undoing.\n";
303       // If the program is not still broken, then loop extraction did something
304       // that masked the error.  Stop loop extraction now.
305       delete TOLEBackup;
306       delete TNOBackup;
307       return MadeChange;
308     }
309     ToOptimizeLoopExtracted = TOLEBackup;
310     ToNotOptimize = TNOBackup;
311
312     std::cout << "*** Loop extraction successful!\n";
313
314     std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
315     for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
316            E = ToOptimizeLoopExtracted->end(); I != E; ++I)
317       if (!I->isExternal())
318         MisCompFunctions.push_back(std::make_pair(I->getName(),
319                                                   I->getFunctionType()));
320
321     // Okay, great!  Now we know that we extracted a loop and that loop
322     // extraction both didn't break the program, and didn't mask the problem.
323     // Replace the current program with the loop extracted version, and try to
324     // extract another loop.
325     std::string ErrorMsg;
326     if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
327       std::cerr << BD.getToolName() << ": Error linking modules together:"
328                 << ErrorMsg << '\n';
329       exit(1);
330     }
331     delete ToOptimizeLoopExtracted;
332
333     // All of the Function*'s in the MiscompiledFunctions list are in the old
334     // module.  Update this list to include all of the functions in the
335     // optimized and loop extracted module.
336     MiscompiledFunctions.clear();
337     for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
338       Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first,
339                                                   MisCompFunctions[i].second);
340       assert(NewF && "Function not found??");
341       MiscompiledFunctions.push_back(NewF);
342     }
343
344     BD.setNewProgram(ToNotOptimize);
345     MadeChange = true;
346   }
347 }
348
349 namespace {
350   class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
351     BugDriver &BD;
352     bool (*TestFn)(BugDriver &, Module *, Module *);
353     std::vector<Function*> FunctionsBeingTested;
354   public:
355     ReduceMiscompiledBlocks(BugDriver &bd,
356                             bool (*F)(BugDriver &, Module *, Module *),
357                             const std::vector<Function*> &Fns)
358       : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
359
360     virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
361                               std::vector<BasicBlock*> &Suffix) {
362       if (!Suffix.empty() && TestFuncs(Suffix))
363         return KeepSuffix;
364       if (TestFuncs(Prefix))
365         return KeepPrefix;
366       return NoFailure;
367     }
368
369     bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
370   };
371 }
372
373 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
374 /// specified blocks.  If the problem still exists, return true.
375 ///
376 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
377   // Test to see if the function is misoptimized if we ONLY run it on the
378   // functions listed in Funcs.
379   std::cout << "Checking to see if the program is misoptimized when all ";
380   if (!BBs.empty()) {
381     std::cout << "but these " << BBs.size() << " blocks are extracted: ";
382     for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
383       std::cout << BBs[i]->getName() << " ";
384     if (BBs.size() > 10) std::cout << "...";
385   } else {
386     std::cout << "blocks are extracted.";
387   }
388   std::cout << '\n';
389
390   // Split the module into the two halves of the program we want.
391   Module *ToNotOptimize = CloneModule(BD.getProgram());
392   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
393                                                  FunctionsBeingTested);
394
395   // Try the extraction.  If it doesn't work, then the block extractor crashed
396   // or something, in which case bugpoint can't chase down this possibility.
397   if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
398     delete ToOptimize;
399     // Run the predicate, not that the predicate will delete both input modules.
400     return TestFn(BD, New, ToNotOptimize);
401   }
402   delete ToOptimize;
403   delete ToNotOptimize;
404   return false;
405 }
406
407
408 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
409 /// extract as many basic blocks from the region as possible without obscuring
410 /// the bug.
411 ///
412 static bool ExtractBlocks(BugDriver &BD,
413                           bool (*TestFn)(BugDriver &, Module *, Module *),
414                           std::vector<Function*> &MiscompiledFunctions) {
415   if (BugpointIsInterrupted) return false;
416   
417   std::vector<BasicBlock*> Blocks;
418   for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
419     for (Function::iterator I = MiscompiledFunctions[i]->begin(),
420            E = MiscompiledFunctions[i]->end(); I != E; ++I)
421       Blocks.push_back(I);
422
423   // Use the list reducer to identify blocks that can be extracted without
424   // obscuring the bug.  The Blocks list will end up containing blocks that must
425   // be retained from the original program.
426   unsigned OldSize = Blocks.size();
427
428   // Check to see if all blocks are extractible first.
429   if (ReduceMiscompiledBlocks(BD, TestFn,
430                   MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
431     Blocks.clear();
432   } else {
433     ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
434     if (Blocks.size() == OldSize)
435       return false;
436   }
437
438   Module *ProgClone = CloneModule(BD.getProgram());
439   Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
440                                                 MiscompiledFunctions);
441   Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
442   if (Extracted == 0) {
443     // Weird, extraction should have worked.
444     std::cerr << "Nondeterministic problem extracting blocks??\n";
445     delete ProgClone;
446     delete ToExtract;
447     return false;
448   }
449
450   // Otherwise, block extraction succeeded.  Link the two program fragments back
451   // together.
452   delete ToExtract;
453
454   std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
455   for (Module::iterator I = Extracted->begin(), E = Extracted->end();
456        I != E; ++I)
457     if (!I->isExternal())
458       MisCompFunctions.push_back(std::make_pair(I->getName(),
459                                                 I->getFunctionType()));
460
461   std::string ErrorMsg;
462   if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
463     std::cerr << BD.getToolName() << ": Error linking modules together:"
464               << ErrorMsg << '\n';
465     exit(1);
466   }
467   delete Extracted;
468
469   // Set the new program and delete the old one.
470   BD.setNewProgram(ProgClone);
471
472   // Update the list of miscompiled functions.
473   MiscompiledFunctions.clear();
474
475   for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
476     Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first,
477                                             MisCompFunctions[i].second);
478     assert(NewF && "Function not found??");
479     MiscompiledFunctions.push_back(NewF);
480   }
481
482   return true;
483 }
484
485
486 /// DebugAMiscompilation - This is a generic driver to narrow down
487 /// miscompilations, either in an optimization or a code generator.
488 ///
489 static std::vector<Function*>
490 DebugAMiscompilation(BugDriver &BD,
491                      bool (*TestFn)(BugDriver &, Module *, Module *)) {
492   // Okay, now that we have reduced the list of passes which are causing the
493   // failure, see if we can pin down which functions are being
494   // miscompiled... first build a list of all of the non-external functions in
495   // the program.
496   std::vector<Function*> MiscompiledFunctions;
497   Module *Prog = BD.getProgram();
498   for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
499     if (!I->isExternal())
500       MiscompiledFunctions.push_back(I);
501
502   // Do the reduction...
503   if (!BugpointIsInterrupted)
504     ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
505
506   std::cout << "\n*** The following function"
507             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
508             << " being miscompiled: ";
509   PrintFunctionList(MiscompiledFunctions);
510   std::cout << '\n';
511
512   // See if we can rip any loops out of the miscompiled functions and still
513   // trigger the problem.
514   if (!BugpointIsInterrupted && 
515       ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
516     // Okay, we extracted some loops and the problem still appears.  See if we
517     // can eliminate some of the created functions from being candidates.
518
519     // Loop extraction can introduce functions with the same name (foo_code).
520     // Make sure to disambiguate the symbols so that when the program is split
521     // apart that we can link it back together again.
522     DisambiguateGlobalSymbols(BD.getProgram());
523
524     // Do the reduction...
525     if (!BugpointIsInterrupted)
526       ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
527
528     std::cout << "\n*** The following function"
529               << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
530               << " being miscompiled: ";
531     PrintFunctionList(MiscompiledFunctions);
532     std::cout << '\n';
533   }
534
535   if (!BugpointIsInterrupted &&
536       ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
537     // Okay, we extracted some blocks and the problem still appears.  See if we
538     // can eliminate some of the created functions from being candidates.
539
540     // Block extraction can introduce functions with the same name (foo_code).
541     // Make sure to disambiguate the symbols so that when the program is split
542     // apart that we can link it back together again.
543     DisambiguateGlobalSymbols(BD.getProgram());
544
545     // Do the reduction...
546     ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
547
548     std::cout << "\n*** The following function"
549               << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
550               << " being miscompiled: ";
551     PrintFunctionList(MiscompiledFunctions);
552     std::cout << '\n';
553   }
554
555   return MiscompiledFunctions;
556 }
557
558 /// TestOptimizer - This is the predicate function used to check to see if the
559 /// "Test" portion of the program is misoptimized.  If so, return true.  In any
560 /// case, both module arguments are deleted.
561 ///
562 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
563   // Run the optimization passes on ToOptimize, producing a transformed version
564   // of the functions being tested.
565   std::cout << "  Optimizing functions being tested: ";
566   Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
567                                      /*AutoDebugCrashes*/true);
568   std::cout << "done.\n";
569   delete Test;
570
571   std::cout << "  Checking to see if the merged program executes correctly: ";
572   bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
573   std::cout << (Broken ? " nope.\n" : " yup.\n");
574   return Broken;
575 }
576
577
578 /// debugMiscompilation - This method is used when the passes selected are not
579 /// crashing, but the generated output is semantically different from the
580 /// input.
581 ///
582 bool BugDriver::debugMiscompilation() {
583   // Make sure something was miscompiled...
584   if (!BugpointIsInterrupted)
585     if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
586       std::cerr << "*** Optimized program matches reference output!  No problem"
587                 << " detected...\nbugpoint can't help you with your problem!\n";
588       return false;
589     }
590
591   std::cout << "\n*** Found miscompiling pass"
592             << (getPassesToRun().size() == 1 ? "" : "es") << ": "
593             << getPassesString(getPassesToRun()) << '\n';
594   EmitProgressBytecode("passinput");
595
596   std::vector<Function*> MiscompiledFunctions =
597     DebugAMiscompilation(*this, TestOptimizer);
598
599   // Output a bunch of bytecode files for the user...
600   std::cout << "Outputting reduced bytecode files which expose the problem:\n";
601   Module *ToNotOptimize = CloneModule(getProgram());
602   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
603                                                  MiscompiledFunctions);
604
605   std::cout << "  Non-optimized portion: ";
606   ToNotOptimize = swapProgramIn(ToNotOptimize);
607   EmitProgressBytecode("tonotoptimize", true);
608   setNewProgram(ToNotOptimize);   // Delete hacked module.
609
610   std::cout << "  Portion that is input to optimizer: ";
611   ToOptimize = swapProgramIn(ToOptimize);
612   EmitProgressBytecode("tooptimize");
613   setNewProgram(ToOptimize);      // Delete hacked module.
614
615   return false;
616 }
617
618 /// CleanupAndPrepareModules - Get the specified modules ready for code
619 /// generator testing.
620 ///
621 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
622                                      Module *Safe) {
623   // Clean up the modules, removing extra cruft that we don't need anymore...
624   Test = BD.performFinalCleanups(Test);
625
626   // If we are executing the JIT, we have several nasty issues to take care of.
627   if (!BD.isExecutingJIT()) return;
628
629   // First, if the main function is in the Safe module, we must add a stub to
630   // the Test module to call into it.  Thus, we create a new function `main'
631   // which just calls the old one.
632   if (Function *oldMain = Safe->getNamedFunction("main"))
633     if (!oldMain->isExternal()) {
634       // Rename it
635       oldMain->setName("llvm_bugpoint_old_main");
636       // Create a NEW `main' function with same type in the test module.
637       Function *newMain = new Function(oldMain->getFunctionType(),
638                                        GlobalValue::ExternalLinkage,
639                                        "main", Test);
640       // Create an `oldmain' prototype in the test module, which will
641       // corresponds to the real main function in the same module.
642       Function *oldMainProto = new Function(oldMain->getFunctionType(),
643                                             GlobalValue::ExternalLinkage,
644                                             oldMain->getName(), Test);
645       // Set up and remember the argument list for the main function.
646       std::vector<Value*> args;
647       for (Function::arg_iterator
648              I = newMain->arg_begin(), E = newMain->arg_end(),
649              OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
650         I->setName(OI->getName());    // Copy argument names from oldMain
651         args.push_back(I);
652       }
653
654       // Call the old main function and return its result
655       BasicBlock *BB = new BasicBlock("entry", newMain);
656       CallInst *call = new CallInst(oldMainProto, args, "", BB);
657
658       // If the type of old function wasn't void, return value of call
659       new ReturnInst(call, BB);
660     }
661
662   // The second nasty issue we must deal with in the JIT is that the Safe
663   // module cannot directly reference any functions defined in the test
664   // module.  Instead, we use a JIT API call to dynamically resolve the
665   // symbol.
666
667   // Add the resolver to the Safe module.
668   // Prototype: void *getPointerToNamedFunction(const char* Name)
669   Function *resolverFunc =
670     Safe->getOrInsertFunction("getPointerToNamedFunction",
671                               PointerType::get(Type::SByteTy),
672                               PointerType::get(Type::SByteTy), (Type *)0);
673
674   // Use the function we just added to get addresses of functions we need.
675   for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
676     if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
677         F->getIntrinsicID() == 0 /* ignore intrinsics */) {
678       Function *TestFn = Test->getNamedFunction(F->getName());
679
680       // Don't forward functions which are external in the test module too.
681       if (TestFn && !TestFn->isExternal()) {
682         // 1. Add a string constant with its name to the global file
683         Constant *InitArray = ConstantArray::get(F->getName());
684         GlobalVariable *funcName =
685           new GlobalVariable(InitArray->getType(), true /*isConstant*/,
686                              GlobalValue::InternalLinkage, InitArray,
687                              F->getName() + "_name", Safe);
688
689         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
690         // sbyte* so it matches the signature of the resolver function.
691
692         // GetElementPtr *funcName, ulong 0, ulong 0
693         std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
694         Value *GEP =
695           ConstantExpr::getGetElementPtr(funcName, GEPargs);
696         std::vector<Value*> ResolverArgs;
697         ResolverArgs.push_back(GEP);
698
699         // Rewrite uses of F in global initializers, etc. to uses of a wrapper
700         // function that dynamically resolves the calls to F via our JIT API
701         if (!F->use_empty()) {
702           // Create a new global to hold the cached function pointer.
703           Constant *NullPtr = ConstantPointerNull::get(F->getType());
704           GlobalVariable *Cache =
705             new GlobalVariable(F->getType(), false,GlobalValue::InternalLinkage,
706                                NullPtr,F->getName()+".fpcache", F->getParent());
707
708           // Construct a new stub function that will re-route calls to F
709           const FunctionType *FuncTy = F->getFunctionType();
710           Function *FuncWrapper = new Function(FuncTy,
711                                                GlobalValue::InternalLinkage,
712                                                F->getName() + "_wrapper",
713                                                F->getParent());
714           BasicBlock *EntryBB  = new BasicBlock("entry", FuncWrapper);
715           BasicBlock *DoCallBB = new BasicBlock("usecache", FuncWrapper);
716           BasicBlock *LookupBB = new BasicBlock("lookupfp", FuncWrapper);
717
718           // Check to see if we already looked up the value.
719           Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
720           Value *IsNull = new SetCondInst(Instruction::SetEQ, CachedVal,
721                                           NullPtr, "isNull", EntryBB);
722           new BranchInst(LookupBB, DoCallBB, IsNull, EntryBB);
723
724           // Resolve the call to function F via the JIT API:
725           //
726           // call resolver(GetElementPtr...)
727           CallInst *Resolver = new CallInst(resolverFunc, ResolverArgs,
728                                             "resolver", LookupBB);
729           // cast the result from the resolver to correctly-typed function
730           CastInst *CastedResolver =
731             new CastInst(Resolver, PointerType::get(F->getFunctionType()),
732                          "resolverCast", LookupBB);
733           // Save the value in our cache.
734           new StoreInst(CastedResolver, Cache, LookupBB);
735           new BranchInst(DoCallBB, LookupBB);
736
737           PHINode *FuncPtr = new PHINode(NullPtr->getType(), "fp", DoCallBB);
738           FuncPtr->addIncoming(CastedResolver, LookupBB);
739           FuncPtr->addIncoming(CachedVal, EntryBB);
740
741           // Save the argument list.
742           std::vector<Value*> Args;
743           for (Function::arg_iterator i = FuncWrapper->arg_begin(),
744                  e = FuncWrapper->arg_end(); i != e; ++i)
745             Args.push_back(i);
746
747           // Pass on the arguments to the real function, return its result
748           if (F->getReturnType() == Type::VoidTy) {
749             CallInst *Call = new CallInst(FuncPtr, Args, "", DoCallBB);
750             new ReturnInst(DoCallBB);
751           } else {
752             CallInst *Call = new CallInst(FuncPtr, Args, "retval", DoCallBB);
753             new ReturnInst(Call, DoCallBB);
754           }
755
756           // Use the wrapper function instead of the old function
757           F->replaceAllUsesWith(FuncWrapper);
758         }
759       }
760     }
761   }
762
763   if (verifyModule(*Test) || verifyModule(*Safe)) {
764     std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
765     abort();
766   }
767 }
768
769
770
771 /// TestCodeGenerator - This is the predicate function used to check to see if
772 /// the "Test" portion of the program is miscompiled by the code generator under
773 /// test.  If so, return true.  In any case, both module arguments are deleted.
774 ///
775 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
776   CleanupAndPrepareModules(BD, Test, Safe);
777
778   sys::Path TestModuleBC("bugpoint.test.bc");
779   TestModuleBC.makeUnique();
780   if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
781     std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
782     exit(1);
783   }
784   delete Test;
785
786   // Make the shared library
787   sys::Path SafeModuleBC("bugpoint.safe.bc");
788   SafeModuleBC.makeUnique();
789
790   if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
791     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
792     exit(1);
793   }
794   std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
795   delete Safe;
796
797   // Run the code generator on the `Test' code, loading the shared library.
798   // The function returns whether or not the new output differs from reference.
799   int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
800
801   if (Result)
802     std::cerr << ": still failing!\n";
803   else
804     std::cerr << ": didn't fail.\n";
805   TestModuleBC.eraseFromDisk();
806   SafeModuleBC.eraseFromDisk();
807   sys::Path(SharedObject).eraseFromDisk();
808
809   return Result;
810 }
811
812
813 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
814 ///
815 bool BugDriver::debugCodeGenerator() {
816   if ((void*)cbe == (void*)Interpreter) {
817     std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
818     std::cout << "\n*** The C backend cannot match the reference diff, but it "
819               << "is used as the 'known good'\n    code generator, so I can't"
820               << " debug it.  Perhaps you have a front-end problem?\n    As a"
821               << " sanity check, I left the result of executing the program "
822               << "with the C backend\n    in this file for you: '"
823               << Result << "'.\n";
824     return true;
825   }
826
827   DisambiguateGlobalSymbols(Program);
828
829   std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
830
831   // Split the module into the two halves of the program we want.
832   Module *ToNotCodeGen = CloneModule(getProgram());
833   Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
834
835   // Condition the modules
836   CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
837
838   sys::Path TestModuleBC("bugpoint.test.bc");
839   TestModuleBC.makeUnique();
840
841   if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
842     std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
843     exit(1);
844   }
845   delete ToCodeGen;
846
847   // Make the shared library
848   sys::Path SafeModuleBC("bugpoint.safe.bc");
849   SafeModuleBC.makeUnique();
850
851   if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
852     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
853     exit(1);
854   }
855   std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
856   delete ToNotCodeGen;
857
858   std::cout << "You can reproduce the problem with the command line: \n";
859   if (isExecutingJIT()) {
860     std::cout << "  lli -load " << SharedObject << " " << TestModuleBC;
861   } else {
862     std::cout << "  llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
863     std::cout << "  gcc " << SharedObject << " " << TestModuleBC
864               << ".s -o " << TestModuleBC << ".exe";
865 #if defined (HAVE_LINK_R)
866     std::cout << " -Wl,-R.";
867 #endif
868     std::cout << "\n";
869     std::cout << "  " << TestModuleBC << ".exe";
870   }
871   for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
872     std::cout << " " << InputArgv[i];
873   std::cout << '\n';
874   std::cout << "The shared object was created with:\n  llc -march=c "
875             << SafeModuleBC << " -o temporary.c\n"
876             << "  gcc -xc temporary.c -O2 -o " << SharedObject
877 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
878             << " -G"            // Compile a shared library, `-G' for Sparc
879 #else
880             << " -shared"       // `-shared' for Linux/X86, maybe others
881 #endif
882             << " -fno-strict-aliasing\n";
883
884   return false;
885 }