Use binary mode for reading/writing bytecode files
[oota-llvm.git] / tools / bugpoint / OptimizerDriver.cpp
1 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an interface that allows bugpoint to run various passes
11 // without the threat of a buggy pass corrupting bugpoint (of course, bugpoint
12 // may have its own bugs, but that's another story...).  It achieves this by
13 // forking a copy of itself and having the child process do the optimizations.
14 // If this client dies, we can always fork a new one.  :)
15 //
16 //===----------------------------------------------------------------------===//
17
18 // Note: as a short term hack, the old Unix-specific code and platform-
19 // independent code co-exist via conditional compilation until it is verified
20 // that the new code works correctly on Unix.
21
22 #define PLATFORMINDEPENDENT
23
24 #include "BugDriver.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Analysis/Verifier.h"
28 #include "llvm/Bytecode/WriteBytecodePass.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Support/FileUtilities.h"
31 #include "llvm/System/Path.h"
32 #include <fstream>
33 #ifndef PLATFORMINDEPENDENT
34 #include <unistd.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #endif
38 using namespace llvm;
39
40 /// writeProgramToFile - This writes the current "Program" to the named bytecode
41 /// file.  If an error occurs, true is returned.
42 ///
43 bool BugDriver::writeProgramToFile(const std::string &Filename,
44                                    Module *M) const {
45   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
46                                std::ios::binary;
47   std::ofstream Out(Filename.c_str(), io_mode);
48   if (!Out.good()) return true;
49   WriteBytecodeToFile(M ? M : Program, Out, /*compression=*/true);
50   return false;
51 }
52
53
54 /// EmitProgressBytecode - This function is used to output the current Program
55 /// to a file named "bugpoint-ID.bc".
56 ///
57 void BugDriver::EmitProgressBytecode(const std::string &ID, bool NoFlyer) {
58   // Output the input to the current pass to a bytecode file, emit a message
59   // telling the user how to reproduce it: opt -foo blah.bc
60   //
61   std::string Filename = "bugpoint-" + ID + ".bc";
62   if (writeProgramToFile(Filename)) {
63     std::cerr <<  "Error opening file '" << Filename << "' for writing!\n";
64     return;
65   }
66
67   std::cout << "Emitted bytecode to '" << Filename << "'\n";
68   if (NoFlyer || PassesToRun.empty()) return;
69   std::cout << "\n*** You can reproduce the problem with: ";
70
71   unsigned PassType = PassesToRun[0]->getPassType();
72   for (unsigned i = 1, e = PassesToRun.size(); i != e; ++i)
73     PassType &= PassesToRun[i]->getPassType();
74
75   if (PassType & PassInfo::Analysis)
76     std::cout << "analyze";
77   else if (PassType & PassInfo::Optimization)
78     std::cout << "opt";
79   else if (PassType & PassInfo::LLC)
80     std::cout << "llc";
81   else
82     std::cout << "bugpoint";
83   std::cout << " " << Filename << " ";
84   std::cout << getPassesString(PassesToRun) << "\n";
85 }
86
87 static void RunChild(Module *Program,const std::vector<const PassInfo*> &Passes,
88                      const std::string &OutFilename) {
89   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
90                                std::ios::binary;
91   std::ofstream OutFile(OutFilename.c_str(), io_mode);
92   if (!OutFile.good()) {
93     std::cerr << "Error opening bytecode file: " << OutFilename << "\n";
94     exit(1);
95   }
96
97   PassManager PM;
98   // Make sure that the appropriate target data is always used...
99   PM.add(new TargetData("bugpoint", Program));
100
101   for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
102     if (Passes[i]->getNormalCtor())
103       PM.add(Passes[i]->getNormalCtor()());
104     else
105       std::cerr << "Cannot create pass yet: " << Passes[i]->getPassName()
106                 << "\n";
107   }
108   // Check that the module is well formed on completion of optimization
109   PM.add(createVerifierPass());
110
111   // Write bytecode out to disk as the last step...
112   PM.add(new WriteBytecodePass(&OutFile));
113
114   // Run all queued passes.
115   PM.run(*Program);
116 }
117
118 /// runPasses - Run the specified passes on Program, outputting a bytecode file
119 /// and writing the filename into OutputFile if successful.  If the
120 /// optimizations fail for some reason (optimizer crashes), return true,
121 /// otherwise return false.  If DeleteOutput is set to true, the bytecode is
122 /// deleted on success, and the filename string is undefined.  This prints to
123 /// cout a single line message indicating whether compilation was successful or
124 /// failed.
125 ///
126 bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
127                           std::string &OutputFilename, bool DeleteOutput,
128                           bool Quiet) const{
129   std::cout << std::flush;
130   sys::Path uniqueFilename("bugpoint-output.bc");
131   uniqueFilename.makeUnique();
132   OutputFilename = uniqueFilename.toString();
133
134 #ifndef PLATFORMINDEPENDENT
135   pid_t child_pid;
136   switch (child_pid = fork()) {
137   case -1:    // Error occurred
138     std::cerr << ToolName << ": Error forking!\n";
139     exit(1);
140   case 0:     // Child process runs passes.
141     RunChild(Program, Passes, OutputFilename);
142     exit(0);  // If we finish successfully, return 0!
143   default:    // Parent continues...
144     break;
145   }
146
147   // Wait for the child process to get done.
148   int Status;
149   if (wait(&Status) != child_pid) {
150     std::cerr << "Error waiting for child process!\n";
151     exit(1);
152   }
153
154   bool ExitedOK = WIFEXITED(Status) && WEXITSTATUS(Status) == 0;
155 #else
156   bool ExitedOK = false;
157 #endif
158
159   // If we are supposed to delete the bytecode file or if the passes crashed,
160   // remove it now.  This may fail if the file was never created, but that's ok.
161   if (DeleteOutput || !ExitedOK)
162     sys::Path(OutputFilename).destroyFile();
163
164 #ifndef PLATFORMINDEPENDENT
165   if (!Quiet) {
166     if (ExitedOK)
167       std::cout << "Success!\n";
168     else if (WIFEXITED(Status))
169       std::cout << "Exited with error code '" << WEXITSTATUS(Status) << "'\n";
170     else if (WIFSIGNALED(Status))
171       std::cout << "Crashed with signal #" << WTERMSIG(Status) << "\n";
172 #ifdef WCOREDUMP
173     else if (WCOREDUMP(Status))
174       std::cout << "Dumped core\n";
175 #endif
176     else
177       std::cout << "Failed for unknown reason!\n";
178   }
179 #endif
180
181   // Was the child successful?
182   return !ExitedOK;
183 }
184
185
186 /// runPassesOn - Carefully run the specified set of pass on the specified
187 /// module, returning the transformed module on success, or a null pointer on
188 /// failure.
189 Module *BugDriver::runPassesOn(Module *M,
190                                const std::vector<const PassInfo*> &Passes,
191                                bool AutoDebugCrashes) {
192   Module *OldProgram = swapProgramIn(M);
193   std::string BytecodeResult;
194   if (runPasses(Passes, BytecodeResult, false/*delete*/, true/*quiet*/)) {
195     if (AutoDebugCrashes) {
196       std::cerr << " Error running this sequence of passes" 
197                 << " on the input program!\n";
198       delete OldProgram;
199       EmitProgressBytecode("pass-error",  false);
200       exit(debugOptimizerCrash());
201     }
202     swapProgramIn(OldProgram);
203     return 0;
204   }
205
206   // Restore the current program.
207   swapProgramIn(OldProgram);
208
209   Module *Ret = ParseInputFile(BytecodeResult);
210   if (Ret == 0) {
211     std::cerr << getToolName() << ": Error reading bytecode file '"
212               << BytecodeResult << "'!\n";
213     exit(1);
214   }
215   sys::Path(BytecodeResult).destroyFile();  // No longer need the file on disk
216   return Ret;
217 }