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