1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "clang/Lex/HeaderSearchOptions.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.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/Support/CommandLine.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/PrettyStackTrace.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
48 #include "llvm/Transforms/Coroutines.h"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/Transforms/IPO/AlwaysInliner.h"
51 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
52 #include "llvm/Transforms/Instrumentation.h"
53 #include "llvm/Transforms/ObjCARC.h"
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/Transforms/Scalar/GVN.h"
56 #include "llvm/Transforms/Utils/SymbolRewriter.h"
57 #include <memory>
58 using namespace clang;
59 using namespace llvm;
60 
61 namespace {
62 
63 // Default filename used for profile generation.
64 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
65 
66 class EmitAssemblyHelper {
67   DiagnosticsEngine &Diags;
68   const HeaderSearchOptions &HSOpts;
69   const CodeGenOptions &CodeGenOpts;
70   const clang::TargetOptions &TargetOpts;
71   const LangOptions &LangOpts;
72   Module *TheModule;
73 
74   Timer CodeGenerationTime;
75 
76   std::unique_ptr<raw_pwrite_stream> OS;
77 
78   TargetIRAnalysis getTargetIRAnalysis() const {
79     if (TM)
80       return TM->getTargetIRAnalysis();
81 
82     return TargetIRAnalysis();
83   }
84 
85   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
86 
87   /// Generates the TargetMachine.
88   /// Leaves TM unchanged if it is unable to create the target machine.
89   /// Some of our clang tests specify triples which are not built
90   /// into clang. This is okay because these tests check the generated
91   /// IR, and they require DataLayout which depends on the triple.
92   /// In this case, we allow this method to fail and not report an error.
93   /// When MustCreateTM is used, we print an error if we are unable to load
94   /// the requested target.
95   void CreateTargetMachine(bool MustCreateTM);
96 
97   /// Add passes necessary to emit assembly or LLVM IR.
98   ///
99   /// \return True on success.
100   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
101                      raw_pwrite_stream &OS);
102 
103 public:
104   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
105                      const HeaderSearchOptions &HeaderSearchOpts,
106                      const CodeGenOptions &CGOpts,
107                      const clang::TargetOptions &TOpts,
108                      const LangOptions &LOpts, Module *M)
109       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
110         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
111         CodeGenerationTime("codegen", "Code Generation Time") {}
112 
113   ~EmitAssemblyHelper() {
114     if (CodeGenOpts.DisableFree)
115       BuryPointer(std::move(TM));
116   }
117 
118   std::unique_ptr<TargetMachine> TM;
119 
120   void EmitAssembly(BackendAction Action,
121                     std::unique_ptr<raw_pwrite_stream> OS);
122 
123   void EmitAssemblyWithNewPassManager(BackendAction Action,
124                                       std::unique_ptr<raw_pwrite_stream> OS);
125 };
126 
127 // We need this wrapper to access LangOpts and CGOpts from extension functions
128 // that we add to the PassManagerBuilder.
129 class PassManagerBuilderWrapper : public PassManagerBuilder {
130 public:
131   PassManagerBuilderWrapper(const Triple &TargetTriple,
132                             const CodeGenOptions &CGOpts,
133                             const LangOptions &LangOpts)
134       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
135         LangOpts(LangOpts) {}
136   const Triple &getTargetTriple() const { return TargetTriple; }
137   const CodeGenOptions &getCGOpts() const { return CGOpts; }
138   const LangOptions &getLangOpts() const { return LangOpts; }
139 
140 private:
141   const Triple &TargetTriple;
142   const CodeGenOptions &CGOpts;
143   const LangOptions &LangOpts;
144 };
145 }
146 
147 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148   if (Builder.OptLevel > 0)
149     PM.add(createObjCARCAPElimPass());
150 }
151 
152 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153   if (Builder.OptLevel > 0)
154     PM.add(createObjCARCExpandPass());
155 }
156 
157 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
158   if (Builder.OptLevel > 0)
159     PM.add(createObjCARCOptPass());
160 }
161 
162 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
163                                      legacy::PassManagerBase &PM) {
164   PM.add(createAddDiscriminatorsPass());
165 }
166 
167 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
168                                   legacy::PassManagerBase &PM) {
169   PM.add(createBoundsCheckingPass());
170 }
171 
172 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
173                                      legacy::PassManagerBase &PM) {
174   const PassManagerBuilderWrapper &BuilderWrapper =
175       static_cast<const PassManagerBuilderWrapper&>(Builder);
176   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
177   SanitizerCoverageOptions Opts;
178   Opts.CoverageType =
179       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
180   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
181   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
182   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
183   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
184   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
185   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
186   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
187   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
188   PM.add(createSanitizerCoverageModulePass(Opts));
189 }
190 
191 // Check if ASan should use GC-friendly instrumentation for globals.
192 // First of all, there is no point if -fdata-sections is off (expect for MachO,
193 // where this is not a factor). Also, on ELF this feature requires an assembler
194 // extension that only works with -integrated-as at the moment.
195 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
196   switch (T.getObjectFormat()) {
197   case Triple::MachO:
198   case Triple::COFF:
199     return true;
200   case Triple::ELF:
201     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
202   default:
203     return false;
204   }
205 }
206 
207 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
208                                       legacy::PassManagerBase &PM) {
209   const PassManagerBuilderWrapper &BuilderWrapper =
210       static_cast<const PassManagerBuilderWrapper&>(Builder);
211   const Triple &T = BuilderWrapper.getTargetTriple();
212   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
213   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
214   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
215   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
216   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
217                                             UseAfterScope));
218   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
219                                           UseGlobalsGC));
220 }
221 
222 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
223                                             legacy::PassManagerBase &PM) {
224   PM.add(createAddressSanitizerFunctionPass(
225       /*CompileKernel*/ true,
226       /*Recover*/ true, /*UseAfterScope*/ false));
227   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
228                                           /*Recover*/true));
229 }
230 
231 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
232                                    legacy::PassManagerBase &PM) {
233   const PassManagerBuilderWrapper &BuilderWrapper =
234       static_cast<const PassManagerBuilderWrapper&>(Builder);
235   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
236   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
237   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
238   PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
239 
240   // MemorySanitizer inserts complex instrumentation that mostly follows
241   // the logic of the original code, but operates on "shadow" values.
242   // It can benefit from re-running some general purpose optimization passes.
243   if (Builder.OptLevel > 0) {
244     PM.add(createEarlyCSEPass());
245     PM.add(createReassociatePass());
246     PM.add(createLICMPass());
247     PM.add(createGVNPass());
248     PM.add(createInstructionCombiningPass());
249     PM.add(createDeadStoreEliminationPass());
250   }
251 }
252 
253 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
254                                    legacy::PassManagerBase &PM) {
255   PM.add(createThreadSanitizerPass());
256 }
257 
258 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
259                                      legacy::PassManagerBase &PM) {
260   const PassManagerBuilderWrapper &BuilderWrapper =
261       static_cast<const PassManagerBuilderWrapper&>(Builder);
262   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
263   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
264 }
265 
266 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
267                                        legacy::PassManagerBase &PM) {
268   const PassManagerBuilderWrapper &BuilderWrapper =
269       static_cast<const PassManagerBuilderWrapper&>(Builder);
270   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
271   EfficiencySanitizerOptions Opts;
272   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
273     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
274   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
275     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
276   PM.add(createEfficiencySanitizerPass(Opts));
277 }
278 
279 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
280                                          const CodeGenOptions &CodeGenOpts) {
281   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
282   if (!CodeGenOpts.SimplifyLibCalls)
283     TLII->disableAllFunctions();
284   else {
285     // Disable individual libc/libm calls in TargetLibraryInfo.
286     LibFunc F;
287     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
288       if (TLII->getLibFunc(FuncName, F))
289         TLII->setUnavailable(F);
290   }
291 
292   switch (CodeGenOpts.getVecLib()) {
293   case CodeGenOptions::Accelerate:
294     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
295     break;
296   case CodeGenOptions::SVML:
297     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
298     break;
299   default:
300     break;
301   }
302   return TLII;
303 }
304 
305 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
306                                   legacy::PassManager *MPM) {
307   llvm::SymbolRewriter::RewriteDescriptorList DL;
308 
309   llvm::SymbolRewriter::RewriteMapParser MapParser;
310   for (const auto &MapFile : Opts.RewriteMapFiles)
311     MapParser.parse(MapFile, &DL);
312 
313   MPM->add(createRewriteSymbolsPass(DL));
314 }
315 
316 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
317   switch (CodeGenOpts.OptimizationLevel) {
318   default:
319     llvm_unreachable("Invalid optimization level!");
320   case 0:
321     return CodeGenOpt::None;
322   case 1:
323     return CodeGenOpt::Less;
324   case 2:
325     return CodeGenOpt::Default; // O2/Os/Oz
326   case 3:
327     return CodeGenOpt::Aggressive;
328   }
329 }
330 
331 static llvm::CodeModel::Model getCodeModel(const CodeGenOptions &CodeGenOpts) {
332   unsigned CodeModel =
333       llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
334       .Case("small", llvm::CodeModel::Small)
335       .Case("kernel", llvm::CodeModel::Kernel)
336       .Case("medium", llvm::CodeModel::Medium)
337       .Case("large", llvm::CodeModel::Large)
338       .Case("default", llvm::CodeModel::Default)
339       .Default(~0u);
340   assert(CodeModel != ~0u && "invalid code model!");
341   return static_cast<llvm::CodeModel::Model>(CodeModel);
342 }
343 
344 static llvm::Reloc::Model getRelocModel(const CodeGenOptions &CodeGenOpts) {
345   // Keep this synced with the equivalent code in
346   // lib/Frontend/CompilerInvocation.cpp
347   llvm::Optional<llvm::Reloc::Model> RM;
348   RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
349       .Case("static", llvm::Reloc::Static)
350       .Case("pic", llvm::Reloc::PIC_)
351       .Case("ropi", llvm::Reloc::ROPI)
352       .Case("rwpi", llvm::Reloc::RWPI)
353       .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
354       .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
355   assert(RM.hasValue() && "invalid PIC model!");
356   return *RM;
357 }
358 
359 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
360   if (Action == Backend_EmitObj)
361     return TargetMachine::CGFT_ObjectFile;
362   else if (Action == Backend_EmitMCNull)
363     return TargetMachine::CGFT_Null;
364   else {
365     assert(Action == Backend_EmitAssembly && "Invalid action!");
366     return TargetMachine::CGFT_AssemblyFile;
367   }
368 }
369 
370 static void initTargetOptions(llvm::TargetOptions &Options,
371                               const CodeGenOptions &CodeGenOpts,
372                               const clang::TargetOptions &TargetOpts,
373                               const LangOptions &LangOpts,
374                               const HeaderSearchOptions &HSOpts) {
375   Options.ThreadModel =
376       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
377           .Case("posix", llvm::ThreadModel::POSIX)
378           .Case("single", llvm::ThreadModel::Single);
379 
380   // Set float ABI type.
381   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
382           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
383          "Invalid Floating Point ABI!");
384   Options.FloatABIType =
385       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
386           .Case("soft", llvm::FloatABI::Soft)
387           .Case("softfp", llvm::FloatABI::Soft)
388           .Case("hard", llvm::FloatABI::Hard)
389           .Default(llvm::FloatABI::Default);
390 
391   // Set FP fusion mode.
392   switch (LangOpts.getDefaultFPContractMode()) {
393   case LangOptions::FPC_Off:
394     // Preserve any contraction performed by the front-end.  (Strict performs
395     // splitting of the muladd instrinsic in the backend.)
396     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
397     break;
398   case LangOptions::FPC_On:
399     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
400     break;
401   case LangOptions::FPC_Fast:
402     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
403     break;
404   }
405 
406   Options.UseInitArray = CodeGenOpts.UseInitArray;
407   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
408   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
409   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
410 
411   // Set EABI version.
412   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
413                             .Case("4", llvm::EABI::EABI4)
414                             .Case("5", llvm::EABI::EABI5)
415                             .Case("gnu", llvm::EABI::GNU)
416                             .Default(llvm::EABI::Default);
417 
418   if (LangOpts.SjLjExceptions)
419     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
420 
421   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
422   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
423   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
424   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
425   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
426   Options.FunctionSections = CodeGenOpts.FunctionSections;
427   Options.DataSections = CodeGenOpts.DataSections;
428   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
429   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
430   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
431 
432   if (CodeGenOpts.EnableSplitDwarf)
433     Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
434   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
435   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
436   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
437   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
438   Options.MCOptions.MCIncrementalLinkerCompatible =
439       CodeGenOpts.IncrementalLinkerCompatible;
440   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
441   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
442   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
443   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
444   Options.MCOptions.ABIName = TargetOpts.ABI;
445   for (const auto &Entry : HSOpts.UserEntries)
446     if (!Entry.IsFramework &&
447         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
448          Entry.Group == frontend::IncludeDirGroup::Angled ||
449          Entry.Group == frontend::IncludeDirGroup::System))
450       Options.MCOptions.IASSearchPaths.push_back(
451           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
452 }
453 
454 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
455                                       legacy::FunctionPassManager &FPM) {
456   // Handle disabling of all LLVM passes, where we want to preserve the
457   // internal module before any optimization.
458   if (CodeGenOpts.DisableLLVMPasses)
459     return;
460 
461   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
462   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
463   // are inserted before PMBuilder ones - they'd get the default-constructed
464   // TLI with an unknown target otherwise.
465   Triple TargetTriple(TheModule->getTargetTriple());
466   std::unique_ptr<TargetLibraryInfoImpl> TLII(
467       createTLII(TargetTriple, CodeGenOpts));
468 
469   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
470 
471   // At O0 and O1 we only run the always inliner which is more efficient. At
472   // higher optimization levels we run the normal inliner.
473   if (CodeGenOpts.OptimizationLevel <= 1) {
474     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
475                                      !CodeGenOpts.DisableLifetimeMarkers);
476     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
477   } else {
478     // We do not want to inline hot callsites for SamplePGO module-summary build
479     // because profile annotation will happen again in ThinLTO backend, and we
480     // want the IR of the hot path to match the profile.
481     PMBuilder.Inliner = createFunctionInliningPass(
482         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
483         (!CodeGenOpts.SampleProfileFile.empty() &&
484          CodeGenOpts.EmitSummaryIndex));
485   }
486 
487   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
488   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
489   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
490   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
491   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
492 
493   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
494   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
495   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
496   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
497   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
498 
499   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
500 
501   if (TM)
502     TM->adjustPassManager(PMBuilder);
503 
504   if (CodeGenOpts.DebugInfoForProfiling ||
505       !CodeGenOpts.SampleProfileFile.empty())
506     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
507                            addAddDiscriminatorsPass);
508 
509   // In ObjC ARC mode, add the main ARC optimization passes.
510   if (LangOpts.ObjCAutoRefCount) {
511     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
512                            addObjCARCExpandPass);
513     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
514                            addObjCARCAPElimPass);
515     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
516                            addObjCARCOptPass);
517   }
518 
519   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
520     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
521                            addBoundsCheckingPass);
522     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
523                            addBoundsCheckingPass);
524   }
525 
526   if (CodeGenOpts.SanitizeCoverageType ||
527       CodeGenOpts.SanitizeCoverageIndirectCalls ||
528       CodeGenOpts.SanitizeCoverageTraceCmp) {
529     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
530                            addSanitizerCoveragePass);
531     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
532                            addSanitizerCoveragePass);
533   }
534 
535   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
536     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
537                            addAddressSanitizerPasses);
538     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
539                            addAddressSanitizerPasses);
540   }
541 
542   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
543     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
544                            addKernelAddressSanitizerPasses);
545     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
546                            addKernelAddressSanitizerPasses);
547   }
548 
549   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
550     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
551                            addMemorySanitizerPass);
552     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
553                            addMemorySanitizerPass);
554   }
555 
556   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
557     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
558                            addThreadSanitizerPass);
559     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
560                            addThreadSanitizerPass);
561   }
562 
563   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
564     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
565                            addDataFlowSanitizerPass);
566     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
567                            addDataFlowSanitizerPass);
568   }
569 
570   if (LangOpts.CoroutinesTS)
571     addCoroutinePassesToExtensionPoints(PMBuilder);
572 
573   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
574     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
575                            addEfficiencySanitizerPass);
576     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
577                            addEfficiencySanitizerPass);
578   }
579 
580   // Set up the per-function pass manager.
581   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
582   if (CodeGenOpts.VerifyModule)
583     FPM.add(createVerifierPass());
584 
585   // Set up the per-module pass manager.
586   if (!CodeGenOpts.RewriteMapFiles.empty())
587     addSymbolRewriterPass(CodeGenOpts, &MPM);
588 
589   if (!CodeGenOpts.DisableGCov &&
590       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
591     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
592     // LLVM's -default-gcov-version flag is set to something invalid.
593     GCOVOptions Options;
594     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
595     Options.EmitData = CodeGenOpts.EmitGcovArcs;
596     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
597     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
598     Options.NoRedZone = CodeGenOpts.DisableRedZone;
599     Options.FunctionNamesInData =
600         !CodeGenOpts.CoverageNoFunctionNamesInData;
601     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
602     MPM.add(createGCOVProfilerPass(Options));
603     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
604       MPM.add(createStripSymbolsPass(true));
605   }
606 
607   if (CodeGenOpts.hasProfileClangInstr()) {
608     InstrProfOptions Options;
609     Options.NoRedZone = CodeGenOpts.DisableRedZone;
610     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
611     MPM.add(createInstrProfilingLegacyPass(Options));
612   }
613   if (CodeGenOpts.hasProfileIRInstr()) {
614     PMBuilder.EnablePGOInstrGen = true;
615     if (!CodeGenOpts.InstrProfileOutput.empty())
616       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
617     else
618       PMBuilder.PGOInstrGen = DefaultProfileGenName;
619   }
620   if (CodeGenOpts.hasProfileIRUse())
621     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
622 
623   if (!CodeGenOpts.SampleProfileFile.empty())
624     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
625 
626   PMBuilder.populateFunctionPassManager(FPM);
627   PMBuilder.populateModulePassManager(MPM);
628 }
629 
630 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
631   SmallVector<const char *, 16> BackendArgs;
632   BackendArgs.push_back("clang"); // Fake program name.
633   if (!CodeGenOpts.DebugPass.empty()) {
634     BackendArgs.push_back("-debug-pass");
635     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
636   }
637   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
638     BackendArgs.push_back("-limit-float-precision");
639     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
640   }
641   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
642     BackendArgs.push_back(BackendOption.c_str());
643   BackendArgs.push_back(nullptr);
644   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
645                                     BackendArgs.data());
646 }
647 
648 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
649   // Create the TargetMachine for generating code.
650   std::string Error;
651   std::string Triple = TheModule->getTargetTriple();
652   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
653   if (!TheTarget) {
654     if (MustCreateTM)
655       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
656     return;
657   }
658 
659   llvm::CodeModel::Model CM  = getCodeModel(CodeGenOpts);
660   std::string FeaturesStr =
661       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
662   llvm::Reloc::Model RM = getRelocModel(CodeGenOpts);
663   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
664 
665   llvm::TargetOptions Options;
666   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
667   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
668                                           Options, RM, CM, OptLevel));
669 }
670 
671 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
672                                        BackendAction Action,
673                                        raw_pwrite_stream &OS) {
674   // Add LibraryInfo.
675   llvm::Triple TargetTriple(TheModule->getTargetTriple());
676   std::unique_ptr<TargetLibraryInfoImpl> TLII(
677       createTLII(TargetTriple, CodeGenOpts));
678   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
679 
680   // Normal mode, emit a .s or .o file by running the code generator. Note,
681   // this also adds codegenerator level optimization passes.
682   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
683 
684   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
685   // "codegen" passes so that it isn't run multiple times when there is
686   // inlining happening.
687   if (CodeGenOpts.OptimizationLevel > 0)
688     CodeGenPasses.add(createObjCARCContractPass());
689 
690   if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
691                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
692     Diags.Report(diag::err_fe_unable_to_interface_with_target);
693     return false;
694   }
695 
696   return true;
697 }
698 
699 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
700                                       std::unique_ptr<raw_pwrite_stream> OS) {
701   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
702 
703   setCommandLineOpts(CodeGenOpts);
704 
705   bool UsesCodeGen = (Action != Backend_EmitNothing &&
706                       Action != Backend_EmitBC &&
707                       Action != Backend_EmitLL);
708   CreateTargetMachine(UsesCodeGen);
709 
710   if (UsesCodeGen && !TM)
711     return;
712   if (TM)
713     TheModule->setDataLayout(TM->createDataLayout());
714 
715   legacy::PassManager PerModulePasses;
716   PerModulePasses.add(
717       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
718 
719   legacy::FunctionPassManager PerFunctionPasses(TheModule);
720   PerFunctionPasses.add(
721       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
722 
723   CreatePasses(PerModulePasses, PerFunctionPasses);
724 
725   legacy::PassManager CodeGenPasses;
726   CodeGenPasses.add(
727       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
728 
729   std::unique_ptr<raw_fd_ostream> ThinLinkOS;
730 
731   switch (Action) {
732   case Backend_EmitNothing:
733     break;
734 
735   case Backend_EmitBC:
736     if (CodeGenOpts.EmitSummaryIndex) {
737       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
738         std::error_code EC;
739         ThinLinkOS.reset(new llvm::raw_fd_ostream(
740             CodeGenOpts.ThinLinkBitcodeFile, EC,
741             llvm::sys::fs::F_None));
742         if (EC) {
743           Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
744                                                            << EC.message();
745           return;
746         }
747       }
748       PerModulePasses.add(
749           createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
750     }
751     else
752       PerModulePasses.add(
753           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
754     break;
755 
756   case Backend_EmitLL:
757     PerModulePasses.add(
758         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
759     break;
760 
761   default:
762     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
763       return;
764   }
765 
766   // Before executing passes, print the final values of the LLVM options.
767   cl::PrintOptionValues();
768 
769   // Run passes. For now we do all passes at once, but eventually we
770   // would like to have the option of streaming code generation.
771 
772   {
773     PrettyStackTraceString CrashInfo("Per-function optimization");
774 
775     PerFunctionPasses.doInitialization();
776     for (Function &F : *TheModule)
777       if (!F.isDeclaration())
778         PerFunctionPasses.run(F);
779     PerFunctionPasses.doFinalization();
780   }
781 
782   {
783     PrettyStackTraceString CrashInfo("Per-module optimization passes");
784     PerModulePasses.run(*TheModule);
785   }
786 
787   {
788     PrettyStackTraceString CrashInfo("Code generation");
789     CodeGenPasses.run(*TheModule);
790   }
791 }
792 
793 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
794   switch (Opts.OptimizationLevel) {
795   default:
796     llvm_unreachable("Invalid optimization level!");
797 
798   case 1:
799     return PassBuilder::O1;
800 
801   case 2:
802     switch (Opts.OptimizeSize) {
803     default:
804       llvm_unreachable("Invalide optimization level for size!");
805 
806     case 0:
807       return PassBuilder::O2;
808 
809     case 1:
810       return PassBuilder::Os;
811 
812     case 2:
813       return PassBuilder::Oz;
814     }
815 
816   case 3:
817     return PassBuilder::O3;
818   }
819 }
820 
821 /// A clean version of `EmitAssembly` that uses the new pass manager.
822 ///
823 /// Not all features are currently supported in this system, but where
824 /// necessary it falls back to the legacy pass manager to at least provide
825 /// basic functionality.
826 ///
827 /// This API is planned to have its functionality finished and then to replace
828 /// `EmitAssembly` at some point in the future when the default switches.
829 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
830     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
831   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
832   setCommandLineOpts(CodeGenOpts);
833 
834   // The new pass manager always makes a target machine available to passes
835   // during construction.
836   CreateTargetMachine(/*MustCreateTM*/ true);
837   if (!TM)
838     // This will already be diagnosed, just bail.
839     return;
840   TheModule->setDataLayout(TM->createDataLayout());
841 
842   PGOOptions PGOOpt;
843 
844   // -fprofile-generate.
845   PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
846   if (PGOOpt.RunProfileGen)
847     PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
848       DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
849 
850   // -fprofile-use.
851   if (CodeGenOpts.hasProfileIRUse())
852     PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
853 
854   // Only pass a PGO options struct if -fprofile-generate or
855   // -fprofile-use were passed on the cmdline.
856   PassBuilder PB(TM.get(),
857     (PGOOpt.RunProfileGen ||
858       !PGOOpt.ProfileUseFile.empty()) ?
859         Optional<PGOOptions>(PGOOpt) : None);
860 
861   LoopAnalysisManager LAM;
862   FunctionAnalysisManager FAM;
863   CGSCCAnalysisManager CGAM;
864   ModuleAnalysisManager MAM;
865 
866   // Register the AA manager first so that our version is the one used.
867   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
868 
869   // Register all the basic analyses with the managers.
870   PB.registerModuleAnalyses(MAM);
871   PB.registerCGSCCAnalyses(CGAM);
872   PB.registerFunctionAnalyses(FAM);
873   PB.registerLoopAnalyses(LAM);
874   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
875 
876   ModulePassManager MPM;
877 
878   if (!CodeGenOpts.DisableLLVMPasses) {
879     if (CodeGenOpts.OptimizationLevel == 0) {
880       // Build a minimal pipeline based on the semantics required by Clang,
881       // which is just that always inlining occurs.
882       MPM.addPass(AlwaysInlinerPass());
883     } else {
884       // Otherwise, use the default pass pipeline. We also have to map our
885       // optimization levels into one of the distinct levels used to configure
886       // the pipeline.
887       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
888 
889       MPM = PB.buildPerModuleDefaultPipeline(Level);
890     }
891   }
892 
893   // FIXME: We still use the legacy pass manager to do code generation. We
894   // create that pass manager here and use it as needed below.
895   legacy::PassManager CodeGenPasses;
896   bool NeedCodeGen = false;
897 
898   // Append any output we need to the pass manager.
899   switch (Action) {
900   case Backend_EmitNothing:
901     break;
902 
903   case Backend_EmitBC:
904     MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
905                                   CodeGenOpts.EmitSummaryIndex,
906                                   CodeGenOpts.EmitSummaryIndex));
907     break;
908 
909   case Backend_EmitLL:
910     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
911     break;
912 
913   case Backend_EmitAssembly:
914   case Backend_EmitMCNull:
915   case Backend_EmitObj:
916     NeedCodeGen = true;
917     CodeGenPasses.add(
918         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
919     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
920       // FIXME: Should we handle this error differently?
921       return;
922     break;
923   }
924 
925   // Before executing passes, print the final values of the LLVM options.
926   cl::PrintOptionValues();
927 
928   // Now that we have all of the passes ready, run them.
929   {
930     PrettyStackTraceString CrashInfo("Optimizer");
931     MPM.run(*TheModule, MAM);
932   }
933 
934   // Now if needed, run the legacy PM for codegen.
935   if (NeedCodeGen) {
936     PrettyStackTraceString CrashInfo("Code generation");
937     CodeGenPasses.run(*TheModule);
938   }
939 }
940 
941 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
942   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
943   if (!BMsOrErr)
944     return BMsOrErr.takeError();
945 
946   // The bitcode file may contain multiple modules, we want the one with a
947   // summary.
948   for (BitcodeModule &BM : *BMsOrErr) {
949     Expected<bool> HasSummary = BM.hasSummary();
950     if (HasSummary && *HasSummary)
951       return BM;
952   }
953 
954   return make_error<StringError>("Could not find module summary",
955                                  inconvertibleErrorCode());
956 }
957 
958 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
959                               const HeaderSearchOptions &HeaderOpts,
960                               const CodeGenOptions &CGOpts,
961                               const clang::TargetOptions &TOpts,
962                               const LangOptions &LOpts,
963                               std::unique_ptr<raw_pwrite_stream> OS,
964                               std::string SampleProfile,
965                               BackendAction Action) {
966   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
967       ModuleToDefinedGVSummaries;
968   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
969 
970   setCommandLineOpts(CGOpts);
971 
972   // We can simply import the values mentioned in the combined index, since
973   // we should only invoke this using the individual indexes written out
974   // via a WriteIndexesThinBackend.
975   FunctionImporter::ImportMapTy ImportList;
976   for (auto &GlobalList : *CombinedIndex) {
977     auto GUID = GlobalList.first;
978     assert(GlobalList.second.size() == 1 &&
979            "Expected individual combined index to have one summary per GUID");
980     auto &Summary = GlobalList.second[0];
981     // Skip the summaries for the importing module. These are included to
982     // e.g. record required linkage changes.
983     if (Summary->modulePath() == M->getModuleIdentifier())
984       continue;
985     // Doesn't matter what value we plug in to the map, just needs an entry
986     // to provoke importing by thinBackend.
987     ImportList[Summary->modulePath()][GUID] = 1;
988   }
989 
990   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
991   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
992 
993   for (auto &I : ImportList) {
994     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
995         llvm::MemoryBuffer::getFile(I.first());
996     if (!MBOrErr) {
997       errs() << "Error loading imported file '" << I.first()
998              << "': " << MBOrErr.getError().message() << "\n";
999       return;
1000     }
1001 
1002     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1003     if (!BMOrErr) {
1004       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1005         errs() << "Error loading imported file '" << I.first()
1006                << "': " << EIB.message() << '\n';
1007       });
1008       return;
1009     }
1010     ModuleMap.insert({I.first(), *BMOrErr});
1011 
1012     OwnedImports.push_back(std::move(*MBOrErr));
1013   }
1014   auto AddStream = [&](size_t Task) {
1015     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1016   };
1017   lto::Config Conf;
1018   Conf.CPU = TOpts.CPU;
1019   Conf.CodeModel = getCodeModel(CGOpts);
1020   Conf.MAttrs = TOpts.Features;
1021   Conf.RelocModel = getRelocModel(CGOpts);
1022   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1023   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1024   Conf.SampleProfile = std::move(SampleProfile);
1025   switch (Action) {
1026   case Backend_EmitNothing:
1027     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1028       return false;
1029     };
1030     break;
1031   case Backend_EmitLL:
1032     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1033       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1034       return false;
1035     };
1036     break;
1037   case Backend_EmitBC:
1038     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1039       WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
1040       return false;
1041     };
1042     break;
1043   default:
1044     Conf.CGFileType = getCodeGenFileType(Action);
1045     break;
1046   }
1047   if (Error E = thinBackend(
1048           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1049           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1050     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1051       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1052     });
1053   }
1054 }
1055 
1056 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1057                               const HeaderSearchOptions &HeaderOpts,
1058                               const CodeGenOptions &CGOpts,
1059                               const clang::TargetOptions &TOpts,
1060                               const LangOptions &LOpts,
1061                               const llvm::DataLayout &TDesc, Module *M,
1062                               BackendAction Action,
1063                               std::unique_ptr<raw_pwrite_stream> OS) {
1064   if (!CGOpts.ThinLTOIndexFile.empty()) {
1065     // If we are performing a ThinLTO importing compile, load the function index
1066     // into memory and pass it into runThinLTOBackend, which will run the
1067     // function importer and invoke LTO passes.
1068     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1069         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
1070     if (!IndexOrErr) {
1071       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1072                             "Error loading index file '" +
1073                             CGOpts.ThinLTOIndexFile + "': ");
1074       return;
1075     }
1076     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1077     // A null CombinedIndex means we should skip ThinLTO compilation
1078     // (LLVM will optionally ignore empty index files, returning null instead
1079     // of an error).
1080     bool DoThinLTOBackend = CombinedIndex != nullptr;
1081     if (DoThinLTOBackend) {
1082       runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1083                         LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
1084       return;
1085     }
1086   }
1087 
1088   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1089 
1090   if (CGOpts.ExperimentalNewPassManager)
1091     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1092   else
1093     AsmHelper.EmitAssembly(Action, std::move(OS));
1094 
1095   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1096   // DataLayout.
1097   if (AsmHelper.TM) {
1098     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1099     if (DLDesc != TDesc.getStringRepresentation()) {
1100       unsigned DiagID = Diags.getCustomDiagID(
1101           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1102                                     "expected target description '%1'");
1103       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1104     }
1105   }
1106 }
1107 
1108 static const char* getSectionNameForBitcode(const Triple &T) {
1109   switch (T.getObjectFormat()) {
1110   case Triple::MachO:
1111     return "__LLVM,__bitcode";
1112   case Triple::COFF:
1113   case Triple::ELF:
1114   case Triple::Wasm:
1115   case Triple::UnknownObjectFormat:
1116     return ".llvmbc";
1117   }
1118   llvm_unreachable("Unimplemented ObjectFormatType");
1119 }
1120 
1121 static const char* getSectionNameForCommandline(const Triple &T) {
1122   switch (T.getObjectFormat()) {
1123   case Triple::MachO:
1124     return "__LLVM,__cmdline";
1125   case Triple::COFF:
1126   case Triple::ELF:
1127   case Triple::Wasm:
1128   case Triple::UnknownObjectFormat:
1129     return ".llvmcmd";
1130   }
1131   llvm_unreachable("Unimplemented ObjectFormatType");
1132 }
1133 
1134 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1135 // __LLVM,__bitcode section.
1136 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1137                          llvm::MemoryBufferRef Buf) {
1138   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1139     return;
1140 
1141   // Save llvm.compiler.used and remote it.
1142   SmallVector<Constant*, 2> UsedArray;
1143   SmallSet<GlobalValue*, 4> UsedGlobals;
1144   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1145   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1146   for (auto *GV : UsedGlobals) {
1147     if (GV->getName() != "llvm.embedded.module" &&
1148         GV->getName() != "llvm.cmdline")
1149       UsedArray.push_back(
1150           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1151   }
1152   if (Used)
1153     Used->eraseFromParent();
1154 
1155   // Embed the bitcode for the llvm module.
1156   std::string Data;
1157   ArrayRef<uint8_t> ModuleData;
1158   Triple T(M->getTargetTriple());
1159   // Create a constant that contains the bitcode.
1160   // In case of embedding a marker, ignore the input Buf and use the empty
1161   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1162   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1163     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1164                    (const unsigned char *)Buf.getBufferEnd())) {
1165       // If the input is LLVM Assembly, bitcode is produced by serializing
1166       // the module. Use-lists order need to be perserved in this case.
1167       llvm::raw_string_ostream OS(Data);
1168       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1169       ModuleData =
1170           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1171     } else
1172       // If the input is LLVM bitcode, write the input byte stream directly.
1173       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1174                                      Buf.getBufferSize());
1175   }
1176   llvm::Constant *ModuleConstant =
1177       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1178   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1179       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1180       ModuleConstant);
1181   GV->setSection(getSectionNameForBitcode(T));
1182   UsedArray.push_back(
1183       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1184   if (llvm::GlobalVariable *Old =
1185           M->getGlobalVariable("llvm.embedded.module", true)) {
1186     assert(Old->hasOneUse() &&
1187            "llvm.embedded.module can only be used once in llvm.compiler.used");
1188     GV->takeName(Old);
1189     Old->eraseFromParent();
1190   } else {
1191     GV->setName("llvm.embedded.module");
1192   }
1193 
1194   // Skip if only bitcode needs to be embedded.
1195   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1196     // Embed command-line options.
1197     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1198                               CGOpts.CmdArgs.size());
1199     llvm::Constant *CmdConstant =
1200       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1201     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1202                                   llvm::GlobalValue::PrivateLinkage,
1203                                   CmdConstant);
1204     GV->setSection(getSectionNameForCommandline(T));
1205     UsedArray.push_back(
1206         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1207     if (llvm::GlobalVariable *Old =
1208             M->getGlobalVariable("llvm.cmdline", true)) {
1209       assert(Old->hasOneUse() &&
1210              "llvm.cmdline can only be used once in llvm.compiler.used");
1211       GV->takeName(Old);
1212       Old->eraseFromParent();
1213     } else {
1214       GV->setName("llvm.cmdline");
1215     }
1216   }
1217 
1218   if (UsedArray.empty())
1219     return;
1220 
1221   // Recreate llvm.compiler.used.
1222   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1223   auto *NewUsed = new GlobalVariable(
1224       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1225       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1226   NewUsed->setSection("llvm.metadata");
1227 }
1228