1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "BreakpointPrinter.h"
16 #include "NewPMDriver.h"
17 #include "PassPrinters.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/RegionPass.h"
23 #include "llvm/Bitcode/BitcodeWriterPass.h"
24 #include "llvm/CodeGen/CommandFlags.h"
25 #include "llvm/InitializePasses.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/IRPrintingPasses.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/LinkAllIR.h"
33 #include "llvm/LinkAllPasses.h"
34 #include "llvm/MC/SubtargetFeature.h"
35 #include "llvm/PassManager.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/PassNameParser.h"
39 #include "llvm/Support/PluginLoader.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/SourceMgr.h"
43 #include "llvm/Support/SystemUtils.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Target/TargetLibraryInfo.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 using namespace opt_tool;
55 // The OptimizationList is automatically populated with registered Passes by the
58 static cl::list<const PassInfo*, bool, PassNameParser>
59 PassList(cl::desc("Optimizations available:"));
61 // This flag specifies a textual description of the optimization pass pipeline
62 // to run over the module. This flag switches opt to use the new pass manager
63 // infrastructure, completely disabling all of the flags specific to the old
65 static cl::opt<std::string> PassPipeline(
67 cl::desc("A textual description of the pass pipeline for optimizing"),
70 // Other command line options...
72 static cl::opt<std::string>
73 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
74 cl::init("-"), cl::value_desc("filename"));
76 static cl::opt<std::string>
77 OutputFilename("o", cl::desc("Override output filename"),
78 cl::value_desc("filename"));
81 Force("f", cl::desc("Enable binary output on terminals"));
84 PrintEachXForm("p", cl::desc("Print module after each transformation"));
87 NoOutput("disable-output",
88 cl::desc("Do not write result bitcode file"), cl::Hidden);
91 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
94 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
97 VerifyEach("verify-each", cl::desc("Verify after each transform"));
100 StripDebug("strip-debug",
101 cl::desc("Strip debugger symbol info from translation unit"));
104 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
107 DisableOptimizations("disable-opt",
108 cl::desc("Do not run any optimization passes"));
111 DisableInternalize("disable-internalize",
112 cl::desc("Do not mark all symbols as internal"));
115 StandardCompileOpts("std-compile-opts",
116 cl::desc("Include the standard compile time optimizations"));
119 StandardLinkOpts("std-link-opts",
120 cl::desc("Include the standard link time optimizations"));
124 cl::desc("Optimization level 1. Similar to clang -O1"));
128 cl::desc("Optimization level 2. Similar to clang -O2"));
132 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
136 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
140 cl::desc("Optimization level 3. Similar to clang -O3"));
142 static cl::opt<std::string>
143 TargetTriple("mtriple", cl::desc("Override target triple for module"));
146 UnitAtATime("funit-at-a-time",
147 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
151 DisableLoopUnrolling("disable-loop-unrolling",
152 cl::desc("Disable loop unrolling in all relevant passes"),
155 DisableLoopVectorization("disable-loop-vectorization",
156 cl::desc("Disable the loop vectorization pass"),
160 DisableSLPVectorization("disable-slp-vectorization",
161 cl::desc("Disable the slp vectorization pass"),
166 DisableSimplifyLibCalls("disable-simplify-libcalls",
167 cl::desc("Disable simplify-libcalls"));
170 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
173 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
176 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
179 PrintBreakpoints("print-breakpoints-for-testing",
180 cl::desc("Print select breakpoints location for testing"));
182 static cl::opt<std::string>
183 DefaultDataLayout("default-data-layout",
184 cl::desc("data layout string to use if not specified by module"),
185 cl::value_desc("layout-string"), cl::init(""));
189 static inline void addPass(PassManagerBase &PM, Pass *P) {
190 // Add the pass to the pass manager...
193 // If we are verifying all of the intermediate steps, add the verifier...
194 if (VerifyEach) PM.add(createVerifierPass());
197 /// AddOptimizationPasses - This routine adds optimization passes
198 /// based on selected optimization level, OptLevel. This routine
199 /// duplicates llvm-gcc behaviour.
201 /// OptLevel - Optimization Level
202 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
203 unsigned OptLevel, unsigned SizeLevel) {
204 FPM.add(createVerifierPass()); // Verify that input is correct
206 PassManagerBuilder Builder;
207 Builder.OptLevel = OptLevel;
208 Builder.SizeLevel = SizeLevel;
212 } else if (OptLevel > 1) {
213 unsigned Threshold = 225;
214 if (SizeLevel == 1) // -Os
216 else if (SizeLevel == 2) // -Oz
220 Builder.Inliner = createFunctionInliningPass(Threshold);
222 Builder.Inliner = createAlwaysInlinerPass();
224 Builder.DisableUnitAtATime = !UnitAtATime;
225 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
226 DisableLoopUnrolling : OptLevel == 0;
228 // This is final, unless there is a #pragma vectorize enable
229 if (DisableLoopVectorization)
230 Builder.LoopVectorize = false;
231 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
232 else if (!Builder.LoopVectorize)
233 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
235 // When #pragma vectorize is on for SLP, do the same as above
236 Builder.SLPVectorize =
237 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
239 Builder.populateFunctionPassManager(FPM);
240 Builder.populateModulePassManager(MPM);
243 static void AddStandardCompilePasses(PassManagerBase &PM) {
244 PM.add(createVerifierPass()); // Verify that input is correct
246 // If the -strip-debug command line option was specified, do it.
248 addPass(PM, createStripSymbolsPass(true));
250 if (DisableOptimizations) return;
252 // -std-compile-opts adds the same module passes as -O3.
253 PassManagerBuilder Builder;
255 Builder.Inliner = createFunctionInliningPass();
256 Builder.OptLevel = 3;
257 Builder.populateModulePassManager(PM);
260 static void AddStandardLinkPasses(PassManagerBase &PM) {
261 PM.add(createVerifierPass()); // Verify that input is correct
263 // If the -strip-debug command line option was specified, do it.
265 addPass(PM, createStripSymbolsPass(true));
267 if (DisableOptimizations) return;
269 PassManagerBuilder Builder;
270 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
271 /*RunInliner=*/ !DisableInline);
274 //===----------------------------------------------------------------------===//
275 // CodeGen-related helper functions.
278 CodeGenOpt::Level GetCodeGenOptLevel() {
280 return CodeGenOpt::Less;
282 return CodeGenOpt::Default;
284 return CodeGenOpt::Aggressive;
285 return CodeGenOpt::None;
288 // Returns the TargetMachine instance or zero if no triple is provided.
289 static TargetMachine* GetTargetMachine(Triple TheTriple) {
291 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
293 // Some modules don't specify a triple, and this is okay.
298 // Package up features to be passed to target/subtarget
299 std::string FeaturesStr;
301 SubtargetFeatures Features;
302 for (unsigned i = 0; i != MAttrs.size(); ++i)
303 Features.AddFeature(MAttrs[i]);
304 FeaturesStr = Features.getString();
307 return TheTarget->createTargetMachine(TheTriple.getTriple(),
309 InitTargetOptionsFromCodeGenFlags(),
311 GetCodeGenOptLevel());
314 //===----------------------------------------------------------------------===//
317 int main(int argc, char **argv) {
318 sys::PrintStackTraceOnErrorSignal();
319 llvm::PrettyStackTraceProgram X(argc, argv);
321 // Enable debug stream buffering.
322 EnableDebugBuffering = true;
324 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
325 LLVMContext &Context = getGlobalContext();
327 InitializeAllTargets();
328 InitializeAllTargetMCs();
331 PassRegistry &Registry = *PassRegistry::getPassRegistry();
332 initializeCore(Registry);
333 initializeDebugIRPass(Registry);
334 initializeScalarOpts(Registry);
335 initializeObjCARCOpts(Registry);
336 initializeVectorization(Registry);
337 initializeIPO(Registry);
338 initializeAnalysis(Registry);
339 initializeIPA(Registry);
340 initializeTransformUtils(Registry);
341 initializeInstCombine(Registry);
342 initializeInstrumentation(Registry);
343 initializeTarget(Registry);
344 // For codegen passes, only passes that do IR to IR transformation are
345 // supported. For now, just add CodeGenPrepare.
346 initializeCodeGenPreparePass(Registry);
348 cl::ParseCommandLineOptions(argc, argv,
349 "llvm .bc -> .bc modular optimizer and analysis printer\n");
351 if (AnalyzeOnly && NoOutput) {
352 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
358 // Load the input module...
360 M.reset(ParseIRFile(InputFilename, Err, Context));
363 Err.print(argv[0], errs());
367 // If we are supposed to override the target triple, do so now.
368 if (!TargetTriple.empty())
369 M->setTargetTriple(Triple::normalize(TargetTriple));
371 // Figure out what stream we are supposed to write to...
372 OwningPtr<tool_output_file> Out;
374 if (!OutputFilename.empty())
375 errs() << "WARNING: The -o (output filename) option is ignored when\n"
376 "the --disable-output option is used.\n";
378 // Default to standard output.
379 if (OutputFilename.empty())
380 OutputFilename = "-";
382 std::string ErrorInfo;
383 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
385 if (!ErrorInfo.empty()) {
386 errs() << ErrorInfo << '\n';
391 // If the output is set to be emitted to standard out, and standard out is a
392 // console, print out a warning message and refuse to do it. We don't
393 // impress anyone by spewing tons of binary goo to a terminal.
394 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
395 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
398 if (PassPipeline.getNumOccurrences() > 0) {
399 OutputKind OK = OK_NoOutput;
401 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
403 VerifierKind VK = VK_VerifyInAndOut;
407 VK = VK_VerifyEachPass;
409 // The user has asked to use the new pass manager and provided a pipeline
410 // string. Hand off the rest of the functionality to the new code for that
412 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
418 // Create a PassManager to hold and optimize the collection of passes we are
423 // Add an appropriate TargetLibraryInfo pass for the module's triple.
424 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
426 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
427 if (DisableSimplifyLibCalls)
428 TLI->disableAllFunctions();
431 // Add an appropriate DataLayout instance for this module.
432 const DataLayout *DL = M.get()->getDataLayout();
433 if (!DL && !DefaultDataLayout.empty())
434 DL = new DataLayout(DefaultDataLayout);
437 Passes.add(new DataLayoutPass(*DL));
439 Triple ModuleTriple(M->getTargetTriple());
440 TargetMachine *Machine = 0;
441 if (ModuleTriple.getArch())
442 Machine = GetTargetMachine(Triple(ModuleTriple));
443 OwningPtr<TargetMachine> TM(Machine);
445 // Add internal analysis passes from the target machine.
447 TM->addAnalysisPasses(Passes);
449 OwningPtr<FunctionPassManager> FPasses;
450 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
451 FPasses.reset(new FunctionPassManager(M.get()));
453 FPasses->add(new DataLayoutPass(*DL));
455 TM->addAnalysisPasses(*FPasses);
459 if (PrintBreakpoints) {
460 // Default to standard output.
462 if (OutputFilename.empty())
463 OutputFilename = "-";
465 std::string ErrorInfo;
466 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
468 if (!ErrorInfo.empty()) {
469 errs() << ErrorInfo << '\n';
473 Passes.add(createBreakpointPrinter(Out->os()));
477 // If the -strip-debug command line option was specified, add it. If
478 // -std-compile-opts was also specified, it will handle StripDebug.
479 if (StripDebug && !StandardCompileOpts)
480 addPass(Passes, createStripSymbolsPass(true));
482 // Create a new optimization pass for each one specified on the command line
483 for (unsigned i = 0; i < PassList.size(); ++i) {
484 // Check to see if -std-compile-opts was specified before this option. If
486 if (StandardCompileOpts &&
487 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
488 AddStandardCompilePasses(Passes);
489 StandardCompileOpts = false;
492 if (StandardLinkOpts &&
493 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
494 AddStandardLinkPasses(Passes);
495 StandardLinkOpts = false;
498 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
499 AddOptimizationPasses(Passes, *FPasses, 1, 0);
503 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
504 AddOptimizationPasses(Passes, *FPasses, 2, 0);
508 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
509 AddOptimizationPasses(Passes, *FPasses, 2, 1);
513 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
514 AddOptimizationPasses(Passes, *FPasses, 2, 2);
518 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
519 AddOptimizationPasses(Passes, *FPasses, 3, 0);
523 const PassInfo *PassInf = PassList[i];
525 if (PassInf->getTargetMachineCtor())
526 P = PassInf->getTargetMachineCtor()(TM.get());
527 else if (PassInf->getNormalCtor())
528 P = PassInf->getNormalCtor()();
530 errs() << argv[0] << ": cannot create pass: "
531 << PassInf->getPassName() << "\n";
533 PassKind Kind = P->getPassKind();
539 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
542 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
545 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
548 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
550 case PT_CallGraphSCC:
551 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
554 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
561 Passes.add(createPrintModulePass(errs()));
564 // If -std-compile-opts was specified at the end of the pass list, add them.
565 if (StandardCompileOpts) {
566 AddStandardCompilePasses(Passes);
567 StandardCompileOpts = false;
570 if (StandardLinkOpts) {
571 AddStandardLinkPasses(Passes);
572 StandardLinkOpts = false;
576 AddOptimizationPasses(Passes, *FPasses, 1, 0);
579 AddOptimizationPasses(Passes, *FPasses, 2, 0);
582 AddOptimizationPasses(Passes, *FPasses, 2, 1);
585 AddOptimizationPasses(Passes, *FPasses, 2, 2);
588 AddOptimizationPasses(Passes, *FPasses, 3, 0);
590 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
591 FPasses->doInitialization();
592 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
594 FPasses->doFinalization();
597 // Check that the module is well formed on completion of optimization
598 if (!NoVerify && !VerifyEach)
599 Passes.add(createVerifierPass());
601 // Write bitcode or assembly to the output as the last step...
602 if (!NoOutput && !AnalyzeOnly) {
604 Passes.add(createPrintModulePass(Out->os()));
606 Passes.add(createBitcodeWriterPass(Out->os()));
609 // Before executing passes, print the final values of the LLVM options.
610 cl::PrintOptionValues();
612 // Now that we have all of the passes ready, run them.
613 Passes.run(*M.get());
616 if (!NoOutput || PrintBreakpoints)