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