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