1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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 #include "clang/CodeGen/BackendUtil.h"
10 #include "clang/Basic/CodeGenOptions.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/FrontendDiagnostic.h"
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Lex/HeaderSearchOptions.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/StackSafetyAnalysis.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/LTO/LTOBackend.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Passes/PassBuilder.h"
41 #include "llvm/Passes/PassPlugin.h"
42 #include "llvm/Passes/StandardInstrumentations.h"
43 #include "llvm/Support/BuryPointer.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TimeProfiler.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
56 #include "llvm/Transforms/Coroutines/CoroEarly.h"
57 #include "llvm/Transforms/Coroutines/CoroElide.h"
58 #include "llvm/Transforms/Coroutines/CoroSplit.h"
59 #include "llvm/Transforms/IPO.h"
60 #include "llvm/Transforms/IPO/AlwaysInliner.h"
61 #include "llvm/Transforms/IPO/LowerTypeTests.h"
62 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64 #include "llvm/Transforms/InstCombine/InstCombine.h"
65 #include "llvm/Transforms/Instrumentation.h"
66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
68 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
69 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
70 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
71 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
72 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
73 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
74 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
75 #include "llvm/Transforms/ObjCARC.h"
76 #include "llvm/Transforms/Scalar.h"
77 #include "llvm/Transforms/Scalar/GVN.h"
78 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
79 #include "llvm/Transforms/Utils.h"
80 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
81 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
82 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
83 #include "llvm/Transforms/Utils/SymbolRewriter.h"
84 #include "llvm/Transforms/Utils/UniqueInternalLinkageNames.h"
85 #include <memory>
86 using namespace clang;
87 using namespace llvm;
88 
89 #define HANDLE_EXTENSION(Ext)                                                  \
90   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
91 #include "llvm/Support/Extension.def"
92 
93 namespace {
94 
95 // Default filename used for profile generation.
96 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
97 
98 class EmitAssemblyHelper {
99   DiagnosticsEngine &Diags;
100   const HeaderSearchOptions &HSOpts;
101   const CodeGenOptions &CodeGenOpts;
102   const clang::TargetOptions &TargetOpts;
103   const LangOptions &LangOpts;
104   Module *TheModule;
105 
106   Timer CodeGenerationTime;
107 
108   std::unique_ptr<raw_pwrite_stream> OS;
109 
110   TargetIRAnalysis getTargetIRAnalysis() const {
111     if (TM)
112       return TM->getTargetIRAnalysis();
113 
114     return TargetIRAnalysis();
115   }
116 
117   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
118 
119   /// Generates the TargetMachine.
120   /// Leaves TM unchanged if it is unable to create the target machine.
121   /// Some of our clang tests specify triples which are not built
122   /// into clang. This is okay because these tests check the generated
123   /// IR, and they require DataLayout which depends on the triple.
124   /// In this case, we allow this method to fail and not report an error.
125   /// When MustCreateTM is used, we print an error if we are unable to load
126   /// the requested target.
127   void CreateTargetMachine(bool MustCreateTM);
128 
129   /// Add passes necessary to emit assembly or LLVM IR.
130   ///
131   /// \return True on success.
132   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
133                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
134 
135   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
136     std::error_code EC;
137     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
138                                                      llvm::sys::fs::OF_None);
139     if (EC) {
140       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
141       F.reset();
142     }
143     return F;
144   }
145 
146 public:
147   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
148                      const HeaderSearchOptions &HeaderSearchOpts,
149                      const CodeGenOptions &CGOpts,
150                      const clang::TargetOptions &TOpts,
151                      const LangOptions &LOpts, Module *M)
152       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
153         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
154         CodeGenerationTime("codegen", "Code Generation Time") {}
155 
156   ~EmitAssemblyHelper() {
157     if (CodeGenOpts.DisableFree)
158       BuryPointer(std::move(TM));
159   }
160 
161   std::unique_ptr<TargetMachine> TM;
162 
163   void EmitAssembly(BackendAction Action,
164                     std::unique_ptr<raw_pwrite_stream> OS);
165 
166   void EmitAssemblyWithNewPassManager(BackendAction Action,
167                                       std::unique_ptr<raw_pwrite_stream> OS);
168 };
169 
170 // We need this wrapper to access LangOpts and CGOpts from extension functions
171 // that we add to the PassManagerBuilder.
172 class PassManagerBuilderWrapper : public PassManagerBuilder {
173 public:
174   PassManagerBuilderWrapper(const Triple &TargetTriple,
175                             const CodeGenOptions &CGOpts,
176                             const LangOptions &LangOpts)
177       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
178         LangOpts(LangOpts) {}
179   const Triple &getTargetTriple() const { return TargetTriple; }
180   const CodeGenOptions &getCGOpts() const { return CGOpts; }
181   const LangOptions &getLangOpts() const { return LangOpts; }
182 
183 private:
184   const Triple &TargetTriple;
185   const CodeGenOptions &CGOpts;
186   const LangOptions &LangOpts;
187 };
188 }
189 
190 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
191   if (Builder.OptLevel > 0)
192     PM.add(createObjCARCAPElimPass());
193 }
194 
195 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
196   if (Builder.OptLevel > 0)
197     PM.add(createObjCARCExpandPass());
198 }
199 
200 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
201   if (Builder.OptLevel > 0)
202     PM.add(createObjCARCOptPass());
203 }
204 
205 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
206                                      legacy::PassManagerBase &PM) {
207   PM.add(createAddDiscriminatorsPass());
208 }
209 
210 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
211                                   legacy::PassManagerBase &PM) {
212   PM.add(createBoundsCheckingLegacyPass());
213 }
214 
215 static SanitizerCoverageOptions
216 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
217   SanitizerCoverageOptions Opts;
218   Opts.CoverageType =
219       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
220   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
221   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
222   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
223   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
224   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
225   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
226   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
227   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
228   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
229   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
230   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
231   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
232   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
233   return Opts;
234 }
235 
236 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
237                                      legacy::PassManagerBase &PM) {
238   const PassManagerBuilderWrapper &BuilderWrapper =
239       static_cast<const PassManagerBuilderWrapper &>(Builder);
240   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
241   auto Opts = getSancovOptsFromCGOpts(CGOpts);
242   PM.add(createModuleSanitizerCoverageLegacyPassPass(
243       Opts, CGOpts.SanitizeCoverageAllowlistFiles,
244       CGOpts.SanitizeCoverageBlocklistFiles));
245 }
246 
247 // Check if ASan should use GC-friendly instrumentation for globals.
248 // First of all, there is no point if -fdata-sections is off (expect for MachO,
249 // where this is not a factor). Also, on ELF this feature requires an assembler
250 // extension that only works with -integrated-as at the moment.
251 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
252   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
253     return false;
254   switch (T.getObjectFormat()) {
255   case Triple::MachO:
256   case Triple::COFF:
257     return true;
258   case Triple::ELF:
259     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
260   case Triple::GOFF:
261     llvm::report_fatal_error("ASan not implemented for GOFF");
262   case Triple::XCOFF:
263     llvm::report_fatal_error("ASan not implemented for XCOFF.");
264   case Triple::Wasm:
265   case Triple::UnknownObjectFormat:
266     break;
267   }
268   return false;
269 }
270 
271 static void addMemProfilerPasses(const PassManagerBuilder &Builder,
272                                  legacy::PassManagerBase &PM) {
273   PM.add(createMemProfilerFunctionPass());
274   PM.add(createModuleMemProfilerLegacyPassPass());
275 }
276 
277 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
278                                       legacy::PassManagerBase &PM) {
279   const PassManagerBuilderWrapper &BuilderWrapper =
280       static_cast<const PassManagerBuilderWrapper&>(Builder);
281   const Triple &T = BuilderWrapper.getTargetTriple();
282   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
283   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
284   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
285   bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
286   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
287   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
288                                             UseAfterScope));
289   PM.add(createModuleAddressSanitizerLegacyPassPass(
290       /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
291 }
292 
293 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
294                                             legacy::PassManagerBase &PM) {
295   PM.add(createAddressSanitizerFunctionPass(
296       /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
297   PM.add(createModuleAddressSanitizerLegacyPassPass(
298       /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
299       /*UseOdrIndicator*/ false));
300 }
301 
302 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
303                                             legacy::PassManagerBase &PM) {
304   const PassManagerBuilderWrapper &BuilderWrapper =
305       static_cast<const PassManagerBuilderWrapper &>(Builder);
306   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
307   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
308   PM.add(
309       createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
310 }
311 
312 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
313                                             legacy::PassManagerBase &PM) {
314   PM.add(createHWAddressSanitizerLegacyPassPass(
315       /*CompileKernel*/ true, /*Recover*/ true));
316 }
317 
318 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
319                                              legacy::PassManagerBase &PM,
320                                              bool CompileKernel) {
321   const PassManagerBuilderWrapper &BuilderWrapper =
322       static_cast<const PassManagerBuilderWrapper&>(Builder);
323   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
324   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
325   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
326   PM.add(createMemorySanitizerLegacyPassPass(
327       MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
328 
329   // MemorySanitizer inserts complex instrumentation that mostly follows
330   // the logic of the original code, but operates on "shadow" values.
331   // It can benefit from re-running some general purpose optimization passes.
332   if (Builder.OptLevel > 0) {
333     PM.add(createEarlyCSEPass());
334     PM.add(createReassociatePass());
335     PM.add(createLICMPass());
336     PM.add(createGVNPass());
337     PM.add(createInstructionCombiningPass());
338     PM.add(createDeadStoreEliminationPass());
339   }
340 }
341 
342 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
343                                    legacy::PassManagerBase &PM) {
344   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
345 }
346 
347 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
348                                          legacy::PassManagerBase &PM) {
349   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
350 }
351 
352 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
353                                    legacy::PassManagerBase &PM) {
354   PM.add(createThreadSanitizerLegacyPassPass());
355 }
356 
357 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
358                                      legacy::PassManagerBase &PM) {
359   const PassManagerBuilderWrapper &BuilderWrapper =
360       static_cast<const PassManagerBuilderWrapper&>(Builder);
361   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
362   PM.add(
363       createDataFlowSanitizerLegacyPassPass(LangOpts.SanitizerBlacklistFiles));
364 }
365 
366 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
367                                          const CodeGenOptions &CodeGenOpts) {
368   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
369 
370   switch (CodeGenOpts.getVecLib()) {
371   case CodeGenOptions::Accelerate:
372     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
373     break;
374   case CodeGenOptions::LIBMVEC:
375     switch(TargetTriple.getArch()) {
376       default:
377         break;
378       case llvm::Triple::x86_64:
379         TLII->addVectorizableFunctionsFromVecLib
380                 (TargetLibraryInfoImpl::LIBMVEC_X86);
381         break;
382     }
383     break;
384   case CodeGenOptions::MASSV:
385     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
386     break;
387   case CodeGenOptions::SVML:
388     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
389     break;
390   default:
391     break;
392   }
393   return TLII;
394 }
395 
396 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
397                                   legacy::PassManager *MPM) {
398   llvm::SymbolRewriter::RewriteDescriptorList DL;
399 
400   llvm::SymbolRewriter::RewriteMapParser MapParser;
401   for (const auto &MapFile : Opts.RewriteMapFiles)
402     MapParser.parse(MapFile, &DL);
403 
404   MPM->add(createRewriteSymbolsPass(DL));
405 }
406 
407 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
408   switch (CodeGenOpts.OptimizationLevel) {
409   default:
410     llvm_unreachable("Invalid optimization level!");
411   case 0:
412     return CodeGenOpt::None;
413   case 1:
414     return CodeGenOpt::Less;
415   case 2:
416     return CodeGenOpt::Default; // O2/Os/Oz
417   case 3:
418     return CodeGenOpt::Aggressive;
419   }
420 }
421 
422 static Optional<llvm::CodeModel::Model>
423 getCodeModel(const CodeGenOptions &CodeGenOpts) {
424   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
425                            .Case("tiny", llvm::CodeModel::Tiny)
426                            .Case("small", llvm::CodeModel::Small)
427                            .Case("kernel", llvm::CodeModel::Kernel)
428                            .Case("medium", llvm::CodeModel::Medium)
429                            .Case("large", llvm::CodeModel::Large)
430                            .Case("default", ~1u)
431                            .Default(~0u);
432   assert(CodeModel != ~0u && "invalid code model!");
433   if (CodeModel == ~1u)
434     return None;
435   return static_cast<llvm::CodeModel::Model>(CodeModel);
436 }
437 
438 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
439   if (Action == Backend_EmitObj)
440     return CGFT_ObjectFile;
441   else if (Action == Backend_EmitMCNull)
442     return CGFT_Null;
443   else {
444     assert(Action == Backend_EmitAssembly && "Invalid action!");
445     return CGFT_AssemblyFile;
446   }
447 }
448 
449 static void initTargetOptions(DiagnosticsEngine &Diags,
450                               llvm::TargetOptions &Options,
451                               const CodeGenOptions &CodeGenOpts,
452                               const clang::TargetOptions &TargetOpts,
453                               const LangOptions &LangOpts,
454                               const HeaderSearchOptions &HSOpts) {
455   Options.ThreadModel =
456       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
457           .Case("posix", llvm::ThreadModel::POSIX)
458           .Case("single", llvm::ThreadModel::Single);
459 
460   // Set float ABI type.
461   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
462           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
463          "Invalid Floating Point ABI!");
464   Options.FloatABIType =
465       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
466           .Case("soft", llvm::FloatABI::Soft)
467           .Case("softfp", llvm::FloatABI::Soft)
468           .Case("hard", llvm::FloatABI::Hard)
469           .Default(llvm::FloatABI::Default);
470 
471   // Set FP fusion mode.
472   switch (LangOpts.getDefaultFPContractMode()) {
473   case LangOptions::FPM_Off:
474     // Preserve any contraction performed by the front-end.  (Strict performs
475     // splitting of the muladd intrinsic in the backend.)
476     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
477     break;
478   case LangOptions::FPM_On:
479     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
480     break;
481   case LangOptions::FPM_Fast:
482     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
483     break;
484   }
485 
486   Options.UseInitArray = CodeGenOpts.UseInitArray;
487   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
488   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
489   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
490 
491   // Set EABI version.
492   Options.EABIVersion = TargetOpts.EABIVersion;
493 
494   if (LangOpts.SjLjExceptions)
495     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
496   if (LangOpts.SEHExceptions)
497     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
498   if (LangOpts.DWARFExceptions)
499     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
500   if (LangOpts.WasmExceptions)
501     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
502 
503   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
504   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
505   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
506   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
507   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
508 
509   Options.BBSections =
510       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
511           .Case("all", llvm::BasicBlockSection::All)
512           .Case("labels", llvm::BasicBlockSection::Labels)
513           .StartsWith("list=", llvm::BasicBlockSection::List)
514           .Case("none", llvm::BasicBlockSection::None)
515           .Default(llvm::BasicBlockSection::None);
516 
517   if (Options.BBSections == llvm::BasicBlockSection::List) {
518     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
519         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
520     if (!MBOrErr)
521       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
522           << MBOrErr.getError().message();
523     else
524       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
525   }
526 
527   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
528   Options.FunctionSections = CodeGenOpts.FunctionSections;
529   Options.DataSections = CodeGenOpts.DataSections;
530   Options.IgnoreXCOFFVisibility = CodeGenOpts.IgnoreXCOFFVisibility;
531   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
532   Options.UniqueBasicBlockSectionNames =
533       CodeGenOpts.UniqueBasicBlockSectionNames;
534   Options.StackProtectorGuard =
535       llvm::StringSwitch<llvm::StackProtectorGuards>(CodeGenOpts
536           .StackProtectorGuard)
537           .Case("tls", llvm::StackProtectorGuards::TLS)
538           .Case("global", llvm::StackProtectorGuards::Global)
539           .Default(llvm::StackProtectorGuards::None);
540   Options.StackProtectorGuardOffset = CodeGenOpts.StackProtectorGuardOffset;
541   Options.StackProtectorGuardReg = CodeGenOpts.StackProtectorGuardReg;
542   Options.TLSSize = CodeGenOpts.TLSSize;
543   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
544   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
545   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
546   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
547   Options.EmitAddrsig = CodeGenOpts.Addrsig;
548   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
549   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
550   Options.ValueTrackingVariableLocations =
551       CodeGenOpts.ValueTrackingVariableLocations;
552   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
553 
554   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
555   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
556   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
557   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
558   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
559   Options.MCOptions.MCIncrementalLinkerCompatible =
560       CodeGenOpts.IncrementalLinkerCompatible;
561   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
562   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
563   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
564   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
565   Options.MCOptions.ABIName = TargetOpts.ABI;
566   for (const auto &Entry : HSOpts.UserEntries)
567     if (!Entry.IsFramework &&
568         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
569          Entry.Group == frontend::IncludeDirGroup::Angled ||
570          Entry.Group == frontend::IncludeDirGroup::System))
571       Options.MCOptions.IASSearchPaths.push_back(
572           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
573   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
574   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
575 }
576 
577 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
578                                             const LangOptions &LangOpts) {
579   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
580     return None;
581   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
582   // LLVM's -default-gcov-version flag is set to something invalid.
583   GCOVOptions Options;
584   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
585   Options.EmitData = CodeGenOpts.EmitGcovArcs;
586   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
587   Options.NoRedZone = CodeGenOpts.DisableRedZone;
588   Options.Filter = CodeGenOpts.ProfileFilterFiles;
589   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
590   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
591   return Options;
592 }
593 
594 static Optional<InstrProfOptions>
595 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
596                     const LangOptions &LangOpts) {
597   if (!CodeGenOpts.hasProfileClangInstr())
598     return None;
599   InstrProfOptions Options;
600   Options.NoRedZone = CodeGenOpts.DisableRedZone;
601   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
602   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
603   return Options;
604 }
605 
606 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
607                                       legacy::FunctionPassManager &FPM) {
608   // Handle disabling of all LLVM passes, where we want to preserve the
609   // internal module before any optimization.
610   if (CodeGenOpts.DisableLLVMPasses)
611     return;
612 
613   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
614   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
615   // are inserted before PMBuilder ones - they'd get the default-constructed
616   // TLI with an unknown target otherwise.
617   Triple TargetTriple(TheModule->getTargetTriple());
618   std::unique_ptr<TargetLibraryInfoImpl> TLII(
619       createTLII(TargetTriple, CodeGenOpts));
620 
621   // If we reached here with a non-empty index file name, then the index file
622   // was empty and we are not performing ThinLTO backend compilation (used in
623   // testing in a distributed build environment). Drop any the type test
624   // assume sequences inserted for whole program vtables so that codegen doesn't
625   // complain.
626   if (!CodeGenOpts.ThinLTOIndexFile.empty())
627     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
628                                      /*ImportSummary=*/nullptr,
629                                      /*DropTypeTests=*/true));
630 
631   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
632 
633   // At O0 and O1 we only run the always inliner which is more efficient. At
634   // higher optimization levels we run the normal inliner.
635   if (CodeGenOpts.OptimizationLevel <= 1) {
636     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
637                                       !CodeGenOpts.DisableLifetimeMarkers) ||
638                                      LangOpts.Coroutines);
639     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
640   } else {
641     // We do not want to inline hot callsites for SamplePGO module-summary build
642     // because profile annotation will happen again in ThinLTO backend, and we
643     // want the IR of the hot path to match the profile.
644     PMBuilder.Inliner = createFunctionInliningPass(
645         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
646         (!CodeGenOpts.SampleProfileFile.empty() &&
647          CodeGenOpts.PrepareForThinLTO));
648   }
649 
650   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
651   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
652   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
653   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
654   // Only enable CGProfilePass when using integrated assembler, since
655   // non-integrated assemblers don't recognize .cgprofile section.
656   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
657 
658   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
659   // Loop interleaving in the loop vectorizer has historically been set to be
660   // enabled when loop unrolling is enabled.
661   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
662   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
663   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
664   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
665   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
666 
667   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
668 
669   if (TM)
670     TM->adjustPassManager(PMBuilder);
671 
672   if (CodeGenOpts.DebugInfoForProfiling ||
673       !CodeGenOpts.SampleProfileFile.empty())
674     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
675                            addAddDiscriminatorsPass);
676 
677   // In ObjC ARC mode, add the main ARC optimization passes.
678   if (LangOpts.ObjCAutoRefCount) {
679     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
680                            addObjCARCExpandPass);
681     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
682                            addObjCARCAPElimPass);
683     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
684                            addObjCARCOptPass);
685   }
686 
687   if (LangOpts.Coroutines)
688     addCoroutinePassesToExtensionPoints(PMBuilder);
689 
690   if (CodeGenOpts.MemProf) {
691     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
692                            addMemProfilerPasses);
693     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
694                            addMemProfilerPasses);
695   }
696 
697   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
698     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
699                            addBoundsCheckingPass);
700     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
701                            addBoundsCheckingPass);
702   }
703 
704   if (CodeGenOpts.SanitizeCoverageType ||
705       CodeGenOpts.SanitizeCoverageIndirectCalls ||
706       CodeGenOpts.SanitizeCoverageTraceCmp) {
707     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
708                            addSanitizerCoveragePass);
709     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
710                            addSanitizerCoveragePass);
711   }
712 
713   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
714     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
715                            addAddressSanitizerPasses);
716     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
717                            addAddressSanitizerPasses);
718   }
719 
720   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
721     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
722                            addKernelAddressSanitizerPasses);
723     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
724                            addKernelAddressSanitizerPasses);
725   }
726 
727   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
728     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
729                            addHWAddressSanitizerPasses);
730     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
731                            addHWAddressSanitizerPasses);
732   }
733 
734   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
735     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
736                            addKernelHWAddressSanitizerPasses);
737     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
738                            addKernelHWAddressSanitizerPasses);
739   }
740 
741   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
742     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
743                            addMemorySanitizerPass);
744     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
745                            addMemorySanitizerPass);
746   }
747 
748   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
749     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
750                            addKernelMemorySanitizerPass);
751     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
752                            addKernelMemorySanitizerPass);
753   }
754 
755   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
756     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
757                            addThreadSanitizerPass);
758     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
759                            addThreadSanitizerPass);
760   }
761 
762   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
763     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
764                            addDataFlowSanitizerPass);
765     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
766                            addDataFlowSanitizerPass);
767   }
768 
769   // Set up the per-function pass manager.
770   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
771   if (CodeGenOpts.VerifyModule)
772     FPM.add(createVerifierPass());
773 
774   // Set up the per-module pass manager.
775   if (!CodeGenOpts.RewriteMapFiles.empty())
776     addSymbolRewriterPass(CodeGenOpts, &MPM);
777 
778   // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols
779   // with unique names.
780   if (CodeGenOpts.UniqueInternalLinkageNames) {
781     MPM.add(createUniqueInternalLinkageNamesPass());
782   }
783 
784   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
785     MPM.add(createGCOVProfilerPass(*Options));
786     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
787       MPM.add(createStripSymbolsPass(true));
788   }
789 
790   if (Optional<InstrProfOptions> Options =
791           getInstrProfOptions(CodeGenOpts, LangOpts))
792     MPM.add(createInstrProfilingLegacyPass(*Options, false));
793 
794   bool hasIRInstr = false;
795   if (CodeGenOpts.hasProfileIRInstr()) {
796     PMBuilder.EnablePGOInstrGen = true;
797     hasIRInstr = true;
798   }
799   if (CodeGenOpts.hasProfileCSIRInstr()) {
800     assert(!CodeGenOpts.hasProfileCSIRUse() &&
801            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
802            "same time");
803     assert(!hasIRInstr &&
804            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
805            "same time");
806     PMBuilder.EnablePGOCSInstrGen = true;
807     hasIRInstr = true;
808   }
809   if (hasIRInstr) {
810     if (!CodeGenOpts.InstrProfileOutput.empty())
811       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
812     else
813       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
814   }
815   if (CodeGenOpts.hasProfileIRUse()) {
816     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
817     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
818   }
819 
820   if (!CodeGenOpts.SampleProfileFile.empty())
821     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
822 
823   PMBuilder.populateFunctionPassManager(FPM);
824   PMBuilder.populateModulePassManager(MPM);
825 }
826 
827 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
828   SmallVector<const char *, 16> BackendArgs;
829   BackendArgs.push_back("clang"); // Fake program name.
830   if (!CodeGenOpts.DebugPass.empty()) {
831     BackendArgs.push_back("-debug-pass");
832     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
833   }
834   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
835     BackendArgs.push_back("-limit-float-precision");
836     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
837   }
838   BackendArgs.push_back(nullptr);
839   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
840                                     BackendArgs.data());
841 }
842 
843 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
844   // Create the TargetMachine for generating code.
845   std::string Error;
846   std::string Triple = TheModule->getTargetTriple();
847   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
848   if (!TheTarget) {
849     if (MustCreateTM)
850       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
851     return;
852   }
853 
854   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
855   std::string FeaturesStr =
856       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
857   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
858   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
859 
860   llvm::TargetOptions Options;
861   initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
862   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
863                                           Options, RM, CM, OptLevel));
864 }
865 
866 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
867                                        BackendAction Action,
868                                        raw_pwrite_stream &OS,
869                                        raw_pwrite_stream *DwoOS) {
870   // Add LibraryInfo.
871   llvm::Triple TargetTriple(TheModule->getTargetTriple());
872   std::unique_ptr<TargetLibraryInfoImpl> TLII(
873       createTLII(TargetTriple, CodeGenOpts));
874   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
875 
876   // Normal mode, emit a .s or .o file by running the code generator. Note,
877   // this also adds codegenerator level optimization passes.
878   CodeGenFileType CGFT = getCodeGenFileType(Action);
879 
880   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
881   // "codegen" passes so that it isn't run multiple times when there is
882   // inlining happening.
883   if (CodeGenOpts.OptimizationLevel > 0)
884     CodeGenPasses.add(createObjCARCContractPass());
885 
886   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
887                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
888     Diags.Report(diag::err_fe_unable_to_interface_with_target);
889     return false;
890   }
891 
892   return true;
893 }
894 
895 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
896                                       std::unique_ptr<raw_pwrite_stream> OS) {
897   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
898 
899   setCommandLineOpts(CodeGenOpts);
900 
901   bool UsesCodeGen = (Action != Backend_EmitNothing &&
902                       Action != Backend_EmitBC &&
903                       Action != Backend_EmitLL);
904   CreateTargetMachine(UsesCodeGen);
905 
906   if (UsesCodeGen && !TM)
907     return;
908   if (TM)
909     TheModule->setDataLayout(TM->createDataLayout());
910 
911   legacy::PassManager PerModulePasses;
912   PerModulePasses.add(
913       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
914 
915   legacy::FunctionPassManager PerFunctionPasses(TheModule);
916   PerFunctionPasses.add(
917       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
918 
919   CreatePasses(PerModulePasses, PerFunctionPasses);
920 
921   legacy::PassManager CodeGenPasses;
922   CodeGenPasses.add(
923       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
924 
925   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
926 
927   switch (Action) {
928   case Backend_EmitNothing:
929     break;
930 
931   case Backend_EmitBC:
932     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
933       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
934         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
935         if (!ThinLinkOS)
936           return;
937       }
938       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
939                                CodeGenOpts.EnableSplitLTOUnit);
940       PerModulePasses.add(createWriteThinLTOBitcodePass(
941           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
942     } else {
943       // Emit a module summary by default for Regular LTO except for ld64
944       // targets
945       bool EmitLTOSummary =
946           (CodeGenOpts.PrepareForLTO &&
947            !CodeGenOpts.DisableLLVMPasses &&
948            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
949                llvm::Triple::Apple);
950       if (EmitLTOSummary) {
951         if (!TheModule->getModuleFlag("ThinLTO"))
952           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
953         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
954                                  uint32_t(1));
955       }
956 
957       PerModulePasses.add(createBitcodeWriterPass(
958           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
959     }
960     break;
961 
962   case Backend_EmitLL:
963     PerModulePasses.add(
964         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
965     break;
966 
967   default:
968     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
969       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
970       if (!DwoOS)
971         return;
972     }
973     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
974                        DwoOS ? &DwoOS->os() : nullptr))
975       return;
976   }
977 
978   // Before executing passes, print the final values of the LLVM options.
979   cl::PrintOptionValues();
980 
981   // Run passes. For now we do all passes at once, but eventually we
982   // would like to have the option of streaming code generation.
983 
984   {
985     PrettyStackTraceString CrashInfo("Per-function optimization");
986     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
987 
988     PerFunctionPasses.doInitialization();
989     for (Function &F : *TheModule)
990       if (!F.isDeclaration())
991         PerFunctionPasses.run(F);
992     PerFunctionPasses.doFinalization();
993   }
994 
995   {
996     PrettyStackTraceString CrashInfo("Per-module optimization passes");
997     llvm::TimeTraceScope TimeScope("PerModulePasses");
998     PerModulePasses.run(*TheModule);
999   }
1000 
1001   {
1002     PrettyStackTraceString CrashInfo("Code generation");
1003     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1004     CodeGenPasses.run(*TheModule);
1005   }
1006 
1007   if (ThinLinkOS)
1008     ThinLinkOS->keep();
1009   if (DwoOS)
1010     DwoOS->keep();
1011 }
1012 
1013 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
1014   switch (Opts.OptimizationLevel) {
1015   default:
1016     llvm_unreachable("Invalid optimization level!");
1017 
1018   case 1:
1019     return PassBuilder::OptimizationLevel::O1;
1020 
1021   case 2:
1022     switch (Opts.OptimizeSize) {
1023     default:
1024       llvm_unreachable("Invalid optimization level for size!");
1025 
1026     case 0:
1027       return PassBuilder::OptimizationLevel::O2;
1028 
1029     case 1:
1030       return PassBuilder::OptimizationLevel::Os;
1031 
1032     case 2:
1033       return PassBuilder::OptimizationLevel::Oz;
1034     }
1035 
1036   case 3:
1037     return PassBuilder::OptimizationLevel::O3;
1038   }
1039 }
1040 
1041 static void addCoroutinePassesAtO0(ModulePassManager &MPM,
1042                                    const LangOptions &LangOpts,
1043                                    const CodeGenOptions &CodeGenOpts) {
1044   if (!LangOpts.Coroutines)
1045     return;
1046 
1047   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1048 
1049   CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
1050   CGPM.addPass(CoroSplitPass());
1051   CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
1052   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1053 
1054   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1055 }
1056 
1057 static void addSanitizersAtO0(ModulePassManager &MPM,
1058                               const Triple &TargetTriple,
1059                               const LangOptions &LangOpts,
1060                               const CodeGenOptions &CodeGenOpts) {
1061   if (CodeGenOpts.SanitizeCoverageType ||
1062       CodeGenOpts.SanitizeCoverageIndirectCalls ||
1063       CodeGenOpts.SanitizeCoverageTraceCmp) {
1064     auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1065     MPM.addPass(ModuleSanitizerCoveragePass(
1066         SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1067         CodeGenOpts.SanitizeCoverageBlocklistFiles));
1068   }
1069 
1070   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1071     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1072     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1073     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1074         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
1075     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1076     MPM.addPass(
1077         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1078                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
1079   };
1080 
1081   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1082     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1083   }
1084 
1085   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1086     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
1087   }
1088 
1089   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1090     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1091     MPM.addPass(HWAddressSanitizerPass(
1092         /*CompileKernel=*/false, Recover));
1093   }
1094   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1095     MPM.addPass(HWAddressSanitizerPass(
1096         /*CompileKernel=*/true, /*Recover=*/true));
1097   }
1098 
1099   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1100     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1101     int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1102     MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1103     MPM.addPass(createModuleToFunctionPassAdaptor(
1104         MemorySanitizerPass({TrackOrigins, Recover, false})));
1105   }
1106 
1107   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1108     MPM.addPass(createModuleToFunctionPassAdaptor(
1109         MemorySanitizerPass({0, false, /*Kernel=*/true})));
1110   }
1111 
1112   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1113     MPM.addPass(ThreadSanitizerPass());
1114     MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1115   }
1116 }
1117 
1118 /// A clean version of `EmitAssembly` that uses the new pass manager.
1119 ///
1120 /// Not all features are currently supported in this system, but where
1121 /// necessary it falls back to the legacy pass manager to at least provide
1122 /// basic functionality.
1123 ///
1124 /// This API is planned to have its functionality finished and then to replace
1125 /// `EmitAssembly` at some point in the future when the default switches.
1126 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1127     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1128   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
1129   setCommandLineOpts(CodeGenOpts);
1130 
1131   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1132                           Action != Backend_EmitBC &&
1133                           Action != Backend_EmitLL);
1134   CreateTargetMachine(RequiresCodeGen);
1135 
1136   if (RequiresCodeGen && !TM)
1137     return;
1138   if (TM)
1139     TheModule->setDataLayout(TM->createDataLayout());
1140 
1141   Optional<PGOOptions> PGOOpt;
1142 
1143   if (CodeGenOpts.hasProfileIRInstr())
1144     // -fprofile-generate.
1145     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1146                             ? std::string(DefaultProfileGenName)
1147                             : CodeGenOpts.InstrProfileOutput,
1148                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1149                         CodeGenOpts.DebugInfoForProfiling);
1150   else if (CodeGenOpts.hasProfileIRUse()) {
1151     // -fprofile-use.
1152     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1153                                                     : PGOOptions::NoCSAction;
1154     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1155                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1156                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1157   } else if (!CodeGenOpts.SampleProfileFile.empty())
1158     // -fprofile-sample-use
1159     PGOOpt =
1160         PGOOptions(CodeGenOpts.SampleProfileFile, "",
1161                    CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1162                    PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1163   else if (CodeGenOpts.DebugInfoForProfiling)
1164     // -fdebug-info-for-profiling
1165     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1166                         PGOOptions::NoCSAction, true);
1167 
1168   // Check to see if we want to generate a CS profile.
1169   if (CodeGenOpts.hasProfileCSIRInstr()) {
1170     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1171            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1172            "the same time");
1173     if (PGOOpt.hasValue()) {
1174       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1175              PGOOpt->Action != PGOOptions::SampleUse &&
1176              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1177              " pass");
1178       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1179                                      ? std::string(DefaultProfileGenName)
1180                                      : CodeGenOpts.InstrProfileOutput;
1181       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1182     } else
1183       PGOOpt = PGOOptions("",
1184                           CodeGenOpts.InstrProfileOutput.empty()
1185                               ? std::string(DefaultProfileGenName)
1186                               : CodeGenOpts.InstrProfileOutput,
1187                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1188                           CodeGenOpts.DebugInfoForProfiling);
1189   }
1190 
1191   PipelineTuningOptions PTO;
1192   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1193   // For historical reasons, loop interleaving is set to mirror setting for loop
1194   // unrolling.
1195   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1196   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1197   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1198   // Only enable CGProfilePass when using integrated assembler, since
1199   // non-integrated assemblers don't recognize .cgprofile section.
1200   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1201   PTO.Coroutines = LangOpts.Coroutines;
1202 
1203   PassInstrumentationCallbacks PIC;
1204   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1205   SI.registerCallbacks(PIC);
1206   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1207 
1208   // Attempt to load pass plugins and register their callbacks with PB.
1209   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1210     auto PassPlugin = PassPlugin::Load(PluginFN);
1211     if (PassPlugin) {
1212       PassPlugin->registerPassBuilderCallbacks(PB);
1213     } else {
1214       Diags.Report(diag::err_fe_unable_to_load_plugin)
1215           << PluginFN << toString(PassPlugin.takeError());
1216     }
1217   }
1218 #define HANDLE_EXTENSION(Ext)                                                  \
1219   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1220 #include "llvm/Support/Extension.def"
1221 
1222   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1223   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1224   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1225   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1226 
1227   // Register the AA manager first so that our version is the one used.
1228   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1229 
1230   // Register the target library analysis directly and give it a customized
1231   // preset TLI.
1232   Triple TargetTriple(TheModule->getTargetTriple());
1233   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1234       createTLII(TargetTriple, CodeGenOpts));
1235   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1236 
1237   // Register all the basic analyses with the managers.
1238   PB.registerModuleAnalyses(MAM);
1239   PB.registerCGSCCAnalyses(CGAM);
1240   PB.registerFunctionAnalyses(FAM);
1241   PB.registerLoopAnalyses(LAM);
1242   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1243 
1244   if (TM)
1245     TM->registerPassBuilderCallbacks(PB, CodeGenOpts.DebugPassManager);
1246 
1247   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1248 
1249   if (!CodeGenOpts.DisableLLVMPasses) {
1250     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1251     bool IsLTO = CodeGenOpts.PrepareForLTO;
1252 
1253     if (CodeGenOpts.OptimizationLevel == 0) {
1254       // If we reached here with a non-empty index file name, then the index
1255       // file was empty and we are not performing ThinLTO backend compilation
1256       // (used in testing in a distributed build environment). Drop any the type
1257       // test assume sequences inserted for whole program vtables so that
1258       // codegen doesn't complain.
1259       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1260         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1261                                        /*ImportSummary=*/nullptr,
1262                                        /*DropTypeTests=*/true));
1263       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1264         MPM.addPass(GCOVProfilerPass(*Options));
1265       if (Optional<InstrProfOptions> Options =
1266               getInstrProfOptions(CodeGenOpts, LangOpts))
1267         MPM.addPass(InstrProfiling(*Options, false));
1268 
1269       // Build a minimal pipeline based on the semantics required by Clang,
1270       // which is just that always inlining occurs. Further, disable generating
1271       // lifetime intrinsics to avoid enabling further optimizations during
1272       // code generation.
1273       // However, we need to insert lifetime intrinsics to avoid invalid access
1274       // caused by multithreaded coroutines.
1275       MPM.addPass(
1276           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1277 
1278       // At -O0, we can still do PGO. Add all the requested passes for
1279       // instrumentation PGO, if requested.
1280       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1281                      PGOOpt->Action == PGOOptions::IRUse))
1282         PB.addPGOInstrPassesForO0(
1283             MPM, CodeGenOpts.DebugPassManager,
1284             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1285             /* IsCS */ false, PGOOpt->ProfileFile,
1286             PGOOpt->ProfileRemappingFile);
1287 
1288       // At -O0 we directly run necessary sanitizer passes.
1289       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1290         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1291 
1292       // Lastly, add semantically necessary passes for LTO.
1293       if (IsLTO || IsThinLTO) {
1294         MPM.addPass(CanonicalizeAliasesPass());
1295         MPM.addPass(NameAnonGlobalPass());
1296       }
1297     } else {
1298       // Map our optimization levels into one of the distinct levels used to
1299       // configure the pipeline.
1300       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1301 
1302       // If we reached here with a non-empty index file name, then the index
1303       // file was empty and we are not performing ThinLTO backend compilation
1304       // (used in testing in a distributed build environment). Drop any the type
1305       // test assume sequences inserted for whole program vtables so that
1306       // codegen doesn't complain.
1307       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1308         PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1309           MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1310                                          /*ImportSummary=*/nullptr,
1311                                          /*DropTypeTests=*/true));
1312         });
1313 
1314       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1315         MPM.addPass(createModuleToFunctionPassAdaptor(
1316             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1317       });
1318 
1319       // Register callbacks to schedule sanitizer passes at the appropriate part of
1320       // the pipeline.
1321       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1322         PB.registerScalarOptimizerLateEPCallback(
1323             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1324               FPM.addPass(BoundsCheckingPass());
1325             });
1326 
1327       if (CodeGenOpts.SanitizeCoverageType ||
1328           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1329           CodeGenOpts.SanitizeCoverageTraceCmp) {
1330         PB.registerOptimizerLastEPCallback(
1331             [this](ModulePassManager &MPM,
1332                    PassBuilder::OptimizationLevel Level) {
1333               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1334               MPM.addPass(ModuleSanitizerCoveragePass(
1335                   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1336                   CodeGenOpts.SanitizeCoverageBlocklistFiles));
1337             });
1338       }
1339 
1340       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1341         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1342         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1343         PB.registerOptimizerLastEPCallback(
1344             [TrackOrigins, Recover](ModulePassManager &MPM,
1345                                     PassBuilder::OptimizationLevel Level) {
1346               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1347               MPM.addPass(createModuleToFunctionPassAdaptor(
1348                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1349             });
1350       }
1351       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1352         PB.registerOptimizerLastEPCallback(
1353             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1354               MPM.addPass(ThreadSanitizerPass());
1355               MPM.addPass(
1356                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1357             });
1358       }
1359       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1360         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1361         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1362         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1363         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1364         PB.registerOptimizerLastEPCallback(
1365             [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator](
1366                 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1367               MPM.addPass(
1368                   RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1369               MPM.addPass(ModuleAddressSanitizerPass(
1370                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1371                   UseOdrIndicator));
1372               MPM.addPass(
1373                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1374                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1375             });
1376       }
1377 
1378       if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1379         bool Recover =
1380             CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1381         PB.registerOptimizerLastEPCallback(
1382             [Recover](ModulePassManager &MPM,
1383                       PassBuilder::OptimizationLevel Level) {
1384               MPM.addPass(HWAddressSanitizerPass(
1385                   /*CompileKernel=*/false, Recover));
1386             });
1387       }
1388       if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1389         bool Recover =
1390             CodeGenOpts.SanitizeRecover.has(SanitizerKind::KernelHWAddress);
1391         PB.registerOptimizerLastEPCallback(
1392             [Recover](ModulePassManager &MPM,
1393                       PassBuilder::OptimizationLevel Level) {
1394               MPM.addPass(HWAddressSanitizerPass(
1395                   /*CompileKernel=*/true, Recover));
1396             });
1397       }
1398 
1399       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1400         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1401           MPM.addPass(GCOVProfilerPass(*Options));
1402         });
1403       if (Optional<InstrProfOptions> Options =
1404               getInstrProfOptions(CodeGenOpts, LangOpts))
1405         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1406           MPM.addPass(InstrProfiling(*Options, false));
1407         });
1408 
1409       if (IsThinLTO) {
1410         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1411             Level, CodeGenOpts.DebugPassManager);
1412         MPM.addPass(CanonicalizeAliasesPass());
1413         MPM.addPass(NameAnonGlobalPass());
1414       } else if (IsLTO) {
1415         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1416                                                 CodeGenOpts.DebugPassManager);
1417         MPM.addPass(CanonicalizeAliasesPass());
1418         MPM.addPass(NameAnonGlobalPass());
1419       } else {
1420         MPM = PB.buildPerModuleDefaultPipeline(Level,
1421                                                CodeGenOpts.DebugPassManager);
1422       }
1423     }
1424 
1425     // Add UniqueInternalLinkageNames Pass which renames internal linkage
1426     // symbols with unique names.
1427     if (CodeGenOpts.UniqueInternalLinkageNames)
1428       MPM.addPass(UniqueInternalLinkageNamesPass());
1429 
1430     if (CodeGenOpts.MemProf) {
1431       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1432       MPM.addPass(ModuleMemProfilerPass());
1433     }
1434 
1435     if (CodeGenOpts.OptimizationLevel == 0) {
1436       // FIXME: the backends do not handle matrix intrinsics currently. Make
1437       // sure they are also lowered in O0. A lightweight version of the pass
1438       // should run in the backend pipeline on demand.
1439       if (LangOpts.MatrixTypes)
1440         MPM.addPass(
1441             createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass()));
1442 
1443       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1444       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1445     }
1446   }
1447 
1448   // FIXME: We still use the legacy pass manager to do code generation. We
1449   // create that pass manager here and use it as needed below.
1450   legacy::PassManager CodeGenPasses;
1451   bool NeedCodeGen = false;
1452   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1453 
1454   // Append any output we need to the pass manager.
1455   switch (Action) {
1456   case Backend_EmitNothing:
1457     break;
1458 
1459   case Backend_EmitBC:
1460     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1461       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1462         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1463         if (!ThinLinkOS)
1464           return;
1465       }
1466       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1467                                CodeGenOpts.EnableSplitLTOUnit);
1468       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1469                                                            : nullptr));
1470     } else {
1471       // Emit a module summary by default for Regular LTO except for ld64
1472       // targets
1473       bool EmitLTOSummary =
1474           (CodeGenOpts.PrepareForLTO &&
1475            !CodeGenOpts.DisableLLVMPasses &&
1476            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1477                llvm::Triple::Apple);
1478       if (EmitLTOSummary) {
1479         if (!TheModule->getModuleFlag("ThinLTO"))
1480           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1481         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1482                                  uint32_t(1));
1483       }
1484       MPM.addPass(
1485           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1486     }
1487     break;
1488 
1489   case Backend_EmitLL:
1490     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1491     break;
1492 
1493   case Backend_EmitAssembly:
1494   case Backend_EmitMCNull:
1495   case Backend_EmitObj:
1496     NeedCodeGen = true;
1497     CodeGenPasses.add(
1498         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1499     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1500       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1501       if (!DwoOS)
1502         return;
1503     }
1504     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1505                        DwoOS ? &DwoOS->os() : nullptr))
1506       // FIXME: Should we handle this error differently?
1507       return;
1508     break;
1509   }
1510 
1511   // Before executing passes, print the final values of the LLVM options.
1512   cl::PrintOptionValues();
1513 
1514   // Now that we have all of the passes ready, run them.
1515   {
1516     PrettyStackTraceString CrashInfo("Optimizer");
1517     MPM.run(*TheModule, MAM);
1518   }
1519 
1520   // Now if needed, run the legacy PM for codegen.
1521   if (NeedCodeGen) {
1522     PrettyStackTraceString CrashInfo("Code generation");
1523     CodeGenPasses.run(*TheModule);
1524   }
1525 
1526   if (ThinLinkOS)
1527     ThinLinkOS->keep();
1528   if (DwoOS)
1529     DwoOS->keep();
1530 }
1531 
1532 static void runThinLTOBackend(
1533     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1534     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1535     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1536     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1537     std::string ProfileRemapping, BackendAction Action) {
1538   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1539       ModuleToDefinedGVSummaries;
1540   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1541 
1542   setCommandLineOpts(CGOpts);
1543 
1544   // We can simply import the values mentioned in the combined index, since
1545   // we should only invoke this using the individual indexes written out
1546   // via a WriteIndexesThinBackend.
1547   FunctionImporter::ImportMapTy ImportList;
1548   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1549   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1550   if (!lto::loadReferencedModules(*M, *CombinedIndex, ImportList, ModuleMap,
1551                                   OwnedImports))
1552     return;
1553 
1554   auto AddStream = [&](size_t Task) {
1555     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1556   };
1557   lto::Config Conf;
1558   if (CGOpts.SaveTempsFilePrefix != "") {
1559     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1560                                     /* UseInputModulePath */ false)) {
1561       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1562         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1563                << '\n';
1564       });
1565     }
1566   }
1567   Conf.CPU = TOpts.CPU;
1568   Conf.CodeModel = getCodeModel(CGOpts);
1569   Conf.MAttrs = TOpts.Features;
1570   Conf.RelocModel = CGOpts.RelocationModel;
1571   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1572   Conf.OptLevel = CGOpts.OptimizationLevel;
1573   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1574   Conf.SampleProfile = std::move(SampleProfile);
1575   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1576   // For historical reasons, loop interleaving is set to mirror setting for loop
1577   // unrolling.
1578   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1579   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1580   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1581   // Only enable CGProfilePass when using integrated assembler, since
1582   // non-integrated assemblers don't recognize .cgprofile section.
1583   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1584 
1585   // Context sensitive profile.
1586   if (CGOpts.hasProfileCSIRInstr()) {
1587     Conf.RunCSIRInstr = true;
1588     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1589   } else if (CGOpts.hasProfileCSIRUse()) {
1590     Conf.RunCSIRInstr = false;
1591     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1592   }
1593 
1594   Conf.ProfileRemapping = std::move(ProfileRemapping);
1595   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1596   Conf.DebugPassManager = CGOpts.DebugPassManager;
1597   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1598   Conf.RemarksFilename = CGOpts.OptRecordFile;
1599   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1600   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1601   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1602   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1603   switch (Action) {
1604   case Backend_EmitNothing:
1605     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1606       return false;
1607     };
1608     break;
1609   case Backend_EmitLL:
1610     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1611       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1612       return false;
1613     };
1614     break;
1615   case Backend_EmitBC:
1616     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1617       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1618       return false;
1619     };
1620     break;
1621   default:
1622     Conf.CGFileType = getCodeGenFileType(Action);
1623     break;
1624   }
1625   if (Error E =
1626           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1627                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1628                       ModuleMap, CGOpts.CmdArgs)) {
1629     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1630       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1631     });
1632   }
1633 }
1634 
1635 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1636                               const HeaderSearchOptions &HeaderOpts,
1637                               const CodeGenOptions &CGOpts,
1638                               const clang::TargetOptions &TOpts,
1639                               const LangOptions &LOpts,
1640                               const llvm::DataLayout &TDesc, Module *M,
1641                               BackendAction Action,
1642                               std::unique_ptr<raw_pwrite_stream> OS) {
1643 
1644   llvm::TimeTraceScope TimeScope("Backend");
1645 
1646   std::unique_ptr<llvm::Module> EmptyModule;
1647   if (!CGOpts.ThinLTOIndexFile.empty()) {
1648     // If we are performing a ThinLTO importing compile, load the function index
1649     // into memory and pass it into runThinLTOBackend, which will run the
1650     // function importer and invoke LTO passes.
1651     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1652         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1653                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1654     if (!IndexOrErr) {
1655       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1656                             "Error loading index file '" +
1657                             CGOpts.ThinLTOIndexFile + "': ");
1658       return;
1659     }
1660     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1661     // A null CombinedIndex means we should skip ThinLTO compilation
1662     // (LLVM will optionally ignore empty index files, returning null instead
1663     // of an error).
1664     if (CombinedIndex) {
1665       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1666         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1667                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1668                           CGOpts.ProfileRemappingFile, Action);
1669         return;
1670       }
1671       // Distributed indexing detected that nothing from the module is needed
1672       // for the final linking. So we can skip the compilation. We sill need to
1673       // output an empty object file to make sure that a linker does not fail
1674       // trying to read it. Also for some features, like CFI, we must skip
1675       // the compilation as CombinedIndex does not contain all required
1676       // information.
1677       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1678       EmptyModule->setTargetTriple(M->getTargetTriple());
1679       M = EmptyModule.get();
1680     }
1681   }
1682 
1683   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1684 
1685   if (CGOpts.ExperimentalNewPassManager)
1686     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1687   else
1688     AsmHelper.EmitAssembly(Action, std::move(OS));
1689 
1690   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1691   // DataLayout.
1692   if (AsmHelper.TM) {
1693     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1694     if (DLDesc != TDesc.getStringRepresentation()) {
1695       unsigned DiagID = Diags.getCustomDiagID(
1696           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1697                                     "expected target description '%1'");
1698       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1699     }
1700   }
1701 }
1702 
1703 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1704 // __LLVM,__bitcode section.
1705 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1706                          llvm::MemoryBufferRef Buf) {
1707   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1708     return;
1709   llvm::EmbedBitcodeInModule(
1710       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1711       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1712       CGOpts.CmdArgs);
1713 }
1714