blob: 64dfe8853ec79a9e8d40e79b46a1ede42323b738 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements optimizer and code generation miscompilation debugging
11// support.
12//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
16#include "ListReducer.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Linker.h"
21#include "llvm/Module.h"
22#include "llvm/Pass.h"
23#include "llvm/Analysis/Verifier.h"
24#include "llvm/Support/Mangler.h"
25#include "llvm/Transforms/Utils/Cloning.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
28#include "llvm/Config/config.h" // for HAVE_LINK_R
29using namespace llvm;
30
31namespace llvm {
32 extern cl::list<std::string> InputArgv;
33}
34
35namespace {
36 static llvm::cl::opt<bool>
37 DisableLoopExtraction("disable-loop-extraction",
38 cl::desc("Don't extract loops when searching for miscompilations"),
39 cl::init(false));
David Goodwin25c07052009-07-28 23:08:36 +000040 static llvm::cl::opt<bool>
41 DisableBlockExtraction("disable-block-extraction",
42 cl::desc("Don't extract blocks when searching for miscompilations"),
43 cl::init(false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044
45 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
46 BugDriver &BD;
47 public:
48 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
49
50 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
51 std::vector<const PassInfo*> &Suffix);
52 };
53}
54
55/// TestResult - After passes have been split into a test group and a control
56/// group, see if they still break the program.
57///
58ReduceMiscompilingPasses::TestResult
59ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
60 std::vector<const PassInfo*> &Suffix) {
61 // First, run the program with just the Suffix passes. If it is still broken
62 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanb714fab2009-07-16 15:30:09 +000063 outs() << "Checking to see if '" << getPassesString(Suffix)
64 << "' compiles correctly: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065
66 std::string BitcodeResult;
67 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +000068 errs() << " Error running this sequence of passes"
69 << " on the input program!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070 BD.setPassesToRun(Suffix);
71 BD.EmitProgressBitcode("pass-error", false);
72 exit(BD.debugOptimizerCrash());
73 }
Owen Anderson9f5b2aa2009-07-14 23:09:55 +000074
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075 // Check to see if the finished program matches the reference output...
76 if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
Dan Gohmanb714fab2009-07-16 15:30:09 +000077 outs() << " nope.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 if (Suffix.empty()) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +000079 errs() << BD.getToolName() << ": I'm confused: the test fails when "
80 << "no passes are run, nondeterministic program?\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 exit(1);
82 }
83 return KeepSuffix; // Miscompilation detected!
84 }
Dan Gohmanb714fab2009-07-16 15:30:09 +000085 outs() << " yup.\n"; // No miscompilation!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086
87 if (Prefix.empty()) return NoFailure;
88
89 // Next, see if the program is broken if we run the "prefix" passes first,
90 // then separately run the "kept" passes.
Dan Gohmanb714fab2009-07-16 15:30:09 +000091 outs() << "Checking to see if '" << getPassesString(Prefix)
92 << "' compiles correctly: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093
94 // If it is not broken with the kept passes, it's possible that the prefix
95 // passes must be run before the kept passes to break it. If the program
96 // WORKS after the prefix passes, but then fails if running the prefix AND
97 // kept passes, we can update our bitcode file to include the result of the
98 // prefix passes, then discard the prefix passes.
99 //
100 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000101 errs() << " Error running this sequence of passes"
102 << " on the input program!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 BD.setPassesToRun(Prefix);
104 BD.EmitProgressBitcode("pass-error", false);
105 exit(BD.debugOptimizerCrash());
106 }
107
108 // If the prefix maintains the predicate by itself, only keep the prefix!
109 if (BD.diffProgram(BitcodeResult)) {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000110 outs() << " nope.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 sys::Path(BitcodeResult).eraseFromDisk();
112 return KeepPrefix;
113 }
Dan Gohmanb714fab2009-07-16 15:30:09 +0000114 outs() << " yup.\n"; // No miscompilation!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115
116 // Ok, so now we know that the prefix passes work, try running the suffix
117 // passes on the result of the prefix passes.
118 //
Owen Anderson25209b42009-07-01 16:58:40 +0000119 Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 if (PrefixOutput == 0) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000121 errs() << BD.getToolName() << ": Error reading bitcode file '"
122 << BitcodeResult << "'!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 exit(1);
124 }
125 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
126
127 // Don't check if there are no passes in the suffix.
128 if (Suffix.empty())
129 return NoFailure;
130
Dan Gohmanb714fab2009-07-16 15:30:09 +0000131 outs() << "Checking to see if '" << getPassesString(Suffix)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 << "' passes compile correctly after the '"
133 << getPassesString(Prefix) << "' passes: ";
134
135 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
136 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000137 errs() << " Error running this sequence of passes"
138 << " on the input program!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139 BD.setPassesToRun(Suffix);
140 BD.EmitProgressBitcode("pass-error", false);
141 exit(BD.debugOptimizerCrash());
142 }
143
144 // Run the result...
145 if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000146 outs() << " nope.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 delete OriginalInput; // We pruned down the original input...
148 return KeepSuffix;
149 }
150
151 // Otherwise, we must not be running the bad pass anymore.
Dan Gohmanb714fab2009-07-16 15:30:09 +0000152 outs() << " yup.\n"; // No miscompilation!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
154 return NoFailure;
155}
156
157namespace {
158 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
159 BugDriver &BD;
160 bool (*TestFn)(BugDriver &, Module *, Module *);
161 public:
162 ReduceMiscompilingFunctions(BugDriver &bd,
163 bool (*F)(BugDriver &, Module *, Module *))
164 : BD(bd), TestFn(F) {}
165
166 virtual TestResult doTest(std::vector<Function*> &Prefix,
167 std::vector<Function*> &Suffix) {
168 if (!Suffix.empty() && TestFuncs(Suffix))
169 return KeepSuffix;
170 if (!Prefix.empty() && TestFuncs(Prefix))
171 return KeepPrefix;
172 return NoFailure;
173 }
174
175 bool TestFuncs(const std::vector<Function*> &Prefix);
176 };
177}
178
179/// TestMergedProgram - Given two modules, link them together and run the
180/// program, checking to see if the program matches the diff. If the diff
181/// matches, return false, otherwise return true. If the DeleteInputs argument
182/// is set to true then this function deletes both input modules before it
183/// returns.
184///
185static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
186 bool DeleteInputs) {
187 // Link the two portions of the program back to together.
188 std::string ErrorMsg;
189 if (!DeleteInputs) {
190 M1 = CloneModule(M1);
191 M2 = CloneModule(M2);
192 }
193 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000194 errs() << BD.getToolName() << ": Error linking modules together:"
195 << ErrorMsg << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 exit(1);
197 }
198 delete M2; // We are done with this module.
199
200 Module *OldProgram = BD.swapProgramIn(M1);
201
202 // Execute the program. If it does not match the expected output, we must
203 // return true.
204 bool Broken = BD.diffProgram();
205
206 // Delete the linked module & restore the original
207 BD.swapProgramIn(OldProgram);
208 delete M1;
209 return Broken;
210}
211
212/// TestFuncs - split functions in a Module into two groups: those that are
213/// under consideration for miscompilation vs. those that are not, and test
214/// accordingly. Each group of functions becomes a separate Module.
215///
216bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
217 // Test to see if the function is misoptimized if we ONLY run it on the
218 // functions listed in Funcs.
Dan Gohmanb714fab2009-07-16 15:30:09 +0000219 outs() << "Checking to see if the program is misoptimized when "
220 << (Funcs.size()==1 ? "this function is" : "these functions are")
221 << " run through the pass"
222 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 PrintFunctionList(Funcs);
Dan Gohmanb714fab2009-07-16 15:30:09 +0000224 outs() << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225
226 // Split the module into the two halves of the program we want.
Dan Gohman819b9562009-04-22 15:57:18 +0000227 DenseMap<const Value*, Value*> ValueMap;
228 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
229 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
230 ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231
Nick Lewycky43e736d2007-11-14 06:47:06 +0000232 // Run the predicate, note that the predicate will delete both input modules.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 return TestFn(BD, ToOptimize, ToNotOptimize);
234}
235
236/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
237/// modifying predominantly internal symbols rather than external ones.
238///
239static void DisambiguateGlobalSymbols(Module *M) {
240 // Try not to cause collisions by minimizing chances of renaming an
241 // already-external symbol, so take in external globals and functions as-is.
242 // The code should work correctly without disambiguation (assuming the same
243 // mangler is used by the two code generators), but having symbols with the
244 // same name causes warnings to be emitted by the code generator.
245 Mangler Mang(*M);
246 // Agree with the CBE on symbol naming
247 Mang.markCharUnacceptable('.');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner98a5ca12009-07-15 04:50:47 +0000249 I != E; ++I) {
250 // Don't mangle asm names.
251 if (!I->hasName() || I->getName()[0] != 1)
252 I->setName(Mang.getMangledName(I));
253 }
254 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Chris Lattner6baff2f2009-07-19 20:19:04 +0000255 // Don't mangle asm names or intrinsics.
Chris Lattnerb053ed42009-07-19 20:19:25 +0000256 if ((!I->hasName() || I->getName()[0] != 1) &&
257 I->getIntrinsicID() == 0)
Chris Lattner98a5ca12009-07-15 04:50:47 +0000258 I->setName(Mang.getMangledName(I));
259 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260}
261
262/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
263/// check to see if we can extract the loops in the region without obscuring the
264/// bug. If so, it reduces the amount of code identified.
265///
266static bool ExtractLoops(BugDriver &BD,
267 bool (*TestFn)(BugDriver &, Module *, Module *),
268 std::vector<Function*> &MiscompiledFunctions) {
269 bool MadeChange = false;
270 while (1) {
271 if (BugpointIsInterrupted) return MadeChange;
272
Dan Gohman819b9562009-04-22 15:57:18 +0000273 DenseMap<const Value*, Value*> ValueMap;
274 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman819b9562009-04-22 15:57:18 +0000276 MiscompiledFunctions,
277 ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
279 if (!ToOptimizeLoopExtracted) {
280 // If the loop extractor crashed or if there were no extractible loops,
281 // then this chapter of our odyssey is over with.
282 delete ToNotOptimize;
283 delete ToOptimize;
284 return MadeChange;
285 }
286
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000287 errs() << "Extracted a loop from the breaking portion of the program.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288
289 // Bugpoint is intentionally not very trusting of LLVM transformations. In
290 // particular, we're not going to assume that the loop extractor works, so
291 // we're going to test the newly loop extracted program to make sure nothing
292 // has broken. If something broke, then we'll inform the user and stop
293 // extraction.
Dan Gohman7fb02ed2008-12-08 04:02:47 +0000294 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
296 BD.switchToInterpreter(AI);
297
298 // Merged program doesn't work anymore!
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000299 errs() << " *** ERROR: Loop extraction broke the program. :("
300 << " Please report a bug!\n";
301 errs() << " Continuing on with un-loop-extracted version.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302
303 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
304 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
305 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
306 ToOptimizeLoopExtracted);
307
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000308 errs() << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 delete ToOptimize;
310 delete ToNotOptimize;
311 delete ToOptimizeLoopExtracted;
312 return MadeChange;
313 }
314 delete ToOptimize;
315 BD.switchToInterpreter(AI);
316
Dan Gohmanb714fab2009-07-16 15:30:09 +0000317 outs() << " Testing after loop extraction:\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 // Clone modules, the tester function will free them.
319 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
320 Module *TNOBackup = CloneModule(ToNotOptimize);
321 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000322 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 // If the program is not still broken, then loop extraction did something
324 // that masked the error. Stop loop extraction now.
325 delete TOLEBackup;
326 delete TNOBackup;
327 return MadeChange;
328 }
329 ToOptimizeLoopExtracted = TOLEBackup;
330 ToNotOptimize = TNOBackup;
331
Dan Gohmanb714fab2009-07-16 15:30:09 +0000332 outs() << "*** Loop extraction successful!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333
334 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
335 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
336 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
337 if (!I->isDeclaration())
338 MisCompFunctions.push_back(std::make_pair(I->getName(),
339 I->getFunctionType()));
340
341 // Okay, great! Now we know that we extracted a loop and that loop
342 // extraction both didn't break the program, and didn't mask the problem.
343 // Replace the current program with the loop extracted version, and try to
344 // extract another loop.
345 std::string ErrorMsg;
346 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000347 errs() << BD.getToolName() << ": Error linking modules together:"
348 << ErrorMsg << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 exit(1);
350 }
351 delete ToOptimizeLoopExtracted;
352
353 // All of the Function*'s in the MiscompiledFunctions list are in the old
354 // module. Update this list to include all of the functions in the
355 // optimized and loop extracted module.
356 MiscompiledFunctions.clear();
357 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
358 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
359
360 assert(NewF && "Function not found??");
361 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
362 "found wrong function type?");
363 MiscompiledFunctions.push_back(NewF);
364 }
365
366 BD.setNewProgram(ToNotOptimize);
367 MadeChange = true;
368 }
369}
370
371namespace {
372 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
373 BugDriver &BD;
374 bool (*TestFn)(BugDriver &, Module *, Module *);
375 std::vector<Function*> FunctionsBeingTested;
376 public:
377 ReduceMiscompiledBlocks(BugDriver &bd,
378 bool (*F)(BugDriver &, Module *, Module *),
379 const std::vector<Function*> &Fns)
380 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
381
382 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
383 std::vector<BasicBlock*> &Suffix) {
384 if (!Suffix.empty() && TestFuncs(Suffix))
385 return KeepSuffix;
386 if (TestFuncs(Prefix))
387 return KeepPrefix;
388 return NoFailure;
389 }
390
391 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
392 };
393}
394
395/// TestFuncs - Extract all blocks for the miscompiled functions except for the
396/// specified blocks. If the problem still exists, return true.
397///
398bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
399 // Test to see if the function is misoptimized if we ONLY run it on the
400 // functions listed in Funcs.
Dan Gohmanb714fab2009-07-16 15:30:09 +0000401 outs() << "Checking to see if the program is misoptimized when all ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 if (!BBs.empty()) {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000403 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanb714fab2009-07-16 15:30:09 +0000405 outs() << BBs[i]->getName() << " ";
406 if (BBs.size() > 10) outs() << "...";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407 } else {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000408 outs() << "blocks are extracted.";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 }
Dan Gohmanb714fab2009-07-16 15:30:09 +0000410 outs() << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411
412 // Split the module into the two halves of the program we want.
Dan Gohman819b9562009-04-22 15:57:18 +0000413 DenseMap<const Value*, Value*> ValueMap;
414 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman819b9562009-04-22 15:57:18 +0000416 FunctionsBeingTested,
417 ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418
419 // Try the extraction. If it doesn't work, then the block extractor crashed
420 // or something, in which case bugpoint can't chase down this possibility.
421 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
422 delete ToOptimize;
423 // Run the predicate, not that the predicate will delete both input modules.
424 return TestFn(BD, New, ToNotOptimize);
425 }
426 delete ToOptimize;
427 delete ToNotOptimize;
428 return false;
429}
430
431
432/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
433/// extract as many basic blocks from the region as possible without obscuring
434/// the bug.
435///
436static bool ExtractBlocks(BugDriver &BD,
437 bool (*TestFn)(BugDriver &, Module *, Module *),
438 std::vector<Function*> &MiscompiledFunctions) {
439 if (BugpointIsInterrupted) return false;
440
441 std::vector<BasicBlock*> Blocks;
442 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
443 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
444 E = MiscompiledFunctions[i]->end(); I != E; ++I)
445 Blocks.push_back(I);
446
447 // Use the list reducer to identify blocks that can be extracted without
448 // obscuring the bug. The Blocks list will end up containing blocks that must
449 // be retained from the original program.
450 unsigned OldSize = Blocks.size();
451
452 // Check to see if all blocks are extractible first.
453 if (ReduceMiscompiledBlocks(BD, TestFn,
454 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
455 Blocks.clear();
456 } else {
457 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
458 if (Blocks.size() == OldSize)
459 return false;
460 }
461
Dan Gohman819b9562009-04-22 15:57:18 +0000462 DenseMap<const Value*, Value*> ValueMap;
463 Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohman819b9562009-04-22 15:57:18 +0000465 MiscompiledFunctions,
466 ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
468 if (Extracted == 0) {
469 // Weird, extraction should have worked.
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000470 errs() << "Nondeterministic problem extracting blocks??\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 delete ProgClone;
472 delete ToExtract;
473 return false;
474 }
475
476 // Otherwise, block extraction succeeded. Link the two program fragments back
477 // together.
478 delete ToExtract;
479
480 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
481 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
482 I != E; ++I)
483 if (!I->isDeclaration())
484 MisCompFunctions.push_back(std::make_pair(I->getName(),
485 I->getFunctionType()));
486
487 std::string ErrorMsg;
488 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000489 errs() << BD.getToolName() << ": Error linking modules together:"
490 << ErrorMsg << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 exit(1);
492 }
493 delete Extracted;
494
495 // Set the new program and delete the old one.
496 BD.setNewProgram(ProgClone);
497
498 // Update the list of miscompiled functions.
499 MiscompiledFunctions.clear();
500
501 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
502 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
503 assert(NewF && "Function not found??");
504 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
505 "Function has wrong type??");
506 MiscompiledFunctions.push_back(NewF);
507 }
508
509 return true;
510}
511
512
513/// DebugAMiscompilation - This is a generic driver to narrow down
514/// miscompilations, either in an optimization or a code generator.
515///
516static std::vector<Function*>
517DebugAMiscompilation(BugDriver &BD,
518 bool (*TestFn)(BugDriver &, Module *, Module *)) {
519 // Okay, now that we have reduced the list of passes which are causing the
520 // failure, see if we can pin down which functions are being
521 // miscompiled... first build a list of all of the non-external functions in
522 // the program.
523 std::vector<Function*> MiscompiledFunctions;
524 Module *Prog = BD.getProgram();
525 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
526 if (!I->isDeclaration())
527 MiscompiledFunctions.push_back(I);
528
529 // Do the reduction...
530 if (!BugpointIsInterrupted)
531 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
532
Dan Gohmanb714fab2009-07-16 15:30:09 +0000533 outs() << "\n*** The following function"
534 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
535 << " being miscompiled: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanb714fab2009-07-16 15:30:09 +0000537 outs() << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538
539 // See if we can rip any loops out of the miscompiled functions and still
540 // trigger the problem.
541
542 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
543 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
544 // Okay, we extracted some loops and the problem still appears. See if we
545 // can eliminate some of the created functions from being candidates.
546
547 // Loop extraction can introduce functions with the same name (foo_code).
548 // Make sure to disambiguate the symbols so that when the program is split
549 // apart that we can link it back together again.
550 DisambiguateGlobalSymbols(BD.getProgram());
551
552 // Do the reduction...
553 if (!BugpointIsInterrupted)
554 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
555
Dan Gohmanb714fab2009-07-16 15:30:09 +0000556 outs() << "\n*** The following function"
557 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
558 << " being miscompiled: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanb714fab2009-07-16 15:30:09 +0000560 outs() << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 }
562
David Goodwin25c07052009-07-28 23:08:36 +0000563 if (!BugpointIsInterrupted && !DisableBlockExtraction &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
565 // Okay, we extracted some blocks and the problem still appears. See if we
566 // can eliminate some of the created functions from being candidates.
567
568 // Block extraction can introduce functions with the same name (foo_code).
569 // Make sure to disambiguate the symbols so that when the program is split
570 // apart that we can link it back together again.
571 DisambiguateGlobalSymbols(BD.getProgram());
572
573 // Do the reduction...
574 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
575
Dan Gohmanb714fab2009-07-16 15:30:09 +0000576 outs() << "\n*** The following function"
577 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
578 << " being miscompiled: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanb714fab2009-07-16 15:30:09 +0000580 outs() << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 }
582
583 return MiscompiledFunctions;
584}
585
586/// TestOptimizer - This is the predicate function used to check to see if the
587/// "Test" portion of the program is misoptimized. If so, return true. In any
588/// case, both module arguments are deleted.
589///
590static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
591 // Run the optimization passes on ToOptimize, producing a transformed version
592 // of the functions being tested.
Dan Gohmanb714fab2009-07-16 15:30:09 +0000593 outs() << " Optimizing functions being tested: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
595 /*AutoDebugCrashes*/true);
Dan Gohmanb714fab2009-07-16 15:30:09 +0000596 outs() << "done.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000597 delete Test;
598
Dan Gohmanb714fab2009-07-16 15:30:09 +0000599 outs() << " Checking to see if the merged program executes correctly: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Dan Gohmanb714fab2009-07-16 15:30:09 +0000601 outs() << (Broken ? " nope.\n" : " yup.\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 return Broken;
603}
604
605
606/// debugMiscompilation - This method is used when the passes selected are not
607/// crashing, but the generated output is semantically different from the
608/// input.
609///
610bool BugDriver::debugMiscompilation() {
611 // Make sure something was miscompiled...
612 if (!BugpointIsInterrupted)
613 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000614 errs() << "*** Optimized program matches reference output! No problem"
615 << " detected...\nbugpoint can't help you with your problem!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 return false;
617 }
618
Dan Gohmanb714fab2009-07-16 15:30:09 +0000619 outs() << "\n*** Found miscompiling pass"
620 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
621 << getPassesString(getPassesToRun()) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 EmitProgressBitcode("passinput");
623
624 std::vector<Function*> MiscompiledFunctions =
625 DebugAMiscompilation(*this, TestOptimizer);
626
627 // Output a bunch of bitcode files for the user...
Dan Gohmanb714fab2009-07-16 15:30:09 +0000628 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Dan Gohman819b9562009-04-22 15:57:18 +0000629 DenseMap<const Value*, Value*> ValueMap;
630 Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman819b9562009-04-22 15:57:18 +0000632 MiscompiledFunctions,
633 ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634
Dan Gohmanb714fab2009-07-16 15:30:09 +0000635 outs() << " Non-optimized portion: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 ToNotOptimize = swapProgramIn(ToNotOptimize);
637 EmitProgressBitcode("tonotoptimize", true);
638 setNewProgram(ToNotOptimize); // Delete hacked module.
639
Dan Gohmanb714fab2009-07-16 15:30:09 +0000640 outs() << " Portion that is input to optimizer: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 ToOptimize = swapProgramIn(ToOptimize);
642 EmitProgressBitcode("tooptimize");
643 setNewProgram(ToOptimize); // Delete hacked module.
644
645 return false;
646}
647
648/// CleanupAndPrepareModules - Get the specified modules ready for code
649/// generator testing.
650///
651static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
652 Module *Safe) {
653 // Clean up the modules, removing extra cruft that we don't need anymore...
654 Test = BD.performFinalCleanups(Test);
655
656 // If we are executing the JIT, we have several nasty issues to take care of.
657 if (!BD.isExecutingJIT()) return;
658
659 // First, if the main function is in the Safe module, we must add a stub to
660 // the Test module to call into it. Thus, we create a new function `main'
661 // which just calls the old one.
662 if (Function *oldMain = Safe->getFunction("main"))
663 if (!oldMain->isDeclaration()) {
664 // Rename it
665 oldMain->setName("llvm_bugpoint_old_main");
666 // Create a NEW `main' function with same type in the test module.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000667 Function *newMain = Function::Create(oldMain->getFunctionType(),
668 GlobalValue::ExternalLinkage,
669 "main", Test);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 // Create an `oldmain' prototype in the test module, which will
671 // corresponds to the real main function in the same module.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000672 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
673 GlobalValue::ExternalLinkage,
674 oldMain->getName(), Test);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675 // Set up and remember the argument list for the main function.
676 std::vector<Value*> args;
677 for (Function::arg_iterator
678 I = newMain->arg_begin(), E = newMain->arg_end(),
679 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Andersonab567f82008-04-14 17:38:21 +0000680 I->setName(OI->getName()); // Copy argument names from oldMain
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 args.push_back(I);
682 }
683
684 // Call the old main function and return its result
Owen Anderson35b47072009-08-13 21:58:54 +0000685 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000686 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
687 "", BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688
689 // If the type of old function wasn't void, return value of call
Owen Anderson35b47072009-08-13 21:58:54 +0000690 ReturnInst::Create(Safe->getContext(), call, BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 }
692
693 // The second nasty issue we must deal with in the JIT is that the Safe
694 // module cannot directly reference any functions defined in the test
695 // module. Instead, we use a JIT API call to dynamically resolve the
696 // symbol.
697
698 // Add the resolver to the Safe module.
699 // Prototype: void *getPointerToNamedFunction(const char* Name)
700 Constant *resolverFunc =
701 Safe->getOrInsertFunction("getPointerToNamedFunction",
Owen Anderson35b47072009-08-13 21:58:54 +0000702 PointerType::getUnqual(Type::getInt8Ty(Safe->getContext())),
703 PointerType::getUnqual(Type::getInt8Ty(Safe->getContext())),
704 (Type *)0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705
706 // Use the function we just added to get addresses of functions we need.
707 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
708 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sands79d28872007-12-03 20:06:50 +0000709 !F->isIntrinsic() /* ignore intrinsics */) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 Function *TestFn = Test->getFunction(F->getName());
711
712 // Don't forward functions which are external in the test module too.
713 if (TestFn && !TestFn->isDeclaration()) {
714 // 1. Add a string constant with its name to the global file
Owen Anderson35b47072009-08-13 21:58:54 +0000715 Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 GlobalVariable *funcName =
Owen Andersone17fc1d2009-07-08 19:03:57 +0000717 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 GlobalValue::InternalLinkage, InitArray,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000719 F->getName() + "_name");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720
721 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
722 // sbyte* so it matches the signature of the resolver function.
723
724 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson35b47072009-08-13 21:58:54 +0000725 std::vector<Constant*> GEPargs(2,
726 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
Owen Anderson9f5b2aa2009-07-14 23:09:55 +0000727 Value *GEP =
Owen Anderson02b48c32009-07-29 18:55:55 +0000728 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 std::vector<Value*> ResolverArgs;
730 ResolverArgs.push_back(GEP);
731
732 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
733 // function that dynamically resolves the calls to F via our JIT API
734 if (!F->use_empty()) {
735 // Create a new global to hold the cached function pointer.
Owen Andersonb99ecca2009-07-30 23:03:37 +0000736 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 GlobalVariable *Cache =
Owen Andersone17fc1d2009-07-08 19:03:57 +0000738 new GlobalVariable(*F->getParent(), F->getType(),
739 false, GlobalValue::InternalLinkage,
740 NullPtr,F->getName()+".fpcache");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741
742 // Construct a new stub function that will re-route calls to F
743 const FunctionType *FuncTy = F->getFunctionType();
Gabor Greifd6da1d02008-04-06 20:25:17 +0000744 Function *FuncWrapper = Function::Create(FuncTy,
745 GlobalValue::InternalLinkage,
746 F->getName() + "_wrapper",
747 F->getParent());
Owen Anderson35b47072009-08-13 21:58:54 +0000748 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
749 "entry", FuncWrapper);
750 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
751 "usecache", FuncWrapper);
752 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
753 "lookupfp", FuncWrapper);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754
755 // Check to see if we already looked up the value.
756 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson6601fcd2009-07-09 23:48:35 +0000757 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
758 NullPtr, "isNull");
Gabor Greifd6da1d02008-04-06 20:25:17 +0000759 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760
761 // Resolve the call to function F via the JIT API:
762 //
763 // call resolver(GetElementPtr...)
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000764 CallInst *Resolver =
765 CallInst::Create(resolverFunc, ResolverArgs.begin(),
766 ResolverArgs.end(), "resolver", LookupBB);
767
768 // Cast the result from the resolver to correctly-typed function.
769 CastInst *CastedResolver =
770 new BitCastInst(Resolver,
Owen Anderson6b6e2d92009-07-29 22:17:13 +0000771 PointerType::getUnqual(F->getFunctionType()),
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000772 "resolverCast", LookupBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773
774 // Save the value in our cache.
775 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000776 BranchInst::Create(DoCallBB, LookupBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000778 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
779 "fp", DoCallBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 FuncPtr->addIncoming(CastedResolver, LookupBB);
781 FuncPtr->addIncoming(CachedVal, EntryBB);
782
783 // Save the argument list.
784 std::vector<Value*> Args;
785 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
786 e = FuncWrapper->arg_end(); i != e; ++i)
787 Args.push_back(i);
788
789 // Pass on the arguments to the real function, return its result
Owen Anderson35b47072009-08-13 21:58:54 +0000790 if (F->getReturnType() == Type::getVoidTy(F->getContext())) {
Gabor Greifd6da1d02008-04-06 20:25:17 +0000791 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
Owen Anderson35b47072009-08-13 21:58:54 +0000792 ReturnInst::Create(F->getContext(), DoCallBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +0000794 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
795 "retval", DoCallBB);
Owen Anderson35b47072009-08-13 21:58:54 +0000796 ReturnInst::Create(F->getContext(),Call, DoCallBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 }
798
799 // Use the wrapper function instead of the old function
800 F->replaceAllUsesWith(FuncWrapper);
801 }
802 }
803 }
804 }
805
806 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000807 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 abort();
809 }
810}
811
812
813
814/// TestCodeGenerator - This is the predicate function used to check to see if
815/// the "Test" portion of the program is miscompiled by the code generator under
816/// test. If so, return true. In any case, both module arguments are deleted.
817///
818static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
819 CleanupAndPrepareModules(BD, Test, Safe);
820
821 sys::Path TestModuleBC("bugpoint.test.bc");
822 std::string ErrMsg;
823 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000824 errs() << BD.getToolName() << "Error making unique filename: "
825 << ErrMsg << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826 exit(1);
827 }
828 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000829 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000830 exit(1);
831 }
832 delete Test;
833
834 // Make the shared library
835 sys::Path SafeModuleBC("bugpoint.safe.bc");
836 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000837 errs() << BD.getToolName() << "Error making unique filename: "
838 << ErrMsg << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 exit(1);
840 }
841
842 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000843 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 exit(1);
845 }
846 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
847 delete Safe;
848
849 // Run the code generator on the `Test' code, loading the shared library.
850 // The function returns whether or not the new output differs from reference.
851 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
852
853 if (Result)
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000854 errs() << ": still failing!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 else
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000856 errs() << ": didn't fail.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 TestModuleBC.eraseFromDisk();
858 SafeModuleBC.eraseFromDisk();
859 sys::Path(SharedObject).eraseFromDisk();
860
861 return Result;
862}
863
864
865/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
866///
867bool BugDriver::debugCodeGenerator() {
Dan Gohman7fb02ed2008-12-08 04:02:47 +0000868 if ((void*)SafeInterpreter == (void*)Interpreter) {
869 std::string Result = executeProgramSafely("bugpoint.safe.out");
Dan Gohmanb714fab2009-07-16 15:30:09 +0000870 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
871 << "the reference diff. This may be due to a\n front-end "
872 << "bug or a bug in the original program, but this can also "
873 << "happen if bugpoint isn't running the program with the "
874 << "right flags or input.\n I left the result of executing "
875 << "the program with the \"safe\" backend in this file for "
876 << "you: '"
877 << Result << "'.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878 return true;
879 }
880
881 DisambiguateGlobalSymbols(Program);
882
883 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
884
885 // Split the module into the two halves of the program we want.
Dan Gohman819b9562009-04-22 15:57:18 +0000886 DenseMap<const Value*, Value*> ValueMap;
887 Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
888 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889
890 // Condition the modules
891 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
892
893 sys::Path TestModuleBC("bugpoint.test.bc");
894 std::string ErrMsg;
895 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000896 errs() << getToolName() << "Error making unique filename: "
897 << ErrMsg << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000898 exit(1);
899 }
900
901 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000902 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 exit(1);
904 }
905 delete ToCodeGen;
906
907 // Make the shared library
908 sys::Path SafeModuleBC("bugpoint.safe.bc");
909 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000910 errs() << getToolName() << "Error making unique filename: "
911 << ErrMsg << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 exit(1);
913 }
914
915 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000916 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 exit(1);
918 }
919 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
920 delete ToNotCodeGen;
921
Dan Gohmanb714fab2009-07-16 15:30:09 +0000922 outs() << "You can reproduce the problem with the command line: \n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 if (isExecutingJIT()) {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000924 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 } else {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000926 outs() << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
927 outs() << " gcc " << SharedObject << " " << TestModuleBC
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 << ".s -o " << TestModuleBC << ".exe";
929#if defined (HAVE_LINK_R)
Dan Gohmanb714fab2009-07-16 15:30:09 +0000930 outs() << " -Wl,-R.";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931#endif
Dan Gohmanb714fab2009-07-16 15:30:09 +0000932 outs() << "\n";
933 outs() << " " << TestModuleBC << ".exe";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 }
935 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanb714fab2009-07-16 15:30:09 +0000936 outs() << " " << InputArgv[i];
937 outs() << '\n';
938 outs() << "The shared object was created with:\n llc -march=c "
939 << SafeModuleBC << " -o temporary.c\n"
940 << " gcc -xc temporary.c -O2 -o " << SharedObject
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
Dan Gohmanb714fab2009-07-16 15:30:09 +0000942 << " -G" // Compile a shared library, `-G' for Sparc
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943#else
Dan Gohmanb714fab2009-07-16 15:30:09 +0000944 << " -fPIC -shared" // `-shared' for Linux/X86, maybe others
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945#endif
Dan Gohmanb714fab2009-07-16 15:30:09 +0000946 << " -fno-strict-aliasing\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947
948 return false;
949}