1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Module.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/Bytecode/Reader.h"
18 #include "llvm/Bytecode/WriteBytecodePass.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/PassNameParser.h"
24 #include "llvm/System/Signals.h"
25 #include "llvm/Support/PluginLoader.h"
26 #include "llvm/Support/Streams.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/LinkAllPasses.h"
30 #include "llvm/LinkAllVMCore.h"
37 // The OptimizationList is automatically populated with registered Passes by the
40 static cl::list<const PassInfo*, bool, PassNameParser>
41 PassList(cl::desc("Optimizations available:"));
43 static cl::opt<bool> NoCompress("disable-compression", cl::init(false),
44 cl::desc("Don't compress the generated bytecode"));
46 // Other command line options...
48 static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input bytecode file>"),
50 cl::init("-"), cl::value_desc("filename"));
52 static cl::opt<std::string>
53 OutputFilename("o", cl::desc("Override output filename"),
54 cl::value_desc("filename"), cl::init("-"));
57 Force("f", cl::desc("Overwrite output files"));
60 PrintEachXForm("p", cl::desc("Print module after each transformation"));
63 NoOutput("disable-output",
64 cl::desc("Do not write result bytecode file"), cl::Hidden);
67 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
70 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
73 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
76 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
78 static Timer BytecodeLoadTimer("Bytecode Loader");
80 // ---------- Define Printers for module and function passes ------------
83 struct ModulePassPrinter : public ModulePass {
84 const PassInfo *PassToPrint;
85 ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
87 virtual bool runOnModule(Module &M) {
89 llvm_cout << "Printing analysis '" << PassToPrint->getPassName()
91 getAnalysisID<Pass>(PassToPrint).print(llvm_cout, &M);
94 // Get and print pass...
98 virtual const char *getPassName() const { return "'Pass' Printer"; }
100 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.addRequiredID(PassToPrint);
102 AU.setPreservesAll();
106 struct FunctionPassPrinter : public FunctionPass {
107 const PassInfo *PassToPrint;
108 FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
110 virtual bool runOnFunction(Function &F) {
112 llvm_cout << "Printing analysis '" << PassToPrint->getPassName()
113 << "' for function '" << F.getName() << "':\n";
115 // Get and print pass...
116 getAnalysisID<Pass>(PassToPrint).print(llvm_cout, F.getParent());
120 virtual const char *getPassName() const { return "FunctionPass Printer"; }
122 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
123 AU.addRequiredID(PassToPrint);
124 AU.setPreservesAll();
128 struct BasicBlockPassPrinter : public BasicBlockPass {
129 const PassInfo *PassToPrint;
130 BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
132 virtual bool runOnBasicBlock(BasicBlock &BB) {
134 llvm_cout << "Printing Analysis info for BasicBlock '" << BB.getName()
135 << "': Pass " << PassToPrint->getPassName() << ":\n";
138 // Get and print pass...
139 getAnalysisID<Pass>(PassToPrint).print(
140 llvm_cout, BB.getParent()->getParent());
144 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
146 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
147 AU.addRequiredID(PassToPrint);
148 AU.setPreservesAll();
152 } // anonymous namespace
155 //===----------------------------------------------------------------------===//
158 int main(int argc, char **argv) {
160 cl::ParseCommandLineOptions(argc, argv,
161 " llvm .bc -> .bc modular optimizer and analysis printer \n");
162 sys::PrintStackTraceOnErrorSignal();
164 // Allocate a full target machine description only if necessary.
165 // FIXME: The choice of target should be controllable on the command line.
166 std::auto_ptr<TargetMachine> target;
168 std::string ErrorMessage;
170 // Load the input module...
171 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
173 llvm_cerr << argv[0] << ": ";
174 if (ErrorMessage.size())
175 llvm_cerr << ErrorMessage << "\n";
177 llvm_cerr << "bytecode didn't read correctly.\n";
181 // Figure out what stream we are supposed to write to...
182 // FIXME: cout is not binary!
183 std::ostream *Out = &std::cout; // Default to printing to stdout...
184 if (OutputFilename != "-") {
185 if (!Force && std::ifstream(OutputFilename.c_str())) {
186 // If force is not specified, make sure not to overwrite a file!
187 llvm_cerr << argv[0] << ": error opening '" << OutputFilename
188 << "': file exists!\n"
189 << "Use -f command line argument to force output\n";
192 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
194 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
197 llvm_cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
201 // Make sure that the Output file gets unlinked from the disk if we get a
203 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
206 // If the output is set to be emitted to standard out, and standard out is a
207 // console, print out a warning message and refuse to do it. We don't
208 // impress anyone by spewing tons of binary goo to a terminal.
209 if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
213 // Create a PassManager to hold and optimize the collection of passes we are
218 // Add an appropriate TargetData instance for this module...
219 Passes.add(new TargetData(M.get()));
221 // Create a new optimization pass for each one specified on the command line
222 for (unsigned i = 0; i < PassList.size(); ++i) {
223 const PassInfo *PassInf = PassList[i];
225 if (PassInf->getNormalCtor())
226 P = PassInf->getNormalCtor()();
227 else if (PassInf->getTargetCtor()) {
228 assert(target.get() && "Could not allocate target machine!");
229 P = PassInf->getTargetCtor()(*target.get());
231 llvm_cerr << argv[0] << ": cannot create pass: "
232 << PassInf->getPassName() << "\n";
237 if (dynamic_cast<BasicBlockPass*>(P))
238 Passes.add(new BasicBlockPassPrinter(PassInf));
239 else if (dynamic_cast<FunctionPass*>(P))
240 Passes.add(new FunctionPassPrinter(PassInf));
242 Passes.add(new ModulePassPrinter(PassInf));
247 Passes.add(new PrintModulePass(&llvm_cerr));
250 // Check that the module is well formed on completion of optimization
252 Passes.add(createVerifierPass());
254 // Write bytecode out to disk or cout as the last step...
255 if (!NoOutput && !AnalyzeOnly) {
256 llvm_ostream L(*Out);
257 Passes.add(new WriteBytecodePass(&L, Out != &std::cout, !NoCompress));
260 // Now that we have all of the passes ready, run them.
261 Passes.run(*M.get());
265 } catch (const std::string& msg) {
266 llvm_cerr << argv[0] << ": " << msg << "\n";
268 llvm_cerr << argv[0] << ": Unexpected unknown exception occurred.\n";