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 1:
1024     return PassBuilder::OptimizationLevel::O1;
1025 
1026   case 2:
1027     switch (Opts.OptimizeSize) {
1028     default:
1029       llvm_unreachable("Invalid optimization level for size!");
1030 
1031     case 0:
1032       return PassBuilder::OptimizationLevel::O2;
1033 
1034     case 1:
1035       return PassBuilder::OptimizationLevel::Os;
1036 
1037     case 2:
1038       return PassBuilder::OptimizationLevel::Oz;
1039     }
1040 
1041   case 3:
1042     return PassBuilder::OptimizationLevel::O3;
1043   }
1044 }
1045 
1046 static void addCoroutinePassesAtO0(ModulePassManager &MPM,
1047                                    const LangOptions &LangOpts,
1048                                    const CodeGenOptions &CodeGenOpts) {
1049   if (!LangOpts.Coroutines)
1050     return;
1051 
1052   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1053 
1054   CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
1055   CGPM.addPass(CoroSplitPass());
1056   CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
1057   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1058 
1059   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1060 }
1061 
1062 static void addSanitizersAtO0(ModulePassManager &MPM,
1063                               const Triple &TargetTriple,
1064                               const LangOptions &LangOpts,
1065                               const CodeGenOptions &CodeGenOpts) {
1066   if (CodeGenOpts.SanitizeCoverageType ||
1067       CodeGenOpts.SanitizeCoverageIndirectCalls ||
1068       CodeGenOpts.SanitizeCoverageTraceCmp) {
1069     auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1070     MPM.addPass(ModuleSanitizerCoveragePass(
1071         SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1072         CodeGenOpts.SanitizeCoverageBlocklistFiles));
1073   }
1074 
1075   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1076     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1077     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1078     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1079         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
1080     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1081     MPM.addPass(
1082         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1083                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
1084   };
1085 
1086   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1087     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1088   }
1089 
1090   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1091     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
1092   }
1093 
1094   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1095     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1096     MPM.addPass(HWAddressSanitizerPass(
1097         /*CompileKernel=*/false, Recover));
1098   }
1099   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1100     MPM.addPass(HWAddressSanitizerPass(
1101         /*CompileKernel=*/true, /*Recover=*/true));
1102   }
1103 
1104   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1105     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1106     int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1107     MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1108     MPM.addPass(createModuleToFunctionPassAdaptor(
1109         MemorySanitizerPass({TrackOrigins, Recover, false})));
1110   }
1111 
1112   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1113     MPM.addPass(createModuleToFunctionPassAdaptor(
1114         MemorySanitizerPass({0, false, /*Kernel=*/true})));
1115   }
1116 
1117   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1118     MPM.addPass(ThreadSanitizerPass());
1119     MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1120   }
1121 }
1122 
1123 /// A clean version of `EmitAssembly` that uses the new pass manager.
1124 ///
1125 /// Not all features are currently supported in this system, but where
1126 /// necessary it falls back to the legacy pass manager to at least provide
1127 /// basic functionality.
1128 ///
1129 /// This API is planned to have its functionality finished and then to replace
1130 /// `EmitAssembly` at some point in the future when the default switches.
1131 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1132     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1133   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
1134   setCommandLineOpts(CodeGenOpts);
1135 
1136   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1137                           Action != Backend_EmitBC &&
1138                           Action != Backend_EmitLL);
1139   CreateTargetMachine(RequiresCodeGen);
1140 
1141   if (RequiresCodeGen && !TM)
1142     return;
1143   if (TM)
1144     TheModule->setDataLayout(TM->createDataLayout());
1145 
1146   Optional<PGOOptions> PGOOpt;
1147 
1148   if (CodeGenOpts.hasProfileIRInstr())
1149     // -fprofile-generate.
1150     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1151                             ? std::string(DefaultProfileGenName)
1152                             : CodeGenOpts.InstrProfileOutput,
1153                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1154                         CodeGenOpts.DebugInfoForProfiling);
1155   else if (CodeGenOpts.hasProfileIRUse()) {
1156     // -fprofile-use.
1157     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1158                                                     : PGOOptions::NoCSAction;
1159     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1160                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1161                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1162   } else if (!CodeGenOpts.SampleProfileFile.empty())
1163     // -fprofile-sample-use
1164     PGOOpt =
1165         PGOOptions(CodeGenOpts.SampleProfileFile, "",
1166                    CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1167                    PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1168   else if (CodeGenOpts.DebugInfoForProfiling)
1169     // -fdebug-info-for-profiling
1170     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1171                         PGOOptions::NoCSAction, true);
1172 
1173   // Check to see if we want to generate a CS profile.
1174   if (CodeGenOpts.hasProfileCSIRInstr()) {
1175     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1176            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1177            "the same time");
1178     if (PGOOpt.hasValue()) {
1179       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1180              PGOOpt->Action != PGOOptions::SampleUse &&
1181              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1182              " pass");
1183       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1184                                      ? std::string(DefaultProfileGenName)
1185                                      : CodeGenOpts.InstrProfileOutput;
1186       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1187     } else
1188       PGOOpt = PGOOptions("",
1189                           CodeGenOpts.InstrProfileOutput.empty()
1190                               ? std::string(DefaultProfileGenName)
1191                               : CodeGenOpts.InstrProfileOutput,
1192                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1193                           CodeGenOpts.DebugInfoForProfiling);
1194   }
1195 
1196   PipelineTuningOptions PTO;
1197   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1198   // For historical reasons, loop interleaving is set to mirror setting for loop
1199   // unrolling.
1200   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1201   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1202   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1203   // Only enable CGProfilePass when using integrated assembler, since
1204   // non-integrated assemblers don't recognize .cgprofile section.
1205   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1206   PTO.Coroutines = LangOpts.Coroutines;
1207 
1208   PassInstrumentationCallbacks PIC;
1209   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1210   SI.registerCallbacks(PIC);
1211   PassBuilder PB(CodeGenOpts.DebugPassManager, TM.get(), PTO, PGOOpt, &PIC);
1212 
1213   // Attempt to load pass plugins and register their callbacks with PB.
1214   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1215     auto PassPlugin = PassPlugin::Load(PluginFN);
1216     if (PassPlugin) {
1217       PassPlugin->registerPassBuilderCallbacks(PB);
1218     } else {
1219       Diags.Report(diag::err_fe_unable_to_load_plugin)
1220           << PluginFN << toString(PassPlugin.takeError());
1221     }
1222   }
1223 #define HANDLE_EXTENSION(Ext)                                                  \
1224   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1225 #include "llvm/Support/Extension.def"
1226 
1227   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1228   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1229   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1230   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1231 
1232   // Register the AA manager first so that our version is the one used.
1233   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1234 
1235   // Register the target library analysis directly and give it a customized
1236   // preset TLI.
1237   Triple TargetTriple(TheModule->getTargetTriple());
1238   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1239       createTLII(TargetTriple, CodeGenOpts));
1240   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1241 
1242   // Register all the basic analyses with the managers.
1243   PB.registerModuleAnalyses(MAM);
1244   PB.registerCGSCCAnalyses(CGAM);
1245   PB.registerFunctionAnalyses(FAM);
1246   PB.registerLoopAnalyses(LAM);
1247   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1248 
1249   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1250 
1251   if (!CodeGenOpts.DisableLLVMPasses) {
1252     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1253     bool IsLTO = CodeGenOpts.PrepareForLTO;
1254 
1255     if (CodeGenOpts.OptimizationLevel == 0) {
1256       // If we reached here with a non-empty index file name, then the index
1257       // file was empty and we are not performing ThinLTO backend compilation
1258       // (used in testing in a distributed build environment). Drop any the type
1259       // test assume sequences inserted for whole program vtables so that
1260       // codegen doesn't complain.
1261       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1262         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1263                                        /*ImportSummary=*/nullptr,
1264                                        /*DropTypeTests=*/true));
1265       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1266         MPM.addPass(GCOVProfilerPass(*Options));
1267       if (Optional<InstrProfOptions> Options =
1268               getInstrProfOptions(CodeGenOpts, LangOpts))
1269         MPM.addPass(InstrProfiling(*Options, false));
1270 
1271       // Build a minimal pipeline based on the semantics required by Clang,
1272       // which is just that always inlining occurs. Further, disable generating
1273       // lifetime intrinsics to avoid enabling further optimizations during
1274       // code generation.
1275       // However, we need to insert lifetime intrinsics to avoid invalid access
1276       // caused by multithreaded coroutines.
1277       MPM.addPass(
1278           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1279 
1280       // At -O0, we can still do PGO. Add all the requested passes for
1281       // instrumentation PGO, if requested.
1282       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1283                      PGOOpt->Action == PGOOptions::IRUse))
1284         PB.addPGOInstrPassesForO0(
1285             MPM,
1286             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1287             /* IsCS */ false, PGOOpt->ProfileFile,
1288             PGOOpt->ProfileRemappingFile);
1289 
1290       // At -O0 we directly run necessary sanitizer passes.
1291       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1292         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1293 
1294       // Lastly, add semantically necessary passes for LTO.
1295       if (IsLTO || IsThinLTO) {
1296         MPM.addPass(CanonicalizeAliasesPass());
1297         MPM.addPass(NameAnonGlobalPass());
1298       }
1299     } else {
1300       // Map our optimization levels into one of the distinct levels used to
1301       // configure the pipeline.
1302       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1303 
1304       // If we reached here with a non-empty index file name, then the index
1305       // file was empty and we are not performing ThinLTO backend compilation
1306       // (used in testing in a distributed build environment). Drop any the type
1307       // test assume sequences inserted for whole program vtables so that
1308       // codegen doesn't complain.
1309       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1310         PB.registerPipelineStartEPCallback(
1311             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1312               MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1313                                              /*ImportSummary=*/nullptr,
1314                                              /*DropTypeTests=*/true));
1315             });
1316 
1317       PB.registerPipelineStartEPCallback(
1318           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1319             MPM.addPass(createModuleToFunctionPassAdaptor(
1320                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1321           });
1322 
1323       // Register callbacks to schedule sanitizer passes at the appropriate part of
1324       // the pipeline.
1325       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1326         PB.registerScalarOptimizerLateEPCallback(
1327             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1328               FPM.addPass(BoundsCheckingPass());
1329             });
1330 
1331       if (CodeGenOpts.SanitizeCoverageType ||
1332           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1333           CodeGenOpts.SanitizeCoverageTraceCmp) {
1334         PB.registerOptimizerLastEPCallback(
1335             [this](ModulePassManager &MPM,
1336                    PassBuilder::OptimizationLevel Level) {
1337               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1338               MPM.addPass(ModuleSanitizerCoveragePass(
1339                   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1340                   CodeGenOpts.SanitizeCoverageBlocklistFiles));
1341             });
1342       }
1343 
1344       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1345         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1346         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1347         PB.registerOptimizerLastEPCallback(
1348             [TrackOrigins, Recover](ModulePassManager &MPM,
1349                                     PassBuilder::OptimizationLevel Level) {
1350               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1351               MPM.addPass(createModuleToFunctionPassAdaptor(
1352                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1353             });
1354       }
1355       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1356         PB.registerOptimizerLastEPCallback(
1357             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1358               MPM.addPass(ThreadSanitizerPass());
1359               MPM.addPass(
1360                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1361             });
1362       }
1363       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1364         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1365         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1366         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1367         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1368         PB.registerOptimizerLastEPCallback(
1369             [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator](
1370                 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1371               MPM.addPass(
1372                   RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1373               MPM.addPass(ModuleAddressSanitizerPass(
1374                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1375                   UseOdrIndicator));
1376               MPM.addPass(
1377                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1378                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1379             });
1380       }
1381 
1382       if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1383         bool Recover =
1384             CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1385         PB.registerOptimizerLastEPCallback(
1386             [Recover](ModulePassManager &MPM,
1387                       PassBuilder::OptimizationLevel Level) {
1388               MPM.addPass(HWAddressSanitizerPass(
1389                   /*CompileKernel=*/false, Recover));
1390             });
1391       }
1392       if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1393         bool Recover =
1394             CodeGenOpts.SanitizeRecover.has(SanitizerKind::KernelHWAddress);
1395         PB.registerOptimizerLastEPCallback(
1396             [Recover](ModulePassManager &MPM,
1397                       PassBuilder::OptimizationLevel Level) {
1398               MPM.addPass(HWAddressSanitizerPass(
1399                   /*CompileKernel=*/true, Recover));
1400             });
1401       }
1402 
1403       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1404         PB.registerPipelineStartEPCallback(
1405             [Options](ModulePassManager &MPM,
1406                       PassBuilder::OptimizationLevel Level) {
1407               MPM.addPass(GCOVProfilerPass(*Options));
1408             });
1409       if (Optional<InstrProfOptions> Options =
1410               getInstrProfOptions(CodeGenOpts, LangOpts))
1411         PB.registerPipelineStartEPCallback(
1412             [Options](ModulePassManager &MPM,
1413                       PassBuilder::OptimizationLevel Level) {
1414               MPM.addPass(InstrProfiling(*Options, false));
1415             });
1416 
1417       if (IsThinLTO) {
1418         MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
1419         MPM.addPass(CanonicalizeAliasesPass());
1420         MPM.addPass(NameAnonGlobalPass());
1421       } else if (IsLTO) {
1422         MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
1423         MPM.addPass(CanonicalizeAliasesPass());
1424         MPM.addPass(NameAnonGlobalPass());
1425       } else {
1426         MPM = PB.buildPerModuleDefaultPipeline(Level);
1427       }
1428     }
1429 
1430     // Add UniqueInternalLinkageNames Pass which renames internal linkage
1431     // symbols with unique names.
1432     if (CodeGenOpts.UniqueInternalLinkageNames)
1433       MPM.addPass(UniqueInternalLinkageNamesPass());
1434 
1435     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1436       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1437       MPM.addPass(ModuleMemProfilerPass());
1438     }
1439 
1440     if (CodeGenOpts.OptimizationLevel == 0) {
1441       // FIXME: the backends do not handle matrix intrinsics currently. Make
1442       // sure they are also lowered in O0. A lightweight version of the pass
1443       // should run in the backend pipeline on demand.
1444       if (LangOpts.MatrixTypes)
1445         MPM.addPass(
1446             createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass()));
1447 
1448       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1449       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1450     }
1451   }
1452 
1453   // FIXME: We still use the legacy pass manager to do code generation. We
1454   // create that pass manager here and use it as needed below.
1455   legacy::PassManager CodeGenPasses;
1456   bool NeedCodeGen = false;
1457   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1458 
1459   // Append any output we need to the pass manager.
1460   switch (Action) {
1461   case Backend_EmitNothing:
1462     break;
1463 
1464   case Backend_EmitBC:
1465     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1466       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1467         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1468         if (!ThinLinkOS)
1469           return;
1470       }
1471       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1472                                CodeGenOpts.EnableSplitLTOUnit);
1473       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1474                                                            : nullptr));
1475     } else {
1476       // Emit a module summary by default for Regular LTO except for ld64
1477       // targets
1478       bool EmitLTOSummary =
1479           (CodeGenOpts.PrepareForLTO &&
1480            !CodeGenOpts.DisableLLVMPasses &&
1481            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1482                llvm::Triple::Apple);
1483       if (EmitLTOSummary) {
1484         if (!TheModule->getModuleFlag("ThinLTO"))
1485           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1486         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1487                                  uint32_t(1));
1488       }
1489       MPM.addPass(
1490           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1491     }
1492     break;
1493 
1494   case Backend_EmitLL:
1495     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1496     break;
1497 
1498   case Backend_EmitAssembly:
1499   case Backend_EmitMCNull:
1500   case Backend_EmitObj:
1501     NeedCodeGen = true;
1502     CodeGenPasses.add(
1503         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1504     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1505       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1506       if (!DwoOS)
1507         return;
1508     }
1509     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1510                        DwoOS ? &DwoOS->os() : nullptr))
1511       // FIXME: Should we handle this error differently?
1512       return;
1513     break;
1514   }
1515 
1516   // Before executing passes, print the final values of the LLVM options.
1517   cl::PrintOptionValues();
1518 
1519   // Now that we have all of the passes ready, run them.
1520   {
1521     PrettyStackTraceString CrashInfo("Optimizer");
1522     MPM.run(*TheModule, MAM);
1523   }
1524 
1525   // Now if needed, run the legacy PM for codegen.
1526   if (NeedCodeGen) {
1527     PrettyStackTraceString CrashInfo("Code generation");
1528     CodeGenPasses.run(*TheModule);
1529   }
1530 
1531   if (ThinLinkOS)
1532     ThinLinkOS->keep();
1533   if (DwoOS)
1534     DwoOS->keep();
1535 }
1536 
1537 static void runThinLTOBackend(
1538     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1539     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1540     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1541     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1542     std::string ProfileRemapping, BackendAction Action) {
1543   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1544       ModuleToDefinedGVSummaries;
1545   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1546 
1547   setCommandLineOpts(CGOpts);
1548 
1549   // We can simply import the values mentioned in the combined index, since
1550   // we should only invoke this using the individual indexes written out
1551   // via a WriteIndexesThinBackend.
1552   FunctionImporter::ImportMapTy ImportList;
1553   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1554   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1555   if (!lto::loadReferencedModules(*M, *CombinedIndex, ImportList, ModuleMap,
1556                                   OwnedImports))
1557     return;
1558 
1559   auto AddStream = [&](size_t Task) {
1560     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1561   };
1562   lto::Config Conf;
1563   if (CGOpts.SaveTempsFilePrefix != "") {
1564     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1565                                     /* UseInputModulePath */ false)) {
1566       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1567         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1568                << '\n';
1569       });
1570     }
1571   }
1572   Conf.CPU = TOpts.CPU;
1573   Conf.CodeModel = getCodeModel(CGOpts);
1574   Conf.MAttrs = TOpts.Features;
1575   Conf.RelocModel = CGOpts.RelocationModel;
1576   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1577   Conf.OptLevel = CGOpts.OptimizationLevel;
1578   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1579   Conf.SampleProfile = std::move(SampleProfile);
1580   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1581   // For historical reasons, loop interleaving is set to mirror setting for loop
1582   // unrolling.
1583   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1584   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1585   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1586   // Only enable CGProfilePass when using integrated assembler, since
1587   // non-integrated assemblers don't recognize .cgprofile section.
1588   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1589 
1590   // Context sensitive profile.
1591   if (CGOpts.hasProfileCSIRInstr()) {
1592     Conf.RunCSIRInstr = true;
1593     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1594   } else if (CGOpts.hasProfileCSIRUse()) {
1595     Conf.RunCSIRInstr = false;
1596     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1597   }
1598 
1599   Conf.ProfileRemapping = std::move(ProfileRemapping);
1600   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1601   Conf.DebugPassManager = CGOpts.DebugPassManager;
1602   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1603   Conf.RemarksFilename = CGOpts.OptRecordFile;
1604   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1605   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1606   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1607   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1608   switch (Action) {
1609   case Backend_EmitNothing:
1610     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1611       return false;
1612     };
1613     break;
1614   case Backend_EmitLL:
1615     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1616       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1617       return false;
1618     };
1619     break;
1620   case Backend_EmitBC:
1621     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1622       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1623       return false;
1624     };
1625     break;
1626   default:
1627     Conf.CGFileType = getCodeGenFileType(Action);
1628     break;
1629   }
1630   if (Error E =
1631           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1632                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1633                       ModuleMap, CGOpts.CmdArgs)) {
1634     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1635       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1636     });
1637   }
1638 }
1639 
1640 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1641                               const HeaderSearchOptions &HeaderOpts,
1642                               const CodeGenOptions &CGOpts,
1643                               const clang::TargetOptions &TOpts,
1644                               const LangOptions &LOpts,
1645                               const llvm::DataLayout &TDesc, Module *M,
1646                               BackendAction Action,
1647                               std::unique_ptr<raw_pwrite_stream> OS) {
1648 
1649   llvm::TimeTraceScope TimeScope("Backend");
1650 
1651   std::unique_ptr<llvm::Module> EmptyModule;
1652   if (!CGOpts.ThinLTOIndexFile.empty()) {
1653     // If we are performing a ThinLTO importing compile, load the function index
1654     // into memory and pass it into runThinLTOBackend, which will run the
1655     // function importer and invoke LTO passes.
1656     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1657         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1658                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1659     if (!IndexOrErr) {
1660       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1661                             "Error loading index file '" +
1662                             CGOpts.ThinLTOIndexFile + "': ");
1663       return;
1664     }
1665     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1666     // A null CombinedIndex means we should skip ThinLTO compilation
1667     // (LLVM will optionally ignore empty index files, returning null instead
1668     // of an error).
1669     if (CombinedIndex) {
1670       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1671         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1672                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1673                           CGOpts.ProfileRemappingFile, Action);
1674         return;
1675       }
1676       // Distributed indexing detected that nothing from the module is needed
1677       // for the final linking. So we can skip the compilation. We sill need to
1678       // output an empty object file to make sure that a linker does not fail
1679       // trying to read it. Also for some features, like CFI, we must skip
1680       // the compilation as CombinedIndex does not contain all required
1681       // information.
1682       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1683       EmptyModule->setTargetTriple(M->getTargetTriple());
1684       M = EmptyModule.get();
1685     }
1686   }
1687 
1688   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1689 
1690   if (CGOpts.ExperimentalNewPassManager)
1691     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1692   else
1693     AsmHelper.EmitAssembly(Action, std::move(OS));
1694 
1695   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1696   // DataLayout.
1697   if (AsmHelper.TM) {
1698     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1699     if (DLDesc != TDesc.getStringRepresentation()) {
1700       unsigned DiagID = Diags.getCustomDiagID(
1701           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1702                                     "expected target description '%1'");
1703       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1704     }
1705   }
1706 }
1707 
1708 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1709 // __LLVM,__bitcode section.
1710 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1711                          llvm::MemoryBufferRef Buf) {
1712   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1713     return;
1714   llvm::EmbedBitcodeInModule(
1715       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1716       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1717       CGOpts.CmdArgs);
1718 }
1719