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