LLVM 21.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"
22#include "AMDGPUIGroupLP.h"
23#include "AMDGPUISelDAGToDAG.h"
24#include "AMDGPUMacroFusion.h"
28#include "AMDGPUSplitModule.h"
33#include "GCNDPPCombine.h"
38#include "GCNSchedStrategy.h"
39#include "GCNVOPDUtils.h"
40#include "R600.h"
41#include "R600TargetMachine.h"
42#include "SIFixSGPRCopies.h"
43#include "SIFixVGPRCopies.h"
44#include "SIFoldOperands.h"
46#include "SILowerControlFlow.h"
47#include "SILowerSGPRSpills.h"
48#include "SILowerWWMCopies.h"
50#include "SIMachineScheduler.h"
53#include "SIPeepholeSDWA.h"
56#include "SIWholeQuadMode.h"
75#include "llvm/CodeGen/Passes.h"
78#include "llvm/IR/IntrinsicsAMDGPU.h"
79#include "llvm/IR/PassManager.h"
86#include "llvm/Transforms/IPO.h"
109#include <optional>
110
111using namespace llvm;
112using namespace llvm::PatternMatch;
113
114namespace {
115class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
116public:
117 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
118 : RegisterRegAllocBase(N, D, C) {}
119};
120
121class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
122public:
123 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
124 : RegisterRegAllocBase(N, D, C) {}
125};
126
127class WWMRegisterRegAlloc : public RegisterRegAllocBase<WWMRegisterRegAlloc> {
128public:
129 WWMRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
130 : RegisterRegAllocBase(N, D, C) {}
131};
132
133static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI,
135 const Register Reg) {
136 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
137 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
138}
139
140static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI,
142 const Register Reg) {
143 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
144 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
145}
146
147static bool onlyAllocateWWMRegs(const TargetRegisterInfo &TRI,
149 const Register Reg) {
150 const SIMachineFunctionInfo *MFI =
151 MRI.getMF().getInfo<SIMachineFunctionInfo>();
152 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
153 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC) &&
155}
156
157/// -{sgpr|wwm|vgpr}-regalloc=... command line option.
158static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
159
160/// A dummy default pass factory indicates whether the register allocator is
161/// overridden on the command line.
162static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag;
163static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag;
164static llvm::once_flag InitializeDefaultWWMRegisterAllocatorFlag;
165
166static SGPRRegisterRegAlloc
167defaultSGPRRegAlloc("default",
168 "pick SGPR register allocator based on -O option",
170
171static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
173SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
174 cl::desc("Register allocator to use for SGPRs"));
175
176static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
178VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
179 cl::desc("Register allocator to use for VGPRs"));
180
181static cl::opt<WWMRegisterRegAlloc::FunctionPassCtor, false,
183 WWMRegAlloc("wwm-regalloc", cl::Hidden,
185 cl::desc("Register allocator to use for WWM registers"));
186
187static void initializeDefaultSGPRRegisterAllocatorOnce() {
188 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
189
190 if (!Ctor) {
191 Ctor = SGPRRegAlloc;
192 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
193 }
194}
195
196static void initializeDefaultVGPRRegisterAllocatorOnce() {
197 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
198
199 if (!Ctor) {
200 Ctor = VGPRRegAlloc;
201 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
202 }
203}
204
205static void initializeDefaultWWMRegisterAllocatorOnce() {
206 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
207
208 if (!Ctor) {
209 Ctor = WWMRegAlloc;
210 WWMRegisterRegAlloc::setDefault(WWMRegAlloc);
211 }
212}
213
214static FunctionPass *createBasicSGPRRegisterAllocator() {
215 return createBasicRegisterAllocator(onlyAllocateSGPRs);
216}
217
218static FunctionPass *createGreedySGPRRegisterAllocator() {
219 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
220}
221
222static FunctionPass *createFastSGPRRegisterAllocator() {
223 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
224}
225
226static FunctionPass *createBasicVGPRRegisterAllocator() {
227 return createBasicRegisterAllocator(onlyAllocateVGPRs);
228}
229
230static FunctionPass *createGreedyVGPRRegisterAllocator() {
231 return createGreedyRegisterAllocator(onlyAllocateVGPRs);
232}
233
234static FunctionPass *createFastVGPRRegisterAllocator() {
235 return createFastRegisterAllocator(onlyAllocateVGPRs, true);
236}
237
238static FunctionPass *createBasicWWMRegisterAllocator() {
239 return createBasicRegisterAllocator(onlyAllocateWWMRegs);
240}
241
242static FunctionPass *createGreedyWWMRegisterAllocator() {
243 return createGreedyRegisterAllocator(onlyAllocateWWMRegs);
244}
245
246static FunctionPass *createFastWWMRegisterAllocator() {
247 return createFastRegisterAllocator(onlyAllocateWWMRegs, false);
248}
249
250static SGPRRegisterRegAlloc basicRegAllocSGPR(
251 "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
252static SGPRRegisterRegAlloc greedyRegAllocSGPR(
253 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
254
255static SGPRRegisterRegAlloc fastRegAllocSGPR(
256 "fast", "fast register allocator", createFastSGPRRegisterAllocator);
257
258
259static VGPRRegisterRegAlloc basicRegAllocVGPR(
260 "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
261static VGPRRegisterRegAlloc greedyRegAllocVGPR(
262 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
263
264static VGPRRegisterRegAlloc fastRegAllocVGPR(
265 "fast", "fast register allocator", createFastVGPRRegisterAllocator);
266static WWMRegisterRegAlloc basicRegAllocWWMReg("basic",
267 "basic register allocator",
268 createBasicWWMRegisterAllocator);
269static WWMRegisterRegAlloc
270 greedyRegAllocWWMReg("greedy", "greedy register allocator",
271 createGreedyWWMRegisterAllocator);
272static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator",
273 createFastWWMRegisterAllocator);
274
276 return Phase == ThinOrFullLTOPhase::FullLTOPreLink ||
277 Phase == ThinOrFullLTOPhase::ThinLTOPreLink;
278}
279} // anonymous namespace
280
281static cl::opt<bool>
283 cl::desc("Run early if-conversion"),
284 cl::init(false));
285
286static cl::opt<bool>
287OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
288 cl::desc("Run pre-RA exec mask optimizations"),
289 cl::init(true));
290
291static cl::opt<bool>
292 LowerCtorDtor("amdgpu-lower-global-ctor-dtor",
293 cl::desc("Lower GPU ctor / dtors to globals on the device."),
294 cl::init(true), cl::Hidden);
295
296// Option to disable vectorizer for tests.
298 "amdgpu-load-store-vectorizer",
299 cl::desc("Enable load store vectorizer"),
300 cl::init(true),
301 cl::Hidden);
302
303// Option to control global loads scalarization
305 "amdgpu-scalarize-global-loads",
306 cl::desc("Enable global load scalarization"),
307 cl::init(true),
308 cl::Hidden);
309
310// Option to run internalize pass.
312 "amdgpu-internalize-symbols",
313 cl::desc("Enable elimination of non-kernel functions and unused globals"),
314 cl::init(false),
315 cl::Hidden);
316
317// Option to inline all early.
319 "amdgpu-early-inline-all",
320 cl::desc("Inline all functions early"),
321 cl::init(false),
322 cl::Hidden);
323
325 "amdgpu-enable-remove-incompatible-functions", cl::Hidden,
326 cl::desc("Enable removal of functions when they"
327 "use features not supported by the target GPU"),
328 cl::init(true));
329
331 "amdgpu-sdwa-peephole",
332 cl::desc("Enable SDWA peepholer"),
333 cl::init(true));
334
336 "amdgpu-dpp-combine",
337 cl::desc("Enable DPP combiner"),
338 cl::init(true));
339
340// Enable address space based alias analysis
342 cl::desc("Enable AMDGPU Alias Analysis"),
343 cl::init(true));
344
345// Enable lib calls simplifications
347 "amdgpu-simplify-libcall",
348 cl::desc("Enable amdgpu library simplifications"),
349 cl::init(true),
350 cl::Hidden);
351
353 "amdgpu-ir-lower-kernel-arguments",
354 cl::desc("Lower kernel argument loads in IR pass"),
355 cl::init(true),
356 cl::Hidden);
357
359 "amdgpu-reassign-regs",
360 cl::desc("Enable register reassign optimizations on gfx10+"),
361 cl::init(true),
362 cl::Hidden);
363
365 "amdgpu-opt-vgpr-liverange",
366 cl::desc("Enable VGPR liverange optimizations for if-else structure"),
367 cl::init(true), cl::Hidden);
368
370 "amdgpu-atomic-optimizer-strategy",
371 cl::desc("Select DPP or Iterative strategy for scan"),
372 cl::init(ScanOptions::Iterative),
374 clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"),
375 clEnumValN(ScanOptions::Iterative, "Iterative",
376 "Use Iterative approach for scan"),
377 clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")));
378
379// Enable Mode register optimization
381 "amdgpu-mode-register",
382 cl::desc("Enable mode register pass"),
383 cl::init(true),
384 cl::Hidden);
385
386// Enable GFX11+ s_delay_alu insertion
387static cl::opt<bool>
388 EnableInsertDelayAlu("amdgpu-enable-delay-alu",
389 cl::desc("Enable s_delay_alu insertion"),
390 cl::init(true), cl::Hidden);
391
392// Enable GFX11+ VOPD
393static cl::opt<bool>
394 EnableVOPD("amdgpu-enable-vopd",
395 cl::desc("Enable VOPD, dual issue of VALU in wave32"),
396 cl::init(true), cl::Hidden);
397
398// Option is used in lit tests to prevent deadcoding of patterns inspected.
399static cl::opt<bool>
400EnableDCEInRA("amdgpu-dce-in-ra",
401 cl::init(true), cl::Hidden,
402 cl::desc("Enable machine DCE inside regalloc"));
403
404static cl::opt<bool> EnableSetWavePriority("amdgpu-set-wave-priority",
405 cl::desc("Adjust wave priority"),
406 cl::init(false), cl::Hidden);
407
409 "amdgpu-scalar-ir-passes",
410 cl::desc("Enable scalar IR passes"),
411 cl::init(true),
412 cl::Hidden);
413
414static cl::opt<bool>
415 EnableSwLowerLDS("amdgpu-enable-sw-lower-lds",
416 cl::desc("Enable lowering of lds to global memory pass "
417 "and asan instrument resulting IR."),
418 cl::init(true), cl::Hidden);
419
421 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
423 cl::Hidden);
424
426 "amdgpu-enable-pre-ra-optimizations",
427 cl::desc("Enable Pre-RA optimizations pass"), cl::init(true),
428 cl::Hidden);
429
431 "amdgpu-enable-promote-kernel-arguments",
432 cl::desc("Enable promotion of flat kernel pointer arguments to global"),
433 cl::Hidden, cl::init(true));
434
436 "amdgpu-enable-image-intrinsic-optimizer",
437 cl::desc("Enable image intrinsic optimizer pass"), cl::init(true),
438 cl::Hidden);
439
440static cl::opt<bool>
441 EnableLoopPrefetch("amdgpu-loop-prefetch",
442 cl::desc("Enable loop data prefetch on AMDGPU"),
443 cl::Hidden, cl::init(false));
444
446 AMDGPUSchedStrategy("amdgpu-sched-strategy",
447 cl::desc("Select custom AMDGPU scheduling strategy."),
448 cl::Hidden, cl::init(""));
449
451 "amdgpu-enable-rewrite-partial-reg-uses",
452 cl::desc("Enable rewrite partial reg uses pass"), cl::init(true),
453 cl::Hidden);
454
456 "amdgpu-enable-hipstdpar",
457 cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false),
458 cl::Hidden);
459
460static cl::opt<bool>
461 EnableAMDGPUAttributor("amdgpu-attributor-enable",
462 cl::desc("Enable AMDGPUAttributorPass"),
463 cl::init(true), cl::Hidden);
464
466 "new-reg-bank-select",
467 cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of "
468 "regbankselect"),
469 cl::init(false), cl::Hidden);
470
472 "amdgpu-link-time-closed-world",
473 cl::desc("Whether has closed-world assumption at link time"),
474 cl::init(false), cl::Hidden);
475
477 // Register the target
480
559}
560
561static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
562 return std::make_unique<AMDGPUTargetObjectFile>();
563}
564
566 return new SIScheduleDAGMI(C);
567}
568
569static ScheduleDAGInstrs *
571 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
572 ScheduleDAGMILive *DAG =
573 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
574 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
575 if (ST.shouldClusterStores())
576 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
577 DAG->addMutation(createIGroupLPDAGMutation(AMDGPU::SchedulingPhase::Initial));
578 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
579 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
580 return DAG;
581}
582
583static ScheduleDAGInstrs *
585 ScheduleDAGMILive *DAG =
586 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C));
587 DAG->addMutation(createIGroupLPDAGMutation(AMDGPU::SchedulingPhase::Initial));
588 return DAG;
589}
590
591static ScheduleDAGInstrs *
593 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
595 C, std::make_unique<GCNMaxMemoryClauseSchedStrategy>(C));
596 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
597 if (ST.shouldClusterStores())
598 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
599 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
600 return DAG;
601}
602
603static ScheduleDAGInstrs *
605 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
606 auto *DAG = new GCNIterativeScheduler(
608 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
609 if (ST.shouldClusterStores())
610 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
611 return DAG;
612}
613
615 return new GCNIterativeScheduler(C,
617}
618
619static ScheduleDAGInstrs *
621 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
623 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
624 if (ST.shouldClusterStores())
625 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
626 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
627 return DAG;
628}
629
631SISchedRegistry("si", "Run SI's custom scheduler",
633
636 "Run GCN scheduler to maximize occupancy",
638
640 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp",
642
644 "gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause",
646
648 "gcn-iterative-max-occupancy-experimental",
649 "Run GCN scheduler to maximize occupancy (experimental)",
651
653 "gcn-iterative-minreg",
654 "Run GCN iterative scheduler for minimal register usage (experimental)",
656
658 "gcn-iterative-ilp",
659 "Run GCN iterative scheduler for ILP scheduling (experimental)",
661
663 if (TT.getArch() == Triple::r600) {
664 // 32-bit pointers.
665 return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
666 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
667 }
668
669 // 32-bit private, local, and region pointers. 64-bit global, constant and
670 // flat. 160-bit non-integral fat buffer pointers that include a 128-bit
671 // buffer descriptor and a 32-bit offset, which are indexed by 32-bit values
672 // (address space 7), and 128-bit non-integral buffer resourcees (address
673 // space 8) which cannot be non-trivilally accessed by LLVM memory operations
674 // like getelementptr.
675 return "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
676 "-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-"
677 "v32:32-v48:64-v96:"
678 "128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-"
679 "G1-ni:7:8:9";
680}
681
684 if (!GPU.empty())
685 return GPU;
686
687 // Need to default to a target with flat support for HSA.
688 if (TT.getArch() == Triple::amdgcn)
689 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
690
691 return "r600";
692}
693
694static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
695 // The AMDGPU toolchain only supports generating shared objects, so we
696 // must always use PIC.
697 return Reloc::PIC_;
698}
699
701 StringRef CPU, StringRef FS,
702 const TargetOptions &Options,
703 std::optional<Reloc::Model> RM,
704 std::optional<CodeModel::Model> CM,
705 CodeGenOptLevel OptLevel)
707 T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU), FS, Options,
709 getEffectiveCodeModel(CM, CodeModel::Small), OptLevel),
710 TLOF(createTLOF(getTargetTriple())) {
711 initAsmInfo();
712 if (TT.getArch() == Triple::amdgcn) {
713 if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize64"))
715 else if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize32"))
717 }
718}
719
722
724
726 Attribute GPUAttr = F.getFnAttribute("target-cpu");
727 return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU();
728}
729
731 Attribute FSAttr = F.getFnAttribute("target-features");
732
733 return FSAttr.isValid() ? FSAttr.getValueAsString()
735}
736
739 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
741 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
742 if (ST.shouldClusterStores())
743 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
744 return DAG;
745}
746
747/// Predicate for Internalize pass.
748static bool mustPreserveGV(const GlobalValue &GV) {
749 if (const Function *F = dyn_cast<Function>(&GV))
750 return F->isDeclaration() || F->getName().starts_with("__asan_") ||
751 F->getName().starts_with("__sanitizer_") ||
752 AMDGPU::isEntryFunctionCC(F->getCallingConv());
753
755 return !GV.use_empty();
756}
757
760}
761
764 if (Params.empty())
766 Params.consume_front("strategy=");
767 auto Result = StringSwitch<std::optional<ScanOptions>>(Params)
768 .Case("dpp", ScanOptions::DPP)
769 .Cases("iterative", "", ScanOptions::Iterative)
770 .Case("none", ScanOptions::None)
771 .Default(std::nullopt);
772 if (Result)
773 return *Result;
774 return make_error<StringError>("invalid parameter", inconvertibleErrorCode());
775}
776
780 while (!Params.empty()) {
781 StringRef ParamName;
782 std::tie(ParamName, Params) = Params.split(';');
783 if (ParamName == "closed-world") {
784 Result.IsClosedWorld = true;
785 } else {
786 return make_error<StringError>(
787 formatv("invalid AMDGPUAttributor pass parameter '{0}' ", ParamName)
788 .str(),
790 }
791 }
792 return Result;
793}
794
796
797#define GET_PASS_REGISTRY "AMDGPUPassRegistry.def"
799
801 [](ModulePassManager &PM, OptimizationLevel Level) {
802 if (EnableHipStdPar)
804 });
805
809 if (!isLTOPreLink(Phase))
811
812 if (Level == OptimizationLevel::O0)
813 return;
814
816
817 // We don't want to run internalization at per-module stage.
821 }
822
825 });
826
828 [](FunctionPassManager &FPM, OptimizationLevel Level) {
829 if (Level == OptimizationLevel::O0)
830 return;
831
835 });
836
838 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
839 if (Level == OptimizationLevel::O0)
840 return;
841
843
844 // Add promote kernel arguments pass to the opt pipeline right before
845 // infer address spaces which is needed to do actual address space
846 // rewriting.
847 if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
850
851 // Add infer address spaces pass to the opt pipeline after inlining
852 // but before SROA to increase SROA opportunities.
854
855 // This should run after inlining to have any chance of doing
856 // anything, and before other cleanup optimizations.
858
859 if (Level != OptimizationLevel::O0) {
860 // Promote alloca to vector before SROA and loop unroll. If we
861 // manage to eliminate allocas before unroll we may choose to unroll
862 // less.
864 }
865
866 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
867 });
868
869 // FIXME: Why is AMDGPUAttributor not in CGSCC?
871 OptimizationLevel Level,
873 if (Level != OptimizationLevel::O0) {
874 if (!isLTOPreLink(Phase))
875 MPM.addPass(AMDGPUAttributorPass(*this));
876 }
877 });
878
880 [this](ModulePassManager &PM, OptimizationLevel Level) {
881 // We want to support the -lto-partitions=N option as "best effort".
882 // For that, we need to lower LDS earlier in the pipeline before the
883 // module is partitioned for codegen.
885 PM.addPass(AMDGPUSwLowerLDSPass(*this));
888 if (Level != OptimizationLevel::O0) {
889 // Do we really need internalization in LTO?
890 if (InternalizeSymbols) {
893 }
897 Opt.IsClosedWorld = true;
898 PM.addPass(AMDGPUAttributorPass(*this, Opt));
899 }
900 }
901 if (!NoKernelInfoEndLTO) {
903 FPM.addPass(KernelInfoPrinter(this));
904 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
905 }
906 });
907
909 [](StringRef FilterName) -> RegAllocFilterFunc {
910 if (FilterName == "sgpr")
911 return onlyAllocateSGPRs;
912 if (FilterName == "vgpr")
913 return onlyAllocateVGPRs;
914 if (FilterName == "wwm")
915 return onlyAllocateWWMRegs;
916 return nullptr;
917 });
918}
919
920int64_t AMDGPUTargetMachine::getNullPointerValue(unsigned AddrSpace) {
921 return (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
922 AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
923 AddrSpace == AMDGPUAS::REGION_ADDRESS)
924 ? -1
925 : 0;
926}
927
929 unsigned DestAS) const {
930 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
932}
933
935 const auto *LD = dyn_cast<LoadInst>(V);
936 if (!LD) // TODO: Handle invariant load like constant.
938
939 // It must be a generic pointer loaded.
940 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
941
942 const auto *Ptr = LD->getPointerOperand();
943 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
945 // For a generic pointer loaded from the constant memory, it could be assumed
946 // as a global pointer since the constant memory is only populated on the
947 // host side. As implied by the offload programming model, only global
948 // pointers could be referenced on the host side.
950}
951
952std::pair<const Value *, unsigned>
954 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
955 switch (II->getIntrinsicID()) {
956 case Intrinsic::amdgcn_is_shared:
957 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
958 case Intrinsic::amdgcn_is_private:
959 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
960 default:
961 break;
962 }
963 return std::pair(nullptr, -1);
964 }
965 // Check the global pointer predication based on
966 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
967 // the order of 'is_shared' and 'is_private' is not significant.
968 Value *Ptr;
969 if (match(
970 const_cast<Value *>(V),
971 m_c_And(m_Not(m_Intrinsic<Intrinsic::amdgcn_is_shared>(m_Value(Ptr))),
972 m_Not(m_Intrinsic<Intrinsic::amdgcn_is_private>(
973 m_Deferred(Ptr))))))
974 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
975
976 return std::pair(nullptr, -1);
977}
978
979unsigned
981 switch (Kind) {
991 }
993}
994
996 Module &M, unsigned NumParts,
997 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
998 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
999 // but all current users of this API don't have one ready and would need to
1000 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1001
1006
1007 PassBuilder PB(this);
1011
1013 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1014 MPM.run(M, MAM);
1015 return true;
1016}
1017
1018//===----------------------------------------------------------------------===//
1019// GCN Target Machine (SI+)
1020//===----------------------------------------------------------------------===//
1021
1023 StringRef CPU, StringRef FS,
1024 const TargetOptions &Options,
1025 std::optional<Reloc::Model> RM,
1026 std::optional<CodeModel::Model> CM,
1027 CodeGenOptLevel OL, bool JIT)
1028 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
1029
1030const TargetSubtargetInfo *
1032 StringRef GPU = getGPUName(F);
1034
1035 SmallString<128> SubtargetKey(GPU);
1036 SubtargetKey.append(FS);
1037
1038 auto &I = SubtargetMap[SubtargetKey];
1039 if (!I) {
1040 // This needs to be done before we create a new subtarget since any
1041 // creation will depend on the TM and the code generation flags on the
1042 // function that reside in TargetOptions.
1044 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
1045 }
1046
1047 I->setScalarizeGlobalBehavior(ScalarizeGlobal);
1048
1049 return I.get();
1050}
1051
1054 return TargetTransformInfo(GCNTTIImpl(this, F));
1055}
1056
1059 CodeGenFileType FileType, const CGPassBuilderOption &Opts,
1061 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1062 return CGPB.buildPipeline(MPM, Out, DwoOut, FileType);
1063}
1064
1067 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1068 if (ST.enableSIScheduler())
1070
1071 Attribute SchedStrategyAttr =
1072 C->MF->getFunction().getFnAttribute("amdgpu-sched-strategy");
1073 StringRef SchedStrategy = SchedStrategyAttr.isValid()
1074 ? SchedStrategyAttr.getValueAsString()
1076
1077 if (SchedStrategy == "max-ilp")
1079
1080 if (SchedStrategy == "max-memory-clause")
1082
1084}
1085
1088 ScheduleDAGMI *DAG =
1089 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1090 /*RemoveKillFlags=*/true);
1091 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1093 if (ST.shouldClusterStores())
1098 EnableVOPD)
1100 return DAG;
1101}
1102//===----------------------------------------------------------------------===//
1103// AMDGPU Legacy Pass Setup
1104//===----------------------------------------------------------------------===//
1105
1106std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1108}
1109
1110namespace {
1111
1112class GCNPassConfig final : public AMDGPUPassConfig {
1113public:
1114 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1115 : AMDGPUPassConfig(TM, PM) {
1116 // It is necessary to know the register usage of the entire call graph. We
1117 // allow calls without EnableAMDGPUFunctionCalls if they are marked
1118 // noinline, so this is always required.
1119 setRequiresCodeGenSCCOrder(true);
1120 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1121 }
1122
1123 GCNTargetMachine &getGCNTargetMachine() const {
1124 return getTM<GCNTargetMachine>();
1125 }
1126
1127 bool addPreISel() override;
1128 void addMachineSSAOptimization() override;
1129 bool addILPOpts() override;
1130 bool addInstSelector() override;
1131 bool addIRTranslator() override;
1132 void addPreLegalizeMachineIR() override;
1133 bool addLegalizeMachineIR() override;
1134 void addPreRegBankSelect() override;
1135 bool addRegBankSelect() override;
1136 void addPreGlobalInstructionSelect() override;
1137 bool addGlobalInstructionSelect() override;
1138 void addFastRegAlloc() override;
1139 void addOptimizedRegAlloc() override;
1140
1141 FunctionPass *createSGPRAllocPass(bool Optimized);
1142 FunctionPass *createVGPRAllocPass(bool Optimized);
1143 FunctionPass *createWWMRegAllocPass(bool Optimized);
1144 FunctionPass *createRegAllocPass(bool Optimized) override;
1145
1146 bool addRegAssignAndRewriteFast() override;
1147 bool addRegAssignAndRewriteOptimized() override;
1148
1149 bool addPreRewrite() override;
1150 void addPostRegAlloc() override;
1151 void addPreSched2() override;
1152 void addPreEmitPass() override;
1153};
1154
1155} // end anonymous namespace
1156
1158 : TargetPassConfig(TM, PM) {
1159 // Exceptions and StackMaps are not supported, so these passes will never do
1160 // anything.
1163 // Garbage collection is not supported.
1166}
1167
1171 else
1173}
1174
1179 // ReassociateGEPs exposes more opportunities for SLSR. See
1180 // the example in reassociate-geps-and-slsr.ll.
1182 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1183 // EarlyCSE can reuse.
1185 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1187 // NaryReassociate on GEPs creates redundant common expressions, so run
1188 // EarlyCSE after it.
1190}
1191
1194
1198
1199 // There is no reason to run these.
1203
1205 if (LowerCtorDtor)
1207
1210
1211 // This can be disabled by passing ::Disable here or on the command line
1212 // with --expand-variadics-override=disable.
1214
1215 // Function calls are not supported, so make sure we inline everything.
1218
1219 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1220 if (Arch == Triple::r600)
1222
1223 // Replace OpenCL enqueued block function pointers with global variables.
1225
1226 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1227 if (EnableSwLowerLDS)
1229
1230 // Runs before PromoteAlloca so the latter can account for function uses
1233 }
1234
1237
1238 // Run atomic optimizer before Atomic Expand
1243 }
1244
1246
1249
1252
1256 AAResults &AAR) {
1257 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1258 AAR.addAAResult(WrapperPass->getResult());
1259 }));
1260 }
1261
1263 // TODO: May want to move later or split into an early and late one.
1265 }
1266
1267 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1268 // have expanded.
1271 }
1272
1274
1275 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1276 // example, GVN can combine
1277 //
1278 // %0 = add %a, %b
1279 // %1 = add %b, %a
1280 //
1281 // and
1282 //
1283 // %0 = shl nsw %a, 2
1284 // %1 = shl %a, 2
1285 //
1286 // but EarlyCSE can do neither of them.
1289}
1290
1293 // FIXME: This pass adds 2 hacky attributes that can be replaced with an
1294 // analysis, and should be removed.
1296 }
1297
1301
1303 // This lowering has been placed after codegenprepare to take advantage of
1304 // address mode matching (which is why it isn't put with the LDS lowerings).
1305 // It could be placed anywhere before uniformity annotations (an analysis
1306 // that it changes by splitting up fat pointers into their components)
1307 // but has been put before switch lowering and CFG flattening so that those
1308 // passes can run on the more optimized control flow this pass creates in
1309 // many cases.
1310 //
1311 // FIXME: This should ideally be put after the LoadStoreVectorizer.
1312 // However, due to some annoying facts about ResourceUsageAnalysis,
1313 // (especially as exercised in the resource-usage-dead-function test),
1314 // we need all the function passes codegenprepare all the way through
1315 // said resource usage analysis to run on the call graph produced
1316 // before codegenprepare runs (because codegenprepare will knock some
1317 // nodes out of the graph, which leads to function-level passes not
1318 // being run on them, which causes crashes in the resource usage analysis).
1320 // In accordance with the above FIXME, manually force all the
1321 // function-level passes into a CGSCCPassManager.
1322 addPass(new DummyCGSCCPass());
1323 }
1324
1326
1329
1330 // LowerSwitch pass may introduce unreachable blocks that can
1331 // cause unexpected behavior for subsequent passes. Placing it
1332 // here seems better that these blocks would get cleaned up by
1333 // UnreachableBlockElim inserted next in the pass flow.
1335}
1336
1340 return false;
1341}
1342
1345 return false;
1346}
1347
1349 // Do nothing. GC is not supported.
1350 return false;
1351}
1352
1353//===----------------------------------------------------------------------===//
1354// GCN Legacy Pass Setup
1355//===----------------------------------------------------------------------===//
1356
1357bool GCNPassConfig::addPreISel() {
1359
1360 if (TM->getOptLevel() > CodeGenOptLevel::None)
1361 addPass(createSinkingPass());
1362
1363 if (TM->getOptLevel() > CodeGenOptLevel::None)
1365
1366 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1367 // regions formed by them.
1369 addPass(createFixIrreduciblePass());
1370 addPass(createUnifyLoopExitsPass());
1371 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1372
1375 // TODO: Move this right after structurizeCFG to avoid extra divergence
1376 // analysis. This depends on stopping SIAnnotateControlFlow from making
1377 // control flow modifications.
1379
1380 addPass(createLCSSAPass());
1381
1382 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1384
1385 return false;
1386}
1387
1388void GCNPassConfig::addMachineSSAOptimization() {
1390
1391 // We want to fold operands after PeepholeOptimizer has run (or as part of
1392 // it), because it will eliminate extra copies making it easier to fold the
1393 // real source operand. We want to eliminate dead instructions after, so that
1394 // we see fewer uses of the copies. We then need to clean up the dead
1395 // instructions leftover after the operands are folded as well.
1396 //
1397 // XXX - Can we get away without running DeadMachineInstructionElim again?
1398 addPass(&SIFoldOperandsLegacyID);
1399 if (EnableDPPCombine)
1400 addPass(&GCNDPPCombineLegacyID);
1402 if (isPassEnabled(EnableSDWAPeephole)) {
1403 addPass(&SIPeepholeSDWALegacyID);
1404 addPass(&EarlyMachineLICMID);
1405 addPass(&MachineCSELegacyID);
1406 addPass(&SIFoldOperandsLegacyID);
1407 }
1410}
1411
1412bool GCNPassConfig::addILPOpts() {
1414 addPass(&EarlyIfConverterLegacyID);
1415
1417 return false;
1418}
1419
1420bool GCNPassConfig::addInstSelector() {
1422 addPass(&SIFixSGPRCopiesLegacyID);
1424 return false;
1425}
1426
1427bool GCNPassConfig::addIRTranslator() {
1428 addPass(new IRTranslator(getOptLevel()));
1429 return false;
1430}
1431
1432void GCNPassConfig::addPreLegalizeMachineIR() {
1433 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1434 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1435 addPass(new Localizer());
1436}
1437
1438bool GCNPassConfig::addLegalizeMachineIR() {
1439 addPass(new Legalizer());
1440 return false;
1441}
1442
1443void GCNPassConfig::addPreRegBankSelect() {
1444 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1445 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1447}
1448
1449bool GCNPassConfig::addRegBankSelect() {
1450 if (NewRegBankSelect) {
1453 } else {
1454 addPass(new RegBankSelect());
1455 }
1456 return false;
1457}
1458
1459void GCNPassConfig::addPreGlobalInstructionSelect() {
1460 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1461 addPass(createAMDGPURegBankCombiner(IsOptNone));
1462}
1463
1464bool GCNPassConfig::addGlobalInstructionSelect() {
1465 addPass(new InstructionSelect(getOptLevel()));
1466 return false;
1467}
1468
1469void GCNPassConfig::addFastRegAlloc() {
1470 // FIXME: We have to disable the verifier here because of PHIElimination +
1471 // TwoAddressInstructions disabling it.
1472
1473 // This must be run immediately after phi elimination and before
1474 // TwoAddressInstructions, otherwise the processing of the tied operand of
1475 // SI_ELSE will introduce a copy of the tied operand source after the else.
1477
1479
1481}
1482
1483void GCNPassConfig::addOptimizedRegAlloc() {
1484 if (EnableDCEInRA)
1486
1487 // FIXME: when an instruction has a Killed operand, and the instruction is
1488 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1489 // the register in LiveVariables, this would trigger a failure in verifier,
1490 // we should fix it and enable the verifier.
1491 if (OptVGPRLiveRange)
1493
1494 // This must be run immediately after phi elimination and before
1495 // TwoAddressInstructions, otherwise the processing of the tied operand of
1496 // SI_ELSE will introduce a copy of the tied operand source after the else.
1498
1501
1502 if (isPassEnabled(EnablePreRAOptimizations))
1504
1505 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1506 // instructions that cause scheduling barriers.
1508
1509 if (OptExecMaskPreRA)
1511
1512 // This is not an essential optimization and it has a noticeable impact on
1513 // compilation time, so we only enable it from O2.
1514 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1516
1518}
1519
1520bool GCNPassConfig::addPreRewrite() {
1522 addPass(&GCNNSAReassignID);
1523 return true;
1524}
1525
1526FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1527 // Initialize the global default.
1528 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1529 initializeDefaultSGPRRegisterAllocatorOnce);
1530
1531 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1532 if (Ctor != useDefaultRegisterAllocator)
1533 return Ctor();
1534
1535 if (Optimized)
1536 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1537
1538 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1539}
1540
1541FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1542 // Initialize the global default.
1543 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1544 initializeDefaultVGPRRegisterAllocatorOnce);
1545
1546 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1547 if (Ctor != useDefaultRegisterAllocator)
1548 return Ctor();
1549
1550 if (Optimized)
1551 return createGreedyVGPRRegisterAllocator();
1552
1553 return createFastVGPRRegisterAllocator();
1554}
1555
1556FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1557 // Initialize the global default.
1558 llvm::call_once(InitializeDefaultWWMRegisterAllocatorFlag,
1559 initializeDefaultWWMRegisterAllocatorOnce);
1560
1561 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1562 if (Ctor != useDefaultRegisterAllocator)
1563 return Ctor();
1564
1565 if (Optimized)
1566 return createGreedyWWMRegisterAllocator();
1567
1568 return createFastWWMRegisterAllocator();
1569}
1570
1571FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1572 llvm_unreachable("should not be used");
1573}
1574
1576 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1577 "and -vgpr-regalloc";
1578
1579bool GCNPassConfig::addRegAssignAndRewriteFast() {
1580 if (!usingDefaultRegAlloc())
1582
1583 addPass(&GCNPreRALongBranchRegID);
1584
1585 addPass(createSGPRAllocPass(false));
1586
1587 // Equivalent of PEI for SGPRs.
1588 addPass(&SILowerSGPRSpillsLegacyID);
1589
1590 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1592
1593 // For allocating other wwm register operands.
1594 addPass(createWWMRegAllocPass(false));
1595
1596 addPass(&SILowerWWMCopiesLegacyID);
1597 addPass(&AMDGPUReserveWWMRegsID);
1598
1599 // For allocating per-thread VGPRs.
1600 addPass(createVGPRAllocPass(false));
1601
1602 return true;
1603}
1604
1605bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1606 if (!usingDefaultRegAlloc())
1608
1609 addPass(&GCNPreRALongBranchRegID);
1610
1611 addPass(createSGPRAllocPass(true));
1612
1613 // Commit allocated register changes. This is mostly necessary because too
1614 // many things rely on the use lists of the physical registers, such as the
1615 // verifier. This is only necessary with allocators which use LiveIntervals,
1616 // since FastRegAlloc does the replacements itself.
1617 addPass(createVirtRegRewriter(false));
1618
1619 // At this point, the sgpr-regalloc has been done and it is good to have the
1620 // stack slot coloring to try to optimize the SGPR spill stack indices before
1621 // attempting the custom SGPR spill lowering.
1622 addPass(&StackSlotColoringID);
1623
1624 // Equivalent of PEI for SGPRs.
1625 addPass(&SILowerSGPRSpillsLegacyID);
1626
1627 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1629
1630 // For allocating other whole wave mode registers.
1631 addPass(createWWMRegAllocPass(true));
1632 addPass(&SILowerWWMCopiesLegacyID);
1633 addPass(createVirtRegRewriter(false));
1634 addPass(&AMDGPUReserveWWMRegsID);
1635
1636 // For allocating per-thread VGPRs.
1637 addPass(createVGPRAllocPass(true));
1638
1639 addPreRewrite();
1640 addPass(&VirtRegRewriterID);
1641
1643
1644 return true;
1645}
1646
1647void GCNPassConfig::addPostRegAlloc() {
1648 addPass(&SIFixVGPRCopiesID);
1649 if (getOptLevel() > CodeGenOptLevel::None)
1652}
1653
1654void GCNPassConfig::addPreSched2() {
1655 if (TM->getOptLevel() > CodeGenOptLevel::None)
1657 addPass(&SIPostRABundlerID);
1658}
1659
1660void GCNPassConfig::addPreEmitPass() {
1661 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1662 addPass(&GCNCreateVOPDID);
1663 addPass(createSIMemoryLegalizerPass());
1664 addPass(createSIInsertWaitcntsPass());
1665
1666 addPass(createSIModeRegisterPass());
1667
1668 if (getOptLevel() > CodeGenOptLevel::None)
1669 addPass(&SIInsertHardClausesID);
1670
1672 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
1674 if (getOptLevel() > CodeGenOptLevel::None)
1675 addPass(&SIPreEmitPeepholeID);
1676 // The hazard recognizer that runs as part of the post-ra scheduler does not
1677 // guarantee to be able handle all hazards correctly. This is because if there
1678 // are multiple scheduling regions in a basic block, the regions are scheduled
1679 // bottom up, so when we begin to schedule a region we don't know what
1680 // instructions were emitted directly before it.
1681 //
1682 // Here we add a stand-alone hazard recognizer pass which can handle all
1683 // cases.
1684 addPass(&PostRAHazardRecognizerID);
1685
1687
1688 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less))
1689 addPass(&AMDGPUInsertDelayAluID);
1690
1691 addPass(&BranchRelaxationPassID);
1693}
1694
1696 return new GCNPassConfig(*this, PM);
1697}
1698
1700 MachineFunction &MF) const {
1702 MF.getRegInfo().addDelegate(MFI);
1703}
1704
1706 BumpPtrAllocator &Allocator, const Function &F,
1707 const TargetSubtargetInfo *STI) const {
1708 return SIMachineFunctionInfo::create<SIMachineFunctionInfo>(
1709 Allocator, F, static_cast<const GCNSubtarget *>(STI));
1710}
1711
1713 return new yaml::SIMachineFunctionInfo();
1714}
1715
1719 return new yaml::SIMachineFunctionInfo(
1720 *MFI, *MF.getSubtarget<GCNSubtarget>().getRegisterInfo(), MF);
1721}
1722
1725 SMDiagnostic &Error, SMRange &SourceRange) const {
1726 const yaml::SIMachineFunctionInfo &YamlMFI =
1727 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1728 MachineFunction &MF = PFS.MF;
1730 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1731
1732 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1733 return true;
1734
1735 if (MFI->Occupancy == 0) {
1736 // Fixup the subtarget dependent default value.
1737 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1738 }
1739
1740 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1741 Register TempReg;
1742 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1743 SourceRange = RegName.SourceRange;
1744 return true;
1745 }
1746 RegVal = TempReg;
1747
1748 return false;
1749 };
1750
1751 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1752 Register &RegVal) {
1753 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1754 };
1755
1756 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
1757 return true;
1758
1759 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
1760 return true;
1761
1762 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
1763 MFI->LongBranchReservedReg))
1764 return true;
1765
1766 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1767 // Create a diagnostic for a the register string literal.
1768 const MemoryBuffer &Buffer =
1769 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1770 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1771 RegName.Value.size(), SourceMgr::DK_Error,
1772 "incorrect register class for field", RegName.Value,
1773 {}, {});
1774 SourceRange = RegName.SourceRange;
1775 return true;
1776 };
1777
1778 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1779 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1780 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1781 return true;
1782
1783 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1784 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1785 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1786 }
1787
1788 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1789 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1790 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1791 }
1792
1793 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1794 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1795 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1796 }
1797
1798 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
1799 Register ParsedReg;
1800 if (parseRegister(YamlReg, ParsedReg))
1801 return true;
1802
1803 MFI->reserveWWMRegister(ParsedReg);
1804 }
1805
1806 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
1807 MFI->setFlag(Info->VReg, Info->Flags);
1808 }
1809 for (const auto &[_, Info] : PFS.VRegInfos) {
1810 MFI->setFlag(Info->VReg, Info->Flags);
1811 }
1812
1813 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
1814 Register ParsedReg;
1815 if (parseRegister(YamlRegStr, ParsedReg))
1816 return true;
1817 MFI->SpillPhysVGPRs.push_back(ParsedReg);
1818 }
1819
1820 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
1821 const TargetRegisterClass &RC,
1822 ArgDescriptor &Arg, unsigned UserSGPRs,
1823 unsigned SystemSGPRs) {
1824 // Skip parsing if it's not present.
1825 if (!A)
1826 return false;
1827
1828 if (A->IsRegister) {
1829 Register Reg;
1830 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
1831 SourceRange = A->RegisterName.SourceRange;
1832 return true;
1833 }
1834 if (!RC.contains(Reg))
1835 return diagnoseRegisterClass(A->RegisterName);
1837 } else
1838 Arg = ArgDescriptor::createStack(A->StackOffset);
1839 // Check and apply the optional mask.
1840 if (A->Mask)
1841 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
1842
1843 MFI->NumUserSGPRs += UserSGPRs;
1844 MFI->NumSystemSGPRs += SystemSGPRs;
1845 return false;
1846 };
1847
1848 if (YamlMFI.ArgInfo &&
1849 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
1850 AMDGPU::SGPR_128RegClass,
1851 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
1852 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
1853 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
1854 2, 0) ||
1855 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
1856 MFI->ArgInfo.QueuePtr, 2, 0) ||
1857 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
1858 AMDGPU::SReg_64RegClass,
1859 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
1860 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
1861 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
1862 2, 0) ||
1863 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
1864 AMDGPU::SReg_64RegClass,
1865 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
1866 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
1867 AMDGPU::SGPR_32RegClass,
1868 MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
1869 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
1870 AMDGPU::SGPR_32RegClass,
1871 MFI->ArgInfo.LDSKernelId, 0, 1) ||
1872 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
1873 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
1874 0, 1) ||
1875 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
1876 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
1877 0, 1) ||
1878 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
1879 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
1880 0, 1) ||
1881 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
1882 AMDGPU::SGPR_32RegClass,
1883 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
1884 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
1885 AMDGPU::SGPR_32RegClass,
1886 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
1887 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
1888 AMDGPU::SReg_64RegClass,
1889 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
1890 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
1891 AMDGPU::SReg_64RegClass,
1892 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
1893 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
1894 AMDGPU::VGPR_32RegClass,
1895 MFI->ArgInfo.WorkItemIDX, 0, 0) ||
1896 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
1897 AMDGPU::VGPR_32RegClass,
1898 MFI->ArgInfo.WorkItemIDY, 0, 0) ||
1899 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
1900 AMDGPU::VGPR_32RegClass,
1901 MFI->ArgInfo.WorkItemIDZ, 0, 0)))
1902 return true;
1903
1904 if (ST.hasIEEEMode())
1905 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
1906 if (ST.hasDX10ClampMode())
1907 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
1908
1909 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
1910 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
1913 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
1916
1923
1924 if (YamlMFI.HasInitWholeWave)
1925 MFI->setInitWholeWave();
1926
1927 return false;
1928}
1929
1930//===----------------------------------------------------------------------===//
1931// AMDGPU CodeGen Pass Builder interface.
1932//===----------------------------------------------------------------------===//
1933
1935 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
1937 : CodeGenPassBuilder(TM, Opts, PIC) {
1938 Opt.MISchedPostRA = true;
1940 // Exceptions and StackMaps are not supported, so these passes will never do
1941 // anything.
1942 // Garbage collection is not supported.
1943 disablePass<StackMapLivenessPass, FuncletLayoutPass,
1945}
1946
1947void AMDGPUCodeGenPassBuilder::addIRPasses(AddIRPass &addPass) const {
1950
1952 if (LowerCtorDtor)
1953 addPass(AMDGPUCtorDtorLoweringPass());
1954
1957
1958 // This can be disabled by passing ::Disable here or on the command line
1959 // with --expand-variadics-override=disable.
1961
1962 addPass(AMDGPUAlwaysInlinePass());
1963 addPass(AlwaysInlinerPass());
1964
1966
1967 if (EnableSwLowerLDS)
1968 addPass(AMDGPUSwLowerLDSPass(TM));
1969
1970 // Runs before PromoteAlloca so the latter can account for function uses
1972 addPass(AMDGPULowerModuleLDSPass(TM));
1973
1975 addPass(InferAddressSpacesPass());
1976
1977 // Run atomic optimizer before Atomic Expand
1981
1982 addPass(AtomicExpandPass(&TM));
1983
1985 addPass(AMDGPUPromoteAllocaPass(TM));
1988
1989 // TODO: Handle EnableAMDGPUAliasAnalysis
1990
1991 // TODO: May want to move later or split into an early and late one.
1992 addPass(AMDGPUCodeGenPreparePass(TM));
1993
1994 // TODO: LICM
1995 }
1996
1997 Base::addIRPasses(addPass);
1998
1999 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2000 // example, GVN can combine
2001 //
2002 // %0 = add %a, %b
2003 // %1 = add %b, %a
2004 //
2005 // and
2006 //
2007 // %0 = shl nsw %a, 2
2008 // %1 = shl %a, 2
2009 //
2010 // but EarlyCSE can do neither of them.
2012 addEarlyCSEOrGVNPass(addPass);
2013}
2014
2015void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(AddIRPass &addPass) const {
2016 // AMDGPUAnnotateKernelFeaturesPass is missing here, but it will hopefully be
2017 // deleted soon.
2018
2021
2022 // This lowering has been placed after codegenprepare to take advantage of
2023 // address mode matching (which is why it isn't put with the LDS lowerings).
2024 // It could be placed anywhere before uniformity annotations (an analysis
2025 // that it changes by splitting up fat pointers into their components)
2026 // but has been put before switch lowering and CFG flattening so that those
2027 // passes can run on the more optimized control flow this pass creates in
2028 // many cases.
2029 //
2030 // FIXME: This should ideally be put after the LoadStoreVectorizer.
2031 // However, due to some annoying facts about ResourceUsageAnalysis,
2032 // (especially as exercised in the resource-usage-dead-function test),
2033 // we need all the function passes codegenprepare all the way through
2034 // said resource usage analysis to run on the call graph produced
2035 // before codegenprepare runs (because codegenprepare will knock some
2036 // nodes out of the graph, which leads to function-level passes not
2037 // being run on them, which causes crashes in the resource usage analysis).
2039
2040 Base::addCodeGenPrepare(addPass);
2041
2043 addPass(LoadStoreVectorizerPass());
2044
2045 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2046 // behavior for subsequent passes. Placing it here seems better that these
2047 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2048 // pass flow.
2049 addPass(LowerSwitchPass());
2050}
2051
2052void AMDGPUCodeGenPassBuilder::addPreISel(AddIRPass &addPass) const {
2053
2055 addPass(FlattenCFGPass());
2056
2058 addPass(SinkingPass());
2059
2061
2062 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2063 // regions formed by them.
2064
2066 addPass(FixIrreduciblePass());
2067 addPass(UnifyLoopExitsPass());
2068 addPass(StructurizeCFGPass(/*SkipUniformRegions=*/false));
2069
2071
2072 addPass(SIAnnotateControlFlowPass(TM));
2073
2074 // TODO: Move this right after structurizeCFG to avoid extra divergence
2075 // analysis. This depends on stopping SIAnnotateControlFlow from making
2076 // control flow modifications.
2078
2079 addPass(LCSSAPass());
2080
2083
2084 // FIXME: Why isn't this queried as required from AMDGPUISelDAGToDAG, and why
2085 // isn't this in addInstSelector?
2087}
2088
2089void AMDGPUCodeGenPassBuilder::addILPOpts(AddMachinePass &addPass) const {
2091 addPass(EarlyIfConverterPass());
2092
2093 Base::addILPOpts(addPass);
2094}
2095
2096void AMDGPUCodeGenPassBuilder::addAsmPrinter(AddMachinePass &addPass,
2097 CreateMCStreamer) const {
2098 // TODO: Add AsmPrinter.
2099}
2100
2101Error AMDGPUCodeGenPassBuilder::addInstSelector(AddMachinePass &addPass) const {
2102 addPass(AMDGPUISelDAGToDAGPass(TM));
2103 addPass(SIFixSGPRCopiesPass());
2104 addPass(SILowerI1CopiesPass());
2105 return Error::success();
2106}
2107
2109 AddMachinePass &addPass) const {
2111
2112 addPass(SIFoldOperandsPass());
2113 if (EnableDPPCombine) {
2114 addPass(GCNDPPCombinePass());
2115 }
2116 addPass(SILoadStoreOptimizerPass());
2118 addPass(SIPeepholeSDWAPass());
2119 addPass(EarlyMachineLICMPass());
2120 addPass(MachineCSEPass());
2121 addPass(SIFoldOperandsPass());
2122 }
2124 addPass(SIShrinkInstructionsPass());
2125}
2126
2127void AMDGPUCodeGenPassBuilder::addPostRegAlloc(AddMachinePass &addPass) const {
2128 addPass(SIFixVGPRCopiesPass());
2130 addPass(SIOptimizeExecMaskingPass());
2131 Base::addPostRegAlloc(addPass);
2132}
2133
2135 CodeGenOptLevel Level) const {
2136 if (Opt.getNumOccurrences())
2137 return Opt;
2138 if (TM.getOptLevel() < Level)
2139 return false;
2140 return Opt;
2141}
2142
2145 addPass(GVNPass());
2146 else
2147 addPass(EarlyCSEPass());
2148}
2149
2151 AddIRPass &addPass) const {
2153 addPass(LoopDataPrefetchPass());
2154
2156
2157 // ReassociateGEPs exposes more opportunities for SLSR. See
2158 // the example in reassociate-geps-and-slsr.ll.
2160
2161 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2162 // EarlyCSE can reuse.
2163 addEarlyCSEOrGVNPass(addPass);
2164
2165 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2166 addPass(NaryReassociatePass());
2167
2168 // NaryReassociate on GEPs creates redundant common expressions, so run
2169 // EarlyCSE after it.
2170 addPass(EarlyCSEPass());
2171}
unsigned const MachineRegisterInfo * MRI
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
static cl::opt< bool > EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden, cl::desc("Run early if-conversion"), cl::init(true))
This is the AMGPU address space based alias analysis pass.
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...
static cl::opt< bool > EnableDCEInRA("amdgpu-dce-in-ra", cl::init(true), cl::Hidden, cl::desc("Enable machine DCE inside regalloc"))
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 MachineSchedRegistry GCNMaxMemoryClauseSchedRegistry("gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause", createGCNMaxMemoryClauseMachineScheduler)
static MachineSchedRegistry SISchedRegistry("si", "Run SI's custom scheduler", createSIMachineScheduler)
static ScheduleDAGInstrs * createIterativeILPMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EarlyInlineAll("amdgpu-early-inline-all", cl::desc("Inline all functions early"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableSwLowerLDS("amdgpu-enable-sw-lower-lds", cl::desc("Enable lowering of lds to global memory pass " "and asan instrument resulting IR."), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableLowerKernelArguments("amdgpu-ir-lower-kernel-arguments", cl::desc("Lower kernel argument loads in IR pass"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxILPMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableSDWAPeephole("amdgpu-sdwa-peephole", cl::desc("Enable SDWA peepholer"), cl::init(true))
static MachineSchedRegistry GCNMinRegSchedRegistry("gcn-iterative-minreg", "Run GCN iterative scheduler for minimal register usage (experimental)", createMinRegScheduler)
static cl::opt< bool > EnableImageIntrinsicOptimizer("amdgpu-enable-image-intrinsic-optimizer", cl::desc("Enable image intrinsic optimizer pass"), cl::init(true), cl::Hidden)
static cl::opt< bool > HasClosedWorldAssumption("amdgpu-link-time-closed-world", cl::desc("Whether has closed-world assumption at link time"), cl::init(false), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxMemoryClauseMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableSIModeRegisterPass("amdgpu-mode-register", cl::desc("Enable mode register pass"), cl::init(true), cl::Hidden)
static cl::opt< std::string > AMDGPUSchedStrategy("amdgpu-sched-strategy", cl::desc("Select custom AMDGPU scheduling strategy."), cl::Hidden, cl::init(""))
static cl::opt< bool > EnableDPPCombine("amdgpu-dpp-combine", cl::desc("Enable DPP combiner"), cl::init(true))
static MachineSchedRegistry IterativeGCNMaxOccupancySchedRegistry("gcn-iterative-max-occupancy-experimental", "Run GCN scheduler to maximize occupancy (experimental)", createIterativeGCNMaxOccupancyMachineScheduler)
static cl::opt< bool > EnableSetWavePriority("amdgpu-set-wave-priority", cl::desc("Adjust wave priority"), cl::init(false), cl::Hidden)
static cl::opt< bool > LowerCtorDtor("amdgpu-lower-global-ctor-dtor", cl::desc("Lower GPU ctor / dtors to globals on the device."), cl::init(true), cl::Hidden)
static cl::opt< bool > OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden, cl::desc("Run pre-RA exec mask optimizations"), cl::init(true))
static cl::opt< bool > EnablePromoteKernelArguments("amdgpu-enable-promote-kernel-arguments", cl::desc("Enable promotion of flat kernel pointer arguments to global"), cl::Hidden, cl::init(true))
static cl::opt< bool > EnableRewritePartialRegUses("amdgpu-enable-rewrite-partial-reg-uses", cl::desc("Enable rewrite partial reg uses pass"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableLibCallSimplify("amdgpu-simplify-libcall", cl::desc("Enable amdgpu library simplifications"), cl::init(true), cl::Hidden)
static MachineSchedRegistry GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp", createGCNMaxILPMachineScheduler)
static cl::opt< bool > InternalizeSymbols("amdgpu-internalize-symbols", cl::desc("Enable elimination of non-kernel functions and unused globals"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableAMDGPUAttributor("amdgpu-attributor-enable", cl::desc("Enable AMDGPUAttributorPass"), cl::init(true), cl::Hidden)
static LLVM_READNONE StringRef getGPUOrDefault(const Triple &TT, StringRef GPU)
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
Expected< AMDGPUAttributorOptions > parseAMDGPUAttributorPassOptions(StringRef Params)
static cl::opt< bool > EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden, cl::desc("Enable AMDGPU Alias Analysis"), cl::init(true))
static Expected< ScanOptions > parseAMDGPUAtomicOptimizerStrategy(StringRef Params)
static ScheduleDAGInstrs * createMinRegScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableHipStdPar("amdgpu-enable-hipstdpar", cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableInsertDelayAlu("amdgpu-enable-delay-alu", cl::desc("Enable s_delay_alu insertion"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableLoadStoreVectorizer("amdgpu-load-store-vectorizer", cl::desc("Enable load store vectorizer"), cl::init(true), cl::Hidden)
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
static cl::opt< bool > EnableLoopPrefetch("amdgpu-loop-prefetch", cl::desc("Enable loop data prefetch on AMDGPU"), cl::Hidden, cl::init(false))
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget()
static cl::opt< bool > NewRegBankSelect("new-reg-bank-select", cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of " "regbankselect"), cl::init(false), cl::Hidden)
static cl::opt< bool > RemoveIncompatibleFunctions("amdgpu-enable-remove-incompatible-functions", cl::Hidden, cl::desc("Enable removal of functions when they" "use features not supported by the target GPU"), cl::init(true))
static cl::opt< bool > EnableScalarIRPasses("amdgpu-scalar-ir-passes", cl::desc("Enable scalar IR passes"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableRegReassign("amdgpu-reassign-regs", cl::desc("Enable register reassign optimizations on gfx10+"), cl::init(true), cl::Hidden)
static cl::opt< bool > OptVGPRLiveRange("amdgpu-opt-vgpr-liverange", cl::desc("Enable VGPR liverange optimizations for if-else structure"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createSIMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnablePreRAOptimizations("amdgpu-enable-pre-ra-optimizations", cl::desc("Enable Pre-RA optimizations pass"), cl::init(true), cl::Hidden)
static cl::opt< ScanOptions > AMDGPUAtomicOptimizerStrategy("amdgpu-atomic-optimizer-strategy", cl::desc("Select DPP or Iterative strategy for scan"), cl::init(ScanOptions::Iterative), cl::values(clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"), clEnumValN(ScanOptions::Iterative, "Iterative", "Use Iterative approach for scan"), clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")))
static cl::opt< bool > EnableVOPD("amdgpu-enable-vopd", cl::desc("Enable VOPD, dual issue of VALU in wave32"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableEarlyIfConversion("amdgpu-early-ifcvt", cl::Hidden, cl::desc("Run early if-conversion"), cl::init(false))
static ScheduleDAGInstrs * createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static MachineSchedRegistry GCNILPSchedRegistry("gcn-iterative-ilp", "Run GCN iterative scheduler for ILP scheduling (experimental)", createIterativeILPMachineScheduler)
static cl::opt< bool > ScalarizeGlobal("amdgpu-scalarize-global-loads", cl::desc("Enable global load scalarization"), cl::init(true), cl::Hidden)
static const char RegAllocOptNotSupportedMessage[]
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 TargetTransformInfo::Concept conforming object specific to the AMDGPU target machine.
Provides passes to inlining "always_inline" functions.
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.
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
Provides analysis for continuously CSEing during GISel passes.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:686
#define LLVM_READNONE
Definition: Compiler.h:299
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:128
This file provides the interface for a simple, fast CSE pass.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
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.
This header defines various interfaces for pass management in LLVM.
#define RegName(no)
static LVOptions Options
Definition: LVOptions.cpp:25
static std::string computeDataLayout()
This file provides the interface for LLVM's Loop Data Prefetching Pass.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
#define P(N)
CGSCCAnalysisManager CGAM
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
The AMDGPU TargetMachine interface definition for hw codegen targets.
Basic Register Allocator
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SI Machine Scheduler interface.
static FunctionPass * useDefaultRegisterAllocator()
-regalloc=... command line option.
Target-Independent Code Generator Pass Configuration Options pass.
LLVM IR instance of the generic uniformity analysis.
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.
Error addInstSelector(AddMachinePass &) const
void addMachineSSAOptimization(AddMachinePass &) const
void addEarlyCSEOrGVNPass(AddIRPass &) const
void addStraightLineScalarOptimizationPasses(AddIRPass &) const
AMDGPUCodeGenPassBuilder(GCNTargetMachine &TM, const CGPassBuilderOption &Opts, PassInstrumentationCallbacks *PIC)
void addPreISel(AddIRPass &addPass) const
void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const
void addCodeGenPrepare(AddIRPass &) const
void addILPOpts(AddMachinePass &) const
void addPostRegAlloc(AddMachinePass &) const
bool isPassEnabled(const cl::opt< bool > &Opt, CodeGenOptLevel Level=CodeGenOptLevel::Default) const
Check if a pass is enabled given Opt option.
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.
bool isPassEnabled(const cl::opt< bool > &Opt, CodeGenOptLevel Level=CodeGenOptLevel::Default) const
Check if a pass is enabled given Opt option.
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)
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.
static int64_t getNullPointerValue(unsigned AddrSpace)
Get the integer value of a null pointer in the given address space.
unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const override
getAddressSpaceForPseudoSourceKind - Given the kind of memory (e.g.
const TargetSubtargetInfo * getSubtargetImpl() const
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,...
StringRef getFeatureString(const Function &F) const
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
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)
bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
StringRef getGPUName(const Function &F) const
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".
Definition: AlwaysInliner.h:32
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:396
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition: Attributes.h:209
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
This class provides access to building LLVM's passes.
void addPostRegAlloc(AddMachinePass &) const
This method may be implemented by targets that want to run passes after register allocation pass pipe...
void addILPOpts(AddMachinePass &) const
Add passes that optimize instruction level parallelism for out-of-order targets.
Error buildPipeline(ModulePassManager &MPM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType) const
void addMachineSSAOptimization(AddMachinePass &) const
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
void addCodeGenPrepare(AddIRPass &) const
Add pass to prepare the LLVM IR for code generation.
void disablePass()
Allow the target to disable a specific pass by default.
void addIRPasses(AddIRPass &) const
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
implements a set of functionality in the TargetMachine class for targets that make use of the indepen...
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:739
This pass is required by interprocedural register allocation.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
const SIRegisterInfo * getRegisterInfo() const override
Definition: GCNSubtarget.h:291
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
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.
Error buildCodeGenPipeline(ModulePassManager &MPM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, const CGPassBuilderOption &Opts, PassInstrumentationCallbacks *PIC) override
yaml::MachineFunctionInfo * createDefaultFuncInfoYAML() const override
Allocate and return a default initialized instance of the YAML representation for the MachineFunction...
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)
MachineFunctionInfo * createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F, const TargetSubtargetInfo *STI) const override
Create the target's instance of MachineFunctionInfo.
The core GVN pass object.
Definition: GVN.h:124
Pass to remove unused function declarations.
Definition: GlobalDCE.h:36
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:36
Converts loops into loop-closed SSA form.
Definition: LCSSA.h:37
This pass implements the localization mechanism described at the top of this file.
Definition: Localizer.h:43
An optimization pass inserting data prefetches in loops.
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...
Definition: MemoryBuffer.h:51
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
Definition: MemoryBuffer.h:76
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static const OptimizationLevel O0
Disable as many optimizations as possible.
unsigned getSpeedupLevel() const
static const OptimizationLevel O1
Optimize quickly without destroying debuggability.
This class provides access to building LLVM's passes.
Definition: PassBuilder.h:109
void registerPipelineEarlySimplificationEPCallback(const std::function< void(ModulePassManager &, OptimizationLevel, ThinOrFullLTOPhase)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:497
void registerPipelineStartEPCallback(const std::function< void(ModulePassManager &, OptimizationLevel)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:488
void crossRegisterProxies(LoopAnalysisManager &LAM, FunctionAnalysisManager &FAM, CGSCCAnalysisManager &CGAM, ModuleAnalysisManager &MAM, MachineFunctionAnalysisManager *MFAM=nullptr)
Cross register the analysis managers through their proxies.
void registerOptimizerLastEPCallback(const std::function< void(ModulePassManager &, OptimizationLevel, ThinOrFullLTOPhase)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:517
void registerPeepholeEPCallback(const std::function< void(FunctionPassManager &, OptimizationLevel)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:411
void registerCGSCCOptimizerLateEPCallback(const std::function< void(CGSCCPassManager &, OptimizationLevel)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:456
void registerRegClassFilterParsingCallback(const std::function< RegAllocFilterFunc(StringRef)> &C)
Register callbacks to parse target specific filter field if regalloc pass needs it.
Definition: PassBuilder.h:607
void registerModuleAnalyses(ModuleAnalysisManager &MAM)
Registers all available module analysis passes.
void registerFullLinkTimeOptimizationLastEPCallback(const std::function< void(ModulePassManager &, OptimizationLevel)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:536
void registerFunctionAnalyses(FunctionAnalysisManager &FAM)
Registers all available function analysis passes.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
Definition: PassManager.h:195
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...
Definition: PassRegistry.h:37
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
Definition: RegBankSelect.h:91
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:19
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:281
Represents a location in source code.
Definition: SMLoc.h:23
Represents a range in source code.
Definition: SMLoc.h:48
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.
Definition: ScheduleDAG.h:575
const TargetRegisterInfo * TRI
Target processor register info.
Definition: ScheduleDAG.h:576
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:26
void append(StringRef RHS)
Append from a StringRef.
Definition: SmallString.h:68
unsigned getMainFileID() const
Definition: SourceMgr.h:132
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:125
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:700
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:635
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:43
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:68
R Default(T Value)
Definition: StringSwitch.h:177
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:87
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:81
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
StringRef getTargetCPU() const
std::unique_ptr< const MCSubtargetInfo > STI
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
std::unique_ptr< const MCRegisterInfo > MRI
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.
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:44
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:395
bool isAMDGCN() const
Tests whether the target is AMDGCN.
Definition: Triple.h:886
LLVM Value Representation.
Definition: Value.h:74
bool use_empty() const
Definition: Value.h:344
int getNumOccurrences() const
Definition: CommandLine.h:399
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 ...
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:434
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.
llvm::cl::opt< bool > NoKernelInfoEndLTO
This file defines the TargetMachine class.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ 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.
bool isFlatGlobalAddrSpace(unsigned AS)
bool isEntryFunctionCC(CallingConv::ID CC)
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
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)
Definition: PatternMatch.h:49
deferredval_ty< 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()...
Definition: PatternMatch.h:903
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:711
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:463
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FunctionPass * createFlattenCFGPass()
void initializeSIFormMemoryClausesPass(PassRegistry &)
FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
ImmutablePass * createAMDGPUAAWrapperPass()
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()
Pass * createLCSSAPass()
Definition: LCSSA.cpp:541
void initializeGCNCreateVOPDPass(PassRegistry &)
char & GCNPreRAOptimizationsID
char & GCLoweringID
GCLowering Pass - Used by gc.root to perform its default lowering operations.
Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
void initializeAMDGPUAttributorLegacyPass(PassRegistry &)
char & SIPostRABundlerID
FunctionPass * createSIAnnotateControlFlowLegacyPass()
Create the annotation pass.
FunctionPass * createSIModeRegisterPass()
void initializeGCNPreRAOptimizationsLegacyPass(PassRegistry &)
void initializeSILowerWWMCopiesLegacyPass(PassRegistry &)
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 &)
void initializeSIModeRegisterPass(PassRegistry &)
ModulePass * createAMDGPUCtorDtorLoweringLegacyPass()
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
Definition: PassManager.h:852
ModulePass * createAMDGPUSwLowerLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
void initializeGCNRewritePartialRegUsesLegacyPass(llvm::PassRegistry &)
void initializeAMDGPURewriteUndefForPHILegacyPass(PassRegistry &)
FunctionPass * createAMDGPUPreLegalizeCombiner(bool IsOptNone)
char & GCNRewritePartialRegUsesID
FunctionPass * createAMDGPUPostLegalizeCombiner(bool IsOptNone)
void initializeAMDGPUSwLowerLDSLegacyPass(PassRegistry &)
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
char & AMDGPUWaitSGPRHazardsLegacyID
void initializeSILowerSGPRSpillsLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
void initializeAMDGPUDAGToDAGISelLegacyPass(PassRegistry &)
FunctionPass * createNaryReassociatePass()
void initializeAMDGPUWaitSGPRHazardsLegacyPass(PassRegistry &)
char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
char & SIOptimizeExecMaskingLegacyID
char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
void initializeR600ExpandSpecialInstrsPassPass(PassRegistry &)
void initializeR600PacketizerPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createVOPDPairingMutation()
ModulePass * createAMDGPUAlwaysInlinePass(bool GlobalOpt=true)
void initializeSIPreEmitPeepholePass(PassRegistry &)
void initializeSIFoldOperandsLegacyPass(PassRegistry &)
char & SILoadStoreOptimizerLegacyID
void initializeAMDGPUGlobalISelDivergenceLoweringPass(PassRegistry &)
std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition: CSEInfo.cpp:89
Target & getTheR600Target()
The target for R600 GPUs.
char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
Pass * createStructurizeCFGPass(bool SkipUniformRegions=false)
When SkipUniformRegions is true the structizer will not structurize regions that only contain uniform...
void initializeGCNNSAReassignPass(PassRegistry &)
char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
void initializeAMDGPUOpenCLEnqueuedBlockLoweringLegacyPass(PassRegistry &)
void initializeSIInsertWaitcntsPass(PassRegistry &)
Pass * createLICMPass()
Definition: LICM.cpp:381
ScheduleDAGMILive * createGenericSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
char & SIFormMemoryClausesID
void initializeSILoadStoreOptimizerLegacyPass(PassRegistry &)
void initializeAMDGPULowerModuleLDSLegacyPass(PassRegistry &)
void initializeAMDGPUCtorDtorLoweringLegacyPass(PassRegistry &)
char & EarlyIfConverterLegacyID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions.
void initializeAMDGPURegBankCombinerPass(PassRegistry &)
void initializeSILateBranchLoweringPass(PassRegistry &)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition: Pass.h:76
char & AMDGPUUnifyDivergentExitNodesID
FunctionPass * createAMDGPUAtomicOptimizerPass(ScanOptions ScanStrategy)
FunctionPass * createAMDGPUPreloadKernArgPrologLegacyPass()
char & SIOptimizeVGPRLiveRangeLegacyID
char & ShadowStackGCLoweringID
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
char & GCNNSAReassignID
void initializeAMDGPURewriteOutArgumentsPass(PassRegistry &)
void initializeAMDGPUExternalAAWrapperPass(PassRegistry &)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void initializeAMDGPULowerKernelArgumentsPass(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.
char & SILateBranchLoweringPassID
char & BranchRelaxationPassID
BranchRelaxation - This pass replaces branches that need to jump further than is supported by a branc...
FunctionPass * createSinkingPass()
Definition: Sink.cpp:277
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 initializeAMDGPUAnnotateKernelFeaturesPass(PassRegistry &)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition: CodeGen.h:83
void initializeSIPostRABundlerPass(PassRegistry &)
void initializeAMDGPUPromoteAllocaToVectorPass(PassRegistry &)
char & GCNDPPCombineLegacyID
std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
FunctionPass * createLoopDataPrefetchPass()
FunctionPass * createAMDGPULowerKernelArgumentsPass()
char & AMDGPUInsertDelayAluID
Pass * createAMDGPUAnnotateKernelFeaturesPass()
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
std::unique_ptr< ScheduleDAGMutation > createAMDGPUMacroFusionDAGMutation()
Note that you have to add: DAG.addMutation(createAMDGPUMacroFusionDAGMutation()); to AMDGPUTargetMach...
char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
void initializeGCNPreRALongBranchRegLegacyPass(PassRegistry &)
char & SILowerWWMCopiesLegacyID
FunctionPass * createUnifyLoopExitsPass()
char & SIOptimizeExecMaskingPreRAID
FunctionPass * createFixIrreduciblePass()
char & FuncletLayoutID
This pass lays out funclets contiguously.
void initializeSIInsertHardClausesPass(PassRegistry &)
char & DetectDeadLanesID
This pass adds dead/undef flags after analyzing subregister lanes.
void initializeAMDGPUPostLegalizerCombinerPass(PassRegistry &)
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
void initializeAMDGPUReserveWWMRegsPass(PassRegistry &)
ModulePass * createAMDGPUPrintfRuntimeBinding()
char & StackSlotColoringID
StackSlotColoring - This pass performs stack slot coloring.
void initializeSIMemoryLegalizerPass(PassRegistry &)
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 initializeSILowerControlFlowLegacyPass(PassRegistry &)
char & SIPreAllocateWWMRegsLegacyID
ModulePass * createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
void initializeAMDGPUPreLegalizerCombinerPass(PassRegistry &)
char & AMDGPUReserveWWMRegsID
FunctionPass * createAMDGPUPromoteAlloca()
FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
char & SIPreEmitPeepholeID
ModulePass * createAMDGPURemoveIncompatibleFunctionsPass(const TargetMachine *)
void initializeGCNRegPressurePrinterPass(PassRegistry &)
void initializeSILowerI1CopiesLegacyPass(PassRegistry &)
char & SILowerSGPRSpillsLegacyID
void initializeAMDGPUArgumentUsageInfoPass(PassRegistry &)
FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
Definition: GlobalISel.cpp:17
char & SILowerControlFlowLegacyID
ModulePass * createR600OpenCLImageTypeLoweringPass()
FunctionPass * createAMDGPUCodeGenPreparePass()
void initializeSIAnnotateControlFlowLegacyPass(PassRegistry &)
ModulePass * createAMDGPUOpenCLEnqueuedBlockLoweringLegacyPass()
FunctionPass * createAMDGPUISelDag(TargetMachine &TM, CodeGenOptLevel OptLevel)
This pass converts a legalized DAG into a AMDGPU-specific.
void initializeSIPreAllocateWWMRegsLegacyPass(PassRegistry &)
void initializeSIFixVGPRCopiesLegacyPass(PassRegistry &)
Target & getTheGCNTarget()
The target for GCN GPUs.
void initializeSIFixSGPRCopiesLegacyPass(PassRegistry &)
void initializeAMDGPUAtomicOptimizerPass(PassRegistry &)
FunctionPass * createGVNPass()
Create a legacy GVN pass.
Definition: GVN.cpp:3378
FunctionPass * createAMDGPURegBankSelectPass()
FunctionPass * createAMDGPURegBankCombiner(bool IsOptNone)
FunctionPass * createAMDGPURegBankLegalizePass()
char & MachineCSELegacyID
MachineCSE - This pass performs global CSE on machine instructions.
Definition: MachineCSE.cpp:164
char & SIWholeQuadModeID
std::unique_ptr< ScheduleDAGMutation > createLoadClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
void initializeSIOptimizeExecMaskingPreRAPass(PassRegistry &)
void initializeAMDGPUMarkLastScratchLoadPass(PassRegistry &)
char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
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()
void initializeAMDGPULowerKernelAttributesPass(PassRegistry &)
char & SIInsertHardClausesID
void initializeAMDGPUResourceUsageAnalysisPass(PassRegistry &)
char & SIFixSGPRCopiesLegacyID
void initializeGCNDPPCombineLegacyPass(PassRegistry &)
char & GCNCreateVOPDID
FunctionPass * createInferAddressSpacesPass(unsigned AddressSpace=~0u)
char & SIPeepholeSDWALegacyID
char & VirtRegRewriterID
VirtRegRewriter pass.
Definition: VirtRegMap.cpp:250
char & SIFixVGPRCopiesID
char & SIFoldOperandsLegacyID
FunctionPass * createLowerSwitchPass()
void initializeAMDGPUPreloadKernArgPrologLegacyPass(PassRegistry &)
FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
Definition: VirtRegMap.cpp:734
void initializeR600VectorRegMergerPass(PassRegistry &)
ImmutablePass * createExternalAAWrapperPass(std::function< void(Pass &, Function &, AAResults &)> Callback)
A wrapper pass around a callback which can be used to populate the AAResults in the AAResultsWrapperP...
FunctionPass * createAMDGPUGlobalISelDivergenceLoweringPass()
FunctionPass * createSIMemoryLegalizerPass()
void initializeAMDGPULateCodeGenPrepareLegacyPass(PassRegistry &)
void initializeSIOptimizeVGPRLiveRangeLegacyPass(PassRegistry &)
void initializeSIPeepholeSDWALegacyPass(PassRegistry &)
void initializeAMDGPURegBankLegalizePass(PassRegistry &)
char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
void initializeAMDGPURegBankSelectPass(PassRegistry &)
FunctionPass * createAMDGPULateCodeGenPrepareLegacyPass()
FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
MCRegisterInfo * createGCNMCRegisterInfo(AMDGPUDwarfFlavour DwarfFlavour)
FunctionPass * createStraightLineStrengthReducePass()
FunctionPass * createAMDGPUImageIntrinsicOptimizerPass(const TargetMachine *)
void initializeAMDGPUUnifyDivergentExitNodesPass(PassRegistry &)
void initializeAMDGPULowerBufferFatPointersPass(PassRegistry &)
FunctionPass * createSIInsertWaitcntsPass()
FunctionPass * createAMDGPUAnnotateUniformValuesLegacy()
FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
Definition: EarlyCSE.cpp:1944
void initializeSIWholeQuadModeLegacyPass(PassRegistry &)
char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3603
FunctionPass * createSIShrinkInstructionsLegacyPass()
char & AMDGPUMarkLastScratchLoadID
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 &)
void initializeAMDGPUInsertDelayAluPass(PassRegistry &)
void initializeAMDGPUUnifyMetadataPass(PassRegistry &)
void initializeAMDGPUAlwaysInlinePass(PassRegistry &)
char & DeadMachineInstructionElimID
DeadMachineInstructionElim - This pass removes dead machine instructions.
char & AMDGPUPerfHintAnalysisLegacyID
char & GCNPreRALongBranchRegID
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)
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:30
MachineFunctionInfo - This class can be derived from and used by targets to hold private target-speci...
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
StringMap< VRegInfo * > VRegInfosNamed
Definition: MIParser.h:177
DenseMap< Register, VRegInfo * > VRegInfos
Definition: MIParser.h:176
RegisterTargetMachine - Helper template for registering a target machine implementation,...
A utility pass template to force an analysis result to be available.
Definition: PassManager.h:878
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.