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