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