Thanks to visit codestin.com
Credit goes to clang.llvm.org

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