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