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/Assembly/Parser.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Bytecode/Reader.h"
19 #include "llvm/Bytecode/WriteBytecodePass.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/System/Signals.h"
26 #include "llvm/Support/PluginLoader.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Transforms/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,
41 FilteredPassNameParser<PassInfo::Optimization> >
42 OptimizationList(cl::desc("Optimizations available:"));
45 // Other command line options...
47 static cl::opt<std::string>
48 InputFilename(cl::Positional, cl::desc("<input bytecode file>"),
49 cl::init("-"), cl::value_desc("filename"));
51 static cl::opt<std::string>
52 OutputFilename("o", cl::desc("Override output filename"),
53 cl::value_desc("filename"), cl::init("-"));
56 Force("f", cl::desc("Overwrite output files"));
59 PrintEachXForm("p", cl::desc("Print module after each transformation"));
62 NoOutput("disable-output",
63 cl::desc("Do not write result bytecode file"), cl::Hidden);
66 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
69 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
72 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
75 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
77 // The AnalysesList is automatically populated with registered Passes by the
80 cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::Analysis> >
81 AnalysesList(cl::desc("Analyses available:"));
83 static Timer BytecodeLoadTimer("Bytecode Loader");
85 // ---------- Define Printers for module and function passes ------------
88 struct ModulePassPrinter : public ModulePass {
89 const PassInfo *PassToPrint;
90 ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
92 virtual bool runOnModule(Module &M) {
94 std::cout << "Printing analysis '" << PassToPrint->getPassName()
96 getAnalysisID<Pass>(PassToPrint).print(std::cout, &M);
99 // Get and print pass...
103 virtual const char *getPassName() const { return "'Pass' Printer"; }
105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106 AU.addRequiredID(PassToPrint);
107 AU.setPreservesAll();
111 struct FunctionPassPrinter : public FunctionPass {
112 const PassInfo *PassToPrint;
113 FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
115 virtual bool runOnFunction(Function &F) {
117 std::cout << "Printing analysis '" << PassToPrint->getPassName()
118 << "' for function '" << F.getName() << "':\n";
120 // Get and print pass...
121 getAnalysisID<Pass>(PassToPrint).print(std::cout, F.getParent());
125 virtual const char *getPassName() const { return "FunctionPass Printer"; }
127 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
128 AU.addRequiredID(PassToPrint);
129 AU.setPreservesAll();
133 struct BasicBlockPassPrinter : public BasicBlockPass {
134 const PassInfo *PassToPrint;
135 BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
137 virtual bool runOnBasicBlock(BasicBlock &BB) {
139 std::cout << "Printing Analysis info for BasicBlock '" << BB.getName()
140 << "': Pass " << PassToPrint->getPassName() << ":\n";
143 // Get and print pass...
144 getAnalysisID<Pass>(PassToPrint).print(
145 std::cout, BB.getParent()->getParent());
149 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152 AU.addRequiredID(PassToPrint);
153 AU.setPreservesAll();
157 } // anonymous namespace
160 //===----------------------------------------------------------------------===//
163 int main(int argc, char **argv) {
165 cl::ParseCommandLineOptions(argc, argv,
166 " llvm .bc -> .bc modular optimizer and analysis printer \n");
167 sys::PrintStackTraceOnErrorSignal();
172 TimeRegion RegionTimer(BytecodeLoadTimer);
174 CurMod = ParseBytecodeFile(InputFilename);
176 if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename,&Err))){
177 std::cerr << argv[0] << ": " << Err.getMessage() << "\n";
181 // Create a PassManager to hold and optimize the collection of passes we
182 // are about to build...
185 // Add an appropriate TargetData instance for this module...
186 Passes.add(new TargetData(CurMod));
188 // Make sure the input LLVM is well formed.
190 Passes.add(createVerifierPass());
192 // Create a new optimization pass for each one specified on the
194 for (unsigned i = 0; i < AnalysesList.size(); ++i) {
195 const PassInfo *Analysis = AnalysesList[i];
197 if (Analysis->getNormalCtor()) {
198 Pass *P = Analysis->getNormalCtor()();
201 if (BasicBlockPass *BBP = dynamic_cast<BasicBlockPass*>(P))
202 Passes.add(new BasicBlockPassPrinter(Analysis));
203 else if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P))
204 Passes.add(new FunctionPassPrinter(Analysis));
206 Passes.add(new ModulePassPrinter(Analysis));
209 std::cerr << argv[0] << ": cannot create pass: "
210 << Analysis->getPassName() << "\n";
219 // Allocate a full target machine description only if necessary...
220 // FIXME: The choice of target should be controllable on the command line.
221 std::auto_ptr<TargetMachine> target;
223 TargetMachine* TM = NULL;
224 std::string ErrorMessage;
226 // Load the input module...
227 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
229 std::cerr << argv[0] << ": ";
230 if (ErrorMessage.size())
231 std::cerr << ErrorMessage << "\n";
233 std::cerr << "bytecode didn't read correctly.\n";
237 // Figure out what stream we are supposed to write to...
238 // FIXME: cout is not binary!
239 std::ostream *Out = &std::cout; // Default to printing to stdout...
240 if (OutputFilename != "-") {
241 if (!Force && std::ifstream(OutputFilename.c_str())) {
242 // If force is not specified, make sure not to overwrite a file!
243 std::cerr << argv[0] << ": error opening '" << OutputFilename
244 << "': file exists!\n"
245 << "Use -f command line argument to force output\n";
248 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
250 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
253 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
257 // Make sure that the Output file gets unlinked from the disk if we get a
259 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
262 // If the output is set to be emitted to standard out, and standard out is a
263 // console, print out a warning message and refuse to do it. We don't
264 // impress anyone by spewing tons of binary goo to a terminal.
265 if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
269 // Create a PassManager to hold and optimize the collection of passes we are
274 // Add an appropriate TargetData instance for this module...
275 Passes.add(new TargetData(M.get()));
277 // Create a new optimization pass for each one specified on the command line
278 for (unsigned i = 0; i < OptimizationList.size(); ++i) {
279 const PassInfo *Opt = OptimizationList[i];
281 if (Opt->getNormalCtor())
282 Passes.add(Opt->getNormalCtor()());
283 else if (Opt->getTargetCtor()) {
285 if (target.get() == NULL)
286 target.reset(allocateSparcTargetMachine()); // FIXME: target option
288 assert(target.get() && "Could not allocate target machine!");
289 Passes.add(Opt->getTargetCtor()(*target.get()));
291 std::cerr << argv[0] << ": cannot create pass: " << Opt->getPassName()
295 Passes.add(new PrintModulePass(&std::cerr));
298 // Check that the module is well formed on completion of optimization
300 Passes.add(createVerifierPass());
302 // Write bytecode out to disk or cout as the last step...
304 Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
306 // Now that we have all of the passes ready, run them.
307 Passes.run(*M.get());
311 } catch (const std::string& msg) {
312 std::cerr << argv[0] << ": " << msg << "\n";
314 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";