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/ManagedStatic.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 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 if (DisableOptimizations) return;
245 // -std-compile-opts adds the same module passes as -O3.
246 PassManagerBuilder Builder;
248 Builder.Inliner = createFunctionInliningPass();
249 Builder.OptLevel = 3;
250 Builder.populateModulePassManager(PM);
253 static void AddStandardLinkPasses(PassManagerBase &PM) {
254 PM.add(createVerifierPass()); // Verify that input is correct
256 // If the -strip-debug command line option was specified, do it.
258 addPass(PM, createStripSymbolsPass(true));
260 if (DisableOptimizations) return;
262 PassManagerBuilder Builder;
263 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
264 /*RunInliner=*/ !DisableInline);
267 //===----------------------------------------------------------------------===//
268 // CodeGen-related helper functions.
271 CodeGenOpt::Level GetCodeGenOptLevel() {
273 return CodeGenOpt::Less;
275 return CodeGenOpt::Default;
277 return CodeGenOpt::Aggressive;
278 return CodeGenOpt::None;
281 // Returns the TargetMachine instance or zero if no triple is provided.
282 static TargetMachine* GetTargetMachine(Triple TheTriple) {
284 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
286 // Some modules don't specify a triple, and this is okay.
291 // Package up features to be passed to target/subtarget
292 std::string FeaturesStr;
294 SubtargetFeatures Features;
295 for (unsigned i = 0; i != MAttrs.size(); ++i)
296 Features.AddFeature(MAttrs[i]);
297 FeaturesStr = Features.getString();
300 return TheTarget->createTargetMachine(TheTriple.getTriple(),
302 InitTargetOptionsFromCodeGenFlags(),
304 GetCodeGenOptLevel());
307 #ifdef LINK_POLLY_INTO_TOOLS
309 void initializePollyPasses(llvm::PassRegistry &Registry);
313 //===----------------------------------------------------------------------===//
316 int main(int argc, char **argv) {
317 sys::PrintStackTraceOnErrorSignal();
318 llvm::PrettyStackTraceProgram X(argc, argv);
320 // Enable debug stream buffering.
321 EnableDebugBuffering = true;
323 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
324 LLVMContext &Context = getGlobalContext();
326 InitializeAllTargets();
327 InitializeAllTargetMCs();
330 PassRegistry &Registry = *PassRegistry::getPassRegistry();
331 initializeCore(Registry);
332 initializeDebugIRPass(Registry);
333 initializeScalarOpts(Registry);
334 initializeObjCARCOpts(Registry);
335 initializeVectorization(Registry);
336 initializeIPO(Registry);
337 initializeAnalysis(Registry);
338 initializeIPA(Registry);
339 initializeTransformUtils(Registry);
340 initializeInstCombine(Registry);
341 initializeInstrumentation(Registry);
342 initializeTarget(Registry);
343 // For codegen passes, only passes that do IR to IR transformation are
344 // supported. For now, just add CodeGenPrepare.
345 initializeCodeGenPreparePass(Registry);
347 #ifdef LINK_POLLY_INTO_TOOLS
348 polly::initializePollyPasses(Registry);
351 cl::ParseCommandLineOptions(argc, argv,
352 "llvm .bc -> .bc modular optimizer and analysis printer\n");
354 if (AnalyzeOnly && NoOutput) {
355 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
361 // Load the input module...
362 std::unique_ptr<Module> M;
363 M.reset(ParseIRFile(InputFilename, Err, Context));
366 Err.print(argv[0], errs());
370 // If we are supposed to override the target triple, do so now.
371 if (!TargetTriple.empty())
372 M->setTargetTriple(Triple::normalize(TargetTriple));
374 // Figure out what stream we are supposed to write to...
375 std::unique_ptr<tool_output_file> Out;
377 if (!OutputFilename.empty())
378 errs() << "WARNING: The -o (output filename) option is ignored when\n"
379 "the --disable-output option is used.\n";
381 // Default to standard output.
382 if (OutputFilename.empty())
383 OutputFilename = "-";
385 std::string ErrorInfo;
386 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
388 if (!ErrorInfo.empty()) {
389 errs() << ErrorInfo << '\n';
394 // If the output is set to be emitted to standard out, and standard out is a
395 // console, print out a warning message and refuse to do it. We don't
396 // impress anyone by spewing tons of binary goo to a terminal.
397 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
398 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
401 if (PassPipeline.getNumOccurrences() > 0) {
402 OutputKind OK = OK_NoOutput;
404 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
406 VerifierKind VK = VK_VerifyInAndOut;
410 VK = VK_VerifyEachPass;
412 // The user has asked to use the new pass manager and provided a pipeline
413 // string. Hand off the rest of the functionality to the new code for that
415 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
421 // Create a PassManager to hold and optimize the collection of passes we are
426 // Add an appropriate TargetLibraryInfo pass for the module's triple.
427 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
429 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
430 if (DisableSimplifyLibCalls)
431 TLI->disableAllFunctions();
434 // Add an appropriate DataLayout instance for this module.
435 const DataLayout *DL = M.get()->getDataLayout();
436 if (!DL && !DefaultDataLayout.empty()) {
437 M->setDataLayout(DefaultDataLayout);
438 DL = M.get()->getDataLayout();
442 Passes.add(new DataLayoutPass(M.get()));
444 Triple ModuleTriple(M->getTargetTriple());
445 TargetMachine *Machine = 0;
446 if (ModuleTriple.getArch())
447 Machine = GetTargetMachine(Triple(ModuleTriple));
448 std::unique_ptr<TargetMachine> TM(Machine);
450 // Add internal analysis passes from the target machine.
452 TM->addAnalysisPasses(Passes);
454 std::unique_ptr<FunctionPassManager> FPasses;
455 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
456 FPasses.reset(new FunctionPassManager(M.get()));
458 FPasses->add(new DataLayoutPass(M.get()));
460 TM->addAnalysisPasses(*FPasses);
464 if (PrintBreakpoints) {
465 // Default to standard output.
467 if (OutputFilename.empty())
468 OutputFilename = "-";
470 std::string ErrorInfo;
471 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
473 if (!ErrorInfo.empty()) {
474 errs() << ErrorInfo << '\n';
478 Passes.add(createBreakpointPrinter(Out->os()));
482 // If the -strip-debug command line option was specified, add it. If
483 // -std-compile-opts was also specified, it will handle StripDebug.
484 if (StripDebug && !StandardCompileOpts)
485 addPass(Passes, createStripSymbolsPass(true));
487 // Create a new optimization pass for each one specified on the command line
488 for (unsigned i = 0; i < PassList.size(); ++i) {
489 // Check to see if -std-compile-opts was specified before this option. If
491 if (StandardCompileOpts &&
492 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
493 AddStandardCompilePasses(Passes);
494 StandardCompileOpts = false;
497 if (StandardLinkOpts &&
498 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
499 AddStandardLinkPasses(Passes);
500 StandardLinkOpts = false;
503 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
504 AddOptimizationPasses(Passes, *FPasses, 1, 0);
508 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
509 AddOptimizationPasses(Passes, *FPasses, 2, 0);
513 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
514 AddOptimizationPasses(Passes, *FPasses, 2, 1);
518 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
519 AddOptimizationPasses(Passes, *FPasses, 2, 2);
523 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
524 AddOptimizationPasses(Passes, *FPasses, 3, 0);
528 const PassInfo *PassInf = PassList[i];
530 if (PassInf->getTargetMachineCtor())
531 P = PassInf->getTargetMachineCtor()(TM.get());
532 else if (PassInf->getNormalCtor())
533 P = PassInf->getNormalCtor()();
535 errs() << argv[0] << ": cannot create pass: "
536 << PassInf->getPassName() << "\n";
538 PassKind Kind = P->getPassKind();
544 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
547 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
550 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
553 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
555 case PT_CallGraphSCC:
556 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
559 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
566 Passes.add(createPrintModulePass(errs()));
569 // If -std-compile-opts was specified at the end of the pass list, add them.
570 if (StandardCompileOpts) {
571 AddStandardCompilePasses(Passes);
572 StandardCompileOpts = false;
575 if (StandardLinkOpts) {
576 AddStandardLinkPasses(Passes);
577 StandardLinkOpts = false;
581 AddOptimizationPasses(Passes, *FPasses, 1, 0);
584 AddOptimizationPasses(Passes, *FPasses, 2, 0);
587 AddOptimizationPasses(Passes, *FPasses, 2, 1);
590 AddOptimizationPasses(Passes, *FPasses, 2, 2);
593 AddOptimizationPasses(Passes, *FPasses, 3, 0);
595 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
596 FPasses->doInitialization();
597 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
599 FPasses->doFinalization();
602 // Check that the module is well formed on completion of optimization
603 if (!NoVerify && !VerifyEach)
604 Passes.add(createVerifierPass());
606 // Write bitcode or assembly to the output as the last step...
607 if (!NoOutput && !AnalyzeOnly) {
609 Passes.add(createPrintModulePass(Out->os()));
611 Passes.add(createBitcodeWriterPass(Out->os()));
614 // Before executing passes, print the final values of the LLVM options.
615 cl::PrintOptionValues();
617 // Now that we have all of the passes ready, run them.
618 Passes.run(*M.get());
621 if (!NoOutput || PrintBreakpoints)