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/PassManager.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(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(PassManagerBase &MPM,FunctionPassManager &FPM,
199 unsigned OptLevel, unsigned SizeLevel) {
200 FPM.add(createVerifierPass()); // Verify that input is correct
201 MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct
203 PassManagerBuilder Builder;
204 Builder.OptLevel = OptLevel;
205 Builder.SizeLevel = SizeLevel;
209 } else if (OptLevel > 1) {
210 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
212 Builder.Inliner = createAlwaysInlinerPass();
214 Builder.DisableUnitAtATime = !UnitAtATime;
215 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
216 DisableLoopUnrolling : OptLevel == 0;
218 // This is final, unless there is a #pragma vectorize enable
219 if (DisableLoopVectorization)
220 Builder.LoopVectorize = false;
221 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
222 else if (!Builder.LoopVectorize)
223 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
225 // When #pragma vectorize is on for SLP, do the same as above
226 Builder.SLPVectorize =
227 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
229 Builder.populateFunctionPassManager(FPM);
230 Builder.populateModulePassManager(MPM);
233 static void AddStandardLinkPasses(PassManagerBase &PM) {
234 PassManagerBuilder Builder;
235 Builder.VerifyInput = true;
236 Builder.StripDebug = StripDebug;
237 if (DisableOptimizations)
238 Builder.OptLevel = 0;
241 Builder.Inliner = createFunctionInliningPass();
242 Builder.populateLTOPassManager(PM);
245 //===----------------------------------------------------------------------===//
246 // CodeGen-related helper functions.
249 CodeGenOpt::Level GetCodeGenOptLevel() {
251 return CodeGenOpt::Less;
253 return CodeGenOpt::Default;
255 return CodeGenOpt::Aggressive;
256 return CodeGenOpt::None;
259 // Returns the TargetMachine instance or zero if no triple is provided.
260 static TargetMachine* GetTargetMachine(Triple TheTriple) {
262 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
264 // Some modules don't specify a triple, and this is okay.
269 // Package up features to be passed to target/subtarget
270 std::string FeaturesStr;
272 SubtargetFeatures Features;
273 for (unsigned i = 0; i != MAttrs.size(); ++i)
274 Features.AddFeature(MAttrs[i]);
275 FeaturesStr = Features.getString();
278 return TheTarget->createTargetMachine(TheTriple.getTriple(),
280 InitTargetOptionsFromCodeGenFlags(),
282 GetCodeGenOptLevel());
285 #ifdef LINK_POLLY_INTO_TOOLS
287 void initializePollyPasses(llvm::PassRegistry &Registry);
291 //===----------------------------------------------------------------------===//
294 int main(int argc, char **argv) {
295 sys::PrintStackTraceOnErrorSignal();
296 llvm::PrettyStackTraceProgram X(argc, argv);
298 // Enable debug stream buffering.
299 EnableDebugBuffering = true;
301 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
302 LLVMContext &Context = getGlobalContext();
304 InitializeAllTargets();
305 InitializeAllTargetMCs();
306 InitializeAllAsmPrinters();
309 PassRegistry &Registry = *PassRegistry::getPassRegistry();
310 initializeCore(Registry);
311 initializeScalarOpts(Registry);
312 initializeObjCARCOpts(Registry);
313 initializeVectorization(Registry);
314 initializeIPO(Registry);
315 initializeAnalysis(Registry);
316 initializeIPA(Registry);
317 initializeTransformUtils(Registry);
318 initializeInstCombine(Registry);
319 initializeInstrumentation(Registry);
320 initializeTarget(Registry);
321 // For codegen passes, only passes that do IR to IR transformation are
323 initializeCodeGenPreparePass(Registry);
324 initializeAtomicExpandPass(Registry);
325 initializeRewriteSymbolsPass(Registry);
326 initializeWinEHPreparePass(Registry);
328 #ifdef LINK_POLLY_INTO_TOOLS
329 polly::initializePollyPasses(Registry);
332 cl::ParseCommandLineOptions(argc, argv,
333 "llvm .bc -> .bc modular optimizer and analysis printer\n");
335 if (AnalyzeOnly && NoOutput) {
336 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
342 // Load the input module...
343 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
346 Err.print(argv[0], errs());
350 // If we are supposed to override the target triple, do so now.
351 if (!TargetTriple.empty())
352 M->setTargetTriple(Triple::normalize(TargetTriple));
354 // Figure out what stream we are supposed to write to...
355 std::unique_ptr<tool_output_file> Out;
357 if (!OutputFilename.empty())
358 errs() << "WARNING: The -o (output filename) option is ignored when\n"
359 "the --disable-output option is used.\n";
361 // Default to standard output.
362 if (OutputFilename.empty())
363 OutputFilename = "-";
366 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
368 errs() << EC.message() << '\n';
373 Triple ModuleTriple(M->getTargetTriple());
374 TargetMachine *Machine = nullptr;
375 if (ModuleTriple.getArch())
376 Machine = GetTargetMachine(ModuleTriple);
377 std::unique_ptr<TargetMachine> TM(Machine);
379 // If the output is set to be emitted to standard out, and standard out is a
380 // console, print out a warning message and refuse to do it. We don't
381 // impress anyone by spewing tons of binary goo to a terminal.
382 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
383 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
386 if (PassPipeline.getNumOccurrences() > 0) {
387 OutputKind OK = OK_NoOutput;
389 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
391 VerifierKind VK = VK_VerifyInAndOut;
395 VK = VK_VerifyEachPass;
397 // The user has asked to use the new pass manager and provided a pipeline
398 // string. Hand off the rest of the functionality to the new code for that
400 return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
401 PassPipeline, OK, VK)
406 // Create a PassManager to hold and optimize the collection of passes we are
411 // Add an appropriate TargetLibraryInfo pass for the module's triple.
412 TargetLibraryInfoImpl TLII(ModuleTriple);
414 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
415 if (DisableSimplifyLibCalls)
416 TLII.disableAllFunctions();
417 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
419 // Add an appropriate DataLayout instance for this module.
420 const DataLayout *DL = M->getDataLayout();
421 if (!DL && !DefaultDataLayout.empty()) {
422 M->setDataLayout(DefaultDataLayout);
423 DL = M->getDataLayout();
427 Passes.add(new DataLayoutPass());
429 // Add internal analysis passes from the target machine.
430 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
431 : TargetIRAnalysis()));
433 std::unique_ptr<FunctionPassManager> FPasses;
434 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
435 FPasses.reset(new FunctionPassManager(M.get()));
437 FPasses->add(new DataLayoutPass());
438 FPasses->add(createTargetTransformInfoWrapperPass(
439 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
442 if (PrintBreakpoints) {
443 // Default to standard output.
445 if (OutputFilename.empty())
446 OutputFilename = "-";
449 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
452 errs() << EC.message() << '\n';
456 Passes.add(createBreakpointPrinter(Out->os()));
460 // If the -strip-debug command line option was specified, add it.
462 addPass(Passes, createStripSymbolsPass(true));
464 // Create a new optimization pass for each one specified on the command line
465 for (unsigned i = 0; i < PassList.size(); ++i) {
466 if (StandardLinkOpts &&
467 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
468 AddStandardLinkPasses(Passes);
469 StandardLinkOpts = false;
472 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
473 AddOptimizationPasses(Passes, *FPasses, 1, 0);
477 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
478 AddOptimizationPasses(Passes, *FPasses, 2, 0);
482 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
483 AddOptimizationPasses(Passes, *FPasses, 2, 1);
487 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
488 AddOptimizationPasses(Passes, *FPasses, 2, 2);
492 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
493 AddOptimizationPasses(Passes, *FPasses, 3, 0);
497 const PassInfo *PassInf = PassList[i];
499 if (PassInf->getTargetMachineCtor())
500 P = PassInf->getTargetMachineCtor()(TM.get());
501 else if (PassInf->getNormalCtor())
502 P = PassInf->getNormalCtor()();
504 errs() << argv[0] << ": cannot create pass: "
505 << PassInf->getPassName() << "\n";
507 PassKind Kind = P->getPassKind();
513 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
516 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
519 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
522 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
524 case PT_CallGraphSCC:
525 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
528 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
535 Passes.add(createPrintModulePass(errs()));
538 if (StandardLinkOpts) {
539 AddStandardLinkPasses(Passes);
540 StandardLinkOpts = false;
544 AddOptimizationPasses(Passes, *FPasses, 1, 0);
547 AddOptimizationPasses(Passes, *FPasses, 2, 0);
550 AddOptimizationPasses(Passes, *FPasses, 2, 1);
553 AddOptimizationPasses(Passes, *FPasses, 2, 2);
556 AddOptimizationPasses(Passes, *FPasses, 3, 0);
558 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
559 FPasses->doInitialization();
560 for (Function &F : *M)
562 FPasses->doFinalization();
565 // Check that the module is well formed on completion of optimization
566 if (!NoVerify && !VerifyEach) {
567 Passes.add(createVerifierPass());
568 Passes.add(createDebugInfoVerifierPass());
571 // Write bitcode or assembly to the output as the last step...
572 if (!NoOutput && !AnalyzeOnly) {
574 Passes.add(createPrintModulePass(Out->os()));
576 Passes.add(createBitcodeWriterPass(Out->os()));
579 // Before executing passes, print the final values of the LLVM options.
580 cl::PrintOptionValues();
582 // Now that we have all of the passes ready, run them.
586 if (!NoOutput || PrintBreakpoints)