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