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