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(false),
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 llvm_cout << "Printing analysis '" << PassToPrint->getPassName()
92 getAnalysisID<Pass>(PassToPrint).print(llvm_cout, &M);
95 // Get and print pass...
99 virtual const char *getPassName() const { return "'Pass' Printer"; }
101 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
102 AU.addRequiredID(PassToPrint);
103 AU.setPreservesAll();
107 struct FunctionPassPrinter : public FunctionPass {
108 const PassInfo *PassToPrint;
109 FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
111 virtual bool runOnFunction(Function &F) {
113 llvm_cout << "Printing analysis '" << PassToPrint->getPassName()
114 << "' for function '" << F.getName() << "':\n";
116 // Get and print pass...
117 getAnalysisID<Pass>(PassToPrint).print(llvm_cout, F.getParent());
121 virtual const char *getPassName() const { return "FunctionPass Printer"; }
123 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
124 AU.addRequiredID(PassToPrint);
125 AU.setPreservesAll();
129 struct BasicBlockPassPrinter : public BasicBlockPass {
130 const PassInfo *PassToPrint;
131 BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
133 virtual bool runOnBasicBlock(BasicBlock &BB) {
135 llvm_cout << "Printing Analysis info for BasicBlock '" << BB.getName()
136 << "': Pass " << PassToPrint->getPassName() << ":\n";
139 // Get and print pass...
140 getAnalysisID<Pass>(PassToPrint).print(
141 llvm_cout, BB.getParent()->getParent());
145 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
147 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
148 AU.addRequiredID(PassToPrint);
149 AU.setPreservesAll();
153 } // anonymous namespace
156 //===----------------------------------------------------------------------===//
159 int main(int argc, char **argv) {
160 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
162 cl::ParseCommandLineOptions(argc, argv,
163 " llvm .bc -> .bc modular optimizer and analysis printer \n");
164 sys::PrintStackTraceOnErrorSignal();
166 // Allocate a full target machine description only if necessary.
167 // FIXME: The choice of target should be controllable on the command line.
168 std::auto_ptr<TargetMachine> target;
170 std::string ErrorMessage;
172 // Load the input module...
173 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
175 llvm_cerr << argv[0] << ": ";
176 if (ErrorMessage.size())
177 llvm_cerr << ErrorMessage << "\n";
179 llvm_cerr << "bytecode didn't read correctly.\n";
183 // Figure out what stream we are supposed to write to...
184 // FIXME: cout is not binary!
185 std::ostream *Out = &std::cout; // Default to printing to stdout...
186 if (OutputFilename != "-") {
187 if (!Force && std::ifstream(OutputFilename.c_str())) {
188 // If force is not specified, make sure not to overwrite a file!
189 llvm_cerr << argv[0] << ": error opening '" << OutputFilename
190 << "': file exists!\n"
191 << "Use -f command line argument to force output\n";
194 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
196 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
199 llvm_cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
203 // Make sure that the Output file gets unlinked from the disk if we get a
205 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
208 // If the output is set to be emitted to standard out, and standard out is a
209 // console, print out a warning message and refuse to do it. We don't
210 // impress anyone by spewing tons of binary goo to a terminal.
211 if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
215 // Create a PassManager to hold and optimize the collection of passes we are
220 // Add an appropriate TargetData instance for this module...
221 Passes.add(new TargetData(M.get()));
223 // Create a new optimization pass for each one specified on the command line
224 for (unsigned i = 0; i < PassList.size(); ++i) {
225 const PassInfo *PassInf = PassList[i];
227 if (PassInf->getNormalCtor())
228 P = PassInf->getNormalCtor()();
230 llvm_cerr << argv[0] << ": cannot create pass: "
231 << PassInf->getPassName() << "\n";
236 if (dynamic_cast<BasicBlockPass*>(P))
237 Passes.add(new BasicBlockPassPrinter(PassInf));
238 else if (dynamic_cast<FunctionPass*>(P))
239 Passes.add(new FunctionPassPrinter(PassInf));
241 Passes.add(new ModulePassPrinter(PassInf));
246 Passes.add(new PrintModulePass(&llvm_cerr));
249 // Check that the module is well formed on completion of optimization
251 Passes.add(createVerifierPass());
253 // Write bytecode out to disk or cout as the last step...
254 llvm_ostream L(*Out);
255 if (!NoOutput && !AnalyzeOnly)
256 Passes.add(new WriteBytecodePass(&L, false, !NoCompress));
258 // Now that we have all of the passes ready, run them.
259 Passes.run(*M.get());
263 } catch (const std::string& msg) {
264 llvm_cerr << argv[0] << ": " << msg << "\n";
266 llvm_cerr << argv[0] << ": Unexpected unknown exception occurred.\n";