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