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  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
913  MPM.addPass(GCOVProfilerPass(*Options));
914 
915  // Build a minimal pipeline based on the semantics required by Clang,
916  // which is just that always inlining occurs.
917  MPM.addPass(AlwaysInlinerPass());
918 
919  // At -O0 we directly run necessary sanitizer passes.
920  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
921  MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
922 
923  // Lastly, add a semantically necessary pass for ThinLTO.
924  if (IsThinLTO)
925  MPM.addPass(NameAnonGlobalPass());
926  } else {
927  // Map our optimization levels into one of the distinct levels used to
928  // configure the pipeline.
929  PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
930 
931  // Register callbacks to schedule sanitizer passes at the appropriate part of
932  // the pipeline.
933  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
934  PB.registerScalarOptimizerLateEPCallback(
935  [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
936  FPM.addPass(BoundsCheckingPass());
937  });
938  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
939  PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
940  MPM.addPass(GCOVProfilerPass(*Options));
941  });
942 
943  if (IsThinLTO) {
944  MPM = PB.buildThinLTOPreLinkDefaultPipeline(
945  Level, CodeGenOpts.DebugPassManager);
946  MPM.addPass(NameAnonGlobalPass());
947  } else if (IsLTO) {
948  MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
949  CodeGenOpts.DebugPassManager);
950  } else {
951  MPM = PB.buildPerModuleDefaultPipeline(Level,
952  CodeGenOpts.DebugPassManager);
953  }
954  }
955  }
956 
957  // FIXME: We still use the legacy pass manager to do code generation. We
958  // create that pass manager here and use it as needed below.
959  legacy::PassManager CodeGenPasses;
960  bool NeedCodeGen = false;
961  Optional<raw_fd_ostream> ThinLinkOS;
962 
963  // Append any output we need to the pass manager.
964  switch (Action) {
965  case Backend_EmitNothing:
966  break;
967 
968  case Backend_EmitBC:
969  if (CodeGenOpts.EmitSummaryIndex) {
970  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
971  std::error_code EC;
972  ThinLinkOS.emplace(CodeGenOpts.ThinLinkBitcodeFile, EC,
973  llvm::sys::fs::F_None);
974  if (EC) {
975  Diags.Report(diag::err_fe_unable_to_open_output)
976  << CodeGenOpts.ThinLinkBitcodeFile << EC.message();
977  return;
978  }
979  }
980  MPM.addPass(
981  ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &*ThinLinkOS : nullptr));
982  } else {
983  MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
984  CodeGenOpts.EmitSummaryIndex,
985  CodeGenOpts.EmitSummaryIndex));
986  }
987  break;
988 
989  case Backend_EmitLL:
990  MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
991  break;
992 
994  case Backend_EmitMCNull:
995  case Backend_EmitObj:
996  NeedCodeGen = true;
997  CodeGenPasses.add(
998  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
999  if (!AddEmitPasses(CodeGenPasses, Action, *OS))
1000  // FIXME: Should we handle this error differently?
1001  return;
1002  break;
1003  }
1004 
1005  // Before executing passes, print the final values of the LLVM options.
1006  cl::PrintOptionValues();
1007 
1008  // Now that we have all of the passes ready, run them.
1009  {
1010  PrettyStackTraceString CrashInfo("Optimizer");
1011  MPM.run(*TheModule, MAM);
1012  }
1013 
1014  // Now if needed, run the legacy PM for codegen.
1015  if (NeedCodeGen) {
1016  PrettyStackTraceString CrashInfo("Code generation");
1017  CodeGenPasses.run(*TheModule);
1018  }
1019 }
1020 
1021 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1022  Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1023  if (!BMsOrErr)
1024  return BMsOrErr.takeError();
1025 
1026  // The bitcode file may contain multiple modules, we want the one that is
1027  // marked as being the ThinLTO module.
1028  if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1029  return *Bm;
1030 
1031  return make_error<StringError>("Could not find module summary",
1032  inconvertibleErrorCode());
1033 }
1034 
1036  for (BitcodeModule &BM : BMs) {
1037  Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1038  if (LTOInfo && LTOInfo->IsThinLTO)
1039  return &BM;
1040  }
1041  return nullptr;
1042 }
1043 
1044 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1045  const HeaderSearchOptions &HeaderOpts,
1046  const CodeGenOptions &CGOpts,
1047  const clang::TargetOptions &TOpts,
1048  const LangOptions &LOpts,
1049  std::unique_ptr<raw_pwrite_stream> OS,
1050  std::string SampleProfile,
1051  BackendAction Action) {
1052  StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1053  ModuleToDefinedGVSummaries;
1054  CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1055 
1056  setCommandLineOpts(CGOpts);
1057 
1058  // We can simply import the values mentioned in the combined index, since
1059  // we should only invoke this using the individual indexes written out
1060  // via a WriteIndexesThinBackend.
1061  FunctionImporter::ImportMapTy ImportList;
1062  for (auto &GlobalList : *CombinedIndex) {
1063  // Ignore entries for undefined references.
1064  if (GlobalList.second.SummaryList.empty())
1065  continue;
1066 
1067  auto GUID = GlobalList.first;
1068  assert(GlobalList.second.SummaryList.size() == 1 &&
1069  "Expected individual combined index to have one summary per GUID");
1070  auto &Summary = GlobalList.second.SummaryList[0];
1071  // Skip the summaries for the importing module. These are included to
1072  // e.g. record required linkage changes.
1073  if (Summary->modulePath() == M->getModuleIdentifier())
1074  continue;
1075  // Doesn't matter what value we plug in to the map, just needs an entry
1076  // to provoke importing by thinBackend.
1077  ImportList[Summary->modulePath()][GUID] = 1;
1078  }
1079 
1080  std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1081  MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1082 
1083  for (auto &I : ImportList) {
1084  ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1085  llvm::MemoryBuffer::getFile(I.first());
1086  if (!MBOrErr) {
1087  errs() << "Error loading imported file '" << I.first()
1088  << "': " << MBOrErr.getError().message() << "\n";
1089  return;
1090  }
1091 
1092  Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1093  if (!BMOrErr) {
1094  handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1095  errs() << "Error loading imported file '" << I.first()
1096  << "': " << EIB.message() << '\n';
1097  });
1098  return;
1099  }
1100  ModuleMap.insert({I.first(), *BMOrErr});
1101 
1102  OwnedImports.push_back(std::move(*MBOrErr));
1103  }
1104  auto AddStream = [&](size_t Task) {
1105  return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1106  };
1107  lto::Config Conf;
1108  Conf.CPU = TOpts.CPU;
1109  Conf.CodeModel = getCodeModel(CGOpts);
1110  Conf.MAttrs = TOpts.Features;
1111  Conf.RelocModel = CGOpts.RelocationModel;
1112  Conf.CGOptLevel = getCGOptLevel(CGOpts);
1113  initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1114  Conf.SampleProfile = std::move(SampleProfile);
1115  Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1116  Conf.DebugPassManager = CGOpts.DebugPassManager;
1117  switch (Action) {
1118  case Backend_EmitNothing:
1119  Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1120  return false;
1121  };
1122  break;
1123  case Backend_EmitLL:
1124  Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1125  M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1126  return false;
1127  };
1128  break;
1129  case Backend_EmitBC:
1130  Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1131  WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1132  return false;
1133  };
1134  break;
1135  default:
1136  Conf.CGFileType = getCodeGenFileType(Action);
1137  break;
1138  }
1139  if (Error E = thinBackend(
1140  Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1141  ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1142  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1143  errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1144  });
1145  }
1146 }
1147 
1149  const HeaderSearchOptions &HeaderOpts,
1150  const CodeGenOptions &CGOpts,
1151  const clang::TargetOptions &TOpts,
1152  const LangOptions &LOpts,
1153  const llvm::DataLayout &TDesc, Module *M,
1154  BackendAction Action,
1155  std::unique_ptr<raw_pwrite_stream> OS) {
1156  std::unique_ptr<llvm::Module> EmptyModule;
1157  if (!CGOpts.ThinLTOIndexFile.empty()) {
1158  // If we are performing a ThinLTO importing compile, load the function index
1159  // into memory and pass it into runThinLTOBackend, which will run the
1160  // function importer and invoke LTO passes.
1162  llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1163  /*IgnoreEmptyThinLTOIndexFile*/true);
1164  if (!IndexOrErr) {
1165  logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1166  "Error loading index file '" +
1167  CGOpts.ThinLTOIndexFile + "': ");
1168  return;
1169  }
1170  std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1171  // A null CombinedIndex means we should skip ThinLTO compilation
1172  // (LLVM will optionally ignore empty index files, returning null instead
1173  // of an error).
1174  if (CombinedIndex) {
1175  if (!CombinedIndex->skipModuleByDistributedBackend()) {
1176  runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1177  LOpts, std::move(OS), CGOpts.SampleProfileFile,
1178  Action);
1179  return;
1180  }
1181  // Distributed indexing detected that nothing from the module is needed
1182  // for the final linking. So we can skip the compilation. We sill need to
1183  // output an empty object file to make sure that a linker does not fail
1184  // trying to read it. Also for some features, like CFI, we must skip
1185  // the compilation as CombinedIndex does not contain all required
1186  // information.
1187  EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1188  EmptyModule->setTargetTriple(M->getTargetTriple());
1189  M = EmptyModule.get();
1190  }
1191  }
1192 
1193  EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1194 
1195  if (CGOpts.ExperimentalNewPassManager)
1196  AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1197  else
1198  AsmHelper.EmitAssembly(Action, std::move(OS));
1199 
1200  // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1201  // DataLayout.
1202  if (AsmHelper.TM) {
1203  std::string DLDesc = M->getDataLayout().getStringRepresentation();
1204  if (DLDesc != TDesc.getStringRepresentation()) {
1205  unsigned DiagID = Diags.getCustomDiagID(
1206  DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1207  "expected target description '%1'");
1208  Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1209  }
1210  }
1211 }
1212 
1213 static const char* getSectionNameForBitcode(const Triple &T) {
1214  switch (T.getObjectFormat()) {
1215  case Triple::MachO:
1216  return "__LLVM,__bitcode";
1217  case Triple::COFF:
1218  case Triple::ELF:
1219  case Triple::Wasm:
1220  case Triple::UnknownObjectFormat:
1221  return ".llvmbc";
1222  }
1223  llvm_unreachable("Unimplemented ObjectFormatType");
1224 }
1225 
1226 static const char* getSectionNameForCommandline(const Triple &T) {
1227  switch (T.getObjectFormat()) {
1228  case Triple::MachO:
1229  return "__LLVM,__cmdline";
1230  case Triple::COFF:
1231  case Triple::ELF:
1232  case Triple::Wasm:
1233  case Triple::UnknownObjectFormat:
1234  return ".llvmcmd";
1235  }
1236  llvm_unreachable("Unimplemented ObjectFormatType");
1237 }
1238 
1239 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1240 // __LLVM,__bitcode section.
1241 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1242  llvm::MemoryBufferRef Buf) {
1243  if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1244  return;
1245 
1246  // Save llvm.compiler.used and remote it.
1247  SmallVector<Constant*, 2> UsedArray;
1248  SmallSet<GlobalValue*, 4> UsedGlobals;
1249  Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1250  GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1251  for (auto *GV : UsedGlobals) {
1252  if (GV->getName() != "llvm.embedded.module" &&
1253  GV->getName() != "llvm.cmdline")
1254  UsedArray.push_back(
1255  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1256  }
1257  if (Used)
1258  Used->eraseFromParent();
1259 
1260  // Embed the bitcode for the llvm module.
1261  std::string Data;
1262  ArrayRef<uint8_t> ModuleData;
1263  Triple T(M->getTargetTriple());
1264  // Create a constant that contains the bitcode.
1265  // In case of embedding a marker, ignore the input Buf and use the empty
1266  // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1267  if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1268  if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1269  (const unsigned char *)Buf.getBufferEnd())) {
1270  // If the input is LLVM Assembly, bitcode is produced by serializing
1271  // the module. Use-lists order need to be perserved in this case.
1272  llvm::raw_string_ostream OS(Data);
1273  llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1274  ModuleData =
1275  ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1276  } else
1277  // If the input is LLVM bitcode, write the input byte stream directly.
1278  ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1279  Buf.getBufferSize());
1280  }
1281  llvm::Constant *ModuleConstant =
1282  llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1283  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1284  *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1285  ModuleConstant);
1286  GV->setSection(getSectionNameForBitcode(T));
1287  UsedArray.push_back(
1288  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1289  if (llvm::GlobalVariable *Old =
1290  M->getGlobalVariable("llvm.embedded.module", true)) {
1291  assert(Old->hasOneUse() &&
1292  "llvm.embedded.module can only be used once in llvm.compiler.used");
1293  GV->takeName(Old);
1294  Old->eraseFromParent();
1295  } else {
1296  GV->setName("llvm.embedded.module");
1297  }
1298 
1299  // Skip if only bitcode needs to be embedded.
1300  if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1301  // Embed command-line options.
1302  ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1303  CGOpts.CmdArgs.size());
1304  llvm::Constant *CmdConstant =
1305  llvm::ConstantDataArray::get(M->getContext(), CmdData);
1306  GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1307  llvm::GlobalValue::PrivateLinkage,
1308  CmdConstant);
1309  GV->setSection(getSectionNameForCommandline(T));
1310  UsedArray.push_back(
1311  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1312  if (llvm::GlobalVariable *Old =
1313  M->getGlobalVariable("llvm.cmdline", true)) {
1314  assert(Old->hasOneUse() &&
1315  "llvm.cmdline can only be used once in llvm.compiler.used");
1316  GV->takeName(Old);
1317  Old->eraseFromParent();
1318  } else {
1319  GV->setName("llvm.cmdline");
1320  }
1321  }
1322 
1323  if (UsedArray.empty())
1324  return;
1325 
1326  // Recreate llvm.compiler.used.
1327  ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1328  auto *NewUsed = new GlobalVariable(
1329  *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1330  llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1331  NewUsed->setSection("llvm.metadata");
1332 }
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:118
The base class of the type hierarchy.
Definition: Type.h:1356
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:1294
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2564
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:50
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:149
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:370
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:775
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:122
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)