xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision f489e2bf)
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14 
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.inc"
27 #include "llvm/CodeGen/TargetPassConfig.h"
28 #include "llvm/Config/llvm-config.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/LegacyPassNameParser.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/LinkAllIR.h"
40 #include "llvm/LinkAllPasses.h"
41 #include "llvm/MC/SubtargetFeature.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/YAMLTraits.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/IPO/AlwaysInliner.h"
56 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
57 #include "llvm/Transforms/Utils/Cloning.h"
58 #include <algorithm>
59 #include <memory>
60 using namespace llvm;
61 using namespace opt_tool;
62 
63 // The OptimizationList is automatically populated with registered Passes by the
64 // PassNameParser.
65 //
66 static cl::list<const PassInfo*, bool, PassNameParser>
67 PassList(cl::desc("Optimizations available:"));
68 
69 // This flag specifies a textual description of the optimization pass pipeline
70 // to run over the module. This flag switches opt to use the new pass manager
71 // infrastructure, completely disabling all of the flags specific to the old
72 // pass management.
73 static cl::opt<std::string> PassPipeline(
74     "passes",
75     cl::desc("A textual description of the pass pipeline for optimizing"),
76     cl::Hidden);
77 
78 // Other command line options...
79 //
80 static cl::opt<std::string>
81 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
82     cl::init("-"), cl::value_desc("filename"));
83 
84 static cl::opt<std::string>
85 OutputFilename("o", cl::desc("Override output filename"),
86                cl::value_desc("filename"));
87 
88 static cl::opt<bool>
89 Force("f", cl::desc("Enable binary output on terminals"));
90 
91 static cl::opt<bool>
92 PrintEachXForm("p", cl::desc("Print module after each transformation"));
93 
94 static cl::opt<bool>
95 NoOutput("disable-output",
96          cl::desc("Do not write result bitcode file"), cl::Hidden);
97 
98 static cl::opt<bool>
99 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
100 
101 static cl::opt<bool>
102     OutputThinLTOBC("thinlto-bc",
103                     cl::desc("Write output as ThinLTO-ready bitcode"));
104 
105 static cl::opt<std::string> ThinLinkBitcodeFile(
106     "thin-link-bitcode-file", cl::value_desc("filename"),
107     cl::desc(
108         "A file in which to write minimized bitcode for the thin link only"));
109 
110 static cl::opt<bool>
111 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
112 
113 static cl::opt<bool>
114 VerifyEach("verify-each", cl::desc("Verify after each transform"));
115 
116 static cl::opt<bool>
117     DisableDITypeMap("disable-debug-info-type-map",
118                      cl::desc("Don't use a uniquing type map for debug info"));
119 
120 static cl::opt<bool>
121 StripDebug("strip-debug",
122            cl::desc("Strip debugger symbol info from translation unit"));
123 
124 static cl::opt<bool>
125 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
126 
127 static cl::opt<bool>
128 DisableOptimizations("disable-opt",
129                      cl::desc("Do not run any optimization passes"));
130 
131 static cl::opt<bool>
132 StandardLinkOpts("std-link-opts",
133                  cl::desc("Include the standard link time optimizations"));
134 
135 static cl::opt<bool>
136 OptLevelO0("O0",
137   cl::desc("Optimization level 0. Similar to clang -O0"));
138 
139 static cl::opt<bool>
140 OptLevelO1("O1",
141            cl::desc("Optimization level 1. Similar to clang -O1"));
142 
143 static cl::opt<bool>
144 OptLevelO2("O2",
145            cl::desc("Optimization level 2. Similar to clang -O2"));
146 
147 static cl::opt<bool>
148 OptLevelOs("Os",
149            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
150 
151 static cl::opt<bool>
152 OptLevelOz("Oz",
153            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
154 
155 static cl::opt<bool>
156 OptLevelO3("O3",
157            cl::desc("Optimization level 3. Similar to clang -O3"));
158 
159 static cl::opt<unsigned>
160 CodeGenOptLevel("codegen-opt-level",
161                 cl::desc("Override optimization level for codegen hooks"));
162 
163 static cl::opt<std::string>
164 TargetTriple("mtriple", cl::desc("Override target triple for module"));
165 
166 static cl::opt<bool>
167 UnitAtATime("funit-at-a-time",
168             cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
169             cl::init(true));
170 
171 static cl::opt<bool>
172 DisableLoopUnrolling("disable-loop-unrolling",
173                      cl::desc("Disable loop unrolling in all relevant passes"),
174                      cl::init(false));
175 static cl::opt<bool>
176 DisableLoopVectorization("disable-loop-vectorization",
177                      cl::desc("Disable the loop vectorization pass"),
178                      cl::init(false));
179 
180 static cl::opt<bool>
181 DisableSLPVectorization("disable-slp-vectorization",
182                         cl::desc("Disable the slp vectorization pass"),
183                         cl::init(false));
184 
185 static cl::opt<bool> EmitSummaryIndex("module-summary",
186                                       cl::desc("Emit module summary index"),
187                                       cl::init(false));
188 
189 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
190                                     cl::init(false));
191 
192 static cl::opt<bool>
193 DisableSimplifyLibCalls("disable-simplify-libcalls",
194                         cl::desc("Disable simplify-libcalls"));
195 
196 static cl::opt<bool>
197 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
198 
199 static cl::alias
200 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
201 
202 static cl::opt<bool>
203 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
204 
205 static cl::opt<bool> EnableDebugify(
206     "enable-debugify",
207     cl::desc(
208         "Start the pipeline with debugify and end it with check-debugify"));
209 
210 static cl::opt<bool>
211 PrintBreakpoints("print-breakpoints-for-testing",
212                  cl::desc("Print select breakpoints location for testing"));
213 
214 static cl::opt<std::string> ClDataLayout("data-layout",
215                                          cl::desc("data layout string to use"),
216                                          cl::value_desc("layout-string"),
217                                          cl::init(""));
218 
219 static cl::opt<bool> PreserveBitcodeUseListOrder(
220     "preserve-bc-uselistorder",
221     cl::desc("Preserve use-list order when writing LLVM bitcode."),
222     cl::init(true), cl::Hidden);
223 
224 static cl::opt<bool> PreserveAssemblyUseListOrder(
225     "preserve-ll-uselistorder",
226     cl::desc("Preserve use-list order when writing LLVM assembly."),
227     cl::init(false), cl::Hidden);
228 
229 static cl::opt<bool>
230     RunTwice("run-twice",
231              cl::desc("Run all passes twice, re-using the same pass manager."),
232              cl::init(false), cl::Hidden);
233 
234 static cl::opt<bool> DiscardValueNames(
235     "discard-value-names",
236     cl::desc("Discard names from Value (other than GlobalValue)."),
237     cl::init(false), cl::Hidden);
238 
239 static cl::opt<bool> Coroutines(
240   "enable-coroutines",
241   cl::desc("Enable coroutine passes."),
242   cl::init(false), cl::Hidden);
243 
244 static cl::opt<bool> PassRemarksWithHotness(
245     "pass-remarks-with-hotness",
246     cl::desc("With PGO, include profile count in optimization remarks"),
247     cl::Hidden);
248 
249 static cl::opt<unsigned> PassRemarksHotnessThreshold(
250     "pass-remarks-hotness-threshold",
251     cl::desc("Minimum profile count required for an optimization remark to be output"),
252     cl::Hidden);
253 
254 static cl::opt<std::string>
255     RemarksFilename("pass-remarks-output",
256                     cl::desc("YAML output filename for pass remarks"),
257                     cl::value_desc("filename"));
258 
259 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
260   // Add the pass to the pass manager...
261   PM.add(P);
262 
263   // If we are verifying all of the intermediate steps, add the verifier...
264   if (VerifyEach)
265     PM.add(createVerifierPass());
266 }
267 
268 /// This routine adds optimization passes based on selected optimization level,
269 /// OptLevel.
270 ///
271 /// OptLevel - Optimization Level
272 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
273                                   legacy::FunctionPassManager &FPM,
274                                   TargetMachine *TM, unsigned OptLevel,
275                                   unsigned SizeLevel) {
276   if (!NoVerify || VerifyEach)
277     FPM.add(createVerifierPass()); // Verify that input is correct
278 
279   PassManagerBuilder Builder;
280   Builder.OptLevel = OptLevel;
281   Builder.SizeLevel = SizeLevel;
282 
283   if (DisableInline) {
284     // No inlining pass
285   } else if (OptLevel > 1) {
286     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
287   } else {
288     Builder.Inliner = createAlwaysInlinerLegacyPass();
289   }
290   Builder.DisableUnitAtATime = !UnitAtATime;
291   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
292                                DisableLoopUnrolling : OptLevel == 0;
293 
294   // This is final, unless there is a #pragma vectorize enable
295   if (DisableLoopVectorization)
296     Builder.LoopVectorize = false;
297   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
298   else if (!Builder.LoopVectorize)
299     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
300 
301   // When #pragma vectorize is on for SLP, do the same as above
302   Builder.SLPVectorize =
303       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
304 
305   if (TM)
306     TM->adjustPassManager(Builder);
307 
308   if (Coroutines)
309     addCoroutinePassesToExtensionPoints(Builder);
310 
311   Builder.populateFunctionPassManager(FPM);
312   Builder.populateModulePassManager(MPM);
313 }
314 
315 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
316   PassManagerBuilder Builder;
317   Builder.VerifyInput = true;
318   if (DisableOptimizations)
319     Builder.OptLevel = 0;
320 
321   if (!DisableInline)
322     Builder.Inliner = createFunctionInliningPass();
323   Builder.populateLTOPassManager(PM);
324 }
325 
326 //===----------------------------------------------------------------------===//
327 // CodeGen-related helper functions.
328 //
329 
330 static CodeGenOpt::Level GetCodeGenOptLevel() {
331   if (CodeGenOptLevel.getNumOccurrences())
332     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
333   if (OptLevelO1)
334     return CodeGenOpt::Less;
335   if (OptLevelO2)
336     return CodeGenOpt::Default;
337   if (OptLevelO3)
338     return CodeGenOpt::Aggressive;
339   return CodeGenOpt::None;
340 }
341 
342 // Returns the TargetMachine instance or zero if no triple is provided.
343 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
344                                        StringRef FeaturesStr,
345                                        const TargetOptions &Options) {
346   std::string Error;
347   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
348                                                          Error);
349   // Some modules don't specify a triple, and this is okay.
350   if (!TheTarget) {
351     return nullptr;
352   }
353 
354   return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
355                                         FeaturesStr, Options, getRelocModel(),
356                                         getCodeModel(), GetCodeGenOptLevel());
357 }
358 
359 #ifdef LINK_POLLY_INTO_TOOLS
360 namespace polly {
361 void initializePollyPasses(llvm::PassRegistry &Registry);
362 }
363 #endif
364 
365 //===----------------------------------------------------------------------===//
366 // main for opt
367 //
368 int main(int argc, char **argv) {
369   InitLLVM X(argc, argv);
370 
371   // Enable debug stream buffering.
372   EnableDebugBuffering = true;
373 
374   LLVMContext Context;
375 
376   InitializeAllTargets();
377   InitializeAllTargetMCs();
378   InitializeAllAsmPrinters();
379   InitializeAllAsmParsers();
380 
381   // Initialize passes
382   PassRegistry &Registry = *PassRegistry::getPassRegistry();
383   initializeCore(Registry);
384   initializeCoroutines(Registry);
385   initializeScalarOpts(Registry);
386   initializeObjCARCOpts(Registry);
387   initializeVectorization(Registry);
388   initializeIPO(Registry);
389   initializeAnalysis(Registry);
390   initializeTransformUtils(Registry);
391   initializeInstCombine(Registry);
392   initializeAggressiveInstCombine(Registry);
393   initializeInstrumentation(Registry);
394   initializeTarget(Registry);
395   // For codegen passes, only passes that do IR to IR transformation are
396   // supported.
397   initializeExpandMemCmpPassPass(Registry);
398   initializeScalarizeMaskedMemIntrinPass(Registry);
399   initializeCodeGenPreparePass(Registry);
400   initializeAtomicExpandPass(Registry);
401   initializeRewriteSymbolsLegacyPassPass(Registry);
402   initializeWinEHPreparePass(Registry);
403   initializeDwarfEHPreparePass(Registry);
404   initializeSafeStackLegacyPassPass(Registry);
405   initializeSjLjEHPreparePass(Registry);
406   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
407   initializeGlobalMergePass(Registry);
408   initializeIndirectBrExpandPassPass(Registry);
409   initializeInterleavedAccessPass(Registry);
410   initializeEntryExitInstrumenterPass(Registry);
411   initializePostInlineEntryExitInstrumenterPass(Registry);
412   initializeUnreachableBlockElimLegacyPassPass(Registry);
413   initializeExpandReductionsPass(Registry);
414   initializeWriteBitcodePassPass(Registry);
415 
416 #ifdef LINK_POLLY_INTO_TOOLS
417   polly::initializePollyPasses(Registry);
418 #endif
419 
420   cl::ParseCommandLineOptions(argc, argv,
421     "llvm .bc -> .bc modular optimizer and analysis printer\n");
422 
423   if (AnalyzeOnly && NoOutput) {
424     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
425     return 1;
426   }
427 
428   SMDiagnostic Err;
429 
430   Context.setDiscardValueNames(DiscardValueNames);
431   if (!DisableDITypeMap)
432     Context.enableDebugTypeODRUniquing();
433 
434   if (PassRemarksWithHotness)
435     Context.setDiagnosticsHotnessRequested(true);
436 
437   if (PassRemarksHotnessThreshold)
438     Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
439 
440   std::unique_ptr<ToolOutputFile> OptRemarkFile;
441   if (RemarksFilename != "") {
442     std::error_code EC;
443     OptRemarkFile =
444         llvm::make_unique<ToolOutputFile>(RemarksFilename, EC, sys::fs::F_None);
445     if (EC) {
446       errs() << EC.message() << '\n';
447       return 1;
448     }
449     Context.setDiagnosticsOutputFile(
450         llvm::make_unique<yaml::Output>(OptRemarkFile->os()));
451   }
452 
453   // Load the input module...
454   std::unique_ptr<Module> M =
455       parseIRFile(InputFilename, Err, Context, !NoVerify, ClDataLayout);
456 
457   if (!M) {
458     Err.print(argv[0], errs());
459     return 1;
460   }
461 
462   // Strip debug info before running the verifier.
463   if (StripDebug)
464     StripDebugInfo(*M);
465 
466   // If we are supposed to override the target triple or data layout, do so now.
467   if (!TargetTriple.empty())
468     M->setTargetTriple(Triple::normalize(TargetTriple));
469 
470   // Immediately run the verifier to catch any problems before starting up the
471   // pass pipelines.  Otherwise we can crash on broken code during
472   // doInitialization().
473   if (!NoVerify && verifyModule(*M, &errs())) {
474     errs() << argv[0] << ": " << InputFilename
475            << ": error: input module is broken!\n";
476     return 1;
477   }
478 
479   // Figure out what stream we are supposed to write to...
480   std::unique_ptr<ToolOutputFile> Out;
481   std::unique_ptr<ToolOutputFile> ThinLinkOut;
482   if (NoOutput) {
483     if (!OutputFilename.empty())
484       errs() << "WARNING: The -o (output filename) option is ignored when\n"
485                 "the --disable-output option is used.\n";
486   } else {
487     // Default to standard output.
488     if (OutputFilename.empty())
489       OutputFilename = "-";
490 
491     std::error_code EC;
492     Out.reset(new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
493     if (EC) {
494       errs() << EC.message() << '\n';
495       return 1;
496     }
497 
498     if (!ThinLinkBitcodeFile.empty()) {
499       ThinLinkOut.reset(
500           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::F_None));
501       if (EC) {
502         errs() << EC.message() << '\n';
503         return 1;
504       }
505     }
506   }
507 
508   Triple ModuleTriple(M->getTargetTriple());
509   std::string CPUStr, FeaturesStr;
510   TargetMachine *Machine = nullptr;
511   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
512 
513   if (ModuleTriple.getArch()) {
514     CPUStr = getCPUStr();
515     FeaturesStr = getFeaturesStr();
516     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
517   }
518 
519   std::unique_ptr<TargetMachine> TM(Machine);
520 
521   // Override function attributes based on CPUStr, FeaturesStr, and command line
522   // flags.
523   setFunctionAttributes(CPUStr, FeaturesStr, *M);
524 
525   // If the output is set to be emitted to standard out, and standard out is a
526   // console, print out a warning message and refuse to do it.  We don't
527   // impress anyone by spewing tons of binary goo to a terminal.
528   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
529     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
530       NoOutput = true;
531 
532   if (PassPipeline.getNumOccurrences() > 0) {
533     OutputKind OK = OK_NoOutput;
534     if (!NoOutput)
535       OK = OutputAssembly
536                ? OK_OutputAssembly
537                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
538 
539     VerifierKind VK = VK_VerifyInAndOut;
540     if (NoVerify)
541       VK = VK_NoVerifier;
542     else if (VerifyEach)
543       VK = VK_VerifyEachPass;
544 
545     // The user has asked to use the new pass manager and provided a pipeline
546     // string. Hand off the rest of the functionality to the new code for that
547     // layer.
548     return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(),
549                            OptRemarkFile.get(), PassPipeline, OK, VK,
550                            PreserveAssemblyUseListOrder,
551                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
552                            EmitModuleHash, EnableDebugify)
553                ? 0
554                : 1;
555   }
556 
557   // Create a PassManager to hold and optimize the collection of passes we are
558   // about to build.
559   //
560   legacy::PassManager Passes;
561 
562   // Add an appropriate TargetLibraryInfo pass for the module's triple.
563   TargetLibraryInfoImpl TLII(ModuleTriple);
564 
565   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
566   if (DisableSimplifyLibCalls)
567     TLII.disableAllFunctions();
568   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
569 
570   // Add internal analysis passes from the target machine.
571   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
572                                                      : TargetIRAnalysis()));
573 
574   if (EnableDebugify)
575     Passes.add(createDebugifyPass());
576 
577   std::unique_ptr<legacy::FunctionPassManager> FPasses;
578   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
579       OptLevelO3) {
580     FPasses.reset(new legacy::FunctionPassManager(M.get()));
581     FPasses->add(createTargetTransformInfoWrapperPass(
582         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
583   }
584 
585   if (PrintBreakpoints) {
586     // Default to standard output.
587     if (!Out) {
588       if (OutputFilename.empty())
589         OutputFilename = "-";
590 
591       std::error_code EC;
592       Out = llvm::make_unique<ToolOutputFile>(OutputFilename, EC,
593                                               sys::fs::F_None);
594       if (EC) {
595         errs() << EC.message() << '\n';
596         return 1;
597       }
598     }
599     Passes.add(createBreakpointPrinter(Out->os()));
600     NoOutput = true;
601   }
602 
603   if (TM) {
604     // FIXME: We should dyn_cast this when supported.
605     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
606     Pass *TPC = LTM.createPassConfig(Passes);
607     Passes.add(TPC);
608   }
609 
610   // Create a new optimization pass for each one specified on the command line
611   for (unsigned i = 0; i < PassList.size(); ++i) {
612     if (StandardLinkOpts &&
613         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
614       AddStandardLinkPasses(Passes);
615       StandardLinkOpts = false;
616     }
617 
618     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
619       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
620       OptLevelO0 = false;
621     }
622 
623     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
624       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
625       OptLevelO1 = false;
626     }
627 
628     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
629       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
630       OptLevelO2 = false;
631     }
632 
633     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
634       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
635       OptLevelOs = false;
636     }
637 
638     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
639       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
640       OptLevelOz = false;
641     }
642 
643     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
644       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
645       OptLevelO3 = false;
646     }
647 
648     const PassInfo *PassInf = PassList[i];
649     Pass *P = nullptr;
650     if (PassInf->getNormalCtor())
651       P = PassInf->getNormalCtor()();
652     else
653       errs() << argv[0] << ": cannot create pass: "
654              << PassInf->getPassName() << "\n";
655     if (P) {
656       PassKind Kind = P->getPassKind();
657       addPass(Passes, P);
658 
659       if (AnalyzeOnly) {
660         switch (Kind) {
661         case PT_BasicBlock:
662           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
663           break;
664         case PT_Region:
665           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
666           break;
667         case PT_Loop:
668           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
669           break;
670         case PT_Function:
671           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
672           break;
673         case PT_CallGraphSCC:
674           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
675           break;
676         default:
677           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
678           break;
679         }
680       }
681     }
682 
683     if (PrintEachXForm)
684       Passes.add(
685           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
686   }
687 
688   if (StandardLinkOpts) {
689     AddStandardLinkPasses(Passes);
690     StandardLinkOpts = false;
691   }
692 
693   if (OptLevelO0)
694     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
695 
696   if (OptLevelO1)
697     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
698 
699   if (OptLevelO2)
700     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
701 
702   if (OptLevelOs)
703     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
704 
705   if (OptLevelOz)
706     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
707 
708   if (OptLevelO3)
709     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
710 
711   if (FPasses) {
712     FPasses->doInitialization();
713     for (Function &F : *M)
714       FPasses->run(F);
715     FPasses->doFinalization();
716   }
717 
718   // Check that the module is well formed on completion of optimization
719   if (!NoVerify && !VerifyEach)
720     Passes.add(createVerifierPass());
721 
722   if (EnableDebugify)
723     Passes.add(createCheckDebugifyPass());
724 
725   // In run twice mode, we want to make sure the output is bit-by-bit
726   // equivalent if we run the pass manager again, so setup two buffers and
727   // a stream to write to them. Note that llc does something similar and it
728   // may be worth to abstract this out in the future.
729   SmallVector<char, 0> Buffer;
730   SmallVector<char, 0> FirstRunBuffer;
731   std::unique_ptr<raw_svector_ostream> BOS;
732   raw_ostream *OS = nullptr;
733 
734   // Write bitcode or assembly to the output as the last step...
735   if (!NoOutput && !AnalyzeOnly) {
736     assert(Out);
737     OS = &Out->os();
738     if (RunTwice) {
739       BOS = make_unique<raw_svector_ostream>(Buffer);
740       OS = BOS.get();
741     }
742     if (OutputAssembly) {
743       if (EmitSummaryIndex)
744         report_fatal_error("Text output is incompatible with -module-summary");
745       if (EmitModuleHash)
746         report_fatal_error("Text output is incompatible with -module-hash");
747       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
748     } else if (OutputThinLTOBC)
749       Passes.add(createWriteThinLTOBitcodePass(
750           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
751     else
752       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
753                                          EmitSummaryIndex, EmitModuleHash));
754   }
755 
756   // Before executing passes, print the final values of the LLVM options.
757   cl::PrintOptionValues();
758 
759   if (!RunTwice) {
760     // Now that we have all of the passes ready, run them.
761     Passes.run(*M);
762   } else {
763     // If requested, run all passes twice with the same pass manager to catch
764     // bugs caused by persistent state in the passes.
765     std::unique_ptr<Module> M2(CloneModule(*M));
766     // Run all passes on the original module first, so the second run processes
767     // the clone to catch CloneModule bugs.
768     Passes.run(*M);
769     FirstRunBuffer = Buffer;
770     Buffer.clear();
771 
772     Passes.run(*M2);
773 
774     // Compare the two outputs and make sure they're the same
775     assert(Out);
776     if (Buffer.size() != FirstRunBuffer.size() ||
777         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
778       errs()
779           << "Running the pass manager twice changed the output.\n"
780              "Writing the result of the second run to the specified output.\n"
781              "To generate the one-run comparison binary, just run without\n"
782              "the compile-twice option\n";
783       Out->os() << BOS->str();
784       Out->keep();
785       if (OptRemarkFile)
786         OptRemarkFile->keep();
787       return 1;
788     }
789     Out->os() << BOS->str();
790   }
791 
792   // Declare success.
793   if (!NoOutput || PrintBreakpoints)
794     Out->keep();
795 
796   if (OptRemarkFile)
797     OptRemarkFile->keep();
798 
799   if (ThinLinkOut)
800     ThinLinkOut->keep();
801 
802   return 0;
803 }
804