For PR351:
[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 #include "BugDriver.h"
19 #include "llvm/Module.h"
20 #include "llvm/PassManager.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Bytecode/WriteBytecodePass.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/FileUtilities.h"
25 #include "llvm/System/Path.h"
26 #include <fstream>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 using namespace llvm;
31
32 /// writeProgramToFile - This writes the current "Program" to the named bytecode
33 /// file.  If an error occurs, true is returned.
34 ///
35 bool BugDriver::writeProgramToFile(const std::string &Filename,
36                                    Module *M) const {
37   std::ofstream Out(Filename.c_str());
38   if (!Out.good()) return true;
39   WriteBytecodeToFile(M ? M : Program, Out, /*compression=*/true);
40   return false;
41 }
42
43
44 /// EmitProgressBytecode - This function is used to output the current Program
45 /// to a file named "bugpoint-ID.bc".
46 ///
47 void BugDriver::EmitProgressBytecode(const std::string &ID, bool NoFlyer) {
48   // Output the input to the current pass to a bytecode file, emit a message
49   // telling the user how to reproduce it: opt -foo blah.bc
50   //
51   std::string Filename = "bugpoint-" + ID + ".bc";
52   if (writeProgramToFile(Filename)) {
53     std::cerr <<  "Error opening file '" << Filename << "' for writing!\n";
54     return;
55   }
56
57   std::cout << "Emitted bytecode to '" << Filename << "'\n";
58   if (NoFlyer || PassesToRun.empty()) return;
59   std::cout << "\n*** You can reproduce the problem with: ";
60
61   unsigned PassType = PassesToRun[0]->getPassType();
62   for (unsigned i = 1, e = PassesToRun.size(); i != e; ++i)
63     PassType &= PassesToRun[i]->getPassType();
64
65   if (PassType & PassInfo::Analysis)
66     std::cout << "analyze";
67   else if (PassType & PassInfo::Optimization)
68     std::cout << "opt";
69   else if (PassType & PassInfo::LLC)
70     std::cout << "llc";
71   else
72     std::cout << "bugpoint";
73   std::cout << " " << Filename << " ";
74   std::cout << getPassesString(PassesToRun) << "\n";
75 }
76
77 static void RunChild(Module *Program,const std::vector<const PassInfo*> &Passes,
78                      const std::string &OutFilename) {
79   std::ofstream OutFile(OutFilename.c_str());
80   if (!OutFile.good()) {
81     std::cerr << "Error opening bytecode file: " << OutFilename << "\n";
82     exit(1);
83   }
84
85   PassManager PM;
86   // Make sure that the appropriate target data is always used...
87   PM.add(new TargetData("bugpoint", Program));
88
89   for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
90     if (Passes[i]->getNormalCtor())
91       PM.add(Passes[i]->getNormalCtor()());
92     else
93       std::cerr << "Cannot create pass yet: " << Passes[i]->getPassName()
94                 << "\n";
95   }
96   // Check that the module is well formed on completion of optimization
97   PM.add(createVerifierPass());
98
99   // Write bytecode out to disk as the last step...
100   PM.add(new WriteBytecodePass(&OutFile));
101
102   // Run all queued passes.
103   PM.run(*Program);
104 }
105
106 /// runPasses - Run the specified passes on Program, outputting a bytecode file
107 /// and writing the filename into OutputFile if successful.  If the
108 /// optimizations fail for some reason (optimizer crashes), return true,
109 /// otherwise return false.  If DeleteOutput is set to true, the bytecode is
110 /// deleted on success, and the filename string is undefined.  This prints to
111 /// cout a single line message indicating whether compilation was successful or
112 /// failed.
113 ///
114 bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
115                           std::string &OutputFilename, bool DeleteOutput,
116                           bool Quiet) const{
117   std::cout << std::flush;
118   sys::Path uniqueFilename("bugpoint-output.bc");
119   uniqueFilename.makeUnique();
120   OutputFilename = uniqueFilename.toString();
121
122   pid_t child_pid;
123   switch (child_pid = fork()) {
124   case -1:    // Error occurred
125     std::cerr << ToolName << ": Error forking!\n";
126     exit(1);
127   case 0:     // Child process runs passes.
128     RunChild(Program, Passes, OutputFilename);
129     exit(0);  // If we finish successfully, return 0!
130   default:    // Parent continues...
131     break;
132   }
133
134   // Wait for the child process to get done.
135   int Status;
136   if (wait(&Status) != child_pid) {
137     std::cerr << "Error waiting for child process!\n";
138     exit(1);
139   }
140
141   bool ExitedOK = WIFEXITED(Status) && WEXITSTATUS(Status) == 0;
142
143   // If we are supposed to delete the bytecode file or if the passes crashed,
144   // remove it now.  This may fail if the file was never created, but that's ok.
145   if (DeleteOutput || !ExitedOK)
146     removeFile(OutputFilename);
147   
148   if (!Quiet) {
149     if (ExitedOK)
150       std::cout << "Success!\n";
151     else if (WIFEXITED(Status))
152       std::cout << "Exited with error code '" << WEXITSTATUS(Status) << "'\n";
153     else if (WIFSIGNALED(Status))
154       std::cout << "Crashed with signal #" << WTERMSIG(Status) << "\n";
155 #ifdef WCOREDUMP
156     else if (WCOREDUMP(Status))
157       std::cout << "Dumped core\n";
158 #endif
159     else
160       std::cout << "Failed for unknown reason!\n";
161   }
162
163   // Was the child successful?
164   return !ExitedOK;
165 }
166
167
168 /// runPassesOn - Carefully run the specified set of pass on the specified
169 /// module, returning the transformed module on success, or a null pointer on
170 /// failure.
171 Module *BugDriver::runPassesOn(Module *M,
172                                const std::vector<const PassInfo*> &Passes,
173                                bool AutoDebugCrashes) {
174   Module *OldProgram = swapProgramIn(M);
175   std::string BytecodeResult;
176   if (runPasses(Passes, BytecodeResult, false/*delete*/, true/*quiet*/)) {
177     if (AutoDebugCrashes) {
178       std::cerr << " Error running this sequence of passes" 
179                 << " on the input program!\n";
180       delete OldProgram;
181       EmitProgressBytecode("pass-error",  false);
182       exit(debugOptimizerCrash());
183     }
184     swapProgramIn(OldProgram);
185     return 0;
186   }
187
188   // Restore the current program.
189   swapProgramIn(OldProgram);
190
191   Module *Ret = ParseInputFile(BytecodeResult);
192   if (Ret == 0) {
193     std::cerr << getToolName() << ": Error reading bytecode file '"
194               << BytecodeResult << "'!\n";
195     exit(1);
196   }
197   removeFile(BytecodeResult);  // No longer need the file on disk
198   return Ret;
199 }