Don't include <stdlib.h>.
[oota-llvm.git] / tools / bugpoint / OptimizerDriver.cpp
1 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
2 //
3 // This file defines an interface that allows bugpoint to run various passes
4 // without the threat of a buggy pass corrupting bugpoint (of course, bugpoint
5 // may have its own bugs, but that's another story...).  It achieves this by
6 // forking a copy of itself and having the child process do the optimizations.
7 // If this client dies, we can always fork a new one.  :)
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "BugDriver.h"
12 #include "llvm/PassManager.h"
13 #include "llvm/Analysis/Verifier.h"
14 #include "llvm/Bytecode/WriteBytecodePass.h"
15 #include "llvm/Target/TargetData.h"
16 #include "Support/FileUtilities.h"
17 #include <fstream>
18 #include <unistd.h>
19 #include <sys/types.h>
20 #include <sys/wait.h>
21
22 /// writeProgramToFile - This writes the current "Program" to the named bytecode
23 /// file.  If an error occurs, true is returned.
24 ///
25 bool BugDriver::writeProgramToFile(const std::string &Filename,
26                                    Module *M) const {
27   std::ofstream Out(Filename.c_str());
28   if (!Out.good()) return true;
29   WriteBytecodeToFile(M ? M : Program, Out);
30   return false;
31 }
32
33
34 /// EmitProgressBytecode - This function is used to output the current Program
35 /// to a file named "bugpoint-ID.bc".
36 ///
37 void BugDriver::EmitProgressBytecode(const std::string &ID, bool NoFlyer) {
38   // Output the input to the current pass to a bytecode file, emit a message
39   // telling the user how to reproduce it: opt -foo blah.bc
40   //
41   std::string Filename = "bugpoint-" + ID + ".bc";
42   if (writeProgramToFile(Filename)) {
43     std::cerr <<  "Error opening file '" << Filename << "' for writing!\n";
44     return;
45   }
46
47   std::cout << "Emitted bytecode to '" << Filename << "'\n";
48   if (NoFlyer) return;
49   std::cout << "\n*** You can reproduce the problem with: ";
50
51   unsigned PassType = PassesToRun[0]->getPassType();
52   for (unsigned i = 1, e = PassesToRun.size(); i != e; ++i)
53     PassType &= PassesToRun[i]->getPassType();
54
55   if (PassType & PassInfo::Analysis)
56     std::cout << "analyze";
57   else if (PassType & PassInfo::Optimization)
58     std::cout << "opt";
59   else if (PassType & PassInfo::LLC)
60     std::cout << "llc";
61   else
62     std::cout << "bugpoint";
63   std::cout << " " << Filename << " ";
64   std::cout << getPassesString(PassesToRun) << "\n";
65 }
66
67 static void RunChild(Module *Program,const std::vector<const PassInfo*> &Passes,
68                      const std::string &OutFilename) {
69   std::ofstream OutFile(OutFilename.c_str());
70   if (!OutFile.good()) {
71     std::cerr << "Error opening bytecode file: " << OutFilename << "\n";
72     exit(1);
73   }
74
75   PassManager PM;
76   // Make sure that the appropriate target data is always used...
77   PM.add(new TargetData("bugpoint", Program));
78
79   for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
80     if (Passes[i]->getNormalCtor())
81       PM.add(Passes[i]->getNormalCtor()());
82     else
83       std::cerr << "Cannot create pass yet: " << Passes[i]->getPassName()
84                 << "\n";
85   }
86   // Check that the module is well formed on completion of optimization
87   PM.add(createVerifierPass());
88
89   // Write bytecode out to disk as the last step...
90   PM.add(new WriteBytecodePass(&OutFile));
91
92   // Run all queued passes.
93   PM.run(*Program);
94 }
95
96 /// runPasses - Run the specified passes on Program, outputting a bytecode file
97 /// and writing the filename into OutputFile if successful.  If the
98 /// optimizations fail for some reason (optimizer crashes), return true,
99 /// otherwise return false.  If DeleteOutput is set to true, the bytecode is
100 /// deleted on success, and the filename string is undefined.  This prints to
101 /// cout a single line message indicating whether compilation was successful or
102 /// failed.
103 ///
104 bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
105                           std::string &OutputFilename, bool DeleteOutput,
106                           bool Quiet) const{
107   std::cout << std::flush;
108   OutputFilename = getUniqueFilename("bugpoint-output.bc");
109
110   pid_t child_pid;
111   switch (child_pid = fork()) {
112   case -1:    // Error occurred
113     std::cerr << ToolName << ": Error forking!\n";
114     exit(1);
115   case 0:     // Child process runs passes.
116     RunChild(Program, Passes, OutputFilename);
117     exit(0);  // If we finish successfully, return 0!
118   default:    // Parent continues...
119     break;
120   }
121
122   // Wait for the child process to get done.
123   int Status;
124   if (wait(&Status) != child_pid) {
125     std::cerr << "Error waiting for child process!\n";
126     exit(1);
127   }
128
129   // If we are supposed to delete the bytecode file, remove it now
130   // unconditionally...  this may fail if the file was never created, but that's
131   // ok.
132   if (DeleteOutput)
133     removeFile(OutputFilename);
134
135   bool ExitedOK = WIFEXITED(Status) && WEXITSTATUS(Status) == 0;
136   
137   if (!Quiet) {
138     if (ExitedOK)
139       std::cout << "Success!\n";
140     else if (WIFEXITED(Status))
141       std::cout << "Exited with error code '" << WEXITSTATUS(Status) << "'\n";
142     else if (WIFSIGNALED(Status))
143       std::cout << "Crashed with signal #" << WTERMSIG(Status) << "\n";
144 #ifdef WCOREDUMP
145     else if (WCOREDUMP(Status))
146       std::cout << "Dumped core\n";
147 #endif
148     else
149       std::cout << "Failed for unknown reason!\n";
150   }
151
152   // Was the child successful?
153   return !ExitedOK;
154 }