blob: b69cbd12003f4d77898f40c78db8ac8a66fa7873 [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
John Criswell7c0e0222003-10-20 17:47:21 +00002//
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//===----------------------------------------------------------------------===//
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) {}
40
41 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*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +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*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +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 Spencer5f767602004-12-16 23:04:20 +0000102 sys::Path(BytecodeResult).destroyFile();
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 Spencer5f767602004-12-16 23:04:20 +0000116 sys::Path(BytecodeResult).destroyFile(); // 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;
121
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*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +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) {}
Chris Lattnerfa761832004-01-14 03:38:37 +0000156
157 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 }
165
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);
235 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
236 I->setName(Mang.getValueName(I));
237 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
238 I->setName(Mang.getValueName(I));
239}
240
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000241/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
242/// check to see if we can extract the loops in the region without obscuring the
243/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000244///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000245static bool ExtractLoops(BugDriver &BD,
246 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000247 std::vector<Function*> &MiscompiledFunctions) {
248 bool MadeChange = false;
249 while (1) {
250 Module *ToNotOptimize = CloneModule(BD.getProgram());
251 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
252 MiscompiledFunctions);
253 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
254 if (!ToOptimizeLoopExtracted) {
255 // If the loop extractor crashed or if there were no extractible loops,
256 // then this chapter of our odyssey is over with.
257 delete ToNotOptimize;
258 delete ToOptimize;
259 return MadeChange;
260 }
261
262 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
263 delete ToOptimize;
264
265 // Bugpoint is intentionally not very trusting of LLVM transformations. In
266 // particular, we're not going to assume that the loop extractor works, so
267 // we're going to test the newly loop extracted program to make sure nothing
268 // has broken. If something broke, then we'll inform the user and stop
269 // extraction.
Chris Lattnera57d86b2004-04-05 22:58:16 +0000270 AbstractInterpreter *AI = BD.switchToCBE();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000271 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000272 BD.switchToInterpreter(AI);
273
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000274 // Merged program doesn't work anymore!
275 std::cerr << " *** ERROR: Loop extraction broke the program. :("
276 << " Please report a bug!\n";
277 std::cerr << " Continuing on with un-loop-extracted version.\n";
278 delete ToNotOptimize;
279 delete ToOptimizeLoopExtracted;
280 return MadeChange;
281 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000282 BD.switchToInterpreter(AI);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000283
Chris Lattnerb15825b2004-04-05 21:37:38 +0000284 std::cout << " Testing after loop extraction:\n";
285 // Clone modules, the tester function will free them.
286 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
287 Module *TNOBackup = CloneModule(ToNotOptimize);
288 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
289 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000290 // If the program is not still broken, then loop extraction did something
291 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000292 delete TOLEBackup;
293 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000294 return MadeChange;
295 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000296 ToOptimizeLoopExtracted = TOLEBackup;
297 ToNotOptimize = TNOBackup;
298
299 std::cout << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000300
Chris Lattner90c18c52004-11-16 06:31:38 +0000301 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
302 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
303 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Chris Lattnerfa1af132004-11-19 07:09:40 +0000304 if (!I->isExternal())
305 MisCompFunctions.push_back(std::make_pair(I->getName(),
306 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000307
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000308 // Okay, great! Now we know that we extracted a loop and that loop
309 // extraction both didn't break the program, and didn't mask the problem.
310 // Replace the current program with the loop extracted version, and try to
311 // extract another loop.
312 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000313 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000314 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukmaneed80e22004-07-23 01:30:49 +0000315 << ErrorMsg << '\n';
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000316 exit(1);
317 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000318 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000319
320 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000321 // module. Update this list to include all of the functions in the
322 // optimized and loop extracted module.
323 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000324 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
325 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first,
326 MisCompFunctions[i].second);
327 assert(NewF && "Function not found??");
328 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000329 }
330
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000331 BD.setNewProgram(ToNotOptimize);
332 MadeChange = true;
333 }
334}
335
Chris Lattner5e783ab2004-05-11 21:54:13 +0000336namespace {
337 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
338 BugDriver &BD;
339 bool (*TestFn)(BugDriver &, Module *, Module *);
340 std::vector<Function*> FunctionsBeingTested;
341 public:
342 ReduceMiscompiledBlocks(BugDriver &bd,
343 bool (*F)(BugDriver &, Module *, Module *),
344 const std::vector<Function*> &Fns)
345 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
346
347 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
348 std::vector<BasicBlock*> &Suffix) {
349 if (!Suffix.empty() && TestFuncs(Suffix))
350 return KeepSuffix;
351 if (TestFuncs(Prefix))
352 return KeepPrefix;
353 return NoFailure;
354 }
355
356 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
357 };
358}
359
360/// TestFuncs - Extract all blocks for the miscompiled functions except for the
361/// specified blocks. If the problem still exists, return true.
362///
363bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
364 // Test to see if the function is misoptimized if we ONLY run it on the
365 // functions listed in Funcs.
Chris Lattner68bee932004-05-12 16:08:01 +0000366 std::cout << "Checking to see if the program is misoptimized when all ";
367 if (!BBs.empty()) {
368 std::cout << "but these " << BBs.size() << " blocks are extracted: ";
369 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
370 std::cout << BBs[i]->getName() << " ";
371 if (BBs.size() > 10) std::cout << "...";
372 } else {
373 std::cout << "blocks are extracted.";
374 }
Misha Brukmaneed80e22004-07-23 01:30:49 +0000375 std::cout << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000376
377 // Split the module into the two halves of the program we want.
378 Module *ToNotOptimize = CloneModule(BD.getProgram());
379 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
380 FunctionsBeingTested);
381
382 // Try the extraction. If it doesn't work, then the block extractor crashed
383 // or something, in which case bugpoint can't chase down this possibility.
384 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
385 delete ToOptimize;
386 // Run the predicate, not that the predicate will delete both input modules.
387 return TestFn(BD, New, ToNotOptimize);
388 }
389 delete ToOptimize;
390 delete ToNotOptimize;
391 return false;
392}
393
394
395/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
396/// extract as many basic blocks from the region as possible without obscuring
397/// the bug.
398///
399static bool ExtractBlocks(BugDriver &BD,
400 bool (*TestFn)(BugDriver &, Module *, Module *),
401 std::vector<Function*> &MiscompiledFunctions) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000402 std::vector<BasicBlock*> Blocks;
403 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
404 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
405 E = MiscompiledFunctions[i]->end(); I != E; ++I)
406 Blocks.push_back(I);
407
408 // Use the list reducer to identify blocks that can be extracted without
409 // obscuring the bug. The Blocks list will end up containing blocks that must
410 // be retained from the original program.
411 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000412
413 // Check to see if all blocks are extractible first.
414 if (ReduceMiscompiledBlocks(BD, TestFn,
415 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
416 Blocks.clear();
417 } else {
418 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
419 if (Blocks.size() == OldSize)
420 return false;
421 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000422
Chris Lattner2290e752004-05-12 02:43:24 +0000423 Module *ProgClone = CloneModule(BD.getProgram());
424 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
425 MiscompiledFunctions);
426 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
427 if (Extracted == 0) {
428 // Wierd, extraction should have worked.
429 std::cerr << "Nondeterministic problem extracting blocks??\n";
430 delete ProgClone;
431 delete ToExtract;
432 return false;
433 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000434
Chris Lattner2290e752004-05-12 02:43:24 +0000435 // Otherwise, block extraction succeeded. Link the two program fragments back
436 // together.
437 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000438
Chris Lattner90c18c52004-11-16 06:31:38 +0000439 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
440 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
441 I != E; ++I)
Chris Lattnerfa1af132004-11-19 07:09:40 +0000442 if (!I->isExternal())
443 MisCompFunctions.push_back(std::make_pair(I->getName(),
444 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000445
Chris Lattner2290e752004-05-12 02:43:24 +0000446 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000447 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Chris Lattner2290e752004-05-12 02:43:24 +0000448 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukmaneed80e22004-07-23 01:30:49 +0000449 << ErrorMsg << '\n';
Chris Lattner2290e752004-05-12 02:43:24 +0000450 exit(1);
451 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000452 delete Extracted;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000453
Chris Lattner2290e752004-05-12 02:43:24 +0000454 // Set the new program and delete the old one.
455 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000456
Chris Lattner2290e752004-05-12 02:43:24 +0000457 // Update the list of miscompiled functions.
458 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000459
Chris Lattner90c18c52004-11-16 06:31:38 +0000460 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
461 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first,
462 MisCompFunctions[i].second);
463 assert(NewF && "Function not found??");
464 MiscompiledFunctions.push_back(NewF);
465 }
Chris Lattner2290e752004-05-12 02:43:24 +0000466
467 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000468}
469
470
Chris Lattnerb15825b2004-04-05 21:37:38 +0000471/// DebugAMiscompilation - This is a generic driver to narrow down
472/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000473///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000474static std::vector<Function*>
475DebugAMiscompilation(BugDriver &BD,
476 bool (*TestFn)(BugDriver &, Module *, Module *)) {
477 // Okay, now that we have reduced the list of passes which are causing the
478 // failure, see if we can pin down which functions are being
479 // miscompiled... first build a list of all of the non-external functions in
480 // the program.
481 std::vector<Function*> MiscompiledFunctions;
482 Module *Prog = BD.getProgram();
483 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
484 if (!I->isExternal())
485 MiscompiledFunctions.push_back(I);
486
487 // Do the reduction...
488 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
489
490 std::cout << "\n*** The following function"
491 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
492 << " being miscompiled: ";
493 PrintFunctionList(MiscompiledFunctions);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000494 std::cout << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000495
496 // See if we can rip any loops out of the miscompiled functions and still
497 // trigger the problem.
498 if (ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
499 // Okay, we extracted some loops and the problem still appears. See if we
500 // can eliminate some of the created functions from being candidates.
501
Chris Lattner36ee07f2004-04-11 23:52:35 +0000502 // Loop extraction can introduce functions with the same name (foo_code).
503 // Make sure to disambiguate the symbols so that when the program is split
504 // apart that we can link it back together again.
505 DisambiguateGlobalSymbols(BD.getProgram());
506
Chris Lattnerb15825b2004-04-05 21:37:38 +0000507 // Do the reduction...
508 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
509
510 std::cout << "\n*** The following function"
511 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
512 << " being miscompiled: ";
513 PrintFunctionList(MiscompiledFunctions);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000514 std::cout << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000515 }
516
Chris Lattner5e783ab2004-05-11 21:54:13 +0000517 if (ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
518 // Okay, we extracted some blocks and the problem still appears. See if we
519 // can eliminate some of the created functions from being candidates.
520
521 // Block extraction can introduce functions with the same name (foo_code).
522 // Make sure to disambiguate the symbols so that when the program is split
523 // apart that we can link it back together again.
524 DisambiguateGlobalSymbols(BD.getProgram());
525
526 // Do the reduction...
527 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
528
529 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 Lattner5e783ab2004-05-11 21:54:13 +0000534 }
535
Chris Lattnerb15825b2004-04-05 21:37:38 +0000536 return MiscompiledFunctions;
537}
538
Chris Lattnera57d86b2004-04-05 22:58:16 +0000539/// TestOptimizer - This is the predicate function used to check to see if the
540/// "Test" portion of the program is misoptimized. If so, return true. In any
541/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000542///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000543static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
544 // Run the optimization passes on ToOptimize, producing a transformed version
545 // of the functions being tested.
546 std::cout << " Optimizing functions being tested: ";
547 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
548 /*AutoDebugCrashes*/true);
549 std::cout << "done.\n";
550 delete Test;
551
552 std::cout << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000553 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000554 std::cout << (Broken ? " nope.\n" : " yup.\n");
555 return Broken;
556}
557
558
Chris Lattner4a106452002-12-23 23:50:16 +0000559/// debugMiscompilation - This method is used when the passes selected are not
560/// crashing, but the generated output is semantically different from the
561/// input.
562///
563bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000564 // Make sure something was miscompiled...
Misha Brukmanbe6bf562003-07-30 20:15:56 +0000565 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Chris Lattner4a106452002-12-23 23:50:16 +0000566 std::cerr << "*** Optimized program matches reference output! No problem "
567 << "detected...\nbugpoint can't help you with your problem!\n";
568 return false;
569 }
570
Chris Lattner640f22e2003-04-24 17:02:17 +0000571 std::cout << "\n*** Found miscompiling pass"
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000572 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
Misha Brukmaneed80e22004-07-23 01:30:49 +0000573 << getPassesString(getPassesToRun()) << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000574 EmitProgressBytecode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000575
Chris Lattnerb15825b2004-04-05 21:37:38 +0000576 std::vector<Function*> MiscompiledFunctions =
577 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000578
Chris Lattner640f22e2003-04-24 17:02:17 +0000579 // Output a bunch of bytecode files for the user...
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000580 std::cout << "Outputting reduced bytecode files which expose the problem:\n";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000581 Module *ToNotOptimize = CloneModule(getProgram());
582 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
583 MiscompiledFunctions);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000584
585 std::cout << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000586 ToNotOptimize = swapProgramIn(ToNotOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000587 EmitProgressBytecode("tonotoptimize", true);
588 setNewProgram(ToNotOptimize); // Delete hacked module.
589
590 std::cout << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000591 ToOptimize = swapProgramIn(ToOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000592 EmitProgressBytecode("tooptimize");
593 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000594
Chris Lattner4a106452002-12-23 23:50:16 +0000595 return false;
596}
Brian Gaeked0fde302003-11-11 22:41:34 +0000597
Chris Lattnera57d86b2004-04-05 22:58:16 +0000598/// CleanupAndPrepareModules - Get the specified modules ready for code
599/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000600///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000601static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
602 Module *Safe) {
603 // Clean up the modules, removing extra cruft that we don't need anymore...
604 Test = BD.performFinalCleanups(Test);
605
606 // If we are executing the JIT, we have several nasty issues to take care of.
607 if (!BD.isExecutingJIT()) return;
608
609 // First, if the main function is in the Safe module, we must add a stub to
610 // the Test module to call into it. Thus, we create a new function `main'
611 // which just calls the old one.
612 if (Function *oldMain = Safe->getNamedFunction("main"))
613 if (!oldMain->isExternal()) {
614 // Rename it
615 oldMain->setName("llvm_bugpoint_old_main");
616 // Create a NEW `main' function with same type in the test module.
617 Function *newMain = new Function(oldMain->getFunctionType(),
618 GlobalValue::ExternalLinkage,
619 "main", Test);
620 // Create an `oldmain' prototype in the test module, which will
621 // corresponds to the real main function in the same module.
622 Function *oldMainProto = new Function(oldMain->getFunctionType(),
623 GlobalValue::ExternalLinkage,
624 oldMain->getName(), Test);
625 // Set up and remember the argument list for the main function.
626 std::vector<Value*> args;
627 for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
628 OI = oldMain->abegin(); I != E; ++I, ++OI) {
629 I->setName(OI->getName()); // Copy argument names from oldMain
630 args.push_back(I);
631 }
632
633 // Call the old main function and return its result
634 BasicBlock *BB = new BasicBlock("entry", newMain);
Chris Lattnerfa1af132004-11-19 07:09:40 +0000635 CallInst *call = new CallInst(oldMainProto, args, "", BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000636
637 // If the type of old function wasn't void, return value of call
Chris Lattnerfa1af132004-11-19 07:09:40 +0000638 new ReturnInst(call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000639 }
640
641 // The second nasty issue we must deal with in the JIT is that the Safe
642 // module cannot directly reference any functions defined in the test
643 // module. Instead, we use a JIT API call to dynamically resolve the
644 // symbol.
645
646 // Add the resolver to the Safe module.
647 // Prototype: void *getPointerToNamedFunction(const char* Name)
648 Function *resolverFunc =
649 Safe->getOrInsertFunction("getPointerToNamedFunction",
650 PointerType::get(Type::SByteTy),
651 PointerType::get(Type::SByteTy), 0);
652
653 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000654 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000655 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
656 F->getIntrinsicID() == 0 /* ignore intrinsics */) {
Misha Brukmandc7fef82004-04-19 01:12:01 +0000657 Function *TestFn = Test->getFunction(F->getName(), F->getFunctionType());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000658
659 // Don't forward functions which are external in the test module too.
660 if (TestFn && !TestFn->isExternal()) {
661 // 1. Add a string constant with its name to the global file
662 Constant *InitArray = ConstantArray::get(F->getName());
663 GlobalVariable *funcName =
664 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
665 GlobalValue::InternalLinkage, InitArray,
666 F->getName() + "_name", Safe);
667
668 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
669 // sbyte* so it matches the signature of the resolver function.
670
671 // GetElementPtr *funcName, ulong 0, ulong 0
672 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
673 Value *GEP =
Reid Spencer518310c2004-07-18 00:44:37 +0000674 ConstantExpr::getGetElementPtr(funcName, GEPargs);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000675 std::vector<Value*> ResolverArgs;
676 ResolverArgs.push_back(GEP);
677
Misha Brukmande4803d2004-04-19 03:36:47 +0000678 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
679 // function that dynamically resolves the calls to F via our JIT API
680 if (F->use_begin() != F->use_end()) {
681 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000682 const FunctionType *FuncTy = F->getFunctionType();
Misha Brukmande4803d2004-04-19 03:36:47 +0000683 Function *FuncWrapper = new Function(FuncTy,
684 GlobalValue::InternalLinkage,
Misha Brukmandc7fef82004-04-19 01:12:01 +0000685 F->getName() + "_wrapper",
686 F->getParent());
687 BasicBlock *Header = new BasicBlock("header", FuncWrapper);
688
Misha Brukmande4803d2004-04-19 03:36:47 +0000689 // Resolve the call to function F via the JIT API:
690 //
691 // call resolver(GetElementPtr...)
692 CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
693 "resolver");
694 Header->getInstList().push_back(resolve);
695 // cast the result from the resolver to correctly-typed function
696 CastInst *castResolver =
697 new CastInst(resolve, PointerType::get(F->getFunctionType()),
698 "resolverCast");
699 Header->getInstList().push_back(castResolver);
700
Misha Brukmandc7fef82004-04-19 01:12:01 +0000701 // Save the argument list
702 std::vector<Value*> Args;
703 for (Function::aiterator i = FuncWrapper->abegin(),
704 e = FuncWrapper->aend(); i != e; ++i)
705 Args.push_back(i);
706
707 // Pass on the arguments to the real function, return its result
708 if (F->getReturnType() == Type::VoidTy) {
Misha Brukmande4803d2004-04-19 03:36:47 +0000709 CallInst *Call = new CallInst(castResolver, Args);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000710 Header->getInstList().push_back(Call);
711 ReturnInst *Ret = new ReturnInst();
712 Header->getInstList().push_back(Ret);
713 } else {
Misha Brukmande4803d2004-04-19 03:36:47 +0000714 CallInst *Call = new CallInst(castResolver, Args, "redir");
Misha Brukmandc7fef82004-04-19 01:12:01 +0000715 Header->getInstList().push_back(Call);
716 ReturnInst *Ret = new ReturnInst(Call);
717 Header->getInstList().push_back(Ret);
718 }
719
Misha Brukmande4803d2004-04-19 03:36:47 +0000720 // Use the wrapper function instead of the old function
721 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000722 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000723 }
724 }
725 }
726
727 if (verifyModule(*Test) || verifyModule(*Safe)) {
728 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
729 abort();
730 }
731}
732
733
734
735/// TestCodeGenerator - This is the predicate function used to check to see if
736/// the "Test" portion of the program is miscompiled by the code generator under
737/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000738///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000739static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
740 CleanupAndPrepareModules(BD, Test, Safe);
741
Reid Spencer97182982004-12-15 01:53:08 +0000742 sys::Path TestModuleBC("bugpoint.test.bc");
743 TestModuleBC.makeUnique();
744 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000745 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
746 exit(1);
747 }
748 delete Test;
749
750 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000751 sys::Path SafeModuleBC("bugpoint.safe.bc");
752 SafeModuleBC.makeUnique();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000753
Reid Spencer97182982004-12-15 01:53:08 +0000754 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000755 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
756 exit(1);
757 }
Reid Spencer97182982004-12-15 01:53:08 +0000758 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000759 delete Safe;
760
761 // Run the code generator on the `Test' code, loading the shared library.
762 // The function returns whether or not the new output differs from reference.
Reid Spencer97182982004-12-15 01:53:08 +0000763 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000764
765 if (Result)
766 std::cerr << ": still failing!\n";
767 else
768 std::cerr << ": didn't fail.\n";
Reid Spencer5f767602004-12-16 23:04:20 +0000769 TestModuleBC.destroyFile();
770 SafeModuleBC.destroyFile();
771 sys::Path(SharedObject).destroyFile();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000772
773 return Result;
774}
775
776
Misha Brukman8c194ea2004-04-21 18:36:43 +0000777/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
778///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000779bool BugDriver::debugCodeGenerator() {
780 if ((void*)cbe == (void*)Interpreter) {
781 std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
782 std::cout << "\n*** The C backend cannot match the reference diff, but it "
783 << "is used as the 'known good'\n code generator, so I can't"
784 << " debug it. Perhaps you have a front-end problem?\n As a"
785 << " sanity check, I left the result of executing the program "
786 << "with the C backend\n in this file for you: '"
787 << Result << "'.\n";
788 return true;
789 }
790
791 DisambiguateGlobalSymbols(Program);
792
793 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
794
795 // Split the module into the two halves of the program we want.
796 Module *ToNotCodeGen = CloneModule(getProgram());
797 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
798
799 // Condition the modules
800 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
801
Reid Spencer97182982004-12-15 01:53:08 +0000802 sys::Path TestModuleBC("bugpoint.test.bc");
803 TestModuleBC.makeUnique();
804
805 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000806 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
807 exit(1);
808 }
809 delete ToCodeGen;
810
811 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000812 sys::Path SafeModuleBC("bugpoint.safe.bc");
813 SafeModuleBC.makeUnique();
814
815 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000816 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
817 exit(1);
818 }
Reid Spencer97182982004-12-15 01:53:08 +0000819 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000820 delete ToNotCodeGen;
821
822 std::cout << "You can reproduce the problem with the command line: \n";
823 if (isExecutingJIT()) {
824 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
825 } else {
Chris Lattner59615f02005-01-15 00:07:19 +0000826 std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000827 std::cout << " gcc " << SharedObject << " " << TestModuleBC
Chris Lattner59615f02005-01-15 00:07:19 +0000828 << ".s -o " << TestModuleBC << ".exe";
829#if defined (HAVE_LINK_R)
830 std::cout << "-Wl,-R.";
831#endif
832 std::cout << "\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000833 std::cout << " " << TestModuleBC << ".exe";
834 }
835 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
836 std::cout << " " << InputArgv[i];
Misha Brukmaneed80e22004-07-23 01:30:49 +0000837 std::cout << '\n';
Chris Lattnera57d86b2004-04-05 22:58:16 +0000838 std::cout << "The shared object was created with:\n llc -march=c "
839 << SafeModuleBC << " -o temporary.c\n"
840 << " gcc -xc temporary.c -O2 -o " << SharedObject
841#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
842 << " -G" // Compile a shared library, `-G' for Sparc
843#else
844 << " -shared" // `-shared' for Linux/X86, maybe others
845#endif
846 << " -fno-strict-aliasing\n";
847
848 return false;
849}