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/ManagedStatic.h"
26 #include "llvm/Support/PluginLoader.h"
27 #include "llvm/Support/Streams.h"
28 #include "llvm/Support/SystemUtils.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/LinkAllPasses.h"
31 #include "llvm/LinkAllVMCore.h"
38 // The OptimizationList is automatically populated with registered Passes by the
41 static cl::list<const PassInfo*, bool, PassNameParser>
42 PassList(cl::desc("Optimizations available:"));
44 static cl::opt<bool> NoCompress("disable-compression", cl::init(true),
45 cl::desc("Don't compress the generated bytecode"));
47 // Other command line options...
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input bytecode file>"),
51 cl::init("-"), cl::value_desc("filename"));
53 static cl::opt<std::string>
54 OutputFilename("o", cl::desc("Override output filename"),
55 cl::value_desc("filename"), cl::init("-"));
58 Force("f", cl::desc("Overwrite output files"));
61 PrintEachXForm("p", cl::desc("Print module after each transformation"));
64 NoOutput("disable-output",
65 cl::desc("Do not write result bytecode file"), cl::Hidden);
68 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
71 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
74 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
77 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
79 static Timer BytecodeLoadTimer("Bytecode Loader");
81 // ---------- Define Printers for module and function passes ------------
84 struct ModulePassPrinter : public ModulePass {
85 const PassInfo *PassToPrint;
86 ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
88 virtual bool runOnModule(Module &M) {
90 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
91 getAnalysisID<Pass>(PassToPrint).print(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 cout << "Printing analysis '" << PassToPrint->getPassName()
113 << "' for function '" << F.getName() << "':\n";
115 // Get and print pass...
116 getAnalysisID<Pass>(PassToPrint).print(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 cout << "Printing Analysis info for BasicBlock '" << BB.getName()
135 << "': Pass " << PassToPrint->getPassName() << ":\n";
138 // Get and print pass...
139 getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
143 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
145 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146 AU.addRequiredID(PassToPrint);
147 AU.setPreservesAll();
151 } // anonymous namespace
154 //===----------------------------------------------------------------------===//
157 int main(int argc, char **argv) {
158 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
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 cerr << argv[0] << ": ";
174 if (ErrorMessage.size())
175 cerr << ErrorMessage << "\n";
177 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 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 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()();
228 cerr << argv[0] << ": cannot create pass: "
229 << PassInf->getPassName() << "\n";
234 if (dynamic_cast<BasicBlockPass*>(P))
235 Passes.add(new BasicBlockPassPrinter(PassInf));
236 else if (dynamic_cast<FunctionPass*>(P))
237 Passes.add(new FunctionPassPrinter(PassInf));
239 Passes.add(new ModulePassPrinter(PassInf));
244 Passes.add(new PrintModulePass(&cerr));
247 // Check that the module is well formed on completion of optimization
249 Passes.add(createVerifierPass());
251 // Write bytecode out to disk or cout as the last step...
253 if (!NoOutput && !AnalyzeOnly)
254 Passes.add(new WriteBytecodePass(&L, false, !NoCompress));
256 // Now that we have all of the passes ready, run them.
257 Passes.run(*M.get());
261 } catch (const std::string& msg) {
262 cerr << argv[0] << ": " << msg << "\n";
264 cerr << argv[0] << ": Unexpected unknown exception occurred.\n";