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