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