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