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