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
.LowerGlobalDtorsViaCxaAtExit
=
371 CodeGenOpts
.RegisterGlobalDtorsWithAtExit
;
372 Options
.DisableIntegratedAS
= CodeGenOpts
.DisableIntegratedAS
;
373 Options
.CompressDebugSections
= CodeGenOpts
.getCompressDebugSections();
374 Options
.RelaxELFRelocations
= CodeGenOpts
.RelaxELFRelocations
;
377 Options
.EABIVersion
= TargetOpts
.EABIVersion
;
379 if (LangOpts
.hasSjLjExceptions())
380 Options
.ExceptionModel
= llvm::ExceptionHandling::SjLj
;
381 if (LangOpts
.hasSEHExceptions())
382 Options
.ExceptionModel
= llvm::ExceptionHandling::WinEH
;
383 if (LangOpts
.hasDWARFExceptions())
384 Options
.ExceptionModel
= llvm::ExceptionHandling::DwarfCFI
;
385 if (LangOpts
.hasWasmExceptions())
386 Options
.ExceptionModel
= llvm::ExceptionHandling::Wasm
;
388 Options
.NoInfsFPMath
= LangOpts
.NoHonorInfs
;
389 Options
.NoNaNsFPMath
= LangOpts
.NoHonorNaNs
;
390 Options
.NoZerosInBSS
= CodeGenOpts
.NoZeroInitializedInBSS
;
391 Options
.UnsafeFPMath
= LangOpts
.AllowFPReassoc
&& LangOpts
.AllowRecip
&&
392 LangOpts
.NoSignedZero
&& LangOpts
.ApproxFunc
&&
393 (LangOpts
.getDefaultFPContractMode() ==
394 LangOptions::FPModeKind::FPM_Fast
||
395 LangOpts
.getDefaultFPContractMode() ==
396 LangOptions::FPModeKind::FPM_FastHonorPragmas
);
397 Options
.ApproxFuncFPMath
= LangOpts
.ApproxFunc
;
400 llvm::StringSwitch
<llvm::BasicBlockSection
>(CodeGenOpts
.BBSections
)
401 .Case("all", llvm::BasicBlockSection::All
)
402 .Case("labels", llvm::BasicBlockSection::Labels
)
403 .StartsWith("list=", llvm::BasicBlockSection::List
)
404 .Case("none", llvm::BasicBlockSection::None
)
405 .Default(llvm::BasicBlockSection::None
);
407 if (Options
.BBSections
== llvm::BasicBlockSection::List
) {
408 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> MBOrErr
=
409 MemoryBuffer::getFile(CodeGenOpts
.BBSections
.substr(5));
411 Diags
.Report(diag::err_fe_unable_to_load_basic_block_sections_file
)
412 << MBOrErr
.getError().message();
415 Options
.BBSectionsFuncListBuf
= std::move(*MBOrErr
);
418 Options
.EnableMachineFunctionSplitter
= CodeGenOpts
.SplitMachineFunctions
;
419 Options
.FunctionSections
= CodeGenOpts
.FunctionSections
;
420 Options
.DataSections
= CodeGenOpts
.DataSections
;
421 Options
.IgnoreXCOFFVisibility
= LangOpts
.IgnoreXCOFFVisibility
;
422 Options
.UniqueSectionNames
= CodeGenOpts
.UniqueSectionNames
;
423 Options
.UniqueBasicBlockSectionNames
=
424 CodeGenOpts
.UniqueBasicBlockSectionNames
;
425 Options
.TLSSize
= CodeGenOpts
.TLSSize
;
426 Options
.EmulatedTLS
= CodeGenOpts
.EmulatedTLS
;
427 Options
.ExplicitEmulatedTLS
= true;
428 Options
.DebuggerTuning
= CodeGenOpts
.getDebuggerTuning();
429 Options
.EmitStackSizeSection
= CodeGenOpts
.StackSizeSection
;
430 Options
.StackUsageOutput
= CodeGenOpts
.StackUsageOutput
;
431 Options
.EmitAddrsig
= CodeGenOpts
.Addrsig
;
432 Options
.ForceDwarfFrameSection
= CodeGenOpts
.ForceDwarfFrameSection
;
433 Options
.EmitCallSiteInfo
= CodeGenOpts
.EmitCallSiteInfo
;
434 Options
.EnableAIXExtendedAltivecABI
= CodeGenOpts
.EnableAIXExtendedAltivecABI
;
435 Options
.XRayOmitFunctionIndex
= CodeGenOpts
.XRayOmitFunctionIndex
;
436 Options
.LoopAlignment
= CodeGenOpts
.LoopAlignment
;
437 Options
.DebugStrictDwarf
= CodeGenOpts
.DebugStrictDwarf
;
438 Options
.ObjectFilenameForDebug
= CodeGenOpts
.ObjectFilenameForDebug
;
439 Options
.Hotpatch
= CodeGenOpts
.HotPatch
;
440 Options
.JMCInstrument
= CodeGenOpts
.JMCInstrument
;
442 switch (CodeGenOpts
.getSwiftAsyncFramePointer()) {
443 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto
:
444 Options
.SwiftAsyncFramePointer
=
445 SwiftAsyncFramePointerMode::DeploymentBased
;
448 case CodeGenOptions::SwiftAsyncFramePointerKind::Always
:
449 Options
.SwiftAsyncFramePointer
= SwiftAsyncFramePointerMode::Always
;
452 case CodeGenOptions::SwiftAsyncFramePointerKind::Never
:
453 Options
.SwiftAsyncFramePointer
= SwiftAsyncFramePointerMode::Never
;
457 Options
.MCOptions
.SplitDwarfFile
= CodeGenOpts
.SplitDwarfFile
;
458 Options
.MCOptions
.EmitDwarfUnwind
= CodeGenOpts
.getEmitDwarfUnwind();
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
.EmitGcovArcs
&& !CodeGenOpts
.EmitGcovNotes
)
493 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
494 // LLVM's -default-gcov-version flag is set to something invalid.
496 Options
.EmitNotes
= CodeGenOpts
.EmitGcovNotes
;
497 Options
.EmitData
= CodeGenOpts
.EmitGcovArcs
;
498 llvm::copy(CodeGenOpts
.CoverageVersion
, std::begin(Options
.Version
));
499 Options
.NoRedZone
= CodeGenOpts
.DisableRedZone
;
500 Options
.Filter
= CodeGenOpts
.ProfileFilterFiles
;
501 Options
.Exclude
= CodeGenOpts
.ProfileExcludeFiles
;
502 Options
.Atomic
= CodeGenOpts
.AtomicProfileUpdate
;
506 static std::optional
<InstrProfOptions
>
507 getInstrProfOptions(const CodeGenOptions
&CodeGenOpts
,
508 const LangOptions
&LangOpts
) {
509 if (!CodeGenOpts
.hasProfileClangInstr())
511 InstrProfOptions Options
;
512 Options
.NoRedZone
= CodeGenOpts
.DisableRedZone
;
513 Options
.InstrProfileOutput
= CodeGenOpts
.InstrProfileOutput
;
514 Options
.Atomic
= CodeGenOpts
.AtomicProfileUpdate
;
518 static void setCommandLineOpts(const CodeGenOptions
&CodeGenOpts
) {
519 SmallVector
<const char *, 16> BackendArgs
;
520 BackendArgs
.push_back("clang"); // Fake program name.
521 if (!CodeGenOpts
.DebugPass
.empty()) {
522 BackendArgs
.push_back("-debug-pass");
523 BackendArgs
.push_back(CodeGenOpts
.DebugPass
.c_str());
525 if (!CodeGenOpts
.LimitFloatPrecision
.empty()) {
526 BackendArgs
.push_back("-limit-float-precision");
527 BackendArgs
.push_back(CodeGenOpts
.LimitFloatPrecision
.c_str());
529 // Check for the default "clang" invocation that won't set any cl::opt values.
530 // Skip trying to parse the command line invocation to avoid the issues
532 if (BackendArgs
.size() == 1)
534 BackendArgs
.push_back(nullptr);
535 // FIXME: The command line parser below is not thread-safe and shares a global
536 // state, so this call might crash or overwrite the options of another Clang
537 // instance in the same process.
538 llvm::cl::ParseCommandLineOptions(BackendArgs
.size() - 1,
542 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM
) {
543 // Create the TargetMachine for generating code.
545 std::string Triple
= TheModule
->getTargetTriple();
546 const llvm::Target
*TheTarget
= TargetRegistry::lookupTarget(Triple
, Error
);
549 Diags
.Report(diag::err_fe_unable_to_create_target
) << Error
;
553 std::optional
<llvm::CodeModel::Model
> CM
= getCodeModel(CodeGenOpts
);
554 std::string FeaturesStr
=
555 llvm::join(TargetOpts
.Features
.begin(), TargetOpts
.Features
.end(), ",");
556 llvm::Reloc::Model RM
= CodeGenOpts
.RelocationModel
;
557 std::optional
<CodeGenOpt::Level
> OptLevelOrNone
=
558 CodeGenOpt::getLevel(CodeGenOpts
.OptimizationLevel
);
559 assert(OptLevelOrNone
&& "Invalid optimization level!");
560 CodeGenOpt::Level OptLevel
= *OptLevelOrNone
;
562 llvm::TargetOptions Options
;
563 if (!initTargetOptions(Diags
, Options
, CodeGenOpts
, TargetOpts
, LangOpts
,
566 TM
.reset(TheTarget
->createTargetMachine(Triple
, TargetOpts
.CPU
, FeaturesStr
,
567 Options
, RM
, CM
, OptLevel
));
570 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager
&CodeGenPasses
,
571 BackendAction Action
,
572 raw_pwrite_stream
&OS
,
573 raw_pwrite_stream
*DwoOS
) {
575 std::unique_ptr
<TargetLibraryInfoImpl
> TLII(
576 createTLII(TargetTriple
, CodeGenOpts
));
577 CodeGenPasses
.add(new TargetLibraryInfoWrapperPass(*TLII
));
579 // Normal mode, emit a .s or .o file by running the code generator. Note,
580 // this also adds codegenerator level optimization passes.
581 CodeGenFileType CGFT
= getCodeGenFileType(Action
);
583 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
584 // "codegen" passes so that it isn't run multiple times when there is
585 // inlining happening.
586 if (CodeGenOpts
.OptimizationLevel
> 0)
587 CodeGenPasses
.add(createObjCARCContractPass());
589 if (TM
->addPassesToEmitFile(CodeGenPasses
, OS
, DwoOS
, CGFT
,
590 /*DisableVerify=*/!CodeGenOpts
.VerifyModule
)) {
591 Diags
.Report(diag::err_fe_unable_to_interface_with_target
);
598 static OptimizationLevel
mapToLevel(const CodeGenOptions
&Opts
) {
599 switch (Opts
.OptimizationLevel
) {
601 llvm_unreachable("Invalid optimization level!");
604 return OptimizationLevel::O0
;
607 return OptimizationLevel::O1
;
610 switch (Opts
.OptimizeSize
) {
612 llvm_unreachable("Invalid optimization level for size!");
615 return OptimizationLevel::O2
;
618 return OptimizationLevel::Os
;
621 return OptimizationLevel::Oz
;
625 return OptimizationLevel::O3
;
629 static void addKCFIPass(const Triple
&TargetTriple
, const LangOptions
&LangOpts
,
631 // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
632 if (TargetTriple
.getArch() == llvm::Triple::x86_64
||
633 TargetTriple
.isAArch64(64))
636 // Ensure we lower KCFI operand bundles with -O0.
637 PB
.registerOptimizerLastEPCallback(
638 [&](ModulePassManager
&MPM
, OptimizationLevel Level
) {
639 if (Level
== OptimizationLevel::O0
&&
640 LangOpts
.Sanitize
.has(SanitizerKind::KCFI
))
641 MPM
.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
644 // When optimizations are requested, run KCIFPass after InstCombine to
645 // avoid unnecessary checks.
646 PB
.registerPeepholeEPCallback(
647 [&](FunctionPassManager
&FPM
, OptimizationLevel Level
) {
648 if (Level
!= OptimizationLevel::O0
&&
649 LangOpts
.Sanitize
.has(SanitizerKind::KCFI
))
650 FPM
.addPass(KCFIPass());
654 static void addSanitizers(const Triple
&TargetTriple
,
655 const CodeGenOptions
&CodeGenOpts
,
656 const LangOptions
&LangOpts
, PassBuilder
&PB
) {
657 auto SanitizersCallback
= [&](ModulePassManager
&MPM
,
658 OptimizationLevel Level
) {
659 if (CodeGenOpts
.hasSanitizeCoverage()) {
660 auto SancovOpts
= getSancovOptsFromCGOpts(CodeGenOpts
);
661 MPM
.addPass(SanitizerCoveragePass(
662 SancovOpts
, CodeGenOpts
.SanitizeCoverageAllowlistFiles
,
663 CodeGenOpts
.SanitizeCoverageIgnorelistFiles
));
666 if (CodeGenOpts
.hasSanitizeBinaryMetadata()) {
667 MPM
.addPass(SanitizerBinaryMetadataPass(
668 getSanitizerBinaryMetadataOptions(CodeGenOpts
),
669 CodeGenOpts
.SanitizeMetadataIgnorelistFiles
));
672 auto MSanPass
= [&](SanitizerMask Mask
, bool CompileKernel
) {
673 if (LangOpts
.Sanitize
.has(Mask
)) {
674 int TrackOrigins
= CodeGenOpts
.SanitizeMemoryTrackOrigins
;
675 bool Recover
= CodeGenOpts
.SanitizeRecover
.has(Mask
);
677 MemorySanitizerOptions
options(TrackOrigins
, Recover
, CompileKernel
,
678 CodeGenOpts
.SanitizeMemoryParamRetval
);
679 MPM
.addPass(MemorySanitizerPass(options
));
680 if (Level
!= OptimizationLevel::O0
) {
681 // MemorySanitizer inserts complex instrumentation that mostly follows
682 // the logic of the original code, but operates on "shadow" values. It
683 // can benefit from re-running some general purpose optimization
685 MPM
.addPass(RequireAnalysisPass
<GlobalsAA
, Module
>());
686 FunctionPassManager FPM
;
687 FPM
.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
688 FPM
.addPass(InstCombinePass());
689 FPM
.addPass(JumpThreadingPass());
690 FPM
.addPass(GVNPass());
691 FPM
.addPass(InstCombinePass());
692 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(FPM
)));
696 MSanPass(SanitizerKind::Memory
, false);
697 MSanPass(SanitizerKind::KernelMemory
, true);
699 if (LangOpts
.Sanitize
.has(SanitizerKind::Thread
)) {
700 MPM
.addPass(ModuleThreadSanitizerPass());
701 MPM
.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
704 auto ASanPass
= [&](SanitizerMask Mask
, bool CompileKernel
) {
705 if (LangOpts
.Sanitize
.has(Mask
)) {
706 bool UseGlobalGC
= asanUseGlobalsGC(TargetTriple
, CodeGenOpts
);
707 bool UseOdrIndicator
= CodeGenOpts
.SanitizeAddressUseOdrIndicator
;
708 llvm::AsanDtorKind DestructorKind
=
709 CodeGenOpts
.getSanitizeAddressDtor();
710 AddressSanitizerOptions Opts
;
711 Opts
.CompileKernel
= CompileKernel
;
712 Opts
.Recover
= CodeGenOpts
.SanitizeRecover
.has(Mask
);
713 Opts
.UseAfterScope
= CodeGenOpts
.SanitizeAddressUseAfterScope
;
714 Opts
.UseAfterReturn
= CodeGenOpts
.getSanitizeAddressUseAfterReturn();
715 MPM
.addPass(AddressSanitizerPass(Opts
, UseGlobalGC
, UseOdrIndicator
,
719 ASanPass(SanitizerKind::Address
, false);
720 ASanPass(SanitizerKind::KernelAddress
, true);
722 auto HWASanPass
= [&](SanitizerMask Mask
, bool CompileKernel
) {
723 if (LangOpts
.Sanitize
.has(Mask
)) {
724 bool Recover
= CodeGenOpts
.SanitizeRecover
.has(Mask
);
725 MPM
.addPass(HWAddressSanitizerPass(
726 {CompileKernel
, Recover
,
727 /*DisableOptimization=*/CodeGenOpts
.OptimizationLevel
== 0}));
730 HWASanPass(SanitizerKind::HWAddress
, false);
731 HWASanPass(SanitizerKind::KernelHWAddress
, true);
733 if (LangOpts
.Sanitize
.has(SanitizerKind::DataFlow
)) {
734 MPM
.addPass(DataFlowSanitizerPass(LangOpts
.NoSanitizeFiles
));
737 if (ClSanitizeOnOptimizerEarlyEP
) {
738 PB
.registerOptimizerEarlyEPCallback(
739 [SanitizersCallback
](ModulePassManager
&MPM
, OptimizationLevel Level
) {
740 ModulePassManager NewMPM
;
741 SanitizersCallback(NewMPM
, Level
);
742 if (!NewMPM
.isEmpty()) {
743 // Sanitizers can abandon<GlobalsAA>.
744 NewMPM
.addPass(RequireAnalysisPass
<GlobalsAA
, Module
>());
745 MPM
.addPass(std::move(NewMPM
));
749 // LastEP does not need GlobalsAA.
750 PB
.registerOptimizerLastEPCallback(SanitizersCallback
);
754 void EmitAssemblyHelper::RunOptimizationPipeline(
755 BackendAction Action
, std::unique_ptr
<raw_pwrite_stream
> &OS
,
756 std::unique_ptr
<llvm::ToolOutputFile
> &ThinLinkOS
) {
757 std::optional
<PGOOptions
> PGOOpt
;
759 if (CodeGenOpts
.hasProfileIRInstr())
760 // -fprofile-generate.
762 CodeGenOpts
.InstrProfileOutput
.empty() ? getDefaultProfileGenName()
763 : CodeGenOpts
.InstrProfileOutput
,
764 "", "", nullptr, PGOOptions::IRInstr
, PGOOptions::NoCSAction
,
765 CodeGenOpts
.DebugInfoForProfiling
);
766 else if (CodeGenOpts
.hasProfileIRUse()) {
768 auto CSAction
= CodeGenOpts
.hasProfileCSIRUse() ? PGOOptions::CSIRUse
769 : PGOOptions::NoCSAction
;
771 PGOOptions(CodeGenOpts
.ProfileInstrumentUsePath
, "",
772 CodeGenOpts
.ProfileRemappingFile
, VFS
, PGOOptions::IRUse
,
773 CSAction
, CodeGenOpts
.DebugInfoForProfiling
);
774 } else if (!CodeGenOpts
.SampleProfileFile
.empty())
775 // -fprofile-sample-use
777 CodeGenOpts
.SampleProfileFile
, "", CodeGenOpts
.ProfileRemappingFile
,
778 VFS
, PGOOptions::SampleUse
, PGOOptions::NoCSAction
,
779 CodeGenOpts
.DebugInfoForProfiling
, CodeGenOpts
.PseudoProbeForProfiling
);
780 else if (CodeGenOpts
.PseudoProbeForProfiling
)
781 // -fpseudo-probe-for-profiling
782 PGOOpt
= PGOOptions("", "", "", nullptr, PGOOptions::NoAction
,
783 PGOOptions::NoCSAction
,
784 CodeGenOpts
.DebugInfoForProfiling
, true);
785 else if (CodeGenOpts
.DebugInfoForProfiling
)
786 // -fdebug-info-for-profiling
787 PGOOpt
= PGOOptions("", "", "", nullptr, PGOOptions::NoAction
,
788 PGOOptions::NoCSAction
, true);
790 // Check to see if we want to generate a CS profile.
791 if (CodeGenOpts
.hasProfileCSIRInstr()) {
792 assert(!CodeGenOpts
.hasProfileCSIRUse() &&
793 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
796 assert(PGOOpt
->Action
!= PGOOptions::IRInstr
&&
797 PGOOpt
->Action
!= PGOOptions::SampleUse
&&
798 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
800 PGOOpt
->CSProfileGenFile
= CodeGenOpts
.InstrProfileOutput
.empty()
801 ? getDefaultProfileGenName()
802 : CodeGenOpts
.InstrProfileOutput
;
803 PGOOpt
->CSAction
= PGOOptions::CSIRInstr
;
807 CodeGenOpts
.InstrProfileOutput
.empty()
808 ? getDefaultProfileGenName()
809 : CodeGenOpts
.InstrProfileOutput
,
810 "", nullptr, PGOOptions::NoAction
, PGOOptions::CSIRInstr
,
811 CodeGenOpts
.DebugInfoForProfiling
);
814 TM
->setPGOOption(PGOOpt
);
816 PipelineTuningOptions PTO
;
817 PTO
.LoopUnrolling
= CodeGenOpts
.UnrollLoops
;
818 // For historical reasons, loop interleaving is set to mirror setting for loop
820 PTO
.LoopInterleaving
= CodeGenOpts
.UnrollLoops
;
821 PTO
.LoopVectorization
= CodeGenOpts
.VectorizeLoop
;
822 PTO
.SLPVectorization
= CodeGenOpts
.VectorizeSLP
;
823 PTO
.MergeFunctions
= CodeGenOpts
.MergeFunctions
;
824 // Only enable CGProfilePass when using integrated assembler, since
825 // non-integrated assemblers don't recognize .cgprofile section.
826 PTO
.CallGraphProfile
= !CodeGenOpts
.DisableIntegratedAS
;
828 LoopAnalysisManager LAM
;
829 FunctionAnalysisManager FAM
;
830 CGSCCAnalysisManager CGAM
;
831 ModuleAnalysisManager MAM
;
833 bool DebugPassStructure
= CodeGenOpts
.DebugPass
== "Structure";
834 PassInstrumentationCallbacks PIC
;
835 PrintPassOptions PrintPassOpts
;
836 PrintPassOpts
.Indent
= DebugPassStructure
;
837 PrintPassOpts
.SkipAnalyses
= DebugPassStructure
;
838 StandardInstrumentations
SI(
839 TheModule
->getContext(),
840 (CodeGenOpts
.DebugPassManager
|| DebugPassStructure
),
841 /*VerifyEach*/ false, PrintPassOpts
);
842 SI
.registerCallbacks(PIC
, &FAM
);
843 PassBuilder
PB(TM
.get(), PTO
, PGOOpt
, &PIC
);
845 if (CodeGenOpts
.EnableAssignmentTracking
) {
846 PB
.registerPipelineStartEPCallback(
847 [&](ModulePassManager
&MPM
, OptimizationLevel Level
) {
848 MPM
.addPass(AssignmentTrackingPass());
852 // Enable verify-debuginfo-preserve-each for new PM.
853 DebugifyEachInstrumentation Debugify
;
854 DebugInfoPerPass DebugInfoBeforePass
;
855 if (CodeGenOpts
.EnableDIPreservationVerify
) {
856 Debugify
.setDebugifyMode(DebugifyMode::OriginalDebugInfo
);
857 Debugify
.setDebugInfoBeforePass(DebugInfoBeforePass
);
859 if (!CodeGenOpts
.DIBugsReportFilePath
.empty())
860 Debugify
.setOrigDIVerifyBugsReportFilePath(
861 CodeGenOpts
.DIBugsReportFilePath
);
862 Debugify
.registerCallbacks(PIC
);
864 // Attempt to load pass plugins and register their callbacks with PB.
865 for (auto &PluginFN
: CodeGenOpts
.PassPlugins
) {
866 auto PassPlugin
= PassPlugin::Load(PluginFN
);
868 PassPlugin
->registerPassBuilderCallbacks(PB
);
870 Diags
.Report(diag::err_fe_unable_to_load_plugin
)
871 << PluginFN
<< toString(PassPlugin
.takeError());
874 #define HANDLE_EXTENSION(Ext) \
875 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
876 #include "llvm/Support/Extension.def"
878 // Register the target library analysis directly and give it a customized
880 std::unique_ptr
<TargetLibraryInfoImpl
> TLII(
881 createTLII(TargetTriple
, CodeGenOpts
));
882 FAM
.registerPass([&] { return TargetLibraryAnalysis(*TLII
); });
884 // Register all the basic analyses with the managers.
885 PB
.registerModuleAnalyses(MAM
);
886 PB
.registerCGSCCAnalyses(CGAM
);
887 PB
.registerFunctionAnalyses(FAM
);
888 PB
.registerLoopAnalyses(LAM
);
889 PB
.crossRegisterProxies(LAM
, FAM
, CGAM
, MAM
);
891 ModulePassManager MPM
;
893 if (!CodeGenOpts
.DisableLLVMPasses
) {
894 // Map our optimization levels into one of the distinct levels used to
895 // configure the pipeline.
896 OptimizationLevel Level
= mapToLevel(CodeGenOpts
);
898 bool IsThinLTO
= CodeGenOpts
.PrepareForThinLTO
;
899 bool IsLTO
= CodeGenOpts
.PrepareForLTO
;
901 if (LangOpts
.ObjCAutoRefCount
) {
902 PB
.registerPipelineStartEPCallback(
903 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
904 if (Level
!= OptimizationLevel::O0
)
906 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
908 PB
.registerPipelineEarlySimplificationEPCallback(
909 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
910 if (Level
!= OptimizationLevel::O0
)
911 MPM
.addPass(ObjCARCAPElimPass());
913 PB
.registerScalarOptimizerLateEPCallback(
914 [](FunctionPassManager
&FPM
, OptimizationLevel Level
) {
915 if (Level
!= OptimizationLevel::O0
)
916 FPM
.addPass(ObjCARCOptPass());
920 // If we reached here with a non-empty index file name, then the index
921 // file was empty and we are not performing ThinLTO backend compilation
922 // (used in testing in a distributed build environment).
923 bool IsThinLTOPostLink
= !CodeGenOpts
.ThinLTOIndexFile
.empty();
924 // If so drop any the type test assume sequences inserted for whole program
925 // vtables so that codegen doesn't complain.
926 if (IsThinLTOPostLink
)
927 PB
.registerPipelineStartEPCallback(
928 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
929 MPM
.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
930 /*ImportSummary=*/nullptr,
931 /*DropTypeTests=*/true));
934 if (CodeGenOpts
.InstrumentFunctions
||
935 CodeGenOpts
.InstrumentFunctionEntryBare
||
936 CodeGenOpts
.InstrumentFunctionsAfterInlining
||
937 CodeGenOpts
.InstrumentForProfiling
) {
938 PB
.registerPipelineStartEPCallback(
939 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
940 MPM
.addPass(createModuleToFunctionPassAdaptor(
941 EntryExitInstrumenterPass(/*PostInlining=*/false)));
943 PB
.registerOptimizerLastEPCallback(
944 [](ModulePassManager
&MPM
, OptimizationLevel Level
) {
945 MPM
.addPass(createModuleToFunctionPassAdaptor(
946 EntryExitInstrumenterPass(/*PostInlining=*/true)));
950 // Register callbacks to schedule sanitizer passes at the appropriate part
952 if (LangOpts
.Sanitize
.has(SanitizerKind::LocalBounds
))
953 PB
.registerScalarOptimizerLateEPCallback(
954 [](FunctionPassManager
&FPM
, OptimizationLevel Level
) {
955 FPM
.addPass(BoundsCheckingPass());
958 // Don't add sanitizers if we are here from ThinLTO PostLink. That already
959 // done on PreLink stage.
960 if (!IsThinLTOPostLink
) {
961 addSanitizers(TargetTriple
, CodeGenOpts
, LangOpts
, PB
);
962 addKCFIPass(TargetTriple
, LangOpts
, PB
);
965 if (std::optional
<GCOVOptions
> Options
=
966 getGCOVOptions(CodeGenOpts
, LangOpts
))
967 PB
.registerPipelineStartEPCallback(
968 [Options
](ModulePassManager
&MPM
, OptimizationLevel Level
) {
969 MPM
.addPass(GCOVProfilerPass(*Options
));
971 if (std::optional
<InstrProfOptions
> Options
=
972 getInstrProfOptions(CodeGenOpts
, LangOpts
))
973 PB
.registerPipelineStartEPCallback(
974 [Options
](ModulePassManager
&MPM
, OptimizationLevel Level
) {
975 MPM
.addPass(InstrProfiling(*Options
, false));
978 if (CodeGenOpts
.OptimizationLevel
== 0) {
979 MPM
= PB
.buildO0DefaultPipeline(Level
, IsLTO
|| IsThinLTO
);
980 } else if (IsThinLTO
) {
981 MPM
= PB
.buildThinLTOPreLinkDefaultPipeline(Level
);
983 MPM
= PB
.buildLTOPreLinkDefaultPipeline(Level
);
985 MPM
= PB
.buildPerModuleDefaultPipeline(Level
);
988 if (!CodeGenOpts
.MemoryProfileOutput
.empty()) {
989 MPM
.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
990 MPM
.addPass(ModuleMemProfilerPass());
994 // Add a verifier pass if requested. We don't have to do this if the action
995 // requires code generation because there will already be a verifier pass in
996 // the code-generation pipeline.
997 if (!actionRequiresCodeGen(Action
) && CodeGenOpts
.VerifyModule
)
998 MPM
.addPass(VerifierPass());
1000 if (Action
== Backend_EmitBC
|| Action
== Backend_EmitLL
) {
1001 if (CodeGenOpts
.PrepareForThinLTO
&& !CodeGenOpts
.DisableLLVMPasses
) {
1002 if (!TheModule
->getModuleFlag("EnableSplitLTOUnit"))
1003 TheModule
->addModuleFlag(Module::Error
, "EnableSplitLTOUnit",
1004 CodeGenOpts
.EnableSplitLTOUnit
);
1005 if (Action
== Backend_EmitBC
) {
1006 if (!CodeGenOpts
.ThinLinkBitcodeFile
.empty()) {
1007 ThinLinkOS
= openOutputFile(CodeGenOpts
.ThinLinkBitcodeFile
);
1011 MPM
.addPass(ThinLTOBitcodeWriterPass(*OS
, ThinLinkOS
? &ThinLinkOS
->os()
1014 MPM
.addPass(PrintModulePass(*OS
, "", CodeGenOpts
.EmitLLVMUseLists
,
1015 /*EmitLTOSummary=*/true));
1019 // Emit a module summary by default for Regular LTO except for ld64
1021 bool EmitLTOSummary
= shouldEmitRegularLTOSummary();
1022 if (EmitLTOSummary
) {
1023 if (!TheModule
->getModuleFlag("ThinLTO"))
1024 TheModule
->addModuleFlag(Module::Error
, "ThinLTO", uint32_t(0));
1025 if (!TheModule
->getModuleFlag("EnableSplitLTOUnit"))
1026 TheModule
->addModuleFlag(Module::Error
, "EnableSplitLTOUnit",
1029 if (Action
== Backend_EmitBC
)
1030 MPM
.addPass(BitcodeWriterPass(*OS
, CodeGenOpts
.EmitLLVMUseLists
,
1033 MPM
.addPass(PrintModulePass(*OS
, "", CodeGenOpts
.EmitLLVMUseLists
,
1038 // Now that we have all of the passes ready, run them.
1040 PrettyStackTraceString
CrashInfo("Optimizer");
1041 llvm::TimeTraceScope
TimeScope("Optimizer");
1042 MPM
.run(*TheModule
, MAM
);
1046 void EmitAssemblyHelper::RunCodegenPipeline(
1047 BackendAction Action
, std::unique_ptr
<raw_pwrite_stream
> &OS
,
1048 std::unique_ptr
<llvm::ToolOutputFile
> &DwoOS
) {
1049 // We still use the legacy PM to run the codegen pipeline since the new PM
1050 // does not work with the codegen pipeline.
1051 // FIXME: make the new PM work with the codegen pipeline.
1052 legacy::PassManager CodeGenPasses
;
1054 // Append any output we need to the pass manager.
1056 case Backend_EmitAssembly
:
1057 case Backend_EmitMCNull
:
1058 case Backend_EmitObj
:
1060 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1061 if (!CodeGenOpts
.SplitDwarfOutput
.empty()) {
1062 DwoOS
= openOutputFile(CodeGenOpts
.SplitDwarfOutput
);
1066 if (!AddEmitPasses(CodeGenPasses
, Action
, *OS
,
1067 DwoOS
? &DwoOS
->os() : nullptr))
1068 // FIXME: Should we handle this error differently?
1076 PrettyStackTraceString
CrashInfo("Code generation");
1077 llvm::TimeTraceScope
TimeScope("CodeGenPasses");
1078 CodeGenPasses
.run(*TheModule
);
1082 void EmitAssemblyHelper::EmitAssembly(BackendAction Action
,
1083 std::unique_ptr
<raw_pwrite_stream
> OS
) {
1084 TimeRegion
Region(CodeGenOpts
.TimePasses
? &CodeGenerationTime
: nullptr);
1085 setCommandLineOpts(CodeGenOpts
);
1087 bool RequiresCodeGen
= actionRequiresCodeGen(Action
);
1088 CreateTargetMachine(RequiresCodeGen
);
1090 if (RequiresCodeGen
&& !TM
)
1093 TheModule
->setDataLayout(TM
->createDataLayout());
1095 // Before executing passes, print the final values of the LLVM options.
1096 cl::PrintOptionValues();
1098 std::unique_ptr
<llvm::ToolOutputFile
> ThinLinkOS
, DwoOS
;
1099 RunOptimizationPipeline(Action
, OS
, ThinLinkOS
);
1100 RunCodegenPipeline(Action
, OS
, DwoOS
);
1108 static void runThinLTOBackend(
1109 DiagnosticsEngine
&Diags
, ModuleSummaryIndex
*CombinedIndex
, Module
*M
,
1110 const HeaderSearchOptions
&HeaderOpts
, const CodeGenOptions
&CGOpts
,
1111 const clang::TargetOptions
&TOpts
, const LangOptions
&LOpts
,
1112 std::unique_ptr
<raw_pwrite_stream
> OS
, std::string SampleProfile
,
1113 std::string ProfileRemapping
, BackendAction Action
) {
1114 StringMap
<DenseMap
<GlobalValue::GUID
, GlobalValueSummary
*>>
1115 ModuleToDefinedGVSummaries
;
1116 CombinedIndex
->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries
);
1118 setCommandLineOpts(CGOpts
);
1120 // We can simply import the values mentioned in the combined index, since
1121 // we should only invoke this using the individual indexes written out
1122 // via a WriteIndexesThinBackend.
1123 FunctionImporter::ImportMapTy ImportList
;
1124 if (!lto::initImportList(*M
, *CombinedIndex
, ImportList
))
1127 auto AddStream
= [&](size_t Task
, const Twine
&ModuleName
) {
1128 return std::make_unique
<CachedFileStream
>(std::move(OS
),
1129 CGOpts
.ObjectFilenameForDebug
);
1132 if (CGOpts
.SaveTempsFilePrefix
!= "") {
1133 if (Error E
= Conf
.addSaveTemps(CGOpts
.SaveTempsFilePrefix
+ ".",
1134 /* UseInputModulePath */ false)) {
1135 handleAllErrors(std::move(E
), [&](ErrorInfoBase
&EIB
) {
1136 errs() << "Error setting up ThinLTO save-temps: " << EIB
.message()
1141 Conf
.CPU
= TOpts
.CPU
;
1142 Conf
.CodeModel
= getCodeModel(CGOpts
);
1143 Conf
.MAttrs
= TOpts
.Features
;
1144 Conf
.RelocModel
= CGOpts
.RelocationModel
;
1145 std::optional
<CodeGenOpt::Level
> OptLevelOrNone
=
1146 CodeGenOpt::getLevel(CGOpts
.OptimizationLevel
);
1147 assert(OptLevelOrNone
&& "Invalid optimization level!");
1148 Conf
.CGOptLevel
= *OptLevelOrNone
;
1149 Conf
.OptLevel
= CGOpts
.OptimizationLevel
;
1150 initTargetOptions(Diags
, Conf
.Options
, CGOpts
, TOpts
, LOpts
, HeaderOpts
);
1151 Conf
.SampleProfile
= std::move(SampleProfile
);
1152 Conf
.PTO
.LoopUnrolling
= CGOpts
.UnrollLoops
;
1153 // For historical reasons, loop interleaving is set to mirror setting for loop
1155 Conf
.PTO
.LoopInterleaving
= CGOpts
.UnrollLoops
;
1156 Conf
.PTO
.LoopVectorization
= CGOpts
.VectorizeLoop
;
1157 Conf
.PTO
.SLPVectorization
= CGOpts
.VectorizeSLP
;
1158 // Only enable CGProfilePass when using integrated assembler, since
1159 // non-integrated assemblers don't recognize .cgprofile section.
1160 Conf
.PTO
.CallGraphProfile
= !CGOpts
.DisableIntegratedAS
;
1162 // Context sensitive profile.
1163 if (CGOpts
.hasProfileCSIRInstr()) {
1164 Conf
.RunCSIRInstr
= true;
1165 Conf
.CSIRProfile
= std::move(CGOpts
.InstrProfileOutput
);
1166 } else if (CGOpts
.hasProfileCSIRUse()) {
1167 Conf
.RunCSIRInstr
= false;
1168 Conf
.CSIRProfile
= std::move(CGOpts
.ProfileInstrumentUsePath
);
1171 Conf
.ProfileRemapping
= std::move(ProfileRemapping
);
1172 Conf
.DebugPassManager
= CGOpts
.DebugPassManager
;
1173 Conf
.RemarksWithHotness
= CGOpts
.DiagnosticsWithHotness
;
1174 Conf
.RemarksFilename
= CGOpts
.OptRecordFile
;
1175 Conf
.RemarksPasses
= CGOpts
.OptRecordPasses
;
1176 Conf
.RemarksFormat
= CGOpts
.OptRecordFormat
;
1177 Conf
.SplitDwarfFile
= CGOpts
.SplitDwarfFile
;
1178 Conf
.SplitDwarfOutput
= CGOpts
.SplitDwarfOutput
;
1180 case Backend_EmitNothing
:
1181 Conf
.PreCodeGenModuleHook
= [](size_t Task
, const Module
&Mod
) {
1185 case Backend_EmitLL
:
1186 Conf
.PreCodeGenModuleHook
= [&](size_t Task
, const Module
&Mod
) {
1187 M
->print(*OS
, nullptr, CGOpts
.EmitLLVMUseLists
);
1191 case Backend_EmitBC
:
1192 Conf
.PreCodeGenModuleHook
= [&](size_t Task
, const Module
&Mod
) {
1193 WriteBitcodeToFile(*M
, *OS
, CGOpts
.EmitLLVMUseLists
);
1198 Conf
.CGFileType
= getCodeGenFileType(Action
);
1202 thinBackend(Conf
, -1, AddStream
, *M
, *CombinedIndex
, ImportList
,
1203 ModuleToDefinedGVSummaries
[M
->getModuleIdentifier()],
1204 /* ModuleMap */ nullptr, CGOpts
.CmdArgs
)) {
1205 handleAllErrors(std::move(E
), [&](ErrorInfoBase
&EIB
) {
1206 errs() << "Error running ThinLTO backend: " << EIB
.message() << '\n';
1211 void clang::EmitBackendOutput(DiagnosticsEngine
&Diags
,
1212 const HeaderSearchOptions
&HeaderOpts
,
1213 const CodeGenOptions
&CGOpts
,
1214 const clang::TargetOptions
&TOpts
,
1215 const LangOptions
&LOpts
, StringRef TDesc
,
1216 Module
*M
, BackendAction Action
,
1217 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
,
1218 std::unique_ptr
<raw_pwrite_stream
> OS
) {
1220 llvm::TimeTraceScope
TimeScope("Backend");
1222 std::unique_ptr
<llvm::Module
> EmptyModule
;
1223 if (!CGOpts
.ThinLTOIndexFile
.empty()) {
1224 // If we are performing a ThinLTO importing compile, load the function index
1225 // into memory and pass it into runThinLTOBackend, which will run the
1226 // function importer and invoke LTO passes.
1227 std::unique_ptr
<ModuleSummaryIndex
> CombinedIndex
;
1228 if (Error E
= llvm::getModuleSummaryIndexForFile(
1229 CGOpts
.ThinLTOIndexFile
,
1230 /*IgnoreEmptyThinLTOIndexFile*/ true)
1231 .moveInto(CombinedIndex
)) {
1232 logAllUnhandledErrors(std::move(E
), errs(),
1233 "Error loading index file '" +
1234 CGOpts
.ThinLTOIndexFile
+ "': ");
1238 // A null CombinedIndex means we should skip ThinLTO compilation
1239 // (LLVM will optionally ignore empty index files, returning null instead
1241 if (CombinedIndex
) {
1242 if (!CombinedIndex
->skipModuleByDistributedBackend()) {
1243 runThinLTOBackend(Diags
, CombinedIndex
.get(), M
, HeaderOpts
, CGOpts
,
1244 TOpts
, LOpts
, std::move(OS
), CGOpts
.SampleProfileFile
,
1245 CGOpts
.ProfileRemappingFile
, Action
);
1248 // Distributed indexing detected that nothing from the module is needed
1249 // for the final linking. So we can skip the compilation. We sill need to
1250 // output an empty object file to make sure that a linker does not fail
1251 // trying to read it. Also for some features, like CFI, we must skip
1252 // the compilation as CombinedIndex does not contain all required
1254 EmptyModule
= std::make_unique
<llvm::Module
>("empty", M
->getContext());
1255 EmptyModule
->setTargetTriple(M
->getTargetTriple());
1256 M
= EmptyModule
.get();
1260 EmitAssemblyHelper
AsmHelper(Diags
, HeaderOpts
, CGOpts
, TOpts
, LOpts
, M
, VFS
);
1261 AsmHelper
.EmitAssembly(Action
, std::move(OS
));
1263 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1266 std::string DLDesc
= M
->getDataLayout().getStringRepresentation();
1267 if (DLDesc
!= TDesc
) {
1268 unsigned DiagID
= Diags
.getCustomDiagID(
1269 DiagnosticsEngine::Error
, "backend data layout '%0' does not match "
1270 "expected target description '%1'");
1271 Diags
.Report(DiagID
) << DLDesc
<< TDesc
;
1276 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1277 // __LLVM,__bitcode section.
1278 void clang::EmbedBitcode(llvm::Module
*M
, const CodeGenOptions
&CGOpts
,
1279 llvm::MemoryBufferRef Buf
) {
1280 if (CGOpts
.getEmbedBitcode() == CodeGenOptions::Embed_Off
)
1282 llvm::embedBitcodeInModule(
1283 *M
, Buf
, CGOpts
.getEmbedBitcode() != CodeGenOptions::Embed_Marker
,
1284 CGOpts
.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode
,
1288 void clang::EmbedObject(llvm::Module
*M
, const CodeGenOptions
&CGOpts
,
1289 DiagnosticsEngine
&Diags
) {
1290 if (CGOpts
.OffloadObjects
.empty())
1293 for (StringRef OffloadObject
: CGOpts
.OffloadObjects
) {
1294 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> ObjectOrErr
=
1295 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject
);
1296 if (std::error_code EC
= ObjectOrErr
.getError()) {
1297 auto DiagID
= Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
1298 "could not open '%0' for embedding");
1299 Diags
.Report(DiagID
) << OffloadObject
;
1303 llvm::embedBufferInModule(*M
, **ObjectOrErr
, ".llvm.offloading",
1304 Align(object::OffloadBinary::getAlignment()));