blob: 3503f7b2c79e8da5adf557839977545631f5cb03 [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4a106452002-12-23 23:50:16 +00009//
Chris Lattnera57d86b2004-04-05 22:58:16 +000010// This file implements optimizer and code generation miscompilation debugging
11// support.
Chris Lattner4a106452002-12-23 23:50:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner126840f2003-04-24 20:16:29 +000016#include "ListReducer.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000020#include "llvm/Linker.h"
Chris Lattner4a106452002-12-23 23:50:16 +000021#include "llvm/Module.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000022#include "llvm/Pass.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000023#include "llvm/Analysis/Verifier.h"
24#include "llvm/Support/Mangler.h"
Chris Lattner640f22e2003-04-24 17:02:17 +000025#include "llvm/Transforms/Utils/Cloning.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
Chris Lattner59615f02005-01-15 00:07:19 +000028#include "llvm/Config/config.h" // for HAVE_LINK_R
Chris Lattnerfa761832004-01-14 03:38:37 +000029using namespace llvm;
Chris Lattner4a106452002-12-23 23:50:16 +000030
Chris Lattnera57d86b2004-04-05 22:58:16 +000031namespace llvm {
32 extern cl::list<std::string> InputArgv;
33}
34
Chris Lattnerefdc0b52004-03-14 20:50:42 +000035namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +000036 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
37 BugDriver &BD;
38 public:
39 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +000040
Chris Lattnerfa761832004-01-14 03:38:37 +000041 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
42 std::vector<const PassInfo*> &Suffix);
43 };
44}
Chris Lattner640f22e2003-04-24 17:02:17 +000045
Misha Brukman8c194ea2004-04-21 18:36:43 +000046/// TestResult - After passes have been split into a test group and a control
47/// group, see if they still break the program.
48///
Chris Lattner640f22e2003-04-24 17:02:17 +000049ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000050ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-04-25 03:16:05 +000051 std::vector<const PassInfo*> &Suffix) {
52 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000053 // with JUST the kept passes, discard the prefix passes.
Chris Lattner06943ad2003-04-25 03:16:05 +000054 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +000055 << "' compile correctly: ";
56
57 std::string BytecodeResult;
Chris Lattner06943ad2003-04-25 03:16:05 +000058 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Misha Brukman3da94ae2005-04-22 00:00:37 +000059 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000060 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000061 BD.setPassesToRun(Suffix);
62 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000063 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000064 }
65
66 // Check to see if the finished program matches the reference output...
Misha Brukman50733362003-07-24 18:17:43 +000067 if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +000068 std::cout << " nope.\n";
Chris Lattner59615f02005-01-15 00:07:19 +000069 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 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000074 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000075 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000076 std::cout << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000077
78 if (Prefix.empty()) return NoFailure;
79
Chris Lattner06943ad2003-04-25 03:16:05 +000080 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000081 // then separately run the "kept" passes.
Chris Lattner640f22e2003-04-24 17:02:17 +000082 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*/)) {
Misha Brukman3da94ae2005-04-22 00:00:37 +000092 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000093 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +000094 BD.setPassesToRun(Prefix);
95 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000096 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000097 }
98
99 // If the prefix maintains the predicate by itself, only keep the prefix!
Misha Brukman50733362003-07-24 18:17:43 +0000100 if (BD.diffProgram(BytecodeResult)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +0000101 std::cout << " nope.\n";
Reid Spencera229c5c2005-07-08 03:08:58 +0000102 sys::Path(BytecodeResult).eraseFromDisk();
Chris Lattner640f22e2003-04-24 17:02:17 +0000103 return KeepPrefix;
104 }
Misha Brukman123f8fe2004-04-22 20:02:09 +0000105 std::cout << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +0000106
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 //
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000110 Module *PrefixOutput = ParseInputFile(BytecodeResult);
Chris Lattner640f22e2003-04-24 17:02:17 +0000111 if (PrefixOutput == 0) {
112 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
113 << BytecodeResult << "'!\n";
114 exit(1);
115 }
Reid Spencera229c5c2005-07-08 03:08:58 +0000116 sys::Path(BytecodeResult).eraseFromDisk(); // No longer need the file on disk
Chris Lattnerf4789e62004-04-23 20:36:51 +0000117
118 // Don't check if there are no passes in the suffix.
119 if (Suffix.empty())
120 return NoFailure;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000121
Chris Lattner06943ad2003-04-25 03:16:05 +0000122 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000123 << "' passes compile correctly after the '"
124 << getPassesString(Prefix) << "' passes: ";
125
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000126 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Chris Lattner06943ad2003-04-25 03:16:05 +0000127 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000128 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +0000129 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000130 BD.setPassesToRun(Suffix);
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000131 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000132 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000133 }
134
135 // Run the result...
Misha Brukman50733362003-07-24 18:17:43 +0000136 if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +0000137 std::cout << " nope.\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000138 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000139 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000140 }
141
142 // Otherwise, we must not be running the bad pass anymore.
Misha Brukman123f8fe2004-04-22 20:02:09 +0000143 std::cout << " yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000144 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000145 return NoFailure;
146}
147
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000148namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000149 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
150 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000151 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000152 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000153 ReduceMiscompilingFunctions(BugDriver &bd,
154 bool (*F)(BugDriver &, Module *, Module *))
155 : BD(bd), TestFn(F) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000156
Chris Lattnerfa761832004-01-14 03:38:37 +0000157 virtual TestResult doTest(std::vector<Function*> &Prefix,
158 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000159 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000160 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000161 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000162 return KeepPrefix;
163 return NoFailure;
164 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000165
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000166 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000167 };
168}
Chris Lattner640f22e2003-04-24 17:02:17 +0000169
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000170/// TestMergedProgram - Given two modules, link them together and run the
171/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000172/// 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.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000175///
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000176static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
177 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000178 // Link the two portions of the program back to together.
179 std::string ErrorMsg;
Chris Lattner90c18c52004-11-16 06:31:38 +0000180 if (!DeleteInputs) {
181 M1 = CloneModule(M1);
182 M2 = CloneModule(M2);
183 }
Reid Spencere4874022004-12-13 03:01:03 +0000184 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000185 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukmaneed80e22004-07-23 01:30:49 +0000186 << ErrorMsg << '\n';
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000187 exit(1);
188 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000189 delete M2; // We are done with this module.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000190
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
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000198 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000199 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000200 return Broken;
201}
202
Misha Brukman8c194ea2004-04-21 18:36:43 +0000203/// 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///
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000207bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-04-24 17:02:17 +0000208 // Test to see if the function is misoptimized if we ONLY run it on the
209 // functions listed in Funcs.
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000210 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"
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000213 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000214 PrintFunctionList(Funcs);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000215 std::cout << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000216
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000217 // Split the module into the two halves of the program we want.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000218 Module *ToNotOptimize = CloneModule(BD.getProgram());
219 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
Chris Lattner640f22e2003-04-24 17:02:17 +0000220
Chris Lattnerb15825b2004-04-05 21:37:38 +0000221 // Run the predicate, not that the predicate will delete both input modules.
222 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000223}
224
Misha Brukman8c194ea2004-04-21 18:36:43 +0000225/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
226/// modifying predominantly internal symbols rather than external ones.
227///
Chris Lattner36ee07f2004-04-11 23:52:35 +0000228static 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);
Andrew Lenharth0fccc742005-12-06 20:51:30 +0000235 // Agree with the CBE on symbol naming
236 Mang.markCharUnacceptable('.');
Chris Lattnerafd39f02006-09-07 18:21:07 +0000237 Mang.setPreserveAsmNames(true);
Chris Lattner67ef9e42006-05-04 23:35:31 +0000238 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
239 I != E; ++I)
Chris Lattner36ee07f2004-04-11 23:52:35 +0000240 I->setName(Mang.getValueName(I));
241 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
242 I->setName(Mang.getValueName(I));
243}
244
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000245/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
246/// check to see if we can extract the loops in the region without obscuring the
247/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000248///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000249static bool ExtractLoops(BugDriver &BD,
250 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000251 std::vector<Function*> &MiscompiledFunctions) {
252 bool MadeChange = false;
253 while (1) {
Chris Lattneraed98fa2005-08-02 23:25:56 +0000254 if (BugpointIsInterrupted) return MadeChange;
255
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000256 Module *ToNotOptimize = CloneModule(BD.getProgram());
257 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
258 MiscompiledFunctions);
259 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
260 if (!ToOptimizeLoopExtracted) {
261 // If the loop extractor crashed or if there were no extractible loops,
262 // then this chapter of our odyssey is over with.
263 delete ToNotOptimize;
264 delete ToOptimize;
265 return MadeChange;
266 }
267
268 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000269
270 // Bugpoint is intentionally not very trusting of LLVM transformations. In
271 // particular, we're not going to assume that the loop extractor works, so
272 // we're going to test the newly loop extracted program to make sure nothing
273 // has broken. If something broke, then we'll inform the user and stop
274 // extraction.
Chris Lattnera57d86b2004-04-05 22:58:16 +0000275 AbstractInterpreter *AI = BD.switchToCBE();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000276 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000277 BD.switchToInterpreter(AI);
278
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000279 // Merged program doesn't work anymore!
280 std::cerr << " *** ERROR: Loop extraction broke the program. :("
281 << " Please report a bug!\n";
282 std::cerr << " Continuing on with un-loop-extracted version.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000283
284 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
285 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
286 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
287 ToOptimizeLoopExtracted);
288
289 std::cerr << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
290 delete ToOptimize;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000291 delete ToNotOptimize;
292 delete ToOptimizeLoopExtracted;
293 return MadeChange;
294 }
Chris Lattner56c41862005-05-08 21:54:56 +0000295 delete ToOptimize;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000296 BD.switchToInterpreter(AI);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000297
Chris Lattnerb15825b2004-04-05 21:37:38 +0000298 std::cout << " Testing after loop extraction:\n";
299 // Clone modules, the tester function will free them.
300 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
301 Module *TNOBackup = CloneModule(ToNotOptimize);
302 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
303 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000304 // If the program is not still broken, then loop extraction did something
305 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000306 delete TOLEBackup;
307 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000308 return MadeChange;
309 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000310 ToOptimizeLoopExtracted = TOLEBackup;
311 ToNotOptimize = TNOBackup;
312
313 std::cout << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000314
Chris Lattner90c18c52004-11-16 06:31:38 +0000315 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
316 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
317 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Chris Lattnerfa1af132004-11-19 07:09:40 +0000318 if (!I->isExternal())
319 MisCompFunctions.push_back(std::make_pair(I->getName(),
320 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000321
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000322 // Okay, great! Now we know that we extracted a loop and that loop
323 // extraction both didn't break the program, and didn't mask the problem.
324 // Replace the current program with the loop extracted version, and try to
325 // extract another loop.
326 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000327 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000328 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukmaneed80e22004-07-23 01:30:49 +0000329 << ErrorMsg << '\n';
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000330 exit(1);
331 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000332 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000333
334 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000335 // module. Update this list to include all of the functions in the
336 // optimized and loop extracted module.
337 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000338 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
339 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first,
340 MisCompFunctions[i].second);
341 assert(NewF && "Function not found??");
342 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000343 }
344
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000345 BD.setNewProgram(ToNotOptimize);
346 MadeChange = true;
347 }
348}
349
Chris Lattner5e783ab2004-05-11 21:54:13 +0000350namespace {
351 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
352 BugDriver &BD;
353 bool (*TestFn)(BugDriver &, Module *, Module *);
354 std::vector<Function*> FunctionsBeingTested;
355 public:
356 ReduceMiscompiledBlocks(BugDriver &bd,
357 bool (*F)(BugDriver &, Module *, Module *),
358 const std::vector<Function*> &Fns)
359 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000360
Chris Lattner5e783ab2004-05-11 21:54:13 +0000361 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
362 std::vector<BasicBlock*> &Suffix) {
363 if (!Suffix.empty() && TestFuncs(Suffix))
364 return KeepSuffix;
365 if (TestFuncs(Prefix))
366 return KeepPrefix;
367 return NoFailure;
368 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000369
Chris Lattner5e783ab2004-05-11 21:54:13 +0000370 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
371 };
372}
373
374/// TestFuncs - Extract all blocks for the miscompiled functions except for the
375/// specified blocks. If the problem still exists, return true.
376///
377bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
378 // Test to see if the function is misoptimized if we ONLY run it on the
379 // functions listed in Funcs.
Chris Lattner68bee932004-05-12 16:08:01 +0000380 std::cout << "Checking to see if the program is misoptimized when all ";
381 if (!BBs.empty()) {
382 std::cout << "but these " << BBs.size() << " blocks are extracted: ";
383 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
384 std::cout << BBs[i]->getName() << " ";
385 if (BBs.size() > 10) std::cout << "...";
386 } else {
387 std::cout << "blocks are extracted.";
388 }
Misha Brukmaneed80e22004-07-23 01:30:49 +0000389 std::cout << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000390
391 // Split the module into the two halves of the program we want.
392 Module *ToNotOptimize = CloneModule(BD.getProgram());
393 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
394 FunctionsBeingTested);
395
396 // Try the extraction. If it doesn't work, then the block extractor crashed
397 // or something, in which case bugpoint can't chase down this possibility.
398 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
399 delete ToOptimize;
400 // Run the predicate, not that the predicate will delete both input modules.
401 return TestFn(BD, New, ToNotOptimize);
402 }
403 delete ToOptimize;
404 delete ToNotOptimize;
405 return false;
406}
407
408
409/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
410/// extract as many basic blocks from the region as possible without obscuring
411/// the bug.
412///
413static bool ExtractBlocks(BugDriver &BD,
414 bool (*TestFn)(BugDriver &, Module *, Module *),
415 std::vector<Function*> &MiscompiledFunctions) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000416 if (BugpointIsInterrupted) return false;
417
Chris Lattner5e783ab2004-05-11 21:54:13 +0000418 std::vector<BasicBlock*> Blocks;
419 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
420 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
421 E = MiscompiledFunctions[i]->end(); I != E; ++I)
422 Blocks.push_back(I);
423
424 // Use the list reducer to identify blocks that can be extracted without
425 // obscuring the bug. The Blocks list will end up containing blocks that must
426 // be retained from the original program.
427 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000428
429 // Check to see if all blocks are extractible first.
430 if (ReduceMiscompiledBlocks(BD, TestFn,
431 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
432 Blocks.clear();
433 } else {
434 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
435 if (Blocks.size() == OldSize)
436 return false;
437 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000438
Chris Lattner2290e752004-05-12 02:43:24 +0000439 Module *ProgClone = CloneModule(BD.getProgram());
440 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
441 MiscompiledFunctions);
442 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
443 if (Extracted == 0) {
Chris Lattnerda895d62005-02-27 06:18:25 +0000444 // Weird, extraction should have worked.
Chris Lattner2290e752004-05-12 02:43:24 +0000445 std::cerr << "Nondeterministic problem extracting blocks??\n";
446 delete ProgClone;
447 delete ToExtract;
448 return false;
449 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000450
Chris Lattner2290e752004-05-12 02:43:24 +0000451 // Otherwise, block extraction succeeded. Link the two program fragments back
452 // together.
453 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000454
Chris Lattner90c18c52004-11-16 06:31:38 +0000455 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
456 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
457 I != E; ++I)
Chris Lattnerfa1af132004-11-19 07:09:40 +0000458 if (!I->isExternal())
459 MisCompFunctions.push_back(std::make_pair(I->getName(),
460 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000461
Chris Lattner2290e752004-05-12 02:43:24 +0000462 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000463 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Chris Lattner2290e752004-05-12 02:43:24 +0000464 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukmaneed80e22004-07-23 01:30:49 +0000465 << ErrorMsg << '\n';
Chris Lattner2290e752004-05-12 02:43:24 +0000466 exit(1);
467 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000468 delete Extracted;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000469
Chris Lattner2290e752004-05-12 02:43:24 +0000470 // Set the new program and delete the old one.
471 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000472
Chris Lattner2290e752004-05-12 02:43:24 +0000473 // Update the list of miscompiled functions.
474 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000475
Chris Lattner90c18c52004-11-16 06:31:38 +0000476 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
477 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first,
478 MisCompFunctions[i].second);
479 assert(NewF && "Function not found??");
480 MiscompiledFunctions.push_back(NewF);
481 }
Chris Lattner2290e752004-05-12 02:43:24 +0000482
483 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000484}
485
486
Chris Lattnerb15825b2004-04-05 21:37:38 +0000487/// DebugAMiscompilation - This is a generic driver to narrow down
488/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000489///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000490static std::vector<Function*>
491DebugAMiscompilation(BugDriver &BD,
492 bool (*TestFn)(BugDriver &, Module *, Module *)) {
493 // Okay, now that we have reduced the list of passes which are causing the
494 // failure, see if we can pin down which functions are being
495 // miscompiled... first build a list of all of the non-external functions in
496 // the program.
497 std::vector<Function*> MiscompiledFunctions;
498 Module *Prog = BD.getProgram();
499 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
500 if (!I->isExternal())
501 MiscompiledFunctions.push_back(I);
502
503 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000504 if (!BugpointIsInterrupted)
505 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000506
507 std::cout << "\n*** The following function"
508 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
509 << " being miscompiled: ";
510 PrintFunctionList(MiscompiledFunctions);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000511 std::cout << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000512
513 // See if we can rip any loops out of the miscompiled functions and still
514 // trigger the problem.
Chris Lattneraed98fa2005-08-02 23:25:56 +0000515 if (!BugpointIsInterrupted &&
516 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000517 // Okay, we extracted some loops and the problem still appears. See if we
518 // can eliminate some of the created functions from being candidates.
519
Chris Lattner36ee07f2004-04-11 23:52:35 +0000520 // Loop extraction can introduce functions with the same name (foo_code).
521 // Make sure to disambiguate the symbols so that when the program is split
522 // apart that we can link it back together again.
523 DisambiguateGlobalSymbols(BD.getProgram());
524
Chris Lattnerb15825b2004-04-05 21:37:38 +0000525 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000526 if (!BugpointIsInterrupted)
527 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000528
Chris Lattnerb15825b2004-04-05 21:37:38 +0000529 std::cout << "\n*** The following function"
530 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
531 << " being miscompiled: ";
532 PrintFunctionList(MiscompiledFunctions);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000533 std::cout << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000534 }
535
Chris Lattneraed98fa2005-08-02 23:25:56 +0000536 if (!BugpointIsInterrupted &&
537 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000538 // Okay, we extracted some blocks and the problem still appears. See if we
539 // can eliminate some of the created functions from being candidates.
540
541 // Block extraction can introduce functions with the same name (foo_code).
542 // Make sure to disambiguate the symbols so that when the program is split
543 // apart that we can link it back together again.
544 DisambiguateGlobalSymbols(BD.getProgram());
545
546 // Do the reduction...
547 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000548
Chris Lattner5e783ab2004-05-11 21:54:13 +0000549 std::cout << "\n*** The following function"
550 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
551 << " being miscompiled: ";
552 PrintFunctionList(MiscompiledFunctions);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000553 std::cout << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000554 }
555
Chris Lattnerb15825b2004-04-05 21:37:38 +0000556 return MiscompiledFunctions;
557}
558
Chris Lattnera57d86b2004-04-05 22:58:16 +0000559/// TestOptimizer - This is the predicate function used to check to see if the
560/// "Test" portion of the program is misoptimized. If so, return true. In any
561/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000562///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000563static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
564 // Run the optimization passes on ToOptimize, producing a transformed version
565 // of the functions being tested.
566 std::cout << " Optimizing functions being tested: ";
567 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
568 /*AutoDebugCrashes*/true);
569 std::cout << "done.\n";
570 delete Test;
571
572 std::cout << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000573 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000574 std::cout << (Broken ? " nope.\n" : " yup.\n");
575 return Broken;
576}
577
578
Chris Lattner4a106452002-12-23 23:50:16 +0000579/// debugMiscompilation - This method is used when the passes selected are not
580/// crashing, but the generated output is semantically different from the
581/// input.
582///
583bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000584 // Make sure something was miscompiled...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000585 if (!BugpointIsInterrupted)
586 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
587 std::cerr << "*** Optimized program matches reference output! No problem"
588 << " detected...\nbugpoint can't help you with your problem!\n";
589 return false;
590 }
Chris Lattner4a106452002-12-23 23:50:16 +0000591
Chris Lattner640f22e2003-04-24 17:02:17 +0000592 std::cout << "\n*** Found miscompiling pass"
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000593 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
Misha Brukmaneed80e22004-07-23 01:30:49 +0000594 << getPassesString(getPassesToRun()) << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000595 EmitProgressBytecode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000596
Chris Lattnerb15825b2004-04-05 21:37:38 +0000597 std::vector<Function*> MiscompiledFunctions =
598 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000599
Chris Lattner640f22e2003-04-24 17:02:17 +0000600 // Output a bunch of bytecode files for the user...
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000601 std::cout << "Outputting reduced bytecode files which expose the problem:\n";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000602 Module *ToNotOptimize = CloneModule(getProgram());
603 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
604 MiscompiledFunctions);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000605
606 std::cout << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000607 ToNotOptimize = swapProgramIn(ToNotOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000608 EmitProgressBytecode("tonotoptimize", true);
609 setNewProgram(ToNotOptimize); // Delete hacked module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000610
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000611 std::cout << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000612 ToOptimize = swapProgramIn(ToOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000613 EmitProgressBytecode("tooptimize");
614 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000615
Chris Lattner4a106452002-12-23 23:50:16 +0000616 return false;
617}
Brian Gaeked0fde302003-11-11 22:41:34 +0000618
Chris Lattnera57d86b2004-04-05 22:58:16 +0000619/// CleanupAndPrepareModules - Get the specified modules ready for code
620/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000621///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000622static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
623 Module *Safe) {
624 // Clean up the modules, removing extra cruft that we don't need anymore...
625 Test = BD.performFinalCleanups(Test);
626
627 // If we are executing the JIT, we have several nasty issues to take care of.
628 if (!BD.isExecutingJIT()) return;
629
630 // First, if the main function is in the Safe module, we must add a stub to
631 // the Test module to call into it. Thus, we create a new function `main'
632 // which just calls the old one.
633 if (Function *oldMain = Safe->getNamedFunction("main"))
634 if (!oldMain->isExternal()) {
635 // Rename it
636 oldMain->setName("llvm_bugpoint_old_main");
637 // Create a NEW `main' function with same type in the test module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000638 Function *newMain = new Function(oldMain->getFunctionType(),
Chris Lattnera57d86b2004-04-05 22:58:16 +0000639 GlobalValue::ExternalLinkage,
640 "main", Test);
641 // Create an `oldmain' prototype in the test module, which will
642 // corresponds to the real main function in the same module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000643 Function *oldMainProto = new Function(oldMain->getFunctionType(),
Chris Lattnera57d86b2004-04-05 22:58:16 +0000644 GlobalValue::ExternalLinkage,
645 oldMain->getName(), Test);
646 // Set up and remember the argument list for the main function.
647 std::vector<Value*> args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000648 for (Function::arg_iterator
649 I = newMain->arg_begin(), E = newMain->arg_end(),
650 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000651 I->setName(OI->getName()); // Copy argument names from oldMain
652 args.push_back(I);
653 }
654
655 // Call the old main function and return its result
656 BasicBlock *BB = new BasicBlock("entry", newMain);
Chris Lattnerfa1af132004-11-19 07:09:40 +0000657 CallInst *call = new CallInst(oldMainProto, args, "", BB);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000658
Chris Lattnera57d86b2004-04-05 22:58:16 +0000659 // If the type of old function wasn't void, return value of call
Chris Lattnerfa1af132004-11-19 07:09:40 +0000660 new ReturnInst(call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000661 }
662
663 // The second nasty issue we must deal with in the JIT is that the Safe
664 // module cannot directly reference any functions defined in the test
665 // module. Instead, we use a JIT API call to dynamically resolve the
666 // symbol.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000667
Chris Lattnera57d86b2004-04-05 22:58:16 +0000668 // Add the resolver to the Safe module.
669 // Prototype: void *getPointerToNamedFunction(const char* Name)
Misha Brukman3da94ae2005-04-22 00:00:37 +0000670 Function *resolverFunc =
Chris Lattnera57d86b2004-04-05 22:58:16 +0000671 Safe->getOrInsertFunction("getPointerToNamedFunction",
672 PointerType::get(Type::SByteTy),
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000673 PointerType::get(Type::SByteTy), (Type *)0);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000674
Chris Lattnera57d86b2004-04-05 22:58:16 +0000675 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000676 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000677 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
678 F->getIntrinsicID() == 0 /* ignore intrinsics */) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000679 Function *TestFn = Test->getNamedFunction(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000680
681 // Don't forward functions which are external in the test module too.
682 if (TestFn && !TestFn->isExternal()) {
683 // 1. Add a string constant with its name to the global file
684 Constant *InitArray = ConstantArray::get(F->getName());
685 GlobalVariable *funcName =
686 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
Misha Brukman3da94ae2005-04-22 00:00:37 +0000687 GlobalValue::InternalLinkage, InitArray,
Chris Lattnera57d86b2004-04-05 22:58:16 +0000688 F->getName() + "_name", Safe);
689
690 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
691 // sbyte* so it matches the signature of the resolver function.
692
693 // GetElementPtr *funcName, ulong 0, ulong 0
694 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
695 Value *GEP =
Reid Spencer518310c2004-07-18 00:44:37 +0000696 ConstantExpr::getGetElementPtr(funcName, GEPargs);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000697 std::vector<Value*> ResolverArgs;
698 ResolverArgs.push_back(GEP);
699
Misha Brukmande4803d2004-04-19 03:36:47 +0000700 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
701 // function that dynamically resolves the calls to F via our JIT API
Chris Lattnera3efca12005-07-12 01:00:32 +0000702 if (!F->use_empty()) {
703 // Create a new global to hold the cached function pointer.
704 Constant *NullPtr = ConstantPointerNull::get(F->getType());
705 GlobalVariable *Cache =
706 new GlobalVariable(F->getType(), false,GlobalValue::InternalLinkage,
707 NullPtr,F->getName()+".fpcache", F->getParent());
Jeff Cohen00b168892005-07-27 06:12:32 +0000708
Misha Brukmande4803d2004-04-19 03:36:47 +0000709 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000710 const FunctionType *FuncTy = F->getFunctionType();
Misha Brukmande4803d2004-04-19 03:36:47 +0000711 Function *FuncWrapper = new Function(FuncTy,
712 GlobalValue::InternalLinkage,
Misha Brukmandc7fef82004-04-19 01:12:01 +0000713 F->getName() + "_wrapper",
714 F->getParent());
Chris Lattnera3efca12005-07-12 01:00:32 +0000715 BasicBlock *EntryBB = new BasicBlock("entry", FuncWrapper);
716 BasicBlock *DoCallBB = new BasicBlock("usecache", FuncWrapper);
717 BasicBlock *LookupBB = new BasicBlock("lookupfp", FuncWrapper);
Jeff Cohen00b168892005-07-27 06:12:32 +0000718
Chris Lattnera3efca12005-07-12 01:00:32 +0000719 // Check to see if we already looked up the value.
720 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
721 Value *IsNull = new SetCondInst(Instruction::SetEQ, CachedVal,
722 NullPtr, "isNull", EntryBB);
723 new BranchInst(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000724
Misha Brukmande4803d2004-04-19 03:36:47 +0000725 // Resolve the call to function F via the JIT API:
726 //
727 // call resolver(GetElementPtr...)
Chris Lattnera3efca12005-07-12 01:00:32 +0000728 CallInst *Resolver = new CallInst(resolverFunc, ResolverArgs,
729 "resolver", LookupBB);
Misha Brukmande4803d2004-04-19 03:36:47 +0000730 // cast the result from the resolver to correctly-typed function
Chris Lattnera3efca12005-07-12 01:00:32 +0000731 CastInst *CastedResolver =
732 new CastInst(Resolver, PointerType::get(F->getFunctionType()),
733 "resolverCast", LookupBB);
734 // Save the value in our cache.
735 new StoreInst(CastedResolver, Cache, LookupBB);
736 new BranchInst(DoCallBB, LookupBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000737
Chris Lattnera3efca12005-07-12 01:00:32 +0000738 PHINode *FuncPtr = new PHINode(NullPtr->getType(), "fp", DoCallBB);
739 FuncPtr->addIncoming(CastedResolver, LookupBB);
740 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000741
Chris Lattnera3efca12005-07-12 01:00:32 +0000742 // Save the argument list.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000743 std::vector<Value*> Args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000744 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
745 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukmandc7fef82004-04-19 01:12:01 +0000746 Args.push_back(i);
747
748 // Pass on the arguments to the real function, return its result
749 if (F->getReturnType() == Type::VoidTy) {
Chris Lattnera3efca12005-07-12 01:00:32 +0000750 CallInst *Call = new CallInst(FuncPtr, Args, "", DoCallBB);
751 new ReturnInst(DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000752 } else {
Chris Lattnera3efca12005-07-12 01:00:32 +0000753 CallInst *Call = new CallInst(FuncPtr, Args, "retval", DoCallBB);
754 new ReturnInst(Call, DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000755 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000756
Misha Brukmande4803d2004-04-19 03:36:47 +0000757 // Use the wrapper function instead of the old function
758 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000759 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000760 }
761 }
762 }
763
764 if (verifyModule(*Test) || verifyModule(*Safe)) {
765 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
766 abort();
767 }
768}
769
770
771
772/// TestCodeGenerator - This is the predicate function used to check to see if
773/// the "Test" portion of the program is miscompiled by the code generator under
774/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000775///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000776static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
777 CleanupAndPrepareModules(BD, Test, Safe);
778
Reid Spencer97182982004-12-15 01:53:08 +0000779 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000780 std::string ErrMsg;
781 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
782 std::cerr << BD.getToolName() << "Error making unique filename: "
783 << ErrMsg << "\n";
784 exit(1);
785 }
Reid Spencer97182982004-12-15 01:53:08 +0000786 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000787 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
788 exit(1);
789 }
790 delete Test;
791
792 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000793 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000794 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
795 std::cerr << BD.getToolName() << "Error making unique filename: "
796 << ErrMsg << "\n";
797 exit(1);
798 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000799
Reid Spencer97182982004-12-15 01:53:08 +0000800 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000801 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
802 exit(1);
803 }
Reid Spencer97182982004-12-15 01:53:08 +0000804 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000805 delete Safe;
806
807 // Run the code generator on the `Test' code, loading the shared library.
808 // The function returns whether or not the new output differs from reference.
Reid Spencer97182982004-12-15 01:53:08 +0000809 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000810
811 if (Result)
812 std::cerr << ": still failing!\n";
813 else
814 std::cerr << ": didn't fail.\n";
Reid Spencera229c5c2005-07-08 03:08:58 +0000815 TestModuleBC.eraseFromDisk();
816 SafeModuleBC.eraseFromDisk();
817 sys::Path(SharedObject).eraseFromDisk();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000818
819 return Result;
820}
821
822
Misha Brukman8c194ea2004-04-21 18:36:43 +0000823/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
824///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000825bool BugDriver::debugCodeGenerator() {
826 if ((void*)cbe == (void*)Interpreter) {
827 std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
828 std::cout << "\n*** The C backend cannot match the reference diff, but it "
829 << "is used as the 'known good'\n code generator, so I can't"
830 << " debug it. Perhaps you have a front-end problem?\n As a"
831 << " sanity check, I left the result of executing the program "
832 << "with the C backend\n in this file for you: '"
833 << Result << "'.\n";
834 return true;
835 }
836
837 DisambiguateGlobalSymbols(Program);
838
839 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
840
841 // Split the module into the two halves of the program we want.
842 Module *ToNotCodeGen = CloneModule(getProgram());
843 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
844
845 // Condition the modules
846 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
847
Reid Spencer97182982004-12-15 01:53:08 +0000848 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000849 std::string ErrMsg;
850 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
851 std::cerr << getToolName() << "Error making unique filename: "
852 << ErrMsg << "\n";
853 exit(1);
854 }
Reid Spencer97182982004-12-15 01:53:08 +0000855
856 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000857 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
858 exit(1);
859 }
860 delete ToCodeGen;
861
862 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000863 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000864 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
865 std::cerr << getToolName() << "Error making unique filename: "
866 << ErrMsg << "\n";
867 exit(1);
868 }
Reid Spencer97182982004-12-15 01:53:08 +0000869
870 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000871 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
872 exit(1);
873 }
Reid Spencer97182982004-12-15 01:53:08 +0000874 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000875 delete ToNotCodeGen;
876
877 std::cout << "You can reproduce the problem with the command line: \n";
878 if (isExecutingJIT()) {
879 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
880 } else {
Chris Lattner59615f02005-01-15 00:07:19 +0000881 std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000882 std::cout << " gcc " << SharedObject << " " << TestModuleBC
Chris Lattner59615f02005-01-15 00:07:19 +0000883 << ".s -o " << TestModuleBC << ".exe";
884#if defined (HAVE_LINK_R)
Chris Lattner3bd5fac2005-12-14 22:01:07 +0000885 std::cout << " -Wl,-R.";
Chris Lattner59615f02005-01-15 00:07:19 +0000886#endif
887 std::cout << "\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000888 std::cout << " " << TestModuleBC << ".exe";
889 }
890 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
891 std::cout << " " << InputArgv[i];
Misha Brukmaneed80e22004-07-23 01:30:49 +0000892 std::cout << '\n';
Chris Lattnera57d86b2004-04-05 22:58:16 +0000893 std::cout << "The shared object was created with:\n llc -march=c "
894 << SafeModuleBC << " -o temporary.c\n"
895 << " gcc -xc temporary.c -O2 -o " << SharedObject
896#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
897 << " -G" // Compile a shared library, `-G' for Sparc
898#else
899 << " -shared" // `-shared' for Linux/X86, maybe others
900#endif
901 << " -fno-strict-aliasing\n";
902
903 return false;
904}