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"
35#include "GCNSchedStrategy.h"
36#include "GCNVOPDUtils.h"
37#include "R600.h"
38#include "R600TargetMachine.h"
39#include "SIFixSGPRCopies.h"
40#include "SIFixVGPRCopies.h"
41#include "SIFoldOperands.h"
43#include "SILowerControlFlow.h"
44#include "SILowerSGPRSpills.h"
45#include "SILowerWWMCopies.h"
47#include "SIMachineScheduler.h"
50#include "SIPeepholeSDWA.h"
70#include "llvm/CodeGen/Passes.h"
73#include "llvm/IR/IntrinsicsAMDGPU.h"
74#include "llvm/IR/PassManager.h"
81#include "llvm/Transforms/IPO.h"
104#include <optional>
105
106using namespace llvm;
107using namespace llvm::PatternMatch;
108
109namespace {
110class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
111public:
112 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
113 : RegisterRegAllocBase(N, D, C) {}
114};
115
116class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
117public:
118 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
119 : RegisterRegAllocBase(N, D, C) {}
120};
121
122class WWMRegisterRegAlloc : public RegisterRegAllocBase<WWMRegisterRegAlloc> {
123public:
124 WWMRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
125 : RegisterRegAllocBase(N, D, C) {}
126};
127
128static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI,
130 const Register Reg) {
131 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
132 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
133}
134
135static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI,
137 const Register Reg) {
138 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
139 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
140}
141
142static bool onlyAllocateWWMRegs(const TargetRegisterInfo &TRI,
144 const Register Reg) {
145 const SIMachineFunctionInfo *MFI =
146 MRI.getMF().getInfo<SIMachineFunctionInfo>();
147 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
148 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC) &&
150}
151
152/// -{sgpr|wwm|vgpr}-regalloc=... command line option.
153static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
154
155/// A dummy default pass factory indicates whether the register allocator is
156/// overridden on the command line.
157static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag;
158static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag;
159static llvm::once_flag InitializeDefaultWWMRegisterAllocatorFlag;
160
161static SGPRRegisterRegAlloc
162defaultSGPRRegAlloc("default",
163 "pick SGPR register allocator based on -O option",
165
166static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
168SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
169 cl::desc("Register allocator to use for SGPRs"));
170
171static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
173VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
174 cl::desc("Register allocator to use for VGPRs"));
175
176static cl::opt<WWMRegisterRegAlloc::FunctionPassCtor, false,
178 WWMRegAlloc("wwm-regalloc", cl::Hidden,
180 cl::desc("Register allocator to use for WWM registers"));
181
182static void initializeDefaultSGPRRegisterAllocatorOnce() {
183 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
184
185 if (!Ctor) {
186 Ctor = SGPRRegAlloc;
187 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
188 }
189}
190
191static void initializeDefaultVGPRRegisterAllocatorOnce() {
192 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
193
194 if (!Ctor) {
195 Ctor = VGPRRegAlloc;
196 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
197 }
198}
199
200static void initializeDefaultWWMRegisterAllocatorOnce() {
201 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
202
203 if (!Ctor) {
204 Ctor = WWMRegAlloc;
205 WWMRegisterRegAlloc::setDefault(WWMRegAlloc);
206 }
207}
208
209static FunctionPass *createBasicSGPRRegisterAllocator() {
210 return createBasicRegisterAllocator(onlyAllocateSGPRs);
211}
212
213static FunctionPass *createGreedySGPRRegisterAllocator() {
214 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
215}
216
217static FunctionPass *createFastSGPRRegisterAllocator() {
218 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
219}
220
221static FunctionPass *createBasicVGPRRegisterAllocator() {
222 return createBasicRegisterAllocator(onlyAllocateVGPRs);
223}
224
225static FunctionPass *createGreedyVGPRRegisterAllocator() {
226 return createGreedyRegisterAllocator(onlyAllocateVGPRs);
227}
228
229static FunctionPass *createFastVGPRRegisterAllocator() {
230 return createFastRegisterAllocator(onlyAllocateVGPRs, true);
231}
232
233static FunctionPass *createBasicWWMRegisterAllocator() {
234 return createBasicRegisterAllocator(onlyAllocateWWMRegs);
235}
236
237static FunctionPass *createGreedyWWMRegisterAllocator() {
238 return createGreedyRegisterAllocator(onlyAllocateWWMRegs);
239}
240
241static FunctionPass *createFastWWMRegisterAllocator() {
242 return createFastRegisterAllocator(onlyAllocateWWMRegs, false);
243}
244
245static SGPRRegisterRegAlloc basicRegAllocSGPR(
246 "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
247static SGPRRegisterRegAlloc greedyRegAllocSGPR(
248 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
249
250static SGPRRegisterRegAlloc fastRegAllocSGPR(
251 "fast", "fast register allocator", createFastSGPRRegisterAllocator);
252
253
254static VGPRRegisterRegAlloc basicRegAllocVGPR(
255 "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
256static VGPRRegisterRegAlloc greedyRegAllocVGPR(
257 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
258
259static VGPRRegisterRegAlloc fastRegAllocVGPR(
260 "fast", "fast register allocator", createFastVGPRRegisterAllocator);
261static WWMRegisterRegAlloc basicRegAllocWWMReg("basic",
262 "basic register allocator",
263 createBasicWWMRegisterAllocator);
264static WWMRegisterRegAlloc
265 greedyRegAllocWWMReg("greedy", "greedy register allocator",
266 createGreedyWWMRegisterAllocator);
267static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator",
268 createFastWWMRegisterAllocator);
269
271 return Phase == ThinOrFullLTOPhase::FullLTOPreLink ||
272 Phase == ThinOrFullLTOPhase::ThinLTOPreLink;
273}
274} // anonymous namespace
275
276static cl::opt<bool>
278 cl::desc("Run early if-conversion"),
279 cl::init(false));
280
281static cl::opt<bool>
282OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
283 cl::desc("Run pre-RA exec mask optimizations"),
284 cl::init(true));
285
286static cl::opt<bool>
287 LowerCtorDtor("amdgpu-lower-global-ctor-dtor",
288 cl::desc("Lower GPU ctor / dtors to globals on the device."),
289 cl::init(true), cl::Hidden);
290
291// Option to disable vectorizer for tests.
293 "amdgpu-load-store-vectorizer",
294 cl::desc("Enable load store vectorizer"),
295 cl::init(true),
296 cl::Hidden);
297
298// Option to control global loads scalarization
300 "amdgpu-scalarize-global-loads",
301 cl::desc("Enable global load scalarization"),
302 cl::init(true),
303 cl::Hidden);
304
305// Option to run internalize pass.
307 "amdgpu-internalize-symbols",
308 cl::desc("Enable elimination of non-kernel functions and unused globals"),
309 cl::init(false),
310 cl::Hidden);
311
312// Option to inline all early.
314 "amdgpu-early-inline-all",
315 cl::desc("Inline all functions early"),
316 cl::init(false),
317 cl::Hidden);
318
320 "amdgpu-enable-remove-incompatible-functions", cl::Hidden,
321 cl::desc("Enable removal of functions when they"
322 "use features not supported by the target GPU"),
323 cl::init(true));
324
326 "amdgpu-sdwa-peephole",
327 cl::desc("Enable SDWA peepholer"),
328 cl::init(true));
329
331 "amdgpu-dpp-combine",
332 cl::desc("Enable DPP combiner"),
333 cl::init(true));
334
335// Enable address space based alias analysis
337 cl::desc("Enable AMDGPU Alias Analysis"),
338 cl::init(true));
339
340// Enable lib calls simplifications
342 "amdgpu-simplify-libcall",
343 cl::desc("Enable amdgpu library simplifications"),
344 cl::init(true),
345 cl::Hidden);
346
348 "amdgpu-ir-lower-kernel-arguments",
349 cl::desc("Lower kernel argument loads in IR pass"),
350 cl::init(true),
351 cl::Hidden);
352
354 "amdgpu-reassign-regs",
355 cl::desc("Enable register reassign optimizations on gfx10+"),
356 cl::init(true),
357 cl::Hidden);
358
360 "amdgpu-opt-vgpr-liverange",
361 cl::desc("Enable VGPR liverange optimizations for if-else structure"),
362 cl::init(true), cl::Hidden);
363
365 "amdgpu-atomic-optimizer-strategy",
366 cl::desc("Select DPP or Iterative strategy for scan"),
367 cl::init(ScanOptions::Iterative),
369 clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"),
370 clEnumValN(ScanOptions::Iterative, "Iterative",
371 "Use Iterative approach for scan"),
372 clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")));
373
374// Enable Mode register optimization
376 "amdgpu-mode-register",
377 cl::desc("Enable mode register pass"),
378 cl::init(true),
379 cl::Hidden);
380
381// Enable GFX11+ s_delay_alu insertion
382static cl::opt<bool>
383 EnableInsertDelayAlu("amdgpu-enable-delay-alu",
384 cl::desc("Enable s_delay_alu insertion"),
385 cl::init(true), cl::Hidden);
386
387// Enable GFX11+ VOPD
388static cl::opt<bool>
389 EnableVOPD("amdgpu-enable-vopd",
390 cl::desc("Enable VOPD, dual issue of VALU in wave32"),
391 cl::init(true), cl::Hidden);
392
393// Option is used in lit tests to prevent deadcoding of patterns inspected.
394static cl::opt<bool>
395EnableDCEInRA("amdgpu-dce-in-ra",
396 cl::init(true), cl::Hidden,
397 cl::desc("Enable machine DCE inside regalloc"));
398
399static cl::opt<bool> EnableSetWavePriority("amdgpu-set-wave-priority",
400 cl::desc("Adjust wave priority"),
401 cl::init(false), cl::Hidden);
402
404 "amdgpu-scalar-ir-passes",
405 cl::desc("Enable scalar IR passes"),
406 cl::init(true),
407 cl::Hidden);
408
409static cl::opt<bool>
410 EnableSwLowerLDS("amdgpu-enable-sw-lower-lds",
411 cl::desc("Enable lowering of lds to global memory pass "
412 "and asan instrument resulting IR."),
413 cl::init(true), cl::Hidden);
414
416 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
418 cl::Hidden);
419
421 "amdgpu-enable-pre-ra-optimizations",
422 cl::desc("Enable Pre-RA optimizations pass"), cl::init(true),
423 cl::Hidden);
424
426 "amdgpu-enable-promote-kernel-arguments",
427 cl::desc("Enable promotion of flat kernel pointer arguments to global"),
428 cl::Hidden, cl::init(true));
429
431 "amdgpu-enable-image-intrinsic-optimizer",
432 cl::desc("Enable image intrinsic optimizer pass"), cl::init(true),
433 cl::Hidden);
434
435static cl::opt<bool>
436 EnableLoopPrefetch("amdgpu-loop-prefetch",
437 cl::desc("Enable loop data prefetch on AMDGPU"),
438 cl::Hidden, cl::init(false));
439
441 AMDGPUSchedStrategy("amdgpu-sched-strategy",
442 cl::desc("Select custom AMDGPU scheduling strategy."),
443 cl::Hidden, cl::init(""));
444
446 "amdgpu-enable-rewrite-partial-reg-uses",
447 cl::desc("Enable rewrite partial reg uses pass"), cl::init(true),
448 cl::Hidden);
449
451 "amdgpu-enable-hipstdpar",
452 cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false),
453 cl::Hidden);
454
455static cl::opt<bool>
456 EnableAMDGPUAttributor("amdgpu-attributor-enable",
457 cl::desc("Enable AMDGPUAttributorPass"),
458 cl::init(true), cl::Hidden);
459
461 "new-reg-bank-select",
462 cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of "
463 "regbankselect"),
464 cl::init(false), cl::Hidden);
465
467 "amdgpu-link-time-closed-world",
468 cl::desc("Whether has closed-world assumption at link time"),
469 cl::init(false), cl::Hidden);
470
472 // Register the target
475
554}
555
556static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
557 return std::make_unique<AMDGPUTargetObjectFile>();
558}
559
561 return new SIScheduleDAGMI(C);
562}
563
564static ScheduleDAGInstrs *
566 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
567 ScheduleDAGMILive *DAG =
568 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
569 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
570 if (ST.shouldClusterStores())
571 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
572 DAG->addMutation(createIGroupLPDAGMutation(AMDGPU::SchedulingPhase::Initial));
573 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
574 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
575 return DAG;
576}
577
578static ScheduleDAGInstrs *
580 ScheduleDAGMILive *DAG =
581 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C));
582 DAG->addMutation(createIGroupLPDAGMutation(AMDGPU::SchedulingPhase::Initial));
583 return DAG;
584}
585
586static ScheduleDAGInstrs *
588 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
590 C, std::make_unique<GCNMaxMemoryClauseSchedStrategy>(C));
591 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
592 if (ST.shouldClusterStores())
593 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
594 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
595 return DAG;
596}
597
598static ScheduleDAGInstrs *
600 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
601 auto *DAG = new GCNIterativeScheduler(
603 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
604 if (ST.shouldClusterStores())
605 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
606 return DAG;
607}
608
610 return new GCNIterativeScheduler(C,
612}
613
614static ScheduleDAGInstrs *
616 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
618 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
619 if (ST.shouldClusterStores())
620 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
621 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
622 return DAG;
623}
624
626SISchedRegistry("si", "Run SI's custom scheduler",
628
631 "Run GCN scheduler to maximize occupancy",
633
635 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp",
637
639 "gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause",
641
643 "gcn-iterative-max-occupancy-experimental",
644 "Run GCN scheduler to maximize occupancy (experimental)",
646
648 "gcn-iterative-minreg",
649 "Run GCN iterative scheduler for minimal register usage (experimental)",
651
653 "gcn-iterative-ilp",
654 "Run GCN iterative scheduler for ILP scheduling (experimental)",
656
658 if (TT.getArch() == Triple::r600) {
659 // 32-bit pointers.
660 return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
661 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
662 }
663
664 // 32-bit private, local, and region pointers. 64-bit global, constant and
665 // flat. 160-bit non-integral fat buffer pointers that include a 128-bit
666 // buffer descriptor and a 32-bit offset, which are indexed by 32-bit values
667 // (address space 7), and 128-bit non-integral buffer resourcees (address
668 // space 8) which cannot be non-trivilally accessed by LLVM memory operations
669 // like getelementptr.
670 return "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
671 "-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-"
672 "v32:32-v48:64-v96:"
673 "128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-"
674 "G1-ni:7:8:9";
675}
676
679 if (!GPU.empty())
680 return GPU;
681
682 // Need to default to a target with flat support for HSA.
683 if (TT.getArch() == Triple::amdgcn)
684 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
685
686 return "r600";
687}
688
689static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
690 // The AMDGPU toolchain only supports generating shared objects, so we
691 // must always use PIC.
692 return Reloc::PIC_;
693}
694
696 StringRef CPU, StringRef FS,
697 const TargetOptions &Options,
698 std::optional<Reloc::Model> RM,
699 std::optional<CodeModel::Model> CM,
700 CodeGenOptLevel OptLevel)
702 T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU), FS, Options,
704 getEffectiveCodeModel(CM, CodeModel::Small), OptLevel),
705 TLOF(createTLOF(getTargetTriple())) {
706 initAsmInfo();
707 if (TT.getArch() == Triple::amdgcn) {
708 if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize64"))
710 else if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize32"))
712 }
713}
714
717
719
721 Attribute GPUAttr = F.getFnAttribute("target-cpu");
722 return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU();
723}
724
726 Attribute FSAttr = F.getFnAttribute("target-features");
727
728 return FSAttr.isValid() ? FSAttr.getValueAsString()
730}
731
732/// Predicate for Internalize pass.
733static bool mustPreserveGV(const GlobalValue &GV) {
734 if (const Function *F = dyn_cast<Function>(&GV))
735 return F->isDeclaration() || F->getName().starts_with("__asan_") ||
736 F->getName().starts_with("__sanitizer_") ||
737 AMDGPU::isEntryFunctionCC(F->getCallingConv());
738
740 return !GV.use_empty();
741}
742
745}
746
749 if (Params.empty())
751 Params.consume_front("strategy=");
752 auto Result = StringSwitch<std::optional<ScanOptions>>(Params)
753 .Case("dpp", ScanOptions::DPP)
754 .Cases("iterative", "", ScanOptions::Iterative)
755 .Case("none", ScanOptions::None)
756 .Default(std::nullopt);
757 if (Result)
758 return *Result;
759 return make_error<StringError>("invalid parameter", inconvertibleErrorCode());
760}
761
765 while (!Params.empty()) {
766 StringRef ParamName;
767 std::tie(ParamName, Params) = Params.split(';');
768 if (ParamName == "closed-world") {
769 Result.IsClosedWorld = true;
770 } else {
771 return make_error<StringError>(
772 formatv("invalid AMDGPUAttributor pass parameter '{0}' ", ParamName)
773 .str(),
775 }
776 }
777 return Result;
778}
779
781
782#define GET_PASS_REGISTRY "AMDGPUPassRegistry.def"
784
786 [](ModulePassManager &PM, OptimizationLevel Level) {
787 if (EnableHipStdPar)
789 });
790
795
796 if (Level == OptimizationLevel::O0)
797 return;
798
800
801 // We don't want to run internalization at per-module stage.
805 }
806
809 });
810
812 [](FunctionPassManager &FPM, OptimizationLevel Level) {
813 if (Level == OptimizationLevel::O0)
814 return;
815
819 });
820
822 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
823 if (Level == OptimizationLevel::O0)
824 return;
825
827
828 // Add promote kernel arguments pass to the opt pipeline right before
829 // infer address spaces which is needed to do actual address space
830 // rewriting.
831 if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
834
835 // Add infer address spaces pass to the opt pipeline after inlining
836 // but before SROA to increase SROA opportunities.
838
839 // This should run after inlining to have any chance of doing
840 // anything, and before other cleanup optimizations.
842
843 if (Level != OptimizationLevel::O0) {
844 // Promote alloca to vector before SROA and loop unroll. If we
845 // manage to eliminate allocas before unroll we may choose to unroll
846 // less.
848 }
849
850 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
851 });
852
853 // FIXME: Why is AMDGPUAttributor not in CGSCC?
855 OptimizationLevel Level,
857 if (Level != OptimizationLevel::O0) {
858 if (!isLTOPreLink(Phase))
859 MPM.addPass(AMDGPUAttributorPass(*this));
860 }
861 });
862
864 [this](ModulePassManager &PM, OptimizationLevel Level) {
865 // We want to support the -lto-partitions=N option as "best effort".
866 // For that, we need to lower LDS earlier in the pipeline before the
867 // module is partitioned for codegen.
869 PM.addPass(AMDGPUSwLowerLDSPass(*this));
872 if (Level != OptimizationLevel::O0) {
873 // Do we really need internalization in LTO?
874 if (InternalizeSymbols) {
877 }
881 Opt.IsClosedWorld = true;
882 PM.addPass(AMDGPUAttributorPass(*this, Opt));
883 }
884 }
885 if (!NoKernelInfoEndLTO) {
887 FPM.addPass(KernelInfoPrinter(this));
888 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
889 }
890 });
891
893 [](StringRef FilterName) -> RegAllocFilterFunc {
894 if (FilterName == "sgpr")
895 return onlyAllocateSGPRs;
896 if (FilterName == "vgpr")
897 return onlyAllocateVGPRs;
898 if (FilterName == "wwm")
899 return onlyAllocateWWMRegs;
900 return nullptr;
901 });
902}
903
904int64_t AMDGPUTargetMachine::getNullPointerValue(unsigned AddrSpace) {
905 return (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
906 AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
907 AddrSpace == AMDGPUAS::REGION_ADDRESS)
908 ? -1
909 : 0;
910}
911
913 unsigned DestAS) const {
914 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
916}
917
919 const auto *LD = dyn_cast<LoadInst>(V);
920 if (!LD) // TODO: Handle invariant load like constant.
922
923 // It must be a generic pointer loaded.
924 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
925
926 const auto *Ptr = LD->getPointerOperand();
927 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
929 // For a generic pointer loaded from the constant memory, it could be assumed
930 // as a global pointer since the constant memory is only populated on the
931 // host side. As implied by the offload programming model, only global
932 // pointers could be referenced on the host side.
934}
935
936std::pair<const Value *, unsigned>
938 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
939 switch (II->getIntrinsicID()) {
940 case Intrinsic::amdgcn_is_shared:
941 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
942 case Intrinsic::amdgcn_is_private:
943 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
944 default:
945 break;
946 }
947 return std::pair(nullptr, -1);
948 }
949 // Check the global pointer predication based on
950 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
951 // the order of 'is_shared' and 'is_private' is not significant.
952 Value *Ptr;
953 if (match(
954 const_cast<Value *>(V),
955 m_c_And(m_Not(m_Intrinsic<Intrinsic::amdgcn_is_shared>(m_Value(Ptr))),
956 m_Not(m_Intrinsic<Intrinsic::amdgcn_is_private>(
957 m_Deferred(Ptr))))))
958 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
959
960 return std::pair(nullptr, -1);
961}
962
963unsigned
965 switch (Kind) {
975 }
977}
978
980 Module &M, unsigned NumParts,
981 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
982 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
983 // but all current users of this API don't have one ready and would need to
984 // create one anyway. Let's hide the boilerplate for now to keep it simple.
985
990
991 PassBuilder PB(this);
995
997 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
998 MPM.run(M, MAM);
999 return true;
1000}
1001
1002//===----------------------------------------------------------------------===//
1003// GCN Target Machine (SI+)
1004//===----------------------------------------------------------------------===//
1005
1007 StringRef CPU, StringRef FS,
1008 const TargetOptions &Options,
1009 std::optional<Reloc::Model> RM,
1010 std::optional<CodeModel::Model> CM,
1011 CodeGenOptLevel OL, bool JIT)
1012 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
1013
1014const TargetSubtargetInfo *
1016 StringRef GPU = getGPUName(F);
1018
1019 SmallString<128> SubtargetKey(GPU);
1020 SubtargetKey.append(FS);
1021
1022 auto &I = SubtargetMap[SubtargetKey];
1023 if (!I) {
1024 // This needs to be done before we create a new subtarget since any
1025 // creation will depend on the TM and the code generation flags on the
1026 // function that reside in TargetOptions.
1028 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
1029 }
1030
1031 I->setScalarizeGlobalBehavior(ScalarizeGlobal);
1032
1033 return I.get();
1034}
1035
1038 return TargetTransformInfo(GCNTTIImpl(this, F));
1039}
1040
1043 CodeGenFileType FileType, const CGPassBuilderOption &Opts,
1045 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1046 return CGPB.buildPipeline(MPM, Out, DwoOut, FileType);
1047}
1048
1049//===----------------------------------------------------------------------===//
1050// AMDGPU Legacy Pass Setup
1051//===----------------------------------------------------------------------===//
1052
1053std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1055}
1056
1057namespace {
1058
1059class GCNPassConfig final : public AMDGPUPassConfig {
1060public:
1061 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1062 : AMDGPUPassConfig(TM, PM) {
1063 // It is necessary to know the register usage of the entire call graph. We
1064 // allow calls without EnableAMDGPUFunctionCalls if they are marked
1065 // noinline, so this is always required.
1066 setRequiresCodeGenSCCOrder(true);
1067 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1068 }
1069
1070 GCNTargetMachine &getGCNTargetMachine() const {
1071 return getTM<GCNTargetMachine>();
1072 }
1073
1075 createMachineScheduler(MachineSchedContext *C) const override;
1076
1078 createPostMachineScheduler(MachineSchedContext *C) const override {
1080 C, std::make_unique<PostGenericScheduler>(C),
1081 /*RemoveKillFlags=*/true);
1082 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1084 if (ST.shouldClusterStores())
1086 DAG->addMutation(
1087 createIGroupLPDAGMutation(AMDGPU::SchedulingPhase::PostRA));
1088 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1090 return DAG;
1091 }
1092
1093 bool addPreISel() override;
1094 void addMachineSSAOptimization() override;
1095 bool addILPOpts() override;
1096 bool addInstSelector() override;
1097 bool addIRTranslator() override;
1098 void addPreLegalizeMachineIR() override;
1099 bool addLegalizeMachineIR() override;
1100 void addPreRegBankSelect() override;
1101 bool addRegBankSelect() override;
1102 void addPreGlobalInstructionSelect() override;
1103 bool addGlobalInstructionSelect() override;
1104 void addFastRegAlloc() override;
1105 void addOptimizedRegAlloc() override;
1106
1107 FunctionPass *createSGPRAllocPass(bool Optimized);
1108 FunctionPass *createVGPRAllocPass(bool Optimized);
1109 FunctionPass *createWWMRegAllocPass(bool Optimized);
1110 FunctionPass *createRegAllocPass(bool Optimized) override;
1111
1112 bool addRegAssignAndRewriteFast() override;
1113 bool addRegAssignAndRewriteOptimized() override;
1114
1115 bool addPreRewrite() override;
1116 void addPostRegAlloc() override;
1117 void addPreSched2() override;
1118 void addPreEmitPass() override;
1119};
1120
1121} // end anonymous namespace
1122
1124 : TargetPassConfig(TM, PM) {
1125 // Exceptions and StackMaps are not supported, so these passes will never do
1126 // anything.
1129 // Garbage collection is not supported.
1132}
1133
1137 else
1139}
1140
1145 // ReassociateGEPs exposes more opportunities for SLSR. See
1146 // the example in reassociate-geps-and-slsr.ll.
1148 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1149 // EarlyCSE can reuse.
1151 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1153 // NaryReassociate on GEPs creates redundant common expressions, so run
1154 // EarlyCSE after it.
1156}
1157
1160
1164
1165 // There is no reason to run these.
1169
1171 if (LowerCtorDtor)
1173
1176
1177 // This can be disabled by passing ::Disable here or on the command line
1178 // with --expand-variadics-override=disable.
1180
1181 // Function calls are not supported, so make sure we inline everything.
1184
1185 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1186 if (Arch == Triple::r600)
1188
1189 // Replace OpenCL enqueued block function pointers with global variables.
1191
1192 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1193 if (EnableSwLowerLDS)
1195
1196 // Runs before PromoteAlloca so the latter can account for function uses
1199 }
1200
1203
1204 // Run atomic optimizer before Atomic Expand
1209 }
1210
1212
1215
1218
1222 AAResults &AAR) {
1223 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1224 AAR.addAAResult(WrapperPass->getResult());
1225 }));
1226 }
1227
1229 // TODO: May want to move later or split into an early and late one.
1231 }
1232
1233 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1234 // have expanded.
1237 }
1238
1240
1241 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1242 // example, GVN can combine
1243 //
1244 // %0 = add %a, %b
1245 // %1 = add %b, %a
1246 //
1247 // and
1248 //
1249 // %0 = shl nsw %a, 2
1250 // %1 = shl %a, 2
1251 //
1252 // but EarlyCSE can do neither of them.
1255}
1256
1259 // FIXME: This pass adds 2 hacky attributes that can be replaced with an
1260 // analysis, and should be removed.
1262 }
1263
1267
1269 // This lowering has been placed after codegenprepare to take advantage of
1270 // address mode matching (which is why it isn't put with the LDS lowerings).
1271 // It could be placed anywhere before uniformity annotations (an analysis
1272 // that it changes by splitting up fat pointers into their components)
1273 // but has been put before switch lowering and CFG flattening so that those
1274 // passes can run on the more optimized control flow this pass creates in
1275 // many cases.
1276 //
1277 // FIXME: This should ideally be put after the LoadStoreVectorizer.
1278 // However, due to some annoying facts about ResourceUsageAnalysis,
1279 // (especially as exercised in the resource-usage-dead-function test),
1280 // we need all the function passes codegenprepare all the way through
1281 // said resource usage analysis to run on the call graph produced
1282 // before codegenprepare runs (because codegenprepare will knock some
1283 // nodes out of the graph, which leads to function-level passes not
1284 // being run on them, which causes crashes in the resource usage analysis).
1286 // In accordance with the above FIXME, manually force all the
1287 // function-level passes into a CGSCCPassManager.
1288 addPass(new DummyCGSCCPass());
1289 }
1290
1292
1295
1296 // LowerSwitch pass may introduce unreachable blocks that can
1297 // cause unexpected behavior for subsequent passes. Placing it
1298 // here seems better that these blocks would get cleaned up by
1299 // UnreachableBlockElim inserted next in the pass flow.
1301}
1302
1306 return false;
1307}
1308
1311 return false;
1312}
1313
1315 // Do nothing. GC is not supported.
1316 return false;
1317}
1318
1321 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1323 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1324 if (ST.shouldClusterStores())
1325 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
1326 return DAG;
1327}
1328
1329//===----------------------------------------------------------------------===//
1330// GCN Legacy Pass Setup
1331//===----------------------------------------------------------------------===//
1332
1333ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler(
1334 MachineSchedContext *C) const {
1335 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1336 if (ST.enableSIScheduler())
1338
1339 Attribute SchedStrategyAttr =
1340 C->MF->getFunction().getFnAttribute("amdgpu-sched-strategy");
1341 StringRef SchedStrategy = SchedStrategyAttr.isValid()
1342 ? SchedStrategyAttr.getValueAsString()
1344
1345 if (SchedStrategy == "max-ilp")
1347
1348 if (SchedStrategy == "max-memory-clause")
1350
1352}
1353
1354bool GCNPassConfig::addPreISel() {
1356
1357 if (TM->getOptLevel() > CodeGenOptLevel::None)
1358 addPass(createSinkingPass());
1359
1360 if (TM->getOptLevel() > CodeGenOptLevel::None)
1362
1363 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1364 // regions formed by them.
1366 addPass(createFixIrreduciblePass());
1367 addPass(createUnifyLoopExitsPass());
1368 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1369
1372 // TODO: Move this right after structurizeCFG to avoid extra divergence
1373 // analysis. This depends on stopping SIAnnotateControlFlow from making
1374 // control flow modifications.
1376
1377 addPass(createLCSSAPass());
1378
1379 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1381
1382 return false;
1383}
1384
1385void GCNPassConfig::addMachineSSAOptimization() {
1387
1388 // We want to fold operands after PeepholeOptimizer has run (or as part of
1389 // it), because it will eliminate extra copies making it easier to fold the
1390 // real source operand. We want to eliminate dead instructions after, so that
1391 // we see fewer uses of the copies. We then need to clean up the dead
1392 // instructions leftover after the operands are folded as well.
1393 //
1394 // XXX - Can we get away without running DeadMachineInstructionElim again?
1395 addPass(&SIFoldOperandsLegacyID);
1396 if (EnableDPPCombine)
1397 addPass(&GCNDPPCombineLegacyID);
1399 if (isPassEnabled(EnableSDWAPeephole)) {
1400 addPass(&SIPeepholeSDWALegacyID);
1401 addPass(&EarlyMachineLICMID);
1402 addPass(&MachineCSELegacyID);
1403 addPass(&SIFoldOperandsLegacyID);
1404 }
1407}
1408
1409bool GCNPassConfig::addILPOpts() {
1411 addPass(&EarlyIfConverterLegacyID);
1412
1414 return false;
1415}
1416
1417bool GCNPassConfig::addInstSelector() {
1419 addPass(&SIFixSGPRCopiesLegacyID);
1421 return false;
1422}
1423
1424bool GCNPassConfig::addIRTranslator() {
1425 addPass(new IRTranslator(getOptLevel()));
1426 return false;
1427}
1428
1429void GCNPassConfig::addPreLegalizeMachineIR() {
1430 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1431 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1432 addPass(new Localizer());
1433}
1434
1435bool GCNPassConfig::addLegalizeMachineIR() {
1436 addPass(new Legalizer());
1437 return false;
1438}
1439
1440void GCNPassConfig::addPreRegBankSelect() {
1441 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1442 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1444}
1445
1446bool GCNPassConfig::addRegBankSelect() {
1447 if (NewRegBankSelect) {
1450 } else {
1451 addPass(new RegBankSelect());
1452 }
1453 return false;
1454}
1455
1456void GCNPassConfig::addPreGlobalInstructionSelect() {
1457 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1458 addPass(createAMDGPURegBankCombiner(IsOptNone));
1459}
1460
1461bool GCNPassConfig::addGlobalInstructionSelect() {
1462 addPass(new InstructionSelect(getOptLevel()));
1463 return false;
1464}
1465
1466void GCNPassConfig::addFastRegAlloc() {
1467 // FIXME: We have to disable the verifier here because of PHIElimination +
1468 // TwoAddressInstructions disabling it.
1469
1470 // This must be run immediately after phi elimination and before
1471 // TwoAddressInstructions, otherwise the processing of the tied operand of
1472 // SI_ELSE will introduce a copy of the tied operand source after the else.
1474
1476
1478}
1479
1480void GCNPassConfig::addOptimizedRegAlloc() {
1481 if (EnableDCEInRA)
1483
1484 // FIXME: when an instruction has a Killed operand, and the instruction is
1485 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1486 // the register in LiveVariables, this would trigger a failure in verifier,
1487 // we should fix it and enable the verifier.
1488 if (OptVGPRLiveRange)
1490
1491 // This must be run immediately after phi elimination and before
1492 // TwoAddressInstructions, otherwise the processing of the tied operand of
1493 // SI_ELSE will introduce a copy of the tied operand source after the else.
1495
1498
1499 if (isPassEnabled(EnablePreRAOptimizations))
1501
1502 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1503 // instructions that cause scheduling barriers.
1505
1506 if (OptExecMaskPreRA)
1508
1509 // This is not an essential optimization and it has a noticeable impact on
1510 // compilation time, so we only enable it from O2.
1511 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1513
1515}
1516
1517bool GCNPassConfig::addPreRewrite() {
1519 addPass(&GCNNSAReassignID);
1520 return true;
1521}
1522
1523FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1524 // Initialize the global default.
1525 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1526 initializeDefaultSGPRRegisterAllocatorOnce);
1527
1528 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1529 if (Ctor != useDefaultRegisterAllocator)
1530 return Ctor();
1531
1532 if (Optimized)
1533 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1534
1535 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1536}
1537
1538FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1539 // Initialize the global default.
1540 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1541 initializeDefaultVGPRRegisterAllocatorOnce);
1542
1543 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1544 if (Ctor != useDefaultRegisterAllocator)
1545 return Ctor();
1546
1547 if (Optimized)
1548 return createGreedyVGPRRegisterAllocator();
1549
1550 return createFastVGPRRegisterAllocator();
1551}
1552
1553FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1554 // Initialize the global default.
1555 llvm::call_once(InitializeDefaultWWMRegisterAllocatorFlag,
1556 initializeDefaultWWMRegisterAllocatorOnce);
1557
1558 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1559 if (Ctor != useDefaultRegisterAllocator)
1560 return Ctor();
1561
1562 if (Optimized)
1563 return createGreedyWWMRegisterAllocator();
1564
1565 return createFastWWMRegisterAllocator();
1566}
1567
1568FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1569 llvm_unreachable("should not be used");
1570}
1571
1573 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1574 "and -vgpr-regalloc";
1575
1576bool GCNPassConfig::addRegAssignAndRewriteFast() {
1577 if (!usingDefaultRegAlloc())
1579
1580 addPass(&GCNPreRALongBranchRegID);
1581
1582 addPass(createSGPRAllocPass(false));
1583
1584 // Equivalent of PEI for SGPRs.
1585 addPass(&SILowerSGPRSpillsLegacyID);
1586
1587 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1589
1590 // For allocating other wwm register operands.
1591 addPass(createWWMRegAllocPass(false));
1592
1593 addPass(&SILowerWWMCopiesLegacyID);
1594 addPass(&AMDGPUReserveWWMRegsID);
1595
1596 // For allocating per-thread VGPRs.
1597 addPass(createVGPRAllocPass(false));
1598
1599 return true;
1600}
1601
1602bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1603 if (!usingDefaultRegAlloc())
1605
1606 addPass(&GCNPreRALongBranchRegID);
1607
1608 addPass(createSGPRAllocPass(true));
1609
1610 // Commit allocated register changes. This is mostly necessary because too
1611 // many things rely on the use lists of the physical registers, such as the
1612 // verifier. This is only necessary with allocators which use LiveIntervals,
1613 // since FastRegAlloc does the replacements itself.
1614 addPass(createVirtRegRewriter(false));
1615
1616 // At this point, the sgpr-regalloc has been done and it is good to have the
1617 // stack slot coloring to try to optimize the SGPR spill stack indices before
1618 // attempting the custom SGPR spill lowering.
1619 addPass(&StackSlotColoringID);
1620
1621 // Equivalent of PEI for SGPRs.
1622 addPass(&SILowerSGPRSpillsLegacyID);
1623
1624 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1626
1627 // For allocating other whole wave mode registers.
1628 addPass(createWWMRegAllocPass(true));
1629 addPass(&SILowerWWMCopiesLegacyID);
1630 addPass(createVirtRegRewriter(false));
1631 addPass(&AMDGPUReserveWWMRegsID);
1632
1633 // For allocating per-thread VGPRs.
1634 addPass(createVGPRAllocPass(true));
1635
1636 addPreRewrite();
1637 addPass(&VirtRegRewriterID);
1638
1640
1641 return true;
1642}
1643
1644void GCNPassConfig::addPostRegAlloc() {
1645 addPass(&SIFixVGPRCopiesID);
1646 if (getOptLevel() > CodeGenOptLevel::None)
1649}
1650
1651void GCNPassConfig::addPreSched2() {
1652 if (TM->getOptLevel() > CodeGenOptLevel::None)
1654 addPass(&SIPostRABundlerID);
1655}
1656
1657void GCNPassConfig::addPreEmitPass() {
1658 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1659 addPass(&GCNCreateVOPDID);
1660 addPass(createSIMemoryLegalizerPass());
1661 addPass(createSIInsertWaitcntsPass());
1662
1663 addPass(createSIModeRegisterPass());
1664
1665 if (getOptLevel() > CodeGenOptLevel::None)
1666 addPass(&SIInsertHardClausesID);
1667
1669 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
1671 if (getOptLevel() > CodeGenOptLevel::None)
1672 addPass(&SIPreEmitPeepholeID);
1673 // The hazard recognizer that runs as part of the post-ra scheduler does not
1674 // guarantee to be able handle all hazards correctly. This is because if there
1675 // are multiple scheduling regions in a basic block, the regions are scheduled
1676 // bottom up, so when we begin to schedule a region we don't know what
1677 // instructions were emitted directly before it.
1678 //
1679 // Here we add a stand-alone hazard recognizer pass which can handle all
1680 // cases.
1681 addPass(&PostRAHazardRecognizerID);
1682
1684
1685 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less))
1686 addPass(&AMDGPUInsertDelayAluID);
1687
1688 addPass(&BranchRelaxationPassID);
1690}
1691
1693 return new GCNPassConfig(*this, PM);
1694}
1695
1697 MachineFunction &MF) const {
1699 MF.getRegInfo().addDelegate(MFI);
1700}
1701
1703 BumpPtrAllocator &Allocator, const Function &F,
1704 const TargetSubtargetInfo *STI) const {
1705 return SIMachineFunctionInfo::create<SIMachineFunctionInfo>(
1706 Allocator, F, static_cast<const GCNSubtarget *>(STI));
1707}
1708
1710 return new yaml::SIMachineFunctionInfo();
1711}
1712
1716 return new yaml::SIMachineFunctionInfo(
1717 *MFI, *MF.getSubtarget<GCNSubtarget>().getRegisterInfo(), MF);
1718}
1719
1722 SMDiagnostic &Error, SMRange &SourceRange) const {
1723 const yaml::SIMachineFunctionInfo &YamlMFI =
1724 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1725 MachineFunction &MF = PFS.MF;
1727 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1728
1729 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1730 return true;
1731
1732 if (MFI->Occupancy == 0) {
1733 // Fixup the subtarget dependent default value.
1734 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1735 }
1736
1737 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1738 Register TempReg;
1739 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1740 SourceRange = RegName.SourceRange;
1741 return true;
1742 }
1743 RegVal = TempReg;
1744
1745 return false;
1746 };
1747
1748 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1749 Register &RegVal) {
1750 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1751 };
1752
1753 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
1754 return true;
1755
1756 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
1757 return true;
1758
1759 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
1760 MFI->LongBranchReservedReg))
1761 return true;
1762
1763 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1764 // Create a diagnostic for a the register string literal.
1765 const MemoryBuffer &Buffer =
1766 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1767 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1768 RegName.Value.size(), SourceMgr::DK_Error,
1769 "incorrect register class for field", RegName.Value,
1770 {}, {});
1771 SourceRange = RegName.SourceRange;
1772 return true;
1773 };
1774
1775 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1776 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1777 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1778 return true;
1779
1780 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1781 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1782 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1783 }
1784
1785 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1786 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1787 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1788 }
1789
1790 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1791 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1792 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1793 }
1794
1795 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
1796 Register ParsedReg;
1797 if (parseRegister(YamlReg, ParsedReg))
1798 return true;
1799
1800 MFI->reserveWWMRegister(ParsedReg);
1801 }
1802
1803 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
1804 MFI->setFlag(Info->VReg, Info->Flags);
1805 }
1806 for (const auto &[_, Info] : PFS.VRegInfos) {
1807 MFI->setFlag(Info->VReg, Info->Flags);
1808 }
1809
1810 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
1811 Register ParsedReg;
1812 if (parseRegister(YamlRegStr, ParsedReg))
1813 return true;
1814 MFI->SpillPhysVGPRs.push_back(ParsedReg);
1815 }
1816
1817 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
1818 const TargetRegisterClass &RC,
1819 ArgDescriptor &Arg, unsigned UserSGPRs,
1820 unsigned SystemSGPRs) {
1821 // Skip parsing if it's not present.
1822 if (!A)
1823 return false;
1824
1825 if (A->IsRegister) {
1826 Register Reg;
1827 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
1828 SourceRange = A->RegisterName.SourceRange;
1829 return true;
1830 }
1831 if (!RC.contains(Reg))
1832 return diagnoseRegisterClass(A->RegisterName);
1834 } else
1835 Arg = ArgDescriptor::createStack(A->StackOffset);
1836 // Check and apply the optional mask.
1837 if (A->Mask)
1838 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
1839
1840 MFI->NumUserSGPRs += UserSGPRs;
1841 MFI->NumSystemSGPRs += SystemSGPRs;
1842 return false;
1843 };
1844
1845 if (YamlMFI.ArgInfo &&
1846 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
1847 AMDGPU::SGPR_128RegClass,
1848 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
1849 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
1850 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
1851 2, 0) ||
1852 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
1853 MFI->ArgInfo.QueuePtr, 2, 0) ||
1854 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
1855 AMDGPU::SReg_64RegClass,
1856 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
1857 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
1858 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
1859 2, 0) ||
1860 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
1861 AMDGPU::SReg_64RegClass,
1862 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
1863 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
1864 AMDGPU::SGPR_32RegClass,
1865 MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
1866 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
1867 AMDGPU::SGPR_32RegClass,
1868 MFI->ArgInfo.LDSKernelId, 0, 1) ||
1869 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
1870 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
1871 0, 1) ||
1872 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
1873 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
1874 0, 1) ||
1875 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
1876 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
1877 0, 1) ||
1878 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
1879 AMDGPU::SGPR_32RegClass,
1880 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
1881 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
1882 AMDGPU::SGPR_32RegClass,
1883 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
1884 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
1885 AMDGPU::SReg_64RegClass,
1886 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
1887 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
1888 AMDGPU::SReg_64RegClass,
1889 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
1890 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
1891 AMDGPU::VGPR_32RegClass,
1892 MFI->ArgInfo.WorkItemIDX, 0, 0) ||
1893 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
1894 AMDGPU::VGPR_32RegClass,
1895 MFI->ArgInfo.WorkItemIDY, 0, 0) ||
1896 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
1897 AMDGPU::VGPR_32RegClass,
1898 MFI->ArgInfo.WorkItemIDZ, 0, 0)))
1899 return true;
1900
1901 if (ST.hasIEEEMode())
1902 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
1903 if (ST.hasDX10ClampMode())
1904 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
1905
1906 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
1907 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
1910 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
1913
1920
1921 if (YamlMFI.HasInitWholeWave)
1922 MFI->setInitWholeWave();
1923
1924 return false;
1925}
1926
1927//===----------------------------------------------------------------------===//
1928// AMDGPU CodeGen Pass Builder interface.
1929//===----------------------------------------------------------------------===//
1930
1932 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
1934 : CodeGenPassBuilder(TM, Opts, PIC) {
1936 // Exceptions and StackMaps are not supported, so these passes will never do
1937 // anything.
1938 // Garbage collection is not supported.
1939 disablePass<StackMapLivenessPass, FuncletLayoutPass,
1941}
1942
1943void AMDGPUCodeGenPassBuilder::addIRPasses(AddIRPass &addPass) const {
1946
1948 if (LowerCtorDtor)
1949 addPass(AMDGPUCtorDtorLoweringPass());
1950
1953
1954 // This can be disabled by passing ::Disable here or on the command line
1955 // with --expand-variadics-override=disable.
1957
1958 addPass(AMDGPUAlwaysInlinePass());
1959 addPass(AlwaysInlinerPass());
1960
1962
1963 if (EnableSwLowerLDS)
1964 addPass(AMDGPUSwLowerLDSPass(TM));
1965
1966 // Runs before PromoteAlloca so the latter can account for function uses
1968 addPass(AMDGPULowerModuleLDSPass(TM));
1969
1971 addPass(InferAddressSpacesPass());
1972
1973 // Run atomic optimizer before Atomic Expand
1977
1978 addPass(AtomicExpandPass(&TM));
1979
1981 addPass(AMDGPUPromoteAllocaPass(TM));
1984
1985 // TODO: Handle EnableAMDGPUAliasAnalysis
1986
1987 // TODO: May want to move later or split into an early and late one.
1988 addPass(AMDGPUCodeGenPreparePass(TM));
1989
1990 // TODO: LICM
1991 }
1992
1993 Base::addIRPasses(addPass);
1994
1995 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1996 // example, GVN can combine
1997 //
1998 // %0 = add %a, %b
1999 // %1 = add %b, %a
2000 //
2001 // and
2002 //
2003 // %0 = shl nsw %a, 2
2004 // %1 = shl %a, 2
2005 //
2006 // but EarlyCSE can do neither of them.
2008 addEarlyCSEOrGVNPass(addPass);
2009}
2010
2011void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(AddIRPass &addPass) const {
2012 // AMDGPUAnnotateKernelFeaturesPass is missing here, but it will hopefully be
2013 // deleted soon.
2014
2017
2018 // This lowering has been placed after codegenprepare to take advantage of
2019 // address mode matching (which is why it isn't put with the LDS lowerings).
2020 // It could be placed anywhere before uniformity annotations (an analysis
2021 // that it changes by splitting up fat pointers into their components)
2022 // but has been put before switch lowering and CFG flattening so that those
2023 // passes can run on the more optimized control flow this pass creates in
2024 // many cases.
2025 //
2026 // FIXME: This should ideally be put after the LoadStoreVectorizer.
2027 // However, due to some annoying facts about ResourceUsageAnalysis,
2028 // (especially as exercised in the resource-usage-dead-function test),
2029 // we need all the function passes codegenprepare all the way through
2030 // said resource usage analysis to run on the call graph produced
2031 // before codegenprepare runs (because codegenprepare will knock some
2032 // nodes out of the graph, which leads to function-level passes not
2033 // being run on them, which causes crashes in the resource usage analysis).
2035
2036 Base::addCodeGenPrepare(addPass);
2037
2039 addPass(LoadStoreVectorizerPass());
2040
2041 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2042 // behavior for subsequent passes. Placing it here seems better that these
2043 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2044 // pass flow.
2045 addPass(LowerSwitchPass());
2046}
2047
2048void AMDGPUCodeGenPassBuilder::addPreISel(AddIRPass &addPass) const {
2049
2051 addPass(FlattenCFGPass());
2052
2054 addPass(SinkingPass());
2055
2057
2058 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2059 // regions formed by them.
2060
2062 addPass(FixIrreduciblePass());
2063 addPass(UnifyLoopExitsPass());
2064 addPass(StructurizeCFGPass(/*SkipUniformRegions=*/false));
2065
2067
2068 addPass(SIAnnotateControlFlowPass(TM));
2069
2070 // TODO: Move this right after structurizeCFG to avoid extra divergence
2071 // analysis. This depends on stopping SIAnnotateControlFlow from making
2072 // control flow modifications.
2074
2075 addPass(LCSSAPass());
2076
2079
2080 // FIXME: Why isn't this queried as required from AMDGPUISelDAGToDAG, and why
2081 // isn't this in addInstSelector?
2083}
2084
2085void AMDGPUCodeGenPassBuilder::addILPOpts(AddMachinePass &addPass) const {
2087 addPass(EarlyIfConverterPass());
2088
2089 Base::addILPOpts(addPass);
2090}
2091
2092void AMDGPUCodeGenPassBuilder::addAsmPrinter(AddMachinePass &addPass,
2093 CreateMCStreamer) const {
2094 // TODO: Add AsmPrinter.
2095}
2096
2097Error AMDGPUCodeGenPassBuilder::addInstSelector(AddMachinePass &addPass) const {
2098 addPass(AMDGPUISelDAGToDAGPass(TM));
2099 addPass(SIFixSGPRCopiesPass());
2100 addPass(SILowerI1CopiesPass());
2101 return Error::success();
2102}
2103
2105 AddMachinePass &addPass) const {
2107
2108 addPass(SIFoldOperandsPass());
2109 if (EnableDPPCombine) {
2110 addPass(GCNDPPCombinePass());
2111 }
2112 addPass(SILoadStoreOptimizerPass());
2114 addPass(SIPeepholeSDWAPass());
2115 addPass(EarlyMachineLICMPass());
2116 addPass(MachineCSEPass());
2117 addPass(SIFoldOperandsPass());
2118 }
2120 addPass(SIShrinkInstructionsPass());
2121}
2122
2123void AMDGPUCodeGenPassBuilder::addPostRegAlloc(AddMachinePass &addPass) const {
2124 addPass(SIFixVGPRCopiesPass());
2126 addPass(SIOptimizeExecMaskingPass());
2127 Base::addPostRegAlloc(addPass);
2128}
2129
2131 CodeGenOptLevel Level) const {
2132 if (Opt.getNumOccurrences())
2133 return Opt;
2134 if (TM.getOptLevel() < Level)
2135 return false;
2136 return Opt;
2137}
2138
2141 addPass(GVNPass());
2142 else
2143 addPass(EarlyCSEPass());
2144}
2145
2147 AddIRPass &addPass) const {
2149 addPass(LoopDataPrefetchPass());
2150
2152
2153 // ReassociateGEPs exposes more opportunities for SLSR. See
2154 // the example in reassociate-geps-and-slsr.ll.
2156
2157 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2158 // EarlyCSE can reuse.
2159 addEarlyCSEOrGVNPass(addPass);
2160
2161 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2162 addPass(NaryReassociatePass());
2163
2164 // NaryReassociate on GEPs creates redundant common expressions, so run
2165 // EarlyCSE after it.
2166 addPass(EarlyCSEPass());
2167}
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.
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
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
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.
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:105
void registerPipelineEarlySimplificationEPCallback(const std::function< void(ModulePassManager &, OptimizationLevel, ThinOrFullLTOPhase)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:493
void registerPipelineStartEPCallback(const std::function< void(ModulePassManager &, OptimizationLevel)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:484
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:513
void registerPeepholeEPCallback(const std::function< void(FunctionPassManager &, OptimizationLevel)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:407
void registerCGSCCOptimizerLateEPCallback(const std::function< void(CGSCCPassManager &, OptimizationLevel)> &C)
Register a callback for a default optimizer pipeline extension point.
Definition: PassBuilder.h:452
void registerRegClassFilterParsingCallback(const std::function< RegAllocFilterFunc(StringRef)> &C)
Register callbacks to parse target specific filter field if regalloc pass needs it.
Definition: PassBuilder.h:603
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:532
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:80
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.
Definition: TargetMachine.h:99
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
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.
void initializeGCNPreRAOptimizationsPass(PassRegistry &)
Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
void initializeGCNRewritePartialRegUsesPass(llvm::PassRegistry &)
void initializeAMDGPUAttributorLegacyPass(PassRegistry &)
char & SIPostRABundlerID
FunctionPass * createSIAnnotateControlFlowLegacyPass()
Create the annotation pass.
FunctionPass * createSIModeRegisterPass()
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 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
void initializeGCNPreRALongBranchRegPass(PassRegistry &)
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
void initializeSIWholeQuadModePass(PassRegistry &)
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 AMDGPUPassConfig...
char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
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
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:3609
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.