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 bool 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       return false;
524     }
525     Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
526   }
527 
528   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
529   Options.FunctionSections = CodeGenOpts.FunctionSections;
530   Options.DataSections = CodeGenOpts.DataSections;
531   Options.IgnoreXCOFFVisibility = CodeGenOpts.IgnoreXCOFFVisibility;
532   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
533   Options.UniqueBasicBlockSectionNames =
534       CodeGenOpts.UniqueBasicBlockSectionNames;
535   Options.StackProtectorGuard =
536       llvm::StringSwitch<llvm::StackProtectorGuards>(CodeGenOpts
537           .StackProtectorGuard)
538           .Case("tls", llvm::StackProtectorGuards::TLS)
539           .Case("global", llvm::StackProtectorGuards::Global)
540           .Default(llvm::StackProtectorGuards::None);
541   Options.StackProtectorGuardOffset = CodeGenOpts.StackProtectorGuardOffset;
542   Options.StackProtectorGuardReg = CodeGenOpts.StackProtectorGuardReg;
543   Options.TLSSize = CodeGenOpts.TLSSize;
544   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
545   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
546   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
547   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
548   Options.EmitAddrsig = CodeGenOpts.Addrsig;
549   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
550   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
551   Options.ValueTrackingVariableLocations =
552       CodeGenOpts.ValueTrackingVariableLocations;
553   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
554 
555   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
556   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
557   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
558   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
559   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
560   Options.MCOptions.MCIncrementalLinkerCompatible =
561       CodeGenOpts.IncrementalLinkerCompatible;
562   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
563   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
564   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
565   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
566   Options.MCOptions.ABIName = TargetOpts.ABI;
567   for (const auto &Entry : HSOpts.UserEntries)
568     if (!Entry.IsFramework &&
569         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
570          Entry.Group == frontend::IncludeDirGroup::Angled ||
571          Entry.Group == frontend::IncludeDirGroup::System))
572       Options.MCOptions.IASSearchPaths.push_back(
573           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
574   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
575   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
576 
577   return true;
578 }
579 
580 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
581                                             const LangOptions &LangOpts) {
582   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
583     return None;
584   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
585   // LLVM's -default-gcov-version flag is set to something invalid.
586   GCOVOptions Options;
587   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
588   Options.EmitData = CodeGenOpts.EmitGcovArcs;
589   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
590   Options.NoRedZone = CodeGenOpts.DisableRedZone;
591   Options.Filter = CodeGenOpts.ProfileFilterFiles;
592   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
593   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
594   return Options;
595 }
596 
597 static Optional<InstrProfOptions>
598 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
599                     const LangOptions &LangOpts) {
600   if (!CodeGenOpts.hasProfileClangInstr())
601     return None;
602   InstrProfOptions Options;
603   Options.NoRedZone = CodeGenOpts.DisableRedZone;
604   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
605   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
606   return Options;
607 }
608 
609 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
610                                       legacy::FunctionPassManager &FPM) {
611   // Handle disabling of all LLVM passes, where we want to preserve the
612   // internal module before any optimization.
613   if (CodeGenOpts.DisableLLVMPasses)
614     return;
615 
616   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
617   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
618   // are inserted before PMBuilder ones - they'd get the default-constructed
619   // TLI with an unknown target otherwise.
620   Triple TargetTriple(TheModule->getTargetTriple());
621   std::unique_ptr<TargetLibraryInfoImpl> TLII(
622       createTLII(TargetTriple, CodeGenOpts));
623 
624   // If we reached here with a non-empty index file name, then the index file
625   // was empty and we are not performing ThinLTO backend compilation (used in
626   // testing in a distributed build environment). Drop any the type test
627   // assume sequences inserted for whole program vtables so that codegen doesn't
628   // complain.
629   if (!CodeGenOpts.ThinLTOIndexFile.empty())
630     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
631                                      /*ImportSummary=*/nullptr,
632                                      /*DropTypeTests=*/true));
633 
634   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
635 
636   // At O0 and O1 we only run the always inliner which is more efficient. At
637   // higher optimization levels we run the normal inliner.
638   if (CodeGenOpts.OptimizationLevel <= 1) {
639     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
640                                       !CodeGenOpts.DisableLifetimeMarkers) ||
641                                      LangOpts.Coroutines);
642     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
643   } else {
644     // We do not want to inline hot callsites for SamplePGO module-summary build
645     // because profile annotation will happen again in ThinLTO backend, and we
646     // want the IR of the hot path to match the profile.
647     PMBuilder.Inliner = createFunctionInliningPass(
648         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
649         (!CodeGenOpts.SampleProfileFile.empty() &&
650          CodeGenOpts.PrepareForThinLTO));
651   }
652 
653   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
654   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
655   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
656   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
657   // Only enable CGProfilePass when using integrated assembler, since
658   // non-integrated assemblers don't recognize .cgprofile section.
659   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
660 
661   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
662   // Loop interleaving in the loop vectorizer has historically been set to be
663   // enabled when loop unrolling is enabled.
664   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
665   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
666   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
667   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
668   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
669 
670   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
671 
672   if (TM)
673     TM->adjustPassManager(PMBuilder);
674 
675   if (CodeGenOpts.DebugInfoForProfiling ||
676       !CodeGenOpts.SampleProfileFile.empty())
677     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
678                            addAddDiscriminatorsPass);
679 
680   // In ObjC ARC mode, add the main ARC optimization passes.
681   if (LangOpts.ObjCAutoRefCount) {
682     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
683                            addObjCARCExpandPass);
684     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
685                            addObjCARCAPElimPass);
686     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
687                            addObjCARCOptPass);
688   }
689 
690   if (LangOpts.Coroutines)
691     addCoroutinePassesToExtensionPoints(PMBuilder);
692 
693   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
694     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
695                            addMemProfilerPasses);
696     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
697                            addMemProfilerPasses);
698   }
699 
700   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
701     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
702                            addBoundsCheckingPass);
703     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
704                            addBoundsCheckingPass);
705   }
706 
707   if (CodeGenOpts.SanitizeCoverageType ||
708       CodeGenOpts.SanitizeCoverageIndirectCalls ||
709       CodeGenOpts.SanitizeCoverageTraceCmp) {
710     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
711                            addSanitizerCoveragePass);
712     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
713                            addSanitizerCoveragePass);
714   }
715 
716   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
717     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
718                            addAddressSanitizerPasses);
719     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
720                            addAddressSanitizerPasses);
721   }
722 
723   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
724     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
725                            addKernelAddressSanitizerPasses);
726     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
727                            addKernelAddressSanitizerPasses);
728   }
729 
730   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
731     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
732                            addHWAddressSanitizerPasses);
733     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
734                            addHWAddressSanitizerPasses);
735   }
736 
737   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
738     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
739                            addKernelHWAddressSanitizerPasses);
740     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
741                            addKernelHWAddressSanitizerPasses);
742   }
743 
744   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
745     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
746                            addMemorySanitizerPass);
747     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
748                            addMemorySanitizerPass);
749   }
750 
751   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
752     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
753                            addKernelMemorySanitizerPass);
754     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
755                            addKernelMemorySanitizerPass);
756   }
757 
758   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
759     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
760                            addThreadSanitizerPass);
761     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
762                            addThreadSanitizerPass);
763   }
764 
765   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
766     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
767                            addDataFlowSanitizerPass);
768     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
769                            addDataFlowSanitizerPass);
770   }
771 
772   // Set up the per-function pass manager.
773   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
774   if (CodeGenOpts.VerifyModule)
775     FPM.add(createVerifierPass());
776 
777   // Set up the per-module pass manager.
778   if (!CodeGenOpts.RewriteMapFiles.empty())
779     addSymbolRewriterPass(CodeGenOpts, &MPM);
780 
781   // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols
782   // with unique names.
783   if (CodeGenOpts.UniqueInternalLinkageNames) {
784     MPM.add(createUniqueInternalLinkageNamesPass());
785   }
786 
787   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
788     MPM.add(createGCOVProfilerPass(*Options));
789     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
790       MPM.add(createStripSymbolsPass(true));
791   }
792 
793   if (Optional<InstrProfOptions> Options =
794           getInstrProfOptions(CodeGenOpts, LangOpts))
795     MPM.add(createInstrProfilingLegacyPass(*Options, false));
796 
797   bool hasIRInstr = false;
798   if (CodeGenOpts.hasProfileIRInstr()) {
799     PMBuilder.EnablePGOInstrGen = true;
800     hasIRInstr = true;
801   }
802   if (CodeGenOpts.hasProfileCSIRInstr()) {
803     assert(!CodeGenOpts.hasProfileCSIRUse() &&
804            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
805            "same time");
806     assert(!hasIRInstr &&
807            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
808            "same time");
809     PMBuilder.EnablePGOCSInstrGen = true;
810     hasIRInstr = true;
811   }
812   if (hasIRInstr) {
813     if (!CodeGenOpts.InstrProfileOutput.empty())
814       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
815     else
816       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
817   }
818   if (CodeGenOpts.hasProfileIRUse()) {
819     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
820     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
821   }
822 
823   if (!CodeGenOpts.SampleProfileFile.empty())
824     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
825 
826   PMBuilder.populateFunctionPassManager(FPM);
827   PMBuilder.populateModulePassManager(MPM);
828 }
829 
830 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
831   SmallVector<const char *, 16> BackendArgs;
832   BackendArgs.push_back("clang"); // Fake program name.
833   if (!CodeGenOpts.DebugPass.empty()) {
834     BackendArgs.push_back("-debug-pass");
835     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
836   }
837   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
838     BackendArgs.push_back("-limit-float-precision");
839     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
840   }
841   BackendArgs.push_back(nullptr);
842   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
843                                     BackendArgs.data());
844 }
845 
846 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
847   // Create the TargetMachine for generating code.
848   std::string Error;
849   std::string Triple = TheModule->getTargetTriple();
850   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
851   if (!TheTarget) {
852     if (MustCreateTM)
853       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
854     return;
855   }
856 
857   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
858   std::string FeaturesStr =
859       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
860   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
861   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
862 
863   llvm::TargetOptions Options;
864   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
865                          HSOpts))
866     return;
867   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
868                                           Options, RM, CM, OptLevel));
869 }
870 
871 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
872                                        BackendAction Action,
873                                        raw_pwrite_stream &OS,
874                                        raw_pwrite_stream *DwoOS) {
875   // Add LibraryInfo.
876   llvm::Triple TargetTriple(TheModule->getTargetTriple());
877   std::unique_ptr<TargetLibraryInfoImpl> TLII(
878       createTLII(TargetTriple, CodeGenOpts));
879   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
880 
881   // Normal mode, emit a .s or .o file by running the code generator. Note,
882   // this also adds codegenerator level optimization passes.
883   CodeGenFileType CGFT = getCodeGenFileType(Action);
884 
885   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
886   // "codegen" passes so that it isn't run multiple times when there is
887   // inlining happening.
888   if (CodeGenOpts.OptimizationLevel > 0)
889     CodeGenPasses.add(createObjCARCContractPass());
890 
891   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
892                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
893     Diags.Report(diag::err_fe_unable_to_interface_with_target);
894     return false;
895   }
896 
897   return true;
898 }
899 
900 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
901                                       std::unique_ptr<raw_pwrite_stream> OS) {
902   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
903 
904   setCommandLineOpts(CodeGenOpts);
905 
906   bool UsesCodeGen = (Action != Backend_EmitNothing &&
907                       Action != Backend_EmitBC &&
908                       Action != Backend_EmitLL);
909   CreateTargetMachine(UsesCodeGen);
910 
911   if (UsesCodeGen && !TM)
912     return;
913   if (TM)
914     TheModule->setDataLayout(TM->createDataLayout());
915 
916   legacy::PassManager PerModulePasses;
917   PerModulePasses.add(
918       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
919 
920   legacy::FunctionPassManager PerFunctionPasses(TheModule);
921   PerFunctionPasses.add(
922       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
923 
924   CreatePasses(PerModulePasses, PerFunctionPasses);
925 
926   legacy::PassManager CodeGenPasses;
927   CodeGenPasses.add(
928       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
929 
930   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
931 
932   switch (Action) {
933   case Backend_EmitNothing:
934     break;
935 
936   case Backend_EmitBC:
937     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
938       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
939         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
940         if (!ThinLinkOS)
941           return;
942       }
943       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
944                                CodeGenOpts.EnableSplitLTOUnit);
945       PerModulePasses.add(createWriteThinLTOBitcodePass(
946           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
947     } else {
948       // Emit a module summary by default for Regular LTO except for ld64
949       // targets
950       bool EmitLTOSummary =
951           (CodeGenOpts.PrepareForLTO &&
952            !CodeGenOpts.DisableLLVMPasses &&
953            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
954                llvm::Triple::Apple);
955       if (EmitLTOSummary) {
956         if (!TheModule->getModuleFlag("ThinLTO"))
957           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
958         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
959                                  uint32_t(1));
960       }
961 
962       PerModulePasses.add(createBitcodeWriterPass(
963           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
964     }
965     break;
966 
967   case Backend_EmitLL:
968     PerModulePasses.add(
969         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
970     break;
971 
972   default:
973     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
974       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
975       if (!DwoOS)
976         return;
977     }
978     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
979                        DwoOS ? &DwoOS->os() : nullptr))
980       return;
981   }
982 
983   // Before executing passes, print the final values of the LLVM options.
984   cl::PrintOptionValues();
985 
986   // Run passes. For now we do all passes at once, but eventually we
987   // would like to have the option of streaming code generation.
988 
989   {
990     PrettyStackTraceString CrashInfo("Per-function optimization");
991     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
992 
993     PerFunctionPasses.doInitialization();
994     for (Function &F : *TheModule)
995       if (!F.isDeclaration())
996         PerFunctionPasses.run(F);
997     PerFunctionPasses.doFinalization();
998   }
999 
1000   {
1001     PrettyStackTraceString CrashInfo("Per-module optimization passes");
1002     llvm::TimeTraceScope TimeScope("PerModulePasses");
1003     PerModulePasses.run(*TheModule);
1004   }
1005 
1006   {
1007     PrettyStackTraceString CrashInfo("Code generation");
1008     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1009     CodeGenPasses.run(*TheModule);
1010   }
1011 
1012   if (ThinLinkOS)
1013     ThinLinkOS->keep();
1014   if (DwoOS)
1015     DwoOS->keep();
1016 }
1017 
1018 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
1019   switch (Opts.OptimizationLevel) {
1020   default:
1021     llvm_unreachable("Invalid optimization level!");
1022 
1023   case 0:
1024     return PassBuilder::OptimizationLevel::O0;
1025 
1026   case 1:
1027     return PassBuilder::OptimizationLevel::O1;
1028 
1029   case 2:
1030     switch (Opts.OptimizeSize) {
1031     default:
1032       llvm_unreachable("Invalid optimization level for size!");
1033 
1034     case 0:
1035       return PassBuilder::OptimizationLevel::O2;
1036 
1037     case 1:
1038       return PassBuilder::OptimizationLevel::Os;
1039 
1040     case 2:
1041       return PassBuilder::OptimizationLevel::Oz;
1042     }
1043 
1044   case 3:
1045     return PassBuilder::OptimizationLevel::O3;
1046   }
1047 }
1048 
1049 static void addCoroutinePassesAtO0(ModulePassManager &MPM,
1050                                    const LangOptions &LangOpts,
1051                                    const CodeGenOptions &CodeGenOpts) {
1052   if (!LangOpts.Coroutines)
1053     return;
1054 
1055   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1056 
1057   CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
1058   CGPM.addPass(CoroSplitPass());
1059   CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
1060   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1061 
1062   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1063 }
1064 
1065 static void addSanitizersAtO0(ModulePassManager &MPM,
1066                               const Triple &TargetTriple,
1067                               const LangOptions &LangOpts,
1068                               const CodeGenOptions &CodeGenOpts) {
1069   if (CodeGenOpts.SanitizeCoverageType ||
1070       CodeGenOpts.SanitizeCoverageIndirectCalls ||
1071       CodeGenOpts.SanitizeCoverageTraceCmp) {
1072     auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1073     MPM.addPass(ModuleSanitizerCoveragePass(
1074         SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1075         CodeGenOpts.SanitizeCoverageBlocklistFiles));
1076   }
1077 
1078   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1079     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1080     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1081     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1082         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
1083     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1084     MPM.addPass(
1085         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1086                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
1087   };
1088 
1089   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1090     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1091   }
1092 
1093   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1094     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
1095   }
1096 
1097   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1098     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1099     MPM.addPass(HWAddressSanitizerPass(
1100         /*CompileKernel=*/false, Recover));
1101   }
1102   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1103     MPM.addPass(HWAddressSanitizerPass(
1104         /*CompileKernel=*/true, /*Recover=*/true));
1105   }
1106 
1107   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1108     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1109     int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1110     MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1111     MPM.addPass(createModuleToFunctionPassAdaptor(
1112         MemorySanitizerPass({TrackOrigins, Recover, false})));
1113   }
1114 
1115   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1116     MPM.addPass(createModuleToFunctionPassAdaptor(
1117         MemorySanitizerPass({0, false, /*Kernel=*/true})));
1118   }
1119 
1120   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1121     MPM.addPass(ThreadSanitizerPass());
1122     MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1123   }
1124 }
1125 
1126 /// A clean version of `EmitAssembly` that uses the new pass manager.
1127 ///
1128 /// Not all features are currently supported in this system, but where
1129 /// necessary it falls back to the legacy pass manager to at least provide
1130 /// basic functionality.
1131 ///
1132 /// This API is planned to have its functionality finished and then to replace
1133 /// `EmitAssembly` at some point in the future when the default switches.
1134 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1135     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1136   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
1137   setCommandLineOpts(CodeGenOpts);
1138 
1139   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1140                           Action != Backend_EmitBC &&
1141                           Action != Backend_EmitLL);
1142   CreateTargetMachine(RequiresCodeGen);
1143 
1144   if (RequiresCodeGen && !TM)
1145     return;
1146   if (TM)
1147     TheModule->setDataLayout(TM->createDataLayout());
1148 
1149   Optional<PGOOptions> PGOOpt;
1150 
1151   if (CodeGenOpts.hasProfileIRInstr())
1152     // -fprofile-generate.
1153     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1154                             ? std::string(DefaultProfileGenName)
1155                             : CodeGenOpts.InstrProfileOutput,
1156                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1157                         CodeGenOpts.DebugInfoForProfiling);
1158   else if (CodeGenOpts.hasProfileIRUse()) {
1159     // -fprofile-use.
1160     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1161                                                     : PGOOptions::NoCSAction;
1162     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1163                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1164                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1165   } else if (!CodeGenOpts.SampleProfileFile.empty())
1166     // -fprofile-sample-use
1167     PGOOpt =
1168         PGOOptions(CodeGenOpts.SampleProfileFile, "",
1169                    CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1170                    PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1171   else if (CodeGenOpts.DebugInfoForProfiling)
1172     // -fdebug-info-for-profiling
1173     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1174                         PGOOptions::NoCSAction, true);
1175 
1176   // Check to see if we want to generate a CS profile.
1177   if (CodeGenOpts.hasProfileCSIRInstr()) {
1178     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1179            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1180            "the same time");
1181     if (PGOOpt.hasValue()) {
1182       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1183              PGOOpt->Action != PGOOptions::SampleUse &&
1184              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1185              " pass");
1186       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1187                                      ? std::string(DefaultProfileGenName)
1188                                      : CodeGenOpts.InstrProfileOutput;
1189       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1190     } else
1191       PGOOpt = PGOOptions("",
1192                           CodeGenOpts.InstrProfileOutput.empty()
1193                               ? std::string(DefaultProfileGenName)
1194                               : CodeGenOpts.InstrProfileOutput,
1195                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1196                           CodeGenOpts.DebugInfoForProfiling);
1197   }
1198 
1199   PipelineTuningOptions PTO;
1200   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1201   // For historical reasons, loop interleaving is set to mirror setting for loop
1202   // unrolling.
1203   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1204   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1205   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1206   // Only enable CGProfilePass when using integrated assembler, since
1207   // non-integrated assemblers don't recognize .cgprofile section.
1208   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1209   PTO.Coroutines = LangOpts.Coroutines;
1210 
1211   PassInstrumentationCallbacks PIC;
1212   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1213   SI.registerCallbacks(PIC);
1214   PassBuilder PB(CodeGenOpts.DebugPassManager, TM.get(), PTO, PGOOpt, &PIC);
1215 
1216   // Attempt to load pass plugins and register their callbacks with PB.
1217   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1218     auto PassPlugin = PassPlugin::Load(PluginFN);
1219     if (PassPlugin) {
1220       PassPlugin->registerPassBuilderCallbacks(PB);
1221     } else {
1222       Diags.Report(diag::err_fe_unable_to_load_plugin)
1223           << PluginFN << toString(PassPlugin.takeError());
1224     }
1225   }
1226 #define HANDLE_EXTENSION(Ext)                                                  \
1227   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1228 #include "llvm/Support/Extension.def"
1229 
1230   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1231   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1232   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1233   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1234 
1235   // Register the AA manager first so that our version is the one used.
1236   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1237 
1238   // Register the target library analysis directly and give it a customized
1239   // preset TLI.
1240   Triple TargetTriple(TheModule->getTargetTriple());
1241   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1242       createTLII(TargetTriple, CodeGenOpts));
1243   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1244 
1245   // Register all the basic analyses with the managers.
1246   PB.registerModuleAnalyses(MAM);
1247   PB.registerCGSCCAnalyses(CGAM);
1248   PB.registerFunctionAnalyses(FAM);
1249   PB.registerLoopAnalyses(LAM);
1250   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1251 
1252   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1253 
1254   if (!CodeGenOpts.DisableLLVMPasses) {
1255     // Map our optimization levels into one of the distinct levels used to
1256     // configure the pipeline.
1257     PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1258 
1259     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1260     bool IsLTO = CodeGenOpts.PrepareForLTO;
1261 
1262     if (CodeGenOpts.OptimizationLevel == 0) {
1263       // If we reached here with a non-empty index file name, then the index
1264       // file was empty and we are not performing ThinLTO backend compilation
1265       // (used in testing in a distributed build environment). Drop any the type
1266       // test assume sequences inserted for whole program vtables so that
1267       // codegen doesn't complain.
1268       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1269         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1270                                        /*ImportSummary=*/nullptr,
1271                                        /*DropTypeTests=*/true));
1272       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1273         MPM.addPass(GCOVProfilerPass(*Options));
1274       if (Optional<InstrProfOptions> Options =
1275               getInstrProfOptions(CodeGenOpts, LangOpts))
1276         MPM.addPass(InstrProfiling(*Options, false));
1277 
1278       // Build a minimal pipeline based on the semantics required by Clang,
1279       // which is just that always inlining occurs. Further, disable generating
1280       // lifetime intrinsics to avoid enabling further optimizations during
1281       // code generation.
1282       // However, we need to insert lifetime intrinsics to avoid invalid access
1283       // caused by multithreaded coroutines.
1284       MPM.addPass(
1285           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1286 
1287       // At -O0, we can still do PGO. Add all the requested passes for
1288       // instrumentation PGO, if requested.
1289       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1290                      PGOOpt->Action == PGOOptions::IRUse))
1291         PB.addPGOInstrPassesForO0(
1292             MPM,
1293             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1294             /* IsCS */ false, PGOOpt->ProfileFile,
1295             PGOOpt->ProfileRemappingFile);
1296 
1297       // At -O0 we directly run necessary sanitizer passes.
1298       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1299         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1300 
1301       // Lastly, add semantically necessary passes for LTO.
1302       if (IsLTO || IsThinLTO) {
1303         MPM.addPass(CanonicalizeAliasesPass());
1304         MPM.addPass(NameAnonGlobalPass());
1305       }
1306     } else {
1307       // If we reached here with a non-empty index file name, then the index
1308       // file was empty and we are not performing ThinLTO backend compilation
1309       // (used in testing in a distributed build environment). Drop any the type
1310       // test assume sequences inserted for whole program vtables so that
1311       // codegen doesn't complain.
1312       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1313         PB.registerPipelineStartEPCallback(
1314             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1315               MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1316                                              /*ImportSummary=*/nullptr,
1317                                              /*DropTypeTests=*/true));
1318             });
1319 
1320       PB.registerPipelineStartEPCallback(
1321           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1322             MPM.addPass(createModuleToFunctionPassAdaptor(
1323                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1324           });
1325 
1326       // Register callbacks to schedule sanitizer passes at the appropriate part of
1327       // the pipeline.
1328       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1329         PB.registerScalarOptimizerLateEPCallback(
1330             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1331               FPM.addPass(BoundsCheckingPass());
1332             });
1333 
1334       if (CodeGenOpts.SanitizeCoverageType ||
1335           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1336           CodeGenOpts.SanitizeCoverageTraceCmp) {
1337         PB.registerOptimizerLastEPCallback(
1338             [this](ModulePassManager &MPM,
1339                    PassBuilder::OptimizationLevel Level) {
1340               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1341               MPM.addPass(ModuleSanitizerCoveragePass(
1342                   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1343                   CodeGenOpts.SanitizeCoverageBlocklistFiles));
1344             });
1345       }
1346 
1347       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1348         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1349         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1350         PB.registerOptimizerLastEPCallback(
1351             [TrackOrigins, Recover](ModulePassManager &MPM,
1352                                     PassBuilder::OptimizationLevel Level) {
1353               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1354               MPM.addPass(createModuleToFunctionPassAdaptor(
1355                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1356             });
1357       }
1358       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1359         PB.registerOptimizerLastEPCallback(
1360             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1361               MPM.addPass(ThreadSanitizerPass());
1362               MPM.addPass(
1363                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1364             });
1365       }
1366       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1367         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1368         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1369         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1370         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1371         PB.registerOptimizerLastEPCallback(
1372             [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator](
1373                 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1374               MPM.addPass(
1375                   RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1376               MPM.addPass(ModuleAddressSanitizerPass(
1377                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1378                   UseOdrIndicator));
1379               MPM.addPass(
1380                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1381                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1382             });
1383       }
1384 
1385       if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1386         bool Recover =
1387             CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1388         PB.registerOptimizerLastEPCallback(
1389             [Recover](ModulePassManager &MPM,
1390                       PassBuilder::OptimizationLevel Level) {
1391               MPM.addPass(HWAddressSanitizerPass(
1392                   /*CompileKernel=*/false, Recover));
1393             });
1394       }
1395       if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1396         bool Recover =
1397             CodeGenOpts.SanitizeRecover.has(SanitizerKind::KernelHWAddress);
1398         PB.registerOptimizerLastEPCallback(
1399             [Recover](ModulePassManager &MPM,
1400                       PassBuilder::OptimizationLevel Level) {
1401               MPM.addPass(HWAddressSanitizerPass(
1402                   /*CompileKernel=*/true, Recover));
1403             });
1404       }
1405 
1406       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1407         PB.registerPipelineStartEPCallback(
1408             [Options](ModulePassManager &MPM,
1409                       PassBuilder::OptimizationLevel Level) {
1410               MPM.addPass(GCOVProfilerPass(*Options));
1411             });
1412       if (Optional<InstrProfOptions> Options =
1413               getInstrProfOptions(CodeGenOpts, LangOpts))
1414         PB.registerPipelineStartEPCallback(
1415             [Options](ModulePassManager &MPM,
1416                       PassBuilder::OptimizationLevel Level) {
1417               MPM.addPass(InstrProfiling(*Options, false));
1418             });
1419 
1420       if (IsThinLTO) {
1421         MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
1422         MPM.addPass(CanonicalizeAliasesPass());
1423         MPM.addPass(NameAnonGlobalPass());
1424       } else if (IsLTO) {
1425         MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
1426         MPM.addPass(CanonicalizeAliasesPass());
1427         MPM.addPass(NameAnonGlobalPass());
1428       } else {
1429         MPM = PB.buildPerModuleDefaultPipeline(Level);
1430       }
1431     }
1432 
1433     // Add UniqueInternalLinkageNames Pass which renames internal linkage
1434     // symbols with unique names.
1435     if (CodeGenOpts.UniqueInternalLinkageNames)
1436       MPM.addPass(UniqueInternalLinkageNamesPass());
1437 
1438     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1439       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1440       MPM.addPass(ModuleMemProfilerPass());
1441     }
1442 
1443     if (CodeGenOpts.OptimizationLevel == 0) {
1444       PB.runRegisteredEPCallbacks(MPM, Level, CodeGenOpts.DebugPassManager);
1445 
1446       // FIXME: the backends do not handle matrix intrinsics currently. Make
1447       // sure they are also lowered in O0. A lightweight version of the pass
1448       // should run in the backend pipeline on demand.
1449       if (LangOpts.MatrixTypes)
1450         MPM.addPass(
1451             createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass()));
1452 
1453       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1454       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1455     }
1456   }
1457 
1458   // FIXME: We still use the legacy pass manager to do code generation. We
1459   // create that pass manager here and use it as needed below.
1460   legacy::PassManager CodeGenPasses;
1461   bool NeedCodeGen = false;
1462   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1463 
1464   // Append any output we need to the pass manager.
1465   switch (Action) {
1466   case Backend_EmitNothing:
1467     break;
1468 
1469   case Backend_EmitBC:
1470     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1471       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1472         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1473         if (!ThinLinkOS)
1474           return;
1475       }
1476       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1477                                CodeGenOpts.EnableSplitLTOUnit);
1478       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1479                                                            : nullptr));
1480     } else {
1481       // Emit a module summary by default for Regular LTO except for ld64
1482       // targets
1483       bool EmitLTOSummary =
1484           (CodeGenOpts.PrepareForLTO &&
1485            !CodeGenOpts.DisableLLVMPasses &&
1486            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1487                llvm::Triple::Apple);
1488       if (EmitLTOSummary) {
1489         if (!TheModule->getModuleFlag("ThinLTO"))
1490           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1491         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1492                                  uint32_t(1));
1493       }
1494       MPM.addPass(
1495           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1496     }
1497     break;
1498 
1499   case Backend_EmitLL:
1500     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1501     break;
1502 
1503   case Backend_EmitAssembly:
1504   case Backend_EmitMCNull:
1505   case Backend_EmitObj:
1506     NeedCodeGen = true;
1507     CodeGenPasses.add(
1508         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1509     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1510       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1511       if (!DwoOS)
1512         return;
1513     }
1514     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1515                        DwoOS ? &DwoOS->os() : nullptr))
1516       // FIXME: Should we handle this error differently?
1517       return;
1518     break;
1519   }
1520 
1521   // Before executing passes, print the final values of the LLVM options.
1522   cl::PrintOptionValues();
1523 
1524   // Now that we have all of the passes ready, run them.
1525   {
1526     PrettyStackTraceString CrashInfo("Optimizer");
1527     MPM.run(*TheModule, MAM);
1528   }
1529 
1530   // Now if needed, run the legacy PM for codegen.
1531   if (NeedCodeGen) {
1532     PrettyStackTraceString CrashInfo("Code generation");
1533     CodeGenPasses.run(*TheModule);
1534   }
1535 
1536   if (ThinLinkOS)
1537     ThinLinkOS->keep();
1538   if (DwoOS)
1539     DwoOS->keep();
1540 }
1541 
1542 static void runThinLTOBackend(
1543     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1544     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1545     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1546     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1547     std::string ProfileRemapping, BackendAction Action) {
1548   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1549       ModuleToDefinedGVSummaries;
1550   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1551 
1552   setCommandLineOpts(CGOpts);
1553 
1554   // We can simply import the values mentioned in the combined index, since
1555   // we should only invoke this using the individual indexes written out
1556   // via a WriteIndexesThinBackend.
1557   FunctionImporter::ImportMapTy ImportList;
1558   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1559   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1560   if (!lto::loadReferencedModules(*M, *CombinedIndex, ImportList, ModuleMap,
1561                                   OwnedImports))
1562     return;
1563 
1564   auto AddStream = [&](size_t Task) {
1565     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1566   };
1567   lto::Config Conf;
1568   if (CGOpts.SaveTempsFilePrefix != "") {
1569     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1570                                     /* UseInputModulePath */ false)) {
1571       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1572         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1573                << '\n';
1574       });
1575     }
1576   }
1577   Conf.CPU = TOpts.CPU;
1578   Conf.CodeModel = getCodeModel(CGOpts);
1579   Conf.MAttrs = TOpts.Features;
1580   Conf.RelocModel = CGOpts.RelocationModel;
1581   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1582   Conf.OptLevel = CGOpts.OptimizationLevel;
1583   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1584   Conf.SampleProfile = std::move(SampleProfile);
1585   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1586   // For historical reasons, loop interleaving is set to mirror setting for loop
1587   // unrolling.
1588   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1589   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1590   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1591   // Only enable CGProfilePass when using integrated assembler, since
1592   // non-integrated assemblers don't recognize .cgprofile section.
1593   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1594 
1595   // Context sensitive profile.
1596   if (CGOpts.hasProfileCSIRInstr()) {
1597     Conf.RunCSIRInstr = true;
1598     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1599   } else if (CGOpts.hasProfileCSIRUse()) {
1600     Conf.RunCSIRInstr = false;
1601     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1602   }
1603 
1604   Conf.ProfileRemapping = std::move(ProfileRemapping);
1605   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1606   Conf.DebugPassManager = CGOpts.DebugPassManager;
1607   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1608   Conf.RemarksFilename = CGOpts.OptRecordFile;
1609   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1610   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1611   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1612   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1613   switch (Action) {
1614   case Backend_EmitNothing:
1615     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1616       return false;
1617     };
1618     break;
1619   case Backend_EmitLL:
1620     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1621       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1622       return false;
1623     };
1624     break;
1625   case Backend_EmitBC:
1626     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1627       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1628       return false;
1629     };
1630     break;
1631   default:
1632     Conf.CGFileType = getCodeGenFileType(Action);
1633     break;
1634   }
1635   if (Error E =
1636           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1637                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1638                       ModuleMap, CGOpts.CmdArgs)) {
1639     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1640       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1641     });
1642   }
1643 }
1644 
1645 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1646                               const HeaderSearchOptions &HeaderOpts,
1647                               const CodeGenOptions &CGOpts,
1648                               const clang::TargetOptions &TOpts,
1649                               const LangOptions &LOpts,
1650                               const llvm::DataLayout &TDesc, Module *M,
1651                               BackendAction Action,
1652                               std::unique_ptr<raw_pwrite_stream> OS) {
1653 
1654   llvm::TimeTraceScope TimeScope("Backend");
1655 
1656   std::unique_ptr<llvm::Module> EmptyModule;
1657   if (!CGOpts.ThinLTOIndexFile.empty()) {
1658     // If we are performing a ThinLTO importing compile, load the function index
1659     // into memory and pass it into runThinLTOBackend, which will run the
1660     // function importer and invoke LTO passes.
1661     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1662         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1663                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1664     if (!IndexOrErr) {
1665       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1666                             "Error loading index file '" +
1667                             CGOpts.ThinLTOIndexFile + "': ");
1668       return;
1669     }
1670     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1671     // A null CombinedIndex means we should skip ThinLTO compilation
1672     // (LLVM will optionally ignore empty index files, returning null instead
1673     // of an error).
1674     if (CombinedIndex) {
1675       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1676         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1677                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1678                           CGOpts.ProfileRemappingFile, Action);
1679         return;
1680       }
1681       // Distributed indexing detected that nothing from the module is needed
1682       // for the final linking. So we can skip the compilation. We sill need to
1683       // output an empty object file to make sure that a linker does not fail
1684       // trying to read it. Also for some features, like CFI, we must skip
1685       // the compilation as CombinedIndex does not contain all required
1686       // information.
1687       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1688       EmptyModule->setTargetTriple(M->getTargetTriple());
1689       M = EmptyModule.get();
1690     }
1691   }
1692 
1693   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1694 
1695   if (CGOpts.ExperimentalNewPassManager)
1696     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1697   else
1698     AsmHelper.EmitAssembly(Action, std::move(OS));
1699 
1700   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1701   // DataLayout.
1702   if (AsmHelper.TM) {
1703     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1704     if (DLDesc != TDesc.getStringRepresentation()) {
1705       unsigned DiagID = Diags.getCustomDiagID(
1706           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1707                                     "expected target description '%1'");
1708       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1709     }
1710   }
1711 }
1712 
1713 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1714 // __LLVM,__bitcode section.
1715 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1716                          llvm::MemoryBufferRef Buf) {
1717   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1718     return;
1719   llvm::EmbedBitcodeInModule(
1720       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1721       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1722       CGOpts.CmdArgs);
1723 }
1724