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/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/CodeGen/CommandFlags.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassNameParser.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/LinkAllIR.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/IR/LegacyPassManager.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/PluginLoader.h"
43 #include "llvm/Support/PrettyStackTrace.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/SystemUtils.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 using namespace opt_tool;
57 // The OptimizationList is automatically populated with registered Passes by the
60 static cl::list<const PassInfo*, bool, PassNameParser>
61 PassList(cl::desc("Optimizations available:"));
63 // This flag specifies a textual description of the optimization pass pipeline
64 // to run over the module. This flag switches opt to use the new pass manager
65 // infrastructure, completely disabling all of the flags specific to the old
67 static cl::opt<std::string> PassPipeline(
69 cl::desc("A textual description of the pass pipeline for optimizing"),
72 // Other command line options...
74 static cl::opt<std::string>
75 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
76 cl::init("-"), cl::value_desc("filename"));
78 static cl::opt<std::string>
79 OutputFilename("o", cl::desc("Override output filename"),
80 cl::value_desc("filename"));
83 Force("f", cl::desc("Enable binary output on terminals"));
86 PrintEachXForm("p", cl::desc("Print module after each transformation"));
89 NoOutput("disable-output",
90 cl::desc("Do not write result bitcode file"), cl::Hidden);
93 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
96 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
99 VerifyEach("verify-each", cl::desc("Verify after each transform"));
102 StripDebug("strip-debug",
103 cl::desc("Strip debugger symbol info from translation unit"));
106 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
109 DisableOptimizations("disable-opt",
110 cl::desc("Do not run any optimization passes"));
113 StandardLinkOpts("std-link-opts",
114 cl::desc("Include the standard link time optimizations"));
118 cl::desc("Optimization level 1. Similar to clang -O1"));
122 cl::desc("Optimization level 2. Similar to clang -O2"));
126 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
130 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
134 cl::desc("Optimization level 3. Similar to clang -O3"));
136 static cl::opt<std::string>
137 TargetTriple("mtriple", cl::desc("Override target triple for module"));
140 UnitAtATime("funit-at-a-time",
141 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
145 DisableLoopUnrolling("disable-loop-unrolling",
146 cl::desc("Disable loop unrolling in all relevant passes"),
149 DisableLoopVectorization("disable-loop-vectorization",
150 cl::desc("Disable the loop vectorization pass"),
154 DisableSLPVectorization("disable-slp-vectorization",
155 cl::desc("Disable the slp vectorization pass"),
160 DisableSimplifyLibCalls("disable-simplify-libcalls",
161 cl::desc("Disable simplify-libcalls"));
164 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
167 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
170 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
173 PrintBreakpoints("print-breakpoints-for-testing",
174 cl::desc("Print select breakpoints location for testing"));
176 static cl::opt<std::string>
177 DefaultDataLayout("default-data-layout",
178 cl::desc("data layout string to use if not specified by module"),
179 cl::value_desc("layout-string"), cl::init(""));
183 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
184 // Add the pass to the pass manager...
187 // If we are verifying all of the intermediate steps, add the verifier...
189 PM.add(createVerifierPass());
190 PM.add(createDebugInfoVerifierPass());
194 /// This routine adds optimization passes based on selected optimization level,
197 /// OptLevel - Optimization Level
198 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
199 legacy::FunctionPassManager &FPM,
200 unsigned OptLevel, unsigned SizeLevel) {
201 FPM.add(createVerifierPass()); // Verify that input is correct
202 MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct
204 PassManagerBuilder Builder;
205 Builder.OptLevel = OptLevel;
206 Builder.SizeLevel = SizeLevel;
210 } else if (OptLevel > 1) {
211 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
213 Builder.Inliner = createAlwaysInlinerPass();
215 Builder.DisableUnitAtATime = !UnitAtATime;
216 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
217 DisableLoopUnrolling : OptLevel == 0;
219 // This is final, unless there is a #pragma vectorize enable
220 if (DisableLoopVectorization)
221 Builder.LoopVectorize = false;
222 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
223 else if (!Builder.LoopVectorize)
224 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
226 // When #pragma vectorize is on for SLP, do the same as above
227 Builder.SLPVectorize =
228 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
230 Builder.populateFunctionPassManager(FPM);
231 Builder.populateModulePassManager(MPM);
234 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
235 PassManagerBuilder Builder;
236 Builder.VerifyInput = true;
237 Builder.StripDebug = StripDebug;
238 if (DisableOptimizations)
239 Builder.OptLevel = 0;
242 Builder.Inliner = createFunctionInliningPass();
243 Builder.populateLTOPassManager(PM);
246 //===----------------------------------------------------------------------===//
247 // CodeGen-related helper functions.
250 CodeGenOpt::Level GetCodeGenOptLevel() {
252 return CodeGenOpt::Less;
254 return CodeGenOpt::Default;
256 return CodeGenOpt::Aggressive;
257 return CodeGenOpt::None;
260 // Returns the TargetMachine instance or zero if no triple is provided.
261 static TargetMachine* GetTargetMachine(Triple TheTriple) {
263 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
265 // Some modules don't specify a triple, and this is okay.
270 // Package up features to be passed to target/subtarget
271 std::string FeaturesStr;
273 SubtargetFeatures Features;
274 for (unsigned i = 0; i != MAttrs.size(); ++i)
275 Features.AddFeature(MAttrs[i]);
276 FeaturesStr = Features.getString();
279 return TheTarget->createTargetMachine(TheTriple.getTriple(),
281 InitTargetOptionsFromCodeGenFlags(),
283 GetCodeGenOptLevel());
286 #ifdef LINK_POLLY_INTO_TOOLS
288 void initializePollyPasses(llvm::PassRegistry &Registry);
292 //===----------------------------------------------------------------------===//
295 int main(int argc, char **argv) {
296 sys::PrintStackTraceOnErrorSignal();
297 llvm::PrettyStackTraceProgram X(argc, argv);
299 // Enable debug stream buffering.
300 EnableDebugBuffering = true;
302 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
303 LLVMContext &Context = getGlobalContext();
305 InitializeAllTargets();
306 InitializeAllTargetMCs();
307 InitializeAllAsmPrinters();
310 PassRegistry &Registry = *PassRegistry::getPassRegistry();
311 initializeCore(Registry);
312 initializeScalarOpts(Registry);
313 initializeObjCARCOpts(Registry);
314 initializeVectorization(Registry);
315 initializeIPO(Registry);
316 initializeAnalysis(Registry);
317 initializeIPA(Registry);
318 initializeTransformUtils(Registry);
319 initializeInstCombine(Registry);
320 initializeInstrumentation(Registry);
321 initializeTarget(Registry);
322 // For codegen passes, only passes that do IR to IR transformation are
324 initializeCodeGenPreparePass(Registry);
325 initializeAtomicExpandPass(Registry);
326 initializeRewriteSymbolsPass(Registry);
327 initializeWinEHPreparePass(Registry);
329 #ifdef LINK_POLLY_INTO_TOOLS
330 polly::initializePollyPasses(Registry);
333 cl::ParseCommandLineOptions(argc, argv,
334 "llvm .bc -> .bc modular optimizer and analysis printer\n");
336 if (AnalyzeOnly && NoOutput) {
337 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
343 // Load the input module...
344 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
347 Err.print(argv[0], errs());
351 // If we are supposed to override the target triple, do so now.
352 if (!TargetTriple.empty())
353 M->setTargetTriple(Triple::normalize(TargetTriple));
355 // Figure out what stream we are supposed to write to...
356 std::unique_ptr<tool_output_file> Out;
358 if (!OutputFilename.empty())
359 errs() << "WARNING: The -o (output filename) option is ignored when\n"
360 "the --disable-output option is used.\n";
362 // Default to standard output.
363 if (OutputFilename.empty())
364 OutputFilename = "-";
367 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
369 errs() << EC.message() << '\n';
374 Triple ModuleTriple(M->getTargetTriple());
375 TargetMachine *Machine = nullptr;
376 if (ModuleTriple.getArch())
377 Machine = GetTargetMachine(ModuleTriple);
378 std::unique_ptr<TargetMachine> TM(Machine);
380 // If the output is set to be emitted to standard out, and standard out is a
381 // console, print out a warning message and refuse to do it. We don't
382 // impress anyone by spewing tons of binary goo to a terminal.
383 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
384 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
387 if (PassPipeline.getNumOccurrences() > 0) {
388 OutputKind OK = OK_NoOutput;
390 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
392 VerifierKind VK = VK_VerifyInAndOut;
396 VK = VK_VerifyEachPass;
398 // The user has asked to use the new pass manager and provided a pipeline
399 // string. Hand off the rest of the functionality to the new code for that
401 return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
402 PassPipeline, OK, VK)
407 // Create a PassManager to hold and optimize the collection of passes we are
410 legacy::PassManager Passes;
412 // Add an appropriate TargetLibraryInfo pass for the module's triple.
413 TargetLibraryInfoImpl TLII(ModuleTriple);
415 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
416 if (DisableSimplifyLibCalls)
417 TLII.disableAllFunctions();
418 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
420 // Add an appropriate DataLayout instance for this module.
421 const DataLayout *DL = M->getDataLayout();
422 if (!DL && !DefaultDataLayout.empty()) {
423 M->setDataLayout(DefaultDataLayout);
424 DL = M->getDataLayout();
428 Passes.add(new DataLayoutPass());
430 // Add internal analysis passes from the target machine.
431 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
432 : TargetIRAnalysis()));
434 std::unique_ptr<legacy::FunctionPassManager> FPasses;
435 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
436 FPasses.reset(new legacy::FunctionPassManager(M.get()));
438 FPasses->add(new DataLayoutPass());
439 FPasses->add(createTargetTransformInfoWrapperPass(
440 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
443 if (PrintBreakpoints) {
444 // Default to standard output.
446 if (OutputFilename.empty())
447 OutputFilename = "-";
450 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
453 errs() << EC.message() << '\n';
457 Passes.add(createBreakpointPrinter(Out->os()));
461 // If the -strip-debug command line option was specified, add it.
463 addPass(Passes, createStripSymbolsPass(true));
465 // Create a new optimization pass for each one specified on the command line
466 for (unsigned i = 0; i < PassList.size(); ++i) {
467 if (StandardLinkOpts &&
468 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
469 AddStandardLinkPasses(Passes);
470 StandardLinkOpts = false;
473 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
474 AddOptimizationPasses(Passes, *FPasses, 1, 0);
478 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
479 AddOptimizationPasses(Passes, *FPasses, 2, 0);
483 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
484 AddOptimizationPasses(Passes, *FPasses, 2, 1);
488 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
489 AddOptimizationPasses(Passes, *FPasses, 2, 2);
493 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
494 AddOptimizationPasses(Passes, *FPasses, 3, 0);
498 const PassInfo *PassInf = PassList[i];
500 if (PassInf->getTargetMachineCtor())
501 P = PassInf->getTargetMachineCtor()(TM.get());
502 else if (PassInf->getNormalCtor())
503 P = PassInf->getNormalCtor()();
505 errs() << argv[0] << ": cannot create pass: "
506 << PassInf->getPassName() << "\n";
508 PassKind Kind = P->getPassKind();
514 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
517 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
520 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
523 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
525 case PT_CallGraphSCC:
526 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
529 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
536 Passes.add(createPrintModulePass(errs()));
539 if (StandardLinkOpts) {
540 AddStandardLinkPasses(Passes);
541 StandardLinkOpts = false;
545 AddOptimizationPasses(Passes, *FPasses, 1, 0);
548 AddOptimizationPasses(Passes, *FPasses, 2, 0);
551 AddOptimizationPasses(Passes, *FPasses, 2, 1);
554 AddOptimizationPasses(Passes, *FPasses, 2, 2);
557 AddOptimizationPasses(Passes, *FPasses, 3, 0);
559 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
560 FPasses->doInitialization();
561 for (Function &F : *M)
563 FPasses->doFinalization();
566 // Check that the module is well formed on completion of optimization
567 if (!NoVerify && !VerifyEach) {
568 Passes.add(createVerifierPass());
569 Passes.add(createDebugInfoVerifierPass());
572 // Write bitcode or assembly to the output as the last step...
573 if (!NoOutput && !AnalyzeOnly) {
575 Passes.add(createPrintModulePass(Out->os()));
577 Passes.add(createBitcodeWriterPass(Out->os()));
580 // Before executing passes, print the final values of the LLVM options.
581 cl::PrintOptionValues();
583 // Now that we have all of the passes ready, run them.
587 if (!NoOutput || PrintBreakpoints)