xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/BackendUtil.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "clang/CodeGen/BackendUtil.h"
105f757f3fSDimitry Andric #include "BackendConsumer.h"
115f757f3fSDimitry Andric #include "LinkInModulesPass.h"
120b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
130b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
140b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
150b57cec5SDimitry Andric #include "clang/Basic/TargetOptions.h"
160b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
170b57cec5SDimitry Andric #include "clang/Frontend/Utils.h"
180b57cec5SDimitry Andric #include "clang/Lex/HeaderSearchOptions.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
200b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
210b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
22e8d8bef9SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
23bdd1243dSDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
260b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
270b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeWriter.h"
280b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeWriterPass.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/RegAllocRegistry.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/SchedulerRegistry.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
325f757f3fSDimitry Andric #include "llvm/Frontend/Driver/CodeGenOptions.h"
330b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
34bdd1243dSDimitry Andric #include "llvm/IR/DebugInfo.h"
350b57cec5SDimitry Andric #include "llvm/IR/LegacyPassManager.h"
360b57cec5SDimitry Andric #include "llvm/IR/Module.h"
370b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
385ffd83dbSDimitry Andric #include "llvm/IR/PassManager.h"
390b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
40bdd1243dSDimitry Andric #include "llvm/IRPrinter/IRPrintingPasses.h"
410b57cec5SDimitry Andric #include "llvm/LTO/LTOBackend.h"
420b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
43349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.h"
4481ad6265SDimitry Andric #include "llvm/Object/OffloadBinary.h"
450b57cec5SDimitry Andric #include "llvm/Passes/PassBuilder.h"
460b57cec5SDimitry Andric #include "llvm/Passes/PassPlugin.h"
47a7dea167SDimitry Andric #include "llvm/Passes/StandardInstrumentations.h"
485f757f3fSDimitry Andric #include "llvm/ProfileData/InstrProfCorrelator.h"
490b57cec5SDimitry Andric #include "llvm/Support/BuryPointer.h"
500b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
510b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
520b57cec5SDimitry Andric #include "llvm/Support/PrettyStackTrace.h"
530b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
540b57cec5SDimitry Andric #include "llvm/Support/Timer.h"
555ffd83dbSDimitry Andric #include "llvm/Support/ToolOutputFile.h"
5606c3fb27SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
570b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
580b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
590b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
6006c3fb27SDimitry Andric #include "llvm/TargetParser/SubtargetFeature.h"
6106c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
625f757f3fSDimitry Andric #include "llvm/Transforms/HipStdPar/HipStdPar.h"
635f757f3fSDimitry Andric #include "llvm/Transforms/IPO/EmbedBitcodePass.h"
645ffd83dbSDimitry Andric #include "llvm/Transforms/IPO/LowerTypeTests.h"
650b57cec5SDimitry Andric #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
660b57cec5SDimitry Andric #include "llvm/Transforms/InstCombine/InstCombine.h"
670b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation.h"
680b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
69fe6060f1SDimitry Andric #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
700b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
71e8d8bef9SDimitry Andric #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
720b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
730b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
740b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
75bdd1243dSDimitry Andric #include "llvm/Transforms/Instrumentation/KCFI.h"
76*0fca6ea1SDimitry Andric #include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
77e8d8bef9SDimitry Andric #include "llvm/Transforms/Instrumentation/MemProfiler.h"
780b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
79*0fca6ea1SDimitry Andric #include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
805f757f3fSDimitry Andric #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
81bdd1243dSDimitry Andric #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
82a7dea167SDimitry Andric #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
830b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
840b57cec5SDimitry Andric #include "llvm/Transforms/ObjCARC.h"
85fe6060f1SDimitry Andric #include "llvm/Transforms/Scalar/EarlyCSE.h"
860b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/GVN.h"
87bdd1243dSDimitry Andric #include "llvm/Transforms/Scalar/JumpThreading.h"
88fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/Debugify.h"
891fd87a68SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
900b57cec5SDimitry Andric #include <memory>
91bdd1243dSDimitry Andric #include <optional>
920b57cec5SDimitry Andric using namespace clang;
930b57cec5SDimitry Andric using namespace llvm;
940b57cec5SDimitry Andric 
95480093f4SDimitry Andric #define HANDLE_EXTENSION(Ext)                                                  \
96480093f4SDimitry Andric   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
97480093f4SDimitry Andric #include "llvm/Support/Extension.def"
98480093f4SDimitry Andric 
990eae32dcSDimitry Andric namespace llvm {
1005f757f3fSDimitry Andric extern cl::opt<bool> PrintPipelinePasses;
101bdd1243dSDimitry Andric 
102bdd1243dSDimitry Andric // Experiment to move sanitizers earlier.
103bdd1243dSDimitry Andric static cl::opt<bool> ClSanitizeOnOptimizerEarlyEP(
104bdd1243dSDimitry Andric     "sanitizer-early-opt-ep", cl::Optional,
105*0fca6ea1SDimitry Andric     cl::desc("Insert sanitizers on OptimizerEarlyEP."));
106*0fca6ea1SDimitry Andric 
107*0fca6ea1SDimitry Andric // Experiment to mark cold functions as optsize/minsize/optnone.
108*0fca6ea1SDimitry Andric // TODO: remove once this is exposed as a proper driver flag.
109*0fca6ea1SDimitry Andric static cl::opt<PGOOptions::ColdFuncOpt> ClPGOColdFuncAttr(
110*0fca6ea1SDimitry Andric     "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
111*0fca6ea1SDimitry Andric     cl::desc(
112*0fca6ea1SDimitry Andric         "Function attribute to apply to cold functions as determined by PGO"),
113*0fca6ea1SDimitry Andric     cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default",
114*0fca6ea1SDimitry Andric                           "Default (no attribute)"),
115*0fca6ea1SDimitry Andric                clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize",
116*0fca6ea1SDimitry Andric                           "Mark cold functions with optsize."),
117*0fca6ea1SDimitry Andric                clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize",
118*0fca6ea1SDimitry Andric                           "Mark cold functions with minsize."),
119*0fca6ea1SDimitry Andric                clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone",
120*0fca6ea1SDimitry Andric                           "Mark cold functions with optnone.")));
1215f757f3fSDimitry Andric 
1225f757f3fSDimitry Andric extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind> ProfileCorrelate;
1235f757f3fSDimitry Andric } // namespace llvm
1240eae32dcSDimitry Andric 
1250b57cec5SDimitry Andric namespace {
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric // Default filename used for profile generation.
1280eae32dcSDimitry Andric std::string getDefaultProfileGenName() {
1295f757f3fSDimitry Andric   return DebugInfoCorrelate || ProfileCorrelate != InstrProfCorrelator::NONE
1305f757f3fSDimitry Andric              ? "default_%m.proflite"
1315f757f3fSDimitry Andric              : "default_%m.profraw";
1320eae32dcSDimitry Andric }
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric class EmitAssemblyHelper {
1350b57cec5SDimitry Andric   DiagnosticsEngine &Diags;
1360b57cec5SDimitry Andric   const HeaderSearchOptions &HSOpts;
1370b57cec5SDimitry Andric   const CodeGenOptions &CodeGenOpts;
1380b57cec5SDimitry Andric   const clang::TargetOptions &TargetOpts;
1390b57cec5SDimitry Andric   const LangOptions &LangOpts;
1405f757f3fSDimitry Andric   llvm::Module *TheModule;
14106c3fb27SDimitry Andric   IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric   Timer CodeGenerationTime;
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   std::unique_ptr<raw_pwrite_stream> OS;
1460b57cec5SDimitry Andric 
14781ad6265SDimitry Andric   Triple TargetTriple;
14881ad6265SDimitry Andric 
1490b57cec5SDimitry Andric   TargetIRAnalysis getTargetIRAnalysis() const {
1500b57cec5SDimitry Andric     if (TM)
1510b57cec5SDimitry Andric       return TM->getTargetIRAnalysis();
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric     return TargetIRAnalysis();
1540b57cec5SDimitry Andric   }
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   /// Generates the TargetMachine.
1570b57cec5SDimitry Andric   /// Leaves TM unchanged if it is unable to create the target machine.
1580b57cec5SDimitry Andric   /// Some of our clang tests specify triples which are not built
1590b57cec5SDimitry Andric   /// into clang. This is okay because these tests check the generated
1600b57cec5SDimitry Andric   /// IR, and they require DataLayout which depends on the triple.
1610b57cec5SDimitry Andric   /// In this case, we allow this method to fail and not report an error.
1620b57cec5SDimitry Andric   /// When MustCreateTM is used, we print an error if we are unable to load
1630b57cec5SDimitry Andric   /// the requested target.
1640b57cec5SDimitry Andric   void CreateTargetMachine(bool MustCreateTM);
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   /// Add passes necessary to emit assembly or LLVM IR.
1670b57cec5SDimitry Andric   ///
1680b57cec5SDimitry Andric   /// \return True on success.
1690b57cec5SDimitry Andric   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
1700b57cec5SDimitry Andric                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
1730b57cec5SDimitry Andric     std::error_code EC;
174a7dea167SDimitry Andric     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
175a7dea167SDimitry Andric                                                      llvm::sys::fs::OF_None);
1760b57cec5SDimitry Andric     if (EC) {
1770b57cec5SDimitry Andric       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
1780b57cec5SDimitry Andric       F.reset();
1790b57cec5SDimitry Andric     }
1800b57cec5SDimitry Andric     return F;
1810b57cec5SDimitry Andric   }
1820b57cec5SDimitry Andric 
1835f757f3fSDimitry Andric   void RunOptimizationPipeline(
1845f757f3fSDimitry Andric       BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1855f757f3fSDimitry Andric       std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
186349cc55cSDimitry Andric   void RunCodegenPipeline(BackendAction Action,
187349cc55cSDimitry Andric                           std::unique_ptr<raw_pwrite_stream> &OS,
188349cc55cSDimitry Andric                           std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
189349cc55cSDimitry Andric 
19081ad6265SDimitry Andric   /// Check whether we should emit a module summary for regular LTO.
19181ad6265SDimitry Andric   /// The module summary should be emitted by default for regular LTO
19281ad6265SDimitry Andric   /// except for ld64 targets.
19381ad6265SDimitry Andric   ///
19481ad6265SDimitry Andric   /// \return True if the module summary should be emitted.
19581ad6265SDimitry Andric   bool shouldEmitRegularLTOSummary() const {
19681ad6265SDimitry Andric     return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
19781ad6265SDimitry Andric            TargetTriple.getVendor() != llvm::Triple::Apple;
19881ad6265SDimitry Andric   }
19981ad6265SDimitry Andric 
200439352acSDimitry Andric   /// Check whether we should emit a flag for UnifiedLTO.
201439352acSDimitry Andric   /// The UnifiedLTO module flag should be set when UnifiedLTO is enabled for
202439352acSDimitry Andric   /// ThinLTO or Full LTO with module summaries.
203439352acSDimitry Andric   bool shouldEmitUnifiedLTOModueFlag() const {
204439352acSDimitry Andric     return CodeGenOpts.UnifiedLTO &&
205439352acSDimitry Andric            (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
206439352acSDimitry Andric   }
207439352acSDimitry Andric 
2080b57cec5SDimitry Andric public:
2090b57cec5SDimitry Andric   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
2100b57cec5SDimitry Andric                      const HeaderSearchOptions &HeaderSearchOpts,
2110b57cec5SDimitry Andric                      const CodeGenOptions &CGOpts,
2120b57cec5SDimitry Andric                      const clang::TargetOptions &TOpts,
2135f757f3fSDimitry Andric                      const LangOptions &LOpts, llvm::Module *M,
21406c3fb27SDimitry Andric                      IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
2150b57cec5SDimitry Andric       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
21606c3fb27SDimitry Andric         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), VFS(std::move(VFS)),
21781ad6265SDimitry Andric         CodeGenerationTime("codegen", "Code Generation Time"),
21881ad6265SDimitry Andric         TargetTriple(TheModule->getTargetTriple()) {}
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric   ~EmitAssemblyHelper() {
2210b57cec5SDimitry Andric     if (CodeGenOpts.DisableFree)
2220b57cec5SDimitry Andric       BuryPointer(std::move(TM));
2230b57cec5SDimitry Andric   }
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   std::unique_ptr<TargetMachine> TM;
2260b57cec5SDimitry Andric 
22781ad6265SDimitry Andric   // Emit output using the new pass manager for the optimization pipeline.
2285f757f3fSDimitry Andric   void EmitAssembly(BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
2295f757f3fSDimitry Andric                     BackendConsumer *BC);
2300b57cec5SDimitry Andric };
2315f757f3fSDimitry Andric } // namespace
2320b57cec5SDimitry Andric 
233a7dea167SDimitry Andric static SanitizerCoverageOptions
234a7dea167SDimitry Andric getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
2350b57cec5SDimitry Andric   SanitizerCoverageOptions Opts;
2360b57cec5SDimitry Andric   Opts.CoverageType =
2370b57cec5SDimitry Andric       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
2380b57cec5SDimitry Andric   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
2390b57cec5SDimitry Andric   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
2400b57cec5SDimitry Andric   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
2410b57cec5SDimitry Andric   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
2420b57cec5SDimitry Andric   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
2430b57cec5SDimitry Andric   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
2440b57cec5SDimitry Andric   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
2450b57cec5SDimitry Andric   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
2460b57cec5SDimitry Andric   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
2470b57cec5SDimitry Andric   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
2485ffd83dbSDimitry Andric   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
2490b57cec5SDimitry Andric   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
2500b57cec5SDimitry Andric   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
251349cc55cSDimitry Andric   Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
252349cc55cSDimitry Andric   Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
253bdd1243dSDimitry Andric   Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
254bdd1243dSDimitry Andric   return Opts;
255bdd1243dSDimitry Andric }
256bdd1243dSDimitry Andric 
257bdd1243dSDimitry Andric static SanitizerBinaryMetadataOptions
258bdd1243dSDimitry Andric getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts) {
259bdd1243dSDimitry Andric   SanitizerBinaryMetadataOptions Opts;
260bdd1243dSDimitry Andric   Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
261bdd1243dSDimitry Andric   Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
262bdd1243dSDimitry Andric   Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
263a7dea167SDimitry Andric   return Opts;
264a7dea167SDimitry Andric }
265a7dea167SDimitry Andric 
2660b57cec5SDimitry Andric // Check if ASan should use GC-friendly instrumentation for globals.
2670b57cec5SDimitry Andric // First of all, there is no point if -fdata-sections is off (expect for MachO,
2680b57cec5SDimitry Andric // where this is not a factor). Also, on ELF this feature requires an assembler
2690b57cec5SDimitry Andric // extension that only works with -integrated-as at the moment.
2700b57cec5SDimitry Andric static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
2710b57cec5SDimitry Andric   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
2720b57cec5SDimitry Andric     return false;
2730b57cec5SDimitry Andric   switch (T.getObjectFormat()) {
2740b57cec5SDimitry Andric   case Triple::MachO:
2750b57cec5SDimitry Andric   case Triple::COFF:
2760b57cec5SDimitry Andric     return true;
2770b57cec5SDimitry Andric   case Triple::ELF:
27881ad6265SDimitry Andric     return !CGOpts.DisableIntegratedAS;
279e8d8bef9SDimitry Andric   case Triple::GOFF:
280e8d8bef9SDimitry Andric     llvm::report_fatal_error("ASan not implemented for GOFF");
281a7dea167SDimitry Andric   case Triple::XCOFF:
282a7dea167SDimitry Andric     llvm::report_fatal_error("ASan not implemented for XCOFF.");
283a7dea167SDimitry Andric   case Triple::Wasm:
28481ad6265SDimitry Andric   case Triple::DXContainer:
28581ad6265SDimitry Andric   case Triple::SPIRV:
286a7dea167SDimitry Andric   case Triple::UnknownObjectFormat:
287a7dea167SDimitry Andric     break;
2880b57cec5SDimitry Andric   }
289a7dea167SDimitry Andric   return false;
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric 
292bdd1243dSDimitry Andric static std::optional<llvm::CodeModel::Model>
2930b57cec5SDimitry Andric getCodeModel(const CodeGenOptions &CodeGenOpts) {
2940b57cec5SDimitry Andric   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
2950b57cec5SDimitry Andric                            .Case("tiny", llvm::CodeModel::Tiny)
2960b57cec5SDimitry Andric                            .Case("small", llvm::CodeModel::Small)
2970b57cec5SDimitry Andric                            .Case("kernel", llvm::CodeModel::Kernel)
2980b57cec5SDimitry Andric                            .Case("medium", llvm::CodeModel::Medium)
2990b57cec5SDimitry Andric                            .Case("large", llvm::CodeModel::Large)
3000b57cec5SDimitry Andric                            .Case("default", ~1u)
3010b57cec5SDimitry Andric                            .Default(~0u);
3020b57cec5SDimitry Andric   assert(CodeModel != ~0u && "invalid code model!");
3030b57cec5SDimitry Andric   if (CodeModel == ~1u)
304bdd1243dSDimitry Andric     return std::nullopt;
3050b57cec5SDimitry Andric   return static_cast<llvm::CodeModel::Model>(CodeModel);
3060b57cec5SDimitry Andric }
3070b57cec5SDimitry Andric 
308480093f4SDimitry Andric static CodeGenFileType getCodeGenFileType(BackendAction Action) {
3090b57cec5SDimitry Andric   if (Action == Backend_EmitObj)
3105f757f3fSDimitry Andric     return CodeGenFileType::ObjectFile;
3110b57cec5SDimitry Andric   else if (Action == Backend_EmitMCNull)
3125f757f3fSDimitry Andric     return CodeGenFileType::Null;
3130b57cec5SDimitry Andric   else {
3140b57cec5SDimitry Andric     assert(Action == Backend_EmitAssembly && "Invalid action!");
3155f757f3fSDimitry Andric     return CodeGenFileType::AssemblyFile;
3160b57cec5SDimitry Andric   }
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
319349cc55cSDimitry Andric static bool actionRequiresCodeGen(BackendAction Action) {
320349cc55cSDimitry Andric   return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
321349cc55cSDimitry Andric          Action != Backend_EmitLL;
322349cc55cSDimitry Andric }
323349cc55cSDimitry Andric 
324e8d8bef9SDimitry Andric static bool initTargetOptions(DiagnosticsEngine &Diags,
3255ffd83dbSDimitry Andric                               llvm::TargetOptions &Options,
3260b57cec5SDimitry Andric                               const CodeGenOptions &CodeGenOpts,
3270b57cec5SDimitry Andric                               const clang::TargetOptions &TargetOpts,
3280b57cec5SDimitry Andric                               const LangOptions &LangOpts,
3290b57cec5SDimitry Andric                               const HeaderSearchOptions &HSOpts) {
330e8d8bef9SDimitry Andric   switch (LangOpts.getThreadModel()) {
331e8d8bef9SDimitry Andric   case LangOptions::ThreadModelKind::POSIX:
332e8d8bef9SDimitry Andric     Options.ThreadModel = llvm::ThreadModel::POSIX;
333e8d8bef9SDimitry Andric     break;
334e8d8bef9SDimitry Andric   case LangOptions::ThreadModelKind::Single:
335e8d8bef9SDimitry Andric     Options.ThreadModel = llvm::ThreadModel::Single;
336e8d8bef9SDimitry Andric     break;
337e8d8bef9SDimitry Andric   }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   // Set float ABI type.
3400b57cec5SDimitry Andric   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
3410b57cec5SDimitry Andric           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
3420b57cec5SDimitry Andric          "Invalid Floating Point ABI!");
3430b57cec5SDimitry Andric   Options.FloatABIType =
3440b57cec5SDimitry Andric       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
3450b57cec5SDimitry Andric           .Case("soft", llvm::FloatABI::Soft)
3460b57cec5SDimitry Andric           .Case("softfp", llvm::FloatABI::Soft)
3470b57cec5SDimitry Andric           .Case("hard", llvm::FloatABI::Hard)
3480b57cec5SDimitry Andric           .Default(llvm::FloatABI::Default);
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   // Set FP fusion mode.
3510b57cec5SDimitry Andric   switch (LangOpts.getDefaultFPContractMode()) {
3525ffd83dbSDimitry Andric   case LangOptions::FPM_Off:
3530b57cec5SDimitry Andric     // Preserve any contraction performed by the front-end.  (Strict performs
3540b57cec5SDimitry Andric     // splitting of the muladd intrinsic in the backend.)
3550b57cec5SDimitry Andric     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
3560b57cec5SDimitry Andric     break;
3575ffd83dbSDimitry Andric   case LangOptions::FPM_On:
358e8d8bef9SDimitry Andric   case LangOptions::FPM_FastHonorPragmas:
3590b57cec5SDimitry Andric     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
3600b57cec5SDimitry Andric     break;
3615ffd83dbSDimitry Andric   case LangOptions::FPM_Fast:
3620b57cec5SDimitry Andric     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
3630b57cec5SDimitry Andric     break;
3640b57cec5SDimitry Andric   }
3650b57cec5SDimitry Andric 
366e8d8bef9SDimitry Andric   Options.BinutilsVersion =
367e8d8bef9SDimitry Andric       llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
3680b57cec5SDimitry Andric   Options.UseInitArray = CodeGenOpts.UseInitArray;
3690b57cec5SDimitry Andric   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   // Set EABI version.
3720b57cec5SDimitry Andric   Options.EABIVersion = TargetOpts.EABIVersion;
3730b57cec5SDimitry Andric 
374e8d8bef9SDimitry Andric   if (LangOpts.hasSjLjExceptions())
3750b57cec5SDimitry Andric     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
376e8d8bef9SDimitry Andric   if (LangOpts.hasSEHExceptions())
3770b57cec5SDimitry Andric     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
378e8d8bef9SDimitry Andric   if (LangOpts.hasDWARFExceptions())
3790b57cec5SDimitry Andric     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
380e8d8bef9SDimitry Andric   if (LangOpts.hasWasmExceptions())
381a7dea167SDimitry Andric     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
3820b57cec5SDimitry Andric 
3835ffd83dbSDimitry Andric   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
3845ffd83dbSDimitry Andric   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
3850b57cec5SDimitry Andric   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
386bdd1243dSDimitry Andric   Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
387bdd1243dSDimitry Andric                          LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
388bdd1243dSDimitry Andric                          (LangOpts.getDefaultFPContractMode() ==
389bdd1243dSDimitry Andric                               LangOptions::FPModeKind::FPM_Fast ||
390bdd1243dSDimitry Andric                           LangOpts.getDefaultFPContractMode() ==
391bdd1243dSDimitry Andric                               LangOptions::FPModeKind::FPM_FastHonorPragmas);
392349cc55cSDimitry Andric   Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
3935ffd83dbSDimitry Andric 
394*0fca6ea1SDimitry Andric   Options.BBAddrMap = CodeGenOpts.BBAddrMap;
3955ffd83dbSDimitry Andric   Options.BBSections =
3965ffd83dbSDimitry Andric       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
3975ffd83dbSDimitry Andric           .Case("all", llvm::BasicBlockSection::All)
3985ffd83dbSDimitry Andric           .Case("labels", llvm::BasicBlockSection::Labels)
3995ffd83dbSDimitry Andric           .StartsWith("list=", llvm::BasicBlockSection::List)
4005ffd83dbSDimitry Andric           .Case("none", llvm::BasicBlockSection::None)
4015ffd83dbSDimitry Andric           .Default(llvm::BasicBlockSection::None);
4025ffd83dbSDimitry Andric 
4035ffd83dbSDimitry Andric   if (Options.BBSections == llvm::BasicBlockSection::List) {
4045ffd83dbSDimitry Andric     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
4055ffd83dbSDimitry Andric         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
406e8d8bef9SDimitry Andric     if (!MBOrErr) {
4075ffd83dbSDimitry Andric       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
4085ffd83dbSDimitry Andric           << MBOrErr.getError().message();
409e8d8bef9SDimitry Andric       return false;
410e8d8bef9SDimitry Andric     }
4115ffd83dbSDimitry Andric     Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
4125ffd83dbSDimitry Andric   }
4135ffd83dbSDimitry Andric 
414e8d8bef9SDimitry Andric   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
4150b57cec5SDimitry Andric   Options.FunctionSections = CodeGenOpts.FunctionSections;
4160b57cec5SDimitry Andric   Options.DataSections = CodeGenOpts.DataSections;
417fe6060f1SDimitry Andric   Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
4180b57cec5SDimitry Andric   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
4195ffd83dbSDimitry Andric   Options.UniqueBasicBlockSectionNames =
4205ffd83dbSDimitry Andric       CodeGenOpts.UniqueBasicBlockSectionNames;
421*0fca6ea1SDimitry Andric   Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
422480093f4SDimitry Andric   Options.TLSSize = CodeGenOpts.TLSSize;
423b3edf446SDimitry Andric   Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
4240b57cec5SDimitry Andric   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
4250b57cec5SDimitry Andric   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
4260b57cec5SDimitry Andric   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
427fe6060f1SDimitry Andric   Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
4280b57cec5SDimitry Andric   Options.EmitAddrsig = CodeGenOpts.Addrsig;
429480093f4SDimitry Andric   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
4305ffd83dbSDimitry Andric   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
43106c3fb27SDimitry Andric   Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
43206c3fb27SDimitry Andric   Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
433349cc55cSDimitry Andric   Options.LoopAlignment = CodeGenOpts.LoopAlignment;
43481ad6265SDimitry Andric   Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
43581ad6265SDimitry Andric   Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
43681ad6265SDimitry Andric   Options.Hotpatch = CodeGenOpts.HotPatch;
43781ad6265SDimitry Andric   Options.JMCInstrument = CodeGenOpts.JMCInstrument;
43806c3fb27SDimitry Andric   Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
439349cc55cSDimitry Andric 
440349cc55cSDimitry Andric   switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
441349cc55cSDimitry Andric   case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
442349cc55cSDimitry Andric     Options.SwiftAsyncFramePointer =
443349cc55cSDimitry Andric         SwiftAsyncFramePointerMode::DeploymentBased;
444349cc55cSDimitry Andric     break;
445349cc55cSDimitry Andric 
446349cc55cSDimitry Andric   case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
447349cc55cSDimitry Andric     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
448349cc55cSDimitry Andric     break;
449349cc55cSDimitry Andric 
450349cc55cSDimitry Andric   case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
451349cc55cSDimitry Andric     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
452349cc55cSDimitry Andric     break;
453349cc55cSDimitry Andric   }
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
45681ad6265SDimitry Andric   Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
45706c3fb27SDimitry Andric   Options.MCOptions.EmitCompactUnwindNonCanonical =
45806c3fb27SDimitry Andric       CodeGenOpts.EmitCompactUnwindNonCanonical;
4590b57cec5SDimitry Andric   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
4600b57cec5SDimitry Andric   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
46181ad6265SDimitry Andric   Options.MCOptions.MCUseDwarfDirectory =
46281ad6265SDimitry Andric       CodeGenOpts.NoDwarfDirectoryAsm
46381ad6265SDimitry Andric           ? llvm::MCTargetOptions::DisableDwarfDirectory
46481ad6265SDimitry Andric           : llvm::MCTargetOptions::EnableDwarfDirectory;
4650b57cec5SDimitry Andric   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
4660b57cec5SDimitry Andric   Options.MCOptions.MCIncrementalLinkerCompatible =
4670b57cec5SDimitry Andric       CodeGenOpts.IncrementalLinkerCompatible;
4680b57cec5SDimitry Andric   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
469a7dea167SDimitry Andric   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
4700b57cec5SDimitry Andric   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
471e8d8bef9SDimitry Andric   Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
4720b57cec5SDimitry Andric   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
473*0fca6ea1SDimitry Andric   Options.MCOptions.Crel = CodeGenOpts.Crel;
474*0fca6ea1SDimitry Andric   Options.MCOptions.X86RelaxRelocations = CodeGenOpts.RelaxELFRelocations;
475*0fca6ea1SDimitry Andric   Options.MCOptions.CompressDebugSections =
476*0fca6ea1SDimitry Andric       CodeGenOpts.getCompressDebugSections();
4770b57cec5SDimitry Andric   Options.MCOptions.ABIName = TargetOpts.ABI;
4780b57cec5SDimitry Andric   for (const auto &Entry : HSOpts.UserEntries)
4790b57cec5SDimitry Andric     if (!Entry.IsFramework &&
4800b57cec5SDimitry Andric         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
4810b57cec5SDimitry Andric          Entry.Group == frontend::IncludeDirGroup::Angled ||
4820b57cec5SDimitry Andric          Entry.Group == frontend::IncludeDirGroup::System))
4830b57cec5SDimitry Andric       Options.MCOptions.IASSearchPaths.push_back(
4840b57cec5SDimitry Andric           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
4855ffd83dbSDimitry Andric   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
4865ffd83dbSDimitry Andric   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
487bdd1243dSDimitry Andric   Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile;
4885f757f3fSDimitry Andric   Options.MCOptions.PPCUseFullRegisterNames =
4895f757f3fSDimitry Andric       CodeGenOpts.PPCUseFullRegisterNames;
49081ad6265SDimitry Andric   Options.MisExpect = CodeGenOpts.MisExpect;
491e8d8bef9SDimitry Andric 
492e8d8bef9SDimitry Andric   return true;
4930b57cec5SDimitry Andric }
494e8d8bef9SDimitry Andric 
495bdd1243dSDimitry Andric static std::optional<GCOVOptions>
496bdd1243dSDimitry Andric getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) {
49706c3fb27SDimitry Andric   if (CodeGenOpts.CoverageNotesFile.empty() &&
49806c3fb27SDimitry Andric       CodeGenOpts.CoverageDataFile.empty())
499bdd1243dSDimitry Andric     return std::nullopt;
5000b57cec5SDimitry Andric   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
5010b57cec5SDimitry Andric   // LLVM's -default-gcov-version flag is set to something invalid.
5020b57cec5SDimitry Andric   GCOVOptions Options;
50306c3fb27SDimitry Andric   Options.EmitNotes = !CodeGenOpts.CoverageNotesFile.empty();
50406c3fb27SDimitry Andric   Options.EmitData = !CodeGenOpts.CoverageDataFile.empty();
5050b57cec5SDimitry Andric   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
5060b57cec5SDimitry Andric   Options.NoRedZone = CodeGenOpts.DisableRedZone;
5070b57cec5SDimitry Andric   Options.Filter = CodeGenOpts.ProfileFilterFiles;
5080b57cec5SDimitry Andric   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
509e8d8bef9SDimitry Andric   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
5100b57cec5SDimitry Andric   return Options;
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric 
513bdd1243dSDimitry Andric static std::optional<InstrProfOptions>
5140b57cec5SDimitry Andric getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
5150b57cec5SDimitry Andric                     const LangOptions &LangOpts) {
5160b57cec5SDimitry Andric   if (!CodeGenOpts.hasProfileClangInstr())
517bdd1243dSDimitry Andric     return std::nullopt;
5180b57cec5SDimitry Andric   InstrProfOptions Options;
5190b57cec5SDimitry Andric   Options.NoRedZone = CodeGenOpts.DisableRedZone;
5200b57cec5SDimitry Andric   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
521e8d8bef9SDimitry Andric   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
5220b57cec5SDimitry Andric   return Options;
5230b57cec5SDimitry Andric }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
5260b57cec5SDimitry Andric   SmallVector<const char *, 16> BackendArgs;
5270b57cec5SDimitry Andric   BackendArgs.push_back("clang"); // Fake program name.
5280b57cec5SDimitry Andric   if (!CodeGenOpts.DebugPass.empty()) {
5290b57cec5SDimitry Andric     BackendArgs.push_back("-debug-pass");
5300b57cec5SDimitry Andric     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
5310b57cec5SDimitry Andric   }
5320b57cec5SDimitry Andric   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
5330b57cec5SDimitry Andric     BackendArgs.push_back("-limit-float-precision");
5340b57cec5SDimitry Andric     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
5350b57cec5SDimitry Andric   }
536fe6060f1SDimitry Andric   // Check for the default "clang" invocation that won't set any cl::opt values.
537fe6060f1SDimitry Andric   // Skip trying to parse the command line invocation to avoid the issues
538fe6060f1SDimitry Andric   // described below.
539fe6060f1SDimitry Andric   if (BackendArgs.size() == 1)
540fe6060f1SDimitry Andric     return;
5410b57cec5SDimitry Andric   BackendArgs.push_back(nullptr);
542fe6060f1SDimitry Andric   // FIXME: The command line parser below is not thread-safe and shares a global
543fe6060f1SDimitry Andric   // state, so this call might crash or overwrite the options of another Clang
544fe6060f1SDimitry Andric   // instance in the same process.
5450b57cec5SDimitry Andric   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
5460b57cec5SDimitry Andric                                     BackendArgs.data());
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
5500b57cec5SDimitry Andric   // Create the TargetMachine for generating code.
5510b57cec5SDimitry Andric   std::string Error;
5520b57cec5SDimitry Andric   std::string Triple = TheModule->getTargetTriple();
5530b57cec5SDimitry Andric   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
5540b57cec5SDimitry Andric   if (!TheTarget) {
5550b57cec5SDimitry Andric     if (MustCreateTM)
5560b57cec5SDimitry Andric       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
5570b57cec5SDimitry Andric     return;
5580b57cec5SDimitry Andric   }
5590b57cec5SDimitry Andric 
560bdd1243dSDimitry Andric   std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
5610b57cec5SDimitry Andric   std::string FeaturesStr =
5620b57cec5SDimitry Andric       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
5630b57cec5SDimitry Andric   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
5645f757f3fSDimitry Andric   std::optional<CodeGenOptLevel> OptLevelOrNone =
565bdd1243dSDimitry Andric       CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
566bdd1243dSDimitry Andric   assert(OptLevelOrNone && "Invalid optimization level!");
5675f757f3fSDimitry Andric   CodeGenOptLevel OptLevel = *OptLevelOrNone;
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   llvm::TargetOptions Options;
570e8d8bef9SDimitry Andric   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
571e8d8bef9SDimitry Andric                          HSOpts))
572e8d8bef9SDimitry Andric     return;
5730b57cec5SDimitry Andric   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
5740b57cec5SDimitry Andric                                           Options, RM, CM, OptLevel));
5755f757f3fSDimitry Andric   TM->setLargeDataThreshold(CodeGenOpts.LargeDataThreshold);
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
5790b57cec5SDimitry Andric                                        BackendAction Action,
5800b57cec5SDimitry Andric                                        raw_pwrite_stream &OS,
5810b57cec5SDimitry Andric                                        raw_pwrite_stream *DwoOS) {
5820b57cec5SDimitry Andric   // Add LibraryInfo.
5830b57cec5SDimitry Andric   std::unique_ptr<TargetLibraryInfoImpl> TLII(
5845f757f3fSDimitry Andric       llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
5850b57cec5SDimitry Andric   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric   // Normal mode, emit a .s or .o file by running the code generator. Note,
5880b57cec5SDimitry Andric   // this also adds codegenerator level optimization passes.
589480093f4SDimitry Andric   CodeGenFileType CGFT = getCodeGenFileType(Action);
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
5920b57cec5SDimitry Andric   // "codegen" passes so that it isn't run multiple times when there is
5930b57cec5SDimitry Andric   // inlining happening.
5940b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0)
5950b57cec5SDimitry Andric     CodeGenPasses.add(createObjCARCContractPass());
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
5980b57cec5SDimitry Andric                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
5990b57cec5SDimitry Andric     Diags.Report(diag::err_fe_unable_to_interface_with_target);
6000b57cec5SDimitry Andric     return false;
6010b57cec5SDimitry Andric   }
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   return true;
6040b57cec5SDimitry Andric }
6050b57cec5SDimitry Andric 
606349cc55cSDimitry Andric static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
6070b57cec5SDimitry Andric   switch (Opts.OptimizationLevel) {
6080b57cec5SDimitry Andric   default:
6090b57cec5SDimitry Andric     llvm_unreachable("Invalid optimization level!");
6100b57cec5SDimitry Andric 
611e8d8bef9SDimitry Andric   case 0:
612349cc55cSDimitry Andric     return OptimizationLevel::O0;
613e8d8bef9SDimitry Andric 
6140b57cec5SDimitry Andric   case 1:
615349cc55cSDimitry Andric     return OptimizationLevel::O1;
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric   case 2:
6180b57cec5SDimitry Andric     switch (Opts.OptimizeSize) {
6190b57cec5SDimitry Andric     default:
6200b57cec5SDimitry Andric       llvm_unreachable("Invalid optimization level for size!");
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric     case 0:
623349cc55cSDimitry Andric       return OptimizationLevel::O2;
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric     case 1:
626349cc55cSDimitry Andric       return OptimizationLevel::Os;
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric     case 2:
629349cc55cSDimitry Andric       return OptimizationLevel::Oz;
6300b57cec5SDimitry Andric     }
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   case 3:
633349cc55cSDimitry Andric     return OptimizationLevel::O3;
6340b57cec5SDimitry Andric   }
6350b57cec5SDimitry Andric }
6360b57cec5SDimitry Andric 
637bdd1243dSDimitry Andric static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts,
638bdd1243dSDimitry Andric                         PassBuilder &PB) {
639bdd1243dSDimitry Andric   // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
640bdd1243dSDimitry Andric   if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
64106c3fb27SDimitry Andric       TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
642bdd1243dSDimitry Andric     return;
643bdd1243dSDimitry Andric 
644bdd1243dSDimitry Andric   // Ensure we lower KCFI operand bundles with -O0.
645bdd1243dSDimitry Andric   PB.registerOptimizerLastEPCallback(
646bdd1243dSDimitry Andric       [&](ModulePassManager &MPM, OptimizationLevel Level) {
647bdd1243dSDimitry Andric         if (Level == OptimizationLevel::O0 &&
648bdd1243dSDimitry Andric             LangOpts.Sanitize.has(SanitizerKind::KCFI))
649bdd1243dSDimitry Andric           MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
650bdd1243dSDimitry Andric       });
651bdd1243dSDimitry Andric 
652bdd1243dSDimitry Andric   // When optimizations are requested, run KCIFPass after InstCombine to
653bdd1243dSDimitry Andric   // avoid unnecessary checks.
654bdd1243dSDimitry Andric   PB.registerPeepholeEPCallback(
655bdd1243dSDimitry Andric       [&](FunctionPassManager &FPM, OptimizationLevel Level) {
656bdd1243dSDimitry Andric         if (Level != OptimizationLevel::O0 &&
657bdd1243dSDimitry Andric             LangOpts.Sanitize.has(SanitizerKind::KCFI))
658bdd1243dSDimitry Andric           FPM.addPass(KCFIPass());
659bdd1243dSDimitry Andric       });
660bdd1243dSDimitry Andric }
661bdd1243dSDimitry Andric 
662fe6060f1SDimitry Andric static void addSanitizers(const Triple &TargetTriple,
663fe6060f1SDimitry Andric                           const CodeGenOptions &CodeGenOpts,
664fe6060f1SDimitry Andric                           const LangOptions &LangOpts, PassBuilder &PB) {
665bdd1243dSDimitry Andric   auto SanitizersCallback = [&](ModulePassManager &MPM,
666349cc55cSDimitry Andric                                 OptimizationLevel Level) {
667fe6060f1SDimitry Andric     if (CodeGenOpts.hasSanitizeCoverage()) {
668fe6060f1SDimitry Andric       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
669bdd1243dSDimitry Andric       MPM.addPass(SanitizerCoveragePass(
670fe6060f1SDimitry Andric           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
671fe6060f1SDimitry Andric           CodeGenOpts.SanitizeCoverageIgnorelistFiles));
672fe6060f1SDimitry Andric     }
673fe6060f1SDimitry Andric 
674bdd1243dSDimitry Andric     if (CodeGenOpts.hasSanitizeBinaryMetadata()) {
675bdd1243dSDimitry Andric       MPM.addPass(SanitizerBinaryMetadataPass(
67606c3fb27SDimitry Andric           getSanitizerBinaryMetadataOptions(CodeGenOpts),
67706c3fb27SDimitry Andric           CodeGenOpts.SanitizeMetadataIgnorelistFiles));
678bdd1243dSDimitry Andric     }
679bdd1243dSDimitry Andric 
680fe6060f1SDimitry Andric     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
681fe6060f1SDimitry Andric       if (LangOpts.Sanitize.has(Mask)) {
682fe6060f1SDimitry Andric         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
683fe6060f1SDimitry Andric         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
684fe6060f1SDimitry Andric 
68504eeddc0SDimitry Andric         MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
68604eeddc0SDimitry Andric                                        CodeGenOpts.SanitizeMemoryParamRetval);
687bdd1243dSDimitry Andric         MPM.addPass(MemorySanitizerPass(options));
688349cc55cSDimitry Andric         if (Level != OptimizationLevel::O0) {
689bdd1243dSDimitry Andric           // MemorySanitizer inserts complex instrumentation that mostly follows
690bdd1243dSDimitry Andric           // the logic of the original code, but operates on "shadow" values. It
691bdd1243dSDimitry Andric           // can benefit from re-running some general purpose optimization
692bdd1243dSDimitry Andric           // passes.
6935f757f3fSDimitry Andric           MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
694bdd1243dSDimitry Andric           FunctionPassManager FPM;
695bdd1243dSDimitry Andric           FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
696bdd1243dSDimitry Andric           FPM.addPass(InstCombinePass());
697bdd1243dSDimitry Andric           FPM.addPass(JumpThreadingPass());
698bdd1243dSDimitry Andric           FPM.addPass(GVNPass());
699bdd1243dSDimitry Andric           FPM.addPass(InstCombinePass());
700fe6060f1SDimitry Andric           MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
701fe6060f1SDimitry Andric         }
702bdd1243dSDimitry Andric       }
703fe6060f1SDimitry Andric     };
704fe6060f1SDimitry Andric     MSanPass(SanitizerKind::Memory, false);
705fe6060f1SDimitry Andric     MSanPass(SanitizerKind::KernelMemory, true);
706fe6060f1SDimitry Andric 
707fe6060f1SDimitry Andric     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
708349cc55cSDimitry Andric       MPM.addPass(ModuleThreadSanitizerPass());
709fe6060f1SDimitry Andric       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
710fe6060f1SDimitry Andric     }
711fe6060f1SDimitry Andric 
712*0fca6ea1SDimitry Andric     if (LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
713*0fca6ea1SDimitry Andric       MPM.addPass(NumericalStabilitySanitizerPass());
714*0fca6ea1SDimitry Andric 
715fe6060f1SDimitry Andric     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
716fe6060f1SDimitry Andric       if (LangOpts.Sanitize.has(Mask)) {
717349cc55cSDimitry Andric         bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
718fe6060f1SDimitry Andric         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
719fe6060f1SDimitry Andric         llvm::AsanDtorKind DestructorKind =
720fe6060f1SDimitry Andric             CodeGenOpts.getSanitizeAddressDtor();
721349cc55cSDimitry Andric         AddressSanitizerOptions Opts;
722349cc55cSDimitry Andric         Opts.CompileKernel = CompileKernel;
723349cc55cSDimitry Andric         Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
724349cc55cSDimitry Andric         Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
725349cc55cSDimitry Andric         Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
726bdd1243dSDimitry Andric         MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
727bdd1243dSDimitry Andric                                          DestructorKind));
728fe6060f1SDimitry Andric       }
729fe6060f1SDimitry Andric     };
730fe6060f1SDimitry Andric     ASanPass(SanitizerKind::Address, false);
731fe6060f1SDimitry Andric     ASanPass(SanitizerKind::KernelAddress, true);
732fe6060f1SDimitry Andric 
733fe6060f1SDimitry Andric     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
734fe6060f1SDimitry Andric       if (LangOpts.Sanitize.has(Mask)) {
735fe6060f1SDimitry Andric         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
736fe6060f1SDimitry Andric         MPM.addPass(HWAddressSanitizerPass(
737349cc55cSDimitry Andric             {CompileKernel, Recover,
738349cc55cSDimitry Andric              /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
739fe6060f1SDimitry Andric       }
740fe6060f1SDimitry Andric     };
741fe6060f1SDimitry Andric     HWASanPass(SanitizerKind::HWAddress, false);
742fe6060f1SDimitry Andric     HWASanPass(SanitizerKind::KernelHWAddress, true);
743fe6060f1SDimitry Andric 
744fe6060f1SDimitry Andric     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
745fe6060f1SDimitry Andric       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
746fe6060f1SDimitry Andric     }
747bdd1243dSDimitry Andric   };
748bdd1243dSDimitry Andric   if (ClSanitizeOnOptimizerEarlyEP) {
749bdd1243dSDimitry Andric     PB.registerOptimizerEarlyEPCallback(
750bdd1243dSDimitry Andric         [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level) {
751bdd1243dSDimitry Andric           ModulePassManager NewMPM;
752bdd1243dSDimitry Andric           SanitizersCallback(NewMPM, Level);
753bdd1243dSDimitry Andric           if (!NewMPM.isEmpty()) {
754bdd1243dSDimitry Andric             // Sanitizers can abandon<GlobalsAA>.
7555f757f3fSDimitry Andric             NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
756bdd1243dSDimitry Andric             MPM.addPass(std::move(NewMPM));
757bdd1243dSDimitry Andric           }
758fe6060f1SDimitry Andric         });
759bdd1243dSDimitry Andric   } else {
760bdd1243dSDimitry Andric     // LastEP does not need GlobalsAA.
761bdd1243dSDimitry Andric     PB.registerOptimizerLastEPCallback(SanitizersCallback);
762bdd1243dSDimitry Andric   }
763*0fca6ea1SDimitry Andric 
764*0fca6ea1SDimitry Andric   if (LowerAllowCheckPass::IsRequested()) {
765*0fca6ea1SDimitry Andric     // We can optimize after inliner, and PGO profile matching. The hook below
766*0fca6ea1SDimitry Andric     // is called at the end `buildFunctionSimplificationPipeline`, which called
767*0fca6ea1SDimitry Andric     // from `buildInlinerPipeline`, which called after profile matching.
768*0fca6ea1SDimitry Andric     PB.registerScalarOptimizerLateEPCallback(
769*0fca6ea1SDimitry Andric         [](FunctionPassManager &FPM, OptimizationLevel Level) {
770*0fca6ea1SDimitry Andric           FPM.addPass(LowerAllowCheckPass());
771*0fca6ea1SDimitry Andric         });
772*0fca6ea1SDimitry Andric   }
773fe6060f1SDimitry Andric }
774fe6060f1SDimitry Andric 
775349cc55cSDimitry Andric void EmitAssemblyHelper::RunOptimizationPipeline(
776349cc55cSDimitry Andric     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
7775f757f3fSDimitry Andric     std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
778bdd1243dSDimitry Andric   std::optional<PGOOptions> PGOOpt;
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileIRInstr())
7810b57cec5SDimitry Andric     // -fprofile-generate.
78206c3fb27SDimitry Andric     PGOOpt = PGOOptions(
78306c3fb27SDimitry Andric         CodeGenOpts.InstrProfileOutput.empty() ? getDefaultProfileGenName()
7840b57cec5SDimitry Andric                                                : CodeGenOpts.InstrProfileOutput,
78506c3fb27SDimitry Andric         "", "", CodeGenOpts.MemoryProfileUsePath, nullptr, PGOOptions::IRInstr,
786*0fca6ea1SDimitry Andric         PGOOptions::NoCSAction, ClPGOColdFuncAttr,
787*0fca6ea1SDimitry Andric         CodeGenOpts.DebugInfoForProfiling,
7885f757f3fSDimitry Andric         /*PseudoProbeForProfiling=*/false, CodeGenOpts.AtomicProfileUpdate);
7890b57cec5SDimitry Andric   else if (CodeGenOpts.hasProfileIRUse()) {
7900b57cec5SDimitry Andric     // -fprofile-use.
7910b57cec5SDimitry Andric     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
7920b57cec5SDimitry Andric                                                     : PGOOptions::NoCSAction;
793*0fca6ea1SDimitry Andric     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
794*0fca6ea1SDimitry Andric                         CodeGenOpts.ProfileRemappingFile,
795*0fca6ea1SDimitry Andric                         CodeGenOpts.MemoryProfileUsePath, VFS,
796*0fca6ea1SDimitry Andric                         PGOOptions::IRUse, CSAction, ClPGOColdFuncAttr,
797*0fca6ea1SDimitry Andric                         CodeGenOpts.DebugInfoForProfiling);
7980b57cec5SDimitry Andric   } else if (!CodeGenOpts.SampleProfileFile.empty())
7990b57cec5SDimitry Andric     // -fprofile-sample-use
800e8d8bef9SDimitry Andric     PGOOpt = PGOOptions(
801e8d8bef9SDimitry Andric         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
80206c3fb27SDimitry Andric         CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse,
803*0fca6ea1SDimitry Andric         PGOOptions::NoCSAction, ClPGOColdFuncAttr,
804*0fca6ea1SDimitry Andric         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
80506c3fb27SDimitry Andric   else if (!CodeGenOpts.MemoryProfileUsePath.empty())
80606c3fb27SDimitry Andric     // -fmemory-profile-use (without any of the above options)
80706c3fb27SDimitry Andric     PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, VFS,
80806c3fb27SDimitry Andric                         PGOOptions::NoAction, PGOOptions::NoCSAction,
809*0fca6ea1SDimitry Andric                         ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
810e8d8bef9SDimitry Andric   else if (CodeGenOpts.PseudoProbeForProfiling)
811e8d8bef9SDimitry Andric     // -fpseudo-probe-for-profiling
812*0fca6ea1SDimitry Andric     PGOOpt =
813*0fca6ea1SDimitry Andric         PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
81406c3fb27SDimitry Andric                    PGOOptions::NoAction, PGOOptions::NoCSAction,
815*0fca6ea1SDimitry Andric                    ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling, true);
8160b57cec5SDimitry Andric   else if (CodeGenOpts.DebugInfoForProfiling)
8170b57cec5SDimitry Andric     // -fdebug-info-for-profiling
81806c3fb27SDimitry Andric     PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
819*0fca6ea1SDimitry Andric                         PGOOptions::NoAction, PGOOptions::NoCSAction,
820*0fca6ea1SDimitry Andric                         ClPGOColdFuncAttr, true);
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric   // Check to see if we want to generate a CS profile.
8230b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileCSIRInstr()) {
8240b57cec5SDimitry Andric     assert(!CodeGenOpts.hasProfileCSIRUse() &&
8250b57cec5SDimitry Andric            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
8260b57cec5SDimitry Andric            "the same time");
82781ad6265SDimitry Andric     if (PGOOpt) {
8280b57cec5SDimitry Andric       assert(PGOOpt->Action != PGOOptions::IRInstr &&
8290b57cec5SDimitry Andric              PGOOpt->Action != PGOOptions::SampleUse &&
8300b57cec5SDimitry Andric              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
8310b57cec5SDimitry Andric              " pass");
8320b57cec5SDimitry Andric       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
8330eae32dcSDimitry Andric                                      ? getDefaultProfileGenName()
8340b57cec5SDimitry Andric                                      : CodeGenOpts.InstrProfileOutput;
8350b57cec5SDimitry Andric       PGOOpt->CSAction = PGOOptions::CSIRInstr;
8360b57cec5SDimitry Andric     } else
837*0fca6ea1SDimitry Andric       PGOOpt = PGOOptions("",
8380b57cec5SDimitry Andric                           CodeGenOpts.InstrProfileOutput.empty()
8390eae32dcSDimitry Andric                               ? getDefaultProfileGenName()
8400b57cec5SDimitry Andric                               : CodeGenOpts.InstrProfileOutput,
841*0fca6ea1SDimitry Andric                           "", /*MemoryProfile=*/"", nullptr,
842*0fca6ea1SDimitry Andric                           PGOOptions::NoAction, PGOOptions::CSIRInstr,
843*0fca6ea1SDimitry Andric                           ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
8440b57cec5SDimitry Andric   }
845349cc55cSDimitry Andric   if (TM)
846349cc55cSDimitry Andric     TM->setPGOOption(PGOOpt);
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   PipelineTuningOptions PTO;
8490b57cec5SDimitry Andric   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
8500b57cec5SDimitry Andric   // For historical reasons, loop interleaving is set to mirror setting for loop
8510b57cec5SDimitry Andric   // unrolling.
8520b57cec5SDimitry Andric   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
8530b57cec5SDimitry Andric   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
8540b57cec5SDimitry Andric   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
855e8d8bef9SDimitry Andric   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
8565ffd83dbSDimitry Andric   // Only enable CGProfilePass when using integrated assembler, since
8575ffd83dbSDimitry Andric   // non-integrated assemblers don't recognize .cgprofile section.
8585ffd83dbSDimitry Andric   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
85906c3fb27SDimitry Andric   PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
8600b57cec5SDimitry Andric 
861fe6060f1SDimitry Andric   LoopAnalysisManager LAM;
862fe6060f1SDimitry Andric   FunctionAnalysisManager FAM;
863fe6060f1SDimitry Andric   CGSCCAnalysisManager CGAM;
864fe6060f1SDimitry Andric   ModuleAnalysisManager MAM;
865fe6060f1SDimitry Andric 
866fe6060f1SDimitry Andric   bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
867a7dea167SDimitry Andric   PassInstrumentationCallbacks PIC;
868fe6060f1SDimitry Andric   PrintPassOptions PrintPassOpts;
869fe6060f1SDimitry Andric   PrintPassOpts.Indent = DebugPassStructure;
870fe6060f1SDimitry Andric   PrintPassOpts.SkipAnalyses = DebugPassStructure;
871bdd1243dSDimitry Andric   StandardInstrumentations SI(
872bdd1243dSDimitry Andric       TheModule->getContext(),
873bdd1243dSDimitry Andric       (CodeGenOpts.DebugPassManager || DebugPassStructure),
87406c3fb27SDimitry Andric       CodeGenOpts.VerifyEach, PrintPassOpts);
87506c3fb27SDimitry Andric   SI.registerCallbacks(PIC, &MAM);
876fe6060f1SDimitry Andric   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
8770b57cec5SDimitry Andric 
87806c3fb27SDimitry Andric   // Handle the assignment tracking feature options.
87906c3fb27SDimitry Andric   switch (CodeGenOpts.getAssignmentTrackingMode()) {
88006c3fb27SDimitry Andric   case CodeGenOptions::AssignmentTrackingOpts::Forced:
881bdd1243dSDimitry Andric     PB.registerPipelineStartEPCallback(
882bdd1243dSDimitry Andric         [&](ModulePassManager &MPM, OptimizationLevel Level) {
883bdd1243dSDimitry Andric           MPM.addPass(AssignmentTrackingPass());
884bdd1243dSDimitry Andric         });
88506c3fb27SDimitry Andric     break;
88606c3fb27SDimitry Andric   case CodeGenOptions::AssignmentTrackingOpts::Enabled:
88706c3fb27SDimitry Andric     // Disable assignment tracking in LTO builds for now as the performance
88806c3fb27SDimitry Andric     // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
88906c3fb27SDimitry Andric     if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
89006c3fb27SDimitry Andric         CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
89106c3fb27SDimitry Andric       PB.registerPipelineStartEPCallback(
89206c3fb27SDimitry Andric           [&](ModulePassManager &MPM, OptimizationLevel Level) {
89306c3fb27SDimitry Andric             // Only use assignment tracking if optimisations are enabled.
89406c3fb27SDimitry Andric             if (Level != OptimizationLevel::O0)
89506c3fb27SDimitry Andric               MPM.addPass(AssignmentTrackingPass());
89606c3fb27SDimitry Andric           });
89706c3fb27SDimitry Andric     }
89806c3fb27SDimitry Andric     break;
89906c3fb27SDimitry Andric   case CodeGenOptions::AssignmentTrackingOpts::Disabled:
90006c3fb27SDimitry Andric     break;
901bdd1243dSDimitry Andric   }
902bdd1243dSDimitry Andric 
903753f127fSDimitry Andric   // Enable verify-debuginfo-preserve-each for new PM.
904753f127fSDimitry Andric   DebugifyEachInstrumentation Debugify;
905753f127fSDimitry Andric   DebugInfoPerPass DebugInfoBeforePass;
906753f127fSDimitry Andric   if (CodeGenOpts.EnableDIPreservationVerify) {
907753f127fSDimitry Andric     Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
908753f127fSDimitry Andric     Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
909753f127fSDimitry Andric 
910753f127fSDimitry Andric     if (!CodeGenOpts.DIBugsReportFilePath.empty())
911753f127fSDimitry Andric       Debugify.setOrigDIVerifyBugsReportFilePath(
912753f127fSDimitry Andric           CodeGenOpts.DIBugsReportFilePath);
91306c3fb27SDimitry Andric     Debugify.registerCallbacks(PIC, MAM);
914753f127fSDimitry Andric   }
9150b57cec5SDimitry Andric   // Attempt to load pass plugins and register their callbacks with PB.
9160b57cec5SDimitry Andric   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
9170b57cec5SDimitry Andric     auto PassPlugin = PassPlugin::Load(PluginFN);
9180b57cec5SDimitry Andric     if (PassPlugin) {
9190b57cec5SDimitry Andric       PassPlugin->registerPassBuilderCallbacks(PB);
9200b57cec5SDimitry Andric     } else {
9210b57cec5SDimitry Andric       Diags.Report(diag::err_fe_unable_to_load_plugin)
9220b57cec5SDimitry Andric           << PluginFN << toString(PassPlugin.takeError());
9230b57cec5SDimitry Andric     }
9240b57cec5SDimitry Andric   }
925cb14a3feSDimitry Andric   for (const auto &PassCallback : CodeGenOpts.PassBuilderCallbacks)
9265f757f3fSDimitry Andric     PassCallback(PB);
927480093f4SDimitry Andric #define HANDLE_EXTENSION(Ext)                                                  \
928480093f4SDimitry Andric   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
929480093f4SDimitry Andric #include "llvm/Support/Extension.def"
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric   // Register the target library analysis directly and give it a customized
9320b57cec5SDimitry Andric   // preset TLI.
9330b57cec5SDimitry Andric   std::unique_ptr<TargetLibraryInfoImpl> TLII(
9345f757f3fSDimitry Andric       llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
9350b57cec5SDimitry Andric   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   // Register all the basic analyses with the managers.
9380b57cec5SDimitry Andric   PB.registerModuleAnalyses(MAM);
9390b57cec5SDimitry Andric   PB.registerCGSCCAnalyses(CGAM);
9400b57cec5SDimitry Andric   PB.registerFunctionAnalyses(FAM);
9410b57cec5SDimitry Andric   PB.registerLoopAnalyses(LAM);
9420b57cec5SDimitry Andric   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
9430b57cec5SDimitry Andric 
944fe6060f1SDimitry Andric   ModulePassManager MPM;
9455f757f3fSDimitry Andric   // Add a verifier pass, before any other passes, to catch CodeGen issues.
9465f757f3fSDimitry Andric   if (CodeGenOpts.VerifyModule)
9475f757f3fSDimitry Andric     MPM.addPass(VerifierPass());
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric   if (!CodeGenOpts.DisableLLVMPasses) {
9500b57cec5SDimitry Andric     // Map our optimization levels into one of the distinct levels used to
9510b57cec5SDimitry Andric     // configure the pipeline.
952349cc55cSDimitry Andric     OptimizationLevel Level = mapToLevel(CodeGenOpts);
9530b57cec5SDimitry Andric 
9545f757f3fSDimitry Andric     const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
9555f757f3fSDimitry Andric     const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
956e8d8bef9SDimitry Andric 
957e8d8bef9SDimitry Andric     if (LangOpts.ObjCAutoRefCount) {
958e8d8bef9SDimitry Andric       PB.registerPipelineStartEPCallback(
959349cc55cSDimitry Andric           [](ModulePassManager &MPM, OptimizationLevel Level) {
960349cc55cSDimitry Andric             if (Level != OptimizationLevel::O0)
961e8d8bef9SDimitry Andric               MPM.addPass(
962e8d8bef9SDimitry Andric                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
963e8d8bef9SDimitry Andric           });
964e8d8bef9SDimitry Andric       PB.registerPipelineEarlySimplificationEPCallback(
965349cc55cSDimitry Andric           [](ModulePassManager &MPM, OptimizationLevel Level) {
966349cc55cSDimitry Andric             if (Level != OptimizationLevel::O0)
967e8d8bef9SDimitry Andric               MPM.addPass(ObjCARCAPElimPass());
968e8d8bef9SDimitry Andric           });
969e8d8bef9SDimitry Andric       PB.registerScalarOptimizerLateEPCallback(
970349cc55cSDimitry Andric           [](FunctionPassManager &FPM, OptimizationLevel Level) {
971349cc55cSDimitry Andric             if (Level != OptimizationLevel::O0)
972e8d8bef9SDimitry Andric               FPM.addPass(ObjCARCOptPass());
973e8d8bef9SDimitry Andric           });
974e8d8bef9SDimitry Andric     }
975e8d8bef9SDimitry Andric 
9765ffd83dbSDimitry Andric     // If we reached here with a non-empty index file name, then the index
9775ffd83dbSDimitry Andric     // file was empty and we are not performing ThinLTO backend compilation
978fe6060f1SDimitry Andric     // (used in testing in a distributed build environment).
979fe6060f1SDimitry Andric     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
980fe6060f1SDimitry Andric     // If so drop any the type test assume sequences inserted for whole program
981fe6060f1SDimitry Andric     // vtables so that codegen doesn't complain.
982fe6060f1SDimitry Andric     if (IsThinLTOPostLink)
983e8d8bef9SDimitry Andric       PB.registerPipelineStartEPCallback(
984349cc55cSDimitry Andric           [](ModulePassManager &MPM, OptimizationLevel Level) {
9855ffd83dbSDimitry Andric             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
9865ffd83dbSDimitry Andric                                            /*ImportSummary=*/nullptr,
9875ffd83dbSDimitry Andric                                            /*DropTypeTests=*/true));
9885ffd83dbSDimitry Andric           });
9895ffd83dbSDimitry Andric 
990e8d8bef9SDimitry Andric     // Register callbacks to schedule sanitizer passes at the appropriate part
991e8d8bef9SDimitry Andric     // of the pipeline.
9920b57cec5SDimitry Andric     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
9930b57cec5SDimitry Andric       PB.registerScalarOptimizerLateEPCallback(
994349cc55cSDimitry Andric           [](FunctionPassManager &FPM, OptimizationLevel Level) {
9950b57cec5SDimitry Andric             FPM.addPass(BoundsCheckingPass());
9960b57cec5SDimitry Andric           });
9975ffd83dbSDimitry Andric 
998fe6060f1SDimitry Andric     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
999fe6060f1SDimitry Andric     // done on PreLink stage.
1000bdd1243dSDimitry Andric     if (!IsThinLTOPostLink) {
1001fe6060f1SDimitry Andric       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1002bdd1243dSDimitry Andric       addKCFIPass(TargetTriple, LangOpts, PB);
1003bdd1243dSDimitry Andric     }
1004e8d8bef9SDimitry Andric 
1005bdd1243dSDimitry Andric     if (std::optional<GCOVOptions> Options =
1006bdd1243dSDimitry Andric             getGCOVOptions(CodeGenOpts, LangOpts))
1007e8d8bef9SDimitry Andric       PB.registerPipelineStartEPCallback(
1008349cc55cSDimitry Andric           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
10090b57cec5SDimitry Andric             MPM.addPass(GCOVProfilerPass(*Options));
10100b57cec5SDimitry Andric           });
1011bdd1243dSDimitry Andric     if (std::optional<InstrProfOptions> Options =
10120b57cec5SDimitry Andric             getInstrProfOptions(CodeGenOpts, LangOpts))
1013e8d8bef9SDimitry Andric       PB.registerPipelineStartEPCallback(
1014349cc55cSDimitry Andric           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
10155f757f3fSDimitry Andric             MPM.addPass(InstrProfilingLoweringPass(*Options, false));
10160b57cec5SDimitry Andric           });
10170b57cec5SDimitry Andric 
101806c3fb27SDimitry Andric     // TODO: Consider passing the MemoryProfileOutput to the pass builder via
101906c3fb27SDimitry Andric     // the PGOOptions, and set this up there.
102006c3fb27SDimitry Andric     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
102106c3fb27SDimitry Andric       PB.registerOptimizerLastEPCallback(
102206c3fb27SDimitry Andric           [](ModulePassManager &MPM, OptimizationLevel Level) {
102306c3fb27SDimitry Andric             MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
102406c3fb27SDimitry Andric             MPM.addPass(ModuleMemProfilerPass());
102506c3fb27SDimitry Andric           });
102606c3fb27SDimitry Andric     }
102706c3fb27SDimitry Andric 
10285f757f3fSDimitry Andric     if (CodeGenOpts.FatLTO) {
10297a6dacacSDimitry Andric       MPM.addPass(PB.buildFatLTODefaultPipeline(
10307a6dacacSDimitry Andric           Level, PrepareForThinLTO,
10317a6dacacSDimitry Andric           PrepareForThinLTO || shouldEmitRegularLTOSummary()));
10325f757f3fSDimitry Andric     } else if (PrepareForThinLTO) {
10335f757f3fSDimitry Andric       MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
10345f757f3fSDimitry Andric     } else if (PrepareForLTO) {
10355f757f3fSDimitry Andric       MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1036e8d8bef9SDimitry Andric     } else {
10375f757f3fSDimitry Andric       MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1038e8d8bef9SDimitry Andric     }
1039a7dea167SDimitry Andric   }
10400b57cec5SDimitry Andric 
1041*0fca6ea1SDimitry Andric   // Link against bitcodes supplied via the -mlink-builtin-bitcode option
1042*0fca6ea1SDimitry Andric   if (CodeGenOpts.LinkBitcodePostopt)
1043*0fca6ea1SDimitry Andric     MPM.addPass(LinkInModulesPass(BC));
10445f757f3fSDimitry Andric 
1045349cc55cSDimitry Andric   // Add a verifier pass if requested. We don't have to do this if the action
1046349cc55cSDimitry Andric   // requires code generation because there will already be a verifier pass in
1047349cc55cSDimitry Andric   // the code-generation pipeline.
10485f757f3fSDimitry Andric   // Since we already added a verifier pass above, this
10495f757f3fSDimitry Andric   // might even not run the analysis, if previous passes caused no changes.
1050349cc55cSDimitry Andric   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
1051349cc55cSDimitry Andric     MPM.addPass(VerifierPass());
10520b57cec5SDimitry Andric 
1053439352acSDimitry Andric   if (Action == Backend_EmitBC || Action == Backend_EmitLL ||
1054439352acSDimitry Andric       CodeGenOpts.FatLTO) {
10550b57cec5SDimitry Andric     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1056bdd1243dSDimitry Andric       if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
10575f757f3fSDimitry Andric         TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1058bdd1243dSDimitry Andric                                  CodeGenOpts.EnableSplitLTOUnit);
1059bdd1243dSDimitry Andric       if (Action == Backend_EmitBC) {
10600b57cec5SDimitry Andric         if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
10610b57cec5SDimitry Andric           ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
10620b57cec5SDimitry Andric           if (!ThinLinkOS)
10630b57cec5SDimitry Andric             return;
10640b57cec5SDimitry Andric         }
106506c3fb27SDimitry Andric         MPM.addPass(ThinLTOBitcodeWriterPass(
106606c3fb27SDimitry Andric             *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1067439352acSDimitry Andric       } else if (Action == Backend_EmitLL) {
1068bdd1243dSDimitry Andric         MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1069bdd1243dSDimitry Andric                                     /*EmitLTOSummary=*/true));
1070bdd1243dSDimitry Andric       }
1071bdd1243dSDimitry Andric     } else {
10720b57cec5SDimitry Andric       // Emit a module summary by default for Regular LTO except for ld64
10730b57cec5SDimitry Andric       // targets
107481ad6265SDimitry Andric       bool EmitLTOSummary = shouldEmitRegularLTOSummary();
10750b57cec5SDimitry Andric       if (EmitLTOSummary) {
107606c3fb27SDimitry Andric         if (!TheModule->getModuleFlag("ThinLTO") && !CodeGenOpts.UnifiedLTO)
10775f757f3fSDimitry Andric           TheModule->addModuleFlag(llvm::Module::Error, "ThinLTO", uint32_t(0));
10784824e7fdSDimitry Andric         if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
10795f757f3fSDimitry Andric           TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1080a7dea167SDimitry Andric                                    uint32_t(1));
10810b57cec5SDimitry Andric       }
1082439352acSDimitry Andric       if (Action == Backend_EmitBC) {
1083bdd1243dSDimitry Andric         MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1084bdd1243dSDimitry Andric                                       EmitLTOSummary));
1085439352acSDimitry Andric       } else if (Action == Backend_EmitLL) {
1086bdd1243dSDimitry Andric         MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1087bdd1243dSDimitry Andric                                     EmitLTOSummary));
10880b57cec5SDimitry Andric       }
1089349cc55cSDimitry Andric     }
1090439352acSDimitry Andric 
1091439352acSDimitry Andric     if (shouldEmitUnifiedLTOModueFlag())
10925f757f3fSDimitry Andric       TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
10935f757f3fSDimitry Andric   }
10945f757f3fSDimitry Andric 
10955f757f3fSDimitry Andric   // Print a textual, '-passes=' compatible, representation of pipeline if
10965f757f3fSDimitry Andric   // requested.
10975f757f3fSDimitry Andric   if (PrintPipelinePasses) {
10985f757f3fSDimitry Andric     MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
10995f757f3fSDimitry Andric       auto PassName = PIC.getPassNameForClassName(ClassName);
11005f757f3fSDimitry Andric       return PassName.empty() ? ClassName : PassName;
11015f757f3fSDimitry Andric     });
11025f757f3fSDimitry Andric     outs() << "\n";
11035f757f3fSDimitry Andric     return;
11045f757f3fSDimitry Andric   }
11055f757f3fSDimitry Andric 
11065f757f3fSDimitry Andric   if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
11075f757f3fSDimitry Andric       LangOpts.HIPStdParInterposeAlloc)
11085f757f3fSDimitry Andric     MPM.addPass(HipStdParAllocationInterpositionPass());
1109349cc55cSDimitry Andric 
1110349cc55cSDimitry Andric   // Now that we have all of the passes ready, run them.
111104eeddc0SDimitry Andric   {
1112349cc55cSDimitry Andric     PrettyStackTraceString CrashInfo("Optimizer");
111304eeddc0SDimitry Andric     llvm::TimeTraceScope TimeScope("Optimizer");
1114349cc55cSDimitry Andric     MPM.run(*TheModule, MAM);
1115349cc55cSDimitry Andric   }
111604eeddc0SDimitry Andric }
1117349cc55cSDimitry Andric 
1118349cc55cSDimitry Andric void EmitAssemblyHelper::RunCodegenPipeline(
1119349cc55cSDimitry Andric     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1120349cc55cSDimitry Andric     std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1121349cc55cSDimitry Andric   // We still use the legacy PM to run the codegen pipeline since the new PM
1122349cc55cSDimitry Andric   // does not work with the codegen pipeline.
1123349cc55cSDimitry Andric   // FIXME: make the new PM work with the codegen pipeline.
1124349cc55cSDimitry Andric   legacy::PassManager CodeGenPasses;
1125349cc55cSDimitry Andric 
1126349cc55cSDimitry Andric   // Append any output we need to the pass manager.
1127349cc55cSDimitry Andric   switch (Action) {
11280b57cec5SDimitry Andric   case Backend_EmitAssembly:
11290b57cec5SDimitry Andric   case Backend_EmitMCNull:
11300b57cec5SDimitry Andric   case Backend_EmitObj:
11310b57cec5SDimitry Andric     CodeGenPasses.add(
11320b57cec5SDimitry Andric         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
11330b57cec5SDimitry Andric     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
11340b57cec5SDimitry Andric       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
11350b57cec5SDimitry Andric       if (!DwoOS)
11360b57cec5SDimitry Andric         return;
11370b57cec5SDimitry Andric     }
11380b57cec5SDimitry Andric     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
11390b57cec5SDimitry Andric                        DwoOS ? &DwoOS->os() : nullptr))
11400b57cec5SDimitry Andric       // FIXME: Should we handle this error differently?
11410b57cec5SDimitry Andric       return;
11420b57cec5SDimitry Andric     break;
1143349cc55cSDimitry Andric   default:
1144349cc55cSDimitry Andric     return;
11450b57cec5SDimitry Andric   }
11460b57cec5SDimitry Andric 
11475f757f3fSDimitry Andric   // If -print-pipeline-passes is requested, don't run the legacy pass manager.
11485f757f3fSDimitry Andric   // FIXME: when codegen is switched to use the new pass manager, it should also
11495f757f3fSDimitry Andric   // emit pass names here.
11505f757f3fSDimitry Andric   if (PrintPipelinePasses) {
11515f757f3fSDimitry Andric     return;
11525f757f3fSDimitry Andric   }
11535f757f3fSDimitry Andric 
115404eeddc0SDimitry Andric   {
1155349cc55cSDimitry Andric     PrettyStackTraceString CrashInfo("Code generation");
115604eeddc0SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1157349cc55cSDimitry Andric     CodeGenPasses.run(*TheModule);
1158349cc55cSDimitry Andric   }
115904eeddc0SDimitry Andric }
1160349cc55cSDimitry Andric 
1161349cc55cSDimitry Andric void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
11625f757f3fSDimitry Andric                                       std::unique_ptr<raw_pwrite_stream> OS,
11635f757f3fSDimitry Andric                                       BackendConsumer *BC) {
1164349cc55cSDimitry Andric   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1165349cc55cSDimitry Andric   setCommandLineOpts(CodeGenOpts);
1166349cc55cSDimitry Andric 
1167349cc55cSDimitry Andric   bool RequiresCodeGen = actionRequiresCodeGen(Action);
1168349cc55cSDimitry Andric   CreateTargetMachine(RequiresCodeGen);
1169349cc55cSDimitry Andric 
1170349cc55cSDimitry Andric   if (RequiresCodeGen && !TM)
1171349cc55cSDimitry Andric     return;
1172349cc55cSDimitry Andric   if (TM)
1173349cc55cSDimitry Andric     TheModule->setDataLayout(TM->createDataLayout());
1174349cc55cSDimitry Andric 
11750b57cec5SDimitry Andric   // Before executing passes, print the final values of the LLVM options.
11760b57cec5SDimitry Andric   cl::PrintOptionValues();
11770b57cec5SDimitry Andric 
1178349cc55cSDimitry Andric   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
11795f757f3fSDimitry Andric   RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1180349cc55cSDimitry Andric   RunCodegenPipeline(Action, OS, DwoOS);
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric   if (ThinLinkOS)
11830b57cec5SDimitry Andric     ThinLinkOS->keep();
11840b57cec5SDimitry Andric   if (DwoOS)
11850b57cec5SDimitry Andric     DwoOS->keep();
11860b57cec5SDimitry Andric }
11870b57cec5SDimitry Andric 
11885ffd83dbSDimitry Andric static void runThinLTOBackend(
11895f757f3fSDimitry Andric     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex,
11905f757f3fSDimitry Andric     llvm::Module *M, const HeaderSearchOptions &HeaderOpts,
11915f757f3fSDimitry Andric     const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
11925f757f3fSDimitry Andric     const LangOptions &LOpts, std::unique_ptr<raw_pwrite_stream> OS,
11935f757f3fSDimitry Andric     std::string SampleProfile, std::string ProfileRemapping,
11945f757f3fSDimitry Andric     BackendAction Action) {
11955f757f3fSDimitry Andric   DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
11960b57cec5SDimitry Andric       ModuleToDefinedGVSummaries;
11970b57cec5SDimitry Andric   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric   setCommandLineOpts(CGOpts);
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric   // We can simply import the values mentioned in the combined index, since
12020b57cec5SDimitry Andric   // we should only invoke this using the individual indexes written out
12030b57cec5SDimitry Andric   // via a WriteIndexesThinBackend.
12040b57cec5SDimitry Andric   FunctionImporter::ImportMapTy ImportList;
1205fe6060f1SDimitry Andric   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
12060b57cec5SDimitry Andric     return;
12070b57cec5SDimitry Andric 
1208bdd1243dSDimitry Andric   auto AddStream = [&](size_t Task, const Twine &ModuleName) {
12090eae32dcSDimitry Andric     return std::make_unique<CachedFileStream>(std::move(OS),
12100eae32dcSDimitry Andric                                               CGOpts.ObjectFilenameForDebug);
12110b57cec5SDimitry Andric   };
12120b57cec5SDimitry Andric   lto::Config Conf;
12130b57cec5SDimitry Andric   if (CGOpts.SaveTempsFilePrefix != "") {
12140b57cec5SDimitry Andric     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
12150b57cec5SDimitry Andric                                     /* UseInputModulePath */ false)) {
12160b57cec5SDimitry Andric       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
12170b57cec5SDimitry Andric         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
12180b57cec5SDimitry Andric                << '\n';
12190b57cec5SDimitry Andric       });
12200b57cec5SDimitry Andric     }
12210b57cec5SDimitry Andric   }
12220b57cec5SDimitry Andric   Conf.CPU = TOpts.CPU;
12230b57cec5SDimitry Andric   Conf.CodeModel = getCodeModel(CGOpts);
12240b57cec5SDimitry Andric   Conf.MAttrs = TOpts.Features;
12250b57cec5SDimitry Andric   Conf.RelocModel = CGOpts.RelocationModel;
12265f757f3fSDimitry Andric   std::optional<CodeGenOptLevel> OptLevelOrNone =
1227bdd1243dSDimitry Andric       CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1228bdd1243dSDimitry Andric   assert(OptLevelOrNone && "Invalid optimization level!");
1229bdd1243dSDimitry Andric   Conf.CGOptLevel = *OptLevelOrNone;
12300b57cec5SDimitry Andric   Conf.OptLevel = CGOpts.OptimizationLevel;
12315ffd83dbSDimitry Andric   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
12320b57cec5SDimitry Andric   Conf.SampleProfile = std::move(SampleProfile);
1233480093f4SDimitry Andric   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1234480093f4SDimitry Andric   // For historical reasons, loop interleaving is set to mirror setting for loop
1235480093f4SDimitry Andric   // unrolling.
1236480093f4SDimitry Andric   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1237480093f4SDimitry Andric   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1238480093f4SDimitry Andric   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
12395ffd83dbSDimitry Andric   // Only enable CGProfilePass when using integrated assembler, since
12405ffd83dbSDimitry Andric   // non-integrated assemblers don't recognize .cgprofile section.
12415ffd83dbSDimitry Andric   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric   // Context sensitive profile.
12440b57cec5SDimitry Andric   if (CGOpts.hasProfileCSIRInstr()) {
12450b57cec5SDimitry Andric     Conf.RunCSIRInstr = true;
12460b57cec5SDimitry Andric     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
12470b57cec5SDimitry Andric   } else if (CGOpts.hasProfileCSIRUse()) {
12480b57cec5SDimitry Andric     Conf.RunCSIRInstr = false;
12490b57cec5SDimitry Andric     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
12500b57cec5SDimitry Andric   }
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric   Conf.ProfileRemapping = std::move(ProfileRemapping);
12530b57cec5SDimitry Andric   Conf.DebugPassManager = CGOpts.DebugPassManager;
125406c3fb27SDimitry Andric   Conf.VerifyEach = CGOpts.VerifyEach;
12550b57cec5SDimitry Andric   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
12560b57cec5SDimitry Andric   Conf.RemarksFilename = CGOpts.OptRecordFile;
12570b57cec5SDimitry Andric   Conf.RemarksPasses = CGOpts.OptRecordPasses;
12580b57cec5SDimitry Andric   Conf.RemarksFormat = CGOpts.OptRecordFormat;
12590b57cec5SDimitry Andric   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
12600b57cec5SDimitry Andric   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
12610b57cec5SDimitry Andric   switch (Action) {
12620b57cec5SDimitry Andric   case Backend_EmitNothing:
12635f757f3fSDimitry Andric     Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) {
12640b57cec5SDimitry Andric       return false;
12650b57cec5SDimitry Andric     };
12660b57cec5SDimitry Andric     break;
12670b57cec5SDimitry Andric   case Backend_EmitLL:
12685f757f3fSDimitry Andric     Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
12690b57cec5SDimitry Andric       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
12700b57cec5SDimitry Andric       return false;
12710b57cec5SDimitry Andric     };
12720b57cec5SDimitry Andric     break;
12730b57cec5SDimitry Andric   case Backend_EmitBC:
12745f757f3fSDimitry Andric     Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
12750b57cec5SDimitry Andric       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
12760b57cec5SDimitry Andric       return false;
12770b57cec5SDimitry Andric     };
12780b57cec5SDimitry Andric     break;
12790b57cec5SDimitry Andric   default:
12800b57cec5SDimitry Andric     Conf.CGFileType = getCodeGenFileType(Action);
12810b57cec5SDimitry Andric     break;
12820b57cec5SDimitry Andric   }
1283e8d8bef9SDimitry Andric   if (Error E =
1284e8d8bef9SDimitry Andric           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1285e8d8bef9SDimitry Andric                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1286fe6060f1SDimitry Andric                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
12870b57cec5SDimitry Andric     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
12880b57cec5SDimitry Andric       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
12890b57cec5SDimitry Andric     });
12900b57cec5SDimitry Andric   }
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
12935f757f3fSDimitry Andric void clang::EmitBackendOutput(
12945f757f3fSDimitry Andric     DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderOpts,
12955f757f3fSDimitry Andric     const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
12965f757f3fSDimitry Andric     const LangOptions &LOpts, StringRef TDesc, llvm::Module *M,
12975f757f3fSDimitry Andric     BackendAction Action, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
12985f757f3fSDimitry Andric     std::unique_ptr<raw_pwrite_stream> OS, BackendConsumer *BC) {
12990b57cec5SDimitry Andric 
1300480093f4SDimitry Andric   llvm::TimeTraceScope TimeScope("Backend");
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric   std::unique_ptr<llvm::Module> EmptyModule;
13030b57cec5SDimitry Andric   if (!CGOpts.ThinLTOIndexFile.empty()) {
13040b57cec5SDimitry Andric     // If we are performing a ThinLTO importing compile, load the function index
13050b57cec5SDimitry Andric     // into memory and pass it into runThinLTOBackend, which will run the
13060b57cec5SDimitry Andric     // function importer and invoke LTO passes.
1307349cc55cSDimitry Andric     std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1308349cc55cSDimitry Andric     if (Error E = llvm::getModuleSummaryIndexForFile(
1309349cc55cSDimitry Andric                       CGOpts.ThinLTOIndexFile,
1310349cc55cSDimitry Andric                       /*IgnoreEmptyThinLTOIndexFile*/ true)
1311349cc55cSDimitry Andric                       .moveInto(CombinedIndex)) {
1312349cc55cSDimitry Andric       logAllUnhandledErrors(std::move(E), errs(),
13130b57cec5SDimitry Andric                             "Error loading index file '" +
13140b57cec5SDimitry Andric                             CGOpts.ThinLTOIndexFile + "': ");
13150b57cec5SDimitry Andric       return;
13160b57cec5SDimitry Andric     }
1317349cc55cSDimitry Andric 
13180b57cec5SDimitry Andric     // A null CombinedIndex means we should skip ThinLTO compilation
13190b57cec5SDimitry Andric     // (LLVM will optionally ignore empty index files, returning null instead
13200b57cec5SDimitry Andric     // of an error).
13210b57cec5SDimitry Andric     if (CombinedIndex) {
13220b57cec5SDimitry Andric       if (!CombinedIndex->skipModuleByDistributedBackend()) {
13235ffd83dbSDimitry Andric         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
13245ffd83dbSDimitry Andric                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
13250b57cec5SDimitry Andric                           CGOpts.ProfileRemappingFile, Action);
13260b57cec5SDimitry Andric         return;
13270b57cec5SDimitry Andric       }
13280b57cec5SDimitry Andric       // Distributed indexing detected that nothing from the module is needed
13290b57cec5SDimitry Andric       // for the final linking. So we can skip the compilation. We sill need to
13300b57cec5SDimitry Andric       // output an empty object file to make sure that a linker does not fail
13310b57cec5SDimitry Andric       // trying to read it. Also for some features, like CFI, we must skip
13320b57cec5SDimitry Andric       // the compilation as CombinedIndex does not contain all required
13330b57cec5SDimitry Andric       // information.
1334a7dea167SDimitry Andric       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
13350b57cec5SDimitry Andric       EmptyModule->setTargetTriple(M->getTargetTriple());
13360b57cec5SDimitry Andric       M = EmptyModule.get();
13370b57cec5SDimitry Andric     }
13380b57cec5SDimitry Andric   }
13390b57cec5SDimitry Andric 
134006c3fb27SDimitry Andric   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M, VFS);
13415f757f3fSDimitry Andric   AsmHelper.EmitAssembly(Action, std::move(OS), BC);
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
13440b57cec5SDimitry Andric   // DataLayout.
13450b57cec5SDimitry Andric   if (AsmHelper.TM) {
13460b57cec5SDimitry Andric     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1347fe6060f1SDimitry Andric     if (DLDesc != TDesc) {
13480b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(
13490b57cec5SDimitry Andric           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
13500b57cec5SDimitry Andric                                     "expected target description '%1'");
1351fe6060f1SDimitry Andric       Diags.Report(DiagID) << DLDesc << TDesc;
13520b57cec5SDimitry Andric     }
13530b57cec5SDimitry Andric   }
13540b57cec5SDimitry Andric }
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric // With -fembed-bitcode, save a copy of the llvm IR as data in the
13570b57cec5SDimitry Andric // __LLVM,__bitcode section.
13580b57cec5SDimitry Andric void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
13590b57cec5SDimitry Andric                          llvm::MemoryBufferRef Buf) {
13600b57cec5SDimitry Andric   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
13610b57cec5SDimitry Andric     return;
13621fd87a68SDimitry Andric   llvm::embedBitcodeInModule(
1363480093f4SDimitry Andric       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1364480093f4SDimitry Andric       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1365e8d8bef9SDimitry Andric       CGOpts.CmdArgs);
13660b57cec5SDimitry Andric }
13671fd87a68SDimitry Andric 
13681fd87a68SDimitry Andric void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
13691fd87a68SDimitry Andric                         DiagnosticsEngine &Diags) {
13701fd87a68SDimitry Andric   if (CGOpts.OffloadObjects.empty())
13711fd87a68SDimitry Andric     return;
13721fd87a68SDimitry Andric 
13731fd87a68SDimitry Andric   for (StringRef OffloadObject : CGOpts.OffloadObjects) {
13741fd87a68SDimitry Andric     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
137581ad6265SDimitry Andric         llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
13765f757f3fSDimitry Andric     if (ObjectOrErr.getError()) {
13771fd87a68SDimitry Andric       auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
13781fd87a68SDimitry Andric                                           "could not open '%0' for embedding");
137981ad6265SDimitry Andric       Diags.Report(DiagID) << OffloadObject;
13801fd87a68SDimitry Andric       return;
13811fd87a68SDimitry Andric     }
13821fd87a68SDimitry Andric 
138381ad6265SDimitry Andric     llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
138481ad6265SDimitry Andric                               Align(object::OffloadBinary::getAlignment()));
13851fd87a68SDimitry Andric   }
13861fd87a68SDimitry Andric }
1387