xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision aa656f6c)
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Optimizations may be specified an arbitrary number of times on the command
10 // line, They are run in the order specified.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "BreakpointPrinter.h"
15 #include "NewPMDriver.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/CallGraph.h"
18 #include "llvm/Analysis/CallGraphSCCPass.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/RegionPass.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/AsmParser/Parser.h"
24 #include "llvm/CodeGen/CommandFlags.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LLVMRemarkStreamer.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/LegacyPassNameParser.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/IRReader/IRReader.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LinkAllIR.h"
39 #include "llvm/LinkAllPasses.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/MC/TargetRegistry.h"
42 #include "llvm/Passes/PassPlugin.h"
43 #include "llvm/Remarks/HotnessThresholdParser.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/InitLLVM.h"
48 #include "llvm/Support/PluginLoader.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/SystemUtils.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/YAMLTraits.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Transforms/IPO/AlwaysInliner.h"
56 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
57 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
58 #include "llvm/Transforms/Utils/Cloning.h"
59 #include "llvm/Transforms/Utils/Debugify.h"
60 #include <algorithm>
61 #include <memory>
62 using namespace llvm;
63 using namespace opt_tool;
64 
65 static codegen::RegisterCodeGenFlags CFG;
66 
67 // The OptimizationList is automatically populated with registered Passes by the
68 // PassNameParser.
69 static cl::list<const PassInfo *, bool, PassNameParser> PassList(cl::desc(
70     "Optimizations available (use '-passes=' for the new pass manager)"));
71 
72 static cl::opt<bool> EnableNewPassManager(
73     "enable-new-pm",
74     cl::desc("Enable the new pass manager, translating "
75              "'opt -foo' to 'opt -passes=foo'. This is strictly for the new PM "
76              "migration, use '-passes=' when possible."),
77     cl::init(true));
78 
79 // This flag specifies a textual description of the optimization pass pipeline
80 // to run over the module. This flag switches opt to use the new pass manager
81 // infrastructure, completely disabling all of the flags specific to the old
82 // pass management.
83 static cl::opt<std::string> PassPipeline(
84     "passes",
85     cl::desc(
86         "A textual description of the pass pipeline. To have analysis passes "
87         "available before a certain pass, add 'require<foo-analysis>'."));
88 
89 static cl::opt<bool> PrintPasses("print-passes",
90                                  cl::desc("Print available passes that can be "
91                                           "specified in -passes=foo and exit"));
92 
93 static cl::opt<std::string>
94 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
95     cl::init("-"), cl::value_desc("filename"));
96 
97 static cl::opt<std::string>
98 OutputFilename("o", cl::desc("Override output filename"),
99                cl::value_desc("filename"));
100 
101 static cl::opt<bool>
102 Force("f", cl::desc("Enable binary output on terminals"));
103 
104 static cl::opt<bool>
105 NoOutput("disable-output",
106          cl::desc("Do not write result bitcode file"), cl::Hidden);
107 
108 static cl::opt<bool>
109 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
110 
111 static cl::opt<bool>
112     OutputThinLTOBC("thinlto-bc",
113                     cl::desc("Write output as ThinLTO-ready bitcode"));
114 
115 static cl::opt<bool>
116     SplitLTOUnit("thinlto-split-lto-unit",
117                  cl::desc("Enable splitting of a ThinLTO LTOUnit"));
118 
119 static cl::opt<std::string> ThinLinkBitcodeFile(
120     "thin-link-bitcode-file", cl::value_desc("filename"),
121     cl::desc(
122         "A file in which to write minimized bitcode for the thin link only"));
123 
124 static cl::opt<bool>
125 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
126 
127 static cl::opt<bool> NoUpgradeDebugInfo("disable-upgrade-debug-info",
128                                         cl::desc("Generate invalid output"),
129                                         cl::ReallyHidden);
130 
131 static cl::opt<bool> VerifyEach("verify-each",
132                                 cl::desc("Verify after each transform"));
133 
134 static cl::opt<bool>
135     DisableDITypeMap("disable-debug-info-type-map",
136                      cl::desc("Don't use a uniquing type map for debug info"));
137 
138 static cl::opt<bool>
139 StripDebug("strip-debug",
140            cl::desc("Strip debugger symbol info from translation unit"));
141 
142 static cl::opt<bool>
143     StripNamedMetadata("strip-named-metadata",
144                        cl::desc("Strip module-level named metadata"));
145 
146 
147 
148 static cl::opt<bool>
149     OptLevelO0("O0", cl::desc("Optimization level 0. Similar to clang -O0. "
150                               "Use -passes='default<O0>' for the new PM"));
151 
152 static cl::opt<bool>
153     OptLevelO1("O1", cl::desc("Optimization level 1. Similar to clang -O1. "
154                               "Use -passes='default<O1>' for the new PM"));
155 
156 static cl::opt<bool>
157     OptLevelO2("O2", cl::desc("Optimization level 2. Similar to clang -O2. "
158                               "Use -passes='default<O2>' for the new PM"));
159 
160 static cl::opt<bool>
161     OptLevelOs("Os", cl::desc("Like -O2 but size-conscious. Similar to clang "
162                               "-Os. Use -passes='default<Os>' for the new PM"));
163 
164 static cl::opt<bool> OptLevelOz(
165     "Oz",
166     cl::desc("Like -O2 but optimize for code size above all else. Similar to "
167              "clang -Oz. Use -passes='default<Oz>' for the new PM"));
168 
169 static cl::opt<bool>
170     OptLevelO3("O3", cl::desc("Optimization level 3. Similar to clang -O3. "
171                               "Use -passes='default<O3>' for the new PM"));
172 
173 static cl::opt<unsigned> CodeGenOptLevel(
174     "codegen-opt-level",
175     cl::desc("Override optimization level for codegen hooks, legacy PM only"));
176 
177 static cl::opt<std::string>
178 TargetTriple("mtriple", cl::desc("Override target triple for module"));
179 
180 cl::opt<bool> DisableLoopUnrolling(
181     "disable-loop-unrolling",
182     cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false));
183 
184 static cl::opt<bool> EmitSummaryIndex("module-summary",
185                                       cl::desc("Emit module summary index"),
186                                       cl::init(false));
187 
188 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
189                                     cl::init(false));
190 
191 static cl::opt<bool>
192 DisableSimplifyLibCalls("disable-simplify-libcalls",
193                         cl::desc("Disable simplify-libcalls"));
194 
195 static cl::list<std::string>
196 DisableBuiltins("disable-builtin",
197                 cl::desc("Disable specific target library builtin function"),
198                 cl::ZeroOrMore);
199 
200 static cl::opt<bool> EnableDebugify(
201     "enable-debugify",
202     cl::desc(
203         "Start the pipeline with debugify and end it with check-debugify"));
204 
205 static cl::opt<bool> VerifyDebugInfoPreserve(
206     "verify-debuginfo-preserve",
207     cl::desc("Start the pipeline with collecting and end it with checking of "
208              "debug info preservation."));
209 
210 static cl::opt<bool> VerifyEachDebugInfoPreserve(
211     "verify-each-debuginfo-preserve",
212     cl::desc("Start each pass with collecting and end it with checking of "
213              "debug info preservation."));
214 
215 static cl::opt<std::string>
216     VerifyDIPreserveExport("verify-di-preserve-export",
217                    cl::desc("Export debug info preservation failures into "
218                             "specified (JSON) file (should be abs path as we use"
219                             " append mode to insert new JSON objects)"),
220                    cl::value_desc("filename"), cl::init(""));
221 
222 static cl::opt<bool>
223 PrintBreakpoints("print-breakpoints-for-testing",
224                  cl::desc("Print select breakpoints location for testing"));
225 
226 static cl::opt<std::string> ClDataLayout("data-layout",
227                                          cl::desc("data layout string to use"),
228                                          cl::value_desc("layout-string"),
229                                          cl::init(""));
230 
231 static cl::opt<bool> PreserveBitcodeUseListOrder(
232     "preserve-bc-uselistorder",
233     cl::desc("Preserve use-list order when writing LLVM bitcode."),
234     cl::init(true), cl::Hidden);
235 
236 static cl::opt<bool> PreserveAssemblyUseListOrder(
237     "preserve-ll-uselistorder",
238     cl::desc("Preserve use-list order when writing LLVM assembly."),
239     cl::init(false), cl::Hidden);
240 
241 static cl::opt<bool> RunTwice("run-twice",
242                               cl::desc("Run all passes twice, re-using the "
243                                        "same pass manager (legacy PM only)."),
244                               cl::init(false), cl::Hidden);
245 
246 static cl::opt<bool> DiscardValueNames(
247     "discard-value-names",
248     cl::desc("Discard names from Value (other than GlobalValue)."),
249     cl::init(false), cl::Hidden);
250 
251 static cl::opt<bool> TimeTrace(
252     "time-trace",
253     cl::desc("Record time trace"));
254 
255 static cl::opt<unsigned> TimeTraceGranularity(
256     "time-trace-granularity",
257     cl::desc("Minimum time granularity (in microseconds) traced by time profiler"),
258     cl::init(500), cl::Hidden);
259 
260 static cl::opt<std::string>
261     TimeTraceFile("time-trace-file",
262                     cl::desc("Specify time trace file destination"),
263                     cl::value_desc("filename"));
264 
265 static cl::opt<bool> RemarksWithHotness(
266     "pass-remarks-with-hotness",
267     cl::desc("With PGO, include profile count in optimization remarks"),
268     cl::Hidden);
269 
270 static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
271     RemarksHotnessThreshold(
272         "pass-remarks-hotness-threshold",
273         cl::desc("Minimum profile count required for "
274                  "an optimization remark to be output. "
275                  "Use 'auto' to apply the threshold from profile summary."),
276         cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
277 
278 static cl::opt<std::string>
279     RemarksFilename("pass-remarks-output",
280                     cl::desc("Output filename for pass remarks"),
281                     cl::value_desc("filename"));
282 
283 static cl::opt<std::string>
284     RemarksPasses("pass-remarks-filter",
285                   cl::desc("Only record optimization remarks from passes whose "
286                            "names match the given regular expression"),
287                   cl::value_desc("regex"));
288 
289 static cl::opt<std::string> RemarksFormat(
290     "pass-remarks-format",
291     cl::desc("The format used for serializing remarks (default: YAML)"),
292     cl::value_desc("format"), cl::init("yaml"));
293 
294 static cl::list<std::string>
295     PassPlugins("load-pass-plugin",
296                 cl::desc("Load passes from plugin library"));
297 
298 namespace llvm {
299 cl::opt<PGOKind>
300     PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
301                 cl::desc("The kind of profile guided optimization"),
302                 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
303                            clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
304                                       "Instrument the IR to generate profile."),
305                            clEnumValN(InstrUse, "pgo-instr-use-pipeline",
306                                       "Use instrumented profile to guide PGO."),
307                            clEnumValN(SampleUse, "pgo-sample-use-pipeline",
308                                       "Use sampled profile to guide PGO.")));
309 cl::opt<std::string> ProfileFile("profile-file",
310                                  cl::desc("Path to the profile."), cl::Hidden);
311 
312 cl::opt<CSPGOKind> CSPGOKindFlag(
313     "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
314     cl::desc("The kind of context sensitive profile guided optimization"),
315     cl::values(
316         clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
317         clEnumValN(
318             CSInstrGen, "cspgo-instr-gen-pipeline",
319             "Instrument (context sensitive) the IR to generate profile."),
320         clEnumValN(
321             CSInstrUse, "cspgo-instr-use-pipeline",
322             "Use instrumented (context sensitive) profile to guide PGO.")));
323 cl::opt<std::string> CSProfileGenFile(
324     "cs-profilegen-file",
325     cl::desc("Path to the instrumented context sensitive profile."),
326     cl::Hidden);
327 } // namespace llvm
328 
329 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
330   // Add the pass to the pass manager...
331   PM.add(P);
332 
333   // If we are verifying all of the intermediate steps, add the verifier...
334   if (VerifyEach)
335     PM.add(createVerifierPass());
336 }
337 
338 /// This routine adds optimization passes based on selected optimization level,
339 /// OptLevel.
340 ///
341 /// OptLevel - Optimization Level
342 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
343                                   legacy::FunctionPassManager &FPM,
344                                   TargetMachine *TM, unsigned OptLevel,
345                                   unsigned SizeLevel) {
346   if (!NoVerify || VerifyEach)
347     FPM.add(createVerifierPass()); // Verify that input is correct
348 
349   PassManagerBuilder Builder;
350   Builder.OptLevel = OptLevel;
351   Builder.SizeLevel = SizeLevel;
352 
353   if (OptLevel > 1) {
354     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
355   } else {
356     Builder.Inliner = createAlwaysInlinerLegacyPass();
357   }
358   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
359                                DisableLoopUnrolling : OptLevel == 0;
360 
361   Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
362 
363   Builder.SLPVectorize = OptLevel > 1 && SizeLevel < 2;
364 
365   if (TM)
366     TM->adjustPassManager(Builder);
367 
368   switch (PGOKindFlag) {
369   case InstrGen:
370     Builder.EnablePGOInstrGen = true;
371     Builder.PGOInstrGen = ProfileFile;
372     break;
373   case InstrUse:
374     Builder.PGOInstrUse = ProfileFile;
375     break;
376   case SampleUse:
377     Builder.PGOSampleUse = ProfileFile;
378     break;
379   default:
380     break;
381   }
382 
383   switch (CSPGOKindFlag) {
384   case CSInstrGen:
385     Builder.EnablePGOCSInstrGen = true;
386     break;
387   case CSInstrUse:
388     Builder.EnablePGOCSInstrUse = true;
389     break;
390   default:
391     break;
392   }
393 
394   Builder.populateFunctionPassManager(FPM);
395   Builder.populateModulePassManager(MPM);
396 }
397 
398 //===----------------------------------------------------------------------===//
399 // CodeGen-related helper functions.
400 //
401 
402 static CodeGenOpt::Level GetCodeGenOptLevel() {
403   if (CodeGenOptLevel.getNumOccurrences())
404     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
405   if (OptLevelO1)
406     return CodeGenOpt::Less;
407   if (OptLevelO2)
408     return CodeGenOpt::Default;
409   if (OptLevelO3)
410     return CodeGenOpt::Aggressive;
411   return CodeGenOpt::None;
412 }
413 
414 // Returns the TargetMachine instance or zero if no triple is provided.
415 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
416                                        StringRef FeaturesStr,
417                                        const TargetOptions &Options) {
418   std::string Error;
419   const Target *TheTarget =
420       TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
421   // Some modules don't specify a triple, and this is okay.
422   if (!TheTarget) {
423     return nullptr;
424   }
425 
426   return TheTarget->createTargetMachine(
427       TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
428       Options, codegen::getExplicitRelocModel(),
429       codegen::getExplicitCodeModel(), GetCodeGenOptLevel());
430 }
431 
432 #ifdef BUILD_EXAMPLES
433 void initializeExampleIRTransforms(llvm::PassRegistry &Registry);
434 #endif
435 
436 struct TimeTracerRAII {
437   TimeTracerRAII(StringRef ProgramName) {
438     if (TimeTrace)
439       timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName);
440   }
441   ~TimeTracerRAII() {
442     if (TimeTrace) {
443       if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
444         handleAllErrors(std::move(E), [&](const StringError &SE) {
445           errs() << SE.getMessage() << "\n";
446         });
447         return;
448       }
449       timeTraceProfilerCleanup();
450     }
451   }
452 };
453 
454 // For use in NPM transition. Currently this contains most codegen-specific
455 // passes. Remove passes from here when porting to the NPM.
456 // TODO: use a codegen version of PassRegistry.def/PassBuilder::is*Pass() once
457 // it exists.
458 static bool shouldPinPassToLegacyPM(StringRef Pass) {
459   std::vector<StringRef> PassNameExactToIgnore = {
460       "nvvm-reflect",
461       "nvvm-intr-range",
462       "amdgpu-simplifylib",
463       "amdgpu-usenative",
464       "amdgpu-promote-alloca",
465       "amdgpu-promote-alloca-to-vector",
466       "amdgpu-lower-kernel-attributes",
467       "amdgpu-propagate-attributes-early",
468       "amdgpu-propagate-attributes-late",
469       "amdgpu-unify-metadata",
470       "amdgpu-printf-runtime-binding",
471       "amdgpu-always-inline"};
472   if (llvm::is_contained(PassNameExactToIgnore, Pass))
473     return false;
474 
475   std::vector<StringRef> PassNamePrefix = {
476       "x86-",    "xcore-", "wasm-",  "systemz-", "ppc-",    "nvvm-",
477       "nvptx-",  "mips-",  "lanai-", "hexagon-", "bpf-",    "avr-",
478       "thumb2-", "arm-",   "si-",    "gcn-",     "amdgpu-", "aarch64-",
479       "amdgcn-", "polly-", "riscv-", "dxil-"};
480   std::vector<StringRef> PassNameContain = {"ehprepare"};
481   std::vector<StringRef> PassNameExact = {
482       "safe-stack",           "cost-model",
483       "codegenprepare",       "interleaved-load-combine",
484       "unreachableblockelim", "verify-safepoint-ir",
485       "atomic-expand",        "expandvp",
486       "hardware-loops",       "type-promotion",
487       "mve-tail-predication", "interleaved-access",
488       "global-merge",         "pre-isel-intrinsic-lowering",
489       "expand-reductions",    "indirectbr-expand",
490       "generic-to-nvvm",      "expandmemcmp",
491       "loop-reduce",          "lower-amx-type",
492       "pre-amx-config",       "lower-amx-intrinsics",
493       "polyhedral-info",      "print-polyhedral-info",
494       "replace-with-veclib",  "jmc-instrument",
495       "dot-regions",          "dot-regions-only",
496       "view-regions",         "view-regions-only"};
497   for (const auto &P : PassNamePrefix)
498     if (Pass.startswith(P))
499       return true;
500   for (const auto &P : PassNameContain)
501     if (Pass.contains(P))
502       return true;
503   return llvm::is_contained(PassNameExact, Pass);
504 }
505 
506 // For use in NPM transition.
507 static bool shouldForceLegacyPM() {
508   for (const auto &P : PassList) {
509     StringRef Arg = P->getPassArgument();
510     if (shouldPinPassToLegacyPM(Arg))
511       return true;
512   }
513   return false;
514 }
515 
516 //===----------------------------------------------------------------------===//
517 // main for opt
518 //
519 int main(int argc, char **argv) {
520   InitLLVM X(argc, argv);
521 
522   // Enable debug stream buffering.
523   EnableDebugBuffering = true;
524 
525   InitializeAllTargets();
526   InitializeAllTargetMCs();
527   InitializeAllAsmPrinters();
528   InitializeAllAsmParsers();
529 
530   // Initialize passes
531   PassRegistry &Registry = *PassRegistry::getPassRegistry();
532   initializeCore(Registry);
533   initializeScalarOpts(Registry);
534   initializeObjCARCOpts(Registry);
535   initializeVectorization(Registry);
536   initializeIPO(Registry);
537   initializeAnalysis(Registry);
538   initializeTransformUtils(Registry);
539   initializeInstCombine(Registry);
540   initializeAggressiveInstCombine(Registry);
541   initializeInstrumentation(Registry);
542   initializeTarget(Registry);
543   // For codegen passes, only passes that do IR to IR transformation are
544   // supported.
545   initializeExpandMemCmpPassPass(Registry);
546   initializeScalarizeMaskedMemIntrinLegacyPassPass(Registry);
547   initializeCodeGenPreparePass(Registry);
548   initializeAtomicExpandPass(Registry);
549   initializeRewriteSymbolsLegacyPassPass(Registry);
550   initializeWinEHPreparePass(Registry);
551   initializeDwarfEHPrepareLegacyPassPass(Registry);
552   initializeSafeStackLegacyPassPass(Registry);
553   initializeSjLjEHPreparePass(Registry);
554   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
555   initializeGlobalMergePass(Registry);
556   initializeIndirectBrExpandPassPass(Registry);
557   initializeInterleavedLoadCombinePass(Registry);
558   initializeInterleavedAccessPass(Registry);
559   initializeEntryExitInstrumenterPass(Registry);
560   initializePostInlineEntryExitInstrumenterPass(Registry);
561   initializeUnreachableBlockElimLegacyPassPass(Registry);
562   initializeExpandReductionsPass(Registry);
563   initializeExpandVectorPredicationPass(Registry);
564   initializeWasmEHPreparePass(Registry);
565   initializeWriteBitcodePassPass(Registry);
566   initializeHardwareLoopsPass(Registry);
567   initializeTypePromotionPass(Registry);
568   initializeReplaceWithVeclibLegacyPass(Registry);
569   initializeJMCInstrumenterPass(Registry);
570 
571 #ifdef BUILD_EXAMPLES
572   initializeExampleIRTransforms(Registry);
573 #endif
574 
575   SmallVector<PassPlugin, 1> PluginList;
576   PassPlugins.setCallback([&](const std::string &PluginPath) {
577     auto Plugin = PassPlugin::Load(PluginPath);
578     if (!Plugin) {
579       errs() << "Failed to load passes from '" << PluginPath
580              << "'. Request ignored.\n";
581       return;
582     }
583     PluginList.emplace_back(Plugin.get());
584   });
585 
586   cl::ParseCommandLineOptions(argc, argv,
587     "llvm .bc -> .bc modular optimizer and analysis printer\n");
588 
589   LLVMContext Context;
590 
591   // If `-passes=` is specified, use NPM.
592   // If `-enable-new-pm` is specified and there are no codegen passes, use NPM.
593   // e.g. `-enable-new-pm -sroa` will use NPM.
594   // but `-enable-new-pm -codegenprepare` will still revert to legacy PM.
595   const bool UseNPM = (EnableNewPassManager && !shouldForceLegacyPM()) ||
596                       PassPipeline.getNumOccurrences() > 0;
597 
598   if (!UseNPM && PluginList.size()) {
599     errs() << argv[0] << ": " << PassPlugins.ArgStr
600            << " specified with legacy PM.\n";
601     return 1;
602   }
603 
604   // FIXME: once the legacy PM code is deleted, move runPassPipeline() here and
605   // construct the PassBuilder before parsing IR so we can reuse the same
606   // PassBuilder for print passes.
607   if (PrintPasses) {
608     printPasses(outs());
609     return 0;
610   }
611 
612   TimeTracerRAII TimeTracer(argv[0]);
613 
614   SMDiagnostic Err;
615 
616   Context.setDiscardValueNames(DiscardValueNames);
617   if (!DisableDITypeMap)
618     Context.enableDebugTypeODRUniquing();
619 
620   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
621       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
622                                    RemarksFormat, RemarksWithHotness,
623                                    RemarksHotnessThreshold);
624   if (Error E = RemarksFileOrErr.takeError()) {
625     errs() << toString(std::move(E)) << '\n';
626     return 1;
627   }
628   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
629 
630   // Load the input module...
631   auto SetDataLayout = [](StringRef) -> Optional<std::string> {
632     if (ClDataLayout.empty())
633       return None;
634     return ClDataLayout;
635   };
636   std::unique_ptr<Module> M;
637   if (NoUpgradeDebugInfo)
638     M = parseAssemblyFileWithIndexNoUpgradeDebugInfo(
639             InputFilename, Err, Context, nullptr, SetDataLayout)
640             .Mod;
641   else
642     M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
643 
644   if (!M) {
645     Err.print(argv[0], errs());
646     return 1;
647   }
648 
649   // Strip debug info before running the verifier.
650   if (StripDebug)
651     StripDebugInfo(*M);
652 
653   // Erase module-level named metadata, if requested.
654   if (StripNamedMetadata) {
655     while (!M->named_metadata_empty()) {
656       NamedMDNode *NMD = &*M->named_metadata_begin();
657       M->eraseNamedMetadata(NMD);
658     }
659   }
660 
661   // If we are supposed to override the target triple or data layout, do so now.
662   if (!TargetTriple.empty())
663     M->setTargetTriple(Triple::normalize(TargetTriple));
664 
665   // Immediately run the verifier to catch any problems before starting up the
666   // pass pipelines.  Otherwise we can crash on broken code during
667   // doInitialization().
668   if (!NoVerify && verifyModule(*M, &errs())) {
669     errs() << argv[0] << ": " << InputFilename
670            << ": error: input module is broken!\n";
671     return 1;
672   }
673 
674   // Enable testing of whole program devirtualization on this module by invoking
675   // the facility for updating public visibility to linkage unit visibility when
676   // specified by an internal option. This is normally done during LTO which is
677   // not performed via opt.
678   updateVCallVisibilityInModule(*M,
679                                 /* WholeProgramVisibilityEnabledInLTO */ false,
680                                 /* DynamicExportSymbols */ {});
681 
682   // Figure out what stream we are supposed to write to...
683   std::unique_ptr<ToolOutputFile> Out;
684   std::unique_ptr<ToolOutputFile> ThinLinkOut;
685   if (NoOutput) {
686     if (!OutputFilename.empty())
687       errs() << "WARNING: The -o (output filename) option is ignored when\n"
688                 "the --disable-output option is used.\n";
689   } else {
690     // Default to standard output.
691     if (OutputFilename.empty())
692       OutputFilename = "-";
693 
694     std::error_code EC;
695     sys::fs::OpenFlags Flags =
696         OutputAssembly ? sys::fs::OF_TextWithCRLF : sys::fs::OF_None;
697     Out.reset(new ToolOutputFile(OutputFilename, EC, Flags));
698     if (EC) {
699       errs() << EC.message() << '\n';
700       return 1;
701     }
702 
703     if (!ThinLinkBitcodeFile.empty()) {
704       ThinLinkOut.reset(
705           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None));
706       if (EC) {
707         errs() << EC.message() << '\n';
708         return 1;
709       }
710     }
711   }
712 
713   Triple ModuleTriple(M->getTargetTriple());
714   std::string CPUStr, FeaturesStr;
715   TargetMachine *Machine = nullptr;
716   const TargetOptions Options =
717       codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);
718 
719   if (ModuleTriple.getArch()) {
720     CPUStr = codegen::getCPUStr();
721     FeaturesStr = codegen::getFeaturesStr();
722     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
723   } else if (ModuleTriple.getArchName() != "unknown" &&
724              ModuleTriple.getArchName() != "") {
725     errs() << argv[0] << ": unrecognized architecture '"
726            << ModuleTriple.getArchName() << "' provided.\n";
727     return 1;
728   }
729 
730   std::unique_ptr<TargetMachine> TM(Machine);
731 
732   // Override function attributes based on CPUStr, FeaturesStr, and command line
733   // flags.
734   codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
735 
736   // If the output is set to be emitted to standard out, and standard out is a
737   // console, print out a warning message and refuse to do it.  We don't
738   // impress anyone by spewing tons of binary goo to a terminal.
739   if (!Force && !NoOutput && !OutputAssembly)
740     if (CheckBitcodeOutputToConsole(Out->os()))
741       NoOutput = true;
742 
743   if (OutputThinLTOBC)
744     M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit);
745 
746   // Add an appropriate TargetLibraryInfo pass for the module's triple.
747   TargetLibraryInfoImpl TLII(ModuleTriple);
748 
749   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
750   if (DisableSimplifyLibCalls)
751     TLII.disableAllFunctions();
752   else {
753     // Disable individual builtin functions in TargetLibraryInfo.
754     LibFunc F;
755     for (auto &FuncName : DisableBuiltins)
756       if (TLII.getLibFunc(FuncName, F))
757         TLII.setUnavailable(F);
758       else {
759         errs() << argv[0] << ": cannot disable nonexistent builtin function "
760                << FuncName << '\n';
761         return 1;
762       }
763   }
764 
765   if (UseNPM) {
766     if (legacy::debugPassSpecified()) {
767       errs()
768           << "-debug-pass does not work with the new PM, either use "
769              "-debug-pass-manager, or use the legacy PM (-enable-new-pm=0)\n";
770       return 1;
771     }
772     if (PassPipeline.getNumOccurrences() > 0 && PassList.size() > 0) {
773       errs()
774           << "Cannot specify passes via both -foo-pass and --passes=foo-pass\n";
775       return 1;
776     }
777     auto NumOLevel = OptLevelO0 + OptLevelO1 + OptLevelO2 + OptLevelO3 +
778                      OptLevelOs + OptLevelOz;
779     if (NumOLevel > 1) {
780       errs() << "Cannot specify multiple -O#\n";
781       return 1;
782     }
783     if (NumOLevel > 0 &&
784         (PassPipeline.getNumOccurrences() > 0 || PassList.size() > 0)) {
785       errs() << "Cannot specify -O# and --passes=/--foo-pass, use "
786                 "-passes='default<O#>,other-pass'\n";
787       return 1;
788     }
789     std::string Pipeline = PassPipeline;
790 
791     SmallVector<StringRef, 4> Passes;
792     if (OptLevelO0)
793       Pipeline = "default<O0>";
794     if (OptLevelO1)
795       Pipeline = "default<O1>";
796     if (OptLevelO2)
797       Pipeline = "default<O2>";
798     if (OptLevelO3)
799       Pipeline = "default<O3>";
800     if (OptLevelOs)
801       Pipeline = "default<Os>";
802     if (OptLevelOz)
803       Pipeline = "default<Oz>";
804     for (const auto &P : PassList)
805       Passes.push_back(P->getPassArgument());
806     OutputKind OK = OK_NoOutput;
807     if (!NoOutput)
808       OK = OutputAssembly
809                ? OK_OutputAssembly
810                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
811 
812     VerifierKind VK = VK_VerifyInAndOut;
813     if (NoVerify)
814       VK = VK_NoVerifier;
815     else if (VerifyEach)
816       VK = VK_VerifyEachPass;
817 
818     // The user has asked to use the new pass manager and provided a pipeline
819     // string. Hand off the rest of the functionality to the new code for that
820     // layer.
821     return runPassPipeline(argv[0], *M, TM.get(), &TLII, Out.get(),
822                            ThinLinkOut.get(), RemarksFile.get(), Pipeline,
823                            Passes, PluginList, OK, VK, PreserveAssemblyUseListOrder,
824                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
825                            EmitModuleHash, EnableDebugify)
826                ? 0
827                : 1;
828   }
829 
830   // Create a PassManager to hold and optimize the collection of passes we are
831   // about to build. If the -debugify-each option is set, wrap each pass with
832   // the (-check)-debugify passes.
833   DebugifyCustomPassManager Passes;
834   DebugifyStatsMap DIStatsMap;
835   DebugInfoPerPass DebugInfoBeforePass;
836   if (DebugifyEach) {
837     Passes.setDebugifyMode(DebugifyMode::SyntheticDebugInfo);
838     Passes.setDIStatsMap(DIStatsMap);
839   } else if (VerifyEachDebugInfoPreserve) {
840     Passes.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
841     Passes.setDebugInfoBeforePass(DebugInfoBeforePass);
842     if (!VerifyDIPreserveExport.empty())
843       Passes.setOrigDIVerifyBugsReportFilePath(VerifyDIPreserveExport);
844   }
845 
846   bool AddOneTimeDebugifyPasses =
847       (EnableDebugify && !DebugifyEach) ||
848       (VerifyDebugInfoPreserve && !VerifyEachDebugInfoPreserve);
849 
850   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
851 
852   // Add internal analysis passes from the target machine.
853   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
854                                                      : TargetIRAnalysis()));
855 
856   if (AddOneTimeDebugifyPasses) {
857     if (EnableDebugify) {
858       Passes.setDIStatsMap(DIStatsMap);
859       Passes.add(createDebugifyModulePass());
860     } else if (VerifyDebugInfoPreserve) {
861       Passes.setDebugInfoBeforePass(DebugInfoBeforePass);
862       Passes.add(createDebugifyModulePass(
863           DebugifyMode::OriginalDebugInfo, "",
864           &(Passes.getDebugInfoPerPass())));
865     }
866   }
867 
868   std::unique_ptr<legacy::FunctionPassManager> FPasses;
869   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
870       OptLevelO3) {
871     FPasses.reset(new legacy::FunctionPassManager(M.get()));
872     FPasses->add(createTargetTransformInfoWrapperPass(
873         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
874   }
875 
876   if (PrintBreakpoints) {
877     // Default to standard output.
878     if (!Out) {
879       if (OutputFilename.empty())
880         OutputFilename = "-";
881 
882       std::error_code EC;
883       Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,
884                                               sys::fs::OF_None);
885       if (EC) {
886         errs() << EC.message() << '\n';
887         return 1;
888       }
889     }
890     Passes.add(createBreakpointPrinter(Out->os()));
891     NoOutput = true;
892   }
893 
894   if (TM) {
895     // FIXME: We should dyn_cast this when supported.
896     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
897     Pass *TPC = LTM.createPassConfig(Passes);
898     Passes.add(TPC);
899   }
900 
901   // Create a new optimization pass for each one specified on the command line
902   for (unsigned i = 0; i < PassList.size(); ++i) {
903     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
904       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
905       OptLevelO0 = false;
906     }
907 
908     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
909       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
910       OptLevelO1 = false;
911     }
912 
913     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
914       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
915       OptLevelO2 = false;
916     }
917 
918     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
919       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
920       OptLevelOs = false;
921     }
922 
923     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
924       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
925       OptLevelOz = false;
926     }
927 
928     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
929       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
930       OptLevelO3 = false;
931     }
932 
933     const PassInfo *PassInf = PassList[i];
934     Pass *P = nullptr;
935     if (PassInf->getNormalCtor())
936       P = PassInf->getNormalCtor()();
937     else
938       errs() << argv[0] << ": cannot create pass: "
939              << PassInf->getPassName() << "\n";
940     if (P)
941       addPass(Passes, P);
942   }
943 
944   if (OptLevelO0)
945     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
946 
947   if (OptLevelO1)
948     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
949 
950   if (OptLevelO2)
951     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
952 
953   if (OptLevelOs)
954     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
955 
956   if (OptLevelOz)
957     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
958 
959   if (OptLevelO3)
960     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
961 
962   if (FPasses) {
963     FPasses->doInitialization();
964     for (Function &F : *M)
965       FPasses->run(F);
966     FPasses->doFinalization();
967   }
968 
969   // Check that the module is well formed on completion of optimization
970   if (!NoVerify && !VerifyEach)
971     Passes.add(createVerifierPass());
972 
973   if (AddOneTimeDebugifyPasses) {
974     if (EnableDebugify)
975       Passes.add(createCheckDebugifyModulePass(false));
976     else if (VerifyDebugInfoPreserve) {
977       if (!VerifyDIPreserveExport.empty())
978         Passes.setOrigDIVerifyBugsReportFilePath(VerifyDIPreserveExport);
979       Passes.add(createCheckDebugifyModulePass(
980           false, "", nullptr, DebugifyMode::OriginalDebugInfo,
981           &(Passes.getDebugInfoPerPass()), VerifyDIPreserveExport));
982     }
983   }
984 
985   // In run twice mode, we want to make sure the output is bit-by-bit
986   // equivalent if we run the pass manager again, so setup two buffers and
987   // a stream to write to them. Note that llc does something similar and it
988   // may be worth to abstract this out in the future.
989   SmallVector<char, 0> Buffer;
990   SmallVector<char, 0> FirstRunBuffer;
991   std::unique_ptr<raw_svector_ostream> BOS;
992   raw_ostream *OS = nullptr;
993 
994   const bool ShouldEmitOutput = !NoOutput;
995 
996   // Write bitcode or assembly to the output as the last step...
997   if (ShouldEmitOutput || RunTwice) {
998     assert(Out);
999     OS = &Out->os();
1000     if (RunTwice) {
1001       BOS = std::make_unique<raw_svector_ostream>(Buffer);
1002       OS = BOS.get();
1003     }
1004     if (OutputAssembly) {
1005       if (EmitSummaryIndex)
1006         report_fatal_error("Text output is incompatible with -module-summary");
1007       if (EmitModuleHash)
1008         report_fatal_error("Text output is incompatible with -module-hash");
1009       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
1010     } else if (OutputThinLTOBC)
1011       Passes.add(createWriteThinLTOBitcodePass(
1012           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
1013     else
1014       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
1015                                          EmitSummaryIndex, EmitModuleHash));
1016   }
1017 
1018   // Before executing passes, print the final values of the LLVM options.
1019   cl::PrintOptionValues();
1020 
1021   if (!RunTwice) {
1022     // Now that we have all of the passes ready, run them.
1023     Passes.run(*M);
1024   } else {
1025     // If requested, run all passes twice with the same pass manager to catch
1026     // bugs caused by persistent state in the passes.
1027     std::unique_ptr<Module> M2(CloneModule(*M));
1028     // Run all passes on the original module first, so the second run processes
1029     // the clone to catch CloneModule bugs.
1030     Passes.run(*M);
1031     FirstRunBuffer = Buffer;
1032     Buffer.clear();
1033 
1034     Passes.run(*M2);
1035 
1036     // Compare the two outputs and make sure they're the same
1037     assert(Out);
1038     if (Buffer.size() != FirstRunBuffer.size() ||
1039         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
1040       errs()
1041           << "Running the pass manager twice changed the output.\n"
1042              "Writing the result of the second run to the specified output.\n"
1043              "To generate the one-run comparison binary, just run without\n"
1044              "the compile-twice option\n";
1045       if (ShouldEmitOutput) {
1046         Out->os() << BOS->str();
1047         Out->keep();
1048       }
1049       if (RemarksFile)
1050         RemarksFile->keep();
1051       return 1;
1052     }
1053     if (ShouldEmitOutput)
1054       Out->os() << BOS->str();
1055   }
1056 
1057   if (DebugifyEach && !DebugifyExport.empty())
1058     exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap());
1059 
1060   // Declare success.
1061   if (!NoOutput || PrintBreakpoints)
1062     Out->keep();
1063 
1064   if (RemarksFile)
1065     RemarksFile->keep();
1066 
1067   if (ThinLinkOut)
1068     ThinLinkOut->keep();
1069 
1070   return 0;
1071 }
1072