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