xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision 2cff3dec)
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/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/Remarks/HotnessThresholdParser.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/YAMLTraits.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/IPO/AlwaysInliner.h"
56 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
57 #include "llvm/Transforms/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(LLVM_ENABLE_NEW_PASS_MANAGER));
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 PrintEachXForm("p", cl::desc("Print module after each transformation"));
106 
107 static cl::opt<bool>
108 NoOutput("disable-output",
109          cl::desc("Do not write result bitcode file"), cl::Hidden);
110 
111 static cl::opt<bool>
112 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
113 
114 static cl::opt<bool>
115     OutputThinLTOBC("thinlto-bc",
116                     cl::desc("Write output as ThinLTO-ready bitcode"));
117 
118 static cl::opt<bool>
119     SplitLTOUnit("thinlto-split-lto-unit",
120                  cl::desc("Enable splitting of a ThinLTO LTOUnit"));
121 
122 static cl::opt<std::string> ThinLinkBitcodeFile(
123     "thin-link-bitcode-file", cl::value_desc("filename"),
124     cl::desc(
125         "A file in which to write minimized bitcode for the thin link only"));
126 
127 static cl::opt<bool>
128 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
129 
130 static cl::opt<bool> NoUpgradeDebugInfo("disable-upgrade-debug-info",
131                                         cl::desc("Generate invalid output"),
132                                         cl::ReallyHidden);
133 
134 static cl::opt<bool> VerifyEach("verify-each",
135                                 cl::desc("Verify after each transform"));
136 
137 static cl::opt<bool>
138     DisableDITypeMap("disable-debug-info-type-map",
139                      cl::desc("Don't use a uniquing type map for debug info"));
140 
141 static cl::opt<bool>
142 StripDebug("strip-debug",
143            cl::desc("Strip debugger symbol info from translation unit"));
144 
145 static cl::opt<bool>
146     StripNamedMetadata("strip-named-metadata",
147                        cl::desc("Strip module-level named metadata"));
148 
149 static cl::opt<bool>
150     DisableInline("disable-inlining",
151                   cl::desc("Do not run the inliner pass (legacy PM only)"));
152 
153 static cl::opt<bool>
154 DisableOptimizations("disable-opt",
155                      cl::desc("Do not run any optimization passes"));
156 
157 static cl::opt<bool> StandardLinkOpts(
158     "std-link-opts",
159     cl::desc("Include the standard link time optimizations (legacy PM only)"));
160 
161 static cl::opt<bool>
162     OptLevelO0("O0", cl::desc("Optimization level 0. Similar to clang -O0. "
163                               "Use -passes='default<O0>' for the new PM"));
164 
165 static cl::opt<bool>
166     OptLevelO1("O1", cl::desc("Optimization level 1. Similar to clang -O1. "
167                               "Use -passes='default<O1>' for the new PM"));
168 
169 static cl::opt<bool>
170     OptLevelO2("O2", cl::desc("Optimization level 2. Similar to clang -O2. "
171                               "Use -passes='default<O2>' for the new PM"));
172 
173 static cl::opt<bool>
174     OptLevelOs("Os", cl::desc("Like -O2 but size-conscious. Similar to clang "
175                               "-Os. Use -passes='default<Os>' for the new PM"));
176 
177 static cl::opt<bool> OptLevelOz(
178     "Oz",
179     cl::desc("Like -O2 but optimize for code size above all else. Similar to "
180              "clang -Oz. Use -passes='default<Oz>' for the new PM"));
181 
182 static cl::opt<bool>
183     OptLevelO3("O3", cl::desc("Optimization level 3. Similar to clang -O3. "
184                               "Use -passes='default<O3>' for the new PM"));
185 
186 static cl::opt<unsigned> CodeGenOptLevel(
187     "codegen-opt-level",
188     cl::desc("Override optimization level for codegen hooks, legacy PM only"));
189 
190 static cl::opt<std::string>
191 TargetTriple("mtriple", cl::desc("Override target triple for module"));
192 
193 cl::opt<bool> DisableLoopUnrolling(
194     "disable-loop-unrolling",
195     cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false));
196 
197 static cl::opt<bool> EmitSummaryIndex("module-summary",
198                                       cl::desc("Emit module summary index"),
199                                       cl::init(false));
200 
201 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
202                                     cl::init(false));
203 
204 static cl::opt<bool>
205 DisableSimplifyLibCalls("disable-simplify-libcalls",
206                         cl::desc("Disable simplify-libcalls"));
207 
208 static cl::list<std::string>
209 DisableBuiltins("disable-builtin",
210                 cl::desc("Disable specific target library builtin function"),
211                 cl::ZeroOrMore);
212 
213 static cl::opt<bool>
214     AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization. "
215                                     "Legacy pass manager only."));
216 
217 static cl::opt<bool> EnableDebugify(
218     "enable-debugify",
219     cl::desc(
220         "Start the pipeline with debugify and end it with check-debugify"));
221 
222 static cl::opt<bool> VerifyDebugInfoPreserve(
223     "verify-debuginfo-preserve",
224     cl::desc("Start the pipeline with collecting and end it with checking of "
225              "debug info preservation."));
226 
227 static cl::opt<bool> VerifyEachDebugInfoPreserve(
228     "verify-each-debuginfo-preserve",
229     cl::desc("Start each pass with collecting and end it with checking of "
230              "debug info preservation."));
231 
232 static cl::opt<bool>
233 PrintBreakpoints("print-breakpoints-for-testing",
234                  cl::desc("Print select breakpoints location for testing"));
235 
236 static cl::opt<std::string> ClDataLayout("data-layout",
237                                          cl::desc("data layout string to use"),
238                                          cl::value_desc("layout-string"),
239                                          cl::init(""));
240 
241 static cl::opt<bool> PreserveBitcodeUseListOrder(
242     "preserve-bc-uselistorder",
243     cl::desc("Preserve use-list order when writing LLVM bitcode."),
244     cl::init(true), cl::Hidden);
245 
246 static cl::opt<bool> PreserveAssemblyUseListOrder(
247     "preserve-ll-uselistorder",
248     cl::desc("Preserve use-list order when writing LLVM assembly."),
249     cl::init(false), cl::Hidden);
250 
251 static cl::opt<bool> RunTwice("run-twice",
252                               cl::desc("Run all passes twice, re-using the "
253                                        "same pass manager (legacy PM only)."),
254                               cl::init(false), cl::Hidden);
255 
256 static cl::opt<bool> DiscardValueNames(
257     "discard-value-names",
258     cl::desc("Discard names from Value (other than GlobalValue)."),
259     cl::init(false), cl::Hidden);
260 
261 static cl::opt<bool> Coroutines(
262   "enable-coroutines",
263   cl::desc("Enable coroutine passes."),
264   cl::init(false), cl::Hidden);
265 
266 static cl::opt<bool> TimeTrace(
267     "time-trace",
268     cl::desc("Record time trace"));
269 
270 static cl::opt<unsigned> TimeTraceGranularity(
271     "time-trace-granularity",
272     cl::desc("Minimum time granularity (in microseconds) traced by time profiler"),
273     cl::init(500), cl::Hidden);
274 
275 static cl::opt<std::string>
276     TimeTraceFile("time-trace-file",
277                     cl::desc("Specify time trace file destination"),
278                     cl::value_desc("filename"));
279 
280 static cl::opt<bool> RemarksWithHotness(
281     "pass-remarks-with-hotness",
282     cl::desc("With PGO, include profile count in optimization remarks"),
283     cl::Hidden);
284 
285 static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
286     RemarksHotnessThreshold(
287         "pass-remarks-hotness-threshold",
288         cl::desc("Minimum profile count required for "
289                  "an optimization remark to be output. "
290                  "Use 'auto' to apply the threshold from profile summary."),
291         cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
292 
293 static cl::opt<std::string>
294     RemarksFilename("pass-remarks-output",
295                     cl::desc("Output filename for pass remarks"),
296                     cl::value_desc("filename"));
297 
298 static cl::opt<std::string>
299     RemarksPasses("pass-remarks-filter",
300                   cl::desc("Only record optimization remarks from passes whose "
301                            "names match the given regular expression"),
302                   cl::value_desc("regex"));
303 
304 static cl::opt<std::string> RemarksFormat(
305     "pass-remarks-format",
306     cl::desc("The format used for serializing remarks (default: YAML)"),
307     cl::value_desc("format"), cl::init("yaml"));
308 
309 cl::opt<PGOKind>
310     PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
311                 cl::desc("The kind of profile guided optimization"),
312                 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
313                            clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
314                                       "Instrument the IR to generate profile."),
315                            clEnumValN(InstrUse, "pgo-instr-use-pipeline",
316                                       "Use instrumented profile to guide PGO."),
317                            clEnumValN(SampleUse, "pgo-sample-use-pipeline",
318                                       "Use sampled profile to guide PGO.")));
319 cl::opt<std::string> ProfileFile("profile-file",
320                                  cl::desc("Path to the profile."), cl::Hidden);
321 
322 cl::opt<CSPGOKind> CSPGOKindFlag(
323     "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
324     cl::desc("The kind of context sensitive profile guided optimization"),
325     cl::values(
326         clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
327         clEnumValN(
328             CSInstrGen, "cspgo-instr-gen-pipeline",
329             "Instrument (context sensitive) the IR to generate profile."),
330         clEnumValN(
331             CSInstrUse, "cspgo-instr-use-pipeline",
332             "Use instrumented (context sensitive) profile to guide PGO.")));
333 cl::opt<std::string> CSProfileGenFile(
334     "cs-profilegen-file",
335     cl::desc("Path to the instrumented context sensitive profile."),
336     cl::Hidden);
337 
338 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
339   // Add the pass to the pass manager...
340   PM.add(P);
341 
342   // If we are verifying all of the intermediate steps, add the verifier...
343   if (VerifyEach)
344     PM.add(createVerifierPass());
345 }
346 
347 /// This routine adds optimization passes based on selected optimization level,
348 /// OptLevel.
349 ///
350 /// OptLevel - Optimization Level
351 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
352                                   legacy::FunctionPassManager &FPM,
353                                   TargetMachine *TM, unsigned OptLevel,
354                                   unsigned SizeLevel) {
355   if (!NoVerify || VerifyEach)
356     FPM.add(createVerifierPass()); // Verify that input is correct
357 
358   PassManagerBuilder Builder;
359   Builder.OptLevel = OptLevel;
360   Builder.SizeLevel = SizeLevel;
361 
362   if (DisableInline) {
363     // No inlining pass
364   } else 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 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
413   PassManagerBuilder Builder;
414   Builder.VerifyInput = true;
415   if (DisableOptimizations)
416     Builder.OptLevel = 0;
417 
418   if (!DisableInline)
419     Builder.Inliner = createFunctionInliningPass();
420   Builder.populateLTOPassManager(PM);
421 }
422 
423 //===----------------------------------------------------------------------===//
424 // CodeGen-related helper functions.
425 //
426 
427 static CodeGenOpt::Level GetCodeGenOptLevel() {
428   if (CodeGenOptLevel.getNumOccurrences())
429     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
430   if (OptLevelO1)
431     return CodeGenOpt::Less;
432   if (OptLevelO2)
433     return CodeGenOpt::Default;
434   if (OptLevelO3)
435     return CodeGenOpt::Aggressive;
436   return CodeGenOpt::None;
437 }
438 
439 // Returns the TargetMachine instance or zero if no triple is provided.
440 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
441                                        StringRef FeaturesStr,
442                                        const TargetOptions &Options) {
443   std::string Error;
444   const Target *TheTarget =
445       TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
446   // Some modules don't specify a triple, and this is okay.
447   if (!TheTarget) {
448     return nullptr;
449   }
450 
451   return TheTarget->createTargetMachine(
452       TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
453       Options, codegen::getExplicitRelocModel(),
454       codegen::getExplicitCodeModel(), GetCodeGenOptLevel());
455 }
456 
457 #ifdef BUILD_EXAMPLES
458 void initializeExampleIRTransforms(llvm::PassRegistry &Registry);
459 #endif
460 
461 struct TimeTracerRAII {
462   TimeTracerRAII(StringRef ProgramName) {
463     if (TimeTrace)
464       timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName);
465   }
466   ~TimeTracerRAII() {
467     if (TimeTrace) {
468       if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
469         handleAllErrors(std::move(E), [&](const StringError &SE) {
470           errs() << SE.getMessage() << "\n";
471         });
472         return;
473       }
474       timeTraceProfilerCleanup();
475     }
476   }
477 };
478 
479 // For use in NPM transition. Currently this contains most codegen-specific
480 // passes. Remove passes from here when porting to the NPM.
481 // TODO: use a codegen version of PassRegistry.def/PassBuilder::is*Pass() once
482 // it exists.
483 static bool shouldPinPassToLegacyPM(StringRef Pass) {
484   std::vector<StringRef> PassNameExactToIgnore = {
485       "nvvm-reflect",
486       "nvvm-intr-range",
487       "amdgpu-simplifylib",
488       "amdgpu-usenative",
489       "amdgpu-promote-alloca",
490       "amdgpu-promote-alloca-to-vector",
491       "amdgpu-lower-kernel-attributes",
492       "amdgpu-propagate-attributes-early",
493       "amdgpu-propagate-attributes-late",
494       "amdgpu-unify-metadata",
495       "amdgpu-printf-runtime-binding",
496       "amdgpu-always-inline"};
497   if (llvm::is_contained(PassNameExactToIgnore, Pass))
498     return false;
499 
500   std::vector<StringRef> PassNamePrefix = {
501       "x86-",  "xcore-", "wasm-",    "systemz-", "ppc-",    "nvvm-",   "nvptx-",
502       "mips-", "lanai-", "hexagon-", "bpf-",     "avr-",    "thumb2-", "arm-",
503       "si-",   "gcn-",   "amdgpu-",  "aarch64-", "amdgcn-", "polly-"};
504   std::vector<StringRef> PassNameContain = {"ehprepare"};
505   std::vector<StringRef> PassNameExact = {
506       "safe-stack",           "cost-model",
507       "codegenprepare",       "interleaved-load-combine",
508       "unreachableblockelim", "verify-safepoint-ir",
509       "atomic-expand",
510       "hardware-loops",       "type-promotion",
511       "mve-tail-predication", "interleaved-access",
512       "global-merge",         "pre-isel-intrinsic-lowering",
513       "expand-reductions",    "indirectbr-expand",
514       "generic-to-nvvm",      "expandmemcmp",
515       "loop-reduce",          "lower-amx-type",
516       "polyhedral-info",      "replace-with-veclib"};
517   for (const auto &P : PassNamePrefix)
518     if (Pass.startswith(P))
519       return true;
520   for (const auto &P : PassNameContain)
521     if (Pass.contains(P))
522       return true;
523   return llvm::is_contained(PassNameExact, Pass);
524 }
525 
526 // For use in NPM transition.
527 static bool shouldForceLegacyPM() {
528   for (const auto &P : PassList) {
529     StringRef Arg = P->getPassArgument();
530     if (shouldPinPassToLegacyPM(Arg))
531       return true;
532   }
533   return false;
534 }
535 
536 //===----------------------------------------------------------------------===//
537 // main for opt
538 //
539 int main(int argc, char **argv) {
540   InitLLVM X(argc, argv);
541 
542   // Enable debug stream buffering.
543   EnableDebugBuffering = true;
544 
545   LLVMContext Context;
546 
547   InitializeAllTargets();
548   InitializeAllTargetMCs();
549   InitializeAllAsmPrinters();
550   InitializeAllAsmParsers();
551 
552   // Initialize passes
553   PassRegistry &Registry = *PassRegistry::getPassRegistry();
554   initializeCore(Registry);
555   initializeCoroutines(Registry);
556   initializeScalarOpts(Registry);
557   initializeObjCARCOpts(Registry);
558   initializeVectorization(Registry);
559   initializeIPO(Registry);
560   initializeAnalysis(Registry);
561   initializeTransformUtils(Registry);
562   initializeInstCombine(Registry);
563   initializeAggressiveInstCombine(Registry);
564   initializeInstrumentation(Registry);
565   initializeTarget(Registry);
566   // For codegen passes, only passes that do IR to IR transformation are
567   // supported.
568   initializeExpandMemCmpPassPass(Registry);
569   initializeScalarizeMaskedMemIntrinLegacyPassPass(Registry);
570   initializeCodeGenPreparePass(Registry);
571   initializeAtomicExpandPass(Registry);
572   initializeRewriteSymbolsLegacyPassPass(Registry);
573   initializeWinEHPreparePass(Registry);
574   initializeDwarfEHPrepareLegacyPassPass(Registry);
575   initializeSafeStackLegacyPassPass(Registry);
576   initializeSjLjEHPreparePass(Registry);
577   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
578   initializeGlobalMergePass(Registry);
579   initializeIndirectBrExpandPassPass(Registry);
580   initializeInterleavedLoadCombinePass(Registry);
581   initializeInterleavedAccessPass(Registry);
582   initializeEntryExitInstrumenterPass(Registry);
583   initializePostInlineEntryExitInstrumenterPass(Registry);
584   initializeUnreachableBlockElimLegacyPassPass(Registry);
585   initializeExpandReductionsPass(Registry);
586   initializeWasmEHPreparePass(Registry);
587   initializeWriteBitcodePassPass(Registry);
588   initializeHardwareLoopsPass(Registry);
589   initializeTypePromotionPass(Registry);
590   initializeReplaceWithVeclibLegacyPass(Registry);
591 
592 #ifdef BUILD_EXAMPLES
593   initializeExampleIRTransforms(Registry);
594 #endif
595 
596   cl::ParseCommandLineOptions(argc, argv,
597     "llvm .bc -> .bc modular optimizer and analysis printer\n");
598 
599   if (AnalyzeOnly && NoOutput) {
600     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\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 = OutputAssembly ? sys::fs::OF_Text
696                                               : 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 && !AnalyzeOnly && !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 `-passes=` is specified, use NPM.
766   // If `-enable-new-pm` is specified and there are no codegen passes, use NPM.
767   // e.g. `-enable-new-pm -sroa` will use NPM.
768   // but `-enable-new-pm -codegenprepare` will still revert to legacy PM.
769   if ((EnableNewPassManager && !shouldForceLegacyPM()) ||
770       PassPipeline.getNumOccurrences() > 0) {
771     if (AnalyzeOnly) {
772       errs() << "Cannot specify -analyze under new pass manager, either "
773                 "specify '-enable-new-pm=0', or use the corresponding new pass "
774                 "manager pass, e.g. '-passes=print<scalar-evolution>'. For a "
775                 "full list of passes, see the '--print-passes' flag.\n";
776       return 1;
777     }
778     if (PassPipeline.getNumOccurrences() > 0 && PassList.size() > 0) {
779       errs()
780           << "Cannot specify passes via both -foo-pass and --passes=foo-pass\n";
781       return 1;
782     }
783     SmallVector<StringRef, 4> Passes;
784     if (OptLevelO0)
785       Passes.push_back("default<O0>");
786     if (OptLevelO1)
787       Passes.push_back("default<O1>");
788     if (OptLevelO2)
789       Passes.push_back("default<O2>");
790     if (OptLevelO3)
791       Passes.push_back("default<O3>");
792     if (OptLevelOs)
793       Passes.push_back("default<Os>");
794     if (OptLevelOz)
795       Passes.push_back("default<Oz>");
796     for (const auto &P : PassList)
797       Passes.push_back(P->getPassArgument());
798     OutputKind OK = OK_NoOutput;
799     if (!NoOutput)
800       OK = OutputAssembly
801                ? OK_OutputAssembly
802                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
803 
804     VerifierKind VK = VK_VerifyInAndOut;
805     if (NoVerify)
806       VK = VK_NoVerifier;
807     else if (VerifyEach)
808       VK = VK_VerifyEachPass;
809 
810     // The user has asked to use the new pass manager and provided a pipeline
811     // string. Hand off the rest of the functionality to the new code for that
812     // layer.
813     return runPassPipeline(argv[0], *M, TM.get(), &TLII, Out.get(),
814                            ThinLinkOut.get(), RemarksFile.get(), PassPipeline,
815                            Passes, OK, VK, PreserveAssemblyUseListOrder,
816                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
817                            EmitModuleHash, EnableDebugify, Coroutines)
818                ? 0
819                : 1;
820   }
821 
822   // Create a PassManager to hold and optimize the collection of passes we are
823   // about to build. If the -debugify-each option is set, wrap each pass with
824   // the (-check)-debugify passes.
825   DebugifyCustomPassManager Passes;
826   DebugifyStatsMap DIStatsMap;
827   DebugInfoPerPassMap DIPreservationMap;
828   if (DebugifyEach) {
829     Passes.setDebugifyMode(DebugifyMode::SyntheticDebugInfo);
830     Passes.setDIStatsMap(DIStatsMap);
831   } else if (VerifyEachDebugInfoPreserve) {
832     Passes.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
833     Passes.setDIPreservationMap(DIPreservationMap);
834   }
835 
836   bool AddOneTimeDebugifyPasses =
837       (EnableDebugify && !DebugifyEach) ||
838       (VerifyDebugInfoPreserve && !VerifyEachDebugInfoPreserve);
839 
840   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
841 
842   // Add internal analysis passes from the target machine.
843   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
844                                                      : TargetIRAnalysis()));
845 
846   if (AddOneTimeDebugifyPasses) {
847     if (EnableDebugify) {
848       Passes.setDIStatsMap(DIStatsMap);
849       Passes.add(createDebugifyModulePass());
850     } else if (VerifyDebugInfoPreserve) {
851       Passes.setDIPreservationMap(DIPreservationMap);
852       Passes.add(createDebugifyModulePass(
853           DebugifyMode::OriginalDebugInfo, "",
854           &(Passes.getDebugInfoPerPassMap())));
855     }
856   }
857 
858   std::unique_ptr<legacy::FunctionPassManager> FPasses;
859   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
860       OptLevelO3) {
861     FPasses.reset(new legacy::FunctionPassManager(M.get()));
862     FPasses->add(createTargetTransformInfoWrapperPass(
863         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
864   }
865 
866   if (PrintBreakpoints) {
867     // Default to standard output.
868     if (!Out) {
869       if (OutputFilename.empty())
870         OutputFilename = "-";
871 
872       std::error_code EC;
873       Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,
874                                               sys::fs::OF_None);
875       if (EC) {
876         errs() << EC.message() << '\n';
877         return 1;
878       }
879     }
880     Passes.add(createBreakpointPrinter(Out->os()));
881     NoOutput = true;
882   }
883 
884   if (TM) {
885     // FIXME: We should dyn_cast this when supported.
886     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
887     Pass *TPC = LTM.createPassConfig(Passes);
888     Passes.add(TPC);
889   }
890 
891   // Create a new optimization pass for each one specified on the command line
892   for (unsigned i = 0; i < PassList.size(); ++i) {
893     if (StandardLinkOpts &&
894         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
895       AddStandardLinkPasses(Passes);
896       StandardLinkOpts = false;
897     }
898 
899     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
900       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
901       OptLevelO0 = false;
902     }
903 
904     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
905       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
906       OptLevelO1 = false;
907     }
908 
909     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
910       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
911       OptLevelO2 = false;
912     }
913 
914     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
915       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
916       OptLevelOs = false;
917     }
918 
919     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
920       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
921       OptLevelOz = false;
922     }
923 
924     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
925       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
926       OptLevelO3 = false;
927     }
928 
929     const PassInfo *PassInf = PassList[i];
930     Pass *P = nullptr;
931     if (PassInf->getNormalCtor())
932       P = PassInf->getNormalCtor()();
933     else
934       errs() << argv[0] << ": cannot create pass: "
935              << PassInf->getPassName() << "\n";
936     if (P) {
937       PassKind Kind = P->getPassKind();
938       addPass(Passes, P);
939 
940       if (AnalyzeOnly) {
941         switch (Kind) {
942         case PT_Region:
943           Passes.add(createRegionPassPrinter(PassInf, Out->os()));
944           break;
945         case PT_Loop:
946           Passes.add(createLoopPassPrinter(PassInf, Out->os()));
947           break;
948         case PT_Function:
949           Passes.add(createFunctionPassPrinter(PassInf, Out->os()));
950           break;
951         case PT_CallGraphSCC:
952           Passes.add(createCallGraphPassPrinter(PassInf, Out->os()));
953           break;
954         default:
955           Passes.add(createModulePassPrinter(PassInf, Out->os()));
956           break;
957         }
958       }
959     }
960 
961     if (PrintEachXForm)
962       Passes.add(
963           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
964   }
965 
966   if (StandardLinkOpts) {
967     AddStandardLinkPasses(Passes);
968     StandardLinkOpts = false;
969   }
970 
971   if (OptLevelO0)
972     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
973 
974   if (OptLevelO1)
975     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
976 
977   if (OptLevelO2)
978     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
979 
980   if (OptLevelOs)
981     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
982 
983   if (OptLevelOz)
984     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
985 
986   if (OptLevelO3)
987     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
988 
989   if (FPasses) {
990     FPasses->doInitialization();
991     for (Function &F : *M)
992       FPasses->run(F);
993     FPasses->doFinalization();
994   }
995 
996   // Check that the module is well formed on completion of optimization
997   if (!NoVerify && !VerifyEach)
998     Passes.add(createVerifierPass());
999 
1000   if (AddOneTimeDebugifyPasses) {
1001     if (EnableDebugify)
1002       Passes.add(createCheckDebugifyModulePass(false));
1003     else if (VerifyDebugInfoPreserve)
1004       Passes.add(createCheckDebugifyModulePass(
1005           false, "", nullptr, DebugifyMode::OriginalDebugInfo,
1006           &(Passes.getDebugInfoPerPassMap())));
1007   }
1008 
1009   // In run twice mode, we want to make sure the output is bit-by-bit
1010   // equivalent if we run the pass manager again, so setup two buffers and
1011   // a stream to write to them. Note that llc does something similar and it
1012   // may be worth to abstract this out in the future.
1013   SmallVector<char, 0> Buffer;
1014   SmallVector<char, 0> FirstRunBuffer;
1015   std::unique_ptr<raw_svector_ostream> BOS;
1016   raw_ostream *OS = nullptr;
1017 
1018   const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly;
1019 
1020   // Write bitcode or assembly to the output as the last step...
1021   if (ShouldEmitOutput || RunTwice) {
1022     assert(Out);
1023     OS = &Out->os();
1024     if (RunTwice) {
1025       BOS = std::make_unique<raw_svector_ostream>(Buffer);
1026       OS = BOS.get();
1027     }
1028     if (OutputAssembly) {
1029       if (EmitSummaryIndex)
1030         report_fatal_error("Text output is incompatible with -module-summary");
1031       if (EmitModuleHash)
1032         report_fatal_error("Text output is incompatible with -module-hash");
1033       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
1034     } else if (OutputThinLTOBC)
1035       Passes.add(createWriteThinLTOBitcodePass(
1036           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
1037     else
1038       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
1039                                          EmitSummaryIndex, EmitModuleHash));
1040   }
1041 
1042   // Before executing passes, print the final values of the LLVM options.
1043   cl::PrintOptionValues();
1044 
1045   if (!RunTwice) {
1046     // Now that we have all of the passes ready, run them.
1047     Passes.run(*M);
1048   } else {
1049     // If requested, run all passes twice with the same pass manager to catch
1050     // bugs caused by persistent state in the passes.
1051     std::unique_ptr<Module> M2(CloneModule(*M));
1052     // Run all passes on the original module first, so the second run processes
1053     // the clone to catch CloneModule bugs.
1054     Passes.run(*M);
1055     FirstRunBuffer = Buffer;
1056     Buffer.clear();
1057 
1058     Passes.run(*M2);
1059 
1060     // Compare the two outputs and make sure they're the same
1061     assert(Out);
1062     if (Buffer.size() != FirstRunBuffer.size() ||
1063         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
1064       errs()
1065           << "Running the pass manager twice changed the output.\n"
1066              "Writing the result of the second run to the specified output.\n"
1067              "To generate the one-run comparison binary, just run without\n"
1068              "the compile-twice option\n";
1069       if (ShouldEmitOutput) {
1070         Out->os() << BOS->str();
1071         Out->keep();
1072       }
1073       if (RemarksFile)
1074         RemarksFile->keep();
1075       return 1;
1076     }
1077     if (ShouldEmitOutput)
1078       Out->os() << BOS->str();
1079   }
1080 
1081   if (DebugifyEach && !DebugifyExport.empty())
1082     exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap());
1083 
1084   // Declare success.
1085   if (!NoOutput || PrintBreakpoints)
1086     Out->keep();
1087 
1088   if (RemarksFile)
1089     RemarksFile->keep();
1090 
1091   if (ThinLinkOut)
1092     ThinLinkOut->keep();
1093 
1094   return 0;
1095 }
1096