blob: c17f2a9d00ff82d31bc50cdc698e730522637b1f [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//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Daniel Dunbarca740962009-08-18 03:35:57 +000017#include "ToolRunner.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Instructions.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000021#include "llvm/Linker.h"
Chris Lattner4a106452002-12-23 23:50:16 +000022#include "llvm/Module.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000023#include "llvm/Pass.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000024#include "llvm/Analysis/Verifier.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 {
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +000032 extern cl::opt<std::string> OutputPrefix;
Chris Lattnera57d86b2004-04-05 22:58:16 +000033 extern cl::list<std::string> InputArgv;
34}
35
Chris Lattnerefdc0b52004-03-14 20:50:42 +000036namespace {
Reid Spencerdc31a8a2006-11-11 19:05:02 +000037 static llvm::cl::opt<bool>
38 DisableLoopExtraction("disable-loop-extraction",
39 cl::desc("Don't extract loops when searching for miscompilations"),
40 cl::init(false));
David Goodwin265d82e2009-07-28 23:08:36 +000041 static llvm::cl::opt<bool>
42 DisableBlockExtraction("disable-block-extraction",
43 cl::desc("Don't extract blocks when searching for miscompilations"),
44 cl::init(false));
Reid Spencerdc31a8a2006-11-11 19:05:02 +000045
Owen Anderson8be32912010-07-20 08:26:15 +000046 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
Chris Lattnerfa761832004-01-14 03:38:37 +000047 BugDriver &BD;
48 public:
49 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +000050
Owen Anderson8be32912010-07-20 08:26:15 +000051 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
52 std::vector<const PassInfo*> &Suffix,
Nick Lewycky22ff7482010-04-12 05:08:25 +000053 std::string &Error);
Chris Lattnerfa761832004-01-14 03:38:37 +000054 };
55}
Chris Lattner640f22e2003-04-24 17:02:17 +000056
Misha Brukman8c194ea2004-04-21 18:36:43 +000057/// TestResult - After passes have been split into a test group and a control
58/// group, see if they still break the program.
59///
Chris Lattner640f22e2003-04-24 17:02:17 +000060ReduceMiscompilingPasses::TestResult
Owen Anderson8be32912010-07-20 08:26:15 +000061ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
62 std::vector<const PassInfo*> &Suffix,
Nick Lewycky22ff7482010-04-12 05:08:25 +000063 std::string &Error) {
Chris Lattner06943ad2003-04-25 03:16:05 +000064 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000065 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000066 outs() << "Checking to see if '" << getPassesString(Suffix)
67 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000068
Gabor Greif8ff70c22007-07-04 21:55:50 +000069 std::string BitcodeResult;
70 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +000071 errs() << " Error running this sequence of passes"
72 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000073 BD.setPassesToRun(Suffix);
Rafael Espindolabae1b712010-07-28 18:12:30 +000074 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000075 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000076 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000077
Chris Lattner640f22e2003-04-24 17:02:17 +000078 // Check to see if the finished program matches the reference output...
Nick Lewycky22ff7482010-04-12 05:08:25 +000079 bool Diff = BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/,
80 &Error);
81 if (!Error.empty())
82 return InternalError;
83 if (Diff) {
Dan Gohmanac95cc72009-07-16 15:30:09 +000084 outs() << " nope.\n";
Chris Lattner59615f02005-01-15 00:07:19 +000085 if (Suffix.empty()) {
Dan Gohman65f57c22009-07-15 16:35:29 +000086 errs() << BD.getToolName() << ": I'm confused: the test fails when "
87 << "no passes are run, nondeterministic program?\n";
Chris Lattner59615f02005-01-15 00:07:19 +000088 exit(1);
89 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000090 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000091 }
Dan Gohmanac95cc72009-07-16 15:30:09 +000092 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000093
94 if (Prefix.empty()) return NoFailure;
95
Chris Lattner06943ad2003-04-25 03:16:05 +000096 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000097 // then separately run the "kept" passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000098 outs() << "Checking to see if '" << getPassesString(Prefix)
99 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +0000100
101 // If it is not broken with the kept passes, it's possible that the prefix
102 // passes must be run before the kept passes to break it. If the program
103 // WORKS after the prefix passes, but then fails if running the prefix AND
Gabor Greif8ff70c22007-07-04 21:55:50 +0000104 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner640f22e2003-04-24 17:02:17 +0000105 // prefix passes, then discard the prefix passes.
106 //
Gabor Greif8ff70c22007-07-04 21:55:50 +0000107 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000108 errs() << " Error running this sequence of passes"
109 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000110 BD.setPassesToRun(Prefix);
Rafael Espindolabae1b712010-07-28 18:12:30 +0000111 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000112 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000113 }
114
115 // If the prefix maintains the predicate by itself, only keep the prefix!
Nick Lewycky22ff7482010-04-12 05:08:25 +0000116 Diff = BD.diffProgram(BitcodeResult, "", false, &Error);
117 if (!Error.empty())
118 return InternalError;
119 if (Diff) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000120 outs() << " nope.\n";
Gabor Greif8ff70c22007-07-04 21:55:50 +0000121 sys::Path(BitcodeResult).eraseFromDisk();
Chris Lattner640f22e2003-04-24 17:02:17 +0000122 return KeepPrefix;
123 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000124 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +0000125
126 // Ok, so now we know that the prefix passes work, try running the suffix
127 // passes on the result of the prefix passes.
128 //
Jeffrey Yasskin6865f292010-05-11 23:25:16 +0000129 OwningPtr<Module> PrefixOutput(ParseInputFile(BitcodeResult,
130 BD.getContext()));
Chris Lattner640f22e2003-04-24 17:02:17 +0000131 if (PrefixOutput == 0) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000132 errs() << BD.getToolName() << ": Error reading bitcode file '"
133 << BitcodeResult << "'!\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000134 exit(1);
135 }
Gabor Greif8ff70c22007-07-04 21:55:50 +0000136 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
Chris Lattnerf4789e62004-04-23 20:36:51 +0000137
138 // Don't check if there are no passes in the suffix.
139 if (Suffix.empty())
140 return NoFailure;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000141
Dan Gohmanac95cc72009-07-16 15:30:09 +0000142 outs() << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000143 << "' passes compile correctly after the '"
144 << getPassesString(Prefix) << "' passes: ";
145
Jeffrey Yasskin6865f292010-05-11 23:25:16 +0000146 OwningPtr<Module> OriginalInput(BD.swapProgramIn(PrefixOutput.take()));
Gabor Greif8ff70c22007-07-04 21:55:50 +0000147 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000148 errs() << " Error running this sequence of passes"
149 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000150 BD.setPassesToRun(Suffix);
Rafael Espindolabae1b712010-07-28 18:12:30 +0000151 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000152 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000153 }
154
155 // Run the result...
Nick Lewycky22ff7482010-04-12 05:08:25 +0000156 Diff = BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/, &Error);
157 if (!Error.empty())
158 return InternalError;
159 if (Diff) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000160 outs() << " nope.\n";
Chris Lattner06943ad2003-04-25 03:16:05 +0000161 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000162 }
163
164 // Otherwise, we must not be running the bad pass anymore.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000165 outs() << " yup.\n"; // No miscompilation!
Jeffrey Yasskin6865f292010-05-11 23:25:16 +0000166 // Restore orig program & free test.
167 delete BD.swapProgramIn(OriginalInput.take());
Chris Lattner640f22e2003-04-24 17:02:17 +0000168 return NoFailure;
169}
170
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000171namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000172 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
173 BugDriver &BD;
Nick Lewycky22ff7482010-04-12 05:08:25 +0000174 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
Chris Lattnerfa761832004-01-14 03:38:37 +0000175 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000176 ReduceMiscompilingFunctions(BugDriver &bd,
Nick Lewycky22ff7482010-04-12 05:08:25 +0000177 bool (*F)(BugDriver &, Module *, Module *,
178 std::string &))
Chris Lattnerb15825b2004-04-05 21:37:38 +0000179 : BD(bd), TestFn(F) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000180
Chris Lattnerfa761832004-01-14 03:38:37 +0000181 virtual TestResult doTest(std::vector<Function*> &Prefix,
Nick Lewycky22ff7482010-04-12 05:08:25 +0000182 std::vector<Function*> &Suffix,
183 std::string &Error) {
184 if (!Suffix.empty()) {
185 bool Ret = TestFuncs(Suffix, Error);
186 if (!Error.empty())
187 return InternalError;
188 if (Ret)
189 return KeepSuffix;
190 }
191 if (!Prefix.empty()) {
192 bool Ret = TestFuncs(Prefix, Error);
193 if (!Error.empty())
194 return InternalError;
195 if (Ret)
196 return KeepPrefix;
197 }
Chris Lattnerfa761832004-01-14 03:38:37 +0000198 return NoFailure;
199 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000200
Rafael Espindola84ae2062010-07-26 00:07:51 +0000201 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
Chris Lattnerfa761832004-01-14 03:38:37 +0000202 };
203}
Chris Lattner640f22e2003-04-24 17:02:17 +0000204
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000205/// TestMergedProgram - Given two modules, link them together and run the
206/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000207/// matches, return false, otherwise return true. If the DeleteInputs argument
208/// is set to true then this function deletes both input modules before it
209/// returns.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000210///
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000211static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
Nick Lewycky22ff7482010-04-12 05:08:25 +0000212 bool DeleteInputs, std::string &Error) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000213 // Link the two portions of the program back to together.
214 std::string ErrorMsg;
Chris Lattner90c18c52004-11-16 06:31:38 +0000215 if (!DeleteInputs) {
216 M1 = CloneModule(M1);
217 M2 = CloneModule(M2);
218 }
Reid Spencere4874022004-12-13 03:01:03 +0000219 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000220 errs() << BD.getToolName() << ": Error linking modules together:"
221 << ErrorMsg << '\n';
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000222 exit(1);
223 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000224 delete M2; // We are done with this module.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000225
Jeffrey Yasskin6865f292010-05-11 23:25:16 +0000226 OwningPtr<Module> OldProgram(BD.swapProgramIn(M1));
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000227
228 // Execute the program. If it does not match the expected output, we must
229 // return true.
Nick Lewycky22ff7482010-04-12 05:08:25 +0000230 bool Broken = BD.diffProgram("", "", false, &Error);
231 if (!Error.empty()) {
232 // Delete the linked module & restore the original
Jeffrey Yasskin6865f292010-05-11 23:25:16 +0000233 delete BD.swapProgramIn(OldProgram.take());
Nick Lewycky22ff7482010-04-12 05:08:25 +0000234 }
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000235 return Broken;
236}
237
Misha Brukman8c194ea2004-04-21 18:36:43 +0000238/// TestFuncs - split functions in a Module into two groups: those that are
239/// under consideration for miscompilation vs. those that are not, and test
240/// accordingly. Each group of functions becomes a separate Module.
241///
Rafael Espindola84ae2062010-07-26 00:07:51 +0000242bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
243 std::string &Error) {
Chris Lattner640f22e2003-04-24 17:02:17 +0000244 // Test to see if the function is misoptimized if we ONLY run it on the
245 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000246 outs() << "Checking to see if the program is misoptimized when "
247 << (Funcs.size()==1 ? "this function is" : "these functions are")
248 << " run through the pass"
249 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000250 PrintFunctionList(Funcs);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000251 outs() << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000252
Rafael Espindola84ae2062010-07-26 00:07:51 +0000253 // Create a clone for two reasons:
254 // * If the optimization passes delete any function, the deleted function
255 // will be in the clone and Funcs will still point to valid memory
256 // * If the optimization passes use interprocedural information to break
257 // a function, we want to continue with the original function. Otherwise
258 // we can conclude that a function triggers the bug when in fact one
259 // needs a larger set of original functions to do so.
Devang Patele9916a32010-06-24 00:33:28 +0000260 ValueMap<const Value*, Value*> VMap;
Rafael Espindola84ae2062010-07-26 00:07:51 +0000261 Module *Clone = CloneModule(BD.getProgram(), VMap);
262 Module *Orig = BD.swapProgramIn(Clone);
263
264 std::vector<Function*> FuncsOnClone;
265 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
266 Function *F = cast<Function>(VMap[Funcs[i]]);
267 FuncsOnClone.push_back(F);
268 }
269
270 // Split the module into the two halves of the program we want.
271 VMap.clear();
Devang Patele9916a32010-06-24 00:33:28 +0000272 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Rafael Espindola84ae2062010-07-26 00:07:51 +0000273 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
Devang Patele9916a32010-06-24 00:33:28 +0000274 VMap);
Chris Lattner640f22e2003-04-24 17:02:17 +0000275
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000276 // Run the predicate, note that the predicate will delete both input modules.
Rafael Espindola84ae2062010-07-26 00:07:51 +0000277 bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
278
279 delete BD.swapProgramIn(Orig);
280
281 return Broken;
Chris Lattner640f22e2003-04-24 17:02:17 +0000282}
283
Chris Lattner8abfb8a2010-01-16 21:34:01 +0000284/// DisambiguateGlobalSymbols - Give anonymous global values names.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000285///
Chris Lattner36ee07f2004-04-11 23:52:35 +0000286static void DisambiguateGlobalSymbols(Module *M) {
Chris Lattner67ef9e42006-05-04 23:35:31 +0000287 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner1ffb33d2010-01-16 21:34:51 +0000288 I != E; ++I)
Chris Lattner8abfb8a2010-01-16 21:34:01 +0000289 if (!I->hasName())
290 I->setName("anon_global");
Chris Lattner1ffb33d2010-01-16 21:34:51 +0000291 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner8abfb8a2010-01-16 21:34:01 +0000292 if (!I->hasName())
293 I->setName("anon_fn");
Chris Lattner36ee07f2004-04-11 23:52:35 +0000294}
295
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000296/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
297/// check to see if we can extract the loops in the region without obscuring the
298/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000299///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000300static bool ExtractLoops(BugDriver &BD,
Nick Lewycky22ff7482010-04-12 05:08:25 +0000301 bool (*TestFn)(BugDriver &, Module *, Module *,
302 std::string &),
303 std::vector<Function*> &MiscompiledFunctions,
304 std::string &Error) {
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000305 bool MadeChange = false;
306 while (1) {
Chris Lattneraed98fa2005-08-02 23:25:56 +0000307 if (BugpointIsInterrupted) return MadeChange;
308
Devang Patele9916a32010-06-24 00:33:28 +0000309 ValueMap<const Value*, Value*> VMap;
310 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000311 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000312 MiscompiledFunctions,
Devang Patele9916a32010-06-24 00:33:28 +0000313 VMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000314 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
315 if (!ToOptimizeLoopExtracted) {
316 // If the loop extractor crashed or if there were no extractible loops,
317 // then this chapter of our odyssey is over with.
318 delete ToNotOptimize;
319 delete ToOptimize;
320 return MadeChange;
321 }
322
Dan Gohman65f57c22009-07-15 16:35:29 +0000323 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000324
325 // Bugpoint is intentionally not very trusting of LLVM transformations. In
326 // particular, we're not going to assume that the loop extractor works, so
327 // we're going to test the newly loop extracted program to make sure nothing
328 // has broken. If something broke, then we'll inform the user and stop
329 // extraction.
Dan Gohman70ef4492008-12-08 04:02:47 +0000330 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Nick Lewycky22ff7482010-04-12 05:08:25 +0000331 bool Failure = TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize,
332 false, Error);
333 if (!Error.empty())
334 return false;
335 if (Failure) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000336 BD.switchToInterpreter(AI);
337
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000338 // Merged program doesn't work anymore!
Dan Gohman65f57c22009-07-15 16:35:29 +0000339 errs() << " *** ERROR: Loop extraction broke the program. :("
340 << " Please report a bug!\n";
341 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000342
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +0000343 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
344 ToNotOptimize);
345 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
346 ToOptimize);
347 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
Chris Lattner56c41862005-05-08 21:54:56 +0000348 ToOptimizeLoopExtracted);
349
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +0000350 errs() << "Please submit the "
351 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000352 delete ToOptimize;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000353 delete ToNotOptimize;
354 delete ToOptimizeLoopExtracted;
355 return MadeChange;
356 }
Chris Lattner56c41862005-05-08 21:54:56 +0000357 delete ToOptimize;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000358 BD.switchToInterpreter(AI);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000359
Dan Gohmanac95cc72009-07-16 15:30:09 +0000360 outs() << " Testing after loop extraction:\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000361 // Clone modules, the tester function will free them.
362 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
363 Module *TNOBackup = CloneModule(ToNotOptimize);
Nick Lewycky22ff7482010-04-12 05:08:25 +0000364 Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
365 if (!Error.empty())
366 return false;
367 if (!Failure) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000368 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000369 // If the program is not still broken, then loop extraction did something
370 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000371 delete TOLEBackup;
372 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000373 return MadeChange;
374 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000375 ToOptimizeLoopExtracted = TOLEBackup;
376 ToNotOptimize = TNOBackup;
377
Dan Gohmanac95cc72009-07-16 15:30:09 +0000378 outs() << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000379
Chris Lattner90c18c52004-11-16 06:31:38 +0000380 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
381 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
382 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000383 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000384 MisCompFunctions.push_back(std::make_pair(I->getName(),
385 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000386
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000387 // Okay, great! Now we know that we extracted a loop and that loop
388 // extraction both didn't break the program, and didn't mask the problem.
389 // Replace the current program with the loop extracted version, and try to
390 // extract another loop.
391 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000392 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Dan Gohman65f57c22009-07-15 16:35:29 +0000393 errs() << BD.getToolName() << ": Error linking modules together:"
394 << ErrorMsg << '\n';
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000395 exit(1);
396 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000397 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000398
399 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000400 // module. Update this list to include all of the functions in the
401 // optimized and loop extracted module.
402 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000403 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000404 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
405
Chris Lattner90c18c52004-11-16 06:31:38 +0000406 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000407 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
408 "found wrong function type?");
Chris Lattner90c18c52004-11-16 06:31:38 +0000409 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000410 }
411
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000412 BD.setNewProgram(ToNotOptimize);
413 MadeChange = true;
414 }
415}
416
Chris Lattner5e783ab2004-05-11 21:54:13 +0000417namespace {
418 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
419 BugDriver &BD;
Nick Lewycky22ff7482010-04-12 05:08:25 +0000420 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000421 std::vector<Function*> FunctionsBeingTested;
422 public:
423 ReduceMiscompiledBlocks(BugDriver &bd,
Nick Lewycky22ff7482010-04-12 05:08:25 +0000424 bool (*F)(BugDriver &, Module *, Module *,
425 std::string &),
Chris Lattner5e783ab2004-05-11 21:54:13 +0000426 const std::vector<Function*> &Fns)
427 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000428
Chris Lattner5e783ab2004-05-11 21:54:13 +0000429 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
Nick Lewycky22ff7482010-04-12 05:08:25 +0000430 std::vector<BasicBlock*> &Suffix,
431 std::string &Error) {
432 if (!Suffix.empty()) {
433 bool Ret = TestFuncs(Suffix, Error);
434 if (!Error.empty())
435 return InternalError;
436 if (Ret)
437 return KeepSuffix;
438 }
439 if (!Prefix.empty()) {
440 bool Ret = TestFuncs(Prefix, Error);
441 if (!Error.empty())
442 return InternalError;
443 if (Ret)
444 return KeepPrefix;
445 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000446 return NoFailure;
447 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000448
Nick Lewycky22ff7482010-04-12 05:08:25 +0000449 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000450 };
451}
452
453/// TestFuncs - Extract all blocks for the miscompiled functions except for the
454/// specified blocks. If the problem still exists, return true.
455///
Nick Lewycky22ff7482010-04-12 05:08:25 +0000456bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
457 std::string &Error) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000458 // Test to see if the function is misoptimized if we ONLY run it on the
459 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000460 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner68bee932004-05-12 16:08:01 +0000461 if (!BBs.empty()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000462 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner68bee932004-05-12 16:08:01 +0000463 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000464 outs() << BBs[i]->getName() << " ";
465 if (BBs.size() > 10) outs() << "...";
Chris Lattner68bee932004-05-12 16:08:01 +0000466 } else {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000467 outs() << "blocks are extracted.";
Chris Lattner68bee932004-05-12 16:08:01 +0000468 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000469 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000470
471 // Split the module into the two halves of the program we want.
Devang Patele9916a32010-06-24 00:33:28 +0000472 ValueMap<const Value*, Value*> VMap;
Rafael Espindola115a9322010-07-29 14:20:59 +0000473 Module *Clone = CloneModule(BD.getProgram(), VMap);
474 Module *Orig = BD.swapProgramIn(Clone);
475 std::vector<Function*> FuncsOnClone;
476 std::vector<BasicBlock*> BBsOnClone;
477 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
478 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
479 FuncsOnClone.push_back(F);
480 }
481 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
482 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
483 BBsOnClone.push_back(BB);
484 }
485 VMap.clear();
486
Devang Patele9916a32010-06-24 00:33:28 +0000487 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000488 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Rafael Espindola115a9322010-07-29 14:20:59 +0000489 FuncsOnClone,
Devang Patele9916a32010-06-24 00:33:28 +0000490 VMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000491
492 // Try the extraction. If it doesn't work, then the block extractor crashed
493 // or something, in which case bugpoint can't chase down this possibility.
Rafael Espindola115a9322010-07-29 14:20:59 +0000494 if (Module *New = BD.ExtractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000495 delete ToOptimize;
Rafael Espindola115a9322010-07-29 14:20:59 +0000496 // Run the predicate,
497 // note that the predicate will delete both input modules.
498 bool Ret = TestFn(BD, New, ToNotOptimize, Error);
499 delete BD.swapProgramIn(Orig);
500 return Ret;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000501 }
Rafael Espindola115a9322010-07-29 14:20:59 +0000502 delete BD.swapProgramIn(Orig);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000503 delete ToOptimize;
504 delete ToNotOptimize;
505 return false;
506}
507
508
509/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
510/// extract as many basic blocks from the region as possible without obscuring
511/// the bug.
512///
513static bool ExtractBlocks(BugDriver &BD,
Nick Lewycky22ff7482010-04-12 05:08:25 +0000514 bool (*TestFn)(BugDriver &, Module *, Module *,
515 std::string &),
516 std::vector<Function*> &MiscompiledFunctions,
517 std::string &Error) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000518 if (BugpointIsInterrupted) return false;
519
Chris Lattner5e783ab2004-05-11 21:54:13 +0000520 std::vector<BasicBlock*> Blocks;
521 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
522 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
523 E = MiscompiledFunctions[i]->end(); I != E; ++I)
524 Blocks.push_back(I);
525
526 // Use the list reducer to identify blocks that can be extracted without
527 // obscuring the bug. The Blocks list will end up containing blocks that must
528 // be retained from the original program.
529 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000530
531 // Check to see if all blocks are extractible first.
Nick Lewycky22ff7482010-04-12 05:08:25 +0000532 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
533 .TestFuncs(std::vector<BasicBlock*>(), Error);
534 if (!Error.empty())
535 return false;
536 if (Ret) {
Chris Lattner68bee932004-05-12 16:08:01 +0000537 Blocks.clear();
538 } else {
Nick Lewycky22ff7482010-04-12 05:08:25 +0000539 ReduceMiscompiledBlocks(BD, TestFn,
540 MiscompiledFunctions).reduceList(Blocks, Error);
541 if (!Error.empty())
542 return false;
Chris Lattner68bee932004-05-12 16:08:01 +0000543 if (Blocks.size() == OldSize)
544 return false;
545 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000546
Devang Patele9916a32010-06-24 00:33:28 +0000547 ValueMap<const Value*, Value*> VMap;
548 Module *ProgClone = CloneModule(BD.getProgram(), VMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000549 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohmand50330c2009-04-22 15:57:18 +0000550 MiscompiledFunctions,
Devang Patele9916a32010-06-24 00:33:28 +0000551 VMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000552 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
553 if (Extracted == 0) {
Chris Lattnerda895d62005-02-27 06:18:25 +0000554 // Weird, extraction should have worked.
Dan Gohman65f57c22009-07-15 16:35:29 +0000555 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner2290e752004-05-12 02:43:24 +0000556 delete ProgClone;
557 delete ToExtract;
558 return false;
559 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000560
Chris Lattner2290e752004-05-12 02:43:24 +0000561 // Otherwise, block extraction succeeded. Link the two program fragments back
562 // together.
563 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000564
Chris Lattner90c18c52004-11-16 06:31:38 +0000565 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
566 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
567 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000568 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000569 MisCompFunctions.push_back(std::make_pair(I->getName(),
570 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000571
Chris Lattner2290e752004-05-12 02:43:24 +0000572 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000573 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000574 errs() << BD.getToolName() << ": Error linking modules together:"
575 << ErrorMsg << '\n';
Chris Lattner2290e752004-05-12 02:43:24 +0000576 exit(1);
577 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000578 delete Extracted;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000579
Chris Lattner2290e752004-05-12 02:43:24 +0000580 // Set the new program and delete the old one.
581 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000582
Chris Lattner2290e752004-05-12 02:43:24 +0000583 // Update the list of miscompiled functions.
584 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000585
Chris Lattner90c18c52004-11-16 06:31:38 +0000586 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000587 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattner90c18c52004-11-16 06:31:38 +0000588 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000589 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
590 "Function has wrong type??");
Chris Lattner90c18c52004-11-16 06:31:38 +0000591 MiscompiledFunctions.push_back(NewF);
592 }
Chris Lattner2290e752004-05-12 02:43:24 +0000593
594 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000595}
596
597
Chris Lattnerb15825b2004-04-05 21:37:38 +0000598/// DebugAMiscompilation - This is a generic driver to narrow down
599/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000600///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000601static std::vector<Function*>
602DebugAMiscompilation(BugDriver &BD,
Nick Lewycky22ff7482010-04-12 05:08:25 +0000603 bool (*TestFn)(BugDriver &, Module *, Module *,
604 std::string &),
605 std::string &Error) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000606 // Okay, now that we have reduced the list of passes which are causing the
607 // failure, see if we can pin down which functions are being
608 // miscompiled... first build a list of all of the non-external functions in
609 // the program.
610 std::vector<Function*> MiscompiledFunctions;
611 Module *Prog = BD.getProgram();
612 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000613 if (!I->isDeclaration())
Chris Lattnerb15825b2004-04-05 21:37:38 +0000614 MiscompiledFunctions.push_back(I);
615
616 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000617 if (!BugpointIsInterrupted)
Nick Lewycky22ff7482010-04-12 05:08:25 +0000618 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
619 Error);
620 if (!Error.empty())
621 return MiscompiledFunctions;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000622
Dan Gohmanac95cc72009-07-16 15:30:09 +0000623 outs() << "\n*** The following function"
624 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
625 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000626 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000627 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000628
629 // See if we can rip any loops out of the miscompiled functions and still
630 // trigger the problem.
Reid Spencerdc31a8a2006-11-11 19:05:02 +0000631
Nick Lewycky22ff7482010-04-12 05:08:25 +0000632 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
633 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
634 if (!Error.empty())
635 return MiscompiledFunctions;
636 if (Ret) {
637 // Okay, we extracted some loops and the problem still appears. See if
638 // we can eliminate some of the created functions from being candidates.
639 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattner36ee07f2004-04-11 23:52:35 +0000640
Nick Lewycky22ff7482010-04-12 05:08:25 +0000641 // Do the reduction...
642 if (!BugpointIsInterrupted)
643 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
644 Error);
645 if (!Error.empty())
646 return MiscompiledFunctions;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000647
Nick Lewycky22ff7482010-04-12 05:08:25 +0000648 outs() << "\n*** The following function"
649 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
650 << " being miscompiled: ";
651 PrintFunctionList(MiscompiledFunctions);
652 outs() << '\n';
653 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000654 }
655
Nick Lewycky22ff7482010-04-12 05:08:25 +0000656 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
657 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
658 if (!Error.empty())
659 return MiscompiledFunctions;
660 if (Ret) {
661 // Okay, we extracted some blocks and the problem still appears. See if
662 // we can eliminate some of the created functions from being candidates.
663 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattner5e783ab2004-05-11 21:54:13 +0000664
Nick Lewycky22ff7482010-04-12 05:08:25 +0000665 // Do the reduction...
666 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
667 Error);
668 if (!Error.empty())
669 return MiscompiledFunctions;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000670
Nick Lewycky22ff7482010-04-12 05:08:25 +0000671 outs() << "\n*** The following function"
672 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
673 << " being miscompiled: ";
674 PrintFunctionList(MiscompiledFunctions);
675 outs() << '\n';
676 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000677 }
678
Chris Lattnerb15825b2004-04-05 21:37:38 +0000679 return MiscompiledFunctions;
680}
681
Chris Lattnera57d86b2004-04-05 22:58:16 +0000682/// TestOptimizer - This is the predicate function used to check to see if the
683/// "Test" portion of the program is misoptimized. If so, return true. In any
684/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000685///
Nick Lewycky22ff7482010-04-12 05:08:25 +0000686static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
687 std::string &Error) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000688 // Run the optimization passes on ToOptimize, producing a transformed version
689 // of the functions being tested.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000690 outs() << " Optimizing functions being tested: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000691 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
692 /*AutoDebugCrashes*/true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000693 outs() << "done.\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000694 delete Test;
695
Dan Gohmanac95cc72009-07-16 15:30:09 +0000696 outs() << " Checking to see if the merged program executes correctly: ";
Nick Lewycky22ff7482010-04-12 05:08:25 +0000697 bool Broken = TestMergedProgram(BD, Optimized, Safe, true, Error);
698 if (Error.empty()) outs() << (Broken ? " nope.\n" : " yup.\n");
Chris Lattnerb15825b2004-04-05 21:37:38 +0000699 return Broken;
700}
701
702
Chris Lattner4a106452002-12-23 23:50:16 +0000703/// debugMiscompilation - This method is used when the passes selected are not
704/// crashing, but the generated output is semantically different from the
705/// input.
706///
Nick Lewycky22ff7482010-04-12 05:08:25 +0000707void BugDriver::debugMiscompilation(std::string *Error) {
Chris Lattner4a106452002-12-23 23:50:16 +0000708 // Make sure something was miscompiled...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000709 if (!BugpointIsInterrupted)
Nick Lewycky22ff7482010-04-12 05:08:25 +0000710 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
711 if (Error->empty())
712 errs() << "*** Optimized program matches reference output! No problem"
713 << " detected...\nbugpoint can't help you with your problem!\n";
714 return;
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000715 }
Chris Lattner4a106452002-12-23 23:50:16 +0000716
Dan Gohmanac95cc72009-07-16 15:30:09 +0000717 outs() << "\n*** Found miscompiling pass"
718 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
719 << getPassesString(getPassesToRun()) << '\n';
Rafael Espindolabae1b712010-07-28 18:12:30 +0000720 EmitProgressBitcode(Program, "passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000721
Nick Lewycky22ff7482010-04-12 05:08:25 +0000722 std::vector<Function *> MiscompiledFunctions =
723 DebugAMiscompilation(*this, TestOptimizer, *Error);
724 if (!Error->empty())
725 return;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000726
Gabor Greif8ff70c22007-07-04 21:55:50 +0000727 // Output a bunch of bitcode files for the user...
Dan Gohmanac95cc72009-07-16 15:30:09 +0000728 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Devang Patele9916a32010-06-24 00:33:28 +0000729 ValueMap<const Value*, Value*> VMap;
730 Module *ToNotOptimize = CloneModule(getProgram(), VMap);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000731 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000732 MiscompiledFunctions,
Devang Patele9916a32010-06-24 00:33:28 +0000733 VMap);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000734
Dan Gohmanac95cc72009-07-16 15:30:09 +0000735 outs() << " Non-optimized portion: ";
Rafael Espindolabae1b712010-07-28 18:12:30 +0000736 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
737 delete ToNotOptimize; // Delete hacked module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000738
Dan Gohmanac95cc72009-07-16 15:30:09 +0000739 outs() << " Portion that is input to optimizer: ";
Rafael Espindolabae1b712010-07-28 18:12:30 +0000740 EmitProgressBitcode(ToOptimize, "tooptimize");
741 delete ToOptimize; // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000742
Nick Lewycky22ff7482010-04-12 05:08:25 +0000743 return;
Chris Lattner4a106452002-12-23 23:50:16 +0000744}
Brian Gaeked0fde302003-11-11 22:41:34 +0000745
Chris Lattnera57d86b2004-04-05 22:58:16 +0000746/// CleanupAndPrepareModules - Get the specified modules ready for code
747/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000748///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000749static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
750 Module *Safe) {
751 // Clean up the modules, removing extra cruft that we don't need anymore...
752 Test = BD.performFinalCleanups(Test);
753
754 // If we are executing the JIT, we have several nasty issues to take care of.
755 if (!BD.isExecutingJIT()) return;
756
757 // First, if the main function is in the Safe module, we must add a stub to
758 // the Test module to call into it. Thus, we create a new function `main'
759 // which just calls the old one.
Reid Spencer688b0492007-02-05 21:19:13 +0000760 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5cbf9852007-01-30 20:08:39 +0000761 if (!oldMain->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000762 // Rename it
763 oldMain->setName("llvm_bugpoint_old_main");
764 // Create a NEW `main' function with same type in the test module.
Gabor Greif051a9502008-04-06 20:25:17 +0000765 Function *newMain = Function::Create(oldMain->getFunctionType(),
766 GlobalValue::ExternalLinkage,
767 "main", Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000768 // Create an `oldmain' prototype in the test module, which will
769 // corresponds to the real main function in the same module.
Gabor Greif051a9502008-04-06 20:25:17 +0000770 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
771 GlobalValue::ExternalLinkage,
772 oldMain->getName(), Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000773 // Set up and remember the argument list for the main function.
774 std::vector<Value*> args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000775 for (Function::arg_iterator
776 I = newMain->arg_begin(), E = newMain->arg_end(),
777 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +0000778 I->setName(OI->getName()); // Copy argument names from oldMain
Chris Lattnera57d86b2004-04-05 22:58:16 +0000779 args.push_back(I);
780 }
781
782 // Call the old main function and return its result
Owen Anderson1d0be152009-08-13 21:58:54 +0000783 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Gabor Greif051a9502008-04-06 20:25:17 +0000784 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
785 "", BB);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000786
Chris Lattnera57d86b2004-04-05 22:58:16 +0000787 // If the type of old function wasn't void, return value of call
Owen Anderson1d0be152009-08-13 21:58:54 +0000788 ReturnInst::Create(Safe->getContext(), call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000789 }
790
791 // The second nasty issue we must deal with in the JIT is that the Safe
792 // module cannot directly reference any functions defined in the test
793 // module. Instead, we use a JIT API call to dynamically resolve the
794 // symbol.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000795
Chris Lattnera57d86b2004-04-05 22:58:16 +0000796 // Add the resolver to the Safe module.
797 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner2db43c82007-01-07 08:13:39 +0000798 Constant *resolverFunc =
Chris Lattnera57d86b2004-04-05 22:58:16 +0000799 Safe->getOrInsertFunction("getPointerToNamedFunction",
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000800 Type::getInt8PtrTy(Safe->getContext()),
801 Type::getInt8PtrTy(Safe->getContext()),
Owen Anderson1d0be152009-08-13 21:58:54 +0000802 (Type *)0);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000803
Chris Lattnera57d86b2004-04-05 22:58:16 +0000804 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000805 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000806 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000807 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer688b0492007-02-05 21:19:13 +0000808 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000809
810 // Don't forward functions which are external in the test module too.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000811 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000812 // 1. Add a string constant with its name to the global file
Owen Anderson1d0be152009-08-13 21:58:54 +0000813 Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000814 GlobalVariable *funcName =
Owen Andersone9b11b42009-07-08 19:03:57 +0000815 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman3da94ae2005-04-22 00:00:37 +0000816 GlobalValue::InternalLinkage, InitArray,
Owen Andersone9b11b42009-07-08 19:03:57 +0000817 F->getName() + "_name");
Chris Lattnera57d86b2004-04-05 22:58:16 +0000818
819 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
820 // sbyte* so it matches the signature of the resolver function.
821
822 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson1d0be152009-08-13 21:58:54 +0000823 std::vector<Constant*> GEPargs(2,
824 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000825 Value *GEP =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000826 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000827 std::vector<Value*> ResolverArgs;
828 ResolverArgs.push_back(GEP);
829
Misha Brukmande4803d2004-04-19 03:36:47 +0000830 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
831 // function that dynamically resolves the calls to F via our JIT API
Chris Lattnera3efca12005-07-12 01:00:32 +0000832 if (!F->use_empty()) {
833 // Create a new global to hold the cached function pointer.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000834 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Chris Lattnera3efca12005-07-12 01:00:32 +0000835 GlobalVariable *Cache =
Owen Andersone9b11b42009-07-08 19:03:57 +0000836 new GlobalVariable(*F->getParent(), F->getType(),
837 false, GlobalValue::InternalLinkage,
838 NullPtr,F->getName()+".fpcache");
Jeff Cohen00b168892005-07-27 06:12:32 +0000839
Misha Brukmande4803d2004-04-19 03:36:47 +0000840 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000841 const FunctionType *FuncTy = F->getFunctionType();
Gabor Greif051a9502008-04-06 20:25:17 +0000842 Function *FuncWrapper = Function::Create(FuncTy,
843 GlobalValue::InternalLinkage,
844 F->getName() + "_wrapper",
845 F->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +0000846 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
847 "entry", FuncWrapper);
848 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
849 "usecache", FuncWrapper);
850 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
851 "lookupfp", FuncWrapper);
Jeff Cohen00b168892005-07-27 06:12:32 +0000852
Chris Lattnera3efca12005-07-12 01:00:32 +0000853 // Check to see if we already looked up the value.
854 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson333c4002009-07-09 23:48:35 +0000855 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
856 NullPtr, "isNull");
Gabor Greif051a9502008-04-06 20:25:17 +0000857 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000858
Misha Brukmande4803d2004-04-19 03:36:47 +0000859 // Resolve the call to function F via the JIT API:
860 //
861 // call resolver(GetElementPtr...)
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000862 CallInst *Resolver =
863 CallInst::Create(resolverFunc, ResolverArgs.begin(),
864 ResolverArgs.end(), "resolver", LookupBB);
865
866 // Cast the result from the resolver to correctly-typed function.
867 CastInst *CastedResolver =
868 new BitCastInst(Resolver,
Owen Andersondebcb012009-07-29 22:17:13 +0000869 PointerType::getUnqual(F->getFunctionType()),
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000870 "resolverCast", LookupBB);
Reid Spencer3da59db2006-11-27 01:05:10 +0000871
Chris Lattnera3efca12005-07-12 01:00:32 +0000872 // Save the value in our cache.
873 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greif051a9502008-04-06 20:25:17 +0000874 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000875
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000876 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
877 "fp", DoCallBB);
Chris Lattnera3efca12005-07-12 01:00:32 +0000878 FuncPtr->addIncoming(CastedResolver, LookupBB);
879 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000880
Chris Lattnera3efca12005-07-12 01:00:32 +0000881 // Save the argument list.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000882 std::vector<Value*> Args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000883 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
884 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukmandc7fef82004-04-19 01:12:01 +0000885 Args.push_back(i);
886
887 // Pass on the arguments to the real function, return its result
Dan Gohmane49a13e2010-06-07 20:19:26 +0000888 if (F->getReturnType()->isVoidTy()) {
Gabor Greif051a9502008-04-06 20:25:17 +0000889 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000890 ReturnInst::Create(F->getContext(), DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000891 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000892 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
893 "retval", DoCallBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000894 ReturnInst::Create(F->getContext(),Call, DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000895 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000896
Misha Brukmande4803d2004-04-19 03:36:47 +0000897 // Use the wrapper function instead of the old function
898 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000899 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000900 }
901 }
902 }
903
904 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000905 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000906 abort();
907 }
908}
909
910
911
912/// TestCodeGenerator - This is the predicate function used to check to see if
913/// the "Test" portion of the program is miscompiled by the code generator under
914/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000915///
Nick Lewycky22ff7482010-04-12 05:08:25 +0000916static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
917 std::string &Error) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000918 CleanupAndPrepareModules(BD, Test, Safe);
919
Reid Spencer97182982004-12-15 01:53:08 +0000920 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000921 std::string ErrMsg;
922 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000923 errs() << BD.getToolName() << "Error making unique filename: "
924 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000925 exit(1);
926 }
Chris Lattner74382b72009-08-23 22:45:37 +0000927 if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
928 errs() << "Error writing bitcode to `" << TestModuleBC.str()
929 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000930 exit(1);
931 }
932 delete Test;
933
Rafael Espindolabc2ed592010-06-21 02:17:36 +0000934 FileRemover TestModuleBCRemover(TestModuleBC, !SaveTemps);
935
Chris Lattnera57d86b2004-04-05 22:58:16 +0000936 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000937 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000938 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000939 errs() << BD.getToolName() << "Error making unique filename: "
940 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000941 exit(1);
942 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000943
Chris Lattner74382b72009-08-23 22:45:37 +0000944 if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
945 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
946 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000947 exit(1);
948 }
Rafael Espindolabc2ed592010-06-21 02:17:36 +0000949
950 FileRemover SafeModuleBCRemover(SafeModuleBC, !SaveTemps);
951
Nick Lewycky22ff7482010-04-12 05:08:25 +0000952 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
953 if (!Error.empty())
Benjamin Kramer27063872010-04-12 12:22:19 +0000954 return false;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000955 delete Safe;
956
Rafael Espindolabc2ed592010-06-21 02:17:36 +0000957 FileRemover SharedObjectRemover(sys::Path(SharedObject), !SaveTemps);
958
Chris Lattnera57d86b2004-04-05 22:58:16 +0000959 // Run the code generator on the `Test' code, loading the shared library.
960 // The function returns whether or not the new output differs from reference.
Nick Lewycky22ff7482010-04-12 05:08:25 +0000961 bool Result = BD.diffProgram(TestModuleBC.str(), SharedObject, false, &Error);
962 if (!Error.empty())
963 return false;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000964
965 if (Result)
Dan Gohman65f57c22009-07-15 16:35:29 +0000966 errs() << ": still failing!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000967 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000968 errs() << ": didn't fail.\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000969
970 return Result;
971}
972
973
Misha Brukman8c194ea2004-04-21 18:36:43 +0000974/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
975///
Nick Lewycky22ff7482010-04-12 05:08:25 +0000976bool BugDriver::debugCodeGenerator(std::string *Error) {
Dan Gohman70ef4492008-12-08 04:02:47 +0000977 if ((void*)SafeInterpreter == (void*)Interpreter) {
Nick Lewycky22ff7482010-04-12 05:08:25 +0000978 std::string Result = executeProgramSafely("bugpoint.safe.out", Error);
979 if (Error->empty()) {
980 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
981 << "the reference diff. This may be due to a\n front-end "
982 << "bug or a bug in the original program, but this can also "
983 << "happen if bugpoint isn't running the program with the "
984 << "right flags or input.\n I left the result of executing "
985 << "the program with the \"safe\" backend in this file for "
986 << "you: '"
987 << Result << "'.\n";
988 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000989 return true;
990 }
991
992 DisambiguateGlobalSymbols(Program);
993
Nick Lewycky22ff7482010-04-12 05:08:25 +0000994 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
995 *Error);
996 if (!Error->empty())
997 return true;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000998
999 // Split the module into the two halves of the program we want.
Devang Patele9916a32010-06-24 00:33:28 +00001000 ValueMap<const Value*, Value*> VMap;
1001 Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1002 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
Chris Lattnera57d86b2004-04-05 22:58:16 +00001003
1004 // Condition the modules
1005 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1006
Reid Spencer97182982004-12-15 01:53:08 +00001007 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +00001008 std::string ErrMsg;
1009 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +00001010 errs() << getToolName() << "Error making unique filename: "
1011 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +00001012 exit(1);
1013 }
Reid Spencer97182982004-12-15 01:53:08 +00001014
Chris Lattner74382b72009-08-23 22:45:37 +00001015 if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
1016 errs() << "Error writing bitcode to `" << TestModuleBC.str()
1017 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001018 exit(1);
1019 }
1020 delete ToCodeGen;
1021
1022 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +00001023 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +00001024 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +00001025 errs() << getToolName() << "Error making unique filename: "
1026 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +00001027 exit(1);
1028 }
Reid Spencer97182982004-12-15 01:53:08 +00001029
Chris Lattner74382b72009-08-23 22:45:37 +00001030 if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
1031 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
1032 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001033 exit(1);
1034 }
Nick Lewycky22ff7482010-04-12 05:08:25 +00001035 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1036 if (!Error->empty())
1037 return true;
Chris Lattnera57d86b2004-04-05 22:58:16 +00001038 delete ToNotCodeGen;
1039
Dan Gohmanac95cc72009-07-16 15:30:09 +00001040 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001041 if (isExecutingJIT()) {
Chris Lattner74382b72009-08-23 22:45:37 +00001042 outs() << " lli -load " << SharedObject << " " << TestModuleBC.str();
Chris Lattnera57d86b2004-04-05 22:58:16 +00001043 } else {
Nick Lewycky8d0e1bc2010-04-29 23:37:44 +00001044 outs() << " llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
Chris Lattner74382b72009-08-23 22:45:37 +00001045 << ".s\n";
1046 outs() << " gcc " << SharedObject << " " << TestModuleBC.str()
1047 << ".s -o " << TestModuleBC.str() << ".exe";
Chris Lattner59615f02005-01-15 00:07:19 +00001048#if defined (HAVE_LINK_R)
Dan Gohmanac95cc72009-07-16 15:30:09 +00001049 outs() << " -Wl,-R.";
Chris Lattner59615f02005-01-15 00:07:19 +00001050#endif
Dan Gohmanac95cc72009-07-16 15:30:09 +00001051 outs() << "\n";
Chris Lattner74382b72009-08-23 22:45:37 +00001052 outs() << " " << TestModuleBC.str() << ".exe";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001053 }
Nick Lewycky22ff7482010-04-12 05:08:25 +00001054 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +00001055 outs() << " " << InputArgv[i];
1056 outs() << '\n';
1057 outs() << "The shared object was created with:\n llc -march=c "
Chris Lattner74382b72009-08-23 22:45:37 +00001058 << SafeModuleBC.str() << " -o temporary.c\n"
Daniel Dunbarca740962009-08-18 03:35:57 +00001059 << " gcc -xc temporary.c -O2 -o " << SharedObject;
1060 if (TargetTriple.getArch() == Triple::sparc)
1061 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1062 else
1063 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1064
1065 outs() << " -fno-strict-aliasing\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001066
1067 return false;
1068}