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