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