LLVM 24.0.0git
AMDGPUTargetMachine.cpp
Go to the documentation of this file.
1//===-- AMDGPUTargetMachine.cpp - TargetMachine for hw codegen targets-----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This file contains both AMDGPU target machine and the CodeGen pass builder.
11/// The AMDGPU target machine contains all of the hardware specific information
12/// needed to emit code for SI+ GPUs in the legacy pass manager pipeline. The
13/// CodeGen pass builder handles the pass pipeline for new pass manager.
14//
15//===----------------------------------------------------------------------===//
16
17#include "AMDGPUTargetMachine.h"
18#include "AMDGPU.h"
19#include "AMDGPUAliasAnalysis.h"
20#include "AMDGPUAsmPrinter.h"
26#include "AMDGPUHazardLatency.h"
27#include "AMDGPUIGroupLP.h"
28#include "AMDGPUISelDAGToDAG.h"
30#include "AMDGPUMacroFusion.h"
38#include "AMDGPUSplitModule.h"
43#include "GCNDPPCombine.h"
45#include "GCNNSAReassign.h"
49#include "GCNSchedStrategy.h"
50#include "GCNVOPDUtils.h"
51#include "R600.h"
52#include "R600TargetMachine.h"
53#include "SIFixSGPRCopies.h"
54#include "SIFixVGPRCopies.h"
55#include "SIFoldOperands.h"
56#include "SIFormMemoryClauses.h"
58#include "SILowerControlFlow.h"
59#include "SILowerSGPRSpills.h"
60#include "SILowerWWMCopies.h"
62#include "SIMachineScheduler.h"
66#include "SIPeepholeSDWA.h"
67#include "SIPostRABundler.h"
70#include "SIWholeQuadMode.h"
93#include "llvm/CodeGen/Passes.h"
104#include "llvm/IR/IntrinsicsAMDGPU.h"
105#include "llvm/IR/Module.h"
106#include "llvm/IR/PassManager.h"
107#include "llvm/IR/PatternMatch.h"
117#include "llvm/Transforms/IPO.h"
142#include <optional>
143
144using namespace llvm;
145using namespace llvm::PatternMatch;
146
147namespace {
148//===----------------------------------------------------------------------===//
149// AMDGPU CodeGen Pass Builder interface.
150//===----------------------------------------------------------------------===//
151
152class AMDGPUCodeGenPassBuilder : public CodeGenPassBuilder {
153 using Base = CodeGenPassBuilder;
154
155 const AMDGPUOptions &CLOpts;
156
157 GCNTargetMachine &getTM() const {
158 return static_cast<GCNTargetMachine &>(TM);
159 }
160
161public:
162 AMDGPUCodeGenPassBuilder(GCNTargetMachine &TM,
163 const CGPassBuilderOption &Opts,
164 PassInstrumentationCallbacks *PIC);
165
166protected:
167 void addIRPasses(PassManagerWrapper &PMW) override;
168 void addCodeGenPrepare(PassManagerWrapper &PMW) override;
169 void addPreISel(PassManagerWrapper &PMW) override;
170 void addILPOpts(PassManagerWrapper &PMW) override;
171 void addAsmPrinterBegin(PassManagerWrapper &PMW) override;
172 void addAsmPrinter(PassManagerWrapper &PMW) override;
173 void addAsmPrinterEnd(PassManagerWrapper &PMW) override;
174 Error addInstSelector(PassManagerWrapper &PMW) override;
175 Error addIRTranslator(PassManagerWrapper &PMW) override;
176 void addPreLegalizeMachineIR(PassManagerWrapper &PMW) override;
177 Error addLegalizeMachineIR(PassManagerWrapper &PMW) override;
178 void addPreRegBankSelect(PassManagerWrapper &PMW) override;
179 Error addRegBankSelect(PassManagerWrapper &PMW) override;
180 void addPreGlobalInstructionSelect(PassManagerWrapper &PMW) override;
181 Error addGlobalInstructionSelect(PassManagerWrapper &PMW) override;
182 void addPreRewrite(PassManagerWrapper &PMW) override;
183 void addMachineSSAOptimization(PassManagerWrapper &PMW) override;
184 void addPostRegAlloc(PassManagerWrapper &PMW) override;
185 void addPreEmitPass(PassManagerWrapper &PMW) override;
186 Error addRegAssignAndRewriteFast(PassManagerWrapper &PMW) override;
187 Error addRegAssignAndRewriteOptimized(PassManagerWrapper &PMW) override;
188 void addPreRegAlloc(PassManagerWrapper &PMW) override;
189 Error addFastRegAlloc(PassManagerWrapper &PMW) override;
190 Error addOptimizedRegAlloc(PassManagerWrapper &PMW) override;
191 void addPreSched2(PassManagerWrapper &PMW) override;
192 void addPostBBSections(PassManagerWrapper &PMW) override;
193
194private:
195 Error validateRegAllocOptions() const;
196
197public:
198 /// Check if a pass is enabled given \p Opt option. The option always
199 /// overrides defaults if explicitly used. Otherwise the pass is enabled at an
200 /// optimization \p Level minimum.
201 bool isPassEnabled(BoolOrDefault Opt,
202 CodeGenOptLevel Level = CodeGenOptLevel::Default) const;
203 void addEarlyCSEOrGVNPass(PassManagerWrapper &PMW);
204 void addStraightLineScalarOptimizationPasses(PassManagerWrapper &PMW);
205};
206
207class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
208public:
209 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
210 : RegisterRegAllocBase(N, D, C) {}
211};
212
213class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
214public:
215 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
216 : RegisterRegAllocBase(N, D, C) {}
217};
218
219class WWMRegisterRegAlloc : public RegisterRegAllocBase<WWMRegisterRegAlloc> {
220public:
221 WWMRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
222 : RegisterRegAllocBase(N, D, C) {}
223};
224
225} // anonymous namespace
226
229 const Register Reg) {
230 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
231 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
232}
233
236 const Register Reg) {
237 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
238 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
239}
240
243 const Register Reg) {
244 const SIMachineFunctionInfo *MFI =
245 MRI.getMF().getInfo<SIMachineFunctionInfo>();
246 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
247 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC) &&
249}
250
251/// -{sgpr|wwm|vgpr}-regalloc=... command line option.
252static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
253
254/// A dummy default pass factory indicates whether the register allocator is
255/// overridden on the command line.
259
260static SGPRRegisterRegAlloc
262 "pick SGPR register allocator based on -O option",
264
265static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
268 cl::desc("Register allocator to use for SGPRs"));
269
270static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
273 cl::desc("Register allocator to use for VGPRs"));
274
275static cl::opt<WWMRegisterRegAlloc::FunctionPassCtor, false,
277 WWMRegAlloc("wwm-regalloc", cl::Hidden,
279 cl::desc("Register allocator to use for WWM registers"));
280
281// New pass manager register allocator options for AMDGPU
283 "sgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
284 cl::desc("Register allocator for SGPRs (new pass manager)"));
285
287 "vgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
288 cl::desc("Register allocator for VGPRs (new pass manager)"));
289
291 "wwm-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
292 cl::desc("Register allocator for WWM registers (new pass manager)"));
293
294/// Check if the given RegAllocType is supported for AMDGPU NPM register
295/// allocation. Only Fast and Greedy are supported; Basic and PBQP are not.
297 if (RAType == RegAllocType::Basic || RAType == RegAllocType::PBQP) {
299 Twine("unsupported register allocator '") +
300 (RAType == RegAllocType::Basic ? "basic" : "pbqp") + "' for " +
301 RegName + " registers",
303 }
304 return Error::success();
305}
306
307Error AMDGPUCodeGenPassBuilder::validateRegAllocOptions() const {
308 // 1. Generic --regalloc-npm is not supported for AMDGPU.
309 if (Opt.RegAlloc != RegAllocType::Unset) {
311 "-regalloc-npm not supported for amdgcn. Use -sgpr-regalloc-npm, "
312 "-vgpr-regalloc-npm, and -wwm-regalloc-npm",
314 }
315
316 // 2. Legacy PM regalloc options are not compatible with NPM.
317 if (SGPRRegAlloc.getNumOccurrences() > 0 ||
318 VGPRRegAlloc.getNumOccurrences() > 0 ||
319 WWMRegAlloc.getNumOccurrences() > 0) {
321 "-sgpr-regalloc, -vgpr-regalloc, and -wwm-regalloc are legacy PM "
322 "options. Use -sgpr-regalloc-npm, -vgpr-regalloc-npm, and "
323 "-wwm-regalloc-npm with the new pass manager",
325 }
326
327 // 3. Only Fast and Greedy allocators are supported for AMDGPU.
328 if (auto Err = checkRegAllocSupported(SGPRRegAllocNPM, "SGPR"))
329 return Err;
330 if (auto Err = checkRegAllocSupported(WWMRegAllocNPM, "WWM"))
331 return Err;
332 if (auto Err = checkRegAllocSupported(VGPRRegAllocNPM, "VGPR"))
333 return Err;
334
335 return Error::success();
336}
337
339 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
340
341 if (!Ctor) {
342 Ctor = SGPRRegAlloc;
343 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
344 }
345}
346
348 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
349
350 if (!Ctor) {
351 Ctor = VGPRRegAlloc;
352 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
353 }
354}
355
357 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
358
359 if (!Ctor) {
360 Ctor = WWMRegAlloc;
361 WWMRegisterRegAlloc::setDefault(WWMRegAlloc);
362 }
363}
364
368
372
376
380
384
388
392
396
400
401static SGPRRegisterRegAlloc basicRegAllocSGPR(
402 "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
403static SGPRRegisterRegAlloc greedyRegAllocSGPR(
404 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
405
406static SGPRRegisterRegAlloc fastRegAllocSGPR(
407 "fast", "fast register allocator", createFastSGPRRegisterAllocator);
408
409
410static VGPRRegisterRegAlloc basicRegAllocVGPR(
411 "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
412static VGPRRegisterRegAlloc greedyRegAllocVGPR(
413 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
414
415static VGPRRegisterRegAlloc fastRegAllocVGPR(
416 "fast", "fast register allocator", createFastVGPRRegisterAllocator);
417static WWMRegisterRegAlloc basicRegAllocWWMReg("basic",
418 "basic register allocator",
420static WWMRegisterRegAlloc
421 greedyRegAllocWWMReg("greedy", "greedy register allocator",
423static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator",
425
430
432 "amdgpu-enable-object-linking",
433 cl::desc("Enable object linking for cross-TU LDS and ABI support"),
435 cl::Hidden);
436
438 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
440 cl::Hidden);
441
442// Scheduler selection is consulted both when creating the scheduler and from
443// overrideSchedPolicy(), so keep the attribute and global command line handling
444// in one helper.
445StringRef llvm::AMDGPU::getSchedStrategy(const AMDGPUOptions &CLOpts,
446 const Function &F) {
447 Attribute SchedStrategyAttr = F.getFnAttribute("amdgpu-sched-strategy");
448 if (SchedStrategyAttr.isValid())
449 return SchedStrategyAttr.getValueAsString();
450
451 return CLOpts.sched_strategy;
452}
453
454static void
456 const GCNSubtarget &ST) {
457 if (ST.hasGFX1250Insts() || ST.hasGFX950Insts())
458 return;
459
460 F.getContext().diagnose(DiagnosticInfoUnsupported(
461 F,
462 "'amdgpu-sched-strategy'='coexec' is only supported for gfx1250/gfx950",
464}
465
466static bool useNoopPostScheduler(const AMDGPUOptions &CLOpts,
467 const Function &F) {
468 Attribute PostSchedStrategyAttr =
469 F.getFnAttribute("amdgpu-post-sched-strategy");
470 if (PostSchedStrategyAttr.isValid())
471 return PostSchedStrategyAttr.getValueAsString() == "nop";
472 return AMDGPU::getSchedStrategy(CLOpts, F) == "coexec";
473}
474
476 // Register the target
481
569}
570
571static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
572 return std::make_unique<AMDGPUTargetObjectFile>();
573}
574
578
579static ScheduleDAGInstrs *
581 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
582 ScheduleDAGMILive *DAG =
583 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
584 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
585 if (ST.shouldClusterStores())
586 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
588 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
589 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
590 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
591 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
592 return DAG;
593}
594
595static ScheduleDAGInstrs *
597 ScheduleDAGMILive *DAG =
598 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C));
600 return DAG;
601}
602
603static ScheduleDAGInstrs *
605 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
607 C, std::make_unique<GCNMaxMemoryClauseSchedStrategy>(C));
608 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
609 if (ST.shouldClusterStores())
610 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
611 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
612 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
613 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
614 return DAG;
615}
616
617static ScheduleDAGInstrs *
619 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
620 auto *DAG = new GCNIterativeScheduler(
622 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
623 if (ST.shouldClusterStores())
624 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
626 return DAG;
627}
628
635
636static ScheduleDAGInstrs *
638 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
640 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
641 if (ST.shouldClusterStores())
642 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
643 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
645 return DAG;
646}
647
648static MachineSchedRegistry
649SISchedRegistry("si", "Run SI's custom scheduler",
651
654 "Run GCN scheduler to maximize occupancy",
656
658 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp",
660
662 "gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause",
664
666 "gcn-iterative-max-occupancy-experimental",
667 "Run GCN scheduler to maximize occupancy (experimental)",
669
671 "gcn-iterative-minreg",
672 "Run GCN iterative scheduler for minimal register usage (experimental)",
674
676 "gcn-iterative-ilp",
677 "Run GCN iterative scheduler for ILP scheduling (experimental)",
679
682 if (!GPU.empty())
683 return GPU;
684
685 if (StringRef Name = AMDGPU::getArchNameFromSubArch(TT.getSubArch());
686 !Name.empty())
687 return Name;
688
689 // Need to default to a target with flat support for HSA.
690 if (TT.isAMDGCN())
691 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
692
693 return "r600";
694}
695
697 // The AMDGPU toolchain only supports generating shared objects, so we
698 // must always use PIC.
699 return Reloc::PIC_;
700}
701
703 StringRef CPU, StringRef FS,
704 const TargetOptions &Options,
705 std::optional<Reloc::Model> RM,
706 std::optional<CodeModel::Model> CM,
711 OptLevel),
712 CLOpts(cl::LibraryOptionsContext::get<AMDGPUOptions>(
713 Options.MCOptions.LibraryOptions)),
715 initAsmInfo();
716 if (TT.isAMDGCN()) {
717 // Triple is missing a representation for non-empty, but unrecognized
718 // subarches. Only permit no subarch for any subtarget if it was really
719 // empty.
720 bool IsUnknownSubArch =
721 TT.getSubArch() == Triple::NoSubArch && TT.getArchName().size() != 6;
722 if (IsUnknownSubArch)
723 reportFatalUsageError("unknown subarch " + TT.getArchName());
724
725 if (TT.getSubArch() != Triple::NoSubArch) {
727 Triple::SubArchType GPUSubArch = AMDGPU::getSubArch(Kind);
728 if (Kind != AMDGPU::GK_NONE && GPUSubArch != TT.getSubArch() &&
729 TT.getSubArch() != AMDGPU::getMajorSubArch(GPUSubArch)) {
730 reportFatalUsageError("invalid cpu '" + CPU + "' for subarch " +
731 TT.getArchName());
732 }
733 }
734
735 if (getMCSubtargetInfo().checkFeatures("+wavefrontsize64"))
737 else if (getMCSubtargetInfo().checkFeatures("+wavefrontsize32"))
739 }
741}
742
746
748
751 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
753 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
754 if (ST.shouldClusterStores())
755 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
756 return DAG;
757}
758
759/// Predicate for Internalize pass.
760static bool mustPreserveGV(const GlobalValue &GV) {
761 if (const Function *F = dyn_cast<Function>(&GV))
762 return F->isDeclaration() || F->getName().starts_with("__asan_") ||
763 F->getName().starts_with("__sanitizer_") ||
764 AMDGPU::isEntryFunctionCC(F->getCallingConv());
765
767 return !GV.use_empty();
768}
769
774
777 if (Params.empty())
779 Params.consume_front("strategy=");
781 .Case("dpp", AMDGPU::ScanOptions::DPP)
782 .Cases({"iterative", ""}, AMDGPU::ScanOptions::Iterative)
783 .Case("none", AMDGPU::ScanOptions::None)
784 .Default(std::nullopt);
785 if (Result)
786 return *Result;
787 return make_error<StringError>("invalid parameter", inconvertibleErrorCode());
788}
789
793 while (!Params.empty()) {
794 StringRef ParamName;
795 std::tie(ParamName, Params) = Params.split(';');
796 if (ParamName == "closed-world") {
797 Result.IsClosedWorld = true;
798 } else {
800 formatv("invalid AMDGPUAttributor pass parameter '{0}' ", ParamName)
801 .str(),
803 }
804 }
805 return Result;
806}
807
809
810#define GET_PASS_REGISTRY "AMDGPUPassRegistry.def"
812
813 PB.registerPipelineParsingCallback(
814 [this](StringRef Name, CGSCCPassManager &PM,
816 if (Name == "amdgpu-attributor-cgscc" && getTargetTriple().isAMDGCN()) {
818 *static_cast<GCNTargetMachine *>(this)));
819 return true;
820 }
821 return false;
822 });
823
824 PB.registerScalarOptimizerLateEPCallback(
825 [](FunctionPassManager &FPM, OptimizationLevel Level) {
826 if (Level == OptimizationLevel::O0)
827 return;
828
830 });
831
832 PB.registerVectorizerEndEPCallback(
833 [](FunctionPassManager &FPM, OptimizationLevel Level) {
834 if (Level == OptimizationLevel::O0)
835 return;
836
838 });
839
840 PB.registerPipelineEarlySimplificationEPCallback(
841 [this](ModulePassManager &PM, OptimizationLevel Level,
843 if (!isLTOPreLink(Phase) && getTargetTriple().isAMDGCN()) {
844 // When we are not using -fgpu-rdc, we can run accelerator code
845 // selection relatively early, but still after linking to prevent
846 // eager removal of potentially reachable symbols.
847 if (CLOpts.enable_hipstdpar) {
850 }
851
853 }
854
855 if (Level == OptimizationLevel::O0)
856 return;
857
858 // We don't want to run internalization at per-module stage.
859 if (CLOpts.internalize_symbols && !isLTOPreLink(Phase)) {
862 }
863
864 if (CLOpts.early_inline_all && !EnableFunctionCalls)
866 });
867
868 PB.registerPeepholeEPCallback(
869 [this](FunctionPassManager &FPM, OptimizationLevel Level) {
870 if (Level == OptimizationLevel::O0)
871 return;
872
874 if (CLOpts.simplify_libcall)
876
877 if (CLOpts.enable_uniform_intrinsic_combine)
879 });
880
881 PB.registerCGSCCOptimizerLateEPCallback(
882 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
883 if (Level == OptimizationLevel::O0)
884 return;
885
887
888 // Add promote kernel arguments pass to the opt pipeline right before
889 // infer address spaces which is needed to do actual address space
890 // rewriting.
891 if (Level > OptimizationLevel::O1 &&
892 CLOpts.enable_promote_kernel_arguments)
894
895 // Add infer address spaces pass to the opt pipeline after inlining
896 // but before SROA to increase SROA opportunities.
898
899 // This should run after inlining to have any chance of doing
900 // anything, and before other cleanup optimizations.
902
903 // Promote alloca to vector before SROA and loop unroll. If we
904 // manage to eliminate allocas before unroll we may choose to unroll
905 // less.
907
908 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
909 });
910
911 // FIXME: Why is AMDGPUAttributor not in CGSCC?
912 PB.registerOptimizerLastEPCallback([this](ModulePassManager &MPM,
913 OptimizationLevel Level,
915 if (Level != OptimizationLevel::O0) {
916 if (!isLTOPreLink(Phase)) {
917 if (CLOpts.attributor_enable && getTargetTriple().isAMDGCN()) {
919 MPM.addPass(AMDGPUAttributorPass(*this, Opts, Phase));
920 }
921 }
922 }
923 });
924
925 PB.registerFullLinkTimeOptimizationLastEPCallback(
926 [this](ModulePassManager &PM, OptimizationLevel Level) {
927 // Clean up redundant memory round-trips that the full-LTO pipeline,
928 // unlike the non-LTO/ThinLTO ones, otherwise leaves for codegen.
929 if (Level != OptimizationLevel::O0) {
931 EarlyCSEPass(/*UseMemorySSA=*/true)));
932 }
933
934 // When we are using -fgpu-rdc, we can only run accelerator code
935 // selection after linking to prevent, otherwise we end up removing
936 // potentially reachable symbols that were exported as external in other
937 // modules.
938 if (CLOpts.enable_hipstdpar) {
941 }
942 // We want to support the -lto-partitions=N option as "best effort".
943 // For that, we need to lower LDS earlier in the pipeline before the
944 // module is partitioned for codegen.
945 if (CLOpts.enable_lower_exec_sync)
947 if (CLOpts.enable_sw_lower_lds)
951 if (Level != OptimizationLevel::O0) {
952 // We only want to run this with O2 or higher since inliner and SROA
953 // don't run in O1.
954 if (Level != OptimizationLevel::O1) {
955 PM.addPass(
957 }
958 // Do we really need internalization in LTO?
959 if (CLOpts.internalize_symbols) {
962 }
963 if (CLOpts.attributor_enable && getTargetTriple().isAMDGCN()) {
965 if (CLOpts.link_time_closed_world)
966 Opt.IsClosedWorld = true;
969 }
970 }
971 if (!NoKernelInfoEndLTO) {
973 FPM.addPass(KernelInfoPrinter(this));
974 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
975 }
976 });
977
978 PB.registerRegClassFilterParsingCallback(
979 [](StringRef FilterName) -> RegAllocFilterFunc {
980 if (FilterName == "sgpr")
981 return onlyAllocateSGPRs;
982 if (FilterName == "vgpr")
983 return onlyAllocateVGPRs;
984 if (FilterName == "wwm")
985 return onlyAllocateWWMRegs;
986 return nullptr;
987 });
988}
989
991 unsigned SrcAS,
992 unsigned DestAS) const {
993 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
995}
996
998 if (auto *Arg = dyn_cast<Argument>(V);
999 Arg &&
1000 AMDGPU::isModuleEntryFunctionCC(Arg->getParent()->getCallingConv()) &&
1001 !Arg->hasByRefAttr())
1003
1004 const auto *LD = dyn_cast<LoadInst>(V);
1005 if (!LD) // TODO: Handle invariant load like constant.
1007
1008 // It must be a generic pointer loaded.
1009 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
1010
1011 const auto *Ptr = LD->getPointerOperand();
1012 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1014 // For a generic pointer loaded from the constant memory, it could be assumed
1015 // as a global pointer since the constant memory is only populated on the
1016 // host side. As implied by the offload programming model, only global
1017 // pointers could be referenced on the host side.
1019}
1020
1021std::pair<const Value *, unsigned>
1023 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1024 switch (II->getIntrinsicID()) {
1025 case Intrinsic::amdgcn_is_shared:
1026 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
1027 case Intrinsic::amdgcn_is_private:
1028 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
1029 default:
1030 break;
1031 }
1032 return std::pair(nullptr, -1);
1033 }
1034 // Check the global pointer predication based on
1035 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
1036 // the order of 'is_shared' and 'is_private' is not significant.
1037 Value *Ptr;
1038 if (match(
1039 const_cast<Value *>(V),
1042 m_Deferred(Ptr))))))
1043 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
1044
1045 return std::pair(nullptr, -1);
1046}
1047
1048unsigned
1063
1065 Module &M, unsigned NumParts,
1066 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1067 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
1068 // but all current users of this API don't have one ready and would need to
1069 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1070
1075
1076 PassBuilder PB(M.getContext(), this);
1077 PB.registerModuleAnalyses(MAM);
1078 PB.registerFunctionAnalyses(FAM);
1079 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1080
1082 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1083 MPM.run(M, MAM);
1084 return true;
1085}
1086
1087//===----------------------------------------------------------------------===//
1088// GCN Target Machine (SI+)
1089//===----------------------------------------------------------------------===//
1090
1092 StringRef CPU, StringRef FS,
1093 const TargetOptions &Options,
1094 std::optional<Reloc::Model> RM,
1095 std::optional<CodeModel::Model> CM,
1096 CodeGenOptLevel OL, bool JIT)
1097 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
1099 // addFastRegAlloc inserts SIWholeQuadMode after TwoAddressInstructionPass.
1101}
1102
1103enum class OOBFlagValue {
1104 Any = 0,
1107};
1108
1109/// Returns the OOB mode encoded by a module flag.
1110/// An absent flag defaults to Any.
1111static OOBFlagValue getOOBFlagValue(const Module &M, StringRef FlagName) {
1112 const auto *Flag =
1113 mdconst::dyn_extract_or_null<ConstantInt>(M.getModuleFlag(FlagName));
1114 if (!Flag)
1115 return OOBFlagValue::Any;
1116 return static_cast<OOBFlagValue>(Flag->getZExtValue());
1117}
1118
1119/// Returns the xnack/sramecc setting encoded by a module flag.
1120/// Module flag values: 0 = disabled, 1 = enabled.
1121/// An absent flag defaults to Any.
1124 StringRef FlagName) const {
1126
1127 if (CLOpts.xnack != BoolOrDefault::Default && FlagName == "amdgpu.xnack")
1128 return CLOpts.xnack == BoolOrDefault::True ? TargetIDSetting::On
1129 : TargetIDSetting::Off;
1130 if (CLOpts.sramecc != BoolOrDefault::Default && FlagName == "amdgpu.sramecc")
1131 return CLOpts.sramecc == BoolOrDefault::True ? TargetIDSetting::On
1132 : TargetIDSetting::Off;
1133
1134 const auto *Flag =
1135 mdconst::dyn_extract_or_null<ConstantInt>(M.getModuleFlag(FlagName));
1136 if (!Flag)
1137 return TargetIDSetting::Any;
1138 return Flag->getZExtValue() == 0 ? TargetIDSetting::Off : TargetIDSetting::On;
1139}
1140
1141const TargetSubtargetInfo *
1143 AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
1144 const Module *M = F.getParent();
1145 if (const GCNSubtarget *ST = LastSubtarget.lookup(FnAttrs, M))
1146 return ST;
1147
1148 SubtargetAttrs Attrs;
1149 Attrs.GPU = FnAttrs.getAttribute("target-cpu");
1150 Attrs.FS = FnAttrs.getAttribute("target-features");
1151 Attrs.BufRelaxed =
1153 Attrs.TBufRelaxed =
1155 Attrs.Xnack = getTargetIDSettingFromModuleFlag(*M, "amdgpu.xnack");
1156 Attrs.SramEcc = getTargetIDSettingFromModuleFlag(*M, "amdgpu.sramecc");
1157
1158 if (const GCNSubtarget *ST = LastSubtarget.lookup(FnAttrs, M, Attrs))
1159 return ST;
1160
1161 StringRef GPU =
1162 Attrs.GPU.isValid() ? Attrs.GPU.getValueAsString() : getTargetCPU();
1163 StringRef FS = Attrs.FS.isValid() ? Attrs.FS.getValueAsString()
1165
1167 SmallString<128> SubtargetKey(GPU);
1168 SubtargetKey.append(FS);
1169 if (Attrs.BufRelaxed)
1170 SubtargetKey.append(",buf-oob=1");
1171 if (Attrs.TBufRelaxed)
1172 SubtargetKey.append(",tbuf-oob=1");
1173 if (Attrs.Xnack != TargetIDSetting::Any) {
1174 SubtargetKey.append(",xnack=");
1175 SubtargetKey.push_back(Attrs.Xnack == TargetIDSetting::On ? '1' : '0');
1176 }
1177 if (Attrs.SramEcc != TargetIDSetting::Any) {
1178 SubtargetKey.append(",sramecc=");
1179 SubtargetKey.push_back(Attrs.SramEcc == TargetIDSetting::On ? '1' : '0');
1180 }
1181
1182 auto &I = SubtargetMap[SubtargetKey];
1183 if (!I) {
1185 Triple::SubArchType GPUSubArch = AMDGPU::getSubArch(Kind);
1186
1187 // Enforce the subtarget is covered by the subarch. Tolerate no subarch for
1188 // legacy compatibility.
1189 const Triple &TT = M->getTargetTriple();
1190 if (GPUSubArch != TT.getSubArch() && Kind != AMDGPU::GK_NONE) {
1191 // Check if this is a generic subarch which has subtargets. Ignore
1192 // unknown subtargets with a known subarch, since for whatever reason
1193 // the convention is to just print a warning and ignore unrecognized
1194 // subtargets.
1195 bool IsLegacyEmptySubArch = TT.getSubArch() == Triple::NoSubArch;
1196 if (!IsLegacyEmptySubArch &&
1197 AMDGPU::getMajorSubArch(GPUSubArch) != TT.getSubArch()) {
1198 F.getContext().emitError("invalid subtarget '" + Twine(GPU) +
1199 "' for subarch " + TT.getArchName());
1200 }
1201 }
1202
1203 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this,
1204 Attrs.BufRelaxed, Attrs.TBufRelaxed,
1205 Attrs.Xnack, Attrs.SramEcc);
1206 }
1207
1208 LastSubtarget.set(FnAttrs, M, Attrs, I.get());
1209 return I.get();
1210}
1211
1214 return TargetTransformInfo(std::make_unique<GCNTTIImpl>(this, F));
1215}
1216
1219 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
1220 const CGPassBuilderOption &Opts, MCContext &Ctx,
1222 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1223 return CGPB.buildPipeline(MPM, MAM, Out, DwoOut, FileType, Ctx);
1224}
1225
1228 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1229 if (ST.enableSIScheduler())
1231
1232 StringRef SchedStrategy =
1233 AMDGPU::getSchedStrategy(CLOpts, C->MF->getFunction());
1234
1235 if (SchedStrategy == "max-ilp")
1237
1238 if (SchedStrategy == "max-memory-clause")
1240
1241 if (SchedStrategy == "iterative-ilp")
1243
1244 if (SchedStrategy == "iterative-minreg")
1245 return createMinRegScheduler(C);
1246
1247 if (SchedStrategy == "iterative-maxocc")
1249
1250 if (SchedStrategy == "coexec") {
1251 diagnoseUnsupportedCoExecSchedulerSelection(C->MF->getFunction(), ST);
1253 }
1254
1256}
1257
1260 if (useNoopPostScheduler(CLOpts, C->MF->getFunction()))
1262
1263 ScheduleDAGMI *DAG =
1264 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1265 /*RemoveKillFlags=*/true);
1266 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1268 if (ST.shouldClusterStores())
1271 if (valueOr(CLOpts.enable_vopd, getOptLevel() >= CodeGenOptLevel::Less))
1276 return DAG;
1277}
1278//===----------------------------------------------------------------------===//
1279// AMDGPU Legacy Pass Setup
1280//===----------------------------------------------------------------------===//
1281
1282std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1283 return getStandardCSEConfigForOpt(TM->getOptLevel());
1284}
1285
1286namespace {
1287
1288class GCNPassConfig final : public AMDGPUPassConfig {
1289public:
1290 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1291 : AMDGPUPassConfig(TM, PM) {
1292 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1293 }
1294
1295 bool addPreISel() override;
1296 void addMachineSSAOptimization() override;
1297 bool addILPOpts() override;
1298 bool addInstSelector() override;
1299 bool addIRTranslator() override;
1300 void addPreLegalizeMachineIR() override;
1301 bool addLegalizeMachineIR() override;
1302 void addPreRegBankSelect() override;
1303 bool addRegBankSelect() override;
1304 void addPreGlobalInstructionSelect() override;
1305 bool addGlobalInstructionSelect() override;
1306 void addPreRegAlloc() override;
1307 void addFastRegAlloc() override;
1308 void addOptimizedRegAlloc() override;
1309
1310 FunctionPass *createSGPRAllocPass(bool Optimized);
1311 FunctionPass *createVGPRAllocPass(bool Optimized);
1312 FunctionPass *createWWMRegAllocPass(bool Optimized);
1313 FunctionPass *createRegAllocPass(bool Optimized) override;
1314
1315 void addRegAssignAndRewriteFast() override;
1316 void addRegAssignAndRewriteOptimized() override;
1317
1318 bool addPreRewrite() override;
1319 void addPostRegAlloc() override;
1320 void addPreSched2() override;
1321 void addPreEmitPass() override;
1322 void addPostBBSections() override;
1323};
1324
1325} // end anonymous namespace
1326
1328 : TargetPassConfig(TM, PM), CLOpts(getAMDGPUTargetMachine().getCLOpts()) {
1329 // Exceptions and StackMaps are not supported, so these passes will never do
1330 // anything.
1333 // Garbage collection is not supported.
1336
1337 if (CLOpts.use_ssa_machine_scheduler) {
1338 // Use SSA Machine Scheduler instead of regular Machine Scheduler.
1341 }
1342}
1343
1350
1352 if (CLOpts.loop_prefetch)
1355 // ReassociateGEPs exposes more opportunities for SLSR. See
1356 // the example in reassociate-geps-and-slsr.ll.
1358 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1359 // EarlyCSE can reuse.
1361 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1363 // NaryReassociate on GEPs creates redundant common expressions, so run
1364 // EarlyCSE after it.
1366}
1367
1370
1371 if (CLOpts.enable_remove_incompatible_functions &&
1372 TM.getTargetTriple().isAMDGCN())
1374
1375 // There is no reason to run these.
1379
1380 if (TM.getTargetTriple().isAMDGCN())
1382
1383 if (CLOpts.lower_global_ctor_dtor)
1385
1386 if (TM.getTargetTriple().isAMDGCN() &&
1387 isPassEnabled(CLOpts.enable_image_intrinsic_optimizer))
1389
1390 if (CLOpts.enable_uniform_intrinsic_combine)
1392
1393 // This can be disabled by passing ::Disable here or on the command line
1394 // with --expand-variadics-override=disable.
1396
1397 // Function calls are not supported, so make sure we inline everything.
1400
1401 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1402 if (TM.getTargetTriple().getArch() == Triple::r600)
1404
1405 // Make enqueued block runtime handles externally visible.
1407
1408 // Lower special LDS accesses.
1409 if (CLOpts.enable_lower_exec_sync)
1411
1412 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1413 if (CLOpts.enable_sw_lower_lds)
1415
1416 // Runs before PromoteAlloca so the latter can account for function uses
1419 }
1420
1421 // Run atomic optimizer before Atomic Expand
1422 if ((TM.getTargetTriple().isAMDGCN()) &&
1423 (TM.getOptLevel() >= CodeGenOptLevel::Less) &&
1424 (CLOpts.atomic_optimizer_strategy != AMDGPU::ScanOptions::None)) {
1425 addPass(createAMDGPUAtomicOptimizerPass(CLOpts.atomic_optimizer_strategy));
1426 }
1427
1429
1430 if (TM.getOptLevel() > CodeGenOptLevel::None) {
1432
1433 if (isPassEnabled(CLOpts.scalar_ir_passes))
1435
1436 if (CLOpts.enable_aa) {
1439 AAResults &AAR) {
1440 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1441 AAR.addAAResult(WrapperPass->getResult());
1442 }));
1443 }
1444
1445 if (TM.getTargetTriple().isAMDGCN()) {
1446 // TODO: May want to move later or split into an early and late one.
1447 addPass(
1448 createAMDGPUCodeGenPreparePass(CLOpts.codegenprepare_expand_div64));
1449 }
1450
1451 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1452 // have expanded.
1453 if (TM.getOptLevel() > CodeGenOptLevel::Less)
1455 }
1456
1458
1459 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1460 // example, GVN can combine
1461 //
1462 // %0 = add %a, %b
1463 // %1 = add %b, %a
1464 //
1465 // and
1466 //
1467 // %0 = shl nsw %a, 2
1468 // %1 = shl %a, 2
1469 //
1470 // but EarlyCSE can do neither of them.
1471 if (isPassEnabled(CLOpts.scalar_ir_passes))
1473}
1474
1476 if (TM->getTargetTriple().isAMDGCN() &&
1477 TM->getOptLevel() > CodeGenOptLevel::None)
1479
1480 if (TM->getTargetTriple().isAMDGCN() && CLOpts.ir_lower_kernel_arguments)
1482
1484
1485 if (isPassEnabled(CLOpts.load_store_vectorizer))
1487
1488 if (TM->getTargetTriple().isAMDGCN()) {
1489 // This lowering has been placed after codegenprepare to take advantage of
1490 // address mode matching (which is why it isn't put with the LDS lowerings).
1491 // It could be placed anywhere before uniformity annotations (an analysis
1492 // that it changes by splitting up fat pointers into their components)
1493 // but has been put before switch lowering and CFG flattening so that those
1494 // passes can run on the more optimized control flow this pass creates in
1495 // many cases.
1498 }
1499
1500 // LowerSwitch pass may introduce unreachable blocks that can
1501 // cause unexpected behavior for subsequent passes. Placing it
1502 // here seems better that these blocks would get cleaned up by
1503 // UnreachableBlockElim inserted next in the pass flow.
1505}
1506
1508 if (TM->getOptLevel() > CodeGenOptLevel::None)
1510 return false;
1511}
1512
1517
1519 // Do nothing. GC is not supported.
1520 return false;
1521}
1522
1523//===----------------------------------------------------------------------===//
1524// GCN Legacy Pass Setup
1525//===----------------------------------------------------------------------===//
1526
1527bool GCNPassConfig::addPreISel() {
1529
1530 if (TM->getOptLevel() > CodeGenOptLevel::None) {
1531 addPass(createSinkingPass());
1533 }
1534
1535 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1536 // regions formed by them.
1538 addPass(createFixIrreduciblePass());
1539 addPass(createUnifyLoopExitsPass());
1540 addPass(createStructurizeCFGPass(/*SkipUniformRegions=*/true));
1541
1544 // TODO: Move this right after structurizeCFG to avoid extra divergence
1545 // analysis. This depends on stopping SIAnnotateControlFlow from making
1546 // control flow modifications.
1548
1549 // SDAG requires LCSSA, GlobalISel does not. Disable LCSSA for -global-isel
1550 // without any of the fallback options.
1553 !isGlobalISelAbortEnabled())
1554 addPass(createLCSSAPass());
1555
1556 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1558
1559 return false;
1560}
1561
1562void GCNPassConfig::addMachineSSAOptimization() {
1564
1565 // We want to fold operands after PeepholeOptimizer has run (or as part of
1566 // it), because it will eliminate extra copies making it easier to fold the
1567 // real source operand. We want to eliminate dead instructions after, so that
1568 // we see fewer uses of the copies. We then need to clean up the dead
1569 // instructions leftover after the operands are folded as well.
1570 //
1571 // XXX - Can we get away without running DeadMachineInstructionElim again?
1572 addPass(&SIFoldOperandsLegacyID);
1573 if (CLOpts.dpp_combine)
1574 addPass(&GCNDPPCombineLegacyID);
1576 if (isPassEnabled(CLOpts.sdwa_peephole)) {
1577 addPass(&SIPeepholeSDWALegacyID);
1578 addPass(&EarlyMachineLICMID);
1579 addPass(&MachineCSELegacyID);
1580 addPass(&SIFoldOperandsLegacyID);
1581 }
1584}
1585
1586bool GCNPassConfig::addILPOpts() {
1587 if (CLOpts.early_ifcvt)
1588 addPass(&EarlyIfConverterLegacyID);
1589
1591 return false;
1592}
1593
1594bool GCNPassConfig::addInstSelector() {
1596 addPass(&SIFixSGPRCopiesLegacyID);
1598 return false;
1599}
1600
1601bool GCNPassConfig::addIRTranslator() {
1602 addPass(new IRTranslatorLegacy(getOptLevel()));
1603 return false;
1604}
1605
1606void GCNPassConfig::addPreLegalizeMachineIR() {
1607 bool IsOptLevelNone = getOptLevel() == CodeGenOptLevel::None;
1608 addPass(createAMDGPUPreLegalizeCombinerLegacyPass(IsOptLevelNone));
1609 addPass(new LocalizerLegacy());
1610}
1611
1612bool GCNPassConfig::addLegalizeMachineIR() {
1613 addPass(new LegalizerLegacy());
1614 return false;
1615}
1616
1617void GCNPassConfig::addPreRegBankSelect() {
1618 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1619 addPass(createAMDGPUPostLegalizeCombinerLegacy(IsOptNone));
1621}
1622
1623bool GCNPassConfig::addRegBankSelect() {
1626 return false;
1627}
1628
1629void GCNPassConfig::addPreGlobalInstructionSelect() {
1630 bool IsOptLevelNone = getOptLevel() == CodeGenOptLevel::None;
1631 addPass(createAMDGPURegBankCombinerLegacy(IsOptLevelNone));
1632}
1633
1634bool GCNPassConfig::addGlobalInstructionSelect() {
1635 addPass(new InstructionSelectLegacy(getOptLevel()));
1636 return false;
1637}
1638
1639void GCNPassConfig::addFastRegAlloc() {
1640 // FIXME: We have to disable the verifier here because of PHIElimination +
1641 // TwoAddressInstructions disabling it.
1642
1643 // This must be run immediately after phi elimination and before
1644 // TwoAddressInstructions, otherwise the processing of the tied operand of
1645 // SI_ELSE will introduce a copy of the tied operand source after the else.
1647
1649
1651}
1652
1653void GCNPassConfig::addPreRegAlloc() {
1654 if (getOptLevel() != CodeGenOptLevel::None)
1656}
1657
1658void GCNPassConfig::addOptimizedRegAlloc() {
1659 if (CLOpts.dce_in_ra)
1661
1662 if (CLOpts.opt_vgpr_liverange)
1664
1665 // This must be run immediately after phi elimination and before
1666 // TwoAddressInstructions, otherwise the processing of the tied operand of
1667 // SI_ELSE will introduce a copy of the tied operand source after the else.
1669
1670 if (CLOpts.enable_rewrite_partial_reg_uses)
1672
1673 // Insertion point for passes depends on whether MachineScheduler is enabled.
1674 AnalysisID EndOfPreRA = CLOpts.use_ssa_machine_scheduler
1677
1678 if (isPassEnabled(CLOpts.enable_pre_ra_optimizations))
1679 insertPass(EndOfPreRA, &GCNPreRAOptimizationsID);
1680
1681 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1682 // instructions that cause scheduling barriers.
1683 insertPass(EndOfPreRA, &SIWholeQuadModeID);
1684
1685 if (CLOpts.opt_exec_mask_pre_ra)
1686 insertPass(EndOfPreRA, &SIOptimizeExecMaskingPreRAID);
1687
1688 // This is not an essential optimization and it has a noticeable impact on
1689 // compilation time, so we only enable it from O2.
1690 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1691 insertPass(EndOfPreRA, &SIFormMemoryClausesID);
1692
1694}
1695
1696bool GCNPassConfig::addPreRewrite() {
1697 if (CLOpts.reassign_regs)
1698 addPass(&GCNNSAReassignID);
1699
1701 return true;
1702}
1703
1704FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1705 // Initialize the global default.
1708
1709 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1710 if (Ctor != useDefaultRegisterAllocator)
1711 return Ctor();
1712
1713 if (Optimized)
1715
1717}
1718
1719FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1720 // Initialize the global default.
1723
1724 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1725 if (Ctor != useDefaultRegisterAllocator)
1726 return Ctor();
1727
1728 if (Optimized)
1730
1732}
1733
1734FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1735 // Initialize the global default.
1738
1739 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1740 if (Ctor != useDefaultRegisterAllocator)
1741 return Ctor();
1742
1743 if (Optimized)
1745
1747}
1748
1749FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1750 llvm_unreachable("should not be used");
1751}
1752
1754 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1755 "and -vgpr-regalloc";
1756
1757void GCNPassConfig::addRegAssignAndRewriteFast() {
1758 if (!usingDefaultRegAlloc())
1760
1761 addPass(&GCNPreRALongBranchRegID);
1762
1763 addPass(createSGPRAllocPass(false));
1764
1765 // Equivalent of PEI for SGPRs.
1766 addPass(&SILowerSGPRSpillsLegacyID);
1767
1768 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1770
1771 // For allocating other wwm register operands.
1772 addPass(createWWMRegAllocPass(false));
1773
1774 addPass(&SILowerWWMCopiesLegacyID);
1776
1777 // For allocating per-thread VGPRs.
1778 addPass(createVGPRAllocPass(false));
1779}
1780
1781void GCNPassConfig::addRegAssignAndRewriteOptimized() {
1782 if (!usingDefaultRegAlloc())
1784
1785 addPass(&GCNPreRALongBranchRegID);
1786
1787 addPass(createSGPRAllocPass(true));
1788
1789 // Commit allocated register changes. This is mostly necessary because too
1790 // many things rely on the use lists of the physical registers, such as the
1791 // verifier. This is only necessary with allocators which use LiveIntervals,
1792 // since FastRegAlloc does the replacements itself.
1793 addPass(createVirtRegRewriter(false));
1794
1795 // At this point, the sgpr-regalloc has been done and it is good to have the
1796 // stack slot coloring to try to optimize the SGPR spill stack indices before
1797 // attempting the custom SGPR spill lowering.
1798 addPass(&StackSlotColoringID);
1799
1800 // Equivalent of PEI for SGPRs.
1801 addPass(&SILowerSGPRSpillsLegacyID);
1802
1803 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1805
1806 // For allocating other whole wave mode registers.
1807 addPass(createWWMRegAllocPass(true));
1808 addPass(&SILowerWWMCopiesLegacyID);
1809 addPass(createVirtRegRewriter(false));
1811
1812 // For allocating per-thread VGPRs.
1813 addPass(createVGPRAllocPass(true));
1814
1815 addPreRewrite();
1816 addPass(&VirtRegRewriterID);
1817
1818 addPass(createRegAllocScoringPass());
1819
1821}
1822
1823void GCNPassConfig::addPostRegAlloc() {
1824 addPass(&SIFixVGPRCopiesID);
1825 if (getOptLevel() > CodeGenOptLevel::None)
1828}
1829
1830void GCNPassConfig::addPreSched2() {
1831 if (TM->getOptLevel() > CodeGenOptLevel::None)
1833 addPass(&SIPostRABundlerLegacyID);
1834}
1835
1837 Triple::SubArchType SubArch = TT.getSubArch();
1838 return SubArch == Triple::NoSubArch ||
1839 SubArch == Triple::AMDGPUSubArch1250S ||
1841}
1842
1843void GCNPassConfig::addPreEmitPass() {
1844 if (isPassEnabled(CLOpts.enable_vopd, CodeGenOptLevel::Less))
1845 addPass(&GCNCreateVOPDID);
1846 addPass(createSIMemoryLegalizerPass());
1847 if (getOptLevel() > CodeGenOptLevel::None)
1849 if (mayNeedAsyncBarrierArriveWorkaround(TM->getTargetTriple()))
1851 addPass(createSIInsertWaitcntsPass());
1852
1853 addPass(createSIModeRegisterPass());
1854
1855 if (getOptLevel() > CodeGenOptLevel::None)
1856 addPass(&SIInsertHardClausesID);
1857
1859 if (CLOpts.set_wave_priority)
1861 if (getOptLevel() > CodeGenOptLevel::None)
1862 addPass(&SIPreEmitPeepholeID);
1863 // The hazard recognizer that runs as part of the post-ra scheduler does not
1864 // guarantee to be able handle all hazards correctly. This is because if there
1865 // are multiple scheduling regions in a basic block, the regions are scheduled
1866 // bottom up, so when we begin to schedule a region we don't know what
1867 // instructions were emitted directly before it.
1868 //
1869 // Here we add a stand-alone hazard recognizer pass which can handle all
1870 // cases.
1871 addPass(&PostRAHazardRecognizerID);
1872
1874
1876
1877 if (isPassEnabled(CLOpts.enable_delay_alu, CodeGenOptLevel::Less))
1878 addPass(&AMDGPUInsertDelayAluID);
1879
1880 addPass(&BranchRelaxationPassID);
1881}
1882
1883void GCNPassConfig::addPostBBSections() {
1884 // We run this later to avoid passes like livedebugvalues and BBSections
1885 // having to deal with the apparent multi-entry functions we may generate.
1887}
1888
1890 return new GCNPassConfig(*this, PM);
1891}
1892
1898
1905
1909
1916
1919 SMDiagnostic &Error, SMRange &SourceRange) const {
1920 const yaml::SIMachineFunctionInfo &YamlMFI =
1921 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1922 MachineFunction &MF = PFS.MF;
1924 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1925
1926 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1927 return true;
1928
1929 if (MFI->Occupancy == 0) {
1930 // Fixup the subtarget dependent default value.
1931 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1932 }
1933
1934 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1935 Register TempReg;
1936 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1937 SourceRange = RegName.SourceRange;
1938 return true;
1939 }
1940 RegVal = TempReg;
1941
1942 return false;
1943 };
1944
1945 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1946 Register &RegVal) {
1947 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1948 };
1949
1950 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
1951 return true;
1952
1953 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
1954 return true;
1955
1956 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
1957 MFI->LongBranchReservedReg))
1958 return true;
1959
1960 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1961 // Create a diagnostic for a the register string literal.
1962 const MemoryBuffer &Buffer =
1963 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1965 *PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1966 static_cast<int>(RegName.Value.size()), SourceMgr::DK_Error,
1967 "incorrect register class for field", RegName.Value, {}, {});
1968 SourceRange = RegName.SourceRange;
1969 return true;
1970 };
1971
1972 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1973 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1974 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1975 return true;
1976
1977 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1978 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1979 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1980 }
1981
1982 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1983 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1984 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1985 }
1986
1987 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1988 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1989 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1990 }
1991
1992 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
1993 Register ParsedReg;
1994 if (parseRegister(YamlReg, ParsedReg))
1995 return true;
1996
1997 MFI->reserveWWMRegister(ParsedReg);
1998 }
1999
2000 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
2001 MFI->setFlag(Info->VReg, Info->Flags);
2002 }
2003 for (const auto &[_, Info] : PFS.VRegInfos) {
2004 MFI->setFlag(Info->VReg, Info->Flags);
2005 }
2006
2007 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
2008 Register ParsedReg;
2009 if (parseRegister(YamlRegStr, ParsedReg))
2010 return true;
2011 MFI->SpillPhysVGPRs.push_back(ParsedReg);
2012 }
2013
2014 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
2015 const TargetRegisterClass &RC,
2016 ArgDescriptor &Arg, unsigned UserSGPRs,
2017 unsigned SystemSGPRs) {
2018 // Skip parsing if it's not present.
2019 if (!A)
2020 return false;
2021
2022 if (A->IsRegister) {
2023 Register Reg;
2024 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
2025 SourceRange = A->RegisterName.SourceRange;
2026 return true;
2027 }
2028 if (!RC.contains(Reg))
2029 return diagnoseRegisterClass(A->RegisterName);
2031 } else
2032 Arg = ArgDescriptor::createStack(A->StackOffset);
2033 // Check and apply the optional mask.
2034 if (A->Mask)
2035 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
2036
2037 MFI->NumUserSGPRs += UserSGPRs;
2038 MFI->NumSystemSGPRs += SystemSGPRs;
2039 return false;
2040 };
2041
2042 if (YamlMFI.ArgInfo &&
2043 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
2044 AMDGPU::SGPR_128RegClass,
2045 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
2046 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
2047 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
2048 2, 0) ||
2049 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
2050 MFI->ArgInfo.QueuePtr, 2, 0) ||
2051 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
2052 AMDGPU::SReg_64RegClass,
2053 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
2054 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
2055 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
2056 2, 0) ||
2057 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
2058 AMDGPU::SReg_64RegClass,
2059 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
2060 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
2061 AMDGPU::SGPR_32RegClass,
2062 MFI->ArgInfo.PrivateSegmentSize, 1, 0) ||
2063 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
2064 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.LDSKernelId,
2065 1, 0) ||
2066 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
2067 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
2068 0, 1) ||
2069 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
2070 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
2071 0, 1) ||
2072 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
2073 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
2074 0, 1) ||
2075 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
2076 AMDGPU::SGPR_32RegClass,
2077 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
2078 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
2079 AMDGPU::SGPR_32RegClass,
2080 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
2081 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
2082 AMDGPU::SReg_64RegClass,
2083 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
2084 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
2085 AMDGPU::SReg_64RegClass,
2086 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
2087 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
2088 AMDGPU::VGPR_32RegClass, MFI->ArgInfo.WorkItemIDX,
2089 0, 0) ||
2090 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
2091 AMDGPU::VGPR_32RegClass, MFI->ArgInfo.WorkItemIDY,
2092 0, 0) ||
2093 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
2094 AMDGPU::VGPR_32RegClass, MFI->ArgInfo.WorkItemIDZ,
2095 0, 0)))
2096 return true;
2097
2098 // Parse FirstKernArgPreloadReg separately, since it's a Register,
2099 // not ArgDescriptor.
2100 if (YamlMFI.ArgInfo && YamlMFI.ArgInfo->FirstKernArgPreloadReg) {
2101 const yaml::SIArgument &A = *YamlMFI.ArgInfo->FirstKernArgPreloadReg;
2102
2103 if (!A.IsRegister) {
2104 // For stack arguments, we don't have RegisterName.SourceRange,
2105 // but we should have some location info from the YAML parser
2106 const MemoryBuffer &Buffer =
2107 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2108 // Create a minimal valid source range
2110 SMRange Range(Loc, Loc);
2111
2113 *PFS.SM, Loc, Buffer.getBufferIdentifier(), 1, 0, SourceMgr::DK_Error,
2114 "firstKernArgPreloadReg must be a register, not a stack location", "",
2115 {}, {});
2116
2117 SourceRange = Range;
2118 return true;
2119 }
2120
2121 Register Reg;
2122 if (parseNamedRegisterReference(PFS, Reg, A.RegisterName.Value, Error)) {
2123 SourceRange = A.RegisterName.SourceRange;
2124 return true;
2125 }
2126
2127 if (!AMDGPU::SGPR_32RegClass.contains(Reg))
2128 return diagnoseRegisterClass(A.RegisterName);
2129
2130 MFI->ArgInfo.FirstKernArgPreloadReg = Reg;
2131 MFI->NumUserSGPRs += YamlMFI.NumKernargPreloadSGPRs;
2132 }
2133
2134 if (ST.hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode)) {
2135 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
2136 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
2137 }
2138
2139 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
2140 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
2143 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
2146
2153
2154 if (YamlMFI.HasInitWholeWave)
2155 MFI->setInitWholeWave();
2156
2157 return false;
2158}
2159
2160//===----------------------------------------------------------------------===//
2161// AMDGPU CodeGen Pass Builder interface.
2162//===----------------------------------------------------------------------===//
2163
2164AMDGPUCodeGenPassBuilder::AMDGPUCodeGenPassBuilder(
2165 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
2167 : CodeGenPassBuilder(TM, Opts, PIC), CLOpts(TM.getCLOpts()) {
2168 Opt.MISchedPostRA = true;
2169 Opt.RequiresCodeGenSCCOrder = true;
2170 Opt.EnableSSAMachineScheduler = CLOpts.use_ssa_machine_scheduler;
2171 // Exceptions and StackMaps are not supported, so these passes will never do
2172 // anything.
2173 // Garbage collection is not supported.
2174 disablePass<StackMapLivenessPass, FuncletLayoutPass, PatchableFunctionPass,
2176
2177 // If enabled, use the SSA machine scheduler instead of the regular machine
2178 // scheduler.
2179 if (Opt.EnableSSAMachineScheduler)
2180 disablePass<MachineSchedulerPass>();
2181}
2182
2183void AMDGPUCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) {
2184 if (CLOpts.enable_remove_incompatible_functions &&
2185 TM.getTargetTriple().isAMDGCN()) {
2186 flushFPMsToMPM(PMW);
2187 addModulePass(AMDGPURemoveIncompatibleFunctionsPass(TM), PMW);
2188 }
2189
2190 flushFPMsToMPM(PMW);
2191
2192 if (TM.getTargetTriple().isAMDGCN())
2193 addModulePass(AMDGPUPrintfRuntimeBindingPass(), PMW);
2194
2195 if (CLOpts.lower_global_ctor_dtor)
2196 addModulePass(AMDGPUCtorDtorLoweringPass(), PMW);
2197
2198 if (isPassEnabled(CLOpts.enable_image_intrinsic_optimizer))
2199 addFunctionPass(AMDGPUImageIntrinsicOptimizerPass(TM), PMW);
2200
2201 if (CLOpts.enable_uniform_intrinsic_combine)
2202 addFunctionPass(AMDGPUUniformIntrinsicCombinePass(), PMW);
2203 // This can be disabled by passing ::Disable here or on the command line
2204 // with --expand-variadics-override=disable.
2205 flushFPMsToMPM(PMW);
2207
2208 addModulePass(AMDGPUAlwaysInlinePass(), PMW);
2209 addModulePass(AlwaysInlinerPass(), PMW);
2210
2211 addModulePass(AMDGPUExportKernelRuntimeHandlesPass(), PMW);
2212
2213 if (CLOpts.enable_lower_exec_sync)
2214 addModulePass(AMDGPULowerExecSyncPass(), PMW);
2215
2216 if (CLOpts.enable_sw_lower_lds)
2217 addModulePass(AMDGPUSwLowerLDSPass(), PMW);
2218
2219 // Runs before PromoteAlloca so the latter can account for function uses
2221 addModulePass(AMDGPULowerModuleLDSPass(getTM()), PMW);
2222
2223 // Run atomic optimizer before Atomic Expand
2224 if (TM.getOptLevel() >= CodeGenOptLevel::Less &&
2225 (CLOpts.atomic_optimizer_strategy != AMDGPU::ScanOptions::None))
2226 addFunctionPass(
2227 AMDGPUAtomicOptimizerPass(TM, CLOpts.atomic_optimizer_strategy), PMW);
2228
2229 addFunctionPass(AtomicExpandPass(TM), PMW);
2230
2232 addFunctionPass(AMDGPUPromoteAllocaPass(TM), PMW);
2233 if (isPassEnabled(CLOpts.scalar_ir_passes))
2234 addStraightLineScalarOptimizationPasses(PMW);
2235
2236 // TODO: Handle CLOpts.enable_aa
2237
2238 // TODO: May want to move later or split into an early and late one.
2239 addFunctionPass(AMDGPUCodeGenPreparePass(TM), PMW);
2240
2241 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
2242 // have expanded.
2245 /*UseMemorySSA=*/true),
2246 PMW);
2247 }
2248 }
2249
2250 Base::addIRPasses(PMW);
2251
2252 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2253 // example, GVN can combine
2254 //
2255 // %0 = add %a, %b
2256 // %1 = add %b, %a
2257 //
2258 // and
2259 //
2260 // %0 = shl nsw %a, 2
2261 // %1 = shl %a, 2
2262 //
2263 // but EarlyCSE can do neither of them.
2264 if (isPassEnabled(CLOpts.scalar_ir_passes))
2265 addEarlyCSEOrGVNPass(PMW);
2266}
2267
2268void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(PassManagerWrapper &PMW) {
2270 flushFPMsToMPM(PMW);
2271 addModulePass(AMDGPUPreloadKernelArgumentsPass(TM), PMW);
2272 }
2273
2274 if (CLOpts.ir_lower_kernel_arguments)
2275 addFunctionPass(AMDGPULowerKernelArgumentsPass(TM), PMW);
2276
2277 Base::addCodeGenPrepare(PMW);
2278
2279 if (isPassEnabled(CLOpts.load_store_vectorizer))
2280 addFunctionPass(LoadStoreVectorizerPass(), PMW);
2281
2282 // This lowering has been placed after codegenprepare to take advantage of
2283 // address mode matching (which is why it isn't put with the LDS lowerings).
2284 // It could be placed anywhere before uniformity annotations (an analysis
2285 // that it changes by splitting up fat pointers into their components)
2286 // but has been put before switch lowering and CFG flattening so that those
2287 // passes can run on the more optimized control flow this pass creates in
2288 // many cases.
2289 flushFPMsToMPM(PMW);
2290 addModulePass(AMDGPULowerBufferFatPointersPass(TM), PMW);
2291 flushFPMsToMPM(PMW);
2292 requireCGSCCOrder(PMW);
2293
2294 addModulePass(AMDGPULowerIntrinsicsPass(getTM()), PMW);
2295
2296 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2297 // behavior for subsequent passes. Placing it here seems better that these
2298 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2299 // pass flow.
2300 addFunctionPass(LowerSwitchPass(), PMW);
2301}
2302
2303void AMDGPUCodeGenPassBuilder::addPreISel(PassManagerWrapper &PMW) {
2304
2306 addFunctionPass(FlattenCFGPass(), PMW);
2307 addFunctionPass(SinkingPass(), PMW);
2308 addFunctionPass(AMDGPULateCodeGenPreparePass(getTM()), PMW);
2309 }
2310
2311 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2312 // regions formed by them.
2313
2314 addFunctionPass(AMDGPUUnifyDivergentExitNodesPass(), PMW);
2315 addFunctionPass(FixIrreduciblePass(), PMW);
2316 addFunctionPass(UnifyLoopExitsPass(), PMW);
2317 addFunctionPass(StructurizeCFGPass(/*SkipUniformRegions=*/true), PMW);
2318
2319 addFunctionPass(AMDGPUAnnotateUniformValuesPass(), PMW);
2320
2321 addFunctionPass(SIAnnotateControlFlowPass(getTM()), PMW);
2322
2323 // TODO: Move this right after structurizeCFG to avoid extra divergence
2324 // analysis. This depends on stopping SIAnnotateControlFlow from making
2325 // control flow modifications.
2326 addFunctionPass(AMDGPURewriteUndefForPHIPass(), PMW);
2327
2328 if (getCGPassBuilderOption(TM).EnableGlobalISelOption !=
2330 !isGlobalISelAbortEnabled())
2331 addFunctionPass(LCSSAPass(), PMW);
2332
2334 flushFPMsToMPM(PMW);
2335 addModulePass(AMDGPUPerfHintAnalysisPass(getTM()), PMW);
2336 }
2337}
2338
2339void AMDGPUCodeGenPassBuilder::addILPOpts(PassManagerWrapper &PMW) {
2340 if (CLOpts.early_ifcvt)
2341 addMachineFunctionPass(EarlyIfConverterPass(), PMW);
2342
2343 Base::addILPOpts(PMW);
2344}
2345
2346void AMDGPUCodeGenPassBuilder::addAsmPrinterBegin(PassManagerWrapper &PMW) {
2347 addModulePass(AMDGPUAsmPrinterBeginPass(), PMW,
2348 /*Force=*/true);
2349}
2350
2351void AMDGPUCodeGenPassBuilder::addAsmPrinter(PassManagerWrapper &PMW) {
2352 addMachineFunctionPass(AMDGPUAsmPrinterPass(), PMW);
2353}
2354
2355void AMDGPUCodeGenPassBuilder::addAsmPrinterEnd(PassManagerWrapper &PMW) {
2356 addModulePass(AMDGPUAsmPrinterEndPass(), PMW);
2357}
2358
2359Error AMDGPUCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) {
2360 addMachineFunctionPass(AMDGPUISelDAGToDAGPass(TM), PMW);
2361 addMachineFunctionPass(SIFixSGPRCopiesPass(), PMW);
2362 addMachineFunctionPass(SILowerI1CopiesPass(), PMW);
2363 return Error::success();
2364}
2365
2366Error AMDGPUCodeGenPassBuilder::addIRTranslator(PassManagerWrapper &PMW) {
2367 addMachineFunctionPass(IRTranslatorPass(getOptLevel()), PMW);
2368 return Error::success();
2369}
2370
2371void AMDGPUCodeGenPassBuilder::addPreLegalizeMachineIR(
2372 PassManagerWrapper &PMW) {
2373 addMachineFunctionPass(AMDGPUPreLegalizerCombinerPass(), PMW);
2374 addMachineFunctionPass(LocalizerPass(), PMW);
2375}
2376
2377Error AMDGPUCodeGenPassBuilder::addLegalizeMachineIR(PassManagerWrapper &PMW) {
2378 addMachineFunctionPass(LegalizerPass(), PMW);
2379 return Error::success();
2380}
2381
2382void AMDGPUCodeGenPassBuilder::addPreRegBankSelect(PassManagerWrapper &PMW) {
2383 addMachineFunctionPass(AMDGPUPostLegalizerCombinerPass(), PMW);
2384 addMachineFunctionPass(AMDGPUGlobalISelDivergenceLoweringPass(), PMW);
2385}
2386
2387Error AMDGPUCodeGenPassBuilder::addRegBankSelect(PassManagerWrapper &PMW) {
2388 addMachineFunctionPass(AMDGPURegBankSelectPass(), PMW);
2389 addMachineFunctionPass(AMDGPURegBankLegalizePass(), PMW);
2390 return Error::success();
2391}
2392
2393void AMDGPUCodeGenPassBuilder::addPreGlobalInstructionSelect(
2394 PassManagerWrapper &PMW) {
2395 bool IsOptLevelNone = getOptLevel() == CodeGenOptLevel::None;
2396 addMachineFunctionPass(AMDGPURegBankCombinerPass(IsOptLevelNone), PMW);
2397}
2398
2399Error AMDGPUCodeGenPassBuilder::addGlobalInstructionSelect(
2400 PassManagerWrapper &PMW) {
2401 addMachineFunctionPass(InstructionSelectPass(getOptLevel()), PMW);
2402 return Error::success();
2403}
2404
2405void AMDGPUCodeGenPassBuilder::addPreRewrite(PassManagerWrapper &PMW) {
2406 if (CLOpts.reassign_regs) {
2407 addMachineFunctionPass(GCNNSAReassignPass(), PMW);
2408 }
2409
2410 addMachineFunctionPass(AMDGPURewriteAGPRCopyMFMAPass(), PMW);
2411}
2412
2413void AMDGPUCodeGenPassBuilder::addMachineSSAOptimization(
2414 PassManagerWrapper &PMW) {
2415 Base::addMachineSSAOptimization(PMW);
2416
2417 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2418 if (CLOpts.dpp_combine) {
2419 addMachineFunctionPass(GCNDPPCombinePass(), PMW);
2420 }
2421 addMachineFunctionPass(SILoadStoreOptimizerPass(), PMW);
2422 if (isPassEnabled(CLOpts.sdwa_peephole)) {
2423 addMachineFunctionPass(SIPeepholeSDWAPass(), PMW);
2424 addMachineFunctionPass(EarlyMachineLICMPass(), PMW);
2425 addMachineFunctionPass(MachineCSEPass(), PMW);
2426 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2427 }
2428 addMachineFunctionPass(DeadMachineInstructionElimPass(), PMW);
2429 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2430}
2431
2432Error AMDGPUCodeGenPassBuilder::addFastRegAlloc(PassManagerWrapper &PMW) {
2433 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2434
2435 insertPass<TwoAddressInstructionPass>(SIWholeQuadModePass());
2436
2437 return Base::addFastRegAlloc(PMW);
2438}
2439
2440Error AMDGPUCodeGenPassBuilder::addRegAssignAndRewriteFast(
2441 PassManagerWrapper &PMW) {
2442 if (auto Err = validateRegAllocOptions())
2443 return Err;
2444
2445 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2446
2447 // SGPR allocation - default to fast at -O0.
2449 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2450 else
2451 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2452 PMW);
2453
2454 // Equivalent of PEI for SGPRs.
2455 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2456
2457 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2458 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2459
2460 // WWM allocation - default to fast at -O0.
2462 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2463 else
2464 addMachineFunctionPass(
2465 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2466
2467 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2468 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2469
2470 // VGPR allocation - default to fast at -O0.
2472 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2473 else
2474 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2475
2476 return Error::success();
2477}
2478
2479Error AMDGPUCodeGenPassBuilder::addOptimizedRegAlloc(PassManagerWrapper &PMW) {
2480 if (CLOpts.dce_in_ra)
2481 insertPass<DetectDeadLanesPass>(DeadMachineInstructionElimPass());
2482
2483 if (CLOpts.opt_vgpr_liverange)
2484 insertPass<RequireAnalysisPass<MachineLoopAnalysis, MachineFunction>>(
2486
2487 // This must be run immediately after phi elimination and before
2488 // TwoAddressInstructions, otherwise the processing of the tied operand of
2489 // SI_ELSE will introduce a copy of the tied operand source after the else.
2490 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2491
2492 if (CLOpts.enable_rewrite_partial_reg_uses)
2493 insertPass<RenameIndependentSubregsPass>(GCNRewritePartialRegUsesPass());
2494
2495 // Following passes run at the end of the pre-RA pipeline, so the pass they
2496 // are anchored on depends on which scheduler is enabled.
2497 auto insertAtEndOfPreRA = [this](auto &&Pass) {
2498 if (Opt.EnableSSAMachineScheduler)
2499 insertPass<RenameIndependentSubregsPass>(std::move(Pass));
2500 else
2501 insertPass<MachineSchedulerPass>(std::move(Pass));
2502 };
2503
2504 if (isPassEnabled(CLOpts.enable_pre_ra_optimizations))
2505 insertAtEndOfPreRA(GCNPreRAOptimizationsPass());
2506
2507 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
2508 // instructions that cause scheduling barriers.
2509 insertAtEndOfPreRA(SIWholeQuadModePass());
2510
2511 if (CLOpts.opt_exec_mask_pre_ra)
2512 insertAtEndOfPreRA(SIOptimizeExecMaskingPreRAPass());
2513
2514 // This is not an essential optimization and it has a noticeable impact on
2515 // compilation time, so we only enable it from O2.
2517 insertAtEndOfPreRA(SIFormMemoryClausesPass());
2518
2519 return Base::addOptimizedRegAlloc(PMW);
2520}
2521
2522void AMDGPUCodeGenPassBuilder::addPreRegAlloc(PassManagerWrapper &PMW) {
2523 if (getOptLevel() != CodeGenOptLevel::None)
2524 addMachineFunctionPass(AMDGPUPrepareAGPRAllocPass(), PMW);
2525}
2526
2527Error AMDGPUCodeGenPassBuilder::addRegAssignAndRewriteOptimized(
2528 PassManagerWrapper &PMW) {
2529 if (auto Err = validateRegAllocOptions())
2530 return Err;
2531
2532 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2533
2534 // SGPR allocation - default to greedy at -O1 and above.
2536 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2537 PMW);
2538 else
2539 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2540
2541 // Commit allocated register changes. This is mostly necessary because too
2542 // many things rely on the use lists of the physical registers, such as the
2543 // verifier. This is only necessary with allocators which use LiveIntervals,
2544 // since FastRegAlloc does the replacements itself.
2545 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2546
2547 // At this point, the sgpr-regalloc has been done and it is good to have the
2548 // stack slot coloring to try to optimize the SGPR spill stack indices before
2549 // attempting the custom SGPR spill lowering.
2550 addMachineFunctionPass(StackSlotColoringPass(), PMW);
2551
2552 // Equivalent of PEI for SGPRs.
2553 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2554
2555 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2556 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2557
2558 // WWM allocation - default to greedy at -O1 and above.
2560 addMachineFunctionPass(
2561 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2562 else
2563 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2564 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2565 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2566 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2567
2568 // VGPR allocation - default to greedy at -O1 and above.
2570 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2571 else
2572 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2573
2574 addPreRewrite(PMW);
2575 addMachineFunctionPass(VirtRegRewriterPass(true), PMW);
2576
2577 addMachineFunctionPass(AMDGPUMarkLastScratchLoadPass(), PMW);
2578 return Error::success();
2579}
2580
2581void AMDGPUCodeGenPassBuilder::addPostRegAlloc(PassManagerWrapper &PMW) {
2582 addMachineFunctionPass(SIFixVGPRCopiesPass(), PMW);
2584 addMachineFunctionPass(SIOptimizeExecMaskingPass(), PMW);
2585 Base::addPostRegAlloc(PMW);
2586}
2587
2588void AMDGPUCodeGenPassBuilder::addPreSched2(PassManagerWrapper &PMW) {
2590 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2591 addMachineFunctionPass(SIPostRABundlerPass(), PMW);
2592}
2593
2594void AMDGPUCodeGenPassBuilder::addPostBBSections(PassManagerWrapper &PMW) {
2595 // We run this later to avoid passes like livedebugvalues and BBSections
2596 // having to deal with the apparent multi-entry functions we may generate.
2597 addMachineFunctionPass(AMDGPUPreloadKernArgPrologPass(), PMW);
2598}
2599
2600void AMDGPUCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) {
2601 if (isPassEnabled(CLOpts.enable_vopd, CodeGenOptLevel::Less)) {
2602 addMachineFunctionPass(GCNCreateVOPDPass(), PMW);
2603 }
2604
2605 addMachineFunctionPass(SIMemoryLegalizerPass(), PMW);
2607 addMachineFunctionPass(SIPostRA16BitMovFoldingPass(), PMW);
2609 addMachineFunctionPass(SIInsertAsyncBarrierArriveWorkaroundPass(), PMW);
2610 addMachineFunctionPass(SIInsertWaitcntsPass(), PMW);
2611
2612 addMachineFunctionPass(SIModeRegisterPass(), PMW);
2613
2615 addMachineFunctionPass(SIInsertHardClausesPass(), PMW);
2616
2617 addMachineFunctionPass(SILateBranchLoweringPass(), PMW);
2618
2619 if (CLOpts.set_wave_priority)
2620 addMachineFunctionPass(AMDGPUSetWavePriorityPass(), PMW);
2621
2623 addMachineFunctionPass(SIPreEmitPeepholePass(), PMW);
2624
2625 // The hazard recognizer that runs as part of the post-ra scheduler does not
2626 // guarantee to be able handle all hazards correctly. This is because if there
2627 // are multiple scheduling regions in a basic block, the regions are scheduled
2628 // bottom up, so when we begin to schedule a region we don't know what
2629 // instructions were emitted directly before it.
2630 //
2631 // Here we add a stand-alone hazard recognizer pass which can handle all
2632 // cases.
2633 addMachineFunctionPass(PostRAHazardRecognizerPass(), PMW);
2634 addMachineFunctionPass(AMDGPUWaitSGPRHazardsPass(), PMW);
2635 addMachineFunctionPass(AMDGPULowerVGPREncodingPass(), PMW);
2636
2637 if (isPassEnabled(CLOpts.enable_delay_alu, CodeGenOptLevel::Less)) {
2638 addMachineFunctionPass(AMDGPUInsertDelayAluPass(), PMW);
2639 }
2640
2641 addMachineFunctionPass(BranchRelaxationPass(), PMW);
2642}
2643
2644bool AMDGPUCodeGenPassBuilder::isPassEnabled(BoolOrDefault Opt,
2645 CodeGenOptLevel Level) const {
2646 return valueOr(Opt, TM.getOptLevel() >= Level);
2647}
2648
2649void AMDGPUCodeGenPassBuilder::addEarlyCSEOrGVNPass(PassManagerWrapper &PMW) {
2651 addFunctionPass(GVNPass(), PMW);
2652 else
2653 addFunctionPass(EarlyCSEPass(), PMW);
2654}
2655
2656void AMDGPUCodeGenPassBuilder::addStraightLineScalarOptimizationPasses(
2657 PassManagerWrapper &PMW) {
2658 if (CLOpts.loop_prefetch)
2659 addFunctionPass(LoopDataPrefetchPass(), PMW);
2660
2661 addFunctionPass(SeparateConstOffsetFromGEPPass(), PMW);
2662
2663 // ReassociateGEPs exposes more opportunities for SLSR. See
2664 // the example in reassociate-geps-and-slsr.ll.
2665 addFunctionPass(StraightLineStrengthReducePass(), PMW);
2666
2667 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2668 // EarlyCSE can reuse.
2669 addEarlyCSEOrGVNPass(PMW);
2670
2671 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2672 addFunctionPass(NaryReassociatePass(), PMW);
2673
2674 // NaryReassociate on GEPs creates redundant common expressions, so run
2675 // EarlyCSE after it.
2676 addFunctionPass(EarlyCSEPass(), PMW);
2677}
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
unsigned NumParts
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static std::unique_ptr< TargetLoweringObjectFile > createTLOF(const Triple &TT)
This is the AMGPU address space based alias analysis pass.
AMDGPU Assembly printer class.
Coexecution-focused scheduling strategy for AMDGPU.
Defines an instruction selector for the AMDGPU target.
Analyzes if a function potentially memory bound and if a kernel kernel may benefit from limiting numb...
Analyzes how many registers and other resources are used by functions.
static cl::opt< RegAllocType, false, RegAllocTypeParser > SGPRRegAllocNPM("sgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default), cl::desc("Register allocator for SGPRs (new pass manager)"))
static cl::opt< bool, true > EnableLowerModuleLDS("amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"), cl::location(AMDGPUTargetMachine::EnableLowerModuleLDS), cl::init(true), cl::Hidden)
static VGPRRegisterRegAlloc greedyRegAllocVGPR("greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator)
static MachineSchedRegistry GCNMaxMemoryClauseSchedRegistry("gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause", createGCNMaxMemoryClauseMachineScheduler)
static Reloc::Model getEffectiveRelocModel()
static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag
static Error checkRegAllocSupported(RegAllocType RAType, StringRef RegName)
Check if the given RegAllocType is supported for AMDGPU NPM register allocation.
static MachineSchedRegistry SISchedRegistry("si", "Run SI's custom scheduler", createSIMachineScheduler)
static ScheduleDAGInstrs * createIterativeILPMachineScheduler(MachineSchedContext *C)
static bool useNoopPostScheduler(const AMDGPUOptions &CLOpts, const Function &F)
static SGPRRegisterRegAlloc defaultSGPRRegAlloc("default", "pick SGPR register allocator based on -O option", useDefaultRegisterAllocator)
static OOBFlagValue getOOBFlagValue(const Module &M, StringRef FlagName)
Returns the OOB mode encoded by a module flag.
static FunctionPass * useDefaultRegisterAllocator()
-{sgpr|wwm|vgpr}-regalloc=... command line option.
static cl::opt< bool, true > EnableObjectLinking("amdgpu-enable-object-linking", cl::desc("Enable object linking for cross-TU LDS and ABI support"), cl::location(AMDGPUTargetMachine::EnableObjectLinking), cl::init(false), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxILPMachineScheduler(MachineSchedContext *C)
static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag
A dummy default pass factory indicates whether the register allocator is overridden on the command li...
static FunctionPass * createFastVGPRRegisterAllocator()
static FunctionPass * createGreedyWWMRegisterAllocator()
static SGPRRegisterRegAlloc fastRegAllocSGPR("fast", "fast register allocator", createFastSGPRRegisterAllocator)
static MachineSchedRegistry GCNMinRegSchedRegistry("gcn-iterative-minreg", "Run GCN iterative scheduler for minimal register usage (experimental)", createMinRegScheduler)
static SGPRRegisterRegAlloc greedyRegAllocSGPR("greedy", "greedy register allocator", createGreedySGPRRegisterAllocator)
static void diagnoseUnsupportedCoExecSchedulerSelection(const Function &F, const GCNSubtarget &ST)
static ScheduleDAGInstrs * createGCNMaxMemoryClauseMachineScheduler(MachineSchedContext *C)
static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)
static WWMRegisterRegAlloc greedyRegAllocWWMReg("greedy", "greedy register allocator", createGreedyWWMRegisterAllocator)
static FunctionPass * createFastSGPRRegisterAllocator()
static Expected< AMDGPU::ScanOptions > parseAMDGPUAtomicOptimizerStrategy(StringRef Params)
static FunctionPass * createGreedyVGPRRegisterAllocator()
static WWMRegisterRegAlloc basicRegAllocWWMReg("basic", "basic register allocator", createBasicWWMRegisterAllocator)
static cl::opt< RegAllocType, false, RegAllocTypeParser > WWMRegAllocNPM("wwm-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default), cl::desc("Register allocator for WWM registers (new pass manager)"))
static MachineSchedRegistry IterativeGCNMaxOccupancySchedRegistry("gcn-iterative-max-occupancy-experimental", "Run GCN scheduler to maximize occupancy (experimental)", createIterativeGCNMaxOccupancyMachineScheduler)
static void initializeDefaultWWMRegisterAllocatorOnce()
static bool onlyAllocateWWMRegs(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)
static cl::opt< WWMRegisterRegAlloc::FunctionPassCtor, false, RegisterPassParser< WWMRegisterRegAlloc > > WWMRegAlloc("wwm-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), cl::desc("Register allocator to use for WWM registers"))
static cl::opt< RegAllocType, false, RegAllocTypeParser > VGPRRegAllocNPM("vgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default), cl::desc("Register allocator for VGPRs (new pass manager)"))
static cl::opt< VGPRRegisterRegAlloc::FunctionPassCtor, false, RegisterPassParser< VGPRRegisterRegAlloc > > VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), cl::desc("Register allocator to use for VGPRs"))
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget()
static MachineSchedRegistry GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp", createGCNMaxILPMachineScheduler)
static FunctionPass * createGreedySGPRRegisterAllocator()
static LLVM_READNONE StringRef getGPUOrDefault(const Triple &TT, StringRef GPU)
Expected< AMDGPUAttributorOptions > parseAMDGPUAttributorPassOptions(StringRef Params)
static ScheduleDAGInstrs * createMinRegScheduler(MachineSchedContext *C)
static void initializeDefaultVGPRRegisterAllocatorOnce()
static ScheduleDAGInstrs * createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static FunctionPass * createFastWWMRegisterAllocator()
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
static FunctionPass * createBasicVGPRRegisterAllocator()
static VGPRRegisterRegAlloc basicRegAllocVGPR("basic", "basic register allocator", createBasicVGPRRegisterAllocator)
static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator", createFastWWMRegisterAllocator)
static VGPRRegisterRegAlloc fastRegAllocVGPR("fast", "fast register allocator", createFastVGPRRegisterAllocator)
static SGPRRegisterRegAlloc basicRegAllocSGPR("basic", "basic register allocator", createBasicSGPRRegisterAllocator)
static llvm::once_flag InitializeDefaultWWMRegisterAllocatorFlag
static cl::opt< SGPRRegisterRegAlloc::FunctionPassCtor, false, RegisterPassParser< SGPRRegisterRegAlloc > > SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), cl::desc("Register allocator to use for SGPRs"))
static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)
static ScheduleDAGInstrs * createSIMachineScheduler(MachineSchedContext *C)
static void initializeDefaultSGPRRegisterAllocatorOnce()
static ScheduleDAGInstrs * createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static MachineSchedRegistry GCNILPSchedRegistry("gcn-iterative-ilp", "Run GCN iterative scheduler for ILP scheduling (experimental)", createIterativeILPMachineScheduler)
static FunctionPass * createBasicWWMRegisterAllocator()
static bool mayNeedAsyncBarrierArriveWorkaround(const Triple &TT)
static const char RegAllocOptNotSupportedMessage[]
static FunctionPass * createBasicSGPRRegisterAllocator()
static MachineSchedRegistry GCNMaxOccupancySchedRegistry("gcn-max-occupancy", "Run GCN scheduler to maximize occupancy", createGCNMaxOccupancyMachineScheduler)
The AMDGPU TargetMachine interface definition for hw codegen targets.
This file declares the AMDGPU-specific subclass of TargetLoweringObjectFile.
This file a TargetTransformInfoImplBase conforming object specific to the AMDGPU target machine.
Provides passes to inlining "always_inline" functions.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This header provides classes for managing passes over SCCs of the call graph.
Provides analysis for continuously CSEing during GISel passes.
Interfaces for producing common pass manager configurations.
#define LLVM_READNONE
Definition Compiler.h:327
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
Analysis that tracks defined/used subregister lanes across COPY instructions and instructions that ge...
This file provides the interface for a simple, fast CSE pass.
This file defines the class GCNIterativeScheduler, which uses an iterative approach to find a best sc...
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
#define _
AcceleratorCodeSelection - Identify all functions reachable from a kernel, removing those that are un...
This file declares the IRTranslator pass.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define RegName(no)
This file provides the interface for LLVM's Loop Data Prefetching Pass.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
CGSCCAnalysisManager CGAM
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
PassInstrumentationCallbacks PIC
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineRegisterInfo & MRI
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
SI Machine Scheduler interface.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static FunctionPass * useDefaultRegisterAllocator()
-regalloc=... command line option.
Target-Independent Code Generator Pass Configuration Options pass.
static std::unique_ptr< TargetLoweringObjectFile > createTLOF()
A manager for alias analyses.
void registerFunctionAnalysis()
Register a specific AA result.
void addAAResult(AAResultT &AAResult)
Register a specific AA result.
Legacy wrapper pass to provide the AMDGPUAAResult object.
Analysis pass providing a never-invalidated alias analysis result.
Lower llvm.global_ctors and llvm.global_dtors to special kernels.
AMDGPUTargetMachine & getAMDGPUTargetMachine() const
std::unique_ptr< CSEConfigBase > getCSEConfig() const override
Returns the CSEConfig object to use for the current optimization level.
const AMDGPUOptions & CLOpts
bool addPreISel() override
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
bool addInstSelector() override
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
bool addGCPasses() override
addGCPasses - Add late codegen passes that analyze code for garbage collection.
AMDGPUPassConfig(TargetMachine &TM, PassManagerBase &PM)
bool isPassEnabled(BoolOrDefault Opt, CodeGenOptLevel Level=CodeGenOptLevel::Default) const
Check if a pass is enabled given Opt option.
void addIRPasses() override
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
void addCodeGenPrepare() override
Add pass to prepare the LLVM IR for code generation.
Splits the module M into N linkable partitions.
std::unique_ptr< TargetLoweringObjectFile > TLOF
unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const override
getAddressSpaceForPseudoSourceKind - Given the kind of memory (e.g.
bool isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
void registerDefaultAliasAnalyses(AAManager &) override
Allow the target to register alias analyses with the AAManager for use with the new pass manager.
std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const override
If the specified predicate checks whether a generic pointer falls within a specified address space,...
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
const AMDGPUOptions & CLOpts
AMDGPUTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL)
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
unsigned getAssumedAddrSpace(const Value *V) const override
If the specified generic pointer could be assumed as a pointer to a specific address space,...
bool splitModule(Module &M, unsigned NumParts, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback) override
Entry point for module splitting.
Inlines functions marked as "always_inline".
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:448
LLVM_ABI Attribute getAttribute(Attribute::AttrKind Kind) const
Return the attribute object.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:107
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
This class provides access to building LLVM's passes.
CodeGenTargetMachineImpl(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Diagnostic information for unsupported feature in backend.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LowerIntrinsics - This pass rewrites calls to the llvm.gcread or llvm.gcwrite intrinsics,...
Definition GCMetadata.h:229
const SIRegisterInfo * getRegisterInfo() const override
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
const TargetSubtargetInfo * getSubtargetImpl(const Function &) const override
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
ScheduleDAGInstrs * createPostMachineScheduler(MachineSchedContext *C) const override
Similar to createMachineScheduler but used when postRA machine scheduling is enabled.
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
void registerMachineRegisterInfoCallback(MachineFunction &MF) const override
bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange) const override
Parse out the target's MachineFunctionInfo from the YAML reprsentation.
yaml::MachineFunctionInfo * convertFuncInfoToYAML(const MachineFunction &MF) const override
Allocate and initialize an instance of the YAML representation of the MachineFunctionInfo.
yaml::MachineFunctionInfo * createDefaultFuncInfoYAML() const override
Allocate and return a default initialized instance of the YAML representation for the MachineFunction...
Error buildCodeGenPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, const CGPassBuilderOption &Opts, MCContext &Ctx, PassInstrumentationCallbacks *PIC) override
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
GCNTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
AMDGPU::TargetIDSetting getTargetIDSettingFromModuleFlag(const Module &M, StringRef FlagName) const
Get xnack/sramecc setting from module flag or command line option (for testing).
MachineFunctionInfo * createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F, const TargetSubtargetInfo *STI) const override
Create the target's instance of MachineFunctionInfo.
Pass to remove unused function declarations.
Definition GlobalDCE.h:39
This pass is responsible for selecting generic machine instructions to target-specific instructions.
A pass that internalizes all functions and variables other than those that must be preserved accordin...
Definition Internalize.h:37
Converts loops into loop-closed SSA form.
Definition LCSSA.h:38
Performs Loop Invariant Code Motion Pass.
Definition LICM.h:71
static void setUseExtended(bool Enable)
This pass implements the localization mechanism described at the top of this file.
Definition Localizer.h:40
An optimization pass inserting data prefetches in loops.
Context object for machine code objects.
Definition MCContext.h:84
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void addDelegate(Delegate *delegate)
MachineSchedRegistry provides a selection of available machine instruction schedulers.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
const char * getBufferStart() const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This class provides access to building LLVM's passes.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
RegisterPassParser class - Handle the addition of new machine passes.
RegisterRegAllocBase class - Track the registration of register allocators.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
bool initializeBaseYamlFields(const yaml::SIMachineFunctionInfo &YamlMFI, const MachineFunction &MF, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange)
void setFlag(Register Reg, uint8_t Flag)
bool checkFlag(Register Reg, uint8_t Flag) const
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:307
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
Represents a range in source code.
Definition SMLoc.h:47
A ScheduleDAG for scheduling lists of MachineInstr.
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.
const TargetInstrInfo * TII
Target instruction information.
Move instructions into successor blocks when possible.
Definition Sink.h:24
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
void push_back(const T &Elt)
unsigned getMainFileID() const
Definition SourceMgr.h:150
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:653
A switch()-like statement whose cases are string literals.
StringSwitch & Cases(std::initializer_list< StringLiteral > CaseStrings, T Value)
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with.
const Triple & getTargetTriple() const
const MCSubtargetInfo & getMCSubtargetInfo() const
StringRef getTargetFeatureString() const
const DataLayout DL
DataLayout for the target: keep ABI type size and alignment.
StringRef getTargetCPU() const
std::unique_ptr< const MCSubtargetInfo > STI
TargetOptions Options
void setEnableTiedFastRegAlloc(bool Value)
std::unique_ptr< const MCRegisterInfo > MRI
CodeGenOptLevel OptLevel
void setEnableDefaultMachineVerifier(bool Enable)
Target-Independent Code Generator Pass Configuration Options.
virtual void addCodeGenPrepare()
Add pass to prepare the LLVM IR for code generation.
virtual bool addILPOpts()
Add passes that optimize instruction level parallelism for out-of-order targets.
virtual void addPostRegAlloc()
This method may be implemented by targets that want to run passes after register allocation pass pipe...
CodeGenOptLevel getOptLevel() const
virtual void addOptimizedRegAlloc()
addOptimizedRegAlloc - Add passes related to register allocation.
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void addFastRegAlloc()
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
virtual void addMachineSSAOptimization()
addMachineSSAOptimization - Add standard passes that optimize machine instructions in SSA form.
void disablePass(AnalysisID PassID)
Allow the target to disable a specific standard pass by default.
AnalysisID addPass(AnalysisID PassID)
Utilities for targets to add passes to the pass manager.
TargetPassConfig(TargetMachine &TM, PassManagerBase &PM)
void setEnableSSAMachineScheduler(bool Enable)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isAMDGCN() const
Tests whether the target is AMDGCN.
Definition Triple.h:998
@ AMDGPUSubArch1250S
Definition Triple.h:275
@ AMDGPUSubArch12_5
Definition Triple.h:274
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
bool use_empty() const
Definition Value.h:348
An efficient, type-erasing, non-owning reference to a callable.
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
Registers T with cl::parseCommandLineOptions.
An abstract base class for streams implementations that also support a pwrite operation.
Interfaces for registering analysis passes, producing common pass manager configurations,...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr StringLiteral BufferFlag("amdgpu.buffer.oob.mode")
constexpr StringLiteral TBufferFlag("amdgpu.tbuffer.oob.mode")
bool isFlatGlobalAddrSpace(unsigned AS)
LLVM_READNONE constexpr bool isModuleEntryFunctionCC(CallingConv::ID CC)
StringRef getSchedStrategy(const AMDGPUOptions &CLOpts, const Function &F)
GPUKind
GPU kinds supported by the AMDGPU target.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
LLVM_ABI Triple::SubArchType getSubArch(GPUKind AK)
LLVM_ABI StringRef getArchNameFromSubArch(Triple::SubArchType SubArch)
Returns the canonical GPU name for an AMDGPU subarch, e.g.
LLVM_ABI GPUKind parseArchAMDGCN(StringRef CPU)
LLVM_ABI Triple::SubArchType getMajorSubArch(Triple::SubArchType SubArch)
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
This namespace contains all of the command line option processing machinery.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:721
This is an optimization pass for GlobalISel generic memory operations.
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
LLVM_ABI FunctionPass * createFlattenCFGPass()
ModulePass * createAMDGPUSwLowerLDSLegacyPass()
std::unique_ptr< ScheduleDAGMutation > createAMDGPUBarrierLatencyDAGMutation(MachineFunction *MF)
LLVM_ABI FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
LLVM_ABI char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
ImmutablePass * createAMDGPUAAWrapperPass()
LLVM_ABI char & PostRAHazardRecognizerID
PostRAHazardRecognizer - This pass runs the post-ra hazard recognizer.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
FunctionPass * createAMDGPUSetWavePriorityPass()
LLVM_ABI Pass * createLCSSAPass()
Definition LCSSA.cpp:544
void initializeAMDGPUMarkLastScratchLoadLegacyPass(PassRegistry &)
void initializeAMDGPUInsertDelayAluLegacyPass(PassRegistry &)
void initializeSIOptimizeExecMaskingPreRALegacyPass(PassRegistry &)
char & GCNPreRAOptimizationsID
LLVM_ABI char & GCLoweringID
GCLowering Pass - Used by gc.root to perform its default lowering operations.
void initializeSIInsertHardClausesLegacyPass(PassRegistry &)
FunctionPass * createSIAnnotateControlFlowLegacyPass()
Create the annotation pass.
FunctionPass * createSIModeRegisterPass()
void initializeGCNPreRAOptimizationsLegacyPass(PassRegistry &)
void initializeSILowerWWMCopiesLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGreedyRegisterAllocator()
Greedy register allocation pass - This pass implements a global register allocator for optimized buil...
void initializeAMDGPUAAWrapperPassPass(PassRegistry &)
void initializeSIShrinkInstructionsLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerBufferFatPointersPass()
void initializeR600ClauseMergePassPass(PassRegistry &)
ModulePass * createAMDGPUCtorDtorLoweringLegacyPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
void initializeGCNRewritePartialRegUsesLegacyPass(llvm::PassRegistry &)
void initializeAMDGPURewriteUndefForPHILegacyPass(PassRegistry &)
char & GCNRewritePartialRegUsesID
void initializeAMDGPUSwLowerLDSLegacyPass(PassRegistry &)
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
void initializeAMDGPULowerVGPREncodingLegacyPass(PassRegistry &)
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createLoadClusterDAGMutation(const TargetInstrInfo *TII, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
char & AMDGPUWaitSGPRHazardsLegacyID
void initializeSILowerSGPRSpillsLegacyPass(PassRegistry &)
char & SILowerControlFlowLegacyID
void initializeAMDGPURegBankCombinerLegacyPass(PassRegistry &)
LLVM_ABI Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
FunctionPass * createAMDGPURegBankCombinerLegacy(bool IsOptLevelNone)
void initializeAMDGPUPostLegalizerCombinerLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
void initializeAMDGPUDAGToDAGISelLegacyPass(PassRegistry &)
char & AMDGPUReserveWWMRegsLegacyID
LLVM_ABI FunctionPass * createNaryReassociatePass()
void initializeAMDGPUWaitSGPRHazardsLegacyPass(PassRegistry &)
LLVM_ABI char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
char & SIOptimizeExecMaskingLegacyID
LLVM_ABI char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
FunctionPass * createAMDGPUPostLegalizeCombinerLegacy(bool IsOptNone)
void initializeAMDGPUNextUseAnalysisLegacyPassPass(PassRegistry &)
void initializeR600ExpandSpecialInstrsPassPass(PassRegistry &)
void initializeR600PacketizerPass(PassRegistry &)
void initializeAMDGPURegBankSelectLegacyPass(PassRegistry &)
@ O1
Optimize quickly without destroying debuggability.
@ O0
Disable as many optimizations as possible.
std::unique_ptr< ScheduleDAGMutation > createVOPDPairingMutation()
ModulePass * createAMDGPUExportKernelRuntimeHandlesLegacyPass()
ModulePass * createAMDGPUAlwaysInlinePass(bool GlobalOpt=true)
void initializeAMDGPUAsmPrinterPass(PassRegistry &)
void initializeSIFoldOperandsLegacyPass(PassRegistry &)
void initializeAMDGPURegBankLegalizeLegacyPass(PassRegistry &)
char & SILoadStoreOptimizerLegacyID
void initializeAMDGPUPreLegalizerCombinerLegacyPass(PassRegistry &)
PassManager< LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, CGSCCUpdateResult & > CGSCCPassManager
The CGSCC pass manager.
LLVM_ABI std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition CSEInfo.cpp:85
Target & getTheR600Target()
The target for R600 GPUs.
LLVM_ABI char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
LLVM_ABI Pass * createStructurizeCFGPass(bool SkipUniformRegions=false)
When SkipUniformRegions is true the structizer will not structurize regions that only contain uniform...
LLVM_ABI char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
LLVM_ABI Pass * createLICMPass()
Definition LICM.cpp:341
char & SIFormMemoryClausesID
void initializeSILoadStoreOptimizerLegacyPass(PassRegistry &)
void initializeAMDGPULowerModuleLDSLegacyPass(PassRegistry &)
void initializeSIInsertAsyncBarrierArriveWorkaroundLegacyPass(PassRegistry &)
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
void initializeAMDGPUCtorDtorLoweringLegacyPass(PassRegistry &)
LLVM_ABI char & EarlyIfConverterLegacyID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
FunctionPass * createAMDGPUUniformIntrinsicCombineLegacyPass()
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:75
@ FullLTOPreLink
Full LTO prelink phase.
Definition Pass.h:83
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:85
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
Definition Pass.h:79
char & AMDGPUUnifyDivergentExitNodesID
void initializeAMDGPUPrepareAGPRAllocLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUPreloadKernArgPrologLegacyPass()
LLVM_ABI char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
char & SIOptimizeVGPRLiveRangeLegacyID
LLVM_ABI char & ShadowStackGCLoweringID
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
char & GCNNSAReassignID
void initializeAMDGPURewriteOutArgumentsPass(PassRegistry &)
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
void initializeAMDGPUExternalAAWrapperPass(PassRegistry &)
char & SIFoldOperandsLegacyID
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void initializeAMDGPULowerKernelArgumentsPass(PassRegistry &)
void initializeSIModeRegisterLegacyPass(PassRegistry &)
CodeModel::Model getEffectiveCodeModel(std::optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
void initializeAMDGPUPreloadKernelArgumentsLegacyPass(PassRegistry &)
LLVM_ABI ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
char & SILateBranchLoweringPassID
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
char & SIPostRA16BitMovFoldingLegacyID
LLVM_ABI char & BranchRelaxationPassID
BranchRelaxation - This pass replaces branches that need to jump further than is supported by a branc...
LLVM_ABI FunctionPass * createSinkingPass()
Definition Sink.cpp:274
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
void initializeSIMemoryLegalizerLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerIntrinsicsLegacyPass()
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void initializeR600MachineCFGStructurizerPass(PassRegistry &)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:309
char & GCNDPPCombineLegacyID
FunctionPass * createSIInsertAsyncBarrierArriveWorkaroundPass()
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI FunctionPass * createLoopDataPrefetchPass()
FunctionPass * createAMDGPULowerKernelArgumentsPass()
char & AMDGPUInsertDelayAluID
std::unique_ptr< ScheduleDAGMutation > createAMDGPUMacroFusionDAGMutation()
Note that you have to add: DAG.addMutation(createAMDGPUMacroFusionDAGMutation()); to AMDGPUTargetMach...
LLVM_ABI char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
void initializeGCNPreRALongBranchRegLegacyPass(PassRegistry &)
char & SILowerWWMCopiesLegacyID
LLVM_ABI FunctionPass * createUnifyLoopExitsPass()
char & SIOptimizeExecMaskingPreRAID
LLVM_ABI FunctionPass * createFixIrreduciblePass()
void initializeR600EmitClauseMarkersPass(PassRegistry &)
LLVM_ABI char & FuncletLayoutID
This pass lays out funclets contiguously.
LLVM_ABI char & DetectDeadLanesID
This pass adds dead/undef flags after analyzing subregister lanes.
void initializeAMDGPULowerExecSyncLegacyPass(PassRegistry &)
ScheduleDAGInstrs * createGCNNoopPostMachineScheduler(MachineSchedContext *C)
void initializeAMDGPUExportKernelRuntimeHandlesLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createRegAllocScoringPass()
When learning an eviction policy, extract score(reward) information, otherwise this does nothing.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
void initializeSIInsertWaitcntsLegacyPass(PassRegistry &)
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption(const TargetMachine &TM)
ModulePass * createAMDGPUPreloadKernelArgumentsLegacyPass(const TargetMachine *)
ModulePass * createAMDGPUPrintfRuntimeBinding()
LLVM_ABI char & StackSlotColoringID
StackSlotColoring - This pass performs stack slot coloring.
LLVM_ABI Pass * createAlwaysInlinerLegacyPass(bool InsertLifetime=true)
Create a legacy pass manager instance of a pass to inline and remove functions marked as "always_inli...
void initializeR600ControlFlowFinalizerPass(PassRegistry &)
void initializeAMDGPUImageIntrinsicOptimizerPass(PassRegistry &)
void initializeSILateBranchLoweringLegacyPass(PassRegistry &)
void initializeSILowerControlFlowLegacyPass(PassRegistry &)
void initializeSIFormMemoryClausesLegacyPass(PassRegistry &)
char & SIPreAllocateWWMRegsLegacyID
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
ModulePass * createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
FunctionPass * createAMDGPUPromoteAlloca()
LLVM_ABI FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
void initializeAMDGPUReserveWWMRegsLegacyPass(PassRegistry &)
char & SIPreEmitPeepholeID
char & SIPostRABundlerLegacyID
ModulePass * createAMDGPURemoveIncompatibleFunctionsPass(const TargetMachine *)
void initializeGCNRegPressurePrinterPass(PassRegistry &)
void initializeSILowerI1CopiesLegacyPass(PassRegistry &)
LLVM_ABI ImmutablePass * createExternalAAWrapperPass(std::function< void(Pass &, Function &, AAResults &)> Callback, bool RunEarly=false)
A wrapper pass around a callback which can be used to populate the AAResults in the AAResultsWrapperP...
char & SILowerSGPRSpillsLegacyID
LLVM_ABI FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
LLVM_ABI void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
ModulePass * createR600OpenCLImageTypeLoweringPass()
void initializeSIAnnotateControlFlowLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUISelDag(TargetMachine &TM, CodeGenOptLevel OptLevel)
This pass converts a legalized DAG into a AMDGPU-specific.
void initializeGCNCreateVOPDLegacyPass(PassRegistry &)
void initializeAMDGPUUniformIntrinsicCombineLegacyPass(PassRegistry &)
ScheduleDAGInstrs * createGCNCoExecMachineScheduler(MachineSchedContext *C)
void initializeSIPreAllocateWWMRegsLegacyPass(PassRegistry &)
void initializeSIFixVGPRCopiesLegacyPass(PassRegistry &)
Target & getTheGCNTarget()
The target for GCN GPUs.
void initializeSIFixSGPRCopiesLegacyPass(PassRegistry &)
void initializeAMDGPUAtomicOptimizerPass(PassRegistry &)
void initializeAMDGPULowerIntrinsicsLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGVNPass()
Definition GVN.cpp:4462
void initializeAMDGPURewriteAGPRCopyMFMALegacyPass(PassRegistry &)
void initializeAMDGPUNextUseAnalysisPrinterLegacyPassPass(PassRegistry &)
void initializeSIPostRABundlerLegacyPass(PassRegistry &)
LLVM_ABI char & MachineCSELegacyID
MachineCSE - This pass performs global CSE on machine instructions.
char & SIWholeQuadModeID
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
void initializeAMDGPUCodeGenPreparePass(PassRegistry &)
FunctionPass * createAMDGPURewriteUndefForPHILegacyPass()
void initializeSIOptimizeExecMaskingLegacyPass(PassRegistry &)
void call_once(once_flag &flag, Function &&F, Args &&... ArgList)
Execute the function specified as a parameter once.
Definition Threading.h:86
FunctionPass * createSILowerI1CopiesLegacyPass()
FunctionPass * createAMDGPURegBankSelectLegacyPass()
void initializeAMDGPULowerKernelAttributesPass(PassRegistry &)
char & SIInsertHardClausesID
char & SIFixSGPRCopiesLegacyID
void initializeGCNDPPCombineLegacyPass(PassRegistry &)
char & GCNCreateVOPDID
char & SIPeepholeSDWALegacyID
LLVM_ABI char & VirtRegRewriterID
VirtRegRewriter pass.
char & SIFixVGPRCopiesID
void initializeGCNNSAReassignLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createLowerSwitchPass()
void initializeAMDGPUPreloadKernArgPrologLegacyPass(PassRegistry &)
Target & getTheGCNLegacyTarget()
The target for GCN GPUs, registered under the legacy "amdgcn" architecture name for use with -march.
LLVM_ABI FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
void initializeR600VectorRegMergerPass(PassRegistry &)
char & AMDGPURewriteAGPRCopyMFMALegacyID
ModulePass * createAMDGPULowerExecSyncLegacyPass()
constexpr bool valueOr(BoolOrDefault X, bool Default)
char & AMDGPULowerVGPREncodingLegacyID
FunctionPass * createAMDGPUGlobalISelDivergenceLoweringPass()
FunctionPass * createAMDGPUPreLegalizeCombinerLegacyPass(bool IsOptLevelNone)
FunctionPass * createSIMemoryLegalizerPass()
void initializeAMDGPULateCodeGenPrepareLegacyPass(PassRegistry &)
void initializeSIOptimizeVGPRLiveRangeLegacyPass(PassRegistry &)
void initializeSIPeepholeSDWALegacyPass(PassRegistry &)
LLVM_ABI char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
FunctionPass * createAMDGPULateCodeGenPrepareLegacyPass()
LLVM_ABI FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
void initializeAMDGPUGlobalISelDivergenceLoweringLegacyPass(PassRegistry &)
MCRegisterInfo * createGCNMCRegisterInfo(AMDGPUDwarfFlavour DwarfFlavour)
LLVM_ABI FunctionPass * createStraightLineStrengthReducePass()
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
FunctionPass * createAMDGPUImageIntrinsicOptimizerPass(const TargetMachine *)
void initializeAMDGPULowerBufferFatPointersPass(PassRegistry &)
void initializeAMDGPUUnifyDivergentExitNodesLegacyPass(PassRegistry &)
FunctionPass * createSIInsertWaitcntsPass()
FunctionPass * createAMDGPUAnnotateUniformValuesLegacy()
LLVM_ABI FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
void initializeSIWholeQuadModeLegacyPass(PassRegistry &)
LLVM_ABI char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
LLVM_ABI llvm::cl::opt< bool > NoKernelInfoEndLTO
LLVM_ABI bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
FunctionPass * createAMDGPUAtomicOptimizerPass(AMDGPU::ScanOptions ScanStrategy)
void initializeAMDGPUResourceUsageAnalysisWrapperPassPass(PassRegistry &)
FunctionPass * createSIShrinkInstructionsLegacyPass()
char & AMDGPUPrepareAGPRAllocLegacyID
char & AMDGPUMarkLastScratchLoadID
LLVM_ABI char & RenameIndependentSubregsID
This pass detects subregister lanes in a virtual register that are used independently of other lanes ...
void initializeAMDGPUAnnotateUniformValuesLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createAMDGPUExportClusteringDAGMutation()
void initializeAMDGPUPrintfRuntimeBindingPass(PassRegistry &)
void initializeAMDGPUPromoteAllocaPass(PassRegistry &)
void initializeAMDGPURemoveIncompatibleFunctionsLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createAMDGPUHazardLatencyDAGMutation(MachineFunction *MF)
void initializeAMDGPUAlwaysInlinePass(PassRegistry &)
LLVM_ABI char & DeadMachineInstructionElimID
DeadMachineInstructionElim - This pass removes dead machine instructions.
const void * AnalysisID
Definition Pass.h:51
void initializeSIPreEmitPeepholeLegacyPass(PassRegistry &)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
char & AMDGPUPerfHintAnalysisLegacyID
char & GCNPreRALongBranchRegID
FunctionPass * createAMDGPUCodeGenPreparePass(bool ExpandDiv64InIR)
void initializeSIPostRA16BitMovFoldingLegacyPass(PassRegistry &)
FunctionPass * createAMDGPURegBankLegalizeLegacyPass()
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void initializeAMDGPUPromoteKernelArgumentsPass(PassRegistry &)
#define N
static ArgDescriptor createStack(unsigned Offset, unsigned Mask=~0u)
static ArgDescriptor createArg(const ArgDescriptor &Arg, unsigned Mask)
static ArgDescriptor createRegister(Register Reg, unsigned Mask=~0u)
cl::boolOrDefault EnableGlobalISelOption
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ IEEE
IEEE-754 denormal numbers preserved.
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
A simple and fast domtree-based CSE pass.
Definition EarlyCSE.h:31
MachineFunctionInfo - This class can be derived from and used by targets to hold private target-speci...
static FuncInfoTy * create(BumpPtrAllocator &Allocator, const Function &F, const SubtargetTy *STI)
Factory function: default behavior is to call new using the supplied allocator.
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:180
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:179
RegisterTargetMachine - Helper template for registering a target machine implementation,...
bool DX10Clamp
Used by the vector ALU to force DX10-style treatment of NaNs: when set, clamp NaN to zero; otherwise,...
DenormalMode FP64FP16Denormals
If this is set, neither input or output denormals are flushed for both f64 and f16/v2f16 instructions...
bool IEEE
Floating point opcodes that support exception flag gathering quiet and propagate signaling NaN inputs...
DenormalMode FP32Denormals
If this is set, neither input or output denormals are flushed for most f32 instructions.
The llvm::once_flag structure.
Definition Threading.h:67
Targets should override this in a way that mirrors the implementation of llvm::MachineFunctionInfo.
SmallVector< StringValue > WWMReservedRegs
std::optional< SIArgumentInfo > ArgInfo
SmallVector< StringValue, 2 > SpillPhysVGPRS
A wrapper around std::string which contains a source range that's being set during parsing.