xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision 3b142bc9)
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/Bitcode/BitcodeWriterPass.h"
25 #include "llvm/CodeGen/CommandFlags.inc"
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/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/LegacyPassNameParser.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/RemarkStreamer.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/LinkAllIR.h"
40 #include "llvm/LinkAllPasses.h"
41 #include "llvm/MC/SubtargetFeature.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/YAMLTraits.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/IPO/AlwaysInliner.h"
56 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
57 #include "llvm/Transforms/Utils/Cloning.h"
58 #include "llvm/Transforms/Utils/Debugify.h"
59 #include <algorithm>
60 #include <memory>
61 using namespace llvm;
62 using namespace opt_tool;
63 
64 // The OptimizationList is automatically populated with registered Passes by the
65 // PassNameParser.
66 //
67 static cl::list<const PassInfo*, bool, PassNameParser>
68 PassList(cl::desc("Optimizations available:"));
69 
70 // This flag specifies a textual description of the optimization pass pipeline
71 // to run over the module. This flag switches opt to use the new pass manager
72 // infrastructure, completely disabling all of the flags specific to the old
73 // pass management.
74 static cl::opt<std::string> PassPipeline(
75     "passes",
76     cl::desc("A textual description of the pass pipeline for optimizing"),
77     cl::Hidden);
78 
79 // Other command line options...
80 //
81 static cl::opt<std::string>
82 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
83     cl::init("-"), cl::value_desc("filename"));
84 
85 static cl::opt<std::string>
86 OutputFilename("o", cl::desc("Override output filename"),
87                cl::value_desc("filename"));
88 
89 static cl::opt<bool>
90 Force("f", cl::desc("Enable binary output on terminals"));
91 
92 static cl::opt<bool>
93 PrintEachXForm("p", cl::desc("Print module after each transformation"));
94 
95 static cl::opt<bool>
96 NoOutput("disable-output",
97          cl::desc("Do not write result bitcode file"), cl::Hidden);
98 
99 static cl::opt<bool>
100 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
101 
102 static cl::opt<bool>
103     OutputThinLTOBC("thinlto-bc",
104                     cl::desc("Write output as ThinLTO-ready bitcode"));
105 
106 static cl::opt<bool>
107     SplitLTOUnit("thinlto-split-lto-unit",
108                  cl::desc("Enable splitting of a ThinLTO LTOUnit"));
109 
110 static cl::opt<std::string> ThinLinkBitcodeFile(
111     "thin-link-bitcode-file", cl::value_desc("filename"),
112     cl::desc(
113         "A file in which to write minimized bitcode for the thin link only"));
114 
115 static cl::opt<bool>
116 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
117 
118 static cl::opt<bool>
119 VerifyEach("verify-each", cl::desc("Verify after each transform"));
120 
121 static cl::opt<bool>
122     DisableDITypeMap("disable-debug-info-type-map",
123                      cl::desc("Don't use a uniquing type map for debug info"));
124 
125 static cl::opt<bool>
126 StripDebug("strip-debug",
127            cl::desc("Strip debugger symbol info from translation unit"));
128 
129 static cl::opt<bool>
130     StripNamedMetadata("strip-named-metadata",
131                        cl::desc("Strip module-level named metadata"));
132 
133 static cl::opt<bool> DisableInline("disable-inlining",
134                                    cl::desc("Do not run the inliner pass"));
135 
136 static cl::opt<bool>
137 DisableOptimizations("disable-opt",
138                      cl::desc("Do not run any optimization passes"));
139 
140 static cl::opt<bool>
141 StandardLinkOpts("std-link-opts",
142                  cl::desc("Include the standard link time optimizations"));
143 
144 static cl::opt<bool>
145 OptLevelO0("O0",
146   cl::desc("Optimization level 0. Similar to clang -O0"));
147 
148 static cl::opt<bool>
149 OptLevelO1("O1",
150            cl::desc("Optimization level 1. Similar to clang -O1"));
151 
152 static cl::opt<bool>
153 OptLevelO2("O2",
154            cl::desc("Optimization level 2. Similar to clang -O2"));
155 
156 static cl::opt<bool>
157 OptLevelOs("Os",
158            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
159 
160 static cl::opt<bool>
161 OptLevelOz("Oz",
162            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
163 
164 static cl::opt<bool>
165 OptLevelO3("O3",
166            cl::desc("Optimization level 3. Similar to clang -O3"));
167 
168 static cl::opt<unsigned>
169 CodeGenOptLevel("codegen-opt-level",
170                 cl::desc("Override optimization level for codegen hooks"));
171 
172 static cl::opt<std::string>
173 TargetTriple("mtriple", cl::desc("Override target triple for module"));
174 
175 static cl::opt<bool>
176 DisableLoopUnrolling("disable-loop-unrolling",
177                      cl::desc("Disable loop unrolling in all relevant passes"),
178                      cl::init(false));
179 
180 static cl::opt<bool>
181 DisableSLPVectorization("disable-slp-vectorization",
182                         cl::desc("Disable the slp vectorization pass"),
183                         cl::init(false));
184 
185 static cl::opt<bool> EmitSummaryIndex("module-summary",
186                                       cl::desc("Emit module summary index"),
187                                       cl::init(false));
188 
189 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
190                                     cl::init(false));
191 
192 static cl::opt<bool>
193 DisableSimplifyLibCalls("disable-simplify-libcalls",
194                         cl::desc("Disable simplify-libcalls"));
195 
196 static cl::list<std::string>
197 DisableBuiltins("disable-builtin",
198                 cl::desc("Disable specific target library builtin function"),
199                 cl::ZeroOrMore);
200 
201 
202 static cl::opt<bool>
203 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
204 
205 static cl::alias
206 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
207 
208 static cl::opt<bool>
209 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
210 
211 static cl::opt<bool> EnableDebugify(
212     "enable-debugify",
213     cl::desc(
214         "Start the pipeline with debugify and end it with check-debugify"));
215 
216 static cl::opt<bool> DebugifyEach(
217     "debugify-each",
218     cl::desc(
219         "Start each pass with debugify and end it with check-debugify"));
220 
221 static cl::opt<std::string>
222     DebugifyExport("debugify-export",
223                    cl::desc("Export per-pass debugify statistics to this file"),
224                    cl::value_desc("filename"), cl::init(""));
225 
226 static cl::opt<bool>
227 PrintBreakpoints("print-breakpoints-for-testing",
228                  cl::desc("Print select breakpoints location for testing"));
229 
230 static cl::opt<std::string> ClDataLayout("data-layout",
231                                          cl::desc("data layout string to use"),
232                                          cl::value_desc("layout-string"),
233                                          cl::init(""));
234 
235 static cl::opt<bool> PreserveBitcodeUseListOrder(
236     "preserve-bc-uselistorder",
237     cl::desc("Preserve use-list order when writing LLVM bitcode."),
238     cl::init(true), cl::Hidden);
239 
240 static cl::opt<bool> PreserveAssemblyUseListOrder(
241     "preserve-ll-uselistorder",
242     cl::desc("Preserve use-list order when writing LLVM assembly."),
243     cl::init(false), cl::Hidden);
244 
245 static cl::opt<bool>
246     RunTwice("run-twice",
247              cl::desc("Run all passes twice, re-using the same pass manager."),
248              cl::init(false), cl::Hidden);
249 
250 static cl::opt<bool> DiscardValueNames(
251     "discard-value-names",
252     cl::desc("Discard names from Value (other than GlobalValue)."),
253     cl::init(false), cl::Hidden);
254 
255 static cl::opt<bool> Coroutines(
256   "enable-coroutines",
257   cl::desc("Enable coroutine passes."),
258   cl::init(false), cl::Hidden);
259 
260 static cl::opt<bool> RemarksWithHotness(
261     "pass-remarks-with-hotness",
262     cl::desc("With PGO, include profile count in optimization remarks"),
263     cl::Hidden);
264 
265 static cl::opt<unsigned>
266     RemarksHotnessThreshold("pass-remarks-hotness-threshold",
267                             cl::desc("Minimum profile count required for "
268                                      "an optimization remark to be output"),
269                             cl::Hidden);
270 
271 static cl::opt<std::string>
272     RemarksFilename("pass-remarks-output",
273                     cl::desc("Output filename for pass remarks"),
274                     cl::value_desc("filename"));
275 
276 static cl::opt<std::string>
277     RemarksPasses("pass-remarks-filter",
278                   cl::desc("Only record optimization remarks from passes whose "
279                            "names match the given regular expression"),
280                   cl::value_desc("regex"));
281 
282 static cl::opt<std::string> RemarksFormat(
283     "pass-remarks-format",
284     cl::desc("The format used for serializing remarks (default: YAML)"),
285     cl::value_desc("format"), cl::init("yaml"));
286 
287 cl::opt<PGOKind>
288     PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
289                 cl::desc("The kind of profile guided optimization"),
290                 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
291                            clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
292                                       "Instrument the IR to generate profile."),
293                            clEnumValN(InstrUse, "pgo-instr-use-pipeline",
294                                       "Use instrumented profile to guide PGO."),
295                            clEnumValN(SampleUse, "pgo-sample-use-pipeline",
296                                       "Use sampled profile to guide PGO.")));
297 cl::opt<std::string> ProfileFile("profile-file",
298                                  cl::desc("Path to the profile."), cl::Hidden);
299 
300 cl::opt<CSPGOKind> CSPGOKindFlag(
301     "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
302     cl::desc("The kind of context sensitive profile guided optimization"),
303     cl::values(
304         clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
305         clEnumValN(
306             CSInstrGen, "cspgo-instr-gen-pipeline",
307             "Instrument (context sensitive) the IR to generate profile."),
308         clEnumValN(
309             CSInstrUse, "cspgo-instr-use-pipeline",
310             "Use instrumented (context sensitive) profile to guide PGO.")));
311 cl::opt<std::string> CSProfileGenFile(
312     "cs-profilegen-file",
313     cl::desc("Path to the instrumented context sensitive profile."),
314     cl::Hidden);
315 
316 class OptCustomPassManager : public legacy::PassManager {
317   DebugifyStatsMap DIStatsMap;
318 
319 public:
320   using super = legacy::PassManager;
321 
322   void add(Pass *P) override {
323     // Wrap each pass with (-check)-debugify passes if requested, making
324     // exceptions for passes which shouldn't see -debugify instrumentation.
325     bool WrapWithDebugify = DebugifyEach && !P->getAsImmutablePass() &&
326                             !isIRPrintingPass(P) && !isBitcodeWriterPass(P);
327     if (!WrapWithDebugify) {
328       super::add(P);
329       return;
330     }
331 
332     // Apply -debugify/-check-debugify before/after each pass and collect
333     // debug info loss statistics.
334     PassKind Kind = P->getPassKind();
335     StringRef Name = P->getPassName();
336 
337     // TODO: Implement Debugify for LoopPass.
338     switch (Kind) {
339       case PT_Function:
340         super::add(createDebugifyFunctionPass());
341         super::add(P);
342         super::add(createCheckDebugifyFunctionPass(true, Name, &DIStatsMap));
343         break;
344       case PT_Module:
345         super::add(createDebugifyModulePass());
346         super::add(P);
347         super::add(createCheckDebugifyModulePass(true, Name, &DIStatsMap));
348         break;
349       default:
350         super::add(P);
351         break;
352     }
353   }
354 
355   const DebugifyStatsMap &getDebugifyStatsMap() const { return DIStatsMap; }
356 };
357 
358 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
359   // Add the pass to the pass manager...
360   PM.add(P);
361 
362   // If we are verifying all of the intermediate steps, add the verifier...
363   if (VerifyEach)
364     PM.add(createVerifierPass());
365 }
366 
367 /// This routine adds optimization passes based on selected optimization level,
368 /// OptLevel.
369 ///
370 /// OptLevel - Optimization Level
371 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
372                                   legacy::FunctionPassManager &FPM,
373                                   TargetMachine *TM, unsigned OptLevel,
374                                   unsigned SizeLevel) {
375   if (!NoVerify || VerifyEach)
376     FPM.add(createVerifierPass()); // Verify that input is correct
377 
378   PassManagerBuilder Builder;
379   Builder.OptLevel = OptLevel;
380   Builder.SizeLevel = SizeLevel;
381 
382   if (DisableInline) {
383     // No inlining pass
384   } else if (OptLevel > 1) {
385     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
386   } else {
387     Builder.Inliner = createAlwaysInlinerLegacyPass();
388   }
389   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
390                                DisableLoopUnrolling : OptLevel == 0;
391 
392   // Check if vectorization is explicitly disabled via -vectorize-loops=false.
393   // The flag enables vectorization in the LoopVectorize pass, it is on by
394   // default, and if it was disabled, leave it disabled here.
395   // Another flag that exists: -loop-vectorize, controls adding the pass to the
396   // pass manager. If set, the pass is added, and there is no additional check
397   // here for it.
398   if (Builder.LoopVectorize)
399     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
400 
401   // When #pragma vectorize is on for SLP, do the same as above
402   Builder.SLPVectorize =
403       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
404 
405   if (TM)
406     TM->adjustPassManager(Builder);
407 
408   if (Coroutines)
409     addCoroutinePassesToExtensionPoints(Builder);
410 
411   switch (PGOKindFlag) {
412   case InstrGen:
413     Builder.EnablePGOInstrGen = true;
414     Builder.PGOInstrGen = ProfileFile;
415     break;
416   case InstrUse:
417     Builder.PGOInstrUse = ProfileFile;
418     break;
419   case SampleUse:
420     Builder.PGOSampleUse = ProfileFile;
421     break;
422   default:
423     break;
424   }
425 
426   switch (CSPGOKindFlag) {
427   case CSInstrGen:
428     Builder.EnablePGOCSInstrGen = true;
429     break;
430   case CSInstrUse:
431     Builder.EnablePGOCSInstrUse = true;
432     break;
433   default:
434     break;
435   }
436 
437   Builder.populateFunctionPassManager(FPM);
438   Builder.populateModulePassManager(MPM);
439 }
440 
441 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
442   PassManagerBuilder Builder;
443   Builder.VerifyInput = true;
444   if (DisableOptimizations)
445     Builder.OptLevel = 0;
446 
447   if (!DisableInline)
448     Builder.Inliner = createFunctionInliningPass();
449   Builder.populateLTOPassManager(PM);
450 }
451 
452 //===----------------------------------------------------------------------===//
453 // CodeGen-related helper functions.
454 //
455 
456 static CodeGenOpt::Level GetCodeGenOptLevel() {
457   if (CodeGenOptLevel.getNumOccurrences())
458     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
459   if (OptLevelO1)
460     return CodeGenOpt::Less;
461   if (OptLevelO2)
462     return CodeGenOpt::Default;
463   if (OptLevelO3)
464     return CodeGenOpt::Aggressive;
465   return CodeGenOpt::None;
466 }
467 
468 // Returns the TargetMachine instance or zero if no triple is provided.
469 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
470                                        StringRef FeaturesStr,
471                                        const TargetOptions &Options) {
472   std::string Error;
473   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
474                                                          Error);
475   // Some modules don't specify a triple, and this is okay.
476   if (!TheTarget) {
477     return nullptr;
478   }
479 
480   return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
481                                         FeaturesStr, Options, getRelocModel(),
482                                         getCodeModel(), GetCodeGenOptLevel());
483 }
484 
485 #ifdef BUILD_EXAMPLES
486 void initializeExampleIRTransforms(llvm::PassRegistry &Registry);
487 #endif
488 
489 #ifdef LINK_POLLY_INTO_TOOLS
490 namespace polly {
491 void initializePollyPasses(llvm::PassRegistry &Registry);
492 }
493 #endif
494 
495 void exportDebugifyStats(llvm::StringRef Path, const DebugifyStatsMap &Map) {
496   std::error_code EC;
497   raw_fd_ostream OS{Path, EC};
498   if (EC) {
499     errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
500     return;
501   }
502 
503   OS << "Pass Name" << ',' << "# of missing debug values" << ','
504      << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
505      << "Missing/Expected location ratio" << '\n';
506   for (const auto &Entry : Map) {
507     StringRef Pass = Entry.first;
508     DebugifyStatistics Stats = Entry.second;
509 
510     OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
511        << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
512        << Stats.getEmptyLocationRatio() << '\n';
513   }
514 }
515 
516 //===----------------------------------------------------------------------===//
517 // main for opt
518 //
519 int main(int argc, char **argv) {
520   InitLLVM X(argc, argv);
521 
522   // Enable debug stream buffering.
523   EnableDebugBuffering = true;
524 
525   LLVMContext Context;
526 
527   InitializeAllTargets();
528   InitializeAllTargetMCs();
529   InitializeAllAsmPrinters();
530   InitializeAllAsmParsers();
531 
532   // Initialize passes
533   PassRegistry &Registry = *PassRegistry::getPassRegistry();
534   initializeCore(Registry);
535   initializeCoroutines(Registry);
536   initializeScalarOpts(Registry);
537   initializeObjCARCOpts(Registry);
538   initializeVectorization(Registry);
539   initializeIPO(Registry);
540   initializeAnalysis(Registry);
541   initializeTransformUtils(Registry);
542   initializeInstCombine(Registry);
543   initializeAggressiveInstCombine(Registry);
544   initializeInstrumentation(Registry);
545   initializeTarget(Registry);
546   // For codegen passes, only passes that do IR to IR transformation are
547   // supported.
548   initializeExpandMemCmpPassPass(Registry);
549   initializeScalarizeMaskedMemIntrinPass(Registry);
550   initializeCodeGenPreparePass(Registry);
551   initializeAtomicExpandPass(Registry);
552   initializeRewriteSymbolsLegacyPassPass(Registry);
553   initializeWinEHPreparePass(Registry);
554   initializeDwarfEHPreparePass(Registry);
555   initializeSafeStackLegacyPassPass(Registry);
556   initializeSjLjEHPreparePass(Registry);
557   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
558   initializeGlobalMergePass(Registry);
559   initializeIndirectBrExpandPassPass(Registry);
560   initializeInterleavedLoadCombinePass(Registry);
561   initializeInterleavedAccessPass(Registry);
562   initializeEntryExitInstrumenterPass(Registry);
563   initializePostInlineEntryExitInstrumenterPass(Registry);
564   initializeUnreachableBlockElimLegacyPassPass(Registry);
565   initializeExpandReductionsPass(Registry);
566   initializeWasmEHPreparePass(Registry);
567   initializeWriteBitcodePassPass(Registry);
568   initializeHardwareLoopsPass(Registry);
569 
570 #ifdef BUILD_EXAMPLES
571   initializeExampleIRTransforms(Registry);
572 #endif
573 
574 #ifdef LINK_POLLY_INTO_TOOLS
575   polly::initializePollyPasses(Registry);
576 #endif
577 
578   cl::ParseCommandLineOptions(argc, argv,
579     "llvm .bc -> .bc modular optimizer and analysis printer\n");
580 
581   if (AnalyzeOnly && NoOutput) {
582     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
583     return 1;
584   }
585 
586   SMDiagnostic Err;
587 
588   Context.setDiscardValueNames(DiscardValueNames);
589   if (!DisableDITypeMap)
590     Context.enableDebugTypeODRUniquing();
591 
592   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
593       setupOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
594                                RemarksFormat, RemarksWithHotness,
595                                RemarksHotnessThreshold);
596   if (Error E = RemarksFileOrErr.takeError()) {
597     errs() << toString(std::move(E)) << '\n';
598     return 1;
599   }
600   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
601 
602   // Load the input module...
603   std::unique_ptr<Module> M =
604       parseIRFile(InputFilename, Err, Context, !NoVerify, ClDataLayout);
605 
606   if (!M) {
607     Err.print(argv[0], errs());
608     return 1;
609   }
610 
611   // Strip debug info before running the verifier.
612   if (StripDebug)
613     StripDebugInfo(*M);
614 
615   // Erase module-level named metadata, if requested.
616   if (StripNamedMetadata) {
617     while (!M->named_metadata_empty()) {
618       NamedMDNode *NMD = &*M->named_metadata_begin();
619       M->eraseNamedMetadata(NMD);
620     }
621   }
622 
623   // If we are supposed to override the target triple or data layout, do so now.
624   if (!TargetTriple.empty())
625     M->setTargetTriple(Triple::normalize(TargetTriple));
626 
627   // Immediately run the verifier to catch any problems before starting up the
628   // pass pipelines.  Otherwise we can crash on broken code during
629   // doInitialization().
630   if (!NoVerify && verifyModule(*M, &errs())) {
631     errs() << argv[0] << ": " << InputFilename
632            << ": error: input module is broken!\n";
633     return 1;
634   }
635 
636   // Figure out what stream we are supposed to write to...
637   std::unique_ptr<ToolOutputFile> Out;
638   std::unique_ptr<ToolOutputFile> ThinLinkOut;
639   if (NoOutput) {
640     if (!OutputFilename.empty())
641       errs() << "WARNING: The -o (output filename) option is ignored when\n"
642                 "the --disable-output option is used.\n";
643   } else {
644     // Default to standard output.
645     if (OutputFilename.empty())
646       OutputFilename = "-";
647 
648     std::error_code EC;
649     sys::fs::OpenFlags Flags = OutputAssembly ? sys::fs::OF_Text
650                                               : sys::fs::OF_None;
651     Out.reset(new ToolOutputFile(OutputFilename, EC, Flags));
652     if (EC) {
653       errs() << EC.message() << '\n';
654       return 1;
655     }
656 
657     if (!ThinLinkBitcodeFile.empty()) {
658       ThinLinkOut.reset(
659           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None));
660       if (EC) {
661         errs() << EC.message() << '\n';
662         return 1;
663       }
664     }
665   }
666 
667   Triple ModuleTriple(M->getTargetTriple());
668   std::string CPUStr, FeaturesStr;
669   TargetMachine *Machine = nullptr;
670   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
671 
672   if (ModuleTriple.getArch()) {
673     CPUStr = getCPUStr();
674     FeaturesStr = getFeaturesStr();
675     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
676   } else if (ModuleTriple.getArchName() != "unknown" &&
677              ModuleTriple.getArchName() != "") {
678     errs() << argv[0] << ": unrecognized architecture '"
679            << ModuleTriple.getArchName() << "' provided.\n";
680     return 1;
681   }
682 
683   std::unique_ptr<TargetMachine> TM(Machine);
684 
685   // Override function attributes based on CPUStr, FeaturesStr, and command line
686   // flags.
687   setFunctionAttributes(CPUStr, FeaturesStr, *M);
688 
689   // If the output is set to be emitted to standard out, and standard out is a
690   // console, print out a warning message and refuse to do it.  We don't
691   // impress anyone by spewing tons of binary goo to a terminal.
692   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
693     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
694       NoOutput = true;
695 
696   if (OutputThinLTOBC)
697     M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit);
698 
699   if (PassPipeline.getNumOccurrences() > 0) {
700     OutputKind OK = OK_NoOutput;
701     if (!NoOutput)
702       OK = OutputAssembly
703                ? OK_OutputAssembly
704                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
705 
706     VerifierKind VK = VK_VerifyInAndOut;
707     if (NoVerify)
708       VK = VK_NoVerifier;
709     else if (VerifyEach)
710       VK = VK_VerifyEachPass;
711 
712     // The user has asked to use the new pass manager and provided a pipeline
713     // string. Hand off the rest of the functionality to the new code for that
714     // layer.
715     return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(),
716                            RemarksFile.get(), PassPipeline, OK, VK,
717                            PreserveAssemblyUseListOrder,
718                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
719                            EmitModuleHash, EnableDebugify)
720                ? 0
721                : 1;
722   }
723 
724   // Create a PassManager to hold and optimize the collection of passes we are
725   // about to build.
726   OptCustomPassManager Passes;
727   bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach;
728 
729   // Add an appropriate TargetLibraryInfo pass for the module's triple.
730   TargetLibraryInfoImpl TLII(ModuleTriple);
731 
732   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
733   if (DisableSimplifyLibCalls)
734     TLII.disableAllFunctions();
735   else {
736     // Disable individual builtin functions in TargetLibraryInfo.
737     LibFunc F;
738     for (auto &FuncName : DisableBuiltins)
739       if (TLII.getLibFunc(FuncName, F))
740         TLII.setUnavailable(F);
741       else {
742         errs() << argv[0] << ": cannot disable nonexistent builtin function "
743                << FuncName << '\n';
744         return 1;
745       }
746   }
747 
748   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
749 
750   // Add internal analysis passes from the target machine.
751   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
752                                                      : TargetIRAnalysis()));
753 
754   if (AddOneTimeDebugifyPasses)
755     Passes.add(createDebugifyModulePass());
756 
757   std::unique_ptr<legacy::FunctionPassManager> FPasses;
758   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
759       OptLevelO3) {
760     FPasses.reset(new legacy::FunctionPassManager(M.get()));
761     FPasses->add(createTargetTransformInfoWrapperPass(
762         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
763   }
764 
765   if (PrintBreakpoints) {
766     // Default to standard output.
767     if (!Out) {
768       if (OutputFilename.empty())
769         OutputFilename = "-";
770 
771       std::error_code EC;
772       Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,
773                                               sys::fs::OF_None);
774       if (EC) {
775         errs() << EC.message() << '\n';
776         return 1;
777       }
778     }
779     Passes.add(createBreakpointPrinter(Out->os()));
780     NoOutput = true;
781   }
782 
783   if (TM) {
784     // FIXME: We should dyn_cast this when supported.
785     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
786     Pass *TPC = LTM.createPassConfig(Passes);
787     Passes.add(TPC);
788   }
789 
790   // Create a new optimization pass for each one specified on the command line
791   for (unsigned i = 0; i < PassList.size(); ++i) {
792     if (StandardLinkOpts &&
793         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
794       AddStandardLinkPasses(Passes);
795       StandardLinkOpts = false;
796     }
797 
798     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
799       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
800       OptLevelO0 = false;
801     }
802 
803     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
804       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
805       OptLevelO1 = false;
806     }
807 
808     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
809       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
810       OptLevelO2 = false;
811     }
812 
813     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
814       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
815       OptLevelOs = false;
816     }
817 
818     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
819       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
820       OptLevelOz = false;
821     }
822 
823     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
824       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
825       OptLevelO3 = false;
826     }
827 
828     const PassInfo *PassInf = PassList[i];
829     Pass *P = nullptr;
830     if (PassInf->getNormalCtor())
831       P = PassInf->getNormalCtor()();
832     else
833       errs() << argv[0] << ": cannot create pass: "
834              << PassInf->getPassName() << "\n";
835     if (P) {
836       PassKind Kind = P->getPassKind();
837       addPass(Passes, P);
838 
839       if (AnalyzeOnly) {
840         switch (Kind) {
841         case PT_Region:
842           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
843           break;
844         case PT_Loop:
845           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
846           break;
847         case PT_Function:
848           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
849           break;
850         case PT_CallGraphSCC:
851           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
852           break;
853         default:
854           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
855           break;
856         }
857       }
858     }
859 
860     if (PrintEachXForm)
861       Passes.add(
862           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
863   }
864 
865   if (StandardLinkOpts) {
866     AddStandardLinkPasses(Passes);
867     StandardLinkOpts = false;
868   }
869 
870   if (OptLevelO0)
871     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
872 
873   if (OptLevelO1)
874     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
875 
876   if (OptLevelO2)
877     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
878 
879   if (OptLevelOs)
880     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
881 
882   if (OptLevelOz)
883     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
884 
885   if (OptLevelO3)
886     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
887 
888   if (FPasses) {
889     FPasses->doInitialization();
890     for (Function &F : *M)
891       FPasses->run(F);
892     FPasses->doFinalization();
893   }
894 
895   // Check that the module is well formed on completion of optimization
896   if (!NoVerify && !VerifyEach)
897     Passes.add(createVerifierPass());
898 
899   if (AddOneTimeDebugifyPasses)
900     Passes.add(createCheckDebugifyModulePass(false));
901 
902   // In run twice mode, we want to make sure the output is bit-by-bit
903   // equivalent if we run the pass manager again, so setup two buffers and
904   // a stream to write to them. Note that llc does something similar and it
905   // may be worth to abstract this out in the future.
906   SmallVector<char, 0> Buffer;
907   SmallVector<char, 0> FirstRunBuffer;
908   std::unique_ptr<raw_svector_ostream> BOS;
909   raw_ostream *OS = nullptr;
910 
911   // Write bitcode or assembly to the output as the last step...
912   if (!NoOutput && !AnalyzeOnly) {
913     assert(Out);
914     OS = &Out->os();
915     if (RunTwice) {
916       BOS = std::make_unique<raw_svector_ostream>(Buffer);
917       OS = BOS.get();
918     }
919     if (OutputAssembly) {
920       if (EmitSummaryIndex)
921         report_fatal_error("Text output is incompatible with -module-summary");
922       if (EmitModuleHash)
923         report_fatal_error("Text output is incompatible with -module-hash");
924       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
925     } else if (OutputThinLTOBC)
926       Passes.add(createWriteThinLTOBitcodePass(
927           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
928     else
929       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
930                                          EmitSummaryIndex, EmitModuleHash));
931   }
932 
933   // Before executing passes, print the final values of the LLVM options.
934   cl::PrintOptionValues();
935 
936   if (!RunTwice) {
937     // Now that we have all of the passes ready, run them.
938     Passes.run(*M);
939   } else {
940     // If requested, run all passes twice with the same pass manager to catch
941     // bugs caused by persistent state in the passes.
942     std::unique_ptr<Module> M2(CloneModule(*M));
943     // Run all passes on the original module first, so the second run processes
944     // the clone to catch CloneModule bugs.
945     Passes.run(*M);
946     FirstRunBuffer = Buffer;
947     Buffer.clear();
948 
949     Passes.run(*M2);
950 
951     // Compare the two outputs and make sure they're the same
952     assert(Out);
953     if (Buffer.size() != FirstRunBuffer.size() ||
954         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
955       errs()
956           << "Running the pass manager twice changed the output.\n"
957              "Writing the result of the second run to the specified output.\n"
958              "To generate the one-run comparison binary, just run without\n"
959              "the compile-twice option\n";
960       Out->os() << BOS->str();
961       Out->keep();
962       if (RemarksFile)
963         RemarksFile->keep();
964       return 1;
965     }
966     Out->os() << BOS->str();
967   }
968 
969   if (DebugifyEach && !DebugifyExport.empty())
970     exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap());
971 
972   // Declare success.
973   if (!NoOutput || PrintBreakpoints)
974     Out->keep();
975 
976   if (RemarksFile)
977     RemarksFile->keep();
978 
979   if (ThinLinkOut)
980     ThinLinkOut->keep();
981 
982   return 0;
983 }
984