14ba67500SRoman Divacky //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
24ba67500SRoman Divacky //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64ba67500SRoman Divacky //
74ba67500SRoman Divacky //===----------------------------------------------------------------------===//
84ba67500SRoman Divacky
94ba67500SRoman Divacky #include "clang/CodeGen/BackendUtil.h"
10b1c73532SDimitry Andric #include "BackendConsumer.h"
11b1c73532SDimitry Andric #include "LinkInModulesPass.h"
12676fbe81SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
134ba67500SRoman Divacky #include "clang/Basic/Diagnostic.h"
14180abc3dSDimitry Andric #include "clang/Basic/LangOptions.h"
15809500fcSDimitry Andric #include "clang/Basic/TargetOptions.h"
164ba67500SRoman Divacky #include "clang/Frontend/FrontendDiagnostic.h"
179f4dbff6SDimitry Andric #include "clang/Frontend/Utils.h"
186694ed09SDimitry Andric #include "clang/Lex/HeaderSearchOptions.h"
19bab175ecSDimitry Andric #include "llvm/ADT/SmallSet.h"
2045b53394SDimitry Andric #include "llvm/ADT/StringExtras.h"
219f4dbff6SDimitry Andric #include "llvm/ADT/StringSwitch.h"
22b60736ecSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
23e3b55780SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
245e20cdd8SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
255e20cdd8SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
26bab175ecSDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
27bab175ecSDimitry Andric #include "llvm/Bitcode/BitcodeWriter.h"
289f4dbff6SDimitry Andric #include "llvm/Bitcode/BitcodeWriterPass.h"
294ba67500SRoman Divacky #include "llvm/CodeGen/RegAllocRegistry.h"
304ba67500SRoman Divacky #include "llvm/CodeGen/SchedulerRegistry.h"
3148675466SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
32b1c73532SDimitry Andric #include "llvm/Frontend/Driver/CodeGenOptions.h"
33809500fcSDimitry Andric #include "llvm/IR/DataLayout.h"
34e3b55780SDimitry Andric #include "llvm/IR/DebugInfo.h"
355e20cdd8SDimitry Andric #include "llvm/IR/LegacyPassManager.h"
36809500fcSDimitry Andric #include "llvm/IR/Module.h"
37bab175ecSDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
38cfca06d7SDimitry Andric #include "llvm/IR/PassManager.h"
399f4dbff6SDimitry Andric #include "llvm/IR/Verifier.h"
40e3b55780SDimitry Andric #include "llvm/IRPrinter/IRPrintingPasses.h"
41bab175ecSDimitry Andric #include "llvm/LTO/LTOBackend.h"
426694ed09SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
43c0981da4SDimitry Andric #include "llvm/MC/TargetRegistry.h"
44145449b1SDimitry Andric #include "llvm/Object/OffloadBinary.h"
45bab175ecSDimitry Andric #include "llvm/Passes/PassBuilder.h"
4622989816SDimitry Andric #include "llvm/Passes/PassPlugin.h"
47519fc96cSDimitry Andric #include "llvm/Passes/StandardInstrumentations.h"
48312c0ed1SDimitry Andric #include "llvm/ProfileData/InstrProfCorrelator.h"
49676fbe81SDimitry Andric #include "llvm/Support/BuryPointer.h"
504ba67500SRoman Divacky #include "llvm/Support/CommandLine.h"
51bab175ecSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
524ba67500SRoman Divacky #include "llvm/Support/PrettyStackTrace.h"
5322989816SDimitry Andric #include "llvm/Support/TimeProfiler.h"
544ba67500SRoman Divacky #include "llvm/Support/Timer.h"
55cfca06d7SDimitry Andric #include "llvm/Support/ToolOutputFile.h"
567fa27ce4SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
574ba67500SRoman Divacky #include "llvm/Support/raw_ostream.h"
584ba67500SRoman Divacky #include "llvm/Target/TargetMachine.h"
594ba67500SRoman Divacky #include "llvm/Target/TargetOptions.h"
607fa27ce4SDimitry Andric #include "llvm/TargetParser/SubtargetFeature.h"
617fa27ce4SDimitry Andric #include "llvm/TargetParser/Triple.h"
62b1c73532SDimitry Andric #include "llvm/Transforms/HipStdPar/HipStdPar.h"
637fa27ce4SDimitry Andric #include "llvm/Transforms/IPO/EmbedBitcodePass.h"
64cfca06d7SDimitry Andric #include "llvm/Transforms/IPO/LowerTypeTests.h"
65551c6985SDimitry Andric #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
6648675466SDimitry Andric #include "llvm/Transforms/InstCombine/InstCombine.h"
67809500fcSDimitry Andric #include "llvm/Transforms/Instrumentation.h"
6822989816SDimitry Andric #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
69344a3780SDimitry Andric #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
70461a67faSDimitry Andric #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
71b60736ecSDimitry Andric #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
7248675466SDimitry Andric #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
7322989816SDimitry Andric #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
7422989816SDimitry Andric #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
75e3b55780SDimitry Andric #include "llvm/Transforms/Instrumentation/KCFI.h"
76ac9a064cSDimitry Andric #include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
77b60736ecSDimitry Andric #include "llvm/Transforms/Instrumentation/MemProfiler.h"
78676fbe81SDimitry Andric #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
79ac9a064cSDimitry Andric #include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
80b1c73532SDimitry Andric #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
81e3b55780SDimitry Andric #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
82519fc96cSDimitry Andric #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
83676fbe81SDimitry Andric #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
84809500fcSDimitry Andric #include "llvm/Transforms/ObjCARC.h"
85344a3780SDimitry Andric #include "llvm/Transforms/Scalar/EarlyCSE.h"
862b6b257fSDimitry Andric #include "llvm/Transforms/Scalar/GVN.h"
87e3b55780SDimitry Andric #include "llvm/Transforms/Scalar/JumpThreading.h"
88344a3780SDimitry Andric #include "llvm/Transforms/Utils/Debugify.h"
89ecbca9f5SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
909f4dbff6SDimitry Andric #include <memory>
91e3b55780SDimitry Andric #include <optional>
924ba67500SRoman Divacky using namespace clang;
934ba67500SRoman Divacky using namespace llvm;
944ba67500SRoman Divacky
95706b4fc4SDimitry Andric #define HANDLE_EXTENSION(Ext) \
96706b4fc4SDimitry Andric llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
97706b4fc4SDimitry Andric #include "llvm/Support/Extension.def"
98706b4fc4SDimitry Andric
9977fc4c14SDimitry Andric namespace llvm {
100b1c73532SDimitry Andric extern cl::opt<bool> PrintPipelinePasses;
101e3b55780SDimitry Andric
102e3b55780SDimitry Andric // Experiment to move sanitizers earlier.
103e3b55780SDimitry Andric static cl::opt<bool> ClSanitizeOnOptimizerEarlyEP(
104e3b55780SDimitry Andric "sanitizer-early-opt-ep", cl::Optional,
105ac9a064cSDimitry Andric cl::desc("Insert sanitizers on OptimizerEarlyEP."));
106ac9a064cSDimitry Andric
107ac9a064cSDimitry Andric // Experiment to mark cold functions as optsize/minsize/optnone.
108ac9a064cSDimitry Andric // TODO: remove once this is exposed as a proper driver flag.
109ac9a064cSDimitry Andric static cl::opt<PGOOptions::ColdFuncOpt> ClPGOColdFuncAttr(
110ac9a064cSDimitry Andric "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
111ac9a064cSDimitry Andric cl::desc(
112ac9a064cSDimitry Andric "Function attribute to apply to cold functions as determined by PGO"),
113ac9a064cSDimitry Andric cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default",
114ac9a064cSDimitry Andric "Default (no attribute)"),
115ac9a064cSDimitry Andric clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize",
116ac9a064cSDimitry Andric "Mark cold functions with optsize."),
117ac9a064cSDimitry Andric clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize",
118ac9a064cSDimitry Andric "Mark cold functions with minsize."),
119ac9a064cSDimitry Andric clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone",
120ac9a064cSDimitry Andric "Mark cold functions with optnone.")));
121b1c73532SDimitry Andric
122312c0ed1SDimitry Andric extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind> ProfileCorrelate;
123312c0ed1SDimitry Andric } // namespace llvm
12477fc4c14SDimitry Andric
1254ba67500SRoman Divacky namespace {
1264ba67500SRoman Divacky
1277442d6faSDimitry Andric // Default filename used for profile generation.
getDefaultProfileGenName()12877fc4c14SDimitry Andric std::string getDefaultProfileGenName() {
129312c0ed1SDimitry Andric return DebugInfoCorrelate || ProfileCorrelate != InstrProfCorrelator::NONE
130312c0ed1SDimitry Andric ? "default_%m.proflite"
131312c0ed1SDimitry Andric : "default_%m.profraw";
13277fc4c14SDimitry Andric }
1337442d6faSDimitry Andric
1344ba67500SRoman Divacky class EmitAssemblyHelper {
13536981b17SDimitry Andric DiagnosticsEngine &Diags;
1366694ed09SDimitry Andric const HeaderSearchOptions &HSOpts;
1374ba67500SRoman Divacky const CodeGenOptions &CodeGenOpts;
138dbe13110SDimitry Andric const clang::TargetOptions &TargetOpts;
139180abc3dSDimitry Andric const LangOptions &LangOpts;
140b1c73532SDimitry Andric llvm::Module *TheModule;
1417fa27ce4SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
1424ba67500SRoman Divacky
1434ba67500SRoman Divacky Timer CodeGenerationTime;
1444ba67500SRoman Divacky
1452b6b257fSDimitry Andric std::unique_ptr<raw_pwrite_stream> OS;
1464ba67500SRoman Divacky
147145449b1SDimitry Andric Triple TargetTriple;
148145449b1SDimitry Andric
getTargetIRAnalysis() const1495e20cdd8SDimitry Andric TargetIRAnalysis getTargetIRAnalysis() const {
150809500fcSDimitry Andric if (TM)
1515e20cdd8SDimitry Andric return TM->getTargetIRAnalysis();
1525e20cdd8SDimitry Andric
1535e20cdd8SDimitry Andric return TargetIRAnalysis();
1545e20cdd8SDimitry Andric }
1555e20cdd8SDimitry Andric
1565e20cdd8SDimitry Andric /// Generates the TargetMachine.
1572b6b257fSDimitry Andric /// Leaves TM unchanged if it is unable to create the target machine.
15813cc256eSDimitry Andric /// Some of our clang tests specify triples which are not built
15913cc256eSDimitry Andric /// into clang. This is okay because these tests check the generated
16013cc256eSDimitry Andric /// IR, and they require DataLayout which depends on the triple.
16113cc256eSDimitry Andric /// In this case, we allow this method to fail and not report an error.
16213cc256eSDimitry Andric /// When MustCreateTM is used, we print an error if we are unable to load
16313cc256eSDimitry Andric /// the requested target.
1642b6b257fSDimitry Andric void CreateTargetMachine(bool MustCreateTM);
1654ba67500SRoman Divacky
1665e20cdd8SDimitry Andric /// Add passes necessary to emit assembly or LLVM IR.
1674ba67500SRoman Divacky ///
1684ba67500SRoman Divacky /// \return True on success.
1692b6b257fSDimitry Andric bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
17048675466SDimitry Andric raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
17148675466SDimitry Andric
openOutputFile(StringRef Path)17248675466SDimitry Andric std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
17348675466SDimitry Andric std::error_code EC;
174519fc96cSDimitry Andric auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
175519fc96cSDimitry Andric llvm::sys::fs::OF_None);
17648675466SDimitry Andric if (EC) {
17748675466SDimitry Andric Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
17848675466SDimitry Andric F.reset();
17948675466SDimitry Andric }
18048675466SDimitry Andric return F;
18148675466SDimitry Andric }
1824ba67500SRoman Divacky
183b1c73532SDimitry Andric void RunOptimizationPipeline(
184b1c73532SDimitry Andric BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
185b1c73532SDimitry Andric std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
186c0981da4SDimitry Andric void RunCodegenPipeline(BackendAction Action,
187c0981da4SDimitry Andric std::unique_ptr<raw_pwrite_stream> &OS,
188c0981da4SDimitry Andric std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
189c0981da4SDimitry Andric
190145449b1SDimitry Andric /// Check whether we should emit a module summary for regular LTO.
191145449b1SDimitry Andric /// The module summary should be emitted by default for regular LTO
192145449b1SDimitry Andric /// except for ld64 targets.
193145449b1SDimitry Andric ///
194145449b1SDimitry Andric /// \return True if the module summary should be emitted.
shouldEmitRegularLTOSummary() const195145449b1SDimitry Andric bool shouldEmitRegularLTOSummary() const {
196145449b1SDimitry Andric return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
197145449b1SDimitry Andric TargetTriple.getVendor() != llvm::Triple::Apple;
198145449b1SDimitry Andric }
199145449b1SDimitry Andric
200ac9a064cSDimitry Andric /// Check whether we should emit a flag for UnifiedLTO.
201ac9a064cSDimitry Andric /// The UnifiedLTO module flag should be set when UnifiedLTO is enabled for
202ac9a064cSDimitry Andric /// ThinLTO or Full LTO with module summaries.
shouldEmitUnifiedLTOModueFlag() const203ac9a064cSDimitry Andric bool shouldEmitUnifiedLTOModueFlag() const {
204ac9a064cSDimitry Andric return CodeGenOpts.UnifiedLTO &&
205ac9a064cSDimitry Andric (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
206ac9a064cSDimitry Andric }
207ac9a064cSDimitry Andric
2084ba67500SRoman Divacky public:
EmitAssemblyHelper(DiagnosticsEngine & _Diags,const HeaderSearchOptions & HeaderSearchOpts,const CodeGenOptions & CGOpts,const clang::TargetOptions & TOpts,const LangOptions & LOpts,llvm::Module * M,IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)2096694ed09SDimitry Andric EmitAssemblyHelper(DiagnosticsEngine &_Diags,
2106694ed09SDimitry Andric const HeaderSearchOptions &HeaderSearchOpts,
2116694ed09SDimitry Andric const CodeGenOptions &CGOpts,
212dbe13110SDimitry Andric const clang::TargetOptions &TOpts,
213b1c73532SDimitry Andric const LangOptions &LOpts, llvm::Module *M,
2147fa27ce4SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
2156694ed09SDimitry Andric : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
2167fa27ce4SDimitry Andric TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), VFS(std::move(VFS)),
217145449b1SDimitry Andric CodeGenerationTime("codegen", "Code Generation Time"),
218145449b1SDimitry Andric TargetTriple(TheModule->getTargetTriple()) {}
2194ba67500SRoman Divacky
~EmitAssemblyHelper()2204ba67500SRoman Divacky ~EmitAssemblyHelper() {
2219f4dbff6SDimitry Andric if (CodeGenOpts.DisableFree)
22206d4ba38SDimitry Andric BuryPointer(std::move(TM));
2234ba67500SRoman Divacky }
2244ba67500SRoman Divacky
2259f4dbff6SDimitry Andric std::unique_ptr<TargetMachine> TM;
2269f4dbff6SDimitry Andric
227145449b1SDimitry Andric // Emit output using the new pass manager for the optimization pipeline.
228b1c73532SDimitry Andric void EmitAssembly(BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
229b1c73532SDimitry Andric BackendConsumer *BC);
2304ba67500SRoman Divacky };
231312c0ed1SDimitry Andric } // namespace
23256d91b49SDimitry Andric
233519fc96cSDimitry Andric static SanitizerCoverageOptions
getSancovOptsFromCGOpts(const CodeGenOptions & CGOpts)234519fc96cSDimitry Andric getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
2355e20cdd8SDimitry Andric SanitizerCoverageOptions Opts;
2365e20cdd8SDimitry Andric Opts.CoverageType =
2375e20cdd8SDimitry Andric static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
2385e20cdd8SDimitry Andric Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
2395e20cdd8SDimitry Andric Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
2405e20cdd8SDimitry Andric Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
241bab175ecSDimitry Andric Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
242bab175ecSDimitry Andric Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
2435e20cdd8SDimitry Andric Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
2442b6b257fSDimitry Andric Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
245bab175ecSDimitry Andric Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
2460a5fb09bSDimitry Andric Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
247551c6985SDimitry Andric Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
248cfca06d7SDimitry Andric Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
249461a67faSDimitry Andric Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
250461a67faSDimitry Andric Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
251c0981da4SDimitry Andric Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
252c0981da4SDimitry Andric Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
253e3b55780SDimitry Andric Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
254e3b55780SDimitry Andric return Opts;
255e3b55780SDimitry Andric }
256e3b55780SDimitry Andric
257e3b55780SDimitry Andric static SanitizerBinaryMetadataOptions
getSanitizerBinaryMetadataOptions(const CodeGenOptions & CGOpts)258e3b55780SDimitry Andric getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts) {
259e3b55780SDimitry Andric SanitizerBinaryMetadataOptions Opts;
260e3b55780SDimitry Andric Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
261e3b55780SDimitry Andric Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
262e3b55780SDimitry Andric Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
263519fc96cSDimitry Andric return Opts;
264519fc96cSDimitry Andric }
265519fc96cSDimitry Andric
266f0c55418SDimitry Andric // Check if ASan should use GC-friendly instrumentation for globals.
267f0c55418SDimitry Andric // First of all, there is no point if -fdata-sections is off (expect for MachO,
268f0c55418SDimitry Andric // where this is not a factor). Also, on ELF this feature requires an assembler
269f0c55418SDimitry Andric // extension that only works with -integrated-as at the moment.
asanUseGlobalsGC(const Triple & T,const CodeGenOptions & CGOpts)270f0c55418SDimitry Andric static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
2712410013dSDimitry Andric if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
2722410013dSDimitry Andric return false;
273f0c55418SDimitry Andric switch (T.getObjectFormat()) {
274f0c55418SDimitry Andric case Triple::MachO:
275f0c55418SDimitry Andric case Triple::COFF:
276f0c55418SDimitry Andric return true;
277f0c55418SDimitry Andric case Triple::ELF:
278145449b1SDimitry Andric return !CGOpts.DisableIntegratedAS;
279b60736ecSDimitry Andric case Triple::GOFF:
280b60736ecSDimitry Andric llvm::report_fatal_error("ASan not implemented for GOFF");
281519fc96cSDimitry Andric case Triple::XCOFF:
282519fc96cSDimitry Andric llvm::report_fatal_error("ASan not implemented for XCOFF.");
283519fc96cSDimitry Andric case Triple::Wasm:
284145449b1SDimitry Andric case Triple::DXContainer:
285145449b1SDimitry Andric case Triple::SPIRV:
286519fc96cSDimitry Andric case Triple::UnknownObjectFormat:
287519fc96cSDimitry Andric break;
288f0c55418SDimitry Andric }
289519fc96cSDimitry Andric return false;
290f0c55418SDimitry Andric }
291f0c55418SDimitry Andric
292e3b55780SDimitry Andric static std::optional<llvm::CodeModel::Model>
getCodeModel(const CodeGenOptions & CodeGenOpts)293461a67faSDimitry Andric getCodeModel(const CodeGenOptions &CodeGenOpts) {
294461a67faSDimitry Andric unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
295676fbe81SDimitry Andric .Case("tiny", llvm::CodeModel::Tiny)
2967442d6faSDimitry Andric .Case("small", llvm::CodeModel::Small)
2977442d6faSDimitry Andric .Case("kernel", llvm::CodeModel::Kernel)
2987442d6faSDimitry Andric .Case("medium", llvm::CodeModel::Medium)
2997442d6faSDimitry Andric .Case("large", llvm::CodeModel::Large)
300461a67faSDimitry Andric .Case("default", ~1u)
3017442d6faSDimitry Andric .Default(~0u);
3027442d6faSDimitry Andric assert(CodeModel != ~0u && "invalid code model!");
303461a67faSDimitry Andric if (CodeModel == ~1u)
304e3b55780SDimitry Andric return std::nullopt;
3057442d6faSDimitry Andric return static_cast<llvm::CodeModel::Model>(CodeModel);
3067442d6faSDimitry Andric }
3077442d6faSDimitry Andric
getCodeGenFileType(BackendAction Action)308706b4fc4SDimitry Andric static CodeGenFileType getCodeGenFileType(BackendAction Action) {
3097442d6faSDimitry Andric if (Action == Backend_EmitObj)
310b1c73532SDimitry Andric return CodeGenFileType::ObjectFile;
3117442d6faSDimitry Andric else if (Action == Backend_EmitMCNull)
312b1c73532SDimitry Andric return CodeGenFileType::Null;
3137442d6faSDimitry Andric else {
3147442d6faSDimitry Andric assert(Action == Backend_EmitAssembly && "Invalid action!");
315b1c73532SDimitry Andric return CodeGenFileType::AssemblyFile;
3167442d6faSDimitry Andric }
3177442d6faSDimitry Andric }
3187442d6faSDimitry Andric
actionRequiresCodeGen(BackendAction Action)319c0981da4SDimitry Andric static bool actionRequiresCodeGen(BackendAction Action) {
320c0981da4SDimitry Andric return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
321c0981da4SDimitry Andric Action != Backend_EmitLL;
322c0981da4SDimitry Andric }
323c0981da4SDimitry Andric
initTargetOptions(DiagnosticsEngine & Diags,llvm::TargetOptions & Options,const CodeGenOptions & CodeGenOpts,const clang::TargetOptions & TargetOpts,const LangOptions & LangOpts,const HeaderSearchOptions & HSOpts)324b60736ecSDimitry Andric static bool initTargetOptions(DiagnosticsEngine &Diags,
325cfca06d7SDimitry Andric llvm::TargetOptions &Options,
3267442d6faSDimitry Andric const CodeGenOptions &CodeGenOpts,
3277442d6faSDimitry Andric const clang::TargetOptions &TargetOpts,
3287442d6faSDimitry Andric const LangOptions &LangOpts,
3297442d6faSDimitry Andric const HeaderSearchOptions &HSOpts) {
330b60736ecSDimitry Andric switch (LangOpts.getThreadModel()) {
331b60736ecSDimitry Andric case LangOptions::ThreadModelKind::POSIX:
332b60736ecSDimitry Andric Options.ThreadModel = llvm::ThreadModel::POSIX;
333b60736ecSDimitry Andric break;
334b60736ecSDimitry Andric case LangOptions::ThreadModelKind::Single:
335b60736ecSDimitry Andric Options.ThreadModel = llvm::ThreadModel::Single;
336b60736ecSDimitry Andric break;
337b60736ecSDimitry Andric }
3387442d6faSDimitry Andric
3397442d6faSDimitry Andric // Set float ABI type.
3407442d6faSDimitry Andric assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
3417442d6faSDimitry Andric CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
3427442d6faSDimitry Andric "Invalid Floating Point ABI!");
3437442d6faSDimitry Andric Options.FloatABIType =
3447442d6faSDimitry Andric llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
3457442d6faSDimitry Andric .Case("soft", llvm::FloatABI::Soft)
3467442d6faSDimitry Andric .Case("softfp", llvm::FloatABI::Soft)
3477442d6faSDimitry Andric .Case("hard", llvm::FloatABI::Hard)
3487442d6faSDimitry Andric .Default(llvm::FloatABI::Default);
3497442d6faSDimitry Andric
3507442d6faSDimitry Andric // Set FP fusion mode.
3517442d6faSDimitry Andric switch (LangOpts.getDefaultFPContractMode()) {
352cfca06d7SDimitry Andric case LangOptions::FPM_Off:
353583e75ccSDimitry Andric // Preserve any contraction performed by the front-end. (Strict performs
354676fbe81SDimitry Andric // splitting of the muladd intrinsic in the backend.)
355583e75ccSDimitry Andric Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
3567442d6faSDimitry Andric break;
357cfca06d7SDimitry Andric case LangOptions::FPM_On:
358b60736ecSDimitry Andric case LangOptions::FPM_FastHonorPragmas:
3597442d6faSDimitry Andric Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
3607442d6faSDimitry Andric break;
361cfca06d7SDimitry Andric case LangOptions::FPM_Fast:
3627442d6faSDimitry Andric Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
3637442d6faSDimitry Andric break;
3647442d6faSDimitry Andric }
3657442d6faSDimitry Andric
366b60736ecSDimitry Andric Options.BinutilsVersion =
367b60736ecSDimitry Andric llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
3687442d6faSDimitry Andric Options.UseInitArray = CodeGenOpts.UseInitArray;
3697442d6faSDimitry Andric Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
3707442d6faSDimitry Andric
3717442d6faSDimitry Andric // Set EABI version.
372cf1b4019SDimitry Andric Options.EABIVersion = TargetOpts.EABIVersion;
3737442d6faSDimitry Andric
374b60736ecSDimitry Andric if (LangOpts.hasSjLjExceptions())
3757442d6faSDimitry Andric Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
376b60736ecSDimitry Andric if (LangOpts.hasSEHExceptions())
377461a67faSDimitry Andric Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
378b60736ecSDimitry Andric if (LangOpts.hasDWARFExceptions())
379461a67faSDimitry Andric Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
380b60736ecSDimitry Andric if (LangOpts.hasWasmExceptions())
381519fc96cSDimitry Andric Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
3827442d6faSDimitry Andric
383cfca06d7SDimitry Andric Options.NoInfsFPMath = LangOpts.NoHonorInfs;
384cfca06d7SDimitry Andric Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
3857442d6faSDimitry Andric Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
386e3b55780SDimitry Andric Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
387e3b55780SDimitry Andric LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
388e3b55780SDimitry Andric (LangOpts.getDefaultFPContractMode() ==
389e3b55780SDimitry Andric LangOptions::FPModeKind::FPM_Fast ||
390e3b55780SDimitry Andric LangOpts.getDefaultFPContractMode() ==
391e3b55780SDimitry Andric LangOptions::FPModeKind::FPM_FastHonorPragmas);
392c0981da4SDimitry Andric Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
393cfca06d7SDimitry Andric
394ac9a064cSDimitry Andric Options.BBAddrMap = CodeGenOpts.BBAddrMap;
395cfca06d7SDimitry Andric Options.BBSections =
396cfca06d7SDimitry Andric llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
397cfca06d7SDimitry Andric .Case("all", llvm::BasicBlockSection::All)
398cfca06d7SDimitry Andric .Case("labels", llvm::BasicBlockSection::Labels)
399cfca06d7SDimitry Andric .StartsWith("list=", llvm::BasicBlockSection::List)
400cfca06d7SDimitry Andric .Case("none", llvm::BasicBlockSection::None)
401cfca06d7SDimitry Andric .Default(llvm::BasicBlockSection::None);
402cfca06d7SDimitry Andric
403cfca06d7SDimitry Andric if (Options.BBSections == llvm::BasicBlockSection::List) {
404cfca06d7SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
405cfca06d7SDimitry Andric MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
406b60736ecSDimitry Andric if (!MBOrErr) {
407cfca06d7SDimitry Andric Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
408cfca06d7SDimitry Andric << MBOrErr.getError().message();
409b60736ecSDimitry Andric return false;
410b60736ecSDimitry Andric }
411cfca06d7SDimitry Andric Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
412cfca06d7SDimitry Andric }
413cfca06d7SDimitry Andric
414b60736ecSDimitry Andric Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
4157442d6faSDimitry Andric Options.FunctionSections = CodeGenOpts.FunctionSections;
4167442d6faSDimitry Andric Options.DataSections = CodeGenOpts.DataSections;
417344a3780SDimitry Andric Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
4187442d6faSDimitry Andric Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
419cfca06d7SDimitry Andric Options.UniqueBasicBlockSectionNames =
420cfca06d7SDimitry Andric CodeGenOpts.UniqueBasicBlockSectionNames;
421ac9a064cSDimitry Andric Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
422706b4fc4SDimitry Andric Options.TLSSize = CodeGenOpts.TLSSize;
423ac9a064cSDimitry Andric Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
4247442d6faSDimitry Andric Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
4257442d6faSDimitry Andric Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
42648675466SDimitry Andric Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
427344a3780SDimitry Andric Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
42848675466SDimitry Andric Options.EmitAddrsig = CodeGenOpts.Addrsig;
429706b4fc4SDimitry Andric Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
430cfca06d7SDimitry Andric Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
4317fa27ce4SDimitry Andric Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
4327fa27ce4SDimitry Andric Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
433c0981da4SDimitry Andric Options.LoopAlignment = CodeGenOpts.LoopAlignment;
434145449b1SDimitry Andric Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
435145449b1SDimitry Andric Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
436145449b1SDimitry Andric Options.Hotpatch = CodeGenOpts.HotPatch;
437145449b1SDimitry Andric Options.JMCInstrument = CodeGenOpts.JMCInstrument;
4387fa27ce4SDimitry Andric Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
439c0981da4SDimitry Andric
440c0981da4SDimitry Andric switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
441c0981da4SDimitry Andric case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
442c0981da4SDimitry Andric Options.SwiftAsyncFramePointer =
443c0981da4SDimitry Andric SwiftAsyncFramePointerMode::DeploymentBased;
444c0981da4SDimitry Andric break;
445c0981da4SDimitry Andric
446c0981da4SDimitry Andric case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
447c0981da4SDimitry Andric Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
448c0981da4SDimitry Andric break;
449c0981da4SDimitry Andric
450c0981da4SDimitry Andric case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
451c0981da4SDimitry Andric Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
452c0981da4SDimitry Andric break;
453c0981da4SDimitry Andric }
4547442d6faSDimitry Andric
455f0c55418SDimitry Andric Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
456145449b1SDimitry Andric Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
4577fa27ce4SDimitry Andric Options.MCOptions.EmitCompactUnwindNonCanonical =
4587fa27ce4SDimitry Andric CodeGenOpts.EmitCompactUnwindNonCanonical;
4597442d6faSDimitry Andric Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
4607442d6faSDimitry Andric Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
461145449b1SDimitry Andric Options.MCOptions.MCUseDwarfDirectory =
462145449b1SDimitry Andric CodeGenOpts.NoDwarfDirectoryAsm
463145449b1SDimitry Andric ? llvm::MCTargetOptions::DisableDwarfDirectory
464145449b1SDimitry Andric : llvm::MCTargetOptions::EnableDwarfDirectory;
4657442d6faSDimitry Andric Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
4667442d6faSDimitry Andric Options.MCOptions.MCIncrementalLinkerCompatible =
4677442d6faSDimitry Andric CodeGenOpts.IncrementalLinkerCompatible;
4687442d6faSDimitry Andric Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
469519fc96cSDimitry Andric Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
4707442d6faSDimitry Andric Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
471b60736ecSDimitry Andric Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
4727442d6faSDimitry Andric Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
473ac9a064cSDimitry Andric Options.MCOptions.Crel = CodeGenOpts.Crel;
474ac9a064cSDimitry Andric Options.MCOptions.X86RelaxRelocations = CodeGenOpts.RelaxELFRelocations;
475ac9a064cSDimitry Andric Options.MCOptions.CompressDebugSections =
476ac9a064cSDimitry Andric CodeGenOpts.getCompressDebugSections();
4777442d6faSDimitry Andric Options.MCOptions.ABIName = TargetOpts.ABI;
4787442d6faSDimitry Andric for (const auto &Entry : HSOpts.UserEntries)
4797442d6faSDimitry Andric if (!Entry.IsFramework &&
4807442d6faSDimitry Andric (Entry.Group == frontend::IncludeDirGroup::Quoted ||
4817442d6faSDimitry Andric Entry.Group == frontend::IncludeDirGroup::Angled ||
4827442d6faSDimitry Andric Entry.Group == frontend::IncludeDirGroup::System))
4837442d6faSDimitry Andric Options.MCOptions.IASSearchPaths.push_back(
4847442d6faSDimitry Andric Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
485cfca06d7SDimitry Andric Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
486cfca06d7SDimitry Andric Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
487e3b55780SDimitry Andric Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile;
488b1c73532SDimitry Andric Options.MCOptions.PPCUseFullRegisterNames =
489b1c73532SDimitry Andric CodeGenOpts.PPCUseFullRegisterNames;
490145449b1SDimitry Andric Options.MisExpect = CodeGenOpts.MisExpect;
491b60736ecSDimitry Andric
492b60736ecSDimitry Andric return true;
4937442d6faSDimitry Andric }
494b60736ecSDimitry Andric
495e3b55780SDimitry Andric static std::optional<GCOVOptions>
getGCOVOptions(const CodeGenOptions & CodeGenOpts,const LangOptions & LangOpts)496e3b55780SDimitry Andric getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) {
4977fa27ce4SDimitry Andric if (CodeGenOpts.CoverageNotesFile.empty() &&
4987fa27ce4SDimitry Andric CodeGenOpts.CoverageDataFile.empty())
499e3b55780SDimitry Andric return std::nullopt;
50048675466SDimitry Andric // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
50148675466SDimitry Andric // LLVM's -default-gcov-version flag is set to something invalid.
50248675466SDimitry Andric GCOVOptions Options;
5037fa27ce4SDimitry Andric Options.EmitNotes = !CodeGenOpts.CoverageNotesFile.empty();
5047fa27ce4SDimitry Andric Options.EmitData = !CodeGenOpts.CoverageDataFile.empty();
50548675466SDimitry Andric llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
50648675466SDimitry Andric Options.NoRedZone = CodeGenOpts.DisableRedZone;
507676fbe81SDimitry Andric Options.Filter = CodeGenOpts.ProfileFilterFiles;
508676fbe81SDimitry Andric Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
509b60736ecSDimitry Andric Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
51048675466SDimitry Andric return Options;
51148675466SDimitry Andric }
5127442d6faSDimitry Andric
513e3b55780SDimitry Andric static std::optional<InstrProfOptions>
getInstrProfOptions(const CodeGenOptions & CodeGenOpts,const LangOptions & LangOpts)51422989816SDimitry Andric getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
51522989816SDimitry Andric const LangOptions &LangOpts) {
51622989816SDimitry Andric if (!CodeGenOpts.hasProfileClangInstr())
517e3b55780SDimitry Andric return std::nullopt;
51822989816SDimitry Andric InstrProfOptions Options;
51922989816SDimitry Andric Options.NoRedZone = CodeGenOpts.DisableRedZone;
52022989816SDimitry Andric Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
521b60736ecSDimitry Andric Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
52222989816SDimitry Andric return Options;
52322989816SDimitry Andric }
52422989816SDimitry Andric
setCommandLineOpts(const CodeGenOptions & CodeGenOpts)525583e75ccSDimitry Andric static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
526dbe13110SDimitry Andric SmallVector<const char *, 16> BackendArgs;
5274ba67500SRoman Divacky BackendArgs.push_back("clang"); // Fake program name.
5284ba67500SRoman Divacky if (!CodeGenOpts.DebugPass.empty()) {
5294ba67500SRoman Divacky BackendArgs.push_back("-debug-pass");
5304ba67500SRoman Divacky BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
5314ba67500SRoman Divacky }
5324ba67500SRoman Divacky if (!CodeGenOpts.LimitFloatPrecision.empty()) {
5334ba67500SRoman Divacky BackendArgs.push_back("-limit-float-precision");
5344ba67500SRoman Divacky BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
5354ba67500SRoman Divacky }
536344a3780SDimitry Andric // Check for the default "clang" invocation that won't set any cl::opt values.
537344a3780SDimitry Andric // Skip trying to parse the command line invocation to avoid the issues
538344a3780SDimitry Andric // described below.
539344a3780SDimitry Andric if (BackendArgs.size() == 1)
540344a3780SDimitry Andric return;
5419f4dbff6SDimitry Andric BackendArgs.push_back(nullptr);
542344a3780SDimitry Andric // FIXME: The command line parser below is not thread-safe and shares a global
543344a3780SDimitry Andric // state, so this call might crash or overwrite the options of another Clang
544344a3780SDimitry Andric // instance in the same process.
5454ba67500SRoman Divacky llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
546dbe13110SDimitry Andric BackendArgs.data());
5472b6b257fSDimitry Andric }
5482b6b257fSDimitry Andric
CreateTargetMachine(bool MustCreateTM)5492b6b257fSDimitry Andric void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
5502b6b257fSDimitry Andric // Create the TargetMachine for generating code.
5512b6b257fSDimitry Andric std::string Error;
5522b6b257fSDimitry Andric std::string Triple = TheModule->getTargetTriple();
5532b6b257fSDimitry Andric const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
5542b6b257fSDimitry Andric if (!TheTarget) {
5552b6b257fSDimitry Andric if (MustCreateTM)
5562b6b257fSDimitry Andric Diags.Report(diag::err_fe_unable_to_create_target) << Error;
5572b6b257fSDimitry Andric return;
5582b6b257fSDimitry Andric }
5592b6b257fSDimitry Andric
560e3b55780SDimitry Andric std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
56145b53394SDimitry Andric std::string FeaturesStr =
56245b53394SDimitry Andric llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
56348675466SDimitry Andric llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
564b1c73532SDimitry Andric std::optional<CodeGenOptLevel> OptLevelOrNone =
565e3b55780SDimitry Andric CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
566e3b55780SDimitry Andric assert(OptLevelOrNone && "Invalid optimization level!");
567b1c73532SDimitry Andric CodeGenOptLevel OptLevel = *OptLevelOrNone;
568dbe13110SDimitry Andric
569dbe13110SDimitry Andric llvm::TargetOptions Options;
570b60736ecSDimitry Andric if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
571b60736ecSDimitry Andric HSOpts))
572b60736ecSDimitry Andric return;
5732b6b257fSDimitry Andric TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
5742b6b257fSDimitry Andric Options, RM, CM, OptLevel));
575b1c73532SDimitry Andric TM->setLargeDataThreshold(CodeGenOpts.LargeDataThreshold);
57613cc256eSDimitry Andric }
57713cc256eSDimitry Andric
AddEmitPasses(legacy::PassManager & CodeGenPasses,BackendAction Action,raw_pwrite_stream & OS,raw_pwrite_stream * DwoOS)5782b6b257fSDimitry Andric bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
5792b6b257fSDimitry Andric BackendAction Action,
58048675466SDimitry Andric raw_pwrite_stream &OS,
58148675466SDimitry Andric raw_pwrite_stream *DwoOS) {
582dbe13110SDimitry Andric // Add LibraryInfo.
5835e20cdd8SDimitry Andric std::unique_ptr<TargetLibraryInfoImpl> TLII(
584b1c73532SDimitry Andric llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
5852b6b257fSDimitry Andric CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
58613cc256eSDimitry Andric
5874ba67500SRoman Divacky // Normal mode, emit a .s or .o file by running the code generator. Note,
5884ba67500SRoman Divacky // this also adds codegenerator level optimization passes.
589706b4fc4SDimitry Andric CodeGenFileType CGFT = getCodeGenFileType(Action);
590180abc3dSDimitry Andric
591180abc3dSDimitry Andric // Add ObjC ARC final-cleanup optimizations. This is done as part of the
592180abc3dSDimitry Andric // "codegen" passes so that it isn't run multiple times when there is
593180abc3dSDimitry Andric // inlining happening.
5945e20cdd8SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0)
5952b6b257fSDimitry Andric CodeGenPasses.add(createObjCARCContractPass());
596180abc3dSDimitry Andric
59748675466SDimitry Andric if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
5984ba67500SRoman Divacky /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
5994ba67500SRoman Divacky Diags.Report(diag::err_fe_unable_to_interface_with_target);
6004ba67500SRoman Divacky return false;
6014ba67500SRoman Divacky }
6024ba67500SRoman Divacky
6034ba67500SRoman Divacky return true;
6044ba67500SRoman Divacky }
6054ba67500SRoman Divacky
mapToLevel(const CodeGenOptions & Opts)606c0981da4SDimitry Andric static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
607bab175ecSDimitry Andric switch (Opts.OptimizationLevel) {
608bab175ecSDimitry Andric default:
609bab175ecSDimitry Andric llvm_unreachable("Invalid optimization level!");
610bab175ecSDimitry Andric
611b60736ecSDimitry Andric case 0:
612c0981da4SDimitry Andric return OptimizationLevel::O0;
613b60736ecSDimitry Andric
614bab175ecSDimitry Andric case 1:
615c0981da4SDimitry Andric return OptimizationLevel::O1;
616bab175ecSDimitry Andric
617bab175ecSDimitry Andric case 2:
618bab175ecSDimitry Andric switch (Opts.OptimizeSize) {
619bab175ecSDimitry Andric default:
62048675466SDimitry Andric llvm_unreachable("Invalid optimization level for size!");
621bab175ecSDimitry Andric
622bab175ecSDimitry Andric case 0:
623c0981da4SDimitry Andric return OptimizationLevel::O2;
624bab175ecSDimitry Andric
625bab175ecSDimitry Andric case 1:
626c0981da4SDimitry Andric return OptimizationLevel::Os;
627bab175ecSDimitry Andric
628bab175ecSDimitry Andric case 2:
629c0981da4SDimitry Andric return OptimizationLevel::Oz;
630bab175ecSDimitry Andric }
631bab175ecSDimitry Andric
632bab175ecSDimitry Andric case 3:
633c0981da4SDimitry Andric return OptimizationLevel::O3;
634bab175ecSDimitry Andric }
635bab175ecSDimitry Andric }
636bab175ecSDimitry Andric
addKCFIPass(const Triple & TargetTriple,const LangOptions & LangOpts,PassBuilder & PB)637e3b55780SDimitry Andric static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts,
638e3b55780SDimitry Andric PassBuilder &PB) {
639e3b55780SDimitry Andric // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
640e3b55780SDimitry Andric if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
6417fa27ce4SDimitry Andric TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
642e3b55780SDimitry Andric return;
643e3b55780SDimitry Andric
644e3b55780SDimitry Andric // Ensure we lower KCFI operand bundles with -O0.
645e3b55780SDimitry Andric PB.registerOptimizerLastEPCallback(
646e3b55780SDimitry Andric [&](ModulePassManager &MPM, OptimizationLevel Level) {
647e3b55780SDimitry Andric if (Level == OptimizationLevel::O0 &&
648e3b55780SDimitry Andric LangOpts.Sanitize.has(SanitizerKind::KCFI))
649e3b55780SDimitry Andric MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
650e3b55780SDimitry Andric });
651e3b55780SDimitry Andric
652e3b55780SDimitry Andric // When optimizations are requested, run KCIFPass after InstCombine to
653e3b55780SDimitry Andric // avoid unnecessary checks.
654e3b55780SDimitry Andric PB.registerPeepholeEPCallback(
655e3b55780SDimitry Andric [&](FunctionPassManager &FPM, OptimizationLevel Level) {
656e3b55780SDimitry Andric if (Level != OptimizationLevel::O0 &&
657e3b55780SDimitry Andric LangOpts.Sanitize.has(SanitizerKind::KCFI))
658e3b55780SDimitry Andric FPM.addPass(KCFIPass());
659e3b55780SDimitry Andric });
660e3b55780SDimitry Andric }
661e3b55780SDimitry Andric
addSanitizers(const Triple & TargetTriple,const CodeGenOptions & CodeGenOpts,const LangOptions & LangOpts,PassBuilder & PB)662344a3780SDimitry Andric static void addSanitizers(const Triple &TargetTriple,
663344a3780SDimitry Andric const CodeGenOptions &CodeGenOpts,
664344a3780SDimitry Andric const LangOptions &LangOpts, PassBuilder &PB) {
665e3b55780SDimitry Andric auto SanitizersCallback = [&](ModulePassManager &MPM,
666c0981da4SDimitry Andric OptimizationLevel Level) {
667344a3780SDimitry Andric if (CodeGenOpts.hasSanitizeCoverage()) {
668344a3780SDimitry Andric auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
669e3b55780SDimitry Andric MPM.addPass(SanitizerCoveragePass(
670344a3780SDimitry Andric SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
671344a3780SDimitry Andric CodeGenOpts.SanitizeCoverageIgnorelistFiles));
672344a3780SDimitry Andric }
673344a3780SDimitry Andric
674e3b55780SDimitry Andric if (CodeGenOpts.hasSanitizeBinaryMetadata()) {
675e3b55780SDimitry Andric MPM.addPass(SanitizerBinaryMetadataPass(
6767fa27ce4SDimitry Andric getSanitizerBinaryMetadataOptions(CodeGenOpts),
6777fa27ce4SDimitry Andric CodeGenOpts.SanitizeMetadataIgnorelistFiles));
678e3b55780SDimitry Andric }
679e3b55780SDimitry Andric
680344a3780SDimitry Andric auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
681344a3780SDimitry Andric if (LangOpts.Sanitize.has(Mask)) {
682344a3780SDimitry Andric int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
683344a3780SDimitry Andric bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
684344a3780SDimitry Andric
6856f8fc217SDimitry Andric MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
6866f8fc217SDimitry Andric CodeGenOpts.SanitizeMemoryParamRetval);
687e3b55780SDimitry Andric MPM.addPass(MemorySanitizerPass(options));
688c0981da4SDimitry Andric if (Level != OptimizationLevel::O0) {
689e3b55780SDimitry Andric // MemorySanitizer inserts complex instrumentation that mostly follows
690e3b55780SDimitry Andric // the logic of the original code, but operates on "shadow" values. It
691e3b55780SDimitry Andric // can benefit from re-running some general purpose optimization
692e3b55780SDimitry Andric // passes.
693b1c73532SDimitry Andric MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
694e3b55780SDimitry Andric FunctionPassManager FPM;
695e3b55780SDimitry Andric FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
696e3b55780SDimitry Andric FPM.addPass(InstCombinePass());
697e3b55780SDimitry Andric FPM.addPass(JumpThreadingPass());
698e3b55780SDimitry Andric FPM.addPass(GVNPass());
699e3b55780SDimitry Andric FPM.addPass(InstCombinePass());
700344a3780SDimitry Andric MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
701344a3780SDimitry Andric }
702e3b55780SDimitry Andric }
703344a3780SDimitry Andric };
704344a3780SDimitry Andric MSanPass(SanitizerKind::Memory, false);
705344a3780SDimitry Andric MSanPass(SanitizerKind::KernelMemory, true);
706344a3780SDimitry Andric
707344a3780SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
708c0981da4SDimitry Andric MPM.addPass(ModuleThreadSanitizerPass());
709344a3780SDimitry Andric MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
710344a3780SDimitry Andric }
711344a3780SDimitry Andric
712ac9a064cSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
713ac9a064cSDimitry Andric MPM.addPass(NumericalStabilitySanitizerPass());
714ac9a064cSDimitry Andric
715344a3780SDimitry Andric auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
716344a3780SDimitry Andric if (LangOpts.Sanitize.has(Mask)) {
717c0981da4SDimitry Andric bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
718344a3780SDimitry Andric bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
719344a3780SDimitry Andric llvm::AsanDtorKind DestructorKind =
720344a3780SDimitry Andric CodeGenOpts.getSanitizeAddressDtor();
721c0981da4SDimitry Andric AddressSanitizerOptions Opts;
722c0981da4SDimitry Andric Opts.CompileKernel = CompileKernel;
723c0981da4SDimitry Andric Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
724c0981da4SDimitry Andric Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
725c0981da4SDimitry Andric Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
726e3b55780SDimitry Andric MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
727e3b55780SDimitry Andric DestructorKind));
728344a3780SDimitry Andric }
729344a3780SDimitry Andric };
730344a3780SDimitry Andric ASanPass(SanitizerKind::Address, false);
731344a3780SDimitry Andric ASanPass(SanitizerKind::KernelAddress, true);
732344a3780SDimitry Andric
733344a3780SDimitry Andric auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
734344a3780SDimitry Andric if (LangOpts.Sanitize.has(Mask)) {
735344a3780SDimitry Andric bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
736344a3780SDimitry Andric MPM.addPass(HWAddressSanitizerPass(
737c0981da4SDimitry Andric {CompileKernel, Recover,
738c0981da4SDimitry Andric /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
739344a3780SDimitry Andric }
740344a3780SDimitry Andric };
741344a3780SDimitry Andric HWASanPass(SanitizerKind::HWAddress, false);
742344a3780SDimitry Andric HWASanPass(SanitizerKind::KernelHWAddress, true);
743344a3780SDimitry Andric
744344a3780SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
745344a3780SDimitry Andric MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
746344a3780SDimitry Andric }
747e3b55780SDimitry Andric };
748e3b55780SDimitry Andric if (ClSanitizeOnOptimizerEarlyEP) {
749e3b55780SDimitry Andric PB.registerOptimizerEarlyEPCallback(
750e3b55780SDimitry Andric [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level) {
751e3b55780SDimitry Andric ModulePassManager NewMPM;
752e3b55780SDimitry Andric SanitizersCallback(NewMPM, Level);
753e3b55780SDimitry Andric if (!NewMPM.isEmpty()) {
754e3b55780SDimitry Andric // Sanitizers can abandon<GlobalsAA>.
755b1c73532SDimitry Andric NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
756e3b55780SDimitry Andric MPM.addPass(std::move(NewMPM));
757e3b55780SDimitry Andric }
758344a3780SDimitry Andric });
759e3b55780SDimitry Andric } else {
760e3b55780SDimitry Andric // LastEP does not need GlobalsAA.
761e3b55780SDimitry Andric PB.registerOptimizerLastEPCallback(SanitizersCallback);
762e3b55780SDimitry Andric }
763ac9a064cSDimitry Andric
764ac9a064cSDimitry Andric if (LowerAllowCheckPass::IsRequested()) {
765ac9a064cSDimitry Andric // We can optimize after inliner, and PGO profile matching. The hook below
766ac9a064cSDimitry Andric // is called at the end `buildFunctionSimplificationPipeline`, which called
767ac9a064cSDimitry Andric // from `buildInlinerPipeline`, which called after profile matching.
768ac9a064cSDimitry Andric PB.registerScalarOptimizerLateEPCallback(
769ac9a064cSDimitry Andric [](FunctionPassManager &FPM, OptimizationLevel Level) {
770ac9a064cSDimitry Andric FPM.addPass(LowerAllowCheckPass());
771ac9a064cSDimitry Andric });
772ac9a064cSDimitry Andric }
773344a3780SDimitry Andric }
774344a3780SDimitry Andric
RunOptimizationPipeline(BackendAction Action,std::unique_ptr<raw_pwrite_stream> & OS,std::unique_ptr<llvm::ToolOutputFile> & ThinLinkOS,BackendConsumer * BC)775c0981da4SDimitry Andric void EmitAssemblyHelper::RunOptimizationPipeline(
776c0981da4SDimitry Andric BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
777b1c73532SDimitry Andric std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
778e3b55780SDimitry Andric std::optional<PGOOptions> PGOOpt;
7797442d6faSDimitry Andric
780461a67faSDimitry Andric if (CodeGenOpts.hasProfileIRInstr())
7817442d6faSDimitry Andric // -fprofile-generate.
7827fa27ce4SDimitry Andric PGOOpt = PGOOptions(
7837fa27ce4SDimitry Andric CodeGenOpts.InstrProfileOutput.empty() ? getDefaultProfileGenName()
784461a67faSDimitry Andric : CodeGenOpts.InstrProfileOutput,
7857fa27ce4SDimitry Andric "", "", CodeGenOpts.MemoryProfileUsePath, nullptr, PGOOptions::IRInstr,
786ac9a064cSDimitry Andric PGOOptions::NoCSAction, ClPGOColdFuncAttr,
787ac9a064cSDimitry Andric CodeGenOpts.DebugInfoForProfiling,
788b1c73532SDimitry Andric /*PseudoProbeForProfiling=*/false, CodeGenOpts.AtomicProfileUpdate);
78922989816SDimitry Andric else if (CodeGenOpts.hasProfileIRUse()) {
7907442d6faSDimitry Andric // -fprofile-use.
79122989816SDimitry Andric auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
79222989816SDimitry Andric : PGOOptions::NoCSAction;
793ac9a064cSDimitry Andric PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
794ac9a064cSDimitry Andric CodeGenOpts.ProfileRemappingFile,
795ac9a064cSDimitry Andric CodeGenOpts.MemoryProfileUsePath, VFS,
796ac9a064cSDimitry Andric PGOOptions::IRUse, CSAction, ClPGOColdFuncAttr,
797ac9a064cSDimitry Andric CodeGenOpts.DebugInfoForProfiling);
79822989816SDimitry Andric } else if (!CodeGenOpts.SampleProfileFile.empty())
799461a67faSDimitry Andric // -fprofile-sample-use
800b60736ecSDimitry Andric PGOOpt = PGOOptions(
801b60736ecSDimitry Andric CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
8027fa27ce4SDimitry Andric CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse,
803ac9a064cSDimitry Andric PGOOptions::NoCSAction, ClPGOColdFuncAttr,
804ac9a064cSDimitry Andric CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
8057fa27ce4SDimitry Andric else if (!CodeGenOpts.MemoryProfileUsePath.empty())
8067fa27ce4SDimitry Andric // -fmemory-profile-use (without any of the above options)
8077fa27ce4SDimitry Andric PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, VFS,
8087fa27ce4SDimitry Andric PGOOptions::NoAction, PGOOptions::NoCSAction,
809ac9a064cSDimitry Andric ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
810b60736ecSDimitry Andric else if (CodeGenOpts.PseudoProbeForProfiling)
811b60736ecSDimitry Andric // -fpseudo-probe-for-profiling
812ac9a064cSDimitry Andric PGOOpt =
813ac9a064cSDimitry Andric PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
8147fa27ce4SDimitry Andric PGOOptions::NoAction, PGOOptions::NoCSAction,
815ac9a064cSDimitry Andric ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling, true);
816461a67faSDimitry Andric else if (CodeGenOpts.DebugInfoForProfiling)
817461a67faSDimitry Andric // -fdebug-info-for-profiling
8187fa27ce4SDimitry Andric PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
819ac9a064cSDimitry Andric PGOOptions::NoAction, PGOOptions::NoCSAction,
820ac9a064cSDimitry Andric ClPGOColdFuncAttr, true);
8217442d6faSDimitry Andric
82222989816SDimitry Andric // Check to see if we want to generate a CS profile.
82322989816SDimitry Andric if (CodeGenOpts.hasProfileCSIRInstr()) {
82422989816SDimitry Andric assert(!CodeGenOpts.hasProfileCSIRUse() &&
82522989816SDimitry Andric "Cannot have both CSProfileUse pass and CSProfileGen pass at "
82622989816SDimitry Andric "the same time");
827145449b1SDimitry Andric if (PGOOpt) {
82822989816SDimitry Andric assert(PGOOpt->Action != PGOOptions::IRInstr &&
82922989816SDimitry Andric PGOOpt->Action != PGOOptions::SampleUse &&
83022989816SDimitry Andric "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
83122989816SDimitry Andric " pass");
83222989816SDimitry Andric PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
83377fc4c14SDimitry Andric ? getDefaultProfileGenName()
83422989816SDimitry Andric : CodeGenOpts.InstrProfileOutput;
83522989816SDimitry Andric PGOOpt->CSAction = PGOOptions::CSIRInstr;
83622989816SDimitry Andric } else
837ac9a064cSDimitry Andric PGOOpt = PGOOptions("",
83822989816SDimitry Andric CodeGenOpts.InstrProfileOutput.empty()
83977fc4c14SDimitry Andric ? getDefaultProfileGenName()
84022989816SDimitry Andric : CodeGenOpts.InstrProfileOutput,
841ac9a064cSDimitry Andric "", /*MemoryProfile=*/"", nullptr,
842ac9a064cSDimitry Andric PGOOptions::NoAction, PGOOptions::CSIRInstr,
843ac9a064cSDimitry Andric ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
84422989816SDimitry Andric }
845c0981da4SDimitry Andric if (TM)
846c0981da4SDimitry Andric TM->setPGOOption(PGOOpt);
84722989816SDimitry Andric
84822989816SDimitry Andric PipelineTuningOptions PTO;
84922989816SDimitry Andric PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
85022989816SDimitry Andric // For historical reasons, loop interleaving is set to mirror setting for loop
85122989816SDimitry Andric // unrolling.
85222989816SDimitry Andric PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
85322989816SDimitry Andric PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
85422989816SDimitry Andric PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
855b60736ecSDimitry Andric PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
856cfca06d7SDimitry Andric // Only enable CGProfilePass when using integrated assembler, since
857cfca06d7SDimitry Andric // non-integrated assemblers don't recognize .cgprofile section.
858cfca06d7SDimitry Andric PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
8597fa27ce4SDimitry Andric PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
86022989816SDimitry Andric
861344a3780SDimitry Andric LoopAnalysisManager LAM;
862344a3780SDimitry Andric FunctionAnalysisManager FAM;
863344a3780SDimitry Andric CGSCCAnalysisManager CGAM;
864344a3780SDimitry Andric ModuleAnalysisManager MAM;
865344a3780SDimitry Andric
866344a3780SDimitry Andric bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
867519fc96cSDimitry Andric PassInstrumentationCallbacks PIC;
868344a3780SDimitry Andric PrintPassOptions PrintPassOpts;
869344a3780SDimitry Andric PrintPassOpts.Indent = DebugPassStructure;
870344a3780SDimitry Andric PrintPassOpts.SkipAnalyses = DebugPassStructure;
871e3b55780SDimitry Andric StandardInstrumentations SI(
872e3b55780SDimitry Andric TheModule->getContext(),
873e3b55780SDimitry Andric (CodeGenOpts.DebugPassManager || DebugPassStructure),
8747fa27ce4SDimitry Andric CodeGenOpts.VerifyEach, PrintPassOpts);
8757fa27ce4SDimitry Andric SI.registerCallbacks(PIC, &MAM);
876344a3780SDimitry Andric PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
87722989816SDimitry Andric
8787fa27ce4SDimitry Andric // Handle the assignment tracking feature options.
8797fa27ce4SDimitry Andric switch (CodeGenOpts.getAssignmentTrackingMode()) {
8807fa27ce4SDimitry Andric case CodeGenOptions::AssignmentTrackingOpts::Forced:
881e3b55780SDimitry Andric PB.registerPipelineStartEPCallback(
882e3b55780SDimitry Andric [&](ModulePassManager &MPM, OptimizationLevel Level) {
883e3b55780SDimitry Andric MPM.addPass(AssignmentTrackingPass());
884e3b55780SDimitry Andric });
8857fa27ce4SDimitry Andric break;
8867fa27ce4SDimitry Andric case CodeGenOptions::AssignmentTrackingOpts::Enabled:
8877fa27ce4SDimitry Andric // Disable assignment tracking in LTO builds for now as the performance
8887fa27ce4SDimitry Andric // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
8897fa27ce4SDimitry Andric if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
8907fa27ce4SDimitry Andric CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
8917fa27ce4SDimitry Andric PB.registerPipelineStartEPCallback(
8927fa27ce4SDimitry Andric [&](ModulePassManager &MPM, OptimizationLevel Level) {
8937fa27ce4SDimitry Andric // Only use assignment tracking if optimisations are enabled.
8947fa27ce4SDimitry Andric if (Level != OptimizationLevel::O0)
8957fa27ce4SDimitry Andric MPM.addPass(AssignmentTrackingPass());
8967fa27ce4SDimitry Andric });
8977fa27ce4SDimitry Andric }
8987fa27ce4SDimitry Andric break;
8997fa27ce4SDimitry Andric case CodeGenOptions::AssignmentTrackingOpts::Disabled:
9007fa27ce4SDimitry Andric break;
901e3b55780SDimitry Andric }
902e3b55780SDimitry Andric
9031f917f69SDimitry Andric // Enable verify-debuginfo-preserve-each for new PM.
9041f917f69SDimitry Andric DebugifyEachInstrumentation Debugify;
9051f917f69SDimitry Andric DebugInfoPerPass DebugInfoBeforePass;
9061f917f69SDimitry Andric if (CodeGenOpts.EnableDIPreservationVerify) {
9071f917f69SDimitry Andric Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
9081f917f69SDimitry Andric Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
9091f917f69SDimitry Andric
9101f917f69SDimitry Andric if (!CodeGenOpts.DIBugsReportFilePath.empty())
9111f917f69SDimitry Andric Debugify.setOrigDIVerifyBugsReportFilePath(
9121f917f69SDimitry Andric CodeGenOpts.DIBugsReportFilePath);
9137fa27ce4SDimitry Andric Debugify.registerCallbacks(PIC, MAM);
9141f917f69SDimitry Andric }
91522989816SDimitry Andric // Attempt to load pass plugins and register their callbacks with PB.
91622989816SDimitry Andric for (auto &PluginFN : CodeGenOpts.PassPlugins) {
91722989816SDimitry Andric auto PassPlugin = PassPlugin::Load(PluginFN);
91822989816SDimitry Andric if (PassPlugin) {
91922989816SDimitry Andric PassPlugin->registerPassBuilderCallbacks(PB);
92022989816SDimitry Andric } else {
92122989816SDimitry Andric Diags.Report(diag::err_fe_unable_to_load_plugin)
92222989816SDimitry Andric << PluginFN << toString(PassPlugin.takeError());
92322989816SDimitry Andric }
92422989816SDimitry Andric }
92599aabd70SDimitry Andric for (const auto &PassCallback : CodeGenOpts.PassBuilderCallbacks)
926b1c73532SDimitry Andric PassCallback(PB);
927706b4fc4SDimitry Andric #define HANDLE_EXTENSION(Ext) \
928706b4fc4SDimitry Andric get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
929706b4fc4SDimitry Andric #include "llvm/Support/Extension.def"
930cf1b4019SDimitry Andric
931461a67faSDimitry Andric // Register the target library analysis directly and give it a customized
932461a67faSDimitry Andric // preset TLI.
933461a67faSDimitry Andric std::unique_ptr<TargetLibraryInfoImpl> TLII(
934b1c73532SDimitry Andric llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
935461a67faSDimitry Andric FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
936461a67faSDimitry Andric
937bab175ecSDimitry Andric // Register all the basic analyses with the managers.
938bab175ecSDimitry Andric PB.registerModuleAnalyses(MAM);
939bab175ecSDimitry Andric PB.registerCGSCCAnalyses(CGAM);
940bab175ecSDimitry Andric PB.registerFunctionAnalyses(FAM);
941bab175ecSDimitry Andric PB.registerLoopAnalyses(LAM);
942bab175ecSDimitry Andric PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
943bab175ecSDimitry Andric
944344a3780SDimitry Andric ModulePassManager MPM;
945b1c73532SDimitry Andric // Add a verifier pass, before any other passes, to catch CodeGen issues.
946b1c73532SDimitry Andric if (CodeGenOpts.VerifyModule)
947b1c73532SDimitry Andric MPM.addPass(VerifierPass());
948bab175ecSDimitry Andric
949bab175ecSDimitry Andric if (!CodeGenOpts.DisableLLVMPasses) {
950cf1b4019SDimitry Andric // Map our optimization levels into one of the distinct levels used to
951cf1b4019SDimitry Andric // configure the pipeline.
952c0981da4SDimitry Andric OptimizationLevel Level = mapToLevel(CodeGenOpts);
953bab175ecSDimitry Andric
954b1c73532SDimitry Andric const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
955b1c73532SDimitry Andric const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
956b60736ecSDimitry Andric
957b60736ecSDimitry Andric if (LangOpts.ObjCAutoRefCount) {
958b60736ecSDimitry Andric PB.registerPipelineStartEPCallback(
959c0981da4SDimitry Andric [](ModulePassManager &MPM, OptimizationLevel Level) {
960c0981da4SDimitry Andric if (Level != OptimizationLevel::O0)
961b60736ecSDimitry Andric MPM.addPass(
962b60736ecSDimitry Andric createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
963b60736ecSDimitry Andric });
964b60736ecSDimitry Andric PB.registerPipelineEarlySimplificationEPCallback(
965c0981da4SDimitry Andric [](ModulePassManager &MPM, OptimizationLevel Level) {
966c0981da4SDimitry Andric if (Level != OptimizationLevel::O0)
967b60736ecSDimitry Andric MPM.addPass(ObjCARCAPElimPass());
968b60736ecSDimitry Andric });
969b60736ecSDimitry Andric PB.registerScalarOptimizerLateEPCallback(
970c0981da4SDimitry Andric [](FunctionPassManager &FPM, OptimizationLevel Level) {
971c0981da4SDimitry Andric if (Level != OptimizationLevel::O0)
972b60736ecSDimitry Andric FPM.addPass(ObjCARCOptPass());
973b60736ecSDimitry Andric });
974b60736ecSDimitry Andric }
975b60736ecSDimitry Andric
976cfca06d7SDimitry Andric // If we reached here with a non-empty index file name, then the index
977cfca06d7SDimitry Andric // file was empty and we are not performing ThinLTO backend compilation
978344a3780SDimitry Andric // (used in testing in a distributed build environment).
979344a3780SDimitry Andric bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
980344a3780SDimitry Andric // If so drop any the type test assume sequences inserted for whole program
981344a3780SDimitry Andric // vtables so that codegen doesn't complain.
982344a3780SDimitry Andric if (IsThinLTOPostLink)
983b60736ecSDimitry Andric PB.registerPipelineStartEPCallback(
984c0981da4SDimitry Andric [](ModulePassManager &MPM, OptimizationLevel Level) {
985cfca06d7SDimitry Andric MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
986cfca06d7SDimitry Andric /*ImportSummary=*/nullptr,
987cfca06d7SDimitry Andric /*DropTypeTests=*/true));
988cfca06d7SDimitry Andric });
989cfca06d7SDimitry Andric
990b60736ecSDimitry Andric // Register callbacks to schedule sanitizer passes at the appropriate part
991b60736ecSDimitry Andric // of the pipeline.
992461a67faSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
993461a67faSDimitry Andric PB.registerScalarOptimizerLateEPCallback(
994c0981da4SDimitry Andric [](FunctionPassManager &FPM, OptimizationLevel Level) {
995461a67faSDimitry Andric FPM.addPass(BoundsCheckingPass());
996461a67faSDimitry Andric });
997cfca06d7SDimitry Andric
998344a3780SDimitry Andric // Don't add sanitizers if we are here from ThinLTO PostLink. That already
999344a3780SDimitry Andric // done on PreLink stage.
1000e3b55780SDimitry Andric if (!IsThinLTOPostLink) {
1001344a3780SDimitry Andric addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1002e3b55780SDimitry Andric addKCFIPass(TargetTriple, LangOpts, PB);
1003e3b55780SDimitry Andric }
1004b60736ecSDimitry Andric
1005e3b55780SDimitry Andric if (std::optional<GCOVOptions> Options =
1006e3b55780SDimitry Andric getGCOVOptions(CodeGenOpts, LangOpts))
1007b60736ecSDimitry Andric PB.registerPipelineStartEPCallback(
1008c0981da4SDimitry Andric [Options](ModulePassManager &MPM, OptimizationLevel Level) {
100948675466SDimitry Andric MPM.addPass(GCOVProfilerPass(*Options));
101048675466SDimitry Andric });
1011e3b55780SDimitry Andric if (std::optional<InstrProfOptions> Options =
101222989816SDimitry Andric getInstrProfOptions(CodeGenOpts, LangOpts))
1013b60736ecSDimitry Andric PB.registerPipelineStartEPCallback(
1014c0981da4SDimitry Andric [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1015312c0ed1SDimitry Andric MPM.addPass(InstrProfilingLoweringPass(*Options, false));
101622989816SDimitry Andric });
1017461a67faSDimitry Andric
10187fa27ce4SDimitry Andric // TODO: Consider passing the MemoryProfileOutput to the pass builder via
10197fa27ce4SDimitry Andric // the PGOOptions, and set this up there.
10207fa27ce4SDimitry Andric if (!CodeGenOpts.MemoryProfileOutput.empty()) {
10217fa27ce4SDimitry Andric PB.registerOptimizerLastEPCallback(
10227fa27ce4SDimitry Andric [](ModulePassManager &MPM, OptimizationLevel Level) {
10237fa27ce4SDimitry Andric MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
10247fa27ce4SDimitry Andric MPM.addPass(ModuleMemProfilerPass());
10257fa27ce4SDimitry Andric });
10267fa27ce4SDimitry Andric }
10277fa27ce4SDimitry Andric
10287fa27ce4SDimitry Andric if (CodeGenOpts.FatLTO) {
10294df029ccSDimitry Andric MPM.addPass(PB.buildFatLTODefaultPipeline(
10304df029ccSDimitry Andric Level, PrepareForThinLTO,
10314df029ccSDimitry Andric PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1032b1c73532SDimitry Andric } else if (PrepareForThinLTO) {
1033b1c73532SDimitry Andric MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1034b1c73532SDimitry Andric } else if (PrepareForLTO) {
1035b1c73532SDimitry Andric MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1036b60736ecSDimitry Andric } else {
1037b1c73532SDimitry Andric MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1038b60736ecSDimitry Andric }
1039519fc96cSDimitry Andric }
1040bab175ecSDimitry Andric
1041ac9a064cSDimitry Andric // Link against bitcodes supplied via the -mlink-builtin-bitcode option
1042ac9a064cSDimitry Andric if (CodeGenOpts.LinkBitcodePostopt)
1043ac9a064cSDimitry Andric MPM.addPass(LinkInModulesPass(BC));
1044b1c73532SDimitry Andric
1045c0981da4SDimitry Andric // Add a verifier pass if requested. We don't have to do this if the action
1046c0981da4SDimitry Andric // requires code generation because there will already be a verifier pass in
1047c0981da4SDimitry Andric // the code-generation pipeline.
1048b1c73532SDimitry Andric // Since we already added a verifier pass above, this
1049b1c73532SDimitry Andric // might even not run the analysis, if previous passes caused no changes.
1050c0981da4SDimitry Andric if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
1051c0981da4SDimitry Andric MPM.addPass(VerifierPass());
1052bab175ecSDimitry Andric
1053ac9a064cSDimitry Andric if (Action == Backend_EmitBC || Action == Backend_EmitLL ||
1054ac9a064cSDimitry Andric CodeGenOpts.FatLTO) {
1055676fbe81SDimitry Andric if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1056e3b55780SDimitry Andric if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1057b1c73532SDimitry Andric TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1058e3b55780SDimitry Andric CodeGenOpts.EnableSplitLTOUnit);
1059e3b55780SDimitry Andric if (Action == Backend_EmitBC) {
1060551c6985SDimitry Andric if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
106148675466SDimitry Andric ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
106248675466SDimitry Andric if (!ThinLinkOS)
1063551c6985SDimitry Andric return;
1064551c6985SDimitry Andric }
10657fa27ce4SDimitry Andric MPM.addPass(ThinLTOBitcodeWriterPass(
10667fa27ce4SDimitry Andric *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1067ac9a064cSDimitry Andric } else if (Action == Backend_EmitLL) {
1068e3b55780SDimitry Andric MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1069e3b55780SDimitry Andric /*EmitLTOSummary=*/true));
1070e3b55780SDimitry Andric }
1071e3b55780SDimitry Andric } else {
107248675466SDimitry Andric // Emit a module summary by default for Regular LTO except for ld64
107348675466SDimitry Andric // targets
1074145449b1SDimitry Andric bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1075676fbe81SDimitry Andric if (EmitLTOSummary) {
10767fa27ce4SDimitry Andric if (!TheModule->getModuleFlag("ThinLTO") && !CodeGenOpts.UnifiedLTO)
1077b1c73532SDimitry Andric TheModule->addModuleFlag(llvm::Module::Error, "ThinLTO", uint32_t(0));
1078f65dcba8SDimitry Andric if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1079b1c73532SDimitry Andric TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1080519fc96cSDimitry Andric uint32_t(1));
1081676fbe81SDimitry Andric }
1082ac9a064cSDimitry Andric if (Action == Backend_EmitBC) {
1083e3b55780SDimitry Andric MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1084e3b55780SDimitry Andric EmitLTOSummary));
1085ac9a064cSDimitry Andric } else if (Action == Backend_EmitLL) {
1086e3b55780SDimitry Andric MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1087e3b55780SDimitry Andric EmitLTOSummary));
1088551c6985SDimitry Andric }
1089c0981da4SDimitry Andric }
1090ac9a064cSDimitry Andric
1091ac9a064cSDimitry Andric if (shouldEmitUnifiedLTOModueFlag())
1092b1c73532SDimitry Andric TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
10937fa27ce4SDimitry Andric }
1094c0981da4SDimitry Andric
1095b1c73532SDimitry Andric // Print a textual, '-passes=' compatible, representation of pipeline if
1096b1c73532SDimitry Andric // requested.
1097b1c73532SDimitry Andric if (PrintPipelinePasses) {
1098b1c73532SDimitry Andric MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1099b1c73532SDimitry Andric auto PassName = PIC.getPassNameForClassName(ClassName);
1100b1c73532SDimitry Andric return PassName.empty() ? ClassName : PassName;
1101b1c73532SDimitry Andric });
1102b1c73532SDimitry Andric outs() << "\n";
1103b1c73532SDimitry Andric return;
1104b1c73532SDimitry Andric }
1105b1c73532SDimitry Andric
1106b1c73532SDimitry Andric if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1107b1c73532SDimitry Andric LangOpts.HIPStdParInterposeAlloc)
1108b1c73532SDimitry Andric MPM.addPass(HipStdParAllocationInterpositionPass());
1109b1c73532SDimitry Andric
1110c0981da4SDimitry Andric // Now that we have all of the passes ready, run them.
11116f8fc217SDimitry Andric {
1112c0981da4SDimitry Andric PrettyStackTraceString CrashInfo("Optimizer");
11136f8fc217SDimitry Andric llvm::TimeTraceScope TimeScope("Optimizer");
1114c0981da4SDimitry Andric MPM.run(*TheModule, MAM);
1115c0981da4SDimitry Andric }
11166f8fc217SDimitry Andric }
1117c0981da4SDimitry Andric
RunCodegenPipeline(BackendAction Action,std::unique_ptr<raw_pwrite_stream> & OS,std::unique_ptr<llvm::ToolOutputFile> & DwoOS)1118c0981da4SDimitry Andric void EmitAssemblyHelper::RunCodegenPipeline(
1119c0981da4SDimitry Andric BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1120c0981da4SDimitry Andric std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1121c0981da4SDimitry Andric // We still use the legacy PM to run the codegen pipeline since the new PM
1122c0981da4SDimitry Andric // does not work with the codegen pipeline.
1123c0981da4SDimitry Andric // FIXME: make the new PM work with the codegen pipeline.
1124c0981da4SDimitry Andric legacy::PassManager CodeGenPasses;
1125c0981da4SDimitry Andric
1126c0981da4SDimitry Andric // Append any output we need to the pass manager.
1127c0981da4SDimitry Andric switch (Action) {
1128bab175ecSDimitry Andric case Backend_EmitAssembly:
1129bab175ecSDimitry Andric case Backend_EmitMCNull:
1130bab175ecSDimitry Andric case Backend_EmitObj:
1131bab175ecSDimitry Andric CodeGenPasses.add(
1132bab175ecSDimitry Andric createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
113322989816SDimitry Andric if (!CodeGenOpts.SplitDwarfOutput.empty()) {
113422989816SDimitry Andric DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
113548675466SDimitry Andric if (!DwoOS)
113648675466SDimitry Andric return;
113748675466SDimitry Andric }
113848675466SDimitry Andric if (!AddEmitPasses(CodeGenPasses, Action, *OS,
113948675466SDimitry Andric DwoOS ? &DwoOS->os() : nullptr))
1140bab175ecSDimitry Andric // FIXME: Should we handle this error differently?
1141bab175ecSDimitry Andric return;
1142bab175ecSDimitry Andric break;
1143c0981da4SDimitry Andric default:
1144c0981da4SDimitry Andric return;
1145bab175ecSDimitry Andric }
1146bab175ecSDimitry Andric
1147b1c73532SDimitry Andric // If -print-pipeline-passes is requested, don't run the legacy pass manager.
1148b1c73532SDimitry Andric // FIXME: when codegen is switched to use the new pass manager, it should also
1149b1c73532SDimitry Andric // emit pass names here.
1150b1c73532SDimitry Andric if (PrintPipelinePasses) {
1151b1c73532SDimitry Andric return;
1152b1c73532SDimitry Andric }
1153b1c73532SDimitry Andric
11546f8fc217SDimitry Andric {
1155c0981da4SDimitry Andric PrettyStackTraceString CrashInfo("Code generation");
11566f8fc217SDimitry Andric llvm::TimeTraceScope TimeScope("CodeGenPasses");
1157c0981da4SDimitry Andric CodeGenPasses.run(*TheModule);
1158c0981da4SDimitry Andric }
11596f8fc217SDimitry Andric }
1160c0981da4SDimitry Andric
EmitAssembly(BackendAction Action,std::unique_ptr<raw_pwrite_stream> OS,BackendConsumer * BC)1161c0981da4SDimitry Andric void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1162b1c73532SDimitry Andric std::unique_ptr<raw_pwrite_stream> OS,
1163b1c73532SDimitry Andric BackendConsumer *BC) {
1164c0981da4SDimitry Andric TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1165c0981da4SDimitry Andric setCommandLineOpts(CodeGenOpts);
1166c0981da4SDimitry Andric
1167c0981da4SDimitry Andric bool RequiresCodeGen = actionRequiresCodeGen(Action);
1168c0981da4SDimitry Andric CreateTargetMachine(RequiresCodeGen);
1169c0981da4SDimitry Andric
1170c0981da4SDimitry Andric if (RequiresCodeGen && !TM)
1171c0981da4SDimitry Andric return;
1172c0981da4SDimitry Andric if (TM)
1173c0981da4SDimitry Andric TheModule->setDataLayout(TM->createDataLayout());
1174c0981da4SDimitry Andric
1175bab175ecSDimitry Andric // Before executing passes, print the final values of the LLVM options.
1176bab175ecSDimitry Andric cl::PrintOptionValues();
1177bab175ecSDimitry Andric
1178c0981da4SDimitry Andric std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1179b1c73532SDimitry Andric RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1180c0981da4SDimitry Andric RunCodegenPipeline(Action, OS, DwoOS);
118148675466SDimitry Andric
118248675466SDimitry Andric if (ThinLinkOS)
118348675466SDimitry Andric ThinLinkOS->keep();
118448675466SDimitry Andric if (DwoOS)
118548675466SDimitry Andric DwoOS->keep();
1186bab175ecSDimitry Andric }
1187bab175ecSDimitry Andric
runThinLTOBackend(DiagnosticsEngine & Diags,ModuleSummaryIndex * CombinedIndex,llvm::Module * M,const HeaderSearchOptions & HeaderOpts,const CodeGenOptions & CGOpts,const clang::TargetOptions & TOpts,const LangOptions & LOpts,std::unique_ptr<raw_pwrite_stream> OS,std::string SampleProfile,std::string ProfileRemapping,BackendAction Action)1188cfca06d7SDimitry Andric static void runThinLTOBackend(
1189b1c73532SDimitry Andric DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex,
1190b1c73532SDimitry Andric llvm::Module *M, const HeaderSearchOptions &HeaderOpts,
1191b1c73532SDimitry Andric const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
1192b1c73532SDimitry Andric const LangOptions &LOpts, std::unique_ptr<raw_pwrite_stream> OS,
1193b1c73532SDimitry Andric std::string SampleProfile, std::string ProfileRemapping,
1194b1c73532SDimitry Andric BackendAction Action) {
1195b1c73532SDimitry Andric DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1196bab175ecSDimitry Andric ModuleToDefinedGVSummaries;
1197bab175ecSDimitry Andric CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1198bab175ecSDimitry Andric
1199583e75ccSDimitry Andric setCommandLineOpts(CGOpts);
1200583e75ccSDimitry Andric
1201bab175ecSDimitry Andric // We can simply import the values mentioned in the combined index, since
1202bab175ecSDimitry Andric // we should only invoke this using the individual indexes written out
1203bab175ecSDimitry Andric // via a WriteIndexesThinBackend.
1204bab175ecSDimitry Andric FunctionImporter::ImportMapTy ImportList;
1205344a3780SDimitry Andric if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1206bab175ecSDimitry Andric return;
1207bab175ecSDimitry Andric
1208e3b55780SDimitry Andric auto AddStream = [&](size_t Task, const Twine &ModuleName) {
120977fc4c14SDimitry Andric return std::make_unique<CachedFileStream>(std::move(OS),
121077fc4c14SDimitry Andric CGOpts.ObjectFilenameForDebug);
1211bab175ecSDimitry Andric };
1212bab175ecSDimitry Andric lto::Config Conf;
121348675466SDimitry Andric if (CGOpts.SaveTempsFilePrefix != "") {
121448675466SDimitry Andric if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
121548675466SDimitry Andric /* UseInputModulePath */ false)) {
121648675466SDimitry Andric handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
121748675466SDimitry Andric errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
121848675466SDimitry Andric << '\n';
121948675466SDimitry Andric });
122048675466SDimitry Andric }
122148675466SDimitry Andric }
12227442d6faSDimitry Andric Conf.CPU = TOpts.CPU;
12237442d6faSDimitry Andric Conf.CodeModel = getCodeModel(CGOpts);
12247442d6faSDimitry Andric Conf.MAttrs = TOpts.Features;
122548675466SDimitry Andric Conf.RelocModel = CGOpts.RelocationModel;
1226b1c73532SDimitry Andric std::optional<CodeGenOptLevel> OptLevelOrNone =
1227e3b55780SDimitry Andric CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1228e3b55780SDimitry Andric assert(OptLevelOrNone && "Invalid optimization level!");
1229e3b55780SDimitry Andric Conf.CGOptLevel = *OptLevelOrNone;
123022989816SDimitry Andric Conf.OptLevel = CGOpts.OptimizationLevel;
1231cfca06d7SDimitry Andric initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
12327442d6faSDimitry Andric Conf.SampleProfile = std::move(SampleProfile);
1233706b4fc4SDimitry Andric Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1234706b4fc4SDimitry Andric // For historical reasons, loop interleaving is set to mirror setting for loop
1235706b4fc4SDimitry Andric // unrolling.
1236706b4fc4SDimitry Andric Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1237706b4fc4SDimitry Andric Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1238706b4fc4SDimitry Andric Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1239cfca06d7SDimitry Andric // Only enable CGProfilePass when using integrated assembler, since
1240cfca06d7SDimitry Andric // non-integrated assemblers don't recognize .cgprofile section.
1241cfca06d7SDimitry Andric Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
124222989816SDimitry Andric
124322989816SDimitry Andric // Context sensitive profile.
124422989816SDimitry Andric if (CGOpts.hasProfileCSIRInstr()) {
124522989816SDimitry Andric Conf.RunCSIRInstr = true;
124622989816SDimitry Andric Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
124722989816SDimitry Andric } else if (CGOpts.hasProfileCSIRUse()) {
124822989816SDimitry Andric Conf.RunCSIRInstr = false;
124922989816SDimitry Andric Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
125022989816SDimitry Andric }
125122989816SDimitry Andric
1252676fbe81SDimitry Andric Conf.ProfileRemapping = std::move(ProfileRemapping);
1253461a67faSDimitry Andric Conf.DebugPassManager = CGOpts.DebugPassManager;
12547fa27ce4SDimitry Andric Conf.VerifyEach = CGOpts.VerifyEach;
125548675466SDimitry Andric Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
125648675466SDimitry Andric Conf.RemarksFilename = CGOpts.OptRecordFile;
125722989816SDimitry Andric Conf.RemarksPasses = CGOpts.OptRecordPasses;
125822989816SDimitry Andric Conf.RemarksFormat = CGOpts.OptRecordFormat;
125922989816SDimitry Andric Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
126022989816SDimitry Andric Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
12617442d6faSDimitry Andric switch (Action) {
12627442d6faSDimitry Andric case Backend_EmitNothing:
1263b1c73532SDimitry Andric Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) {
12647442d6faSDimitry Andric return false;
12657442d6faSDimitry Andric };
12667442d6faSDimitry Andric break;
12677442d6faSDimitry Andric case Backend_EmitLL:
1268b1c73532SDimitry Andric Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
12697442d6faSDimitry Andric M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
12707442d6faSDimitry Andric return false;
12717442d6faSDimitry Andric };
12727442d6faSDimitry Andric break;
12737442d6faSDimitry Andric case Backend_EmitBC:
1274b1c73532SDimitry Andric Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
127548675466SDimitry Andric WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
12767442d6faSDimitry Andric return false;
12777442d6faSDimitry Andric };
12787442d6faSDimitry Andric break;
12797442d6faSDimitry Andric default:
12807442d6faSDimitry Andric Conf.CGFileType = getCodeGenFileType(Action);
12817442d6faSDimitry Andric break;
12827442d6faSDimitry Andric }
1283b60736ecSDimitry Andric if (Error E =
1284b60736ecSDimitry Andric thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1285b60736ecSDimitry Andric ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1286344a3780SDimitry Andric /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1287bab175ecSDimitry Andric handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1288bab175ecSDimitry Andric errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1289bab175ecSDimitry Andric });
1290bab175ecSDimitry Andric }
1291bab175ecSDimitry Andric }
1292bab175ecSDimitry Andric
EmitBackendOutput(DiagnosticsEngine & Diags,const HeaderSearchOptions & HeaderOpts,const CodeGenOptions & CGOpts,const clang::TargetOptions & TOpts,const LangOptions & LOpts,StringRef TDesc,llvm::Module * M,BackendAction Action,IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,std::unique_ptr<raw_pwrite_stream> OS,BackendConsumer * BC)1293b1c73532SDimitry Andric void clang::EmitBackendOutput(
1294b1c73532SDimitry Andric DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderOpts,
1295b1c73532SDimitry Andric const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
1296b1c73532SDimitry Andric const LangOptions &LOpts, StringRef TDesc, llvm::Module *M,
1297b1c73532SDimitry Andric BackendAction Action, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
1298b1c73532SDimitry Andric std::unique_ptr<raw_pwrite_stream> OS, BackendConsumer *BC) {
129922989816SDimitry Andric
1300706b4fc4SDimitry Andric llvm::TimeTraceScope TimeScope("Backend");
130122989816SDimitry Andric
130248675466SDimitry Andric std::unique_ptr<llvm::Module> EmptyModule;
1303bab175ecSDimitry Andric if (!CGOpts.ThinLTOIndexFile.empty()) {
1304fdc82ccbSDimitry Andric // If we are performing a ThinLTO importing compile, load the function index
1305fdc82ccbSDimitry Andric // into memory and pass it into runThinLTOBackend, which will run the
1306fdc82ccbSDimitry Andric // function importer and invoke LTO passes.
1307c0981da4SDimitry Andric std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1308c0981da4SDimitry Andric if (Error E = llvm::getModuleSummaryIndexForFile(
1309c0981da4SDimitry Andric CGOpts.ThinLTOIndexFile,
1310c0981da4SDimitry Andric /*IgnoreEmptyThinLTOIndexFile*/ true)
1311c0981da4SDimitry Andric .moveInto(CombinedIndex)) {
1312c0981da4SDimitry Andric logAllUnhandledErrors(std::move(E), errs(),
1313fdc82ccbSDimitry Andric "Error loading index file '" +
1314fdc82ccbSDimitry Andric CGOpts.ThinLTOIndexFile + "': ");
1315bab175ecSDimitry Andric return;
1316bab175ecSDimitry Andric }
1317c0981da4SDimitry Andric
1318fdc82ccbSDimitry Andric // A null CombinedIndex means we should skip ThinLTO compilation
1319fdc82ccbSDimitry Andric // (LLVM will optionally ignore empty index files, returning null instead
1320fdc82ccbSDimitry Andric // of an error).
132148675466SDimitry Andric if (CombinedIndex) {
132248675466SDimitry Andric if (!CombinedIndex->skipModuleByDistributedBackend()) {
1323cfca06d7SDimitry Andric runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1324cfca06d7SDimitry Andric TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1325676fbe81SDimitry Andric CGOpts.ProfileRemappingFile, Action);
1326fdc82ccbSDimitry Andric return;
1327fdc82ccbSDimitry Andric }
132848675466SDimitry Andric // Distributed indexing detected that nothing from the module is needed
132948675466SDimitry Andric // for the final linking. So we can skip the compilation. We sill need to
133048675466SDimitry Andric // output an empty object file to make sure that a linker does not fail
133148675466SDimitry Andric // trying to read it. Also for some features, like CFI, we must skip
133248675466SDimitry Andric // the compilation as CombinedIndex does not contain all required
133348675466SDimitry Andric // information.
1334519fc96cSDimitry Andric EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
133548675466SDimitry Andric EmptyModule->setTargetTriple(M->getTargetTriple());
133648675466SDimitry Andric M = EmptyModule.get();
133748675466SDimitry Andric }
1338fdc82ccbSDimitry Andric }
1339bab175ecSDimitry Andric
13407fa27ce4SDimitry Andric EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M, VFS);
1341b1c73532SDimitry Andric AsmHelper.EmitAssembly(Action, std::move(OS), BC);
13429f4dbff6SDimitry Andric
13432b6b257fSDimitry Andric // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
13442b6b257fSDimitry Andric // DataLayout.
13452b6b257fSDimitry Andric if (AsmHelper.TM) {
134645b53394SDimitry Andric std::string DLDesc = M->getDataLayout().getStringRepresentation();
1347344a3780SDimitry Andric if (DLDesc != TDesc) {
13489f4dbff6SDimitry Andric unsigned DiagID = Diags.getCustomDiagID(
13499f4dbff6SDimitry Andric DiagnosticsEngine::Error, "backend data layout '%0' does not match "
13509f4dbff6SDimitry Andric "expected target description '%1'");
1351344a3780SDimitry Andric Diags.Report(DiagID) << DLDesc << TDesc;
13529f4dbff6SDimitry Andric }
13539f4dbff6SDimitry Andric }
13544ba67500SRoman Divacky }
13552b6b257fSDimitry Andric
13562b6b257fSDimitry Andric // With -fembed-bitcode, save a copy of the llvm IR as data in the
13572b6b257fSDimitry Andric // __LLVM,__bitcode section.
EmbedBitcode(llvm::Module * M,const CodeGenOptions & CGOpts,llvm::MemoryBufferRef Buf)13582b6b257fSDimitry Andric void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
13592b6b257fSDimitry Andric llvm::MemoryBufferRef Buf) {
13602b6b257fSDimitry Andric if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
13612b6b257fSDimitry Andric return;
1362ecbca9f5SDimitry Andric llvm::embedBitcodeInModule(
1363706b4fc4SDimitry Andric *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1364706b4fc4SDimitry Andric CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1365b60736ecSDimitry Andric CGOpts.CmdArgs);
13662b6b257fSDimitry Andric }
1367ecbca9f5SDimitry Andric
EmbedObject(llvm::Module * M,const CodeGenOptions & CGOpts,DiagnosticsEngine & Diags)1368ecbca9f5SDimitry Andric void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1369ecbca9f5SDimitry Andric DiagnosticsEngine &Diags) {
1370ecbca9f5SDimitry Andric if (CGOpts.OffloadObjects.empty())
1371ecbca9f5SDimitry Andric return;
1372ecbca9f5SDimitry Andric
1373ecbca9f5SDimitry Andric for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1374ecbca9f5SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1375145449b1SDimitry Andric llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1376b1c73532SDimitry Andric if (ObjectOrErr.getError()) {
1377ecbca9f5SDimitry Andric auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1378ecbca9f5SDimitry Andric "could not open '%0' for embedding");
1379145449b1SDimitry Andric Diags.Report(DiagID) << OffloadObject;
1380ecbca9f5SDimitry Andric return;
1381ecbca9f5SDimitry Andric }
1382ecbca9f5SDimitry Andric
1383145449b1SDimitry Andric llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1384145449b1SDimitry Andric Align(object::OffloadBinary::getAlignment()));
1385ecbca9f5SDimitry Andric }
1386ecbca9f5SDimitry Andric }
1387