1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/CodeGen/BackendUtil.h"
10 #include "clang/Basic/CodeGenOptions.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/FrontendDiagnostic.h"
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Lex/HeaderSearchOptions.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Analysis/AliasAnalysis.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/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/IRPrinter/IRPrintingPasses.h"
38 #include "llvm/LTO/LTOBackend.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/MC/TargetRegistry.h"
42 #include "llvm/Object/OffloadBinary.h"
43 #include "llvm/Passes/PassBuilder.h"
44 #include "llvm/Passes/PassPlugin.h"
45 #include "llvm/Passes/StandardInstrumentations.h"
46 #include "llvm/Support/BuryPointer.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/PrettyStackTrace.h"
50 #include "llvm/Support/TimeProfiler.h"
51 #include "llvm/Support/Timer.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/VirtualFileSystem.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include "llvm/Target/TargetOptions.h"
57 #include "llvm/TargetParser/Triple.h"
58 #include "llvm/Transforms/IPO/LowerTypeTests.h"
59 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
60 #include "llvm/Transforms/InstCombine/InstCombine.h"
61 #include "llvm/Transforms/Instrumentation.h"
62 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
63 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
64 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
65 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
66 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
67 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
68 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
69 #include "llvm/Transforms/Instrumentation/KCFI.h"
70 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
71 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
72 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
73 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
74 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
75 #include "llvm/Transforms/ObjCARC.h"
76 #include "llvm/Transforms/Scalar/EarlyCSE.h"
77 #include "llvm/Transforms/Scalar/GVN.h"
78 #include "llvm/Transforms/Scalar/JumpThreading.h"
79 #include "llvm/Transforms/Utils/Debugify.h"
80 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
81 #include "llvm/Transforms/Utils/ModuleUtils.h"
84 using namespace clang
;
87 #define HANDLE_EXTENSION(Ext) \
88 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
89 #include "llvm/Support/Extension.def"
92 extern cl::opt
<bool> DebugInfoCorrelate
;
94 // Experiment to move sanitizers earlier.
95 static cl::opt
<bool> ClSanitizeOnOptimizerEarlyEP(
96 "sanitizer-early-opt-ep", cl::Optional
,
97 cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false));
102 // Default filename used for profile generation.
103 std::string
getDefaultProfileGenName() {
104 return DebugInfoCorrelate
? "default_%p.proflite" : "default_%m.profraw";
107 class EmitAssemblyHelper
{
108 DiagnosticsEngine
&Diags
;
109 const HeaderSearchOptions
&HSOpts
;
110 const CodeGenOptions
&CodeGenOpts
;
111 const clang::TargetOptions
&TargetOpts
;
112 const LangOptions
&LangOpts
;
114 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
;
116 Timer CodeGenerationTime
;
118 std::unique_ptr
<raw_pwrite_stream
> OS
;
122 TargetIRAnalysis
getTargetIRAnalysis() const {
124 return TM
->getTargetIRAnalysis();
126 return TargetIRAnalysis();
129 /// Generates the TargetMachine.
130 /// Leaves TM unchanged if it is unable to create the target machine.
131 /// Some of our clang tests specify triples which are not built
132 /// into clang. This is okay because these tests check the generated
133 /// IR, and they require DataLayout which depends on the triple.
134 /// In this case, we allow this method to fail and not report an error.
135 /// When MustCreateTM is used, we print an error if we are unable to load
136 /// the requested target.
137 void CreateTargetMachine(bool MustCreateTM
);
139 /// Add passes necessary to emit assembly or LLVM IR.
141 /// \return True on success.
142 bool AddEmitPasses(legacy::PassManager
&CodeGenPasses
, BackendAction Action
,
143 raw_pwrite_stream
&OS
, raw_pwrite_stream
*DwoOS
);
145 std::unique_ptr
<llvm::ToolOutputFile
> openOutputFile(StringRef Path
) {
147 auto F
= std::make_unique
<llvm::ToolOutputFile
>(Path
, EC
,
148 llvm::sys::fs::OF_None
);
150 Diags
.Report(diag::err_fe_unable_to_open_output
) << Path
<< EC
.message();
157 RunOptimizationPipeline(BackendAction Action
,
158 std::unique_ptr
<raw_pwrite_stream
> &OS
,
159 std::unique_ptr
<llvm::ToolOutputFile
> &ThinLinkOS
);
160 void RunCodegenPipeline(BackendAction Action
,
161 std::unique_ptr
<raw_pwrite_stream
> &OS
,
162 std::unique_ptr
<llvm::ToolOutputFile
> &DwoOS
);
164 /// Check whether we should emit a module summary for regular LTO.
165 /// The module summary should be emitted by default for regular LTO
166 /// except for ld64 targets.
168 /// \return True if the module summary should be emitted.
169 bool shouldEmitRegularLTOSummary() const {
170 return CodeGenOpts
.PrepareForLTO
&& !CodeGenOpts
.DisableLLVMPasses
&&
171 TargetTriple
.getVendor() != llvm::Triple::Apple
;
175 EmitAssemblyHelper(DiagnosticsEngine
&_Diags
,
176 const HeaderSearchOptions
&HeaderSearchOpts
,
177 const CodeGenOptions
&CGOpts
,
178 const clang::TargetOptions
&TOpts
,
179 const LangOptions
&LOpts
, Module
*M
,
180 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
)
181 : Diags(_Diags
), HSOpts(HeaderSearchOpts
), CodeGenOpts(CGOpts
),
182 TargetOpts(TOpts
), LangOpts(LOpts
), TheModule(M
), VFS(std::move(VFS
)),
183 CodeGenerationTime("codegen", "Code Generation Time"),
184 TargetTriple(TheModule
->getTargetTriple()) {}
186 ~EmitAssemblyHelper() {
187 if (CodeGenOpts
.DisableFree
)
188 BuryPointer(std::move(TM
));
191 std::unique_ptr
<TargetMachine
> TM
;
193 // Emit output using the new pass manager for the optimization pipeline.
194 void EmitAssembly(BackendAction Action
,
195 std::unique_ptr
<raw_pwrite_stream
> OS
);
199 static SanitizerCoverageOptions
200 getSancovOptsFromCGOpts(const CodeGenOptions
&CGOpts
) {
201 SanitizerCoverageOptions Opts
;
203 static_cast<SanitizerCoverageOptions::Type
>(CGOpts
.SanitizeCoverageType
);
204 Opts
.IndirectCalls
= CGOpts
.SanitizeCoverageIndirectCalls
;
205 Opts
.TraceBB
= CGOpts
.SanitizeCoverageTraceBB
;
206 Opts
.TraceCmp
= CGOpts
.SanitizeCoverageTraceCmp
;
207 Opts
.TraceDiv
= CGOpts
.SanitizeCoverageTraceDiv
;
208 Opts
.TraceGep
= CGOpts
.SanitizeCoverageTraceGep
;
209 Opts
.Use8bitCounters
= CGOpts
.SanitizeCoverage8bitCounters
;
210 Opts
.TracePC
= CGOpts
.SanitizeCoverageTracePC
;
211 Opts
.TracePCGuard
= CGOpts
.SanitizeCoverageTracePCGuard
;
212 Opts
.NoPrune
= CGOpts
.SanitizeCoverageNoPrune
;
213 Opts
.Inline8bitCounters
= CGOpts
.SanitizeCoverageInline8bitCounters
;
214 Opts
.InlineBoolFlag
= CGOpts
.SanitizeCoverageInlineBoolFlag
;
215 Opts
.PCTable
= CGOpts
.SanitizeCoveragePCTable
;
216 Opts
.StackDepth
= CGOpts
.SanitizeCoverageStackDepth
;
217 Opts
.TraceLoads
= CGOpts
.SanitizeCoverageTraceLoads
;
218 Opts
.TraceStores
= CGOpts
.SanitizeCoverageTraceStores
;
219 Opts
.CollectControlFlow
= CGOpts
.SanitizeCoverageControlFlow
;
223 static SanitizerBinaryMetadataOptions
224 getSanitizerBinaryMetadataOptions(const CodeGenOptions
&CGOpts
) {
225 SanitizerBinaryMetadataOptions Opts
;
226 Opts
.Covered
= CGOpts
.SanitizeBinaryMetadataCovered
;
227 Opts
.Atomics
= CGOpts
.SanitizeBinaryMetadataAtomics
;
228 Opts
.UAR
= CGOpts
.SanitizeBinaryMetadataUAR
;
232 // Check if ASan should use GC-friendly instrumentation for globals.
233 // First of all, there is no point if -fdata-sections is off (expect for MachO,
234 // where this is not a factor). Also, on ELF this feature requires an assembler
235 // extension that only works with -integrated-as at the moment.
236 static bool asanUseGlobalsGC(const Triple
&T
, const CodeGenOptions
&CGOpts
) {
237 if (!CGOpts
.SanitizeAddressGlobalsDeadStripping
)
239 switch (T
.getObjectFormat()) {
244 return !CGOpts
.DisableIntegratedAS
;
246 llvm::report_fatal_error("ASan not implemented for GOFF");
248 llvm::report_fatal_error("ASan not implemented for XCOFF.");
250 case Triple::DXContainer
:
252 case Triple::UnknownObjectFormat
:
258 static TargetLibraryInfoImpl
*createTLII(llvm::Triple
&TargetTriple
,
259 const CodeGenOptions
&CodeGenOpts
) {
260 TargetLibraryInfoImpl
*TLII
= new TargetLibraryInfoImpl(TargetTriple
);
262 switch (CodeGenOpts
.getVecLib()) {
263 case CodeGenOptions::Accelerate
:
264 TLII
->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate
,
267 case CodeGenOptions::LIBMVEC
:
268 TLII
->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::LIBMVEC_X86
,
271 case CodeGenOptions::MASSV
:
272 TLII
->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV
,
275 case CodeGenOptions::SVML
:
276 TLII
->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML
,
279 case CodeGenOptions::SLEEF
:
280 TLII
->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SLEEFGNUABI
,
283 case CodeGenOptions::Darwin_libsystem_m
:
284 TLII
->addVectorizableFunctionsFromVecLib(
285 TargetLibraryInfoImpl::DarwinLibSystemM
, TargetTriple
);
293 static std::optional
<llvm::CodeModel::Model
>
294 getCodeModel(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 .Case("default", ~1u)
303 assert(CodeModel
!= ~0u && "invalid code model!");
304 if (CodeModel
== ~1u)
306 return static_cast<llvm::CodeModel::Model
>(CodeModel
);
309 static CodeGenFileType
getCodeGenFileType(BackendAction Action
) {
310 if (Action
== Backend_EmitObj
)
311 return CGFT_ObjectFile
;
312 else if (Action
== Backend_EmitMCNull
)
315 assert(Action
== Backend_EmitAssembly
&& "Invalid action!");
316 return CGFT_AssemblyFile
;
320 static bool actionRequiresCodeGen(BackendAction Action
) {
321 return Action
!= Backend_EmitNothing
&& Action
!= Backend_EmitBC
&&
322 Action
!= Backend_EmitLL
;
325 static bool initTargetOptions(DiagnosticsEngine
&Diags
,
326 llvm::TargetOptions
&Options
,
327 const CodeGenOptions
&CodeGenOpts
,
328 const clang::TargetOptions
&TargetOpts
,
329 const LangOptions
&LangOpts
,
330 const HeaderSearchOptions
&HSOpts
) {
331 switch (LangOpts
.getThreadModel()) {
332 case LangOptions::ThreadModelKind::POSIX
:
333 Options
.ThreadModel
= llvm::ThreadModel::POSIX
;
335 case LangOptions::ThreadModelKind::Single
:
336 Options
.ThreadModel
= llvm::ThreadModel::Single
;
340 // Set float ABI type.
341 assert((CodeGenOpts
.FloatABI
== "soft" || CodeGenOpts
.FloatABI
== "softfp" ||
342 CodeGenOpts
.FloatABI
== "hard" || CodeGenOpts
.FloatABI
.empty()) &&
343 "Invalid Floating Point ABI!");
344 Options
.FloatABIType
=
345 llvm::StringSwitch
<llvm::FloatABI::ABIType
>(CodeGenOpts
.FloatABI
)
346 .Case("soft", llvm::FloatABI::Soft
)
347 .Case("softfp", llvm::FloatABI::Soft
)
348 .Case("hard", llvm::FloatABI::Hard
)
349 .Default(llvm::FloatABI::Default
);
351 // Set FP fusion mode.
352 switch (LangOpts
.getDefaultFPContractMode()) {
353 case LangOptions::FPM_Off
:
354 // Preserve any contraction performed by the front-end. (Strict performs
355 // splitting of the muladd intrinsic in the backend.)
356 Options
.AllowFPOpFusion
= llvm::FPOpFusion::Standard
;
358 case LangOptions::FPM_On
:
359 case LangOptions::FPM_FastHonorPragmas
:
360 Options
.AllowFPOpFusion
= llvm::FPOpFusion::Standard
;
362 case LangOptions::FPM_Fast
:
363 Options
.AllowFPOpFusion
= llvm::FPOpFusion::Fast
;
367 Options
.BinutilsVersion
=
368 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts
.BinutilsVersion
);
369 Options
.UseInitArray
= CodeGenOpts
.UseInitArray
;
370 Options
.DisableIntegratedAS
= CodeGenOpts
.DisableIntegratedAS
;
371 Options
.CompressDebugSections
= CodeGenOpts
.getCompressDebugSections();
372 Options
.RelaxELFRelocations
= CodeGenOpts
.RelaxELFRelocations
;
375 Options
.EABIVersion
= TargetOpts
.EABIVersion
;
377 if (LangOpts
.hasSjLjExceptions())
378 Options
.ExceptionModel
= llvm::ExceptionHandling::SjLj
;
379 if (LangOpts
.hasSEHExceptions())
380 Options
.ExceptionModel
= llvm::ExceptionHandling::WinEH
;
381 if (LangOpts
.hasDWARFExceptions())
382 Options
.ExceptionModel
= llvm::ExceptionHandling::DwarfCFI
;
383 if (LangOpts
.hasWasmExceptions())
384 Options
.ExceptionModel
= llvm::ExceptionHandling::Wasm
;
386 Options
.NoInfsFPMath
= LangOpts
.NoHonorInfs
;
387 Options
.NoNaNsFPMath
= LangOpts
.NoHonorNaNs
;
388 Options
.NoZerosInBSS
= CodeGenOpts
.NoZeroInitializedInBSS
;
389 Options
.UnsafeFPMath
= LangOpts
.AllowFPReassoc
&& LangOpts
.AllowRecip
&&
390 LangOpts
.NoSignedZero
&& LangOpts
.ApproxFunc
&&
391 (LangOpts
.getDefaultFPContractMode() ==
392 LangOptions::FPModeKind::FPM_Fast
||
393 LangOpts
.getDefaultFPContractMode() ==
394 LangOptions::FPModeKind::FPM_FastHonorPragmas
);
395 Options
.ApproxFuncFPMath
= LangOpts
.ApproxFunc
;
398 llvm::StringSwitch
<llvm::BasicBlockSection
>(CodeGenOpts
.BBSections
)
399 .Case("all", llvm::BasicBlockSection::All
)
400 .Case("labels", llvm::BasicBlockSection::Labels
)
401 .StartsWith("list=", llvm::BasicBlockSection::List
)
402 .Case("none", llvm::BasicBlockSection::None
)
403 .Default(llvm::BasicBlockSection::None
);
405 if (Options
.BBSections
== llvm::BasicBlockSection::List
) {
406 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> MBOrErr
=
407 MemoryBuffer::getFile(CodeGenOpts
.BBSections
.substr(5));
409 Diags
.Report(diag::err_fe_unable_to_load_basic_block_sections_file
)
410 << MBOrErr
.getError().message();
413 Options
.BBSectionsFuncListBuf
= std::move(*MBOrErr
);
416 Options
.EnableMachineFunctionSplitter
= CodeGenOpts
.SplitMachineFunctions
;
417 Options
.FunctionSections
= CodeGenOpts
.FunctionSections
;
418 Options
.DataSections
= CodeGenOpts
.DataSections
;
419 Options
.IgnoreXCOFFVisibility
= LangOpts
.IgnoreXCOFFVisibility
;
420 Options
.UniqueSectionNames
= CodeGenOpts
.UniqueSectionNames
;
421 Options
.UniqueBasicBlockSectionNames
=
422 CodeGenOpts
.UniqueBasicBlockSectionNames
;
423 Options
.TLSSize
= CodeGenOpts
.TLSSize
;
424 Options
.EmulatedTLS
= CodeGenOpts
.EmulatedTLS
;
425 Options
.DebuggerTuning
= CodeGenOpts
.getDebuggerTuning();
426 Options
.EmitStackSizeSection
= CodeGenOpts
.StackSizeSection
;
427 Options
.StackUsageOutput
= CodeGenOpts
.StackUsageOutput
;
428 Options
.EmitAddrsig
= CodeGenOpts
.Addrsig
;
429 Options
.ForceDwarfFrameSection
= CodeGenOpts
.ForceDwarfFrameSection
;
430 Options
.EmitCallSiteInfo
= CodeGenOpts
.EmitCallSiteInfo
;
431 Options
.EnableAIXExtendedAltivecABI
= LangOpts
.EnableAIXExtendedAltivecABI
;
432 Options
.XRayFunctionIndex
= CodeGenOpts
.XRayFunctionIndex
;
433 Options
.LoopAlignment
= CodeGenOpts
.LoopAlignment
;
434 Options
.DebugStrictDwarf
= CodeGenOpts
.DebugStrictDwarf
;
435 Options
.ObjectFilenameForDebug
= CodeGenOpts
.ObjectFilenameForDebug
;
436 Options
.Hotpatch
= CodeGenOpts
.HotPatch
;
437 Options
.JMCInstrument
= CodeGenOpts
.JMCInstrument
;
438 Options
.XCOFFReadOnlyPointers
= CodeGenOpts
.XCOFFReadOnlyPointers
;
440 switch (CodeGenOpts
.getSwiftAsyncFramePointer()) {
441 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto
:
442 Options
.SwiftAsyncFramePointer
=
443 SwiftAsyncFramePointerMode::DeploymentBased
;
446 case CodeGenOptions::SwiftAsyncFramePointerKind::Always
:
447 Options
.SwiftAsyncFramePointer
= SwiftAsyncFramePointerMode::Always
;
450 case CodeGenOptions::SwiftAsyncFramePointerKind::Never
:
451 Options
.SwiftAsyncFramePointer
= SwiftAsyncFramePointerMode::Never
;
455 Options
.MCOptions
.SplitDwarfFile
= CodeGenOpts
.SplitDwarfFile
;
456 Options
.MCOptions
.EmitDwarfUnwind
= CodeGenOpts
.getEmitDwarfUnwind();
457 Options
.MCOptions
.EmitCompactUnwindNonCanonical
=
458 CodeGenOpts
.EmitCompactUnwindNonCanonical
;
459 Options
.MCOptions
.MCRelaxAll
= CodeGenOpts
.RelaxAll
;
460 Options
.MCOptions
.MCSaveTempLabels
= CodeGenOpts
.SaveTempLabels
;
461 Options
.MCOptions
.MCUseDwarfDirectory
=
462 CodeGenOpts
.NoDwarfDirectoryAsm
463 ? llvm::MCTargetOptions::DisableDwarfDirectory
464 : llvm::MCTargetOptions::EnableDwarfDirectory
;
465 Options
.MCOptions
.MCNoExecStack
= CodeGenOpts
.NoExecStack
;
466 Options
.MCOptions
.MCIncrementalLinkerCompatible
=
467 CodeGenOpts
.IncrementalLinkerCompatible
;
468 Options
.MCOptions
.MCFatalWarnings
= CodeGenOpts
.FatalWarnings
;
469 Options
.MCOptions
.MCNoWarn
= CodeGenOpts
.NoWarn
;
470 Options
.MCOptions
.AsmVerbose
= CodeGenOpts
.AsmVerbose
;
471 Options
.MCOptions
.Dwarf64
= CodeGenOpts
.Dwarf64
;
472 Options
.MCOptions
.PreserveAsmComments
= CodeGenOpts
.PreserveAsmComments
;
473 Options
.MCOptions
.ABIName
= TargetOpts
.ABI
;
474 for (const auto &Entry
: HSOpts
.UserEntries
)
475 if (!Entry
.IsFramework
&&
476 (Entry
.Group
== frontend::IncludeDirGroup::Quoted
||
477 Entry
.Group
== frontend::IncludeDirGroup::Angled
||
478 Entry
.Group
== frontend::IncludeDirGroup::System
))
479 Options
.MCOptions
.IASSearchPaths
.push_back(
480 Entry
.IgnoreSysRoot
? Entry
.Path
: HSOpts
.Sysroot
+ Entry
.Path
);
481 Options
.MCOptions
.Argv0
= CodeGenOpts
.Argv0
;
482 Options
.MCOptions
.CommandLineArgs
= CodeGenOpts
.CommandLineArgs
;
483 Options
.MCOptions
.AsSecureLogFile
= CodeGenOpts
.AsSecureLogFile
;
484 Options
.MisExpect
= CodeGenOpts
.MisExpect
;
489 static std::optional
<GCOVOptions
>
490 getGCOVOptions(const CodeGenOptions
&CodeGenOpts
, const LangOptions
&LangOpts
) {
491 if (CodeGenOpts
.CoverageNotesFile
.empty() &&
492 CodeGenOpts
.CoverageDataFile
.empty())
494 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
495 // LLVM's -default-gcov-version flag is set to something invalid.
497 Options
.EmitNotes
= !CodeGenOpts
.CoverageNotesFile
.empty();
498 Options
.EmitData
= !CodeGenOpts
.CoverageDataFile
.empty();
499 llvm::copy(CodeGenOpts
.CoverageVersion
, std::begin(Options
.Version
));
500 Options
.NoRedZone
= CodeGenOpts
.DisableRedZone
;
501 Options
.Filter
= CodeGenOpts
.ProfileFilterFiles
;
502 Options
.Exclude
= CodeGenOpts
.ProfileExcludeFiles
;
503 Options
.Atomic
= CodeGenOpts
.AtomicProfileUpdate
;
507 static std::optional
<InstrProfOptions
>
508 getInstrProfOptions(const CodeGenOptions
&CodeGenOpts
,
509 const LangOptions
&LangOpts
) {
510 if (!CodeGenOpts
.hasProfileClangInstr())
512 InstrProfOptions Options
;
513 Options
.NoRedZone
= CodeGenOpts
.DisableRedZone
;
514 Options
.InstrProfileOutput
= CodeGenOpts
.InstrProfileOutput
;
515 Options
.Atomic
= CodeGenOpts
.AtomicProfileUpdate
;
519 static void setCommandLineOpts(const CodeGenOptions
&CodeGenOpts
) {
520 SmallVector
<const char *, 16> BackendArgs
;
521 BackendArgs
.push_back("clang"); // Fake program name.
522 if (!CodeGenOpts
.DebugPass
.empty()) {
523 BackendArgs
.push_back("-debug-pass");
524 BackendArgs
.push_back(CodeGenOpts
.DebugPass
.c_str());
526 if (!CodeGenOpts
.LimitFloatPrecision
.empty()) {
527 BackendArgs
.push_back("-limit-float-precision");
528 BackendArgs
.push_back(CodeGenOpts
.LimitFloatPrecision
.c_str());
530 // Check for the default "clang" invocation that won't set any cl::opt values.
531 // Skip trying to parse the command line invocation to avoid the issues
533 if (BackendArgs
.size() == 1)
535 BackendArgs
.push_back(nullptr);
536 // FIXME: The command line parser below is not thread-safe and shares a global
537 // state, so this call might crash or overwrite the options of another Clang
538 // instance in the same process.
539 llvm::cl::ParseCommandLineOptions(BackendArgs
.size() - 1,
543 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM
) {
544 // Create the TargetMachine for generating code.
546 std::string Triple
= TheModule
->getTargetTriple();
547 const llvm::Target
*TheTarget
= TargetRegistry::lookupTarget(Triple
, Error
);
550 Diags
.Report(diag::err_fe_unable_to_create_target
) << Error
;
554 std::optional
<llvm::CodeModel::Model
> CM
= getCodeModel(CodeGenOpts
);
555 std::string FeaturesStr
=
556 llvm::join(TargetOpts
.Features
.begin(), TargetOpts
.Features
.end(), ",");
557 llvm::Reloc::Model RM
= CodeGenOpts
.RelocationModel
;
558 std::optional
<CodeGenOpt::Level
> OptLevelOrNone
=
559 CodeGenOpt::getLevel(CodeGenOpts
.OptimizationLevel
);
560 assert(OptLevelOrNone
&& "Invalid optimization level!");
561 CodeGenOpt::Level OptLevel
= *OptLevelOrNone
;
563 llvm::TargetOptions Options
;
564 if (!initTargetOptions(Diags
, Options
, CodeGenOpts
, TargetOpts
, LangOpts
,
567 TM
.reset(TheTarget
->createTargetMachine(Triple
, TargetOpts
.CPU
, FeaturesStr
,
568 Options
, RM
, CM
, OptLevel
));
571 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager
&CodeGenPasses
,
572 BackendAction Action
,
573 raw_pwrite_stream
&OS
,
574 raw_pwrite_stream
*DwoOS
) {
576 std::unique_ptr
<TargetLibraryInfoImpl
> TLII(
577 createTLII(TargetTriple
, CodeGenOpts
));
578 CodeGenPasses
.add(new TargetLibraryInfoWrapperPass(*TLII
));
580 // Normal mode, emit a .s or .o file by running the code generator. Note,
581 // this also adds codegenerator level optimization passes.
582 CodeGenFileType CGFT
= getCodeGenFileType(Action
);
584 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
585 // "codegen" passes so that it isn't run multiple times when there is
586 // inlining happening.
587 if (CodeGenOpts
.OptimizationLevel
> 0)
588 CodeGenPasses
.add(createObjCARCContractPass());
590 if (TM
->addPassesToEmitFile(CodeGenPasses
, OS
, DwoOS
, CGFT
,
591 /*DisableVerify=*/!CodeGenOpts
.VerifyModule
)) {
592 Diags
.Report(diag::err_fe_unable_to_interface_with_target
);
599 static OptimizationLevel
mapToLevel(const CodeGenOptions
&Opts
) {
600 switch (Opts
.OptimizationLevel
) {
602 llvm_unreachable("Invalid optimization level!");
605 return OptimizationLevel::O0
;
608 return OptimizationLevel::O1
;
611 switch (Opts
.OptimizeSize
) {
613 llvm_unreachable("Invalid optimization level for size!");
616 return OptimizationLevel::O2
;
619 return OptimizationLevel::Os
;
622 return OptimizationLevel::Oz
;
626 return OptimizationLevel::O3
;
630 static void addKCFIPass(const Triple
&TargetTriple
, const LangOptions
&LangOpts
,
632 // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
633 if (TargetTriple
.getArch() == llvm::Triple::x86_64
||
634 TargetTriple
.isAArch64(64))
637 // Ensure we lower KCFI operand bundles with -O0.
638 PB
.registerOptimizerLastEPCallback(
639 [&](ModulePassManager
&MPM
, OptimizationLevel Level
) {
640 if (Level
== OptimizationLevel::O0
&&
641 LangOpts
.Sanitize
.has(SanitizerKind::KCFI
))
642 MPM
.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
645 // When optimizations are requested, run KCIFPass after InstCombine to
646 // avoid unnecessary checks.
647 PB
.registerPeepholeEPCallback(
648 [&](FunctionPassManager
&FPM
, OptimizationLevel Level
) {
649 if (Level
!= OptimizationLevel::O0
&&
650 LangOpts
.Sanitize
.has(SanitizerKind::KCFI
))
651 FPM
.addPass(KCFIPass());
655 static void addSanitizers(const Triple
&TargetTriple
,
656 const CodeGenOptions
&CodeGenOpts
,
657 const LangOptions
&LangOpts
, PassBuilder
&PB
) {
658 auto SanitizersCallback
= [&](ModulePassManager
&MPM
,
659 OptimizationLevel Level
) {
660 if (CodeGenOpts
.hasSanitizeCoverage()) {
661 auto SancovOpts
= getSancovOptsFromCGOpts(CodeGenOpts
);
662 MPM
.addPass(SanitizerCoveragePass(
663 SancovOpts
, CodeGenOpts
.SanitizeCoverageAllowlistFiles
,
664 CodeGenOpts
.SanitizeCoverageIgnorelistFiles
));
667 if (CodeGenOpts
.hasSanitizeBinaryMetadata()) {
668 MPM
.addPass(SanitizerBinaryMetadataPass(
669 getSanitizerBinaryMetadataOptions(CodeGenOpts
),
670 CodeGenOpts
.SanitizeMetadataIgnorelistFiles
));
673 auto MSanPass
= [&](SanitizerMask Mask
, bool CompileKernel
) {
674 if (LangOpts
.Sanitize
.has(Mask
)) {
675 int TrackOrigins
= CodeGenOpts
.SanitizeMemoryTrackOrigins
;
676 bool Recover
= CodeGenOpts
.SanitizeRecover
.has(Mask
);
678 MemorySanitizerOptions
options(TrackOrigins
, Recover
, CompileKernel
,
679 CodeGenOpts
.SanitizeMemoryParamRetval
);
680 MPM
.addPass(MemorySanitizerPass(options
));
681 if (Level
!= OptimizationLevel::O0
) {
682 // MemorySanitizer inserts complex instrumentation that mostly follows
683 // the logic of the original code, but operates on "shadow" values. It
684 // can benefit from re-running some general purpose optimization
686 MPM
.addPass(RequireAnalysisPass
<GlobalsAA
, Module
>());
687 FunctionPassManager FPM
;
688 FPM
.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
689 FPM
.addPass(InstCombinePass());
690 FPM
.addPass(JumpThreadingPass());
691 FPM
.addPass(GVNPass());
692 FPM
.addPass(InstCombinePass());
693 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(FPM
)));
697 MSanPass(SanitizerKind::Memory
, false);
698 MSanPass(SanitizerKind::KernelMemory
, true);
700 if (LangOpts
.Sanitize
.has(SanitizerKind::Thread
)) {
701 MPM
.addPass(ModuleThreadSanitizerPass());
702 MPM
.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
705 auto ASanPass
= [&](SanitizerMask Mask
, bool CompileKernel
) {
706 if (LangOpts
.Sanitize
.has(Mask
)) {
707 bool UseGlobalGC
= asanUseGlobalsGC(TargetTriple
, CodeGenOpts
);
708 bool UseOdrIndicator
= CodeGenOpts
.SanitizeAddressUseOdrIndicator
;
709 llvm::AsanDtorKind DestructorKind
=
710 CodeGenOpts
.getSanitizeAddressDtor();
711 AddressSanitizerOptions Opts
;
712 Opts
.CompileKernel
= CompileKernel
;
713 Opts
.Recover
= CodeGenOpts
.SanitizeRecover
.has(Mask
);
714 Opts
.UseAfterScope
= CodeGenOpts
.SanitizeAddressUseAfterScope
;
715 Opts
.UseAfterReturn
= CodeGenOpts
.getSanitizeAddressUseAfterReturn();
716 MPM
.addPass(AddressSanitizerPass(Opts
, UseGlobalGC
, UseOdrIndicator
,
720 ASanPass(SanitizerKind::Address
, false);
721 ASanPass(SanitizerKind::KernelAddress
, true);
723 auto HWASanPass
= [&](SanitizerMask Mask
, bool CompileKernel
) {
724 if (LangOpts
.Sanitize
.has(Mask
)) {
725 bool Recover
= CodeGenOpts
.SanitizeRecover
.has(Mask
);
726 MPM
.addPass(HWAddressSanitizerPass(
727 {CompileKernel
, Recover
,
728 /*DisableOptimization=*/CodeGenOpts
.OptimizationLevel
== 0}));
731 HWASanPass(SanitizerKind::HWAddress
, false);
732 HWASanPass(SanitizerKind::KernelHWAddress
, true);
734 if (LangOpts
.Sanitize
.has(SanitizerKind::DataFlow
)) {
735 MPM
.addPass(DataFlowSanitizerPass(LangOpts
.NoSanitizeFiles
));
738 if (ClSanitizeOnOptimizerEarlyEP
) {
739 PB
.registerOptimizerEarlyEPCallback(
740 [SanitizersCallback
](ModulePassManager
&MPM
, OptimizationLevel Level
) {
741 ModulePassManager NewMPM
;
742 SanitizersCallback(NewMPM
, Level
);
743 if (!NewMPM
.isEmpty()) {
744 // Sanitizers can abandon<GlobalsAA>.
745 NewMPM
.addPass(RequireAnalysisPass
<GlobalsAA
, Module
>());
746 MPM
.addPass(std::move(NewMPM
));
750 // LastEP does not need GlobalsAA.
751 PB
.registerOptimizerLastEPCallback(SanitizersCallback
);
755 void EmitAssemblyHelper::RunOptimizationPipeline(
756 BackendAction Action
, std::unique_ptr
<raw_pwrite_stream
> &OS
,
757 std::unique_ptr
<llvm::ToolOutputFile
> &ThinLinkOS
) {
758 std::optional
<PGOOptions
> PGOOpt
;
760 if (CodeGenOpts
.hasProfileIRInstr())
761 // -fprofile-generate.
763 CodeGenOpts
.InstrProfileOutput
.empty() ? getDefaultProfileGenName()
764 : CodeGenOpts
.InstrProfileOutput
,
765 "", "", nullptr, PGOOptions::IRInstr
, PGOOptions::NoCSAction
,
766 CodeGenOpts
.DebugInfoForProfiling
);
767 else if (CodeGenOpts
.hasProfileIRUse()) {
769 auto CSAction
= CodeGenOpts
.hasProfileCSIRUse() ? PGOOptions::CSIRUse
770 : PGOOptions::NoCSAction
;
772 PGOOptions(CodeGenOpts
.ProfileInstrumentUsePath
, "",
773 CodeGenOpts
.ProfileRemappingFile
, VFS
, PGOOptions::IRUse
,
774 CSAction
, CodeGenOpts
.DebugInfoForProfiling
);
775 } else if (!CodeGenOpts
.SampleProfileFile
.empty())
776 // -fprofile-sample-use
778 CodeGenOpts
.SampleProfileFile
, "", CodeGenOpts
.ProfileRemappingFile
,
779 VFS
, PGOOptions::SampleUse
, PGOOptions::NoCSAction
,
780 CodeGenOpts
.DebugInfoForProfiling
, CodeGenOpts
.PseudoProbeForProfiling
);
781 else if (CodeGenOpts
.PseudoProbeForProfiling
)
782 // -fpseudo-probe-for-profiling
783 PGOOpt
= PGOOptions("", "", "", nullptr, PGOOptions::NoAction
,
784 PGOOptions::NoCSAction
,
785 CodeGenOpts
.DebugInfoForProfiling
, true);
786 else if (CodeGenOpts
.DebugInfoForProfiling
)
787 // -fdebug-info-for-profiling
788 PGOOpt
= PGOOptions("", "", "", nullptr, PGOOptions::NoAction
,
789 PGOOptions::NoCSAction
, true);
791 // Check to see if we want to generate a CS profile.
792 if (CodeGenOpts
.hasProfileCSIRInstr()) {
793 assert(!CodeGenOpts
.hasProfileCSIRUse() &&
794 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
797 assert(PGOOpt
->Action
!= PGOOptions::IRInstr
&&
798 PGOOpt
->Action
!= PGOOptions::SampleUse
&&
799 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
801 PGOOpt
->CSProfileGenFile
= CodeGenOpts
.InstrProfileOutput
.empty()
802 ? getDefaultProfileGenName()
803 : CodeGenOpts
.InstrProfileOutput
;
804 PGOOpt
->CSAction
= PGOOptions::CSIRInstr
;
808 CodeGenOpts
.InstrProfileOutput
.empty()
809 ? getDefaultProfileGenName()
810 : CodeGenOpts
.InstrProfileOutput
,
811 "", nullptr, PGOOptions::NoAction
, PGOOptions::CSIRInstr
,
812 CodeGenOpts
.DebugInfoForProfiling
);
815 TM
->setPGOOption(PGOOpt
);
817 PipelineTuningOptions PTO
;
818 PTO
.LoopUnrolling
= CodeGenOpts
.UnrollLoops
;
819 // For historical reasons, loop interleaving is set to mirror setting for loop
821 PTO
.LoopInterleaving
= CodeGenOpts
.UnrollLoops
;
822 PTO
.LoopVectorization
= CodeGenOpts
.VectorizeLoop
;
823 PTO
.SLPVectorization
= CodeGenOpts
.VectorizeSLP
;
824 PTO
.MergeFunctions
= CodeGenOpts
.MergeFunctions
;
825 // Only enable CGProfilePass when using integrated assembler, since
826 // non-integrated assemblers don't recognize .cgprofile section.
827 PTO
.CallGraphProfile
= !CodeGenOpts
.DisableIntegratedAS
;
829 LoopAnalysisManager LAM
;
830 FunctionAnalysisManager FAM
;
831 CGSCCAnalysisManager CGAM
;
832 ModuleAnalysisManager MAM
;
834 bool DebugPassStructure
= CodeGenOpts
.DebugPass
== "Structure";
835 PassInstrumentationCallbacks PIC
;
836 PrintPassOptions PrintPassOpts
;
837 PrintPassOpts
.Indent
= DebugPassStructure
;
838 PrintPassOpts
.SkipAnalyses
= DebugPassStructure
;
839 StandardInstrumentations
SI(
840 TheModule
->getContext(),
841 (CodeGenOpts
.DebugPassManager
|| DebugPassStructure
),
842 /*VerifyEach*/ false, PrintPassOpts
);
843 SI
.registerCallbacks(PIC
, &MAM
);
844 PassBuilder
PB(TM
.get(), PTO
, PGOOpt
, &PIC
);
846 // Handle the assignment tracking feature options.
847 switch (CodeGenOpts
.getAssignmentTrackingMode()) {
848 case CodeGenOptions::AssignmentTrackingOpts::Forced
:
849 PB
.registerPipelineStartEPCallback(
850 [&](ModulePassManager
&MPM
, OptimizationLevel Level
) {
851 MPM
.addPass(AssignmentTrackingPass());
854 case CodeGenOptions::AssignmentTrackingOpts::Enabled
:
855 // Disable assignment tracking in LTO builds for now as the performance
856 // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
857 if (!CodeGenOpts
.PrepareForThinLTO
&& !CodeGenOpts
.PrepareForLTO
&&
858 CodeGenOpts
.getDebuggerTuning() != llvm::DebuggerKind::LLDB
) {
859 PB
.registerPipelineStartEPCallback(
860 [&](ModulePassManager
&MPM
, OptimizationLevel Level
) {
861 // Only use assignment tracking if optimisations are enabled.
862 if (Level
!= OptimizationLevel::O0
)
863 MPM
.addPass(AssignmentTrackingPass());
867 case CodeGenOptions::AssignmentTrackingOpts::Disabled
:
871 // Enable verify-debuginfo-preserve-each for new PM.
872 DebugifyEachInstrumentation Debugify
;
873 DebugInfoPerPass DebugInfoBeforePass
;
874 if (CodeGenOpts
.EnableDIPreservationVerify
) {
875 Debugify
.setDebugifyMode(DebugifyMode::OriginalDebugInfo
);
876 Debugify
.setDebugInfoBeforePass(DebugInfoBeforePass
);
878 if (!CodeGenOpts
.DIBugsReportFilePath
.empty())
879 Debugify
.setOrigDIVerifyBugsReportFilePath(
880 CodeGenOpts
.DIBugsReportFilePath
);
881 Debugify
.registerCallbacks(PIC
, MAM
);
883 // Attempt to load pass plugins and register their callbacks with PB.
884 for (auto &PluginFN
: CodeGenOpts
.PassPlugins
) {
885 auto PassPlugin
= PassPlugin::Load(PluginFN
);
887 PassPlugin
->registerPassBuilderCallbacks(PB
);
889 Diags
.Report(diag::err_fe_unable_to_load_plugin
)
890 << PluginFN
<< toString(PassPlugin
.takeError());
893 #define HANDLE_EXTENSION(Ext) \
894 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
895 #include "llvm/Support/Extension.def"
897 // Register the target library analysis directly and give it a customized
899 std::unique_ptr
<TargetLibraryInfoImpl
> TLII(
900 createTLII(TargetTriple
, CodeGenOpts
));
901 FAM
.registerPass([&] { return TargetLibraryAnalysis(*TLII
); });
903 // Register all the basic analyses with the managers.
904 PB
.registerModuleAnalyses(MAM
);
905 PB
.registerCGSCCAnalyses(CGAM
);
906 PB
.registerFunctionAnalyses(FAM
);
907 PB
.registerLoopAnalyses(LAM
);
908 PB
.crossRegisterProxies(LAM
, FAM
, CGAM
, MAM
);
910 ModulePassManager MPM
;
912 if (!CodeGenOpts
.DisableLLVMPasses
) {
913 // Map our optimization levels into one of the distinct levels used to
914 // configure the pipeline.
915 OptimizationLevel Level
= mapToLevel(CodeGenOpts
);
917 bool IsThinLTO
= CodeGenOpts
.PrepareForThinLTO
;
918 bool IsLTO
= CodeGenOpts
.PrepareForLTO
;
920 if (LangOpts
.ObjCAutoRefCount
) {
921 PB
.registerPipelineStartEPCallback(
922 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
923 if (Level
!= OptimizationLevel::O0
)
925 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
927 PB
.registerPipelineEarlySimplificationEPCallback(
928 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
929 if (Level
!= OptimizationLevel::O0
)
930 MPM
.addPass(ObjCARCAPElimPass());
932 PB
.registerScalarOptimizerLateEPCallback(
933 [](FunctionPassManager
&FPM
, OptimizationLevel Level
) {
934 if (Level
!= OptimizationLevel::O0
)
935 FPM
.addPass(ObjCARCOptPass());
939 // If we reached here with a non-empty index file name, then the index
940 // file was empty and we are not performing ThinLTO backend compilation
941 // (used in testing in a distributed build environment).
942 bool IsThinLTOPostLink
= !CodeGenOpts
.ThinLTOIndexFile
.empty();
943 // If so drop any the type test assume sequences inserted for whole program
944 // vtables so that codegen doesn't complain.
945 if (IsThinLTOPostLink
)
946 PB
.registerPipelineStartEPCallback(
947 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
948 MPM
.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
949 /*ImportSummary=*/nullptr,
950 /*DropTypeTests=*/true));
953 if (CodeGenOpts
.InstrumentFunctions
||
954 CodeGenOpts
.InstrumentFunctionEntryBare
||
955 CodeGenOpts
.InstrumentFunctionsAfterInlining
||
956 CodeGenOpts
.InstrumentForProfiling
) {
957 PB
.registerPipelineStartEPCallback(
958 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
959 MPM
.addPass(createModuleToFunctionPassAdaptor(
960 EntryExitInstrumenterPass(/*PostInlining=*/false)));
962 PB
.registerOptimizerLastEPCallback(
963 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
964 MPM
.addPass(createModuleToFunctionPassAdaptor(
965 EntryExitInstrumenterPass(/*PostInlining=*/true)));
969 // Register callbacks to schedule sanitizer passes at the appropriate part
971 if (LangOpts
.Sanitize
.has(SanitizerKind::LocalBounds
))
972 PB
.registerScalarOptimizerLateEPCallback(
973 [](FunctionPassManager
&FPM
, OptimizationLevel Level
) {
974 FPM
.addPass(BoundsCheckingPass());
977 // Don't add sanitizers if we are here from ThinLTO PostLink. That already
978 // done on PreLink stage.
979 if (!IsThinLTOPostLink
) {
980 addSanitizers(TargetTriple
, CodeGenOpts
, LangOpts
, PB
);
981 addKCFIPass(TargetTriple
, LangOpts
, PB
);
984 if (std::optional
<GCOVOptions
> Options
=
985 getGCOVOptions(CodeGenOpts
, LangOpts
))
986 PB
.registerPipelineStartEPCallback(
987 [Options
](ModulePassManager
&MPM
, OptimizationLevel Level
) {
988 MPM
.addPass(GCOVProfilerPass(*Options
));
990 if (std::optional
<InstrProfOptions
> Options
=
991 getInstrProfOptions(CodeGenOpts
, LangOpts
))
992 PB
.registerPipelineStartEPCallback(
993 [Options
](ModulePassManager
&MPM
, OptimizationLevel Level
) {
994 MPM
.addPass(InstrProfiling(*Options
, false));
997 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
998 // the PGOOptions, and set this up there.
999 if (!CodeGenOpts
.MemoryProfileOutput
.empty()) {
1000 PB
.registerOptimizerLastEPCallback(
1001 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
1002 MPM
.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1003 MPM
.addPass(ModuleMemProfilerPass());
1008 MPM
= PB
.buildThinLTOPreLinkDefaultPipeline(Level
);
1010 MPM
= PB
.buildLTOPreLinkDefaultPipeline(Level
);
1012 MPM
= PB
.buildPerModuleDefaultPipeline(Level
);
1016 // Add a verifier pass if requested. We don't have to do this if the action
1017 // requires code generation because there will already be a verifier pass in
1018 // the code-generation pipeline.
1019 if (!actionRequiresCodeGen(Action
) && CodeGenOpts
.VerifyModule
)
1020 MPM
.addPass(VerifierPass());
1022 if (Action
== Backend_EmitBC
|| Action
== Backend_EmitLL
) {
1023 if (CodeGenOpts
.PrepareForThinLTO
&& !CodeGenOpts
.DisableLLVMPasses
) {
1024 if (!TheModule
->getModuleFlag("EnableSplitLTOUnit"))
1025 TheModule
->addModuleFlag(Module::Error
, "EnableSplitLTOUnit",
1026 CodeGenOpts
.EnableSplitLTOUnit
);
1027 if (Action
== Backend_EmitBC
) {
1028 if (!CodeGenOpts
.ThinLinkBitcodeFile
.empty()) {
1029 ThinLinkOS
= openOutputFile(CodeGenOpts
.ThinLinkBitcodeFile
);
1033 MPM
.addPass(ThinLTOBitcodeWriterPass(*OS
, ThinLinkOS
? &ThinLinkOS
->os()
1036 MPM
.addPass(PrintModulePass(*OS
, "", CodeGenOpts
.EmitLLVMUseLists
,
1037 /*EmitLTOSummary=*/true));
1041 // Emit a module summary by default for Regular LTO except for ld64
1043 bool EmitLTOSummary
= shouldEmitRegularLTOSummary();
1044 if (EmitLTOSummary
) {
1045 if (!TheModule
->getModuleFlag("ThinLTO"))
1046 TheModule
->addModuleFlag(Module::Error
, "ThinLTO", uint32_t(0));
1047 if (!TheModule
->getModuleFlag("EnableSplitLTOUnit"))
1048 TheModule
->addModuleFlag(Module::Error
, "EnableSplitLTOUnit",
1051 if (Action
== Backend_EmitBC
)
1052 MPM
.addPass(BitcodeWriterPass(*OS
, CodeGenOpts
.EmitLLVMUseLists
,
1055 MPM
.addPass(PrintModulePass(*OS
, "", CodeGenOpts
.EmitLLVMUseLists
,
1060 // Now that we have all of the passes ready, run them.
1062 PrettyStackTraceString
CrashInfo("Optimizer");
1063 llvm::TimeTraceScope
TimeScope("Optimizer");
1064 MPM
.run(*TheModule
, MAM
);
1068 void EmitAssemblyHelper::RunCodegenPipeline(
1069 BackendAction Action
, std::unique_ptr
<raw_pwrite_stream
> &OS
,
1070 std::unique_ptr
<llvm::ToolOutputFile
> &DwoOS
) {
1071 // We still use the legacy PM to run the codegen pipeline since the new PM
1072 // does not work with the codegen pipeline.
1073 // FIXME: make the new PM work with the codegen pipeline.
1074 legacy::PassManager CodeGenPasses
;
1076 // Append any output we need to the pass manager.
1078 case Backend_EmitAssembly
:
1079 case Backend_EmitMCNull
:
1080 case Backend_EmitObj
:
1082 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1083 if (!CodeGenOpts
.SplitDwarfOutput
.empty()) {
1084 DwoOS
= openOutputFile(CodeGenOpts
.SplitDwarfOutput
);
1088 if (!AddEmitPasses(CodeGenPasses
, Action
, *OS
,
1089 DwoOS
? &DwoOS
->os() : nullptr))
1090 // FIXME: Should we handle this error differently?
1098 PrettyStackTraceString
CrashInfo("Code generation");
1099 llvm::TimeTraceScope
TimeScope("CodeGenPasses");
1100 CodeGenPasses
.run(*TheModule
);
1104 void EmitAssemblyHelper::EmitAssembly(BackendAction Action
,
1105 std::unique_ptr
<raw_pwrite_stream
> OS
) {
1106 TimeRegion
Region(CodeGenOpts
.TimePasses
? &CodeGenerationTime
: nullptr);
1107 setCommandLineOpts(CodeGenOpts
);
1109 bool RequiresCodeGen
= actionRequiresCodeGen(Action
);
1110 CreateTargetMachine(RequiresCodeGen
);
1112 if (RequiresCodeGen
&& !TM
)
1115 TheModule
->setDataLayout(TM
->createDataLayout());
1117 // Before executing passes, print the final values of the LLVM options.
1118 cl::PrintOptionValues();
1120 std::unique_ptr
<llvm::ToolOutputFile
> ThinLinkOS
, DwoOS
;
1121 RunOptimizationPipeline(Action
, OS
, ThinLinkOS
);
1122 RunCodegenPipeline(Action
, OS
, DwoOS
);
1130 static void runThinLTOBackend(
1131 DiagnosticsEngine
&Diags
, ModuleSummaryIndex
*CombinedIndex
, Module
*M
,
1132 const HeaderSearchOptions
&HeaderOpts
, const CodeGenOptions
&CGOpts
,
1133 const clang::TargetOptions
&TOpts
, const LangOptions
&LOpts
,
1134 std::unique_ptr
<raw_pwrite_stream
> OS
, std::string SampleProfile
,
1135 std::string ProfileRemapping
, BackendAction Action
) {
1136 StringMap
<DenseMap
<GlobalValue::GUID
, GlobalValueSummary
*>>
1137 ModuleToDefinedGVSummaries
;
1138 CombinedIndex
->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries
);
1140 setCommandLineOpts(CGOpts
);
1142 // We can simply import the values mentioned in the combined index, since
1143 // we should only invoke this using the individual indexes written out
1144 // via a WriteIndexesThinBackend.
1145 FunctionImporter::ImportMapTy ImportList
;
1146 if (!lto::initImportList(*M
, *CombinedIndex
, ImportList
))
1149 auto AddStream
= [&](size_t Task
, const Twine
&ModuleName
) {
1150 return std::make_unique
<CachedFileStream
>(std::move(OS
),
1151 CGOpts
.ObjectFilenameForDebug
);
1154 if (CGOpts
.SaveTempsFilePrefix
!= "") {
1155 if (Error E
= Conf
.addSaveTemps(CGOpts
.SaveTempsFilePrefix
+ ".",
1156 /* UseInputModulePath */ false)) {
1157 handleAllErrors(std::move(E
), [&](ErrorInfoBase
&EIB
) {
1158 errs() << "Error setting up ThinLTO save-temps: " << EIB
.message()
1163 Conf
.CPU
= TOpts
.CPU
;
1164 Conf
.CodeModel
= getCodeModel(CGOpts
);
1165 Conf
.MAttrs
= TOpts
.Features
;
1166 Conf
.RelocModel
= CGOpts
.RelocationModel
;
1167 std::optional
<CodeGenOpt::Level
> OptLevelOrNone
=
1168 CodeGenOpt::getLevel(CGOpts
.OptimizationLevel
);
1169 assert(OptLevelOrNone
&& "Invalid optimization level!");
1170 Conf
.CGOptLevel
= *OptLevelOrNone
;
1171 Conf
.OptLevel
= CGOpts
.OptimizationLevel
;
1172 initTargetOptions(Diags
, Conf
.Options
, CGOpts
, TOpts
, LOpts
, HeaderOpts
);
1173 Conf
.SampleProfile
= std::move(SampleProfile
);
1174 Conf
.PTO
.LoopUnrolling
= CGOpts
.UnrollLoops
;
1175 // For historical reasons, loop interleaving is set to mirror setting for loop
1177 Conf
.PTO
.LoopInterleaving
= CGOpts
.UnrollLoops
;
1178 Conf
.PTO
.LoopVectorization
= CGOpts
.VectorizeLoop
;
1179 Conf
.PTO
.SLPVectorization
= CGOpts
.VectorizeSLP
;
1180 // Only enable CGProfilePass when using integrated assembler, since
1181 // non-integrated assemblers don't recognize .cgprofile section.
1182 Conf
.PTO
.CallGraphProfile
= !CGOpts
.DisableIntegratedAS
;
1184 // Context sensitive profile.
1185 if (CGOpts
.hasProfileCSIRInstr()) {
1186 Conf
.RunCSIRInstr
= true;
1187 Conf
.CSIRProfile
= std::move(CGOpts
.InstrProfileOutput
);
1188 } else if (CGOpts
.hasProfileCSIRUse()) {
1189 Conf
.RunCSIRInstr
= false;
1190 Conf
.CSIRProfile
= std::move(CGOpts
.ProfileInstrumentUsePath
);
1193 Conf
.ProfileRemapping
= std::move(ProfileRemapping
);
1194 Conf
.DebugPassManager
= CGOpts
.DebugPassManager
;
1195 Conf
.RemarksWithHotness
= CGOpts
.DiagnosticsWithHotness
;
1196 Conf
.RemarksFilename
= CGOpts
.OptRecordFile
;
1197 Conf
.RemarksPasses
= CGOpts
.OptRecordPasses
;
1198 Conf
.RemarksFormat
= CGOpts
.OptRecordFormat
;
1199 Conf
.SplitDwarfFile
= CGOpts
.SplitDwarfFile
;
1200 Conf
.SplitDwarfOutput
= CGOpts
.SplitDwarfOutput
;
1202 case Backend_EmitNothing
:
1203 Conf
.PreCodeGenModuleHook
= [](size_t Task
, const Module
&Mod
) {
1207 case Backend_EmitLL
:
1208 Conf
.PreCodeGenModuleHook
= [&](size_t Task
, const Module
&Mod
) {
1209 M
->print(*OS
, nullptr, CGOpts
.EmitLLVMUseLists
);
1213 case Backend_EmitBC
:
1214 Conf
.PreCodeGenModuleHook
= [&](size_t Task
, const Module
&Mod
) {
1215 WriteBitcodeToFile(*M
, *OS
, CGOpts
.EmitLLVMUseLists
);
1220 Conf
.CGFileType
= getCodeGenFileType(Action
);
1224 thinBackend(Conf
, -1, AddStream
, *M
, *CombinedIndex
, ImportList
,
1225 ModuleToDefinedGVSummaries
[M
->getModuleIdentifier()],
1226 /* ModuleMap */ nullptr, CGOpts
.CmdArgs
)) {
1227 handleAllErrors(std::move(E
), [&](ErrorInfoBase
&EIB
) {
1228 errs() << "Error running ThinLTO backend: " << EIB
.message() << '\n';
1233 void clang::EmitBackendOutput(DiagnosticsEngine
&Diags
,
1234 const HeaderSearchOptions
&HeaderOpts
,
1235 const CodeGenOptions
&CGOpts
,
1236 const clang::TargetOptions
&TOpts
,
1237 const LangOptions
&LOpts
, StringRef TDesc
,
1238 Module
*M
, BackendAction Action
,
1239 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
,
1240 std::unique_ptr
<raw_pwrite_stream
> OS
) {
1242 llvm::TimeTraceScope
TimeScope("Backend");
1244 std::unique_ptr
<llvm::Module
> EmptyModule
;
1245 if (!CGOpts
.ThinLTOIndexFile
.empty()) {
1246 // If we are performing a ThinLTO importing compile, load the function index
1247 // into memory and pass it into runThinLTOBackend, which will run the
1248 // function importer and invoke LTO passes.
1249 std::unique_ptr
<ModuleSummaryIndex
> CombinedIndex
;
1250 if (Error E
= llvm::getModuleSummaryIndexForFile(
1251 CGOpts
.ThinLTOIndexFile
,
1252 /*IgnoreEmptyThinLTOIndexFile*/ true)
1253 .moveInto(CombinedIndex
)) {
1254 logAllUnhandledErrors(std::move(E
), errs(),
1255 "Error loading index file '" +
1256 CGOpts
.ThinLTOIndexFile
+ "': ");
1260 // A null CombinedIndex means we should skip ThinLTO compilation
1261 // (LLVM will optionally ignore empty index files, returning null instead
1263 if (CombinedIndex
) {
1264 if (!CombinedIndex
->skipModuleByDistributedBackend()) {
1265 runThinLTOBackend(Diags
, CombinedIndex
.get(), M
, HeaderOpts
, CGOpts
,
1266 TOpts
, LOpts
, std::move(OS
), CGOpts
.SampleProfileFile
,
1267 CGOpts
.ProfileRemappingFile
, Action
);
1270 // Distributed indexing detected that nothing from the module is needed
1271 // for the final linking. So we can skip the compilation. We sill need to
1272 // output an empty object file to make sure that a linker does not fail
1273 // trying to read it. Also for some features, like CFI, we must skip
1274 // the compilation as CombinedIndex does not contain all required
1276 EmptyModule
= std::make_unique
<llvm::Module
>("empty", M
->getContext());
1277 EmptyModule
->setTargetTriple(M
->getTargetTriple());
1278 M
= EmptyModule
.get();
1282 EmitAssemblyHelper
AsmHelper(Diags
, HeaderOpts
, CGOpts
, TOpts
, LOpts
, M
, VFS
);
1283 AsmHelper
.EmitAssembly(Action
, std::move(OS
));
1285 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1288 std::string DLDesc
= M
->getDataLayout().getStringRepresentation();
1289 if (DLDesc
!= TDesc
) {
1290 unsigned DiagID
= Diags
.getCustomDiagID(
1291 DiagnosticsEngine::Error
, "backend data layout '%0' does not match "
1292 "expected target description '%1'");
1293 Diags
.Report(DiagID
) << DLDesc
<< TDesc
;
1298 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1299 // __LLVM,__bitcode section.
1300 void clang::EmbedBitcode(llvm::Module
*M
, const CodeGenOptions
&CGOpts
,
1301 llvm::MemoryBufferRef Buf
) {
1302 if (CGOpts
.getEmbedBitcode() == CodeGenOptions::Embed_Off
)
1304 llvm::embedBitcodeInModule(
1305 *M
, Buf
, CGOpts
.getEmbedBitcode() != CodeGenOptions::Embed_Marker
,
1306 CGOpts
.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode
,
1310 void clang::EmbedObject(llvm::Module
*M
, const CodeGenOptions
&CGOpts
,
1311 DiagnosticsEngine
&Diags
) {
1312 if (CGOpts
.OffloadObjects
.empty())
1315 for (StringRef OffloadObject
: CGOpts
.OffloadObjects
) {
1316 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> ObjectOrErr
=
1317 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject
);
1318 if (std::error_code EC
= ObjectOrErr
.getError()) {
1319 auto DiagID
= Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
1320 "could not open '%0' for embedding");
1321 Diags
.Report(DiagID
) << OffloadObject
;
1325 llvm::embedBufferInModule(*M
, **ObjectOrErr
, ".llvm.offloading",
1326 Align(object::OffloadBinary::getAlignment()));