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