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