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/IR/DataLayout.h"
26 #include "llvm/IR/IRPrintingPasses.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/LegacyPassNameParser.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/LinkAllIR.h"
34 #include "llvm/LinkAllPasses.h"
35 #include "llvm/MC/SubtargetFeature.h"
36 #include "llvm/PassManager.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/PluginLoader.h"
41 #include "llvm/Support/PrettyStackTrace.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/SystemUtils.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Target/TargetLibraryInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 using namespace opt_tool;
56 // The OptimizationList is automatically populated with registered Passes by the
59 static cl::list<const PassInfo*, bool, PassNameParser>
60 PassList(cl::desc("Optimizations available:"));
62 // This flag specifies a textual description of the optimization pass pipeline
63 // to run over the module. This flag switches opt to use the new pass manager
64 // infrastructure, completely disabling all of the flags specific to the old
66 static cl::opt<std::string> PassPipeline(
68 cl::desc("A textual description of the pass pipeline for optimizing"),
71 // Other command line options...
73 static cl::opt<std::string>
74 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
75 cl::init("-"), cl::value_desc("filename"));
77 static cl::opt<std::string>
78 OutputFilename("o", cl::desc("Override output filename"),
79 cl::value_desc("filename"));
82 Force("f", cl::desc("Enable binary output on terminals"));
85 PrintEachXForm("p", cl::desc("Print module after each transformation"));
88 NoOutput("disable-output",
89 cl::desc("Do not write result bitcode file"), cl::Hidden);
92 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
95 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
98 VerifyEach("verify-each", cl::desc("Verify after each transform"));
101 StripDebug("strip-debug",
102 cl::desc("Strip debugger symbol info from translation unit"));
105 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
108 DisableOptimizations("disable-opt",
109 cl::desc("Do not run any optimization passes"));
112 StandardCompileOpts("std-compile-opts",
113 cl::desc("Include the standard compile time optimizations"));
116 StandardLinkOpts("std-link-opts",
117 cl::desc("Include the standard link time optimizations"));
121 cl::desc("Optimization level 1. Similar to clang -O1"));
125 cl::desc("Optimization level 2. Similar to clang -O2"));
129 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
133 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
137 cl::desc("Optimization level 3. Similar to clang -O3"));
139 static cl::opt<std::string>
140 TargetTriple("mtriple", cl::desc("Override target triple for module"));
143 UnitAtATime("funit-at-a-time",
144 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
148 DisableLoopUnrolling("disable-loop-unrolling",
149 cl::desc("Disable loop unrolling in all relevant passes"),
152 DisableLoopVectorization("disable-loop-vectorization",
153 cl::desc("Disable the loop vectorization pass"),
157 DisableSLPVectorization("disable-slp-vectorization",
158 cl::desc("Disable the slp vectorization pass"),
163 DisableSimplifyLibCalls("disable-simplify-libcalls",
164 cl::desc("Disable simplify-libcalls"));
167 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
170 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
173 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
176 PrintBreakpoints("print-breakpoints-for-testing",
177 cl::desc("Print select breakpoints location for testing"));
179 static cl::opt<std::string>
180 DefaultDataLayout("default-data-layout",
181 cl::desc("data layout string to use if not specified by module"),
182 cl::value_desc("layout-string"), cl::init(""));
186 static inline void addPass(PassManagerBase &PM, Pass *P) {
187 // Add the pass to the pass manager...
190 // If we are verifying all of the intermediate steps, add the verifier...
192 PM.add(createVerifierPass());
193 PM.add(createDebugInfoVerifierPass());
197 /// This routine adds optimization passes based on selected optimization level,
200 /// OptLevel - Optimization Level
201 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
202 unsigned OptLevel, unsigned SizeLevel) {
203 FPM.add(createVerifierPass()); // Verify that input is correct
204 MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct
206 PassManagerBuilder Builder;
207 Builder.OptLevel = OptLevel;
208 Builder.SizeLevel = SizeLevel;
212 } else if (OptLevel > 1) {
213 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
215 Builder.Inliner = createAlwaysInlinerPass();
217 Builder.DisableUnitAtATime = !UnitAtATime;
218 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
219 DisableLoopUnrolling : OptLevel == 0;
221 // This is final, unless there is a #pragma vectorize enable
222 if (DisableLoopVectorization)
223 Builder.LoopVectorize = false;
224 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
225 else if (!Builder.LoopVectorize)
226 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
228 // When #pragma vectorize is on for SLP, do the same as above
229 Builder.SLPVectorize =
230 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
232 Builder.populateFunctionPassManager(FPM);
233 Builder.populateModulePassManager(MPM);
236 static void AddStandardCompilePasses(PassManagerBase &PM) {
237 PM.add(createVerifierPass()); // Verify that input is correct
239 // If the -strip-debug command line option was specified, do it.
241 addPass(PM, createStripSymbolsPass(true));
243 // Verify debug info only after it's (possibly) stripped.
244 PM.add(createDebugInfoVerifierPass());
246 if (DisableOptimizations) return;
248 // -std-compile-opts adds the same module passes as -O3.
249 PassManagerBuilder Builder;
251 Builder.Inliner = createFunctionInliningPass();
252 Builder.OptLevel = 3;
253 Builder.populateModulePassManager(PM);
256 static void AddStandardLinkPasses(PassManagerBase &PM) {
257 PM.add(createVerifierPass()); // Verify that input is correct
259 // If the -strip-debug command line option was specified, do it.
261 addPass(PM, createStripSymbolsPass(true));
263 // Verify debug info only after it's (possibly) stripped.
264 PM.add(createDebugInfoVerifierPass());
266 if (DisableOptimizations) return;
268 PassManagerBuilder Builder;
270 Builder.Inliner = createFunctionInliningPass();
271 Builder.populateLTOPassManager(PM);
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 #ifdef LINK_POLLY_INTO_TOOLS
316 void initializePollyPasses(llvm::PassRegistry &Registry);
320 //===----------------------------------------------------------------------===//
323 int main(int argc, char **argv) {
324 sys::PrintStackTraceOnErrorSignal();
325 llvm::PrettyStackTraceProgram X(argc, argv);
327 // Enable debug stream buffering.
328 EnableDebugBuffering = true;
330 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
331 LLVMContext &Context = getGlobalContext();
333 InitializeAllTargets();
334 InitializeAllTargetMCs();
335 InitializeAllAsmPrinters();
338 PassRegistry &Registry = *PassRegistry::getPassRegistry();
339 initializeCore(Registry);
340 initializeDebugIRPass(Registry);
341 initializeScalarOpts(Registry);
342 initializeObjCARCOpts(Registry);
343 initializeVectorization(Registry);
344 initializeIPO(Registry);
345 initializeAnalysis(Registry);
346 initializeIPA(Registry);
347 initializeTransformUtils(Registry);
348 initializeInstCombine(Registry);
349 initializeInstrumentation(Registry);
350 initializeTarget(Registry);
351 // For codegen passes, only passes that do IR to IR transformation are
353 initializeCodeGenPreparePass(Registry);
354 initializeAtomicExpandLoadLinkedPass(Registry);
356 #ifdef LINK_POLLY_INTO_TOOLS
357 polly::initializePollyPasses(Registry);
360 cl::ParseCommandLineOptions(argc, argv,
361 "llvm .bc -> .bc modular optimizer and analysis printer\n");
363 if (AnalyzeOnly && NoOutput) {
364 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
370 // Load the input module...
371 std::unique_ptr<Module> M;
372 M.reset(ParseIRFile(InputFilename, Err, Context));
375 Err.print(argv[0], errs());
379 // If we are supposed to override the target triple, do so now.
380 if (!TargetTriple.empty())
381 M->setTargetTriple(Triple::normalize(TargetTriple));
383 // Figure out what stream we are supposed to write to...
384 std::unique_ptr<tool_output_file> Out;
386 if (!OutputFilename.empty())
387 errs() << "WARNING: The -o (output filename) option is ignored when\n"
388 "the --disable-output option is used.\n";
390 // Default to standard output.
391 if (OutputFilename.empty())
392 OutputFilename = "-";
394 std::string ErrorInfo;
395 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
397 if (!ErrorInfo.empty()) {
398 errs() << ErrorInfo << '\n';
403 // If the output is set to be emitted to standard out, and standard out is a
404 // console, print out a warning message and refuse to do it. We don't
405 // impress anyone by spewing tons of binary goo to a terminal.
406 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
407 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
410 if (PassPipeline.getNumOccurrences() > 0) {
411 OutputKind OK = OK_NoOutput;
413 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
415 VerifierKind VK = VK_VerifyInAndOut;
419 VK = VK_VerifyEachPass;
421 // The user has asked to use the new pass manager and provided a pipeline
422 // string. Hand off the rest of the functionality to the new code for that
424 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
430 // Create a PassManager to hold and optimize the collection of passes we are
435 // Add an appropriate TargetLibraryInfo pass for the module's triple.
436 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
438 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
439 if (DisableSimplifyLibCalls)
440 TLI->disableAllFunctions();
443 // Add an appropriate DataLayout instance for this module.
444 const DataLayout *DL = M.get()->getDataLayout();
445 if (!DL && !DefaultDataLayout.empty()) {
446 M->setDataLayout(DefaultDataLayout);
447 DL = M.get()->getDataLayout();
451 Passes.add(new DataLayoutPass(M.get()));
453 Triple ModuleTriple(M->getTargetTriple());
454 TargetMachine *Machine = nullptr;
455 if (ModuleTriple.getArch())
456 Machine = GetTargetMachine(Triple(ModuleTriple));
457 std::unique_ptr<TargetMachine> TM(Machine);
459 // Add internal analysis passes from the target machine.
461 TM->addAnalysisPasses(Passes);
463 std::unique_ptr<FunctionPassManager> FPasses;
464 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
465 FPasses.reset(new FunctionPassManager(M.get()));
467 FPasses->add(new DataLayoutPass(M.get()));
469 TM->addAnalysisPasses(*FPasses);
473 if (PrintBreakpoints) {
474 // Default to standard output.
476 if (OutputFilename.empty())
477 OutputFilename = "-";
479 std::string ErrorInfo;
480 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
482 if (!ErrorInfo.empty()) {
483 errs() << ErrorInfo << '\n';
487 Passes.add(createBreakpointPrinter(Out->os()));
491 // If the -strip-debug command line option was specified, add it. If
492 // -std-compile-opts was also specified, it will handle StripDebug.
493 if (StripDebug && !StandardCompileOpts)
494 addPass(Passes, createStripSymbolsPass(true));
496 // Create a new optimization pass for each one specified on the command line
497 for (unsigned i = 0; i < PassList.size(); ++i) {
498 // Check to see if -std-compile-opts was specified before this option. If
500 if (StandardCompileOpts &&
501 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
502 AddStandardCompilePasses(Passes);
503 StandardCompileOpts = false;
506 if (StandardLinkOpts &&
507 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
508 AddStandardLinkPasses(Passes);
509 StandardLinkOpts = false;
512 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
513 AddOptimizationPasses(Passes, *FPasses, 1, 0);
517 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
518 AddOptimizationPasses(Passes, *FPasses, 2, 0);
522 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
523 AddOptimizationPasses(Passes, *FPasses, 2, 1);
527 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
528 AddOptimizationPasses(Passes, *FPasses, 2, 2);
532 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
533 AddOptimizationPasses(Passes, *FPasses, 3, 0);
537 const PassInfo *PassInf = PassList[i];
539 if (PassInf->getTargetMachineCtor())
540 P = PassInf->getTargetMachineCtor()(TM.get());
541 else if (PassInf->getNormalCtor())
542 P = PassInf->getNormalCtor()();
544 errs() << argv[0] << ": cannot create pass: "
545 << PassInf->getPassName() << "\n";
547 PassKind Kind = P->getPassKind();
553 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
556 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
559 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
562 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
564 case PT_CallGraphSCC:
565 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
568 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
575 Passes.add(createPrintModulePass(errs()));
578 // If -std-compile-opts was specified at the end of the pass list, add them.
579 if (StandardCompileOpts) {
580 AddStandardCompilePasses(Passes);
581 StandardCompileOpts = false;
584 if (StandardLinkOpts) {
585 AddStandardLinkPasses(Passes);
586 StandardLinkOpts = false;
590 AddOptimizationPasses(Passes, *FPasses, 1, 0);
593 AddOptimizationPasses(Passes, *FPasses, 2, 0);
596 AddOptimizationPasses(Passes, *FPasses, 2, 1);
599 AddOptimizationPasses(Passes, *FPasses, 2, 2);
602 AddOptimizationPasses(Passes, *FPasses, 3, 0);
604 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
605 FPasses->doInitialization();
606 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
608 FPasses->doFinalization();
611 // Check that the module is well formed on completion of optimization
612 if (!NoVerify && !VerifyEach) {
613 Passes.add(createVerifierPass());
614 Passes.add(createDebugInfoVerifierPass());
617 // Write bitcode or assembly to the output as the last step...
618 if (!NoOutput && !AnalyzeOnly) {
620 Passes.add(createPrintModulePass(Out->os()));
622 Passes.add(createBitcodeWriterPass(Out->os()));
625 // Before executing passes, print the final values of the LLVM options.
626 cl::PrintOptionValues();
628 // Now that we have all of the passes ready, run them.
629 Passes.run(*M.get());
632 if (!NoOutput || PrintBreakpoints)