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/Support/BuryPointer.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/PrettyStackTrace.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TimeProfiler.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Transforms/Coroutines.h"
51 #include "llvm/Transforms/IPO.h"
52 #include "llvm/Transforms/IPO/AlwaysInliner.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
55 #include "llvm/Transforms/InstCombine/InstCombine.h"
56 #include "llvm/Transforms/Instrumentation.h"
57 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
58 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
59 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
60 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
61 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
62 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
63 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
64 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
65 #include "llvm/Transforms/ObjCARC.h"
66 #include "llvm/Transforms/Scalar.h"
67 #include "llvm/Transforms/Scalar/GVN.h"
68 #include "llvm/Transforms/Utils.h"
69 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
70 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
71 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
72 #include "llvm/Transforms/Utils/SymbolRewriter.h"
73 #include <memory>
74 using namespace clang;
75 using namespace llvm;
76 
77 namespace {
78 
79 // Default filename used for profile generation.
80 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
81 
82 class EmitAssemblyHelper {
83   DiagnosticsEngine &Diags;
84   const HeaderSearchOptions &HSOpts;
85   const CodeGenOptions &CodeGenOpts;
86   const clang::TargetOptions &TargetOpts;
87   const LangOptions &LangOpts;
88   Module *TheModule;
89 
90   Timer CodeGenerationTime;
91 
92   std::unique_ptr<raw_pwrite_stream> OS;
93 
94   TargetIRAnalysis getTargetIRAnalysis() const {
95     if (TM)
96       return TM->getTargetIRAnalysis();
97 
98     return TargetIRAnalysis();
99   }
100 
101   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
102 
103   /// Generates the TargetMachine.
104   /// Leaves TM unchanged if it is unable to create the target machine.
105   /// Some of our clang tests specify triples which are not built
106   /// into clang. This is okay because these tests check the generated
107   /// IR, and they require DataLayout which depends on the triple.
108   /// In this case, we allow this method to fail and not report an error.
109   /// When MustCreateTM is used, we print an error if we are unable to load
110   /// the requested target.
111   void CreateTargetMachine(bool MustCreateTM);
112 
113   /// Add passes necessary to emit assembly or LLVM IR.
114   ///
115   /// \return True on success.
116   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
117                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
118 
119   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
120     std::error_code EC;
121     auto F = llvm::make_unique<llvm::ToolOutputFile>(Path, EC,
122                                                      llvm::sys::fs::F_None);
123     if (EC) {
124       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
125       F.reset();
126     }
127     return F;
128   }
129 
130 public:
131   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
132                      const HeaderSearchOptions &HeaderSearchOpts,
133                      const CodeGenOptions &CGOpts,
134                      const clang::TargetOptions &TOpts,
135                      const LangOptions &LOpts, Module *M)
136       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
137         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
138         CodeGenerationTime("codegen", "Code Generation Time") {}
139 
140   ~EmitAssemblyHelper() {
141     if (CodeGenOpts.DisableFree)
142       BuryPointer(std::move(TM));
143   }
144 
145   std::unique_ptr<TargetMachine> TM;
146 
147   void EmitAssembly(BackendAction Action,
148                     std::unique_ptr<raw_pwrite_stream> OS);
149 
150   void EmitAssemblyWithNewPassManager(BackendAction Action,
151                                       std::unique_ptr<raw_pwrite_stream> OS);
152 };
153 
154 // We need this wrapper to access LangOpts and CGOpts from extension functions
155 // that we add to the PassManagerBuilder.
156 class PassManagerBuilderWrapper : public PassManagerBuilder {
157 public:
158   PassManagerBuilderWrapper(const Triple &TargetTriple,
159                             const CodeGenOptions &CGOpts,
160                             const LangOptions &LangOpts)
161       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
162         LangOpts(LangOpts) {}
163   const Triple &getTargetTriple() const { return TargetTriple; }
164   const CodeGenOptions &getCGOpts() const { return CGOpts; }
165   const LangOptions &getLangOpts() const { return LangOpts; }
166 
167 private:
168   const Triple &TargetTriple;
169   const CodeGenOptions &CGOpts;
170   const LangOptions &LangOpts;
171 };
172 }
173 
174 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
175   if (Builder.OptLevel > 0)
176     PM.add(createObjCARCAPElimPass());
177 }
178 
179 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
180   if (Builder.OptLevel > 0)
181     PM.add(createObjCARCExpandPass());
182 }
183 
184 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
185   if (Builder.OptLevel > 0)
186     PM.add(createObjCARCOptPass());
187 }
188 
189 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
190                                      legacy::PassManagerBase &PM) {
191   PM.add(createAddDiscriminatorsPass());
192 }
193 
194 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
195                                   legacy::PassManagerBase &PM) {
196   PM.add(createBoundsCheckingLegacyPass());
197 }
198 
199 static SanitizerCoverageOptions
200 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
201   SanitizerCoverageOptions Opts;
202   Opts.CoverageType =
203       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
204   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
205   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
206   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
207   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
208   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
209   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
210   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
211   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
212   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
213   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
214   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
215   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
216   return Opts;
217 }
218 
219 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
220                                      legacy::PassManagerBase &PM) {
221   const PassManagerBuilderWrapper &BuilderWrapper =
222       static_cast<const PassManagerBuilderWrapper &>(Builder);
223   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
224   auto Opts = getSancovOptsFromCGOpts(CGOpts);
225   PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts));
226   PM.add(createSanitizerCoverageLegacyPassPass(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 
472   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
473   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
474   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
475   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
476   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
477   Options.FunctionSections = CodeGenOpts.FunctionSections;
478   Options.DataSections = CodeGenOpts.DataSections;
479   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
480   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
481   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
482   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
483   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
484   Options.EmitAddrsig = CodeGenOpts.Addrsig;
485   Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
486 
487   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
488   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
489   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
490   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
491   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
492   Options.MCOptions.MCIncrementalLinkerCompatible =
493       CodeGenOpts.IncrementalLinkerCompatible;
494   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
495   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
496   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
497   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
498   Options.MCOptions.ABIName = TargetOpts.ABI;
499   for (const auto &Entry : HSOpts.UserEntries)
500     if (!Entry.IsFramework &&
501         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
502          Entry.Group == frontend::IncludeDirGroup::Angled ||
503          Entry.Group == frontend::IncludeDirGroup::System))
504       Options.MCOptions.IASSearchPaths.push_back(
505           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
506 }
507 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
508   if (CodeGenOpts.DisableGCov)
509     return None;
510   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
511     return None;
512   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
513   // LLVM's -default-gcov-version flag is set to something invalid.
514   GCOVOptions Options;
515   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
516   Options.EmitData = CodeGenOpts.EmitGcovArcs;
517   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
518   Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
519   Options.NoRedZone = CodeGenOpts.DisableRedZone;
520   Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
521   Options.Filter = CodeGenOpts.ProfileFilterFiles;
522   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
523   Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
524   return Options;
525 }
526 
527 static Optional<InstrProfOptions>
528 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
529                     const LangOptions &LangOpts) {
530   if (!CodeGenOpts.hasProfileClangInstr())
531     return None;
532   InstrProfOptions Options;
533   Options.NoRedZone = CodeGenOpts.DisableRedZone;
534   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
535 
536   // TODO: Surface the option to emit atomic profile counter increments at
537   // the driver level.
538   Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
539   return Options;
540 }
541 
542 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
543                                       legacy::FunctionPassManager &FPM) {
544   // Handle disabling of all LLVM passes, where we want to preserve the
545   // internal module before any optimization.
546   if (CodeGenOpts.DisableLLVMPasses)
547     return;
548 
549   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
550   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
551   // are inserted before PMBuilder ones - they'd get the default-constructed
552   // TLI with an unknown target otherwise.
553   Triple TargetTriple(TheModule->getTargetTriple());
554   std::unique_ptr<TargetLibraryInfoImpl> TLII(
555       createTLII(TargetTriple, CodeGenOpts));
556 
557   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
558 
559   // At O0 and O1 we only run the always inliner which is more efficient. At
560   // higher optimization levels we run the normal inliner.
561   if (CodeGenOpts.OptimizationLevel <= 1) {
562     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
563                                      !CodeGenOpts.DisableLifetimeMarkers);
564     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
565   } else {
566     // We do not want to inline hot callsites for SamplePGO module-summary build
567     // because profile annotation will happen again in ThinLTO backend, and we
568     // want the IR of the hot path to match the profile.
569     PMBuilder.Inliner = createFunctionInliningPass(
570         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
571         (!CodeGenOpts.SampleProfileFile.empty() &&
572          CodeGenOpts.PrepareForThinLTO));
573   }
574 
575   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
576   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
577   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
578   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
579 
580   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
581   // Loop interleaving in the loop vectorizer has historically been set to be
582   // enabled when loop unrolling is enabled.
583   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
584   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
585   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
586   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
587   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
588 
589   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
590 
591   if (TM)
592     TM->adjustPassManager(PMBuilder);
593 
594   if (CodeGenOpts.DebugInfoForProfiling ||
595       !CodeGenOpts.SampleProfileFile.empty())
596     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
597                            addAddDiscriminatorsPass);
598 
599   // In ObjC ARC mode, add the main ARC optimization passes.
600   if (LangOpts.ObjCAutoRefCount) {
601     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
602                            addObjCARCExpandPass);
603     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
604                            addObjCARCAPElimPass);
605     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
606                            addObjCARCOptPass);
607   }
608 
609   if (LangOpts.Coroutines)
610     addCoroutinePassesToExtensionPoints(PMBuilder);
611 
612   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
613     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
614                            addBoundsCheckingPass);
615     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
616                            addBoundsCheckingPass);
617   }
618 
619   if (CodeGenOpts.SanitizeCoverageType ||
620       CodeGenOpts.SanitizeCoverageIndirectCalls ||
621       CodeGenOpts.SanitizeCoverageTraceCmp) {
622     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
623                            addSanitizerCoveragePass);
624     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
625                            addSanitizerCoveragePass);
626   }
627 
628   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
629     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
630                            addAddressSanitizerPasses);
631     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
632                            addAddressSanitizerPasses);
633   }
634 
635   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
636     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
637                            addKernelAddressSanitizerPasses);
638     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
639                            addKernelAddressSanitizerPasses);
640   }
641 
642   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
643     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
644                            addHWAddressSanitizerPasses);
645     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
646                            addHWAddressSanitizerPasses);
647   }
648 
649   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
650     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
651                            addKernelHWAddressSanitizerPasses);
652     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
653                            addKernelHWAddressSanitizerPasses);
654   }
655 
656   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
657     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
658                            addMemorySanitizerPass);
659     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
660                            addMemorySanitizerPass);
661   }
662 
663   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
664     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
665                            addKernelMemorySanitizerPass);
666     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
667                            addKernelMemorySanitizerPass);
668   }
669 
670   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
671     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
672                            addThreadSanitizerPass);
673     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
674                            addThreadSanitizerPass);
675   }
676 
677   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
678     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
679                            addDataFlowSanitizerPass);
680     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
681                            addDataFlowSanitizerPass);
682   }
683 
684   // Set up the per-function pass manager.
685   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
686   if (CodeGenOpts.VerifyModule)
687     FPM.add(createVerifierPass());
688 
689   // Set up the per-module pass manager.
690   if (!CodeGenOpts.RewriteMapFiles.empty())
691     addSymbolRewriterPass(CodeGenOpts, &MPM);
692 
693   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
694     MPM.add(createGCOVProfilerPass(*Options));
695     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
696       MPM.add(createStripSymbolsPass(true));
697   }
698 
699   if (Optional<InstrProfOptions> Options =
700           getInstrProfOptions(CodeGenOpts, LangOpts))
701     MPM.add(createInstrProfilingLegacyPass(*Options, false));
702 
703   bool hasIRInstr = false;
704   if (CodeGenOpts.hasProfileIRInstr()) {
705     PMBuilder.EnablePGOInstrGen = true;
706     hasIRInstr = true;
707   }
708   if (CodeGenOpts.hasProfileCSIRInstr()) {
709     assert(!CodeGenOpts.hasProfileCSIRUse() &&
710            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
711            "same time");
712     assert(!hasIRInstr &&
713            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
714            "same time");
715     PMBuilder.EnablePGOCSInstrGen = true;
716     hasIRInstr = true;
717   }
718   if (hasIRInstr) {
719     if (!CodeGenOpts.InstrProfileOutput.empty())
720       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
721     else
722       PMBuilder.PGOInstrGen = DefaultProfileGenName;
723   }
724   if (CodeGenOpts.hasProfileIRUse()) {
725     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
726     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
727   }
728 
729   if (!CodeGenOpts.SampleProfileFile.empty())
730     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
731 
732   PMBuilder.populateFunctionPassManager(FPM);
733   PMBuilder.populateModulePassManager(MPM);
734 }
735 
736 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
737   SmallVector<const char *, 16> BackendArgs;
738   BackendArgs.push_back("clang"); // Fake program name.
739   if (!CodeGenOpts.DebugPass.empty()) {
740     BackendArgs.push_back("-debug-pass");
741     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
742   }
743   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
744     BackendArgs.push_back("-limit-float-precision");
745     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
746   }
747   BackendArgs.push_back(nullptr);
748   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
749                                     BackendArgs.data());
750 }
751 
752 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
753   // Create the TargetMachine for generating code.
754   std::string Error;
755   std::string Triple = TheModule->getTargetTriple();
756   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
757   if (!TheTarget) {
758     if (MustCreateTM)
759       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
760     return;
761   }
762 
763   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
764   std::string FeaturesStr =
765       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
766   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
767   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
768 
769   llvm::TargetOptions Options;
770   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
771   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
772                                           Options, RM, CM, OptLevel));
773 }
774 
775 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
776                                        BackendAction Action,
777                                        raw_pwrite_stream &OS,
778                                        raw_pwrite_stream *DwoOS) {
779   // Add LibraryInfo.
780   llvm::Triple TargetTriple(TheModule->getTargetTriple());
781   std::unique_ptr<TargetLibraryInfoImpl> TLII(
782       createTLII(TargetTriple, CodeGenOpts));
783   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
784 
785   // Normal mode, emit a .s or .o file by running the code generator. Note,
786   // this also adds codegenerator level optimization passes.
787   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
788 
789   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
790   // "codegen" passes so that it isn't run multiple times when there is
791   // inlining happening.
792   if (CodeGenOpts.OptimizationLevel > 0)
793     CodeGenPasses.add(createObjCARCContractPass());
794 
795   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
796                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
797     Diags.Report(diag::err_fe_unable_to_interface_with_target);
798     return false;
799   }
800 
801   return true;
802 }
803 
804 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
805                                       std::unique_ptr<raw_pwrite_stream> OS) {
806   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
807 
808   setCommandLineOpts(CodeGenOpts);
809 
810   bool UsesCodeGen = (Action != Backend_EmitNothing &&
811                       Action != Backend_EmitBC &&
812                       Action != Backend_EmitLL);
813   CreateTargetMachine(UsesCodeGen);
814 
815   if (UsesCodeGen && !TM)
816     return;
817   if (TM)
818     TheModule->setDataLayout(TM->createDataLayout());
819 
820   legacy::PassManager PerModulePasses;
821   PerModulePasses.add(
822       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
823 
824   legacy::FunctionPassManager PerFunctionPasses(TheModule);
825   PerFunctionPasses.add(
826       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
827 
828   CreatePasses(PerModulePasses, PerFunctionPasses);
829 
830   legacy::PassManager CodeGenPasses;
831   CodeGenPasses.add(
832       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
833 
834   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
835 
836   switch (Action) {
837   case Backend_EmitNothing:
838     break;
839 
840   case Backend_EmitBC:
841     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
842       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
843         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
844         if (!ThinLinkOS)
845           return;
846       }
847       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
848                                CodeGenOpts.EnableSplitLTOUnit);
849       PerModulePasses.add(createWriteThinLTOBitcodePass(
850           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
851     } else {
852       // Emit a module summary by default for Regular LTO except for ld64
853       // targets
854       bool EmitLTOSummary =
855           (CodeGenOpts.PrepareForLTO &&
856            !CodeGenOpts.DisableLLVMPasses &&
857            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
858                llvm::Triple::Apple);
859       if (EmitLTOSummary) {
860         if (!TheModule->getModuleFlag("ThinLTO"))
861           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
862         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
863                                  uint32_t(1));
864       }
865 
866       PerModulePasses.add(createBitcodeWriterPass(
867           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
868     }
869     break;
870 
871   case Backend_EmitLL:
872     PerModulePasses.add(
873         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
874     break;
875 
876   default:
877     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
878       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
879       if (!DwoOS)
880         return;
881     }
882     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
883                        DwoOS ? &DwoOS->os() : nullptr))
884       return;
885   }
886 
887   // Before executing passes, print the final values of the LLVM options.
888   cl::PrintOptionValues();
889 
890   // Run passes. For now we do all passes at once, but eventually we
891   // would like to have the option of streaming code generation.
892 
893   {
894     PrettyStackTraceString CrashInfo("Per-function optimization");
895 
896     PerFunctionPasses.doInitialization();
897     for (Function &F : *TheModule)
898       if (!F.isDeclaration())
899         PerFunctionPasses.run(F);
900     PerFunctionPasses.doFinalization();
901   }
902 
903   {
904     PrettyStackTraceString CrashInfo("Per-module optimization passes");
905     PerModulePasses.run(*TheModule);
906   }
907 
908   {
909     PrettyStackTraceString CrashInfo("Code generation");
910     CodeGenPasses.run(*TheModule);
911   }
912 
913   if (ThinLinkOS)
914     ThinLinkOS->keep();
915   if (DwoOS)
916     DwoOS->keep();
917 }
918 
919 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
920   switch (Opts.OptimizationLevel) {
921   default:
922     llvm_unreachable("Invalid optimization level!");
923 
924   case 1:
925     return PassBuilder::O1;
926 
927   case 2:
928     switch (Opts.OptimizeSize) {
929     default:
930       llvm_unreachable("Invalid optimization level for size!");
931 
932     case 0:
933       return PassBuilder::O2;
934 
935     case 1:
936       return PassBuilder::Os;
937 
938     case 2:
939       return PassBuilder::Oz;
940     }
941 
942   case 3:
943     return PassBuilder::O3;
944   }
945 }
946 
947 static void addSanitizersAtO0(ModulePassManager &MPM,
948                               const Triple &TargetTriple,
949                               const LangOptions &LangOpts,
950                               const CodeGenOptions &CodeGenOpts) {
951   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
952     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
953     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
954     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
955         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
956     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
957     MPM.addPass(
958         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
959                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
960   };
961 
962   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
963     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
964   }
965 
966   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
967     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
968   }
969 
970   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
971     MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
972   }
973 
974   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
975     MPM.addPass(createModuleToFunctionPassAdaptor(
976         MemorySanitizerPass({0, false, /*Kernel=*/true})));
977   }
978 
979   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
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   PassBuilder PB(TM.get(), PTO, PGOOpt);
1066 
1067   // Attempt to load pass plugins and register their callbacks with PB.
1068   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1069     auto PassPlugin = PassPlugin::Load(PluginFN);
1070     if (PassPlugin) {
1071       PassPlugin->registerPassBuilderCallbacks(PB);
1072     } else {
1073       Diags.Report(diag::err_fe_unable_to_load_plugin)
1074           << PluginFN << toString(PassPlugin.takeError());
1075     }
1076   }
1077 
1078   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1079   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1080   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1081   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1082 
1083   // Register the AA manager first so that our version is the one used.
1084   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1085 
1086   // Register the target library analysis directly and give it a customized
1087   // preset TLI.
1088   Triple TargetTriple(TheModule->getTargetTriple());
1089   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1090       createTLII(TargetTriple, CodeGenOpts));
1091   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1092   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1093 
1094   // Register all the basic analyses with the managers.
1095   PB.registerModuleAnalyses(MAM);
1096   PB.registerCGSCCAnalyses(CGAM);
1097   PB.registerFunctionAnalyses(FAM);
1098   PB.registerLoopAnalyses(LAM);
1099   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1100 
1101   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1102 
1103   if (!CodeGenOpts.DisableLLVMPasses) {
1104     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1105     bool IsLTO = CodeGenOpts.PrepareForLTO;
1106 
1107     if (CodeGenOpts.OptimizationLevel == 0) {
1108       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1109         MPM.addPass(GCOVProfilerPass(*Options));
1110       if (Optional<InstrProfOptions> Options =
1111               getInstrProfOptions(CodeGenOpts, LangOpts))
1112         MPM.addPass(InstrProfiling(*Options, false));
1113 
1114       // Build a minimal pipeline based on the semantics required by Clang,
1115       // which is just that always inlining occurs. Further, disable generating
1116       // lifetime intrinsics to avoid enabling further optimizations during
1117       // code generation.
1118       MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
1119 
1120       // At -O0 we directly run necessary sanitizer passes.
1121       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1122         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1123 
1124       // Lastly, add semantically necessary passes for LTO.
1125       if (IsLTO || IsThinLTO) {
1126         MPM.addPass(CanonicalizeAliasesPass());
1127         MPM.addPass(NameAnonGlobalPass());
1128       }
1129     } else {
1130       // Map our optimization levels into one of the distinct levels used to
1131       // configure the pipeline.
1132       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1133 
1134       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1135         MPM.addPass(createModuleToFunctionPassAdaptor(
1136             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1137       });
1138 
1139       if (CodeGenOpts.SanitizeCoverageType ||
1140           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1141           CodeGenOpts.SanitizeCoverageTraceCmp) {
1142         auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1143         PB.registerPipelineStartEPCallback(
1144             [SancovOpts](ModulePassManager &MPM) {
1145               MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1146             });
1147         PB.registerOptimizerLastEPCallback(
1148             [SancovOpts](FunctionPassManager &FPM,
1149                          PassBuilder::OptimizationLevel Level) {
1150               FPM.addPass(SanitizerCoveragePass(SancovOpts));
1151             });
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 (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1222       bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1223       MPM.addPass(HWAddressSanitizerPass(
1224           /*CompileKernel=*/false, Recover));
1225     }
1226     if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1227       MPM.addPass(HWAddressSanitizerPass(
1228           /*CompileKernel=*/true, /*Recover=*/true));
1229     }
1230 
1231     if (CodeGenOpts.OptimizationLevel == 0) {
1232       if (CodeGenOpts.SanitizeCoverageType ||
1233           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1234           CodeGenOpts.SanitizeCoverageTraceCmp) {
1235         auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1236         MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1237         MPM.addPass(createModuleToFunctionPassAdaptor(
1238             SanitizerCoveragePass(SancovOpts)));
1239       }
1240 
1241       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1242     }
1243   }
1244 
1245   // FIXME: We still use the legacy pass manager to do code generation. We
1246   // create that pass manager here and use it as needed below.
1247   legacy::PassManager CodeGenPasses;
1248   bool NeedCodeGen = false;
1249   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1250 
1251   // Append any output we need to the pass manager.
1252   switch (Action) {
1253   case Backend_EmitNothing:
1254     break;
1255 
1256   case Backend_EmitBC:
1257     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1258       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1259         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1260         if (!ThinLinkOS)
1261           return;
1262       }
1263       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1264                                CodeGenOpts.EnableSplitLTOUnit);
1265       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1266                                                            : nullptr));
1267     } else {
1268       // Emit a module summary by default for Regular LTO except for ld64
1269       // targets
1270       bool EmitLTOSummary =
1271           (CodeGenOpts.PrepareForLTO &&
1272            !CodeGenOpts.DisableLLVMPasses &&
1273            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1274                llvm::Triple::Apple);
1275       if (EmitLTOSummary) {
1276         if (!TheModule->getModuleFlag("ThinLTO"))
1277           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1278         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1279                                  CodeGenOpts.EnableSplitLTOUnit);
1280       }
1281       MPM.addPass(
1282           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1283     }
1284     break;
1285 
1286   case Backend_EmitLL:
1287     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1288     break;
1289 
1290   case Backend_EmitAssembly:
1291   case Backend_EmitMCNull:
1292   case Backend_EmitObj:
1293     NeedCodeGen = true;
1294     CodeGenPasses.add(
1295         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1296     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1297       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1298       if (!DwoOS)
1299         return;
1300     }
1301     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1302                        DwoOS ? &DwoOS->os() : nullptr))
1303       // FIXME: Should we handle this error differently?
1304       return;
1305     break;
1306   }
1307 
1308   // Before executing passes, print the final values of the LLVM options.
1309   cl::PrintOptionValues();
1310 
1311   // Now that we have all of the passes ready, run them.
1312   {
1313     PrettyStackTraceString CrashInfo("Optimizer");
1314     MPM.run(*TheModule, MAM);
1315   }
1316 
1317   // Now if needed, run the legacy PM for codegen.
1318   if (NeedCodeGen) {
1319     PrettyStackTraceString CrashInfo("Code generation");
1320     CodeGenPasses.run(*TheModule);
1321   }
1322 
1323   if (ThinLinkOS)
1324     ThinLinkOS->keep();
1325   if (DwoOS)
1326     DwoOS->keep();
1327 }
1328 
1329 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1330   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1331   if (!BMsOrErr)
1332     return BMsOrErr.takeError();
1333 
1334   // The bitcode file may contain multiple modules, we want the one that is
1335   // marked as being the ThinLTO module.
1336   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1337     return *Bm;
1338 
1339   return make_error<StringError>("Could not find module summary",
1340                                  inconvertibleErrorCode());
1341 }
1342 
1343 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1344   for (BitcodeModule &BM : BMs) {
1345     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1346     if (LTOInfo && LTOInfo->IsThinLTO)
1347       return &BM;
1348   }
1349   return nullptr;
1350 }
1351 
1352 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1353                               const HeaderSearchOptions &HeaderOpts,
1354                               const CodeGenOptions &CGOpts,
1355                               const clang::TargetOptions &TOpts,
1356                               const LangOptions &LOpts,
1357                               std::unique_ptr<raw_pwrite_stream> OS,
1358                               std::string SampleProfile,
1359                               std::string ProfileRemapping,
1360                               BackendAction Action) {
1361   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1362       ModuleToDefinedGVSummaries;
1363   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1364 
1365   setCommandLineOpts(CGOpts);
1366 
1367   // We can simply import the values mentioned in the combined index, since
1368   // we should only invoke this using the individual indexes written out
1369   // via a WriteIndexesThinBackend.
1370   FunctionImporter::ImportMapTy ImportList;
1371   for (auto &GlobalList : *CombinedIndex) {
1372     // Ignore entries for undefined references.
1373     if (GlobalList.second.SummaryList.empty())
1374       continue;
1375 
1376     auto GUID = GlobalList.first;
1377     for (auto &Summary : GlobalList.second.SummaryList) {
1378       // Skip the summaries for the importing module. These are included to
1379       // e.g. record required linkage changes.
1380       if (Summary->modulePath() == M->getModuleIdentifier())
1381         continue;
1382       // Add an entry to provoke importing by thinBackend.
1383       ImportList[Summary->modulePath()].insert(GUID);
1384     }
1385   }
1386 
1387   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1388   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1389 
1390   for (auto &I : ImportList) {
1391     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1392         llvm::MemoryBuffer::getFile(I.first());
1393     if (!MBOrErr) {
1394       errs() << "Error loading imported file '" << I.first()
1395              << "': " << MBOrErr.getError().message() << "\n";
1396       return;
1397     }
1398 
1399     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1400     if (!BMOrErr) {
1401       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1402         errs() << "Error loading imported file '" << I.first()
1403                << "': " << EIB.message() << '\n';
1404       });
1405       return;
1406     }
1407     ModuleMap.insert({I.first(), *BMOrErr});
1408 
1409     OwnedImports.push_back(std::move(*MBOrErr));
1410   }
1411   auto AddStream = [&](size_t Task) {
1412     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1413   };
1414   lto::Config Conf;
1415   if (CGOpts.SaveTempsFilePrefix != "") {
1416     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1417                                     /* UseInputModulePath */ false)) {
1418       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1419         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1420                << '\n';
1421       });
1422     }
1423   }
1424   Conf.CPU = TOpts.CPU;
1425   Conf.CodeModel = getCodeModel(CGOpts);
1426   Conf.MAttrs = TOpts.Features;
1427   Conf.RelocModel = CGOpts.RelocationModel;
1428   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1429   Conf.OptLevel = CGOpts.OptimizationLevel;
1430   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1431   Conf.SampleProfile = std::move(SampleProfile);
1432 
1433   // Context sensitive profile.
1434   if (CGOpts.hasProfileCSIRInstr()) {
1435     Conf.RunCSIRInstr = true;
1436     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1437   } else if (CGOpts.hasProfileCSIRUse()) {
1438     Conf.RunCSIRInstr = false;
1439     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1440   }
1441 
1442   Conf.ProfileRemapping = std::move(ProfileRemapping);
1443   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1444   Conf.DebugPassManager = CGOpts.DebugPassManager;
1445   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1446   Conf.RemarksFilename = CGOpts.OptRecordFile;
1447   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1448   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1449   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1450   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1451   switch (Action) {
1452   case Backend_EmitNothing:
1453     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1454       return false;
1455     };
1456     break;
1457   case Backend_EmitLL:
1458     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1459       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1460       return false;
1461     };
1462     break;
1463   case Backend_EmitBC:
1464     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1465       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1466       return false;
1467     };
1468     break;
1469   default:
1470     Conf.CGFileType = getCodeGenFileType(Action);
1471     break;
1472   }
1473   if (Error E = thinBackend(
1474           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1475           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1476     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1477       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1478     });
1479   }
1480 }
1481 
1482 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1483                               const HeaderSearchOptions &HeaderOpts,
1484                               const CodeGenOptions &CGOpts,
1485                               const clang::TargetOptions &TOpts,
1486                               const LangOptions &LOpts,
1487                               const llvm::DataLayout &TDesc, Module *M,
1488                               BackendAction Action,
1489                               std::unique_ptr<raw_pwrite_stream> OS) {
1490 
1491   llvm::TimeTraceScope TimeScope("Backend", StringRef(""));
1492 
1493   std::unique_ptr<llvm::Module> EmptyModule;
1494   if (!CGOpts.ThinLTOIndexFile.empty()) {
1495     // If we are performing a ThinLTO importing compile, load the function index
1496     // into memory and pass it into runThinLTOBackend, which will run the
1497     // function importer and invoke LTO passes.
1498     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1499         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1500                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1501     if (!IndexOrErr) {
1502       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1503                             "Error loading index file '" +
1504                             CGOpts.ThinLTOIndexFile + "': ");
1505       return;
1506     }
1507     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1508     // A null CombinedIndex means we should skip ThinLTO compilation
1509     // (LLVM will optionally ignore empty index files, returning null instead
1510     // of an error).
1511     if (CombinedIndex) {
1512       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1513         runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1514                           LOpts, std::move(OS), CGOpts.SampleProfileFile,
1515                           CGOpts.ProfileRemappingFile, Action);
1516         return;
1517       }
1518       // Distributed indexing detected that nothing from the module is needed
1519       // for the final linking. So we can skip the compilation. We sill need to
1520       // output an empty object file to make sure that a linker does not fail
1521       // trying to read it. Also for some features, like CFI, we must skip
1522       // the compilation as CombinedIndex does not contain all required
1523       // information.
1524       EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1525       EmptyModule->setTargetTriple(M->getTargetTriple());
1526       M = EmptyModule.get();
1527     }
1528   }
1529 
1530   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1531 
1532   if (CGOpts.ExperimentalNewPassManager)
1533     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1534   else
1535     AsmHelper.EmitAssembly(Action, std::move(OS));
1536 
1537   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1538   // DataLayout.
1539   if (AsmHelper.TM) {
1540     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1541     if (DLDesc != TDesc.getStringRepresentation()) {
1542       unsigned DiagID = Diags.getCustomDiagID(
1543           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1544                                     "expected target description '%1'");
1545       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1546     }
1547   }
1548 }
1549 
1550 static const char* getSectionNameForBitcode(const Triple &T) {
1551   switch (T.getObjectFormat()) {
1552   case Triple::MachO:
1553     return "__LLVM,__bitcode";
1554   case Triple::COFF:
1555   case Triple::ELF:
1556   case Triple::Wasm:
1557   case Triple::UnknownObjectFormat:
1558     return ".llvmbc";
1559   case Triple::XCOFF:
1560     llvm_unreachable("XCOFF is not yet implemented");
1561     break;
1562   }
1563   llvm_unreachable("Unimplemented ObjectFormatType");
1564 }
1565 
1566 static const char* getSectionNameForCommandline(const Triple &T) {
1567   switch (T.getObjectFormat()) {
1568   case Triple::MachO:
1569     return "__LLVM,__cmdline";
1570   case Triple::COFF:
1571   case Triple::ELF:
1572   case Triple::Wasm:
1573   case Triple::UnknownObjectFormat:
1574     return ".llvmcmd";
1575   case Triple::XCOFF:
1576     llvm_unreachable("XCOFF is not yet implemented");
1577     break;
1578   }
1579   llvm_unreachable("Unimplemented ObjectFormatType");
1580 }
1581 
1582 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1583 // __LLVM,__bitcode section.
1584 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1585                          llvm::MemoryBufferRef Buf) {
1586   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1587     return;
1588 
1589   // Save llvm.compiler.used and remote it.
1590   SmallVector<Constant*, 2> UsedArray;
1591   SmallPtrSet<GlobalValue*, 4> UsedGlobals;
1592   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1593   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1594   for (auto *GV : UsedGlobals) {
1595     if (GV->getName() != "llvm.embedded.module" &&
1596         GV->getName() != "llvm.cmdline")
1597       UsedArray.push_back(
1598           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1599   }
1600   if (Used)
1601     Used->eraseFromParent();
1602 
1603   // Embed the bitcode for the llvm module.
1604   std::string Data;
1605   ArrayRef<uint8_t> ModuleData;
1606   Triple T(M->getTargetTriple());
1607   // Create a constant that contains the bitcode.
1608   // In case of embedding a marker, ignore the input Buf and use the empty
1609   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1610   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1611     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1612                    (const unsigned char *)Buf.getBufferEnd())) {
1613       // If the input is LLVM Assembly, bitcode is produced by serializing
1614       // the module. Use-lists order need to be perserved in this case.
1615       llvm::raw_string_ostream OS(Data);
1616       llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1617       ModuleData =
1618           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1619     } else
1620       // If the input is LLVM bitcode, write the input byte stream directly.
1621       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1622                                      Buf.getBufferSize());
1623   }
1624   llvm::Constant *ModuleConstant =
1625       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1626   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1627       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1628       ModuleConstant);
1629   GV->setSection(getSectionNameForBitcode(T));
1630   UsedArray.push_back(
1631       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1632   if (llvm::GlobalVariable *Old =
1633           M->getGlobalVariable("llvm.embedded.module", true)) {
1634     assert(Old->hasOneUse() &&
1635            "llvm.embedded.module can only be used once in llvm.compiler.used");
1636     GV->takeName(Old);
1637     Old->eraseFromParent();
1638   } else {
1639     GV->setName("llvm.embedded.module");
1640   }
1641 
1642   // Skip if only bitcode needs to be embedded.
1643   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1644     // Embed command-line options.
1645     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1646                               CGOpts.CmdArgs.size());
1647     llvm::Constant *CmdConstant =
1648       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1649     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1650                                   llvm::GlobalValue::PrivateLinkage,
1651                                   CmdConstant);
1652     GV->setSection(getSectionNameForCommandline(T));
1653     UsedArray.push_back(
1654         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1655     if (llvm::GlobalVariable *Old =
1656             M->getGlobalVariable("llvm.cmdline", true)) {
1657       assert(Old->hasOneUse() &&
1658              "llvm.cmdline can only be used once in llvm.compiler.used");
1659       GV->takeName(Old);
1660       Old->eraseFromParent();
1661     } else {
1662       GV->setName("llvm.cmdline");
1663     }
1664   }
1665 
1666   if (UsedArray.empty())
1667     return;
1668 
1669   // Recreate llvm.compiler.used.
1670   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1671   auto *NewUsed = new GlobalVariable(
1672       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1673       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1674   NewUsed->setSection("llvm.metadata");
1675 }
1676