56bc16b6bdd3204daeb9e2d61169a115d5142fdc
[oota-llvm.git] / tools / opt / opt.cpp
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
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 // Optimizations may be specified an arbitrary number of times on the command
11 // line, they are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14
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/TargetMachine.h"
22 #include "llvm/Support/PassNameParser.h"
23 #include "llvm/System/Signals.h"
24 #include "llvm/Support/PluginLoader.h"
25 #include "llvm/Support/SystemUtils.h"
26 #include <fstream>
27 #include <memory>
28 #include <algorithm>
29
30 using namespace llvm;
31
32 // The OptimizationList is automatically populated with registered Passes by the
33 // PassNameParser.
34 //
35 static cl::list<const PassInfo*, bool,
36                 FilteredPassNameParser<PassInfo::Optimization> >
37 OptimizationList(cl::desc("Optimizations available:"));
38
39
40 // Other command line options...
41 //
42 static cl::opt<std::string>
43 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
44
45 static cl::opt<std::string>
46 OutputFilename("o", cl::desc("Override output filename"),
47                cl::value_desc("filename"), cl::init("-"));
48
49 static cl::opt<bool>
50 Force("f", cl::desc("Overwrite output files"));
51
52 static cl::opt<bool>
53 PrintEachXForm("p", cl::desc("Print module after each transformation"));
54
55 static cl::opt<bool>
56 NoOutput("disable-output",
57          cl::desc("Do not write result bytecode file"), cl::Hidden);
58
59 static cl::opt<bool>
60 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
61
62 static cl::opt<bool>
63 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
64
65 static cl::alias
66 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
67
68
69 //===----------------------------------------------------------------------===//
70 // main for opt
71 //
72 int main(int argc, char **argv) {
73   try {
74     cl::ParseCommandLineOptions(argc, argv,
75                                 " llvm .bc -> .bc modular optimizer\n");
76     sys::PrintStackTraceOnErrorSignal();
77
78     // Allocate a full target machine description only if necessary...
79     // FIXME: The choice of target should be controllable on the command line.
80     std::auto_ptr<TargetMachine> target;
81
82     TargetMachine* TM = NULL;
83     std::string ErrorMessage;
84
85     // Load the input module...
86     std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
87     if (M.get() == 0) {
88       std::cerr << argv[0] << ": ";
89       if (ErrorMessage.size())
90         std::cerr << ErrorMessage << "\n";
91       else
92         std::cerr << "bytecode didn't read correctly.\n";
93       return 1;
94     }
95
96     // Figure out what stream we are supposed to write to...
97     std::ostream *Out = &std::cout;  // Default to printing to stdout...
98     if (OutputFilename != "-") {
99       if (!Force && std::ifstream(OutputFilename.c_str())) {
100         // If force is not specified, make sure not to overwrite a file!
101         std::cerr << argv[0] << ": error opening '" << OutputFilename
102                   << "': file exists!\n"
103                   << "Use -f command line argument to force output\n";
104         return 1;
105       }
106       Out = new std::ofstream(OutputFilename.c_str());
107
108       if (!Out->good()) {
109         std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
110         return 1;
111       }
112
113       // Make sure that the Output file gets unlinked from the disk if we get a
114       // SIGINT
115       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
116     }
117
118     // If the output is set to be emitted to standard out, and standard out is a
119     // console, print out a warning message and refuse to do it.  We don't impress
120     // anyone by spewing tons of binary goo to a terminal.
121     if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
122       NoOutput = true;
123     }
124
125     // Create a PassManager to hold and optimize the collection of passes we are
126     // about to build...
127     //
128     PassManager Passes;
129
130     // Add an appropriate TargetData instance for this module...
131     Passes.add(new TargetData("opt", M.get()));
132
133     // Create a new optimization pass for each one specified on the command line
134     for (unsigned i = 0; i < OptimizationList.size(); ++i) {
135       const PassInfo *Opt = OptimizationList[i];
136       
137       if (Opt->getNormalCtor())
138         Passes.add(Opt->getNormalCtor()());
139       else if (Opt->getTargetCtor()) {
140 #if 0
141         if (target.get() == NULL)
142           target.reset(allocateSparcTargetMachine()); // FIXME: target option
143 #endif
144         assert(target.get() && "Could not allocate target machine!");
145         Passes.add(Opt->getTargetCtor()(*target.get()));
146       } else
147         std::cerr << argv[0] << ": cannot create pass: " << Opt->getPassName()
148                   << "\n";
149
150       if (PrintEachXForm)
151         Passes.add(new PrintModulePass(&std::cerr));
152     }
153
154     // Check that the module is well formed on completion of optimization
155     if (!NoVerify)
156       Passes.add(createVerifierPass());
157
158     // Write bytecode out to disk or cout as the last step...
159     if (!NoOutput)
160       Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
161
162     // Now that we have all of the passes ready, run them.
163     Passes.run(*M.get());
164
165     return 0;
166   } catch (const std::string& msg) {
167     std::cerr << argv[0] << ": " << msg << "\n";
168   } catch (...) {
169     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
170   }
171   return 1;
172 }