]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304659, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / BackendUtil.cpp
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/SymbolRewriter.h"
58 #include <memory>
59 using namespace clang;
60 using namespace llvm;
61
62 namespace {
63
64 // Default filename used for profile generation.
65 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
66
67 class EmitAssemblyHelper {
68   DiagnosticsEngine &Diags;
69   const HeaderSearchOptions &HSOpts;
70   const CodeGenOptions &CodeGenOpts;
71   const clang::TargetOptions &TargetOpts;
72   const LangOptions &LangOpts;
73   Module *TheModule;
74
75   Timer CodeGenerationTime;
76
77   std::unique_ptr<raw_pwrite_stream> OS;
78
79   TargetIRAnalysis getTargetIRAnalysis() const {
80     if (TM)
81       return TM->getTargetIRAnalysis();
82
83     return TargetIRAnalysis();
84   }
85
86   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
87
88   /// Generates the TargetMachine.
89   /// Leaves TM unchanged if it is unable to create the target machine.
90   /// Some of our clang tests specify triples which are not built
91   /// into clang. This is okay because these tests check the generated
92   /// IR, and they require DataLayout which depends on the triple.
93   /// In this case, we allow this method to fail and not report an error.
94   /// When MustCreateTM is used, we print an error if we are unable to load
95   /// the requested target.
96   void CreateTargetMachine(bool MustCreateTM);
97
98   /// Add passes necessary to emit assembly or LLVM IR.
99   ///
100   /// \return True on success.
101   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
102                      raw_pwrite_stream &OS);
103
104 public:
105   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
106                      const HeaderSearchOptions &HeaderSearchOpts,
107                      const CodeGenOptions &CGOpts,
108                      const clang::TargetOptions &TOpts,
109                      const LangOptions &LOpts, Module *M)
110       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
111         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
112         CodeGenerationTime("codegen", "Code Generation Time") {}
113
114   ~EmitAssemblyHelper() {
115     if (CodeGenOpts.DisableFree)
116       BuryPointer(std::move(TM));
117   }
118
119   std::unique_ptr<TargetMachine> TM;
120
121   void EmitAssembly(BackendAction Action,
122                     std::unique_ptr<raw_pwrite_stream> OS);
123
124   void EmitAssemblyWithNewPassManager(BackendAction Action,
125                                       std::unique_ptr<raw_pwrite_stream> OS);
126 };
127
128 // We need this wrapper to access LangOpts and CGOpts from extension functions
129 // that we add to the PassManagerBuilder.
130 class PassManagerBuilderWrapper : public PassManagerBuilder {
131 public:
132   PassManagerBuilderWrapper(const Triple &TargetTriple,
133                             const CodeGenOptions &CGOpts,
134                             const LangOptions &LangOpts)
135       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
136         LangOpts(LangOpts) {}
137   const Triple &getTargetTriple() const { return TargetTriple; }
138   const CodeGenOptions &getCGOpts() const { return CGOpts; }
139   const LangOptions &getLangOpts() const { return LangOpts; }
140
141 private:
142   const Triple &TargetTriple;
143   const CodeGenOptions &CGOpts;
144   const LangOptions &LangOpts;
145 };
146 }
147
148 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
149   if (Builder.OptLevel > 0)
150     PM.add(createObjCARCAPElimPass());
151 }
152
153 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
154   if (Builder.OptLevel > 0)
155     PM.add(createObjCARCExpandPass());
156 }
157
158 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
159   if (Builder.OptLevel > 0)
160     PM.add(createObjCARCOptPass());
161 }
162
163 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
164                                      legacy::PassManagerBase &PM) {
165   PM.add(createAddDiscriminatorsPass());
166 }
167
168 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
169                                   legacy::PassManagerBase &PM) {
170   PM.add(createBoundsCheckingPass());
171 }
172
173 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
174                                      legacy::PassManagerBase &PM) {
175   const PassManagerBuilderWrapper &BuilderWrapper =
176       static_cast<const PassManagerBuilderWrapper&>(Builder);
177   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
178   SanitizerCoverageOptions Opts;
179   Opts.CoverageType =
180       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
181   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
182   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
183   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
184   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
185   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
186   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
187   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
188   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
189   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
190   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
191   PM.add(createSanitizerCoverageModulePass(Opts));
192 }
193
194 // Check if ASan should use GC-friendly instrumentation for globals.
195 // First of all, there is no point if -fdata-sections is off (expect for MachO,
196 // where this is not a factor). Also, on ELF this feature requires an assembler
197 // extension that only works with -integrated-as at the moment.
198 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
199   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
200     return false;
201   switch (T.getObjectFormat()) {
202   case Triple::MachO:
203   case Triple::COFF:
204     return true;
205   case Triple::ELF:
206     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
207   default:
208     return false;
209   }
210 }
211
212 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
213                                       legacy::PassManagerBase &PM) {
214   const PassManagerBuilderWrapper &BuilderWrapper =
215       static_cast<const PassManagerBuilderWrapper&>(Builder);
216   const Triple &T = BuilderWrapper.getTargetTriple();
217   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
218   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
219   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
220   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
221   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
222                                             UseAfterScope));
223   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
224                                           UseGlobalsGC));
225 }
226
227 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
228                                             legacy::PassManagerBase &PM) {
229   PM.add(createAddressSanitizerFunctionPass(
230       /*CompileKernel*/ true,
231       /*Recover*/ true, /*UseAfterScope*/ false));
232   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
233                                           /*Recover*/true));
234 }
235
236 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
237                                    legacy::PassManagerBase &PM) {
238   const PassManagerBuilderWrapper &BuilderWrapper =
239       static_cast<const PassManagerBuilderWrapper&>(Builder);
240   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
241   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
242   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
243   PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
244
245   // MemorySanitizer inserts complex instrumentation that mostly follows
246   // the logic of the original code, but operates on "shadow" values.
247   // It can benefit from re-running some general purpose optimization passes.
248   if (Builder.OptLevel > 0) {
249     PM.add(createEarlyCSEPass());
250     PM.add(createReassociatePass());
251     PM.add(createLICMPass());
252     PM.add(createGVNPass());
253     PM.add(createInstructionCombiningPass());
254     PM.add(createDeadStoreEliminationPass());
255   }
256 }
257
258 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
259                                    legacy::PassManagerBase &PM) {
260   PM.add(createThreadSanitizerPass());
261 }
262
263 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
264                                      legacy::PassManagerBase &PM) {
265   const PassManagerBuilderWrapper &BuilderWrapper =
266       static_cast<const PassManagerBuilderWrapper&>(Builder);
267   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
268   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
269 }
270
271 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
272                                        legacy::PassManagerBase &PM) {
273   const PassManagerBuilderWrapper &BuilderWrapper =
274       static_cast<const PassManagerBuilderWrapper&>(Builder);
275   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
276   EfficiencySanitizerOptions Opts;
277   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
278     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
279   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
280     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
281   PM.add(createEfficiencySanitizerPass(Opts));
282 }
283
284 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
285                                          const CodeGenOptions &CodeGenOpts) {
286   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
287   if (!CodeGenOpts.SimplifyLibCalls)
288     TLII->disableAllFunctions();
289   else {
290     // Disable individual libc/libm calls in TargetLibraryInfo.
291     LibFunc F;
292     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
293       if (TLII->getLibFunc(FuncName, F))
294         TLII->setUnavailable(F);
295   }
296
297   switch (CodeGenOpts.getVecLib()) {
298   case CodeGenOptions::Accelerate:
299     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
300     break;
301   case CodeGenOptions::SVML:
302     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
303     break;
304   default:
305     break;
306   }
307   return TLII;
308 }
309
310 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
311                                   legacy::PassManager *MPM) {
312   llvm::SymbolRewriter::RewriteDescriptorList DL;
313
314   llvm::SymbolRewriter::RewriteMapParser MapParser;
315   for (const auto &MapFile : Opts.RewriteMapFiles)
316     MapParser.parse(MapFile, &DL);
317
318   MPM->add(createRewriteSymbolsPass(DL));
319 }
320
321 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
322   switch (CodeGenOpts.OptimizationLevel) {
323   default:
324     llvm_unreachable("Invalid optimization level!");
325   case 0:
326     return CodeGenOpt::None;
327   case 1:
328     return CodeGenOpt::Less;
329   case 2:
330     return CodeGenOpt::Default; // O2/Os/Oz
331   case 3:
332     return CodeGenOpt::Aggressive;
333   }
334 }
335
336 static llvm::CodeModel::Model getCodeModel(const CodeGenOptions &CodeGenOpts) {
337   unsigned CodeModel =
338       llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
339       .Case("small", llvm::CodeModel::Small)
340       .Case("kernel", llvm::CodeModel::Kernel)
341       .Case("medium", llvm::CodeModel::Medium)
342       .Case("large", llvm::CodeModel::Large)
343       .Case("default", llvm::CodeModel::Default)
344       .Default(~0u);
345   assert(CodeModel != ~0u && "invalid code model!");
346   return static_cast<llvm::CodeModel::Model>(CodeModel);
347 }
348
349 static llvm::Reloc::Model getRelocModel(const CodeGenOptions &CodeGenOpts) {
350   // Keep this synced with the equivalent code in
351   // lib/Frontend/CompilerInvocation.cpp
352   llvm::Optional<llvm::Reloc::Model> RM;
353   RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
354       .Case("static", llvm::Reloc::Static)
355       .Case("pic", llvm::Reloc::PIC_)
356       .Case("ropi", llvm::Reloc::ROPI)
357       .Case("rwpi", llvm::Reloc::RWPI)
358       .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
359       .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
360   assert(RM.hasValue() && "invalid PIC model!");
361   return *RM;
362 }
363
364 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
365   if (Action == Backend_EmitObj)
366     return TargetMachine::CGFT_ObjectFile;
367   else if (Action == Backend_EmitMCNull)
368     return TargetMachine::CGFT_Null;
369   else {
370     assert(Action == Backend_EmitAssembly && "Invalid action!");
371     return TargetMachine::CGFT_AssemblyFile;
372   }
373 }
374
375 static void initTargetOptions(llvm::TargetOptions &Options,
376                               const CodeGenOptions &CodeGenOpts,
377                               const clang::TargetOptions &TargetOpts,
378                               const LangOptions &LangOpts,
379                               const HeaderSearchOptions &HSOpts) {
380   Options.ThreadModel =
381       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
382           .Case("posix", llvm::ThreadModel::POSIX)
383           .Case("single", llvm::ThreadModel::Single);
384
385   // Set float ABI type.
386   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
387           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
388          "Invalid Floating Point ABI!");
389   Options.FloatABIType =
390       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
391           .Case("soft", llvm::FloatABI::Soft)
392           .Case("softfp", llvm::FloatABI::Soft)
393           .Case("hard", llvm::FloatABI::Hard)
394           .Default(llvm::FloatABI::Default);
395
396   // Set FP fusion mode.
397   switch (LangOpts.getDefaultFPContractMode()) {
398   case LangOptions::FPC_Off:
399     // Preserve any contraction performed by the front-end.  (Strict performs
400     // splitting of the muladd instrinsic in the backend.)
401     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
402     break;
403   case LangOptions::FPC_On:
404     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
405     break;
406   case LangOptions::FPC_Fast:
407     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
408     break;
409   }
410
411   Options.UseInitArray = CodeGenOpts.UseInitArray;
412   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
413   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
414   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
415
416   // Set EABI version.
417   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
418                             .Case("4", llvm::EABI::EABI4)
419                             .Case("5", llvm::EABI::EABI5)
420                             .Case("gnu", llvm::EABI::GNU)
421                             .Default(llvm::EABI::Default);
422
423   if (LangOpts.SjLjExceptions)
424     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
425
426   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
427   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
428   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
429   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
430   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
431   Options.FunctionSections = CodeGenOpts.FunctionSections;
432   Options.DataSections = CodeGenOpts.DataSections;
433   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
434   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
435   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
436
437   if (CodeGenOpts.EnableSplitDwarf)
438     Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
439   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
440   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
441   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
442   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
443   Options.MCOptions.MCIncrementalLinkerCompatible =
444       CodeGenOpts.IncrementalLinkerCompatible;
445   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
446   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
447   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
448   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
449   Options.MCOptions.ABIName = TargetOpts.ABI;
450   for (const auto &Entry : HSOpts.UserEntries)
451     if (!Entry.IsFramework &&
452         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
453          Entry.Group == frontend::IncludeDirGroup::Angled ||
454          Entry.Group == frontend::IncludeDirGroup::System))
455       Options.MCOptions.IASSearchPaths.push_back(
456           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
457 }
458
459 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
460                                       legacy::FunctionPassManager &FPM) {
461   // Handle disabling of all LLVM passes, where we want to preserve the
462   // internal module before any optimization.
463   if (CodeGenOpts.DisableLLVMPasses)
464     return;
465
466   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
467   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
468   // are inserted before PMBuilder ones - they'd get the default-constructed
469   // TLI with an unknown target otherwise.
470   Triple TargetTriple(TheModule->getTargetTriple());
471   std::unique_ptr<TargetLibraryInfoImpl> TLII(
472       createTLII(TargetTriple, CodeGenOpts));
473
474   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
475
476   // At O0 and O1 we only run the always inliner which is more efficient. At
477   // higher optimization levels we run the normal inliner.
478   if (CodeGenOpts.OptimizationLevel <= 1) {
479     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
480                                      !CodeGenOpts.DisableLifetimeMarkers);
481     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
482   } else {
483     // We do not want to inline hot callsites for SamplePGO module-summary build
484     // because profile annotation will happen again in ThinLTO backend, and we
485     // want the IR of the hot path to match the profile.
486     PMBuilder.Inliner = createFunctionInliningPass(
487         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
488         (!CodeGenOpts.SampleProfileFile.empty() &&
489          CodeGenOpts.EmitSummaryIndex));
490   }
491
492   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
493   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
494   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
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   // Only pass a PGO options struct if -fprofile-generate or
860   // -fprofile-use were passed on the cmdline.
861   PassBuilder PB(TM.get(),
862     (PGOOpt.RunProfileGen ||
863       !PGOOpt.ProfileUseFile.empty()) ?
864         Optional<PGOOptions>(PGOOpt) : None);
865
866   LoopAnalysisManager LAM;
867   FunctionAnalysisManager FAM;
868   CGSCCAnalysisManager CGAM;
869   ModuleAnalysisManager MAM;
870
871   // Register the AA manager first so that our version is the one used.
872   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
873
874   // Register all the basic analyses with the managers.
875   PB.registerModuleAnalyses(MAM);
876   PB.registerCGSCCAnalyses(CGAM);
877   PB.registerFunctionAnalyses(FAM);
878   PB.registerLoopAnalyses(LAM);
879   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
880
881   ModulePassManager MPM;
882
883   if (!CodeGenOpts.DisableLLVMPasses) {
884     if (CodeGenOpts.OptimizationLevel == 0) {
885       // Build a minimal pipeline based on the semantics required by Clang,
886       // which is just that always inlining occurs.
887       MPM.addPass(AlwaysInlinerPass());
888     } else {
889       // Otherwise, use the default pass pipeline. We also have to map our
890       // optimization levels into one of the distinct levels used to configure
891       // the pipeline.
892       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
893
894       MPM = PB.buildPerModuleDefaultPipeline(Level);
895     }
896   }
897
898   // FIXME: We still use the legacy pass manager to do code generation. We
899   // create that pass manager here and use it as needed below.
900   legacy::PassManager CodeGenPasses;
901   bool NeedCodeGen = false;
902   Optional<raw_fd_ostream> ThinLinkOS;
903
904   // Append any output we need to the pass manager.
905   switch (Action) {
906   case Backend_EmitNothing:
907     break;
908
909   case Backend_EmitBC:
910     if (CodeGenOpts.EmitSummaryIndex) {
911       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
912         std::error_code EC;
913         ThinLinkOS.emplace(CodeGenOpts.ThinLinkBitcodeFile, EC,
914                            llvm::sys::fs::F_None);
915         if (EC) {
916           Diags.Report(diag::err_fe_unable_to_open_output)
917               << CodeGenOpts.ThinLinkBitcodeFile << EC.message();
918           return;
919         }
920       }
921       MPM.addPass(
922           ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &*ThinLinkOS : nullptr));
923     } else {
924       MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
925                                     CodeGenOpts.EmitSummaryIndex,
926                                     CodeGenOpts.EmitSummaryIndex));
927     }
928     break;
929
930   case Backend_EmitLL:
931     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
932     break;
933
934   case Backend_EmitAssembly:
935   case Backend_EmitMCNull:
936   case Backend_EmitObj:
937     NeedCodeGen = true;
938     CodeGenPasses.add(
939         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
940     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
941       // FIXME: Should we handle this error differently?
942       return;
943     break;
944   }
945
946   // Before executing passes, print the final values of the LLVM options.
947   cl::PrintOptionValues();
948
949   // Now that we have all of the passes ready, run them.
950   {
951     PrettyStackTraceString CrashInfo("Optimizer");
952     MPM.run(*TheModule, MAM);
953   }
954
955   // Now if needed, run the legacy PM for codegen.
956   if (NeedCodeGen) {
957     PrettyStackTraceString CrashInfo("Code generation");
958     CodeGenPasses.run(*TheModule);
959   }
960 }
961
962 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
963   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
964   if (!BMsOrErr)
965     return BMsOrErr.takeError();
966
967   // The bitcode file may contain multiple modules, we want the one with a
968   // summary.
969   for (BitcodeModule &BM : *BMsOrErr) {
970     Expected<bool> HasSummary = BM.hasSummary();
971     if (HasSummary && *HasSummary)
972       return BM;
973   }
974
975   return make_error<StringError>("Could not find module summary",
976                                  inconvertibleErrorCode());
977 }
978
979 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
980                               const HeaderSearchOptions &HeaderOpts,
981                               const CodeGenOptions &CGOpts,
982                               const clang::TargetOptions &TOpts,
983                               const LangOptions &LOpts,
984                               std::unique_ptr<raw_pwrite_stream> OS,
985                               std::string SampleProfile,
986                               BackendAction Action) {
987   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
988       ModuleToDefinedGVSummaries;
989   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
990
991   setCommandLineOpts(CGOpts);
992
993   // We can simply import the values mentioned in the combined index, since
994   // we should only invoke this using the individual indexes written out
995   // via a WriteIndexesThinBackend.
996   FunctionImporter::ImportMapTy ImportList;
997   for (auto &GlobalList : *CombinedIndex) {
998     // Ignore entries for undefined references.
999     if (GlobalList.second.SummaryList.empty())
1000       continue;
1001
1002     auto GUID = GlobalList.first;
1003     assert(GlobalList.second.SummaryList.size() == 1 &&
1004            "Expected individual combined index to have one summary per GUID");
1005     auto &Summary = GlobalList.second.SummaryList[0];
1006     // Skip the summaries for the importing module. These are included to
1007     // e.g. record required linkage changes.
1008     if (Summary->modulePath() == M->getModuleIdentifier())
1009       continue;
1010     // Doesn't matter what value we plug in to the map, just needs an entry
1011     // to provoke importing by thinBackend.
1012     ImportList[Summary->modulePath()][GUID] = 1;
1013   }
1014
1015   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1016   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1017
1018   for (auto &I : ImportList) {
1019     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1020         llvm::MemoryBuffer::getFile(I.first());
1021     if (!MBOrErr) {
1022       errs() << "Error loading imported file '" << I.first()
1023              << "': " << MBOrErr.getError().message() << "\n";
1024       return;
1025     }
1026
1027     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1028     if (!BMOrErr) {
1029       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1030         errs() << "Error loading imported file '" << I.first()
1031                << "': " << EIB.message() << '\n';
1032       });
1033       return;
1034     }
1035     ModuleMap.insert({I.first(), *BMOrErr});
1036
1037     OwnedImports.push_back(std::move(*MBOrErr));
1038   }
1039   auto AddStream = [&](size_t Task) {
1040     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1041   };
1042   lto::Config Conf;
1043   Conf.CPU = TOpts.CPU;
1044   Conf.CodeModel = getCodeModel(CGOpts);
1045   Conf.MAttrs = TOpts.Features;
1046   Conf.RelocModel = getRelocModel(CGOpts);
1047   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1048   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1049   Conf.SampleProfile = std::move(SampleProfile);
1050   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1051   switch (Action) {
1052   case Backend_EmitNothing:
1053     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1054       return false;
1055     };
1056     break;
1057   case Backend_EmitLL:
1058     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1059       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1060       return false;
1061     };
1062     break;
1063   case Backend_EmitBC:
1064     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1065       WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
1066       return false;
1067     };
1068     break;
1069   default:
1070     Conf.CGFileType = getCodeGenFileType(Action);
1071     break;
1072   }
1073   if (Error E = thinBackend(
1074           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1075           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1076     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1077       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1078     });
1079   }
1080 }
1081
1082 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1083                               const HeaderSearchOptions &HeaderOpts,
1084                               const CodeGenOptions &CGOpts,
1085                               const clang::TargetOptions &TOpts,
1086                               const LangOptions &LOpts,
1087                               const llvm::DataLayout &TDesc, Module *M,
1088                               BackendAction Action,
1089                               std::unique_ptr<raw_pwrite_stream> OS) {
1090   if (!CGOpts.ThinLTOIndexFile.empty()) {
1091     // If we are performing a ThinLTO importing compile, load the function index
1092     // into memory and pass it into runThinLTOBackend, which will run the
1093     // function importer and invoke LTO passes.
1094     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1095         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1096                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1097     if (!IndexOrErr) {
1098       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1099                             "Error loading index file '" +
1100                             CGOpts.ThinLTOIndexFile + "': ");
1101       return;
1102     }
1103     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1104     // A null CombinedIndex means we should skip ThinLTO compilation
1105     // (LLVM will optionally ignore empty index files, returning null instead
1106     // of an error).
1107     bool DoThinLTOBackend = CombinedIndex != nullptr;
1108     if (DoThinLTOBackend) {
1109       runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1110                         LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
1111       return;
1112     }
1113   }
1114
1115   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1116
1117   if (CGOpts.ExperimentalNewPassManager)
1118     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1119   else
1120     AsmHelper.EmitAssembly(Action, std::move(OS));
1121
1122   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1123   // DataLayout.
1124   if (AsmHelper.TM) {
1125     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1126     if (DLDesc != TDesc.getStringRepresentation()) {
1127       unsigned DiagID = Diags.getCustomDiagID(
1128           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1129                                     "expected target description '%1'");
1130       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1131     }
1132   }
1133 }
1134
1135 static const char* getSectionNameForBitcode(const Triple &T) {
1136   switch (T.getObjectFormat()) {
1137   case Triple::MachO:
1138     return "__LLVM,__bitcode";
1139   case Triple::COFF:
1140   case Triple::ELF:
1141   case Triple::Wasm:
1142   case Triple::UnknownObjectFormat:
1143     return ".llvmbc";
1144   }
1145   llvm_unreachable("Unimplemented ObjectFormatType");
1146 }
1147
1148 static const char* getSectionNameForCommandline(const Triple &T) {
1149   switch (T.getObjectFormat()) {
1150   case Triple::MachO:
1151     return "__LLVM,__cmdline";
1152   case Triple::COFF:
1153   case Triple::ELF:
1154   case Triple::Wasm:
1155   case Triple::UnknownObjectFormat:
1156     return ".llvmcmd";
1157   }
1158   llvm_unreachable("Unimplemented ObjectFormatType");
1159 }
1160
1161 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1162 // __LLVM,__bitcode section.
1163 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1164                          llvm::MemoryBufferRef Buf) {
1165   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1166     return;
1167
1168   // Save llvm.compiler.used and remote it.
1169   SmallVector<Constant*, 2> UsedArray;
1170   SmallSet<GlobalValue*, 4> UsedGlobals;
1171   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1172   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1173   for (auto *GV : UsedGlobals) {
1174     if (GV->getName() != "llvm.embedded.module" &&
1175         GV->getName() != "llvm.cmdline")
1176       UsedArray.push_back(
1177           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1178   }
1179   if (Used)
1180     Used->eraseFromParent();
1181
1182   // Embed the bitcode for the llvm module.
1183   std::string Data;
1184   ArrayRef<uint8_t> ModuleData;
1185   Triple T(M->getTargetTriple());
1186   // Create a constant that contains the bitcode.
1187   // In case of embedding a marker, ignore the input Buf and use the empty
1188   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1189   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1190     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1191                    (const unsigned char *)Buf.getBufferEnd())) {
1192       // If the input is LLVM Assembly, bitcode is produced by serializing
1193       // the module. Use-lists order need to be perserved in this case.
1194       llvm::raw_string_ostream OS(Data);
1195       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1196       ModuleData =
1197           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1198     } else
1199       // If the input is LLVM bitcode, write the input byte stream directly.
1200       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1201                                      Buf.getBufferSize());
1202   }
1203   llvm::Constant *ModuleConstant =
1204       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1205   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1206       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1207       ModuleConstant);
1208   GV->setSection(getSectionNameForBitcode(T));
1209   UsedArray.push_back(
1210       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1211   if (llvm::GlobalVariable *Old =
1212           M->getGlobalVariable("llvm.embedded.module", true)) {
1213     assert(Old->hasOneUse() &&
1214            "llvm.embedded.module can only be used once in llvm.compiler.used");
1215     GV->takeName(Old);
1216     Old->eraseFromParent();
1217   } else {
1218     GV->setName("llvm.embedded.module");
1219   }
1220
1221   // Skip if only bitcode needs to be embedded.
1222   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1223     // Embed command-line options.
1224     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1225                               CGOpts.CmdArgs.size());
1226     llvm::Constant *CmdConstant =
1227       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1228     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1229                                   llvm::GlobalValue::PrivateLinkage,
1230                                   CmdConstant);
1231     GV->setSection(getSectionNameForCommandline(T));
1232     UsedArray.push_back(
1233         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1234     if (llvm::GlobalVariable *Old =
1235             M->getGlobalVariable("llvm.cmdline", true)) {
1236       assert(Old->hasOneUse() &&
1237              "llvm.cmdline can only be used once in llvm.compiler.used");
1238       GV->takeName(Old);
1239       Old->eraseFromParent();
1240     } else {
1241       GV->setName("llvm.cmdline");
1242     }
1243   }
1244
1245   if (UsedArray.empty())
1246     return;
1247
1248   // Recreate llvm.compiler.used.
1249   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1250   auto *NewUsed = new GlobalVariable(
1251       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1252       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1253   NewUsed->setSection("llvm.metadata");
1254 }