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