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