Fix passing of float arguments through ffi.
[llvm.git] / tools / opt / opt.cpp
blob12bb2ec2c7cc38f98a736319dfe5caeb9264593b
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/LLVMContext.h"
16 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Assembly/PrintModulePass.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/PassNameParser.h"
28 #include "llvm/System/Signals.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/PluginLoader.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/LinkAllVMCore.h"
38 #include <memory>
39 #include <algorithm>
40 using namespace llvm;
42 // The OptimizationList is automatically populated with registered Passes by the
43 // PassNameParser.
45 static cl::list<const PassInfo*, bool, PassNameParser>
46 PassList(cl::desc("Optimizations available:"));
48 // Other command line options...
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
52 cl::init("-"), cl::value_desc("filename"));
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Override output filename"),
56 cl::value_desc("filename"), cl::init("-"));
58 static cl::opt<bool>
59 Force("f", cl::desc("Enable binary output on terminals"));
61 static cl::opt<bool>
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
64 static cl::opt<bool>
65 NoOutput("disable-output",
66 cl::desc("Do not write result bitcode file"), cl::Hidden);
68 static cl::opt<bool>
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
71 static cl::opt<bool>
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
74 static cl::opt<bool>
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
77 static cl::opt<bool>
78 StripDebug("strip-debug",
79 cl::desc("Strip debugger symbol info from translation unit"));
81 static cl::opt<bool>
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
84 static cl::opt<bool>
85 DisableOptimizations("disable-opt",
86 cl::desc("Do not run any optimization passes"));
88 static cl::opt<bool>
89 DisableInternalize("disable-internalize",
90 cl::desc("Do not mark all symbols as internal"));
92 static cl::opt<bool>
93 StandardCompileOpts("std-compile-opts",
94 cl::desc("Include the standard compile time optimizations"));
96 static cl::opt<bool>
97 StandardLinkOpts("std-link-opts",
98 cl::desc("Include the standard link time optimizations"));
100 static cl::opt<bool>
101 OptLevelO1("O1",
102 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
104 static cl::opt<bool>
105 OptLevelO2("O2",
106 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
108 static cl::opt<bool>
109 OptLevelO3("O3",
110 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
112 static cl::opt<bool>
113 UnitAtATime("funit-at-a-time",
114 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
115 cl::init(true));
117 static cl::opt<bool>
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119 cl::desc("Disable simplify-libcalls"));
121 static cl::opt<bool>
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
124 static cl::alias
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
127 static cl::opt<bool>
128 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
130 static cl::opt<std::string>
131 DefaultDataLayout("default-data-layout",
132 cl::desc("data layout string to use if not specified by module"),
133 cl::value_desc("layout-string"), cl::init(""));
135 // ---------- Define Printers for module and function passes ------------
136 namespace {
138 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
139 static char ID;
140 const PassInfo *PassToPrint;
141 CallGraphSCCPassPrinter(const PassInfo *PI) :
142 CallGraphSCCPass(&ID), PassToPrint(PI) {}
144 virtual bool runOnSCC(std::vector<CallGraphNode *>&SCC) {
145 if (!Quiet) {
146 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
148 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
149 Function *F = SCC[i]->getFunction();
150 if (F) {
151 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
155 // Get and print pass...
156 return false;
159 virtual const char *getPassName() const { return "'Pass' Printer"; }
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162 AU.addRequiredID(PassToPrint);
163 AU.setPreservesAll();
167 char CallGraphSCCPassPrinter::ID = 0;
169 struct ModulePassPrinter : public ModulePass {
170 static char ID;
171 const PassInfo *PassToPrint;
172 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
173 PassToPrint(PI) {}
175 virtual bool runOnModule(Module &M) {
176 if (!Quiet) {
177 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
178 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
181 // Get and print pass...
182 return false;
185 virtual const char *getPassName() const { return "'Pass' Printer"; }
187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
188 AU.addRequiredID(PassToPrint);
189 AU.setPreservesAll();
193 char ModulePassPrinter::ID = 0;
194 struct FunctionPassPrinter : public FunctionPass {
195 const PassInfo *PassToPrint;
196 static char ID;
197 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
198 PassToPrint(PI) {}
200 virtual bool runOnFunction(Function &F) {
201 if (!Quiet) {
202 outs() << "Printing analysis '" << PassToPrint->getPassName()
203 << "' for function '" << F.getName() << "':\n";
205 // Get and print pass...
206 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
207 return false;
210 virtual const char *getPassName() const { return "FunctionPass Printer"; }
212 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
213 AU.addRequiredID(PassToPrint);
214 AU.setPreservesAll();
218 char FunctionPassPrinter::ID = 0;
220 struct LoopPassPrinter : public LoopPass {
221 static char ID;
222 const PassInfo *PassToPrint;
223 LoopPassPrinter(const PassInfo *PI) :
224 LoopPass(&ID), PassToPrint(PI) {}
226 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
227 if (!Quiet) {
228 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
229 getAnalysisID<Pass>(PassToPrint).print(outs(),
230 L->getHeader()->getParent()->getParent());
232 // Get and print pass...
233 return false;
236 virtual const char *getPassName() const { return "'Pass' Printer"; }
238 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
239 AU.addRequiredID(PassToPrint);
240 AU.setPreservesAll();
244 char LoopPassPrinter::ID = 0;
246 struct BasicBlockPassPrinter : public BasicBlockPass {
247 const PassInfo *PassToPrint;
248 static char ID;
249 BasicBlockPassPrinter(const PassInfo *PI)
250 : BasicBlockPass(&ID), PassToPrint(PI) {}
252 virtual bool runOnBasicBlock(BasicBlock &BB) {
253 if (!Quiet) {
254 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
255 << "': Pass " << PassToPrint->getPassName() << ":\n";
258 // Get and print pass...
259 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
260 return false;
263 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
265 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
266 AU.addRequiredID(PassToPrint);
267 AU.setPreservesAll();
271 char BasicBlockPassPrinter::ID = 0;
272 inline void addPass(PassManager &PM, Pass *P) {
273 // Add the pass to the pass manager...
274 PM.add(P);
276 // If we are verifying all of the intermediate steps, add the verifier...
277 if (VerifyEach) PM.add(createVerifierPass());
280 /// AddOptimizationPasses - This routine adds optimization passes
281 /// based on selected optimization level, OptLevel. This routine
282 /// duplicates llvm-gcc behaviour.
284 /// OptLevel - Optimization Level
285 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
286 unsigned OptLevel) {
287 createStandardFunctionPasses(&FPM, OptLevel);
289 llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
290 createStandardModulePasses(&MPM, OptLevel,
291 /*OptimizeSize=*/ false,
292 UnitAtATime,
293 /*UnrollLoops=*/ OptLevel > 1,
294 !DisableSimplifyLibCalls,
295 /*HaveExceptions=*/ true,
296 InliningPass);
299 void AddStandardCompilePasses(PassManager &PM) {
300 PM.add(createVerifierPass()); // Verify that input is correct
302 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
304 // If the -strip-debug command line option was specified, do it.
305 if (StripDebug)
306 addPass(PM, createStripSymbolsPass(true));
308 if (DisableOptimizations) return;
310 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
312 // -std-compile-opts adds the same module passes as -O3.
313 createStandardModulePasses(&PM, 3,
314 /*OptimizeSize=*/ false,
315 /*UnitAtATime=*/ true,
316 /*UnrollLoops=*/ true,
317 /*SimplifyLibCalls=*/ true,
318 /*HaveExceptions=*/ true,
319 InliningPass);
322 void AddStandardLinkPasses(PassManager &PM) {
323 PM.add(createVerifierPass()); // Verify that input is correct
325 // If the -strip-debug command line option was specified, do it.
326 if (StripDebug)
327 addPass(PM, createStripSymbolsPass(true));
329 if (DisableOptimizations) return;
331 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
332 /*RunInliner=*/ !DisableInline,
333 /*VerifyEach=*/ VerifyEach);
336 } // anonymous namespace
339 //===----------------------------------------------------------------------===//
340 // main for opt
342 int main(int argc, char **argv) {
343 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
344 LLVMContext &Context = getGlobalContext();
346 cl::ParseCommandLineOptions(argc, argv,
347 "llvm .bc -> .bc modular optimizer and analysis printer\n");
348 sys::PrintStackTraceOnErrorSignal();
350 // Allocate a full target machine description only if necessary.
351 // FIXME: The choice of target should be controllable on the command line.
352 std::auto_ptr<TargetMachine> target;
354 SMDiagnostic Err;
356 // Load the input module...
357 std::auto_ptr<Module> M;
358 M.reset(ParseIRFile(InputFilename, Err, Context));
360 if (M.get() == 0) {
361 Err.Print(argv[0], errs());
362 return 1;
365 // Figure out what stream we are supposed to write to...
366 // FIXME: outs() is not binary!
367 raw_ostream *Out = &outs(); // Default to printing to stdout...
368 if (OutputFilename != "-") {
369 // Make sure that the Output file gets unlinked from the disk if we get a
370 // SIGINT
371 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
373 std::string ErrorInfo;
374 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
375 raw_fd_ostream::F_Binary);
376 if (!ErrorInfo.empty()) {
377 errs() << ErrorInfo << '\n';
378 delete Out;
379 return 1;
383 // If the output is set to be emitted to standard out, and standard out is a
384 // console, print out a warning message and refuse to do it. We don't
385 // impress anyone by spewing tons of binary goo to a terminal.
386 if (!Force && !NoOutput && !OutputAssembly)
387 if (CheckBitcodeOutputToConsole(*Out, !Quiet))
388 NoOutput = true;
390 // Create a PassManager to hold and optimize the collection of passes we are
391 // about to build...
393 PassManager Passes;
395 // Add an appropriate TargetData instance for this module...
396 TargetData *TD = 0;
397 const std::string &ModuleDataLayout = M.get()->getDataLayout();
398 if (!ModuleDataLayout.empty())
399 TD = new TargetData(ModuleDataLayout);
400 else if (!DefaultDataLayout.empty())
401 TD = new TargetData(DefaultDataLayout);
403 if (TD)
404 Passes.add(TD);
406 FunctionPassManager *FPasses = NULL;
407 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
408 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
409 if (TD)
410 FPasses->add(new TargetData(*TD));
413 // If the -strip-debug command line option was specified, add it. If
414 // -std-compile-opts was also specified, it will handle StripDebug.
415 if (StripDebug && !StandardCompileOpts)
416 addPass(Passes, createStripSymbolsPass(true));
418 // Create a new optimization pass for each one specified on the command line
419 for (unsigned i = 0; i < PassList.size(); ++i) {
420 // Check to see if -std-compile-opts was specified before this option. If
421 // so, handle it.
422 if (StandardCompileOpts &&
423 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
424 AddStandardCompilePasses(Passes);
425 StandardCompileOpts = false;
428 if (StandardLinkOpts &&
429 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
430 AddStandardLinkPasses(Passes);
431 StandardLinkOpts = false;
434 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
435 AddOptimizationPasses(Passes, *FPasses, 1);
436 OptLevelO1 = false;
439 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
440 AddOptimizationPasses(Passes, *FPasses, 2);
441 OptLevelO2 = false;
444 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
445 AddOptimizationPasses(Passes, *FPasses, 3);
446 OptLevelO3 = false;
449 const PassInfo *PassInf = PassList[i];
450 Pass *P = 0;
451 if (PassInf->getNormalCtor())
452 P = PassInf->getNormalCtor()();
453 else
454 errs() << argv[0] << ": cannot create pass: "
455 << PassInf->getPassName() << "\n";
456 if (P) {
457 bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
458 bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
459 bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
460 bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
462 addPass(Passes, P);
464 if (AnalyzeOnly) {
465 if (isBBPass)
466 Passes.add(new BasicBlockPassPrinter(PassInf));
467 else if (isLPass)
468 Passes.add(new LoopPassPrinter(PassInf));
469 else if (isFPass)
470 Passes.add(new FunctionPassPrinter(PassInf));
471 else if (isCGSCCPass)
472 Passes.add(new CallGraphSCCPassPrinter(PassInf));
473 else
474 Passes.add(new ModulePassPrinter(PassInf));
478 if (PrintEachXForm)
479 Passes.add(createPrintModulePass(&errs()));
482 // If -std-compile-opts was specified at the end of the pass list, add them.
483 if (StandardCompileOpts) {
484 AddStandardCompilePasses(Passes);
485 StandardCompileOpts = false;
488 if (StandardLinkOpts) {
489 AddStandardLinkPasses(Passes);
490 StandardLinkOpts = false;
493 if (OptLevelO1)
494 AddOptimizationPasses(Passes, *FPasses, 1);
496 if (OptLevelO2)
497 AddOptimizationPasses(Passes, *FPasses, 2);
499 if (OptLevelO3)
500 AddOptimizationPasses(Passes, *FPasses, 3);
502 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
503 FPasses->doInitialization();
504 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
505 I != E; ++I)
506 FPasses->run(*I);
509 // Check that the module is well formed on completion of optimization
510 if (!NoVerify && !VerifyEach)
511 Passes.add(createVerifierPass());
513 // Write bitcode or assembly out to disk or outs() as the last step...
514 if (!NoOutput && !AnalyzeOnly) {
515 if (OutputAssembly)
516 Passes.add(createPrintModulePass(Out));
517 else
518 Passes.add(createBitcodeWriterPass(*Out));
521 // Now that we have all of the passes ready, run them.
522 Passes.run(*M.get());
524 // Delete the raw_fd_ostream.
525 if (Out != &outs())
526 delete Out;
527 return 0;