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