blob: 6d3b3b648aadc2a3c039f7593a6a971b4c9fc1ac [file] [log] [blame]
Chris Lattner76351aa2004-04-02 05:06:57 +00001//===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattner00950542001-06-06 20:29:01 +000010// Optimizations may be specified an arbitrary number of times on the command
Reid Spencerfd90dd52006-08-18 06:34:30 +000011// line, They are run in the order specified.
Chris Lattner00950542001-06-06 20:29:01 +000012//
Chris Lattner0eafc312001-10-18 06:05:15 +000013//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000014
Chris Lattner00950542001-06-06 20:29:01 +000015#include "llvm/Module.h"
Reid Spencerfd90dd52006-08-18 06:34:30 +000016#include "llvm/Assembly/Parser.h"
Chris Lattnerfb1b3f12002-01-31 00:47:12 +000017#include "llvm/PassManager.h"
Chris Lattner00950542001-06-06 20:29:01 +000018#include "llvm/Bytecode/Reader.h"
Chris Lattnerfb1b3f12002-01-31 00:47:12 +000019#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattnerffa6f9c2001-10-19 15:39:14 +000020#include "llvm/Assembly/PrintModulePass.h"
Chris Lattner22d26d72002-02-20 17:56:53 +000021#include "llvm/Analysis/Verifier.h"
Owen Anderson07000c62006-05-12 06:33:49 +000022#include "llvm/Target/TargetData.h"
Vikram S. Adve18fdfc42002-09-16 16:09:43 +000023#include "llvm/Target/TargetMachine.h"
Chris Lattner2053a2a2002-07-26 21:09:32 +000024#include "llvm/Support/PassNameParser.h"
Chris Lattnerbed85ff2004-05-27 05:41:36 +000025#include "llvm/System/Signals.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/Support/PluginLoader.h"
27#include "llvm/Support/SystemUtils.h"
Reid Spencerfd90dd52006-08-18 06:34:30 +000028#include "llvm/Support/Timer.h"
Reid Spencer023fcf92006-08-21 02:04:43 +000029#include "llvm/LinkAllPasses.h"
Reid Spenceraf303d52006-06-07 23:03:13 +000030#include "llvm/LinkAllVMCore.h"
Chris Lattner73e11d72001-10-18 06:13:08 +000031#include <fstream>
Chris Lattner63202322001-11-26 19:22:39 +000032#include <memory>
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000033#include <algorithm>
Anand Shukla63aaa112002-06-25 21:43:28 +000034
Brian Gaeked0fde302003-11-11 22:41:34 +000035using namespace llvm;
Chris Lattner9d6e7eb2002-04-12 18:21:13 +000036
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000037// The OptimizationList is automatically populated with registered Passes by the
38// PassNameParser.
39//
Chris Lattner2053a2a2002-07-26 21:09:32 +000040static cl::list<const PassInfo*, bool,
41 FilteredPassNameParser<PassInfo::Optimization> >
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000042OptimizationList(cl::desc("Optimizations available:"));
43
44
45// Other command line options...
Chris Lattnerfb1b3f12002-01-31 00:47:12 +000046//
Chris Lattner6c8103f2003-05-22 20:13:16 +000047static cl::opt<std::string>
Reid Spencerfd90dd52006-08-18 06:34:30 +000048InputFilename(cl::Positional, cl::desc("<input bytecode file>"),
49 cl::init("-"), cl::value_desc("filename"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000050
Chris Lattner6c8103f2003-05-22 20:13:16 +000051static cl::opt<std::string>
Chris Lattner5ff62e92002-07-22 02:10:13 +000052OutputFilename("o", cl::desc("Override output filename"),
Chris Lattnerb592fc22003-12-10 14:41:33 +000053 cl::value_desc("filename"), cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000054
55static cl::opt<bool>
56Force("f", cl::desc("Overwrite output files"));
57
58static cl::opt<bool>
59PrintEachXForm("p", cl::desc("Print module after each transformation"));
60
61static cl::opt<bool>
Chris Lattnerddd5b412003-02-26 20:00:41 +000062NoOutput("disable-output",
63 cl::desc("Do not write result bytecode file"), cl::Hidden);
Chris Lattnerd70b68e2003-02-12 18:43:33 +000064
65static cl::opt<bool>
Chris Lattnerddd5b412003-02-26 20:00:41 +000066NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
Chris Lattnerf3bafc12003-02-12 18:45:08 +000067
68static cl::opt<bool>
Chris Lattner3153e4f2004-05-27 20:32:10 +000069Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
Chris Lattner5ff62e92002-07-22 02:10:13 +000070
Reid Spencerec7eb452004-05-27 16:28:54 +000071static cl::alias
72QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
73
Reid Spencerfd90dd52006-08-18 06:34:30 +000074static cl::opt<bool>
75AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
76
77// The AnalysesList is automatically populated with registered Passes by the
78// PassNameParser.
79static
80 cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::Analysis> >
81 AnalysesList(cl::desc("Analyses available:"));
82
83static Timer BytecodeLoadTimer("Bytecode Loader");
84
85// ---------- Define Printers for module and function passes ------------
86namespace {
87
88struct ModulePassPrinter : public ModulePass {
89 const PassInfo *PassToPrint;
90 ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
91
92 virtual bool runOnModule(Module &M) {
93 if (!Quiet) {
94 std::cout << "Printing analysis '" << PassToPrint->getPassName()
95 << "':\n";
96 getAnalysisID<Pass>(PassToPrint).print(std::cout, &M);
97 }
98
99 // Get and print pass...
100 return false;
101 }
102
103 virtual const char *getPassName() const { return "'Pass' Printer"; }
104
105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106 AU.addRequiredID(PassToPrint);
107 AU.setPreservesAll();
108 }
109};
110
111struct FunctionPassPrinter : public FunctionPass {
112 const PassInfo *PassToPrint;
113 FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
114
115 virtual bool runOnFunction(Function &F) {
116 if (!Quiet) {
117 std::cout << "Printing analysis '" << PassToPrint->getPassName()
118 << "' for function '" << F.getName() << "':\n";
119 }
120 // Get and print pass...
121 getAnalysisID<Pass>(PassToPrint).print(std::cout, F.getParent());
122 return false;
123 }
124
125 virtual const char *getPassName() const { return "FunctionPass Printer"; }
126
127 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
128 AU.addRequiredID(PassToPrint);
129 AU.setPreservesAll();
130 }
131};
132
133struct BasicBlockPassPrinter : public BasicBlockPass {
134 const PassInfo *PassToPrint;
135 BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
136
137 virtual bool runOnBasicBlock(BasicBlock &BB) {
138 if (!Quiet) {
139 std::cout << "Printing Analysis info for BasicBlock '" << BB.getName()
140 << "': Pass " << PassToPrint->getPassName() << ":\n";
141 }
142
143 // Get and print pass...
144 getAnalysisID<Pass>(PassToPrint).print(
145 std::cout, BB.getParent()->getParent());
146 return false;
147 }
148
149 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
150
151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152 AU.addRequiredID(PassToPrint);
153 AU.setPreservesAll();
154 }
155};
156
157} // anonymous namespace
158
Chris Lattner0be41012002-02-01 04:54:11 +0000159
Chris Lattnerc0ce68b2002-07-23 18:12:22 +0000160//===----------------------------------------------------------------------===//
161// main for opt
162//
Chris Lattner00950542001-06-06 20:29:01 +0000163int main(int argc, char **argv) {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000164 try {
165 cl::ParseCommandLineOptions(argc, argv,
Reid Spencerfd90dd52006-08-18 06:34:30 +0000166 " llvm .bc -> .bc modular optimizer and analysis printer \n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000167 sys::PrintStackTraceOnErrorSignal();
Chris Lattnerfb1b3f12002-01-31 00:47:12 +0000168
Reid Spencerfd90dd52006-08-18 06:34:30 +0000169 if (AnalyzeOnly) {
170 Module *CurMod = 0;
Reid Spencerfd90dd52006-08-18 06:34:30 +0000171#if 0
Reid Spencer61c83e02006-08-18 08:43:06 +0000172 TimeRegion RegionTimer(BytecodeLoadTimer);
Reid Spencerfd90dd52006-08-18 06:34:30 +0000173#endif
Reid Spencer61c83e02006-08-18 08:43:06 +0000174 CurMod = ParseBytecodeFile(InputFilename);
175 ParseError Err;
176 if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename,&Err))){
177 std::cerr << argv[0] << ": " << Err.getMessage() << "\n";
Reid Spencerfd90dd52006-08-18 06:34:30 +0000178 return 1;
179 }
180
181 // Create a PassManager to hold and optimize the collection of passes we
182 // are about to build...
183 PassManager Passes;
184
185 // Add an appropriate TargetData instance for this module...
186 Passes.add(new TargetData(CurMod));
187
188 // Make sure the input LLVM is well formed.
189 if (!NoVerify)
190 Passes.add(createVerifierPass());
191
192 // Create a new optimization pass for each one specified on the
193 // command line
194 for (unsigned i = 0; i < AnalysesList.size(); ++i) {
195 const PassInfo *Analysis = AnalysesList[i];
196
197 if (Analysis->getNormalCtor()) {
198 Pass *P = Analysis->getNormalCtor()();
199 Passes.add(P);
200
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));
205 else
206 Passes.add(new ModulePassPrinter(Analysis));
207
208 } else
209 std::cerr << argv[0] << ": cannot create pass: "
210 << Analysis->getPassName() << "\n";
211 }
212
213 Passes.run(*CurMod);
214
215 delete CurMod;
216 return 0;
217 }
218
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000219 // 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;
Vikram S. Adve18fdfc42002-09-16 16:09:43 +0000222
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000223 TargetMachine* TM = NULL;
224 std::string ErrorMessage;
Vikram S. Adve18fdfc42002-09-16 16:09:43 +0000225
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000226 // Load the input module...
227 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
228 if (M.get() == 0) {
229 std::cerr << argv[0] << ": ";
230 if (ErrorMessage.size())
231 std::cerr << ErrorMessage << "\n";
232 else
233 std::cerr << "bytecode didn't read correctly.\n";
Chris Lattner00950542001-06-06 20:29:01 +0000234 return 1;
235 }
Chris Lattner76d12292002-04-18 19:55:25 +0000236
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000237 // Figure out what stream we are supposed to write to...
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000238 // FIXME: cout is not binary!
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000239 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";
246 return 1;
247 }
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000248 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
249 std::ios::binary;
250 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
Chris Lattner00950542001-06-06 20:29:01 +0000251
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000252 if (!Out->good()) {
253 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
254 return 1;
255 }
Chris Lattner76351aa2004-04-02 05:06:57 +0000256
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000257 // Make sure that the Output file gets unlinked from the disk if we get a
258 // SIGINT
259 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
260 }
Chris Lattner00950542001-06-06 20:29:01 +0000261
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000262 // If the output is set to be emitted to standard out, and standard out is a
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000263 // 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.
Reid Spencer564a5712005-01-05 17:31:55 +0000265 if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000266 NoOutput = true;
267 }
Chris Lattner9c3b55e2003-04-24 19:13:02 +0000268
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000269 // Create a PassManager to hold and optimize the collection of passes we are
270 // about to build...
271 //
272 PassManager Passes;
273
274 // Add an appropriate TargetData instance for this module...
Chris Lattner831b1212006-06-16 18:23:49 +0000275 Passes.add(new TargetData(M.get()));
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000276
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];
Misha Brukman3da94ae2005-04-22 00:00:37 +0000280
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000281 if (Opt->getNormalCtor())
282 Passes.add(Opt->getNormalCtor()());
283 else if (Opt->getTargetCtor()) {
Chris Lattner0af1e8e2003-04-16 23:02:16 +0000284#if 0
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000285 if (target.get() == NULL)
286 target.reset(allocateSparcTargetMachine()); // FIXME: target option
Chris Lattner0af1e8e2003-04-16 23:02:16 +0000287#endif
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000288 assert(target.get() && "Could not allocate target machine!");
289 Passes.add(Opt->getTargetCtor()(*target.get()));
290 } else
291 std::cerr << argv[0] << ": cannot create pass: " << Opt->getPassName()
292 << "\n";
Chris Lattnerfb1b3f12002-01-31 00:47:12 +0000293
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000294 if (PrintEachXForm)
295 Passes.add(new PrintModulePass(&std::cerr));
296 }
297
298 // Check that the module is well formed on completion of optimization
299 if (!NoVerify)
300 Passes.add(createVerifierPass());
301
302 // Write bytecode out to disk or cout as the last step...
303 if (!NoOutput)
304 Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
305
306 // Now that we have all of the passes ready, run them.
307 Passes.run(*M.get());
308
309 return 0;
Reid Spencerfd90dd52006-08-18 06:34:30 +0000310
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000311 } catch (const std::string& msg) {
312 std::cerr << argv[0] << ": " << msg << "\n";
313 } catch (...) {
314 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
Chris Lattnerfb1b3f12002-01-31 00:47:12 +0000315 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000316 return 1;
Chris Lattner00950542001-06-06 20:29:01 +0000317}