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