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