clang  14.0.0git
BackendUtil.cpp
Go to the documentation of this file.
1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
11 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Frontend/Utils.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/StackSafetyAnalysis.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeReader.h"
26 #include "llvm/Bitcode/BitcodeWriter.h"
27 #include "llvm/Bitcode/BitcodeWriterPass.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/SchedulerRegistry.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/IRPrintingPasses.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ModuleSummaryIndex.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/LTO/LTOBackend.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/Passes/PassBuilder.h"
42 #include "llvm/Passes/PassPlugin.h"
43 #include "llvm/Passes/StandardInstrumentations.h"
44 #include "llvm/Support/BuryPointer.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TimeProfiler.h"
50 #include "llvm/Support/Timer.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/Transforms/Coroutines.h"
56 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
57 #include "llvm/Transforms/Coroutines/CoroEarly.h"
58 #include "llvm/Transforms/Coroutines/CoroElide.h"
59 #include "llvm/Transforms/Coroutines/CoroSplit.h"
60 #include "llvm/Transforms/IPO.h"
61 #include "llvm/Transforms/IPO/AlwaysInliner.h"
62 #include "llvm/Transforms/IPO/LowerTypeTests.h"
63 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
64 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
65 #include "llvm/Transforms/InstCombine/InstCombine.h"
66 #include "llvm/Transforms/Instrumentation.h"
67 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
68 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
69 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
70 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
71 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
72 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
73 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
74 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
75 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
76 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
77 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
78 #include "llvm/Transforms/ObjCARC.h"
79 #include "llvm/Transforms/Scalar.h"
80 #include "llvm/Transforms/Scalar/EarlyCSE.h"
81 #include "llvm/Transforms/Scalar/GVN.h"
82 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
83 #include "llvm/Transforms/Utils.h"
84 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
85 #include "llvm/Transforms/Utils/Debugify.h"
86 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
87 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
88 #include "llvm/Transforms/Utils/SymbolRewriter.h"
89 #include <memory>
90 using namespace clang;
91 using namespace llvm;
92 
93 #define HANDLE_EXTENSION(Ext) \
94  llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
95 #include "llvm/Support/Extension.def"
96 
97 namespace {
98 
99 // Default filename used for profile generation.
100 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
101 
102 class EmitAssemblyHelper {
103  DiagnosticsEngine &Diags;
104  const HeaderSearchOptions &HSOpts;
105  const CodeGenOptions &CodeGenOpts;
106  const clang::TargetOptions &TargetOpts;
107  const LangOptions &LangOpts;
108  Module *TheModule;
109 
110  Timer CodeGenerationTime;
111 
112  std::unique_ptr<raw_pwrite_stream> OS;
113 
114  TargetIRAnalysis getTargetIRAnalysis() const {
115  if (TM)
116  return TM->getTargetIRAnalysis();
117 
118  return TargetIRAnalysis();
119  }
120 
121  void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
122 
123  /// Generates the TargetMachine.
124  /// Leaves TM unchanged if it is unable to create the target machine.
125  /// Some of our clang tests specify triples which are not built
126  /// into clang. This is okay because these tests check the generated
127  /// IR, and they require DataLayout which depends on the triple.
128  /// In this case, we allow this method to fail and not report an error.
129  /// When MustCreateTM is used, we print an error if we are unable to load
130  /// the requested target.
131  void CreateTargetMachine(bool MustCreateTM);
132 
133  /// Add passes necessary to emit assembly or LLVM IR.
134  ///
135  /// \return True on success.
136  bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
137  raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
138 
139  std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
140  std::error_code EC;
141  auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
142  llvm::sys::fs::OF_None);
143  if (EC) {
144  Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
145  F.reset();
146  }
147  return F;
148  }
149 
150 public:
151  EmitAssemblyHelper(DiagnosticsEngine &_Diags,
152  const HeaderSearchOptions &HeaderSearchOpts,
153  const CodeGenOptions &CGOpts,
154  const clang::TargetOptions &TOpts,
155  const LangOptions &LOpts, Module *M)
156  : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
157  TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
158  CodeGenerationTime("codegen", "Code Generation Time") {}
159 
160  ~EmitAssemblyHelper() {
161  if (CodeGenOpts.DisableFree)
162  BuryPointer(std::move(TM));
163  }
164 
165  std::unique_ptr<TargetMachine> TM;
166 
167  void EmitAssembly(BackendAction Action,
168  std::unique_ptr<raw_pwrite_stream> OS);
169 
170  void EmitAssemblyWithNewPassManager(BackendAction Action,
171  std::unique_ptr<raw_pwrite_stream> OS);
172 };
173 
174 // We need this wrapper to access LangOpts and CGOpts from extension functions
175 // that we add to the PassManagerBuilder.
176 class PassManagerBuilderWrapper : public PassManagerBuilder {
177 public:
178  PassManagerBuilderWrapper(const Triple &TargetTriple,
179  const CodeGenOptions &CGOpts,
180  const LangOptions &LangOpts)
181  : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
182  LangOpts(LangOpts) {}
183  const Triple &getTargetTriple() const { return TargetTriple; }
184  const CodeGenOptions &getCGOpts() const { return CGOpts; }
185  const LangOptions &getLangOpts() const { return LangOpts; }
186 
187 private:
188  const Triple &TargetTriple;
189  const CodeGenOptions &CGOpts;
190  const LangOptions &LangOpts;
191 };
192 }
193 
194 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
195  if (Builder.OptLevel > 0)
196  PM.add(createObjCARCAPElimPass());
197 }
198 
199 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
200  if (Builder.OptLevel > 0)
201  PM.add(createObjCARCExpandPass());
202 }
203 
204 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
205  if (Builder.OptLevel > 0)
206  PM.add(createObjCARCOptPass());
207 }
208 
209 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
210  legacy::PassManagerBase &PM) {
211  PM.add(createAddDiscriminatorsPass());
212 }
213 
214 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
215  legacy::PassManagerBase &PM) {
216  PM.add(createBoundsCheckingLegacyPass());
217 }
218 
219 static SanitizerCoverageOptions
221  SanitizerCoverageOptions Opts;
222  Opts.CoverageType =
223  static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
224  Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
225  Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
226  Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
227  Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
228  Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
229  Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
230  Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
231  Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
232  Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
233  Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
234  Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
235  Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
236  Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
237  return Opts;
238 }
239 
240 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
241  legacy::PassManagerBase &PM) {
242  const PassManagerBuilderWrapper &BuilderWrapper =
243  static_cast<const PassManagerBuilderWrapper &>(Builder);
244  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
245  auto Opts = getSancovOptsFromCGOpts(CGOpts);
246  PM.add(createModuleSanitizerCoverageLegacyPassPass(
247  Opts, CGOpts.SanitizeCoverageAllowlistFiles,
249 }
250 
251 // Check if ASan should use GC-friendly instrumentation for globals.
252 // First of all, there is no point if -fdata-sections is off (expect for MachO,
253 // where this is not a factor). Also, on ELF this feature requires an assembler
254 // extension that only works with -integrated-as at the moment.
255 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
256  if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
257  return false;
258  switch (T.getObjectFormat()) {
259  case Triple::MachO:
260  case Triple::COFF:
261  return true;
262  case Triple::ELF:
263  return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
264  case Triple::GOFF:
265  llvm::report_fatal_error("ASan not implemented for GOFF");
266  case Triple::XCOFF:
267  llvm::report_fatal_error("ASan not implemented for XCOFF.");
268  case Triple::Wasm:
269  case Triple::UnknownObjectFormat:
270  break;
271  }
272  return false;
273 }
274 
275 static void addMemProfilerPasses(const PassManagerBuilder &Builder,
276  legacy::PassManagerBase &PM) {
277  PM.add(createMemProfilerFunctionPass());
278  PM.add(createModuleMemProfilerLegacyPassPass());
279 }
280 
281 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
282  legacy::PassManagerBase &PM) {
283  const PassManagerBuilderWrapper &BuilderWrapper =
284  static_cast<const PassManagerBuilderWrapper&>(Builder);
285  const Triple &T = BuilderWrapper.getTargetTriple();
286  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
287  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
288  bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
289  bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
290  bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
291  llvm::AsanDtorKind DestructorKind = CGOpts.getSanitizeAddressDtor();
292  llvm::AsanDetectStackUseAfterReturnMode UseAfterReturn =
293  CGOpts.getSanitizeAddressUseAfterReturn();
294  PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
295  UseAfterScope, UseAfterReturn));
296  PM.add(createModuleAddressSanitizerLegacyPassPass(
297  /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator,
298  DestructorKind));
299 }
300 
301 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
302  legacy::PassManagerBase &PM) {
303  PM.add(createAddressSanitizerFunctionPass(
304  /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false,
305  /*UseAfterReturn*/ llvm::AsanDetectStackUseAfterReturnMode::Never));
306  PM.add(createModuleAddressSanitizerLegacyPassPass(
307  /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
308  /*UseOdrIndicator*/ false));
309 }
310 
311 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
312  legacy::PassManagerBase &PM) {
313  const PassManagerBuilderWrapper &BuilderWrapper =
314  static_cast<const PassManagerBuilderWrapper &>(Builder);
315  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
316  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
317  PM.add(createHWAddressSanitizerLegacyPassPass(
318  /*CompileKernel*/ false, Recover,
319  /*DisableOptimization*/ CGOpts.OptimizationLevel == 0));
320 }
321 
322 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
323  legacy::PassManagerBase &PM) {
324  const PassManagerBuilderWrapper &BuilderWrapper =
325  static_cast<const PassManagerBuilderWrapper &>(Builder);
326  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
327  PM.add(createHWAddressSanitizerLegacyPassPass(
328  /*CompileKernel*/ true, /*Recover*/ true,
329  /*DisableOptimization*/ CGOpts.OptimizationLevel == 0));
330 }
331 
332 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
333  legacy::PassManagerBase &PM,
334  bool CompileKernel) {
335  const PassManagerBuilderWrapper &BuilderWrapper =
336  static_cast<const PassManagerBuilderWrapper&>(Builder);
337  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
338  int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
339  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
340  PM.add(createMemorySanitizerLegacyPassPass(
341  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
342 
343  // MemorySanitizer inserts complex instrumentation that mostly follows
344  // the logic of the original code, but operates on "shadow" values.
345  // It can benefit from re-running some general purpose optimization passes.
346  if (Builder.OptLevel > 0) {
347  PM.add(createEarlyCSEPass());
348  PM.add(createReassociatePass());
349  PM.add(createLICMPass());
350  PM.add(createGVNPass());
351  PM.add(createInstructionCombiningPass());
352  PM.add(createDeadStoreEliminationPass());
353  }
354 }
355 
356 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
357  legacy::PassManagerBase &PM) {
358  addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
359 }
360 
361 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
362  legacy::PassManagerBase &PM) {
363  addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
364 }
365 
366 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
367  legacy::PassManagerBase &PM) {
368  PM.add(createThreadSanitizerLegacyPassPass());
369 }
370 
371 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
372  legacy::PassManagerBase &PM) {
373  const PassManagerBuilderWrapper &BuilderWrapper =
374  static_cast<const PassManagerBuilderWrapper&>(Builder);
375  const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
376  PM.add(createDataFlowSanitizerLegacyPassPass(LangOpts.NoSanitizeFiles));
377 }
378 
379 static void addEntryExitInstrumentationPass(const PassManagerBuilder &Builder,
380  legacy::PassManagerBase &PM) {
381  PM.add(createEntryExitInstrumenterPass());
382 }
383 
384 static void
385 addPostInlineEntryExitInstrumentationPass(const PassManagerBuilder &Builder,
386  legacy::PassManagerBase &PM) {
387  PM.add(createPostInlineEntryExitInstrumenterPass());
388 }
389 
390 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
391  const CodeGenOptions &CodeGenOpts) {
392  TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
393 
394  switch (CodeGenOpts.getVecLib()) {
396  TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
397  break;
399  switch(TargetTriple.getArch()) {
400  default:
401  break;
402  case llvm::Triple::x86_64:
403  TLII->addVectorizableFunctionsFromVecLib
404  (TargetLibraryInfoImpl::LIBMVEC_X86);
405  break;
406  }
407  break;
409  TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
410  break;
412  TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
413  break;
415  TLII->addVectorizableFunctionsFromVecLib(
416  TargetLibraryInfoImpl::DarwinLibSystemM);
417  break;
418  default:
419  break;
420  }
421  return TLII;
422 }
423 
424 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
425  legacy::PassManager *MPM) {
426  llvm::SymbolRewriter::RewriteDescriptorList DL;
427 
428  llvm::SymbolRewriter::RewriteMapParser MapParser;
429  for (const auto &MapFile : Opts.RewriteMapFiles)
430  MapParser.parse(MapFile, &DL);
431 
432  MPM->add(createRewriteSymbolsPass(DL));
433 }
434 
435 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
436  switch (CodeGenOpts.OptimizationLevel) {
437  default:
438  llvm_unreachable("Invalid optimization level!");
439  case 0:
440  return CodeGenOpt::None;
441  case 1:
442  return CodeGenOpt::Less;
443  case 2:
444  return CodeGenOpt::Default; // O2/Os/Oz
445  case 3:
446  return CodeGenOpt::Aggressive;
447  }
448 }
449 
451 getCodeModel(const CodeGenOptions &CodeGenOpts) {
452  unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
453  .Case("tiny", llvm::CodeModel::Tiny)
454  .Case("small", llvm::CodeModel::Small)
455  .Case("kernel", llvm::CodeModel::Kernel)
456  .Case("medium", llvm::CodeModel::Medium)
457  .Case("large", llvm::CodeModel::Large)
458  .Case("default", ~1u)
459  .Default(~0u);
460  assert(CodeModel != ~0u && "invalid code model!");
461  if (CodeModel == ~1u)
462  return None;
463  return static_cast<llvm::CodeModel::Model>(CodeModel);
464 }
465 
466 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
467  if (Action == Backend_EmitObj)
468  return CGFT_ObjectFile;
469  else if (Action == Backend_EmitMCNull)
470  return CGFT_Null;
471  else {
472  assert(Action == Backend_EmitAssembly && "Invalid action!");
473  return CGFT_AssemblyFile;
474  }
475 }
476 
478  llvm::TargetOptions &Options,
479  const CodeGenOptions &CodeGenOpts,
480  const clang::TargetOptions &TargetOpts,
481  const LangOptions &LangOpts,
482  const HeaderSearchOptions &HSOpts) {
483  switch (LangOpts.getThreadModel()) {
485  Options.ThreadModel = llvm::ThreadModel::POSIX;
486  break;
488  Options.ThreadModel = llvm::ThreadModel::Single;
489  break;
490  }
491 
492  // Set float ABI type.
493  assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
494  CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
495  "Invalid Floating Point ABI!");
496  Options.FloatABIType =
497  llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
498  .Case("soft", llvm::FloatABI::Soft)
499  .Case("softfp", llvm::FloatABI::Soft)
500  .Case("hard", llvm::FloatABI::Hard)
501  .Default(llvm::FloatABI::Default);
502 
503  // Set FP fusion mode.
504  switch (LangOpts.getDefaultFPContractMode()) {
506  // Preserve any contraction performed by the front-end. (Strict performs
507  // splitting of the muladd intrinsic in the backend.)
508  Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
509  break;
510  case LangOptions::FPM_On:
512  Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
513  break;
515  Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
516  break;
517  }
518 
519  Options.BinutilsVersion =
520  llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
521  Options.UseInitArray = CodeGenOpts.UseInitArray;
522  Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
523  Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
524  Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
525 
526  // Set EABI version.
527  Options.EABIVersion = TargetOpts.EABIVersion;
528 
529  if (LangOpts.hasSjLjExceptions())
530  Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
531  if (LangOpts.hasSEHExceptions())
532  Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
533  if (LangOpts.hasDWARFExceptions())
534  Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
535  if (LangOpts.hasWasmExceptions())
536  Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
537 
538  Options.NoInfsFPMath = LangOpts.NoHonorInfs;
539  Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
540  Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
541  Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
542 
543  Options.BBSections =
544  llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
545  .Case("all", llvm::BasicBlockSection::All)
546  .Case("labels", llvm::BasicBlockSection::Labels)
547  .StartsWith("list=", llvm::BasicBlockSection::List)
548  .Case("none", llvm::BasicBlockSection::None)
550 
551  if (Options.BBSections == llvm::BasicBlockSection::List) {
552  ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
553  MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
554  if (!MBOrErr) {
555  Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
556  << MBOrErr.getError().message();
557  return false;
558  }
559  Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
560  }
561 
562  Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
563  Options.FunctionSections = CodeGenOpts.FunctionSections;
564  Options.DataSections = CodeGenOpts.DataSections;
565  Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
566  Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
567  Options.UniqueBasicBlockSectionNames =
568  CodeGenOpts.UniqueBasicBlockSectionNames;
569  Options.TLSSize = CodeGenOpts.TLSSize;
570  Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
571  Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
572  Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
573  Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
574  Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
575  Options.EmitAddrsig = CodeGenOpts.Addrsig;
576  Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
577  Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
578  Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
579  Options.PseudoProbeForProfiling = CodeGenOpts.PseudoProbeForProfiling;
580  Options.ValueTrackingVariableLocations =
581  CodeGenOpts.ValueTrackingVariableLocations;
582  Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
583  Options.LoopAlignment = CodeGenOpts.LoopAlignment;
584 
585  switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
587  Options.SwiftAsyncFramePointer =
588  SwiftAsyncFramePointerMode::DeploymentBased;
589  break;
590 
592  Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
593  break;
594 
596  Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
597  break;
598  }
599 
600  Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
601  Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
602  Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
603  Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
604  Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
605  Options.MCOptions.MCIncrementalLinkerCompatible =
606  CodeGenOpts.IncrementalLinkerCompatible;
607  Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
608  Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
609  Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
610  Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
611  Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
612  Options.MCOptions.ABIName = TargetOpts.ABI;
613  for (const auto &Entry : HSOpts.UserEntries)
614  if (!Entry.IsFramework &&
615  (Entry.Group == frontend::IncludeDirGroup::Quoted ||
616  Entry.Group == frontend::IncludeDirGroup::Angled ||
617  Entry.Group == frontend::IncludeDirGroup::System))
618  Options.MCOptions.IASSearchPaths.push_back(
619  Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
620  Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
621  Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
622  Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
623 
624  return true;
625 }
626 
628  const LangOptions &LangOpts) {
629  if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
630  return None;
631  // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
632  // LLVM's -default-gcov-version flag is set to something invalid.
633  GCOVOptions Options;
634  Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
635  Options.EmitData = CodeGenOpts.EmitGcovArcs;
636  llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
637  Options.NoRedZone = CodeGenOpts.DisableRedZone;
638  Options.Filter = CodeGenOpts.ProfileFilterFiles;
639  Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
640  Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
641  return Options;
642 }
643 
646  const LangOptions &LangOpts) {
647  if (!CodeGenOpts.hasProfileClangInstr())
648  return None;
649  InstrProfOptions Options;
650  Options.NoRedZone = CodeGenOpts.DisableRedZone;
651  Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
652  Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
653  return Options;
654 }
655 
656 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
657  legacy::FunctionPassManager &FPM) {
658  // Handle disabling of all LLVM passes, where we want to preserve the
659  // internal module before any optimization.
660  if (CodeGenOpts.DisableLLVMPasses)
661  return;
662 
663  // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
664  // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
665  // are inserted before PMBuilder ones - they'd get the default-constructed
666  // TLI with an unknown target otherwise.
667  Triple TargetTriple(TheModule->getTargetTriple());
668  std::unique_ptr<TargetLibraryInfoImpl> TLII(
669  createTLII(TargetTriple, CodeGenOpts));
670 
671  // If we reached here with a non-empty index file name, then the index file
672  // was empty and we are not performing ThinLTO backend compilation (used in
673  // testing in a distributed build environment). Drop any the type test
674  // assume sequences inserted for whole program vtables so that codegen doesn't
675  // complain.
676  if (!CodeGenOpts.ThinLTOIndexFile.empty())
677  MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
678  /*ImportSummary=*/nullptr,
679  /*DropTypeTests=*/true));
680 
681  PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
682 
683  // At O0 and O1 we only run the always inliner which is more efficient. At
684  // higher optimization levels we run the normal inliner.
685  if (CodeGenOpts.OptimizationLevel <= 1) {
686  bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
687  !CodeGenOpts.DisableLifetimeMarkers) ||
688  LangOpts.Coroutines);
689  PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
690  } else {
691  // We do not want to inline hot callsites for SamplePGO module-summary build
692  // because profile annotation will happen again in ThinLTO backend, and we
693  // want the IR of the hot path to match the profile.
694  PMBuilder.Inliner = createFunctionInliningPass(
695  CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
696  (!CodeGenOpts.SampleProfileFile.empty() &&
697  CodeGenOpts.PrepareForThinLTO));
698  }
699 
700  PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
701  PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
702  PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
703  PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
704  // Only enable CGProfilePass when using integrated assembler, since
705  // non-integrated assemblers don't recognize .cgprofile section.
706  PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
707 
708  PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
709  // Loop interleaving in the loop vectorizer has historically been set to be
710  // enabled when loop unrolling is enabled.
711  PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
712  PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
713  PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
714  PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
715  PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
716 
717  MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
718 
719  if (TM)
720  TM->adjustPassManager(PMBuilder);
721 
722  if (CodeGenOpts.DebugInfoForProfiling ||
723  !CodeGenOpts.SampleProfileFile.empty())
724  PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
726 
727  // In ObjC ARC mode, add the main ARC optimization passes.
728  if (LangOpts.ObjCAutoRefCount) {
729  PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
731  PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
733  PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
735  }
736 
737  if (LangOpts.Coroutines)
738  addCoroutinePassesToExtensionPoints(PMBuilder);
739 
740  if (!CodeGenOpts.MemoryProfileOutput.empty()) {
741  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
743  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
745  }
746 
747  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
748  PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
750  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
752  }
753 
754  if (CodeGenOpts.hasSanitizeCoverage()) {
755  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
757  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
759  }
760 
761  if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
762  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
764  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
766  }
767 
768  if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
769  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
771  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
773  }
774 
775  if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
776  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
778  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
780  }
781 
782  if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
783  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
785  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
787  }
788 
789  if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
790  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
792  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
794  }
795 
796  if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
797  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
799  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
801  }
802 
803  if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
804  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
806  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
808  }
809 
810  if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
811  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
813  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
815  }
816 
817  if (CodeGenOpts.InstrumentFunctions ||
818  CodeGenOpts.InstrumentFunctionEntryBare ||
819  CodeGenOpts.InstrumentFunctionsAfterInlining ||
820  CodeGenOpts.InstrumentForProfiling) {
821  PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
823  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
825  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
827  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
829  }
830 
831  // Set up the per-function pass manager.
832  FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
833  if (CodeGenOpts.VerifyModule)
834  FPM.add(createVerifierPass());
835 
836  // Set up the per-module pass manager.
837  if (!CodeGenOpts.RewriteMapFiles.empty())
838  addSymbolRewriterPass(CodeGenOpts, &MPM);
839 
840  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
841  MPM.add(createGCOVProfilerPass(*Options));
842  if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
843  MPM.add(createStripSymbolsPass(true));
844  }
845 
846  if (Optional<InstrProfOptions> Options =
847  getInstrProfOptions(CodeGenOpts, LangOpts))
848  MPM.add(createInstrProfilingLegacyPass(*Options, false));
849 
850  bool hasIRInstr = false;
851  if (CodeGenOpts.hasProfileIRInstr()) {
852  PMBuilder.EnablePGOInstrGen = true;
853  hasIRInstr = true;
854  }
855  if (CodeGenOpts.hasProfileCSIRInstr()) {
856  assert(!CodeGenOpts.hasProfileCSIRUse() &&
857  "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
858  "same time");
859  assert(!hasIRInstr &&
860  "Cannot have both ProfileGen pass and CSProfileGen pass at the "
861  "same time");
862  PMBuilder.EnablePGOCSInstrGen = true;
863  hasIRInstr = true;
864  }
865  if (hasIRInstr) {
866  if (!CodeGenOpts.InstrProfileOutput.empty())
867  PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
868  else
869  PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
870  }
871  if (CodeGenOpts.hasProfileIRUse()) {
872  PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
873  PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
874  }
875 
876  if (!CodeGenOpts.SampleProfileFile.empty())
877  PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
878 
879  PMBuilder.populateFunctionPassManager(FPM);
880  PMBuilder.populateModulePassManager(MPM);
881 }
882 
883 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
884  SmallVector<const char *, 16> BackendArgs;
885  BackendArgs.push_back("clang"); // Fake program name.
886  if (!CodeGenOpts.DebugPass.empty()) {
887  BackendArgs.push_back("-debug-pass");
888  BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
889  }
890  if (!CodeGenOpts.LimitFloatPrecision.empty()) {
891  BackendArgs.push_back("-limit-float-precision");
892  BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
893  }
894  // Check for the default "clang" invocation that won't set any cl::opt values.
895  // Skip trying to parse the command line invocation to avoid the issues
896  // described below.
897  if (BackendArgs.size() == 1)
898  return;
899  BackendArgs.push_back(nullptr);
900  // FIXME: The command line parser below is not thread-safe and shares a global
901  // state, so this call might crash or overwrite the options of another Clang
902  // instance in the same process.
903  llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
904  BackendArgs.data());
905 }
906 
907 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
908  // Create the TargetMachine for generating code.
910  std::string Triple = TheModule->getTargetTriple();
911  const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
912  if (!TheTarget) {
913  if (MustCreateTM)
914  Diags.Report(diag::err_fe_unable_to_create_target) << Error;
915  return;
916  }
917 
919  std::string FeaturesStr =
920  llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
921  llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
922  CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
923 
924  llvm::TargetOptions Options;
925  if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
926  HSOpts))
927  return;
928  TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
929  Options, RM, CM, OptLevel));
930 }
931 
932 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
933  BackendAction Action,
934  raw_pwrite_stream &OS,
935  raw_pwrite_stream *DwoOS) {
936  // Add LibraryInfo.
937  llvm::Triple TargetTriple(TheModule->getTargetTriple());
938  std::unique_ptr<TargetLibraryInfoImpl> TLII(
939  createTLII(TargetTriple, CodeGenOpts));
940  CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
941 
942  // Normal mode, emit a .s or .o file by running the code generator. Note,
943  // this also adds codegenerator level optimization passes.
944  CodeGenFileType CGFT = getCodeGenFileType(Action);
945 
946  // Add ObjC ARC final-cleanup optimizations. This is done as part of the
947  // "codegen" passes so that it isn't run multiple times when there is
948  // inlining happening.
949  if (CodeGenOpts.OptimizationLevel > 0)
950  CodeGenPasses.add(createObjCARCContractPass());
951 
952  if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
953  /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
954  Diags.Report(diag::err_fe_unable_to_interface_with_target);
955  return false;
956  }
957 
958  return true;
959 }
960 
962  std::unique_ptr<raw_pwrite_stream> OS) {
963  TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
964 
965  setCommandLineOpts(CodeGenOpts);
966 
967  bool UsesCodeGen = (Action != Backend_EmitNothing &&
968  Action != Backend_EmitBC &&
969  Action != Backend_EmitLL);
970  CreateTargetMachine(UsesCodeGen);
971 
972  if (UsesCodeGen && !TM)
973  return;
974  if (TM)
975  TheModule->setDataLayout(TM->createDataLayout());
976 
977  DebugifyCustomPassManager PerModulePasses;
978  DebugInfoPerPassMap DIPreservationMap;
979  if (CodeGenOpts.EnableDIPreservationVerify) {
980  PerModulePasses.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
981  PerModulePasses.setDIPreservationMap(DIPreservationMap);
982 
983  if (!CodeGenOpts.DIBugsReportFilePath.empty())
984  PerModulePasses.setOrigDIVerifyBugsReportFilePath(
985  CodeGenOpts.DIBugsReportFilePath);
986  }
987  PerModulePasses.add(
988  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
989 
990  legacy::FunctionPassManager PerFunctionPasses(TheModule);
991  PerFunctionPasses.add(
992  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
993 
994  CreatePasses(PerModulePasses, PerFunctionPasses);
995 
996  legacy::PassManager CodeGenPasses;
997  CodeGenPasses.add(
998  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
999 
1000  std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1001 
1002  switch (Action) {
1003  case Backend_EmitNothing:
1004  break;
1005 
1006  case Backend_EmitBC:
1007  if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1008  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1009  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1010  if (!ThinLinkOS)
1011  return;
1012  }
1013  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1014  CodeGenOpts.EnableSplitLTOUnit);
1015  PerModulePasses.add(createWriteThinLTOBitcodePass(
1016  *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1017  } else {
1018  // Emit a module summary by default for Regular LTO except for ld64
1019  // targets
1020  bool EmitLTOSummary =
1021  (CodeGenOpts.PrepareForLTO &&
1022  !CodeGenOpts.DisableLLVMPasses &&
1023  llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1024  llvm::Triple::Apple);
1025  if (EmitLTOSummary) {
1026  if (!TheModule->getModuleFlag("ThinLTO"))
1027  TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1028  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1029  uint32_t(1));
1030  }
1031 
1032  PerModulePasses.add(createBitcodeWriterPass(
1033  *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1034  }
1035  break;
1036 
1037  case Backend_EmitLL:
1038  PerModulePasses.add(
1039  createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1040  break;
1041 
1042  default:
1043  if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1044  DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1045  if (!DwoOS)
1046  return;
1047  }
1048  if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1049  DwoOS ? &DwoOS->os() : nullptr))
1050  return;
1051  }
1052 
1053  // Before executing passes, print the final values of the LLVM options.
1054  cl::PrintOptionValues();
1055 
1056  // Run passes. For now we do all passes at once, but eventually we
1057  // would like to have the option of streaming code generation.
1058 
1059  {
1060  PrettyStackTraceString CrashInfo("Per-function optimization");
1061  llvm::TimeTraceScope TimeScope("PerFunctionPasses");
1062 
1063  PerFunctionPasses.doInitialization();
1064  for (Function &F : *TheModule)
1065  if (!F.isDeclaration())
1066  PerFunctionPasses.run(F);
1067  PerFunctionPasses.doFinalization();
1068  }
1069 
1070  {
1071  PrettyStackTraceString CrashInfo("Per-module optimization passes");
1072  llvm::TimeTraceScope TimeScope("PerModulePasses");
1073  PerModulePasses.run(*TheModule);
1074  }
1075 
1076  {
1077  PrettyStackTraceString CrashInfo("Code generation");
1078  llvm::TimeTraceScope TimeScope("CodeGenPasses");
1079  CodeGenPasses.run(*TheModule);
1080  }
1081 
1082  if (ThinLinkOS)
1083  ThinLinkOS->keep();
1084  if (DwoOS)
1085  DwoOS->keep();
1086 }
1087 
1088 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
1089  switch (Opts.OptimizationLevel) {
1090  default:
1091  llvm_unreachable("Invalid optimization level!");
1092 
1093  case 0:
1094  return OptimizationLevel::O0;
1095 
1096  case 1:
1097  return OptimizationLevel::O1;
1098 
1099  case 2:
1100  switch (Opts.OptimizeSize) {
1101  default:
1102  llvm_unreachable("Invalid optimization level for size!");
1103 
1104  case 0:
1105  return OptimizationLevel::O2;
1106 
1107  case 1:
1108  return OptimizationLevel::Os;
1109 
1110  case 2:
1111  return OptimizationLevel::Oz;
1112  }
1113 
1114  case 3:
1115  return OptimizationLevel::O3;
1116  }
1117 }
1118 
1119 static void addSanitizers(const Triple &TargetTriple,
1120  const CodeGenOptions &CodeGenOpts,
1121  const LangOptions &LangOpts, PassBuilder &PB) {
1122  PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
1123  OptimizationLevel Level) {
1124  if (CodeGenOpts.hasSanitizeCoverage()) {
1125  auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1126  MPM.addPass(ModuleSanitizerCoveragePass(
1127  SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1128  CodeGenOpts.SanitizeCoverageIgnorelistFiles));
1129  }
1130 
1131  auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1132  if (LangOpts.Sanitize.has(Mask)) {
1133  int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1134  bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1135 
1136  MPM.addPass(
1137  ModuleMemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
1138  FunctionPassManager FPM;
1139  FPM.addPass(
1140  MemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
1141  if (Level != OptimizationLevel::O0) {
1142  // MemorySanitizer inserts complex instrumentation that mostly
1143  // follows the logic of the original code, but operates on
1144  // "shadow" values. It can benefit from re-running some
1145  // general purpose optimization passes.
1146  FPM.addPass(EarlyCSEPass());
1147  // TODO: Consider add more passes like in
1148  // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
1149  // difference on size. It's not clear if the rest is still
1150  // usefull. InstCombinePass breakes
1151  // compiler-rt/test/msan/select_origin.cpp.
1152  }
1153  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1154  }
1155  };
1156  MSanPass(SanitizerKind::Memory, false);
1157  MSanPass(SanitizerKind::KernelMemory, true);
1158 
1159  if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1160  MPM.addPass(ModuleThreadSanitizerPass());
1161  MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1162  }
1163 
1164  auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1165  if (LangOpts.Sanitize.has(Mask)) {
1166  bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1167  bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1168  bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1169  bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1170  llvm::AsanDtorKind DestructorKind =
1171  CodeGenOpts.getSanitizeAddressDtor();
1172  llvm::AsanDetectStackUseAfterReturnMode UseAfterReturn =
1173  CodeGenOpts.getSanitizeAddressUseAfterReturn();
1174  MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1175  MPM.addPass(ModuleAddressSanitizerPass(
1176  CompileKernel, Recover, ModuleUseAfterScope, UseOdrIndicator,
1177  DestructorKind));
1178  MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1179  {CompileKernel, Recover, UseAfterScope, UseAfterReturn})));
1180  }
1181  };
1182  ASanPass(SanitizerKind::Address, false);
1183  ASanPass(SanitizerKind::KernelAddress, true);
1184 
1185  auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1186  if (LangOpts.Sanitize.has(Mask)) {
1187  bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1188  MPM.addPass(HWAddressSanitizerPass(
1189  {CompileKernel, Recover,
1190  /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
1191  }
1192  };
1193  HWASanPass(SanitizerKind::HWAddress, false);
1194  HWASanPass(SanitizerKind::KernelHWAddress, true);
1195 
1196  if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
1197  MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
1198  }
1199  });
1200 }
1201 
1202 /// A clean version of `EmitAssembly` that uses the new pass manager.
1203 ///
1204 /// Not all features are currently supported in this system, but where
1205 /// necessary it falls back to the legacy pass manager to at least provide
1206 /// basic functionality.
1207 ///
1208 /// This API is planned to have its functionality finished and then to replace
1209 /// `EmitAssembly` at some point in the future when the default switches.
1210 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1211  BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1212  TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1213  setCommandLineOpts(CodeGenOpts);
1214 
1215  bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1216  Action != Backend_EmitBC &&
1217  Action != Backend_EmitLL);
1218  CreateTargetMachine(RequiresCodeGen);
1219 
1220  if (RequiresCodeGen && !TM)
1221  return;
1222  if (TM)
1223  TheModule->setDataLayout(TM->createDataLayout());
1224 
1225  Optional<PGOOptions> PGOOpt;
1226 
1227  if (CodeGenOpts.hasProfileIRInstr())
1228  // -fprofile-generate.
1229  PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1230  ? std::string(DefaultProfileGenName)
1231  : CodeGenOpts.InstrProfileOutput,
1232  "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1233  CodeGenOpts.DebugInfoForProfiling);
1234  else if (CodeGenOpts.hasProfileIRUse()) {
1235  // -fprofile-use.
1236  auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1237  : PGOOptions::NoCSAction;
1238  PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1239  CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1240  CSAction, CodeGenOpts.DebugInfoForProfiling);
1241  } else if (!CodeGenOpts.SampleProfileFile.empty())
1242  // -fprofile-sample-use
1243  PGOOpt = PGOOptions(
1244  CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
1245  PGOOptions::SampleUse, PGOOptions::NoCSAction,
1246  CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
1247  else if (CodeGenOpts.PseudoProbeForProfiling)
1248  // -fpseudo-probe-for-profiling
1249  PGOOpt =
1250  PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
1251  CodeGenOpts.DebugInfoForProfiling, true);
1252  else if (CodeGenOpts.DebugInfoForProfiling)
1253  // -fdebug-info-for-profiling
1254  PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1255  PGOOptions::NoCSAction, true);
1256 
1257  // Check to see if we want to generate a CS profile.
1258  if (CodeGenOpts.hasProfileCSIRInstr()) {
1259  assert(!CodeGenOpts.hasProfileCSIRUse() &&
1260  "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1261  "the same time");
1262  if (PGOOpt.hasValue()) {
1263  assert(PGOOpt->Action != PGOOptions::IRInstr &&
1264  PGOOpt->Action != PGOOptions::SampleUse &&
1265  "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1266  " pass");
1267  PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1268  ? std::string(DefaultProfileGenName)
1269  : CodeGenOpts.InstrProfileOutput;
1270  PGOOpt->CSAction = PGOOptions::CSIRInstr;
1271  } else
1272  PGOOpt = PGOOptions("",
1273  CodeGenOpts.InstrProfileOutput.empty()
1274  ? std::string(DefaultProfileGenName)
1275  : CodeGenOpts.InstrProfileOutput,
1276  "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1277  CodeGenOpts.DebugInfoForProfiling);
1278  }
1279  if (TM)
1280  TM->setPGOOption(PGOOpt);
1281 
1282  PipelineTuningOptions PTO;
1283  PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1284  // For historical reasons, loop interleaving is set to mirror setting for loop
1285  // unrolling.
1286  PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1287  PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1288  PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1289  PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
1290  // Only enable CGProfilePass when using integrated assembler, since
1291  // non-integrated assemblers don't recognize .cgprofile section.
1292  PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1293 
1294  LoopAnalysisManager LAM;
1295  FunctionAnalysisManager FAM;
1296  CGSCCAnalysisManager CGAM;
1297  ModuleAnalysisManager MAM;
1298 
1299  bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
1300  PassInstrumentationCallbacks PIC;
1301  PrintPassOptions PrintPassOpts;
1302  PrintPassOpts.Indent = DebugPassStructure;
1303  PrintPassOpts.SkipAnalyses = DebugPassStructure;
1304  StandardInstrumentations SI(CodeGenOpts.DebugPassManager ||
1305  DebugPassStructure,
1306  /*VerifyEach*/ false, PrintPassOpts);
1307  SI.registerCallbacks(PIC, &FAM);
1308  PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1309 
1310  // Attempt to load pass plugins and register their callbacks with PB.
1311  for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1312  auto PassPlugin = PassPlugin::Load(PluginFN);
1313  if (PassPlugin) {
1314  PassPlugin->registerPassBuilderCallbacks(PB);
1315  } else {
1316  Diags.Report(diag::err_fe_unable_to_load_plugin)
1317  << PluginFN << toString(PassPlugin.takeError());
1318  }
1319  }
1320 #define HANDLE_EXTENSION(Ext) \
1321  get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1322 #include "llvm/Support/Extension.def"
1323 
1324  // Register the AA manager first so that our version is the one used.
1325  FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1326 
1327  // Register the target library analysis directly and give it a customized
1328  // preset TLI.
1329  Triple TargetTriple(TheModule->getTargetTriple());
1330  std::unique_ptr<TargetLibraryInfoImpl> TLII(
1331  createTLII(TargetTriple, CodeGenOpts));
1332  FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1333 
1334  // Register all the basic analyses with the managers.
1335  PB.registerModuleAnalyses(MAM);
1336  PB.registerCGSCCAnalyses(CGAM);
1337  PB.registerFunctionAnalyses(FAM);
1338  PB.registerLoopAnalyses(LAM);
1339  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1340 
1341  ModulePassManager MPM;
1342 
1343  if (!CodeGenOpts.DisableLLVMPasses) {
1344  // Map our optimization levels into one of the distinct levels used to
1345  // configure the pipeline.
1346  OptimizationLevel Level = mapToLevel(CodeGenOpts);
1347 
1348  bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1349  bool IsLTO = CodeGenOpts.PrepareForLTO;
1350 
1351  if (LangOpts.ObjCAutoRefCount) {
1352  PB.registerPipelineStartEPCallback(
1353  [](ModulePassManager &MPM, OptimizationLevel Level) {
1354  if (Level != OptimizationLevel::O0)
1355  MPM.addPass(
1356  createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1357  });
1358  PB.registerPipelineEarlySimplificationEPCallback(
1359  [](ModulePassManager &MPM, OptimizationLevel Level) {
1360  if (Level != OptimizationLevel::O0)
1361  MPM.addPass(ObjCARCAPElimPass());
1362  });
1363  PB.registerScalarOptimizerLateEPCallback(
1364  [](FunctionPassManager &FPM, OptimizationLevel Level) {
1365  if (Level != OptimizationLevel::O0)
1366  FPM.addPass(ObjCARCOptPass());
1367  });
1368  }
1369 
1370  // If we reached here with a non-empty index file name, then the index
1371  // file was empty and we are not performing ThinLTO backend compilation
1372  // (used in testing in a distributed build environment).
1373  bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
1374  // If so drop any the type test assume sequences inserted for whole program
1375  // vtables so that codegen doesn't complain.
1376  if (IsThinLTOPostLink)
1377  PB.registerPipelineStartEPCallback(
1378  [](ModulePassManager &MPM, OptimizationLevel Level) {
1379  MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1380  /*ImportSummary=*/nullptr,
1381  /*DropTypeTests=*/true));
1382  });
1383 
1384  if (CodeGenOpts.InstrumentFunctions ||
1385  CodeGenOpts.InstrumentFunctionEntryBare ||
1386  CodeGenOpts.InstrumentFunctionsAfterInlining ||
1387  CodeGenOpts.InstrumentForProfiling) {
1388  PB.registerPipelineStartEPCallback(
1389  [](ModulePassManager &MPM, OptimizationLevel Level) {
1390  MPM.addPass(createModuleToFunctionPassAdaptor(
1391  EntryExitInstrumenterPass(/*PostInlining=*/false)));
1392  });
1393  PB.registerOptimizerLastEPCallback(
1394  [](ModulePassManager &MPM, OptimizationLevel Level) {
1395  MPM.addPass(createModuleToFunctionPassAdaptor(
1396  EntryExitInstrumenterPass(/*PostInlining=*/true)));
1397  });
1398  }
1399 
1400  // Register callbacks to schedule sanitizer passes at the appropriate part
1401  // of the pipeline.
1402  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1403  PB.registerScalarOptimizerLateEPCallback(
1404  [](FunctionPassManager &FPM, OptimizationLevel Level) {
1405  FPM.addPass(BoundsCheckingPass());
1406  });
1407 
1408  // Don't add sanitizers if we are here from ThinLTO PostLink. That already
1409  // done on PreLink stage.
1410  if (!IsThinLTOPostLink)
1411  addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1412 
1413  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1414  PB.registerPipelineStartEPCallback(
1415  [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1416  MPM.addPass(GCOVProfilerPass(*Options));
1417  });
1418  if (Optional<InstrProfOptions> Options =
1419  getInstrProfOptions(CodeGenOpts, LangOpts))
1420  PB.registerPipelineStartEPCallback(
1421  [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1422  MPM.addPass(InstrProfiling(*Options, false));
1423  });
1424 
1425  if (CodeGenOpts.OptimizationLevel == 0) {
1426  MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
1427  } else if (IsThinLTO) {
1428  MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
1429  } else if (IsLTO) {
1430  MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
1431  } else {
1432  MPM = PB.buildPerModuleDefaultPipeline(Level);
1433  }
1434 
1435  if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1436  MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1437  MPM.addPass(ModuleMemProfilerPass());
1438  }
1439  }
1440 
1441  // FIXME: We still use the legacy pass manager to do code generation. We
1442  // create that pass manager here and use it as needed below.
1443  legacy::PassManager CodeGenPasses;
1444  bool NeedCodeGen = false;
1445  std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1446 
1447  // Append any output we need to the pass manager.
1448  switch (Action) {
1449  case Backend_EmitNothing:
1450  break;
1451 
1452  case Backend_EmitBC:
1453  if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1454  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1455  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1456  if (!ThinLinkOS)
1457  return;
1458  }
1459  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1460  CodeGenOpts.EnableSplitLTOUnit);
1461  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1462  : nullptr));
1463  } else {
1464  // Emit a module summary by default for Regular LTO except for ld64
1465  // targets
1466  bool EmitLTOSummary =
1467  (CodeGenOpts.PrepareForLTO &&
1468  !CodeGenOpts.DisableLLVMPasses &&
1469  llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1470  llvm::Triple::Apple);
1471  if (EmitLTOSummary) {
1472  if (!TheModule->getModuleFlag("ThinLTO"))
1473  TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1474  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1475  uint32_t(1));
1476  }
1477  MPM.addPass(
1478  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1479  }
1480  break;
1481 
1482  case Backend_EmitLL:
1483  MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1484  break;
1485 
1486  case Backend_EmitAssembly:
1487  case Backend_EmitMCNull:
1488  case Backend_EmitObj:
1489  NeedCodeGen = true;
1490  CodeGenPasses.add(
1491  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1492  if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1493  DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1494  if (!DwoOS)
1495  return;
1496  }
1497  if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1498  DwoOS ? &DwoOS->os() : nullptr))
1499  // FIXME: Should we handle this error differently?
1500  return;
1501  break;
1502  }
1503 
1504  // Before executing passes, print the final values of the LLVM options.
1505  cl::PrintOptionValues();
1506 
1507  // Now that we have all of the passes ready, run them.
1508  {
1509  PrettyStackTraceString CrashInfo("Optimizer");
1510  MPM.run(*TheModule, MAM);
1511  }
1512 
1513  // Now if needed, run the legacy PM for codegen.
1514  if (NeedCodeGen) {
1515  PrettyStackTraceString CrashInfo("Code generation");
1516  CodeGenPasses.run(*TheModule);
1517  }
1518 
1519  if (ThinLinkOS)
1520  ThinLinkOS->keep();
1521  if (DwoOS)
1522  DwoOS->keep();
1523 }
1524 
1525 static void runThinLTOBackend(
1526  DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1527  const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1528  const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1529  std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1530  std::string ProfileRemapping, BackendAction Action) {
1531  StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1532  ModuleToDefinedGVSummaries;
1533  CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1534 
1535  setCommandLineOpts(CGOpts);
1536 
1537  // We can simply import the values mentioned in the combined index, since
1538  // we should only invoke this using the individual indexes written out
1539  // via a WriteIndexesThinBackend.
1540  FunctionImporter::ImportMapTy ImportList;
1541  if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1542  return;
1543 
1544  auto AddStream = [&](size_t Task) {
1545  return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1546  };
1547  lto::Config Conf;
1548  if (CGOpts.SaveTempsFilePrefix != "") {
1549  if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1550  /* UseInputModulePath */ false)) {
1551  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1552  errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1553  << '\n';
1554  });
1555  }
1556  }
1557  Conf.CPU = TOpts.CPU;
1558  Conf.CodeModel = getCodeModel(CGOpts);
1559  Conf.MAttrs = TOpts.Features;
1560  Conf.RelocModel = CGOpts.RelocationModel;
1561  Conf.CGOptLevel = getCGOptLevel(CGOpts);
1562  Conf.OptLevel = CGOpts.OptimizationLevel;
1563  initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1564  Conf.SampleProfile = std::move(SampleProfile);
1565  Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1566  // For historical reasons, loop interleaving is set to mirror setting for loop
1567  // unrolling.
1568  Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1569  Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1570  Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1571  // Only enable CGProfilePass when using integrated assembler, since
1572  // non-integrated assemblers don't recognize .cgprofile section.
1573  Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1574 
1575  // Context sensitive profile.
1576  if (CGOpts.hasProfileCSIRInstr()) {
1577  Conf.RunCSIRInstr = true;
1578  Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1579  } else if (CGOpts.hasProfileCSIRUse()) {
1580  Conf.RunCSIRInstr = false;
1581  Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1582  }
1583 
1584  Conf.ProfileRemapping = std::move(ProfileRemapping);
1585  Conf.UseNewPM = !CGOpts.LegacyPassManager;
1586  Conf.DebugPassManager = CGOpts.DebugPassManager;
1587  Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1588  Conf.RemarksFilename = CGOpts.OptRecordFile;
1589  Conf.RemarksPasses = CGOpts.OptRecordPasses;
1590  Conf.RemarksFormat = CGOpts.OptRecordFormat;
1591  Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1592  Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1593  switch (Action) {
1594  case Backend_EmitNothing:
1595  Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1596  return false;
1597  };
1598  break;
1599  case Backend_EmitLL:
1600  Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1601  M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1602  return false;
1603  };
1604  break;
1605  case Backend_EmitBC:
1606  Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1607  WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1608  return false;
1609  };
1610  break;
1611  default:
1612  Conf.CGFileType = getCodeGenFileType(Action);
1613  break;
1614  }
1615  if (Error E =
1616  thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1617  ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1618  /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1619  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1620  errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1621  });
1622  }
1623 }
1624 
1626  const HeaderSearchOptions &HeaderOpts,
1627  const CodeGenOptions &CGOpts,
1628  const clang::TargetOptions &TOpts,
1629  const LangOptions &LOpts,
1630  StringRef TDesc, Module *M,
1631  BackendAction Action,
1632  std::unique_ptr<raw_pwrite_stream> OS) {
1633 
1634  llvm::TimeTraceScope TimeScope("Backend");
1635 
1636  std::unique_ptr<llvm::Module> EmptyModule;
1637  if (!CGOpts.ThinLTOIndexFile.empty()) {
1638  // If we are performing a ThinLTO importing compile, load the function index
1639  // into memory and pass it into runThinLTOBackend, which will run the
1640  // function importer and invoke LTO passes.
1642  llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1643  /*IgnoreEmptyThinLTOIndexFile*/true);
1644  if (!IndexOrErr) {
1645  logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1646  "Error loading index file '" +
1647  CGOpts.ThinLTOIndexFile + "': ");
1648  return;
1649  }
1650  std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1651  // A null CombinedIndex means we should skip ThinLTO compilation
1652  // (LLVM will optionally ignore empty index files, returning null instead
1653  // of an error).
1654  if (CombinedIndex) {
1655  if (!CombinedIndex->skipModuleByDistributedBackend()) {
1656  runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1657  TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1658  CGOpts.ProfileRemappingFile, Action);
1659  return;
1660  }
1661  // Distributed indexing detected that nothing from the module is needed
1662  // for the final linking. So we can skip the compilation. We sill need to
1663  // output an empty object file to make sure that a linker does not fail
1664  // trying to read it. Also for some features, like CFI, we must skip
1665  // the compilation as CombinedIndex does not contain all required
1666  // information.
1667  EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1668  EmptyModule->setTargetTriple(M->getTargetTriple());
1669  M = EmptyModule.get();
1670  }
1671  }
1672 
1673  EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1674 
1675  if (!CGOpts.LegacyPassManager)
1676  AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1677  else
1678  AsmHelper.EmitAssembly(Action, std::move(OS));
1679 
1680  // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1681  // DataLayout.
1682  if (AsmHelper.TM) {
1683  std::string DLDesc = M->getDataLayout().getStringRepresentation();
1684  if (DLDesc != TDesc) {
1685  unsigned DiagID = Diags.getCustomDiagID(
1686  DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1687  "expected target description '%1'");
1688  Diags.Report(DiagID) << DLDesc << TDesc;
1689  }
1690  }
1691 }
1692 
1693 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1694 // __LLVM,__bitcode section.
1695 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1696  llvm::MemoryBufferRef Buf) {
1697  if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1698  return;
1699  llvm::EmbedBitcodeInModule(
1700  *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1701  CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1702  CGOpts.CmdArgs);
1703 }
clang::CodeGenOptions::BinutilsVersion
std::string BinutilsVersion
Definition: CodeGenOptions.h:120
clang::CodeGenOptions::Argv0
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
Definition: CodeGenOptions.h:392
clang::LangOptions::hasSEHExceptions
bool hasSEHExceptions() const
Definition: LangOptions.h:460
addSanitizers
static void addSanitizers(const Triple &TargetTriple, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
Definition: BackendUtil.cpp:1119
llvm
Definition: Dominators.h:30
initTargetOptions
static bool initTargetOptions(DiagnosticsEngine &Diags, llvm::TargetOptions &Options, const CodeGenOptions &CodeGenOpts, const clang::TargetOptions &TargetOpts, const LangOptions &LangOpts, const HeaderSearchOptions &HSOpts)
Definition: BackendUtil.cpp:477
clang::frontend::EmitAssembly
@ EmitAssembly
Emit a .s file.
Definition: FrontendOptions.h:58
clang::CodeGenOptions::InstrProfileOutput
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
Definition: CodeGenOptions.h:240
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::CodeGenOptions::SanitizeRecover
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
Definition: CodeGenOptions.h:338
getCodeGenFileType
static CodeGenFileType getCodeGenFileType(BackendAction Action)
Definition: BackendUtil.cpp:466
getCodeModel
static Optional< llvm::CodeModel::Model > getCodeModel(const CodeGenOptions &CodeGenOpts)
Definition: BackendUtil.cpp:451
llvm::SmallVector
Definition: LLVM.h:38
addMemorySanitizerPass
static void addMemorySanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:356
clang::CodeGenOptions::SwiftAsyncFramePointerKind::Auto
@ Auto
clang::CodeGenOptions::hasSanitizeCoverage
bool hasSanitizeCoverage() const
Definition: CodeGenOptions.h:464
clang::SanitizerSet::has
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:155
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:191
clang::CodeGenOptions::SampleProfileFile
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
Definition: CodeGenOptions.h:243
clang::CodeGenOptions::SaveTempsFilePrefix
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
Definition: CodeGenOptions.h:265
clang::LangOptions::FPM_On
@ FPM_On
Definition: LangOptions.h:210
addObjCARCExpandPass
static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM)
Definition: BackendUtil.cpp:199
clang::codegenoptions::NoDebugInfo
@ NoDebugInfo
Don't generate debug info.
Definition: DebugInfoOptions.h:22
addSymbolRewriterPass
static void addSymbolRewriterPass(const CodeGenOptions &Opts, legacy::PassManager *MPM)
Definition: BackendUtil.cpp:424
llvm::Optional
Definition: LLVM.h:40
clang::CodeGenOptions::CodeModel
std::string CodeModel
The code model to use (-mcmodel).
Definition: CodeGenOptions.h:142
clang::Backend_EmitLL
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:33
clang::CodeGenOptions::RewriteMapFiles
std::vector< std::string > RewriteMapFiles
Set of files defining the rules for the symbol rewriting.
Definition: CodeGenOptions.h:334
llvm::Expected
Definition: LLVM.h:41
clang::CodeGenOptions::hasProfileCSIRUse
bool hasProfileCSIRUse() const
Check if CSIR profile use is on.
Definition: CodeGenOptions.h:451
clang::LangOptions::hasDWARFExceptions
bool hasDWARFExceptions() const
Definition: LangOptions.h:464
addBoundsCheckingPass
static void addBoundsCheckingPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:214
clang::CodeGenOptions::DebugPass
std::string DebugPass
Enable additional debugging information.
Definition: CodeGenOptions.h:162
clang::CodeGenOptions::CommandLineArgs
ArrayRef< const char * > CommandLineArgs
Definition: CodeGenOptions.h:393
clang::CodeGenOptions::ProfileFilterFiles
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
Definition: CodeGenOptions.h:153
addKernelHWAddressSanitizerPasses
static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:322
CodeGenOptions.h
clang::CodeGenOptions::ProfileRemappingFile
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
Definition: CodeGenOptions.h:253
clang::CodeGenOptions::Always
@ Always
clang::CodeGenOptions::SplitDwarfFile
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
Definition: CodeGenOptions.h:220
clang::XRayInstrKind::All
constexpr XRayInstrMask All
Definition: XRayInstr.h:43
clang::frontend::System
@ System
Like Angled, but marks system directories.
Definition: HeaderSearchOptions.h:43
BackendUtil.h
clang::CodeGenOptions::FloatABI
std::string FloatABI
The ABI to use for passing floating point arguments.
Definition: CodeGenOptions.h:182
addGeneralOptsForMemorySanitizer
static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM, bool CompileKernel)
Definition: BackendUtil.cpp:332
clang::Module
Describes a module or submodule.
Definition: Module.h:96
HeaderSearchOptions.h
addAddressSanitizerPasses
static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:281
clang::CodeGenOptions::CmdArgs
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
Definition: CodeGenOptions.h:344
clang::CodeGenOptions::MASSV
@ MASSV
Definition: CodeGenOptions.h:61
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::LangOptions::hasWasmExceptions
bool hasWasmExceptions() const
Definition: LangOptions.h:468
clang::HeaderSearchOptions::Sysroot
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
Definition: HeaderSearchOptions.h:100
addHWAddressSanitizerPasses
static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:311
clang::BackendAction
BackendAction
Definition: BackendUtil.h:30
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:89
setCommandLineOpts
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts)
Definition: BackendUtil.cpp:883
addObjCARCAPElimPass
static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM)
Definition: BackendUtil.cpp:194
clang::LangOptions::ThreadModelKind::POSIX
@ POSIX
POSIX Threads.
clang::CodeGenOptions::SplitDwarfOutput
std::string SplitDwarfOutput
Output filename for the split debug info, not used in the skeleton CU.
Definition: CodeGenOptions.h:223
LangOptions.h
Diagnostic.h
getGCOVOptions
static Optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
Definition: BackendUtil.cpp:627
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:199
Utils.h
clang::TargetOptions::ABI
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
clang::interp::Load
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:618
clang::CodeGenOptions::OptRecordFormat
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
Definition: CodeGenOptions.h:280
runThinLTOBackend
static void runThinLTOBackend(DiagnosticsEngine &Diags, 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, std::string ProfileRemapping, BackendAction Action)
Definition: BackendUtil.cpp:1525
clang::frontend::Quoted
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Definition: HeaderSearchOptions.h:34
clang::StringLiteral
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1761
clang::LangOptions::hasSjLjExceptions
bool hasSjLjExceptions() const
Definition: LangOptions.h:456
addAddDiscriminatorsPass
static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:209
addSanitizerCoveragePass
static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:240
clang::Backend_EmitBC
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition: BackendUtil.h:32
clang::Backend_EmitMCNull
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition: BackendUtil.h:35
clang::EmbedBitcode
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
Definition: BackendUtil.cpp:1695
clang::CodeGenOptions
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Definition: CodeGenOptions.h:49
clang::CodeGenOptions::CoverageVersion
char CoverageVersion[4]
The version string to put into coverage files.
Definition: CodeGenOptions.h:159
addDataFlowSanitizerPass
static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:371
clang::CodeGenOptions::LimitFloatPrecision
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
Definition: CodeGenOptions.h:195
clang::LangOptions::Sanitize
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:294
clang::frontend::Angled
@ Angled
Paths for '#include <>' added by '-I'.
Definition: HeaderSearchOptions.h:37
clang::CodeGenOptions::Embed_Off
@ Embed_Off
Definition: CodeGenOptions.h:94
clang::CodeGenOptions::SanitizeCoverageIgnorelistFiles
std::vector< std::string > SanitizeCoverageIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
Definition: CodeGenOptions.h:383
clang::TargetOptions::Features
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
addKernelAddressSanitizerPasses
static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:301
getCGOptLevel
static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts)
Definition: BackendUtil.cpp:435
getInstrProfOptions
static Optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
Definition: BackendUtil.cpp:645
clang::CodeGenOptions::Darwin_libsystem_m
@ Darwin_libsystem_m
Definition: CodeGenOptions.h:63
clang::LangOptions::NoSanitizeFiles
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
Definition: LangOptions.h:300
clang::CodeGenOptions::RelocationModel
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
Definition: CodeGenOptions.h:226
TargetOptions.h
clang::LangOptions::ThreadModelKind::Single
@ Single
Single Threaded Environment.
clang::EmitBackendOutput
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, std::unique_ptr< raw_pwrite_stream > OS)
clang::CodeGenOptions::hasProfileCSIRInstr
bool hasProfileCSIRInstr() const
Check if CS IR level profile instrumentation is on.
Definition: CodeGenOptions.h:435
clang::LangOptions::FPM_FastHonorPragmas
@ FPM_FastHonorPragmas
Definition: LangOptions.h:216
addThreadSanitizerPass
static void addThreadSanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:366
clang::HeaderSearchOptions::UserEntries
std::vector< Entry > UserEntries
User specified include entries.
Definition: HeaderSearchOptions.h:103
clang::CodeGenOptions::LIBMVEC
@ LIBMVEC
Definition: CodeGenOptions.h:60
clang::CodeGenOptions::hasProfileClangInstr
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
Definition: CodeGenOptions.h:425
getSancovOptsFromCGOpts
static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts)
Definition: BackendUtil.cpp:220
clang::Backend_EmitAssembly
@ Backend_EmitAssembly
Emit native assembly files.
Definition: BackendUtil.h:31
clang::TargetOptions::CPU
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
clang::CodeGenOptions::BBSections
std::string BBSections
Definition: CodeGenOptions.h:114
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
clang::CodeGenOptions::StackUsageOutput
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
Definition: CodeGenOptions.h:388
clang::DiagnosticsEngine::getCustomDiagID
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:863
clang
Definition: CalledOnceCheck.h:17
clang::CodeGenOptions::Accelerate
@ Accelerate
Definition: CodeGenOptions.h:59
asanUseGlobalsGC
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
Definition: BackendUtil.cpp:255
FrontendDiagnostic.h
clang::CodeGenOptions::OptRecordFile
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
Definition: CodeGenOptions.h:273
addKernelMemorySanitizerPass
static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:361
clang::CodeGenOptions::SVML
@ SVML
Definition: CodeGenOptions.h:62
clang::Module::print
void print(raw_ostream &OS, unsigned Indent=0, bool Dump=false) const
Print the module map for this module to the given stream.
Definition: Module.cpp:433
clang::prec::Level
Level
Definition: OperatorPrecedence.h:26
addPostInlineEntryExitInstrumentationPass
static void addPostInlineEntryExitInstrumentationPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:385
addEntryExitInstrumentationPass
static void addEntryExitInstrumentationPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:379
addObjCARCOptPass
static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM)
Definition: BackendUtil.cpp:204
clang::CodeGenOptions::ThinLTOIndexFile
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
Definition: CodeGenOptions.h:257
clang::CodeGenOptions::Embed_Marker
@ Embed_Marker
Definition: CodeGenOptions.h:97
clang::Backend_EmitNothing
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition: BackendUtil.h:34
clang::TargetOptions::EABIVersion
llvm::EABI EABIVersion
The EABI version to use.
Definition: TargetOptions.h:48
clang::CodeGenOptions::ProfileExcludeFiles
std::string ProfileExcludeFiles
Regexes separated by a semi-colon to filter the files to not instrument.
Definition: CodeGenOptions.h:156
clang::LangOptions::FPM_Off
@ FPM_Off
Definition: LangOptions.h:207
clang::Backend_EmitObj
@ Backend_EmitObj
Emit native object files.
Definition: BackendUtil.h:36
clang::TargetOptions
Options for controlling the target.
Definition: TargetOptions.h:26
createTLII
static TargetLibraryInfoImpl * createTLII(llvm::Triple &TargetTriple, const CodeGenOptions &CodeGenOpts)
Definition: BackendUtil.cpp:390
addMemProfilerPasses
static void addMemProfilerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Definition: BackendUtil.cpp:275
clang::CodeGenOptions::ProfileInstrumentUsePath
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
Definition: CodeGenOptions.h:249
clang::CodeGenOptions::Embed_Bitcode
@ Embed_Bitcode
Definition: CodeGenOptions.h:96
clang::LangOptions::FPM_Fast
@ FPM_Fast
Definition: LangOptions.h:213
clang::CodeGenOptions::OptRecordPasses
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
Definition: CodeGenOptions.h:277
clang::SanitizerMask
Definition: Sanitizers.h:30
mapToLevel
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts)
Definition: BackendUtil.cpp:1088
clang::HeaderSearchOptions
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Definition: HeaderSearchOptions.h:68
clang::CodeGenOptions::Never
@ Never
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1508
Type
MatchType Type
Definition: ASTMatchFinder.cpp:70
clang::CodeGenOptions::SanitizeCoverageAllowlistFiles
std::vector< std::string > SanitizeCoverageAllowlistFiles
Path to allowlist file specifying which objects (files, functions) should exclusively be instrumented...
Definition: CodeGenOptions.h:367