clang 18.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
10#include "BackendConsumer.h"
11#include "LinkInModulesPass.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/GlobalsModRef.h"
24#include "llvm/Analysis/TargetLibraryInfo.h"
25#include "llvm/Analysis/TargetTransformInfo.h"
26#include "llvm/Bitcode/BitcodeReader.h"
27#include "llvm/Bitcode/BitcodeWriter.h"
28#include "llvm/Bitcode/BitcodeWriterPass.h"
29#include "llvm/CodeGen/RegAllocRegistry.h"
30#include "llvm/CodeGen/SchedulerRegistry.h"
31#include "llvm/CodeGen/TargetSubtargetInfo.h"
32#include "llvm/Frontend/Driver/CodeGenOptions.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/LegacyPassManager.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/ModuleSummaryIndex.h"
38#include "llvm/IR/PassManager.h"
39#include "llvm/IR/Verifier.h"
40#include "llvm/IRPrinter/IRPrintingPasses.h"
41#include "llvm/LTO/LTOBackend.h"
42#include "llvm/MC/MCAsmInfo.h"
43#include "llvm/MC/TargetRegistry.h"
44#include "llvm/Object/OffloadBinary.h"
45#include "llvm/Passes/PassBuilder.h"
46#include "llvm/Passes/PassPlugin.h"
47#include "llvm/Passes/StandardInstrumentations.h"
48#include "llvm/Support/BuryPointer.h"
49#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/PrettyStackTrace.h"
52#include "llvm/Support/TimeProfiler.h"
53#include "llvm/Support/Timer.h"
54#include "llvm/Support/ToolOutputFile.h"
55#include "llvm/Support/VirtualFileSystem.h"
56#include "llvm/Support/raw_ostream.h"
57#include "llvm/Target/TargetMachine.h"
58#include "llvm/Target/TargetOptions.h"
59#include "llvm/TargetParser/SubtargetFeature.h"
60#include "llvm/TargetParser/Triple.h"
61#include "llvm/Transforms/HipStdPar/HipStdPar.h"
62#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
63#include "llvm/Transforms/IPO/LowerTypeTests.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/KCFI.h"
75#include "llvm/Transforms/Instrumentation/MemProfiler.h"
76#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
77#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
78#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
79#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
80#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
81#include "llvm/Transforms/ObjCARC.h"
82#include "llvm/Transforms/Scalar/EarlyCSE.h"
83#include "llvm/Transforms/Scalar/GVN.h"
84#include "llvm/Transforms/Scalar/JumpThreading.h"
85#include "llvm/Transforms/Utils/Debugify.h"
86#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
87#include "llvm/Transforms/Utils/ModuleUtils.h"
88#include <memory>
89#include <optional>
90using namespace clang;
91using namespace llvm;
92
93#define HANDLE_EXTENSION(Ext) \
94 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
95#include "llvm/Support/Extension.def"
96
97namespace llvm {
98extern cl::opt<bool> PrintPipelinePasses;
99
100// Experiment to move sanitizers earlier.
101static cl::opt<bool> ClSanitizeOnOptimizerEarlyEP(
102 "sanitizer-early-opt-ep", cl::Optional,
103 cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false));
104
105// Re-link builtin bitcodes after optimization
107 "relink-builtin-bitcode-postop", cl::Optional,
108 cl::desc("Re-link builtin bitcodes after optimization."), cl::init(false));
109}
110
111namespace {
112
113// Default filename used for profile generation.
114std::string getDefaultProfileGenName() {
115 return DebugInfoCorrelate ? "default_%m.proflite" : "default_%m.profraw";
116}
117
118class EmitAssemblyHelper {
119 DiagnosticsEngine &Diags;
120 const HeaderSearchOptions &HSOpts;
121 const CodeGenOptions &CodeGenOpts;
122 const clang::TargetOptions &TargetOpts;
123 const LangOptions &LangOpts;
124 llvm::Module *TheModule;
126
127 Timer CodeGenerationTime;
128
129 std::unique_ptr<raw_pwrite_stream> OS;
130
131 Triple TargetTriple;
132
133 TargetIRAnalysis getTargetIRAnalysis() const {
134 if (TM)
135 return TM->getTargetIRAnalysis();
136
137 return TargetIRAnalysis();
138 }
139
140 /// Generates the TargetMachine.
141 /// Leaves TM unchanged if it is unable to create the target machine.
142 /// Some of our clang tests specify triples which are not built
143 /// into clang. This is okay because these tests check the generated
144 /// IR, and they require DataLayout which depends on the triple.
145 /// In this case, we allow this method to fail and not report an error.
146 /// When MustCreateTM is used, we print an error if we are unable to load
147 /// the requested target.
148 void CreateTargetMachine(bool MustCreateTM);
149
150 /// Add passes necessary to emit assembly or LLVM IR.
151 ///
152 /// \return True on success.
153 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
154 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
155
156 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
157 std::error_code EC;
158 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
159 llvm::sys::fs::OF_None);
160 if (EC) {
161 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
162 F.reset();
163 }
164 return F;
165 }
166
167 void RunOptimizationPipeline(
168 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
169 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
170 void RunCodegenPipeline(BackendAction Action,
171 std::unique_ptr<raw_pwrite_stream> &OS,
172 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
173
174 /// Check whether we should emit a module summary for regular LTO.
175 /// The module summary should be emitted by default for regular LTO
176 /// except for ld64 targets.
177 ///
178 /// \return True if the module summary should be emitted.
179 bool shouldEmitRegularLTOSummary() const {
180 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
181 TargetTriple.getVendor() != llvm::Triple::Apple;
182 }
183
184public:
185 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
186 const HeaderSearchOptions &HeaderSearchOpts,
187 const CodeGenOptions &CGOpts,
188 const clang::TargetOptions &TOpts,
189 const LangOptions &LOpts, llvm::Module *M,
191 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
192 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), VFS(std::move(VFS)),
193 CodeGenerationTime("codegen", "Code Generation Time"),
194 TargetTriple(TheModule->getTargetTriple()) {}
195
196 ~EmitAssemblyHelper() {
197 if (CodeGenOpts.DisableFree)
198 BuryPointer(std::move(TM));
199 }
200
201 std::unique_ptr<TargetMachine> TM;
202
203 // Emit output using the new pass manager for the optimization pipeline.
204 void EmitAssembly(BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
205 BackendConsumer *BC);
206};
207}
208
209static SanitizerCoverageOptions
211 SanitizerCoverageOptions Opts;
212 Opts.CoverageType =
213 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
214 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
215 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
216 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
217 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
218 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
219 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
220 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
221 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
222 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
223 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
224 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
225 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
226 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
227 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
228 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
229 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
230 return Opts;
231}
232
233static SanitizerBinaryMetadataOptions
235 SanitizerBinaryMetadataOptions Opts;
236 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
237 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
238 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
239 return Opts;
240}
241
242// Check if ASan should use GC-friendly instrumentation for globals.
243// First of all, there is no point if -fdata-sections is off (expect for MachO,
244// where this is not a factor). Also, on ELF this feature requires an assembler
245// extension that only works with -integrated-as at the moment.
246static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
247 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
248 return false;
249 switch (T.getObjectFormat()) {
250 case Triple::MachO:
251 case Triple::COFF:
252 return true;
253 case Triple::ELF:
254 return !CGOpts.DisableIntegratedAS;
255 case Triple::GOFF:
256 llvm::report_fatal_error("ASan not implemented for GOFF");
257 case Triple::XCOFF:
258 llvm::report_fatal_error("ASan not implemented for XCOFF.");
259 case Triple::Wasm:
260 case Triple::DXContainer:
261 case Triple::SPIRV:
262 case Triple::UnknownObjectFormat:
263 break;
264 }
265 return false;
266}
267
268static std::optional<llvm::CodeModel::Model>
269getCodeModel(const CodeGenOptions &CodeGenOpts) {
270 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
271 .Case("tiny", llvm::CodeModel::Tiny)
272 .Case("small", llvm::CodeModel::Small)
273 .Case("kernel", llvm::CodeModel::Kernel)
274 .Case("medium", llvm::CodeModel::Medium)
275 .Case("large", llvm::CodeModel::Large)
276 .Case("default", ~1u)
277 .Default(~0u);
278 assert(CodeModel != ~0u && "invalid code model!");
279 if (CodeModel == ~1u)
280 return std::nullopt;
281 return static_cast<llvm::CodeModel::Model>(CodeModel);
282}
283
284static CodeGenFileType getCodeGenFileType(BackendAction Action) {
285 if (Action == Backend_EmitObj)
286 return CodeGenFileType::ObjectFile;
287 else if (Action == Backend_EmitMCNull)
288 return CodeGenFileType::Null;
289 else {
290 assert(Action == Backend_EmitAssembly && "Invalid action!");
291 return CodeGenFileType::AssemblyFile;
292 }
293}
294
296 return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
297 Action != Backend_EmitLL;
298}
299
301 llvm::TargetOptions &Options,
302 const CodeGenOptions &CodeGenOpts,
303 const clang::TargetOptions &TargetOpts,
304 const LangOptions &LangOpts,
305 const HeaderSearchOptions &HSOpts) {
306 switch (LangOpts.getThreadModel()) {
307 case LangOptions::ThreadModelKind::POSIX:
308 Options.ThreadModel = llvm::ThreadModel::POSIX;
309 break;
310 case LangOptions::ThreadModelKind::Single:
311 Options.ThreadModel = llvm::ThreadModel::Single;
312 break;
313 }
314
315 // Set float ABI type.
316 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
317 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
318 "Invalid Floating Point ABI!");
319 Options.FloatABIType =
320 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
321 .Case("soft", llvm::FloatABI::Soft)
322 .Case("softfp", llvm::FloatABI::Soft)
323 .Case("hard", llvm::FloatABI::Hard)
324 .Default(llvm::FloatABI::Default);
325
326 // Set FP fusion mode.
327 switch (LangOpts.getDefaultFPContractMode()) {
329 // Preserve any contraction performed by the front-end. (Strict performs
330 // splitting of the muladd intrinsic in the backend.)
331 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
332 break;
335 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
336 break;
338 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
339 break;
340 }
341
342 Options.BinutilsVersion =
343 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
344 Options.UseInitArray = CodeGenOpts.UseInitArray;
345 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
346 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
347 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
348
349 // Set EABI version.
350 Options.EABIVersion = TargetOpts.EABIVersion;
351
352 if (LangOpts.hasSjLjExceptions())
353 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
354 if (LangOpts.hasSEHExceptions())
355 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
356 if (LangOpts.hasDWARFExceptions())
357 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
358 if (LangOpts.hasWasmExceptions())
359 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
360
361 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
362 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
363 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
364 Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
365 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
366 (LangOpts.getDefaultFPContractMode() ==
367 LangOptions::FPModeKind::FPM_Fast ||
368 LangOpts.getDefaultFPContractMode() ==
369 LangOptions::FPModeKind::FPM_FastHonorPragmas);
370 Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
371
372 Options.BBSections =
373 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
374 .Case("all", llvm::BasicBlockSection::All)
375 .Case("labels", llvm::BasicBlockSection::Labels)
376 .StartsWith("list=", llvm::BasicBlockSection::List)
377 .Case("none", llvm::BasicBlockSection::None)
378 .Default(llvm::BasicBlockSection::None);
379
380 if (Options.BBSections == llvm::BasicBlockSection::List) {
381 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
382 MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
383 if (!MBOrErr) {
384 Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
385 << MBOrErr.getError().message();
386 return false;
387 }
388 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
389 }
390
391 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
392 Options.FunctionSections = CodeGenOpts.FunctionSections;
393 Options.DataSections = CodeGenOpts.DataSections;
394 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
395 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
396 Options.UniqueBasicBlockSectionNames =
397 CodeGenOpts.UniqueBasicBlockSectionNames;
398 Options.TLSSize = CodeGenOpts.TLSSize;
399 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
400 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
401 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
402 Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
403 Options.EmitAddrsig = CodeGenOpts.Addrsig;
404 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
405 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
406 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
407 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
408 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
409 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
410 Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
411 Options.Hotpatch = CodeGenOpts.HotPatch;
412 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
413 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
414
415 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
416 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
417 Options.SwiftAsyncFramePointer =
418 SwiftAsyncFramePointerMode::DeploymentBased;
419 break;
420
421 case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
422 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
423 break;
424
425 case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
426 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
427 break;
428 }
429
430 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
431 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
432 Options.MCOptions.EmitCompactUnwindNonCanonical =
433 CodeGenOpts.EmitCompactUnwindNonCanonical;
434 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
435 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
436 Options.MCOptions.MCUseDwarfDirectory =
437 CodeGenOpts.NoDwarfDirectoryAsm
438 ? llvm::MCTargetOptions::DisableDwarfDirectory
439 : llvm::MCTargetOptions::EnableDwarfDirectory;
440 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
441 Options.MCOptions.MCIncrementalLinkerCompatible =
442 CodeGenOpts.IncrementalLinkerCompatible;
443 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
444 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
445 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
446 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
447 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
448 Options.MCOptions.ABIName = TargetOpts.ABI;
449 for (const auto &Entry : HSOpts.UserEntries)
450 if (!Entry.IsFramework &&
451 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
452 Entry.Group == frontend::IncludeDirGroup::Angled ||
453 Entry.Group == frontend::IncludeDirGroup::System))
454 Options.MCOptions.IASSearchPaths.push_back(
455 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
456 Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
457 Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
458 Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile;
459 Options.MCOptions.PPCUseFullRegisterNames =
460 CodeGenOpts.PPCUseFullRegisterNames;
461 Options.MisExpect = CodeGenOpts.MisExpect;
462
463 return true;
464}
465
466static std::optional<GCOVOptions>
467getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) {
468 if (CodeGenOpts.CoverageNotesFile.empty() &&
469 CodeGenOpts.CoverageDataFile.empty())
470 return std::nullopt;
471 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
472 // LLVM's -default-gcov-version flag is set to something invalid.
473 GCOVOptions Options;
474 Options.EmitNotes = !CodeGenOpts.CoverageNotesFile.empty();
475 Options.EmitData = !CodeGenOpts.CoverageDataFile.empty();
476 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
477 Options.NoRedZone = CodeGenOpts.DisableRedZone;
478 Options.Filter = CodeGenOpts.ProfileFilterFiles;
479 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
480 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
481 return Options;
482}
483
484static std::optional<InstrProfOptions>
486 const LangOptions &LangOpts) {
487 if (!CodeGenOpts.hasProfileClangInstr())
488 return std::nullopt;
489 InstrProfOptions Options;
490 Options.NoRedZone = CodeGenOpts.DisableRedZone;
491 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
492 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
493 return Options;
494}
495
496static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
498 BackendArgs.push_back("clang"); // Fake program name.
499 if (!CodeGenOpts.DebugPass.empty()) {
500 BackendArgs.push_back("-debug-pass");
501 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
502 }
503 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
504 BackendArgs.push_back("-limit-float-precision");
505 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
506 }
507 // Check for the default "clang" invocation that won't set any cl::opt values.
508 // Skip trying to parse the command line invocation to avoid the issues
509 // described below.
510 if (BackendArgs.size() == 1)
511 return;
512 BackendArgs.push_back(nullptr);
513 // FIXME: The command line parser below is not thread-safe and shares a global
514 // state, so this call might crash or overwrite the options of another Clang
515 // instance in the same process.
516 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
517 BackendArgs.data());
518}
519
520void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
521 // Create the TargetMachine for generating code.
522 std::string Error;
523 std::string Triple = TheModule->getTargetTriple();
524 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
525 if (!TheTarget) {
526 if (MustCreateTM)
527 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
528 return;
529 }
530
531 std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
532 std::string FeaturesStr =
533 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
534 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
535 std::optional<CodeGenOptLevel> OptLevelOrNone =
536 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
537 assert(OptLevelOrNone && "Invalid optimization level!");
538 CodeGenOptLevel OptLevel = *OptLevelOrNone;
539
540 llvm::TargetOptions Options;
541 if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
542 HSOpts))
543 return;
544 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
545 Options, RM, CM, OptLevel));
546 TM->setLargeDataThreshold(CodeGenOpts.LargeDataThreshold);
547}
548
549bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
550 BackendAction Action,
551 raw_pwrite_stream &OS,
552 raw_pwrite_stream *DwoOS) {
553 // Add LibraryInfo.
554 std::unique_ptr<TargetLibraryInfoImpl> TLII(
555 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
556 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
557
558 // Normal mode, emit a .s or .o file by running the code generator. Note,
559 // this also adds codegenerator level optimization passes.
560 CodeGenFileType CGFT = getCodeGenFileType(Action);
561
562 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
563 // "codegen" passes so that it isn't run multiple times when there is
564 // inlining happening.
565 if (CodeGenOpts.OptimizationLevel > 0)
566 CodeGenPasses.add(createObjCARCContractPass());
567
568 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
569 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
570 Diags.Report(diag::err_fe_unable_to_interface_with_target);
571 return false;
572 }
573
574 return true;
575}
576
577static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
578 switch (Opts.OptimizationLevel) {
579 default:
580 llvm_unreachable("Invalid optimization level!");
581
582 case 0:
583 return OptimizationLevel::O0;
584
585 case 1:
586 return OptimizationLevel::O1;
587
588 case 2:
589 switch (Opts.OptimizeSize) {
590 default:
591 llvm_unreachable("Invalid optimization level for size!");
592
593 case 0:
594 return OptimizationLevel::O2;
595
596 case 1:
597 return OptimizationLevel::Os;
598
599 case 2:
600 return OptimizationLevel::Oz;
601 }
602
603 case 3:
604 return OptimizationLevel::O3;
605 }
606}
607
608static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts,
609 PassBuilder &PB) {
610 // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
611 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
612 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
613 return;
614
615 // Ensure we lower KCFI operand bundles with -O0.
616 PB.registerOptimizerLastEPCallback(
617 [&](ModulePassManager &MPM, OptimizationLevel Level) {
618 if (Level == OptimizationLevel::O0 &&
619 LangOpts.Sanitize.has(SanitizerKind::KCFI))
620 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
621 });
622
623 // When optimizations are requested, run KCIFPass after InstCombine to
624 // avoid unnecessary checks.
625 PB.registerPeepholeEPCallback(
626 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
627 if (Level != OptimizationLevel::O0 &&
628 LangOpts.Sanitize.has(SanitizerKind::KCFI))
629 FPM.addPass(KCFIPass());
630 });
631}
632
633static void addSanitizers(const Triple &TargetTriple,
634 const CodeGenOptions &CodeGenOpts,
635 const LangOptions &LangOpts, PassBuilder &PB) {
636 auto SanitizersCallback = [&](ModulePassManager &MPM,
637 OptimizationLevel Level) {
638 if (CodeGenOpts.hasSanitizeCoverage()) {
639 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
640 MPM.addPass(SanitizerCoveragePass(
641 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
643 }
644
645 if (CodeGenOpts.hasSanitizeBinaryMetadata()) {
646 MPM.addPass(SanitizerBinaryMetadataPass(
649 }
650
651 auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
652 if (LangOpts.Sanitize.has(Mask)) {
653 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
654 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
655
656 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
657 CodeGenOpts.SanitizeMemoryParamRetval);
658 MPM.addPass(MemorySanitizerPass(options));
659 if (Level != OptimizationLevel::O0) {
660 // MemorySanitizer inserts complex instrumentation that mostly follows
661 // the logic of the original code, but operates on "shadow" values. It
662 // can benefit from re-running some general purpose optimization
663 // passes.
664 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
665 FunctionPassManager FPM;
666 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
667 FPM.addPass(InstCombinePass());
668 FPM.addPass(JumpThreadingPass());
669 FPM.addPass(GVNPass());
670 FPM.addPass(InstCombinePass());
671 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
672 }
673 }
674 };
675 MSanPass(SanitizerKind::Memory, false);
676 MSanPass(SanitizerKind::KernelMemory, true);
677
678 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
679 MPM.addPass(ModuleThreadSanitizerPass());
680 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
681 }
682
683 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
684 if (LangOpts.Sanitize.has(Mask)) {
685 bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
686 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
687 llvm::AsanDtorKind DestructorKind =
688 CodeGenOpts.getSanitizeAddressDtor();
689 AddressSanitizerOptions Opts;
690 Opts.CompileKernel = CompileKernel;
691 Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
692 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
693 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
694 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
695 DestructorKind));
696 }
697 };
698 ASanPass(SanitizerKind::Address, false);
699 ASanPass(SanitizerKind::KernelAddress, true);
700
701 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
702 if (LangOpts.Sanitize.has(Mask)) {
703 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
704 MPM.addPass(HWAddressSanitizerPass(
705 {CompileKernel, Recover,
706 /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
707 }
708 };
709 HWASanPass(SanitizerKind::HWAddress, false);
710 HWASanPass(SanitizerKind::KernelHWAddress, true);
711
712 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
713 MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
714 }
715 };
717 PB.registerOptimizerEarlyEPCallback(
718 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level) {
719 ModulePassManager NewMPM;
720 SanitizersCallback(NewMPM, Level);
721 if (!NewMPM.isEmpty()) {
722 // Sanitizers can abandon<GlobalsAA>.
723 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
724 MPM.addPass(std::move(NewMPM));
725 }
726 });
727 } else {
728 // LastEP does not need GlobalsAA.
729 PB.registerOptimizerLastEPCallback(SanitizersCallback);
730 }
731}
732
733void EmitAssemblyHelper::RunOptimizationPipeline(
734 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
735 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
736 std::optional<PGOOptions> PGOOpt;
737
738 if (CodeGenOpts.hasProfileIRInstr())
739 // -fprofile-generate.
740 PGOOpt = PGOOptions(
741 CodeGenOpts.InstrProfileOutput.empty() ? getDefaultProfileGenName()
742 : CodeGenOpts.InstrProfileOutput,
743 "", "", CodeGenOpts.MemoryProfileUsePath, nullptr, PGOOptions::IRInstr,
744 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling,
745 /*PseudoProbeForProfiling=*/false, CodeGenOpts.AtomicProfileUpdate);
746 else if (CodeGenOpts.hasProfileIRUse()) {
747 // -fprofile-use.
748 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
749 : PGOOptions::NoCSAction;
750 PGOOpt = PGOOptions(
751 CodeGenOpts.ProfileInstrumentUsePath, "",
752 CodeGenOpts.ProfileRemappingFile, CodeGenOpts.MemoryProfileUsePath, VFS,
753 PGOOptions::IRUse, CSAction, CodeGenOpts.DebugInfoForProfiling);
754 } else if (!CodeGenOpts.SampleProfileFile.empty())
755 // -fprofile-sample-use
756 PGOOpt = PGOOptions(
757 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
758 CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse,
759 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling,
760 CodeGenOpts.PseudoProbeForProfiling);
761 else if (!CodeGenOpts.MemoryProfileUsePath.empty())
762 // -fmemory-profile-use (without any of the above options)
763 PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, VFS,
764 PGOOptions::NoAction, PGOOptions::NoCSAction,
765 CodeGenOpts.DebugInfoForProfiling);
766 else if (CodeGenOpts.PseudoProbeForProfiling)
767 // -fpseudo-probe-for-profiling
768 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
769 PGOOptions::NoAction, PGOOptions::NoCSAction,
770 CodeGenOpts.DebugInfoForProfiling, true);
771 else if (CodeGenOpts.DebugInfoForProfiling)
772 // -fdebug-info-for-profiling
773 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
774 PGOOptions::NoAction, PGOOptions::NoCSAction, true);
775
776 // Check to see if we want to generate a CS profile.
777 if (CodeGenOpts.hasProfileCSIRInstr()) {
778 assert(!CodeGenOpts.hasProfileCSIRUse() &&
779 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
780 "the same time");
781 if (PGOOpt) {
782 assert(PGOOpt->Action != PGOOptions::IRInstr &&
783 PGOOpt->Action != PGOOptions::SampleUse &&
784 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
785 " pass");
786 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
787 ? getDefaultProfileGenName()
788 : CodeGenOpts.InstrProfileOutput;
789 PGOOpt->CSAction = PGOOptions::CSIRInstr;
790 } else
791 PGOOpt =
792 PGOOptions("",
793 CodeGenOpts.InstrProfileOutput.empty()
794 ? getDefaultProfileGenName()
795 : CodeGenOpts.InstrProfileOutput,
796 "", /*MemoryProfile=*/"", nullptr, PGOOptions::NoAction,
797 PGOOptions::CSIRInstr, CodeGenOpts.DebugInfoForProfiling);
798 }
799 if (TM)
800 TM->setPGOOption(PGOOpt);
801
802 PipelineTuningOptions PTO;
803 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
804 // For historical reasons, loop interleaving is set to mirror setting for loop
805 // unrolling.
806 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
807 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
808 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
809 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
810 // Only enable CGProfilePass when using integrated assembler, since
811 // non-integrated assemblers don't recognize .cgprofile section.
812 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
813 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
814
815 LoopAnalysisManager LAM;
816 FunctionAnalysisManager FAM;
817 CGSCCAnalysisManager CGAM;
818 ModuleAnalysisManager MAM;
819
820 bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
821 PassInstrumentationCallbacks PIC;
822 PrintPassOptions PrintPassOpts;
823 PrintPassOpts.Indent = DebugPassStructure;
824 PrintPassOpts.SkipAnalyses = DebugPassStructure;
825 StandardInstrumentations SI(
826 TheModule->getContext(),
827 (CodeGenOpts.DebugPassManager || DebugPassStructure),
828 CodeGenOpts.VerifyEach, PrintPassOpts);
829 SI.registerCallbacks(PIC, &MAM);
830 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
831
832 // Handle the assignment tracking feature options.
833 switch (CodeGenOpts.getAssignmentTrackingMode()) {
834 case CodeGenOptions::AssignmentTrackingOpts::Forced:
835 PB.registerPipelineStartEPCallback(
836 [&](ModulePassManager &MPM, OptimizationLevel Level) {
837 MPM.addPass(AssignmentTrackingPass());
838 });
839 break;
840 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
841 // Disable assignment tracking in LTO builds for now as the performance
842 // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
843 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
844 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
845 PB.registerPipelineStartEPCallback(
846 [&](ModulePassManager &MPM, OptimizationLevel Level) {
847 // Only use assignment tracking if optimisations are enabled.
848 if (Level != OptimizationLevel::O0)
849 MPM.addPass(AssignmentTrackingPass());
850 });
851 }
852 break;
853 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
854 break;
855 }
856
857 // Enable verify-debuginfo-preserve-each for new PM.
858 DebugifyEachInstrumentation Debugify;
859 DebugInfoPerPass DebugInfoBeforePass;
860 if (CodeGenOpts.EnableDIPreservationVerify) {
861 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
862 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
863
864 if (!CodeGenOpts.DIBugsReportFilePath.empty())
865 Debugify.setOrigDIVerifyBugsReportFilePath(
866 CodeGenOpts.DIBugsReportFilePath);
867 Debugify.registerCallbacks(PIC, MAM);
868 }
869 // Attempt to load pass plugins and register their callbacks with PB.
870 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
871 auto PassPlugin = PassPlugin::Load(PluginFN);
872 if (PassPlugin) {
873 PassPlugin->registerPassBuilderCallbacks(PB);
874 } else {
875 Diags.Report(diag::err_fe_unable_to_load_plugin)
876 << PluginFN << toString(PassPlugin.takeError());
877 }
878 }
879 for (auto PassCallback : CodeGenOpts.PassBuilderCallbacks)
880 PassCallback(PB);
881#define HANDLE_EXTENSION(Ext) \
882 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
883#include "llvm/Support/Extension.def"
884
885 // Register the target library analysis directly and give it a customized
886 // preset TLI.
887 std::unique_ptr<TargetLibraryInfoImpl> TLII(
888 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
889 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
890
891 // Register all the basic analyses with the managers.
892 PB.registerModuleAnalyses(MAM);
893 PB.registerCGSCCAnalyses(CGAM);
894 PB.registerFunctionAnalyses(FAM);
895 PB.registerLoopAnalyses(LAM);
896 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
897
898 ModulePassManager MPM;
899 // Add a verifier pass, before any other passes, to catch CodeGen issues.
900 if (CodeGenOpts.VerifyModule)
901 MPM.addPass(VerifierPass());
902
903 if (!CodeGenOpts.DisableLLVMPasses) {
904 // Map our optimization levels into one of the distinct levels used to
905 // configure the pipeline.
906 OptimizationLevel Level = mapToLevel(CodeGenOpts);
907
908 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
909 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
910
911 if (LangOpts.ObjCAutoRefCount) {
912 PB.registerPipelineStartEPCallback(
913 [](ModulePassManager &MPM, OptimizationLevel Level) {
914 if (Level != OptimizationLevel::O0)
915 MPM.addPass(
916 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
917 });
918 PB.registerPipelineEarlySimplificationEPCallback(
919 [](ModulePassManager &MPM, OptimizationLevel Level) {
920 if (Level != OptimizationLevel::O0)
921 MPM.addPass(ObjCARCAPElimPass());
922 });
923 PB.registerScalarOptimizerLateEPCallback(
924 [](FunctionPassManager &FPM, OptimizationLevel Level) {
925 if (Level != OptimizationLevel::O0)
926 FPM.addPass(ObjCARCOptPass());
927 });
928 }
929
930 // If we reached here with a non-empty index file name, then the index
931 // file was empty and we are not performing ThinLTO backend compilation
932 // (used in testing in a distributed build environment).
933 bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
934 // If so drop any the type test assume sequences inserted for whole program
935 // vtables so that codegen doesn't complain.
936 if (IsThinLTOPostLink)
937 PB.registerPipelineStartEPCallback(
938 [](ModulePassManager &MPM, OptimizationLevel Level) {
939 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
940 /*ImportSummary=*/nullptr,
941 /*DropTypeTests=*/true));
942 });
943
944 if (CodeGenOpts.InstrumentFunctions ||
945 CodeGenOpts.InstrumentFunctionEntryBare ||
946 CodeGenOpts.InstrumentFunctionsAfterInlining ||
947 CodeGenOpts.InstrumentForProfiling) {
948 PB.registerPipelineStartEPCallback(
949 [](ModulePassManager &MPM, OptimizationLevel Level) {
950 MPM.addPass(createModuleToFunctionPassAdaptor(
951 EntryExitInstrumenterPass(/*PostInlining=*/false)));
952 });
953 PB.registerOptimizerLastEPCallback(
954 [](ModulePassManager &MPM, OptimizationLevel Level) {
955 MPM.addPass(createModuleToFunctionPassAdaptor(
956 EntryExitInstrumenterPass(/*PostInlining=*/true)));
957 });
958 }
959
960 // Register callbacks to schedule sanitizer passes at the appropriate part
961 // of the pipeline.
962 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
963 PB.registerScalarOptimizerLateEPCallback(
964 [](FunctionPassManager &FPM, OptimizationLevel Level) {
965 FPM.addPass(BoundsCheckingPass());
966 });
967
968 // Don't add sanitizers if we are here from ThinLTO PostLink. That already
969 // done on PreLink stage.
970 if (!IsThinLTOPostLink) {
971 addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
972 addKCFIPass(TargetTriple, LangOpts, PB);
973 }
974
975 if (std::optional<GCOVOptions> Options =
976 getGCOVOptions(CodeGenOpts, LangOpts))
977 PB.registerPipelineStartEPCallback(
978 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
979 MPM.addPass(GCOVProfilerPass(*Options));
980 });
981 if (std::optional<InstrProfOptions> Options =
982 getInstrProfOptions(CodeGenOpts, LangOpts))
983 PB.registerPipelineStartEPCallback(
984 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
985 MPM.addPass(InstrProfiling(*Options, false));
986 });
987
988 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
989 // the PGOOptions, and set this up there.
990 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
991 PB.registerOptimizerLastEPCallback(
992 [](ModulePassManager &MPM, OptimizationLevel Level) {
993 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
994 MPM.addPass(ModuleMemProfilerPass());
995 });
996 }
997
998 if (CodeGenOpts.FatLTO) {
999 assert(CodeGenOpts.UnifiedLTO && "FatLTO requires UnifiedLTO");
1000 MPM.addPass(PB.buildFatLTODefaultPipeline(Level));
1001 } else if (PrepareForThinLTO) {
1002 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1003 } else if (PrepareForLTO) {
1004 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1005 } else {
1006 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1007 }
1008 }
1009
1010 // Re-link against any bitcodes supplied via the -mlink-builtin-bitcode option
1011 // Some optimizations may generate new function calls that would not have
1012 // been linked pre-optimization (i.e. fused sincos calls generated by
1013 // AMDGPULibCalls::fold_sincos.)
1015 MPM.addPass(LinkInModulesPass(BC, false));
1016
1017 // Add a verifier pass if requested. We don't have to do this if the action
1018 // requires code generation because there will already be a verifier pass in
1019 // the code-generation pipeline.
1020 // Since we already added a verifier pass above, this
1021 // might even not run the analysis, if previous passes caused no changes.
1022 if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
1023 MPM.addPass(VerifierPass());
1024
1025 if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
1026 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1027 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1028 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1029 CodeGenOpts.EnableSplitLTOUnit);
1030 if (Action == Backend_EmitBC) {
1031 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1032 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1033 if (!ThinLinkOS)
1034 return;
1035 }
1036 if (CodeGenOpts.UnifiedLTO)
1037 TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
1038 MPM.addPass(ThinLTOBitcodeWriterPass(
1039 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1040 } else {
1041 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1042 /*EmitLTOSummary=*/true));
1043 }
1044 } else {
1045 // Emit a module summary by default for Regular LTO except for ld64
1046 // targets
1047 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1048 if (EmitLTOSummary) {
1049 if (!TheModule->getModuleFlag("ThinLTO") && !CodeGenOpts.UnifiedLTO)
1050 TheModule->addModuleFlag(llvm::Module::Error, "ThinLTO", uint32_t(0));
1051 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1052 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1053 uint32_t(1));
1054 if (CodeGenOpts.UnifiedLTO)
1055 TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
1056 }
1057 if (Action == Backend_EmitBC)
1058 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1059 EmitLTOSummary));
1060 else
1061 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1062 EmitLTOSummary));
1063 }
1064 }
1065 if (CodeGenOpts.FatLTO) {
1066 // Set module flags, like EnableSplitLTOUnit and UnifiedLTO, since FatLTO
1067 // uses a different action than Backend_EmitBC or Backend_EmitLL.
1068 if (!TheModule->getModuleFlag("ThinLTO"))
1069 TheModule->addModuleFlag(llvm::Module::Error, "ThinLTO",
1070 uint32_t(CodeGenOpts.PrepareForThinLTO));
1071 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1072 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1073 uint32_t(CodeGenOpts.EnableSplitLTOUnit));
1074 // FatLTO always means UnifiedLTO
1075 if (!TheModule->getModuleFlag("UnifiedLTO"))
1076 TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
1077 }
1078
1079 // Print a textual, '-passes=' compatible, representation of pipeline if
1080 // requested.
1081 if (PrintPipelinePasses) {
1082 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1083 auto PassName = PIC.getPassNameForClassName(ClassName);
1084 return PassName.empty() ? ClassName : PassName;
1085 });
1086 outs() << "\n";
1087 return;
1088 }
1089
1090 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1091 LangOpts.HIPStdParInterposeAlloc)
1092 MPM.addPass(HipStdParAllocationInterpositionPass());
1093
1094 // Now that we have all of the passes ready, run them.
1095 {
1096 PrettyStackTraceString CrashInfo("Optimizer");
1097 llvm::TimeTraceScope TimeScope("Optimizer");
1098 MPM.run(*TheModule, MAM);
1099 }
1100}
1101
1102void EmitAssemblyHelper::RunCodegenPipeline(
1103 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1104 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1105 // We still use the legacy PM to run the codegen pipeline since the new PM
1106 // does not work with the codegen pipeline.
1107 // FIXME: make the new PM work with the codegen pipeline.
1108 legacy::PassManager CodeGenPasses;
1109
1110 // Append any output we need to the pass manager.
1111 switch (Action) {
1113 case Backend_EmitMCNull:
1114 case Backend_EmitObj:
1115 CodeGenPasses.add(
1116 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1117 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1118 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1119 if (!DwoOS)
1120 return;
1121 }
1122 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1123 DwoOS ? &DwoOS->os() : nullptr))
1124 // FIXME: Should we handle this error differently?
1125 return;
1126 break;
1127 default:
1128 return;
1129 }
1130
1131 // If -print-pipeline-passes is requested, don't run the legacy pass manager.
1132 // FIXME: when codegen is switched to use the new pass manager, it should also
1133 // emit pass names here.
1134 if (PrintPipelinePasses) {
1135 return;
1136 }
1137
1138 {
1139 PrettyStackTraceString CrashInfo("Code generation");
1140 llvm::TimeTraceScope TimeScope("CodeGenPasses");
1141 CodeGenPasses.run(*TheModule);
1142 }
1143}
1144
1145void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1146 std::unique_ptr<raw_pwrite_stream> OS,
1147 BackendConsumer *BC) {
1148 TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1149 setCommandLineOpts(CodeGenOpts);
1150
1151 bool RequiresCodeGen = actionRequiresCodeGen(Action);
1152 CreateTargetMachine(RequiresCodeGen);
1153
1154 if (RequiresCodeGen && !TM)
1155 return;
1156 if (TM)
1157 TheModule->setDataLayout(TM->createDataLayout());
1158
1159 // Before executing passes, print the final values of the LLVM options.
1160 cl::PrintOptionValues();
1161
1162 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1163 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1164 RunCodegenPipeline(Action, OS, DwoOS);
1165
1166 if (ThinLinkOS)
1167 ThinLinkOS->keep();
1168 if (DwoOS)
1169 DwoOS->keep();
1170}
1171
1173 DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex,
1174 llvm::Module *M, const HeaderSearchOptions &HeaderOpts,
1175 const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
1176 const LangOptions &LOpts, std::unique_ptr<raw_pwrite_stream> OS,
1177 std::string SampleProfile, std::string ProfileRemapping,
1178 BackendAction Action) {
1179 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1180 ModuleToDefinedGVSummaries;
1181 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1182
1183 setCommandLineOpts(CGOpts);
1184
1185 // We can simply import the values mentioned in the combined index, since
1186 // we should only invoke this using the individual indexes written out
1187 // via a WriteIndexesThinBackend.
1188 FunctionImporter::ImportMapTy ImportList;
1189 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1190 return;
1191
1192 auto AddStream = [&](size_t Task, const Twine &ModuleName) {
1193 return std::make_unique<CachedFileStream>(std::move(OS),
1194 CGOpts.ObjectFilenameForDebug);
1195 };
1196 lto::Config Conf;
1197 if (CGOpts.SaveTempsFilePrefix != "") {
1198 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1199 /* UseInputModulePath */ false)) {
1200 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1201 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1202 << '\n';
1203 });
1204 }
1205 }
1206 Conf.CPU = TOpts.CPU;
1207 Conf.CodeModel = getCodeModel(CGOpts);
1208 Conf.MAttrs = TOpts.Features;
1209 Conf.RelocModel = CGOpts.RelocationModel;
1210 std::optional<CodeGenOptLevel> OptLevelOrNone =
1211 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1212 assert(OptLevelOrNone && "Invalid optimization level!");
1213 Conf.CGOptLevel = *OptLevelOrNone;
1214 Conf.OptLevel = CGOpts.OptimizationLevel;
1215 initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1216 Conf.SampleProfile = std::move(SampleProfile);
1217 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1218 // For historical reasons, loop interleaving is set to mirror setting for loop
1219 // unrolling.
1220 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1221 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1222 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1223 // Only enable CGProfilePass when using integrated assembler, since
1224 // non-integrated assemblers don't recognize .cgprofile section.
1225 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1226
1227 // Context sensitive profile.
1228 if (CGOpts.hasProfileCSIRInstr()) {
1229 Conf.RunCSIRInstr = true;
1230 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1231 } else if (CGOpts.hasProfileCSIRUse()) {
1232 Conf.RunCSIRInstr = false;
1233 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1234 }
1235
1236 Conf.ProfileRemapping = std::move(ProfileRemapping);
1237 Conf.DebugPassManager = CGOpts.DebugPassManager;
1238 Conf.VerifyEach = CGOpts.VerifyEach;
1239 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1240 Conf.RemarksFilename = CGOpts.OptRecordFile;
1241 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1242 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1243 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1244 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1245 switch (Action) {
1247 Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) {
1248 return false;
1249 };
1250 break;
1251 case Backend_EmitLL:
1252 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1253 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1254 return false;
1255 };
1256 break;
1257 case Backend_EmitBC:
1258 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1259 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1260 return false;
1261 };
1262 break;
1263 default:
1264 Conf.CGFileType = getCodeGenFileType(Action);
1265 break;
1266 }
1267 if (Error E =
1268 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1269 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1270 /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1271 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1272 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1273 });
1274 }
1275}
1276
1278 DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderOpts,
1279 const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
1280 const LangOptions &LOpts, StringRef TDesc, llvm::Module *M,
1282 std::unique_ptr<raw_pwrite_stream> OS, BackendConsumer *BC) {
1283
1284 llvm::TimeTraceScope TimeScope("Backend");
1285
1286 std::unique_ptr<llvm::Module> EmptyModule;
1287 if (!CGOpts.ThinLTOIndexFile.empty()) {
1288 // If we are performing a ThinLTO importing compile, load the function index
1289 // into memory and pass it into runThinLTOBackend, which will run the
1290 // function importer and invoke LTO passes.
1291 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1292 if (Error E = llvm::getModuleSummaryIndexForFile(
1293 CGOpts.ThinLTOIndexFile,
1294 /*IgnoreEmptyThinLTOIndexFile*/ true)
1295 .moveInto(CombinedIndex)) {
1296 logAllUnhandledErrors(std::move(E), errs(),
1297 "Error loading index file '" +
1298 CGOpts.ThinLTOIndexFile + "': ");
1299 return;
1300 }
1301
1302 // A null CombinedIndex means we should skip ThinLTO compilation
1303 // (LLVM will optionally ignore empty index files, returning null instead
1304 // of an error).
1305 if (CombinedIndex) {
1306 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1307 runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1308 TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1309 CGOpts.ProfileRemappingFile, Action);
1310 return;
1311 }
1312 // Distributed indexing detected that nothing from the module is needed
1313 // for the final linking. So we can skip the compilation. We sill need to
1314 // output an empty object file to make sure that a linker does not fail
1315 // trying to read it. Also for some features, like CFI, we must skip
1316 // the compilation as CombinedIndex does not contain all required
1317 // information.
1318 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1319 EmptyModule->setTargetTriple(M->getTargetTriple());
1320 M = EmptyModule.get();
1321 }
1322 }
1323
1324 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M, VFS);
1325 AsmHelper.EmitAssembly(Action, std::move(OS), BC);
1326
1327 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1328 // DataLayout.
1329 if (AsmHelper.TM) {
1330 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1331 if (DLDesc != TDesc) {
1332 unsigned DiagID = Diags.getCustomDiagID(
1333 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1334 "expected target description '%1'");
1335 Diags.Report(DiagID) << DLDesc << TDesc;
1336 }
1337 }
1338}
1339
1340// With -fembed-bitcode, save a copy of the llvm IR as data in the
1341// __LLVM,__bitcode section.
1342void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1343 llvm::MemoryBufferRef Buf) {
1344 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1345 return;
1346 llvm::embedBitcodeInModule(
1347 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1348 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1349 CGOpts.CmdArgs);
1350}
1351
1352void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1353 DiagnosticsEngine &Diags) {
1354 if (CGOpts.OffloadObjects.empty())
1355 return;
1356
1357 for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1358 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1359 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1360 if (ObjectOrErr.getError()) {
1361 auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1362 "could not open '%0' for embedding");
1363 Diags.Report(DiagID) << OffloadObject;
1364 return;
1365 }
1366
1367 llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1368 Align(object::OffloadBinary::getAlignment()));
1369 }
1370}
static bool actionRequiresCodeGen(BackendAction Action)
static void addSanitizers(const Triple &TargetTriple, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static std::optional< llvm::CodeModel::Model > getCodeModel(const CodeGenOptions &CodeGenOpts)
static SanitizerBinaryMetadataOptions getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts)
static std::optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool initTargetOptions(DiagnosticsEngine &Diags, llvm::TargetOptions &Options, const CodeGenOptions &CodeGenOpts, const clang::TargetOptions &TargetOpts, const LangOptions &LangOpts, const HeaderSearchOptions &HSOpts)
static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts, PassBuilder &PB)
static void runThinLTOBackend(DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, llvm::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)
static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts)
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts)
static std::optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
Defines the Diagnostic-related interfaces.
Defines the clang::LangOptions interface.
This file provides a pass to link in Modules from a provided BackendConsumer.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines the clang::TargetOptions class.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
std::string BinutilsVersion
bool hasProfileIRUse() const
Check if IR level profile use is on.
char CoverageVersion[4]
The version string to put into coverage files.
std::string FloatABI
The ABI to use for passing floating point arguments.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
bool hasProfileCSIRInstr() const
Check if CS IR level profile instrumentation is on.
std::string DebugPass
Enable additional debugging information.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
uint64_t LargeDataThreshold
The code model-specific large data threshold to use (-mlarge-data-threshold).
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::function< void(llvm::PassBuilder &)> > PassBuilderCallbacks
List of pass builder callbacks.
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
std::string CodeModel
The code model to use (-mcmodel).
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::vector< std::string > PassPlugins
List of dynamic shared object files to be loaded as pass plugins.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::vector< std::string > SanitizeCoverageAllowlistFiles
Path to allowlist file specifying which objects (files, functions) should exclusively be instrumented...
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
std::vector< std::string > SanitizeCoverageIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
bool hasSanitizeCoverage() const
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
bool hasProfileCSIRUse() const
Check if CSIR profile use is on.
std::vector< std::string > SanitizeMetadataIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
std::string ProfileExcludeFiles
Regexes separated by a semi-colon to filter the files to not instrument.
std::string AsSecureLogFile
The name of a file to use with .secure_log_unique directives.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
bool hasSanitizeBinaryMetadata() const
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
std::vector< std::string > CommandLineArgs
std::string MemoryProfileUsePath
Name of the profile file to use as input for -fmemory-profile-use.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
std::vector< std::string > OffloadObjects
List of filenames passed in using the -fembed-offload-object option.
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
std::string ObjectFilenameForDebug
Output filename used in the COFF debug information.
std::string SplitDwarfOutput
Output filename for the split debug info, not used in the skeleton CU.
std::string DIBugsReportFilePath
The file to use for dumping bug report by Debugify for original debug info.
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::vector< Entry > UserEntries
User specified include entries.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:83
bool hasWasmExceptions() const
Definition: LangOptions.h:641
bool hasSjLjExceptions() const
Definition: LangOptions.h:629
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:399
bool hasDWARFExceptions() const
Definition: LangOptions.h:637
bool hasSEHExceptions() const
Definition: LangOptions.h:633
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
Definition: LangOptions.h:405
Options for controlling the target.
Definition: TargetOptions.h:26
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
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
llvm::EABI EABIVersion
The EABI version to use.
Definition: TargetOptions.h:48
Create and return a pass that links in Moduels from a provided BackendConsumer to a given primary Mod...
@ EmitAssembly
Emit a .s file.
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
BackendAction
Definition: BackendUtil.h:35
@ Backend_EmitAssembly
Emit native assembly files.
Definition: BackendUtil.h:36
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:38
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition: BackendUtil.h:37
@ Backend_EmitObj
Emit native object files.
Definition: BackendUtil.h:41
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition: BackendUtil.h:40
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition: BackendUtil.h:39
YAML serialization mapping.
Definition: Dominators.h:30
cl::opt< bool > PrintPipelinePasses
static cl::opt< bool > ClSanitizeOnOptimizerEarlyEP("sanitizer-early-opt-ep", cl::Optional, cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false))
cl::opt< bool > ClRelinkBuiltinBitcodePostop
Definition: Format.h:5226
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:159