LLVM 23.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"
25#include "AMDGPUHazardLatency.h"
26#include "AMDGPUIGroupLP.h"
27#include "AMDGPUISelDAGToDAG.h"
29#include "AMDGPUMacroFusion.h"
37#include "AMDGPUSplitModule.h"
42#include "GCNDPPCombine.h"
44#include "GCNNSAReassign.h"
48#include "GCNSchedStrategy.h"
49#include "GCNVOPDUtils.h"
50#include "R600.h"
51#include "R600TargetMachine.h"
52#include "SIFixSGPRCopies.h"
53#include "SIFixVGPRCopies.h"
54#include "SIFoldOperands.h"
55#include "SIFormMemoryClauses.h"
57#include "SILowerControlFlow.h"
58#include "SILowerSGPRSpills.h"
59#include "SILowerWWMCopies.h"
61#include "SIMachineScheduler.h"
65#include "SIPeepholeSDWA.h"
66#include "SIPostRABundler.h"
69#include "SIWholeQuadMode.h"
90#include "llvm/CodeGen/Passes.h"
95#include "llvm/IR/IntrinsicsAMDGPU.h"
96#include "llvm/IR/PassManager.h"
105#include "llvm/Transforms/IPO.h"
130#include <optional>
131
132using namespace llvm;
133using namespace llvm::PatternMatch;
134
135namespace {
136//===----------------------------------------------------------------------===//
137// AMDGPU CodeGen Pass Builder interface.
138//===----------------------------------------------------------------------===//
139
140class AMDGPUCodeGenPassBuilder
141 : public CodeGenPassBuilder<AMDGPUCodeGenPassBuilder, GCNTargetMachine> {
142 using Base = CodeGenPassBuilder<AMDGPUCodeGenPassBuilder, GCNTargetMachine>;
143
144public:
145 AMDGPUCodeGenPassBuilder(GCNTargetMachine &TM,
146 const CGPassBuilderOption &Opts,
147 PassInstrumentationCallbacks *PIC);
148
149 void addIRPasses(PassManagerWrapper &PMW) const;
150 void addCodeGenPrepare(PassManagerWrapper &PMW) const;
151 void addPreISel(PassManagerWrapper &PMW) const;
152 void addILPOpts(PassManagerWrapper &PMWM) const;
153 void addAsmPrinterBegin(PassManagerWrapper &PMW) const;
154 void addAsmPrinter(PassManagerWrapper &PMW) const;
155 void addAsmPrinterEnd(PassManagerWrapper &PMW) const;
156 Error addInstSelector(PassManagerWrapper &PMW) const;
157 void addPreRewrite(PassManagerWrapper &PMW) const;
158 void addMachineSSAOptimization(PassManagerWrapper &PMW) const;
159 void addPostRegAlloc(PassManagerWrapper &PMW) const;
160 void addPreEmitPass(PassManagerWrapper &PMWM) const;
161 void addPreEmitRegAlloc(PassManagerWrapper &PMW) const;
162 Error addRegAssignmentFast(PassManagerWrapper &PMW) const;
163 Error addRegAssignmentOptimized(PassManagerWrapper &PMW) const;
164 void addPreRegAlloc(PassManagerWrapper &PMW) const;
165 Error addFastRegAlloc(PassManagerWrapper &PMW) const;
166 Error addOptimizedRegAlloc(PassManagerWrapper &PMW) const;
167 void addPreSched2(PassManagerWrapper &PMW) const;
168 void addPostBBSections(PassManagerWrapper &PMW) const;
169
170private:
171 Error validateRegAllocOptions() const;
172
173public:
174 /// Check if a pass is enabled given \p Opt option. The option always
175 /// overrides defaults if explicitly used. Otherwise its default will be used
176 /// given that a pass shall work at an optimization \p Level minimum.
177 bool isPassEnabled(const cl::opt<bool> &Opt,
178 CodeGenOptLevel Level = CodeGenOptLevel::Default) const;
179 void addEarlyCSEOrGVNPass(PassManagerWrapper &PMW) const;
180 void addStraightLineScalarOptimizationPasses(PassManagerWrapper &PMW) const;
181};
182
183class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
184public:
185 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
186 : RegisterRegAllocBase(N, D, C) {}
187};
188
189class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
190public:
191 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
192 : RegisterRegAllocBase(N, D, C) {}
193};
194
195class WWMRegisterRegAlloc : public RegisterRegAllocBase<WWMRegisterRegAlloc> {
196public:
197 WWMRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
198 : RegisterRegAllocBase(N, D, C) {}
199};
200
201static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI,
202 const MachineRegisterInfo &MRI,
203 const Register Reg) {
204 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
205 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
206}
207
208static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI,
209 const MachineRegisterInfo &MRI,
210 const Register Reg) {
211 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
212 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
213}
214
215static bool onlyAllocateWWMRegs(const TargetRegisterInfo &TRI,
216 const MachineRegisterInfo &MRI,
217 const Register Reg) {
218 const SIMachineFunctionInfo *MFI =
220 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
221 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC) &&
223}
224
225/// -{sgpr|wwm|vgpr}-regalloc=... command line option.
226static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
227
228/// A dummy default pass factory indicates whether the register allocator is
229/// overridden on the command line.
230static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag;
231static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag;
232static llvm::once_flag InitializeDefaultWWMRegisterAllocatorFlag;
233
234static SGPRRegisterRegAlloc
235defaultSGPRRegAlloc("default",
236 "pick SGPR register allocator based on -O option",
238
239static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
241SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
242 cl::desc("Register allocator to use for SGPRs"));
243
244static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
246VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
247 cl::desc("Register allocator to use for VGPRs"));
248
249static cl::opt<WWMRegisterRegAlloc::FunctionPassCtor, false,
251 WWMRegAlloc("wwm-regalloc", cl::Hidden,
253 cl::desc("Register allocator to use for WWM registers"));
254
255// New pass manager register allocator options for AMDGPU
257 "sgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
258 cl::desc("Register allocator for SGPRs (new pass manager)"));
259
261 "vgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
262 cl::desc("Register allocator for VGPRs (new pass manager)"));
263
265 "wwm-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
266 cl::desc("Register allocator for WWM registers (new pass manager)"));
267
268/// Check if the given RegAllocType is supported for AMDGPU NPM register
269/// allocation. Only Fast and Greedy are supported; Basic and PBQP are not.
270static Error checkRegAllocSupported(RegAllocType RAType, StringRef RegName) {
271 if (RAType == RegAllocType::Basic || RAType == RegAllocType::PBQP) {
273 Twine("unsupported register allocator '") +
274 (RAType == RegAllocType::Basic ? "basic" : "pbqp") + "' for " +
275 RegName + " registers",
277 }
278 return Error::success();
279}
280
281Error AMDGPUCodeGenPassBuilder::validateRegAllocOptions() const {
282 // 1. Generic --regalloc-npm is not supported for AMDGPU.
283 if (Opt.RegAlloc != RegAllocType::Unset) {
285 "-regalloc-npm not supported for amdgcn. Use -sgpr-regalloc-npm, "
286 "-vgpr-regalloc-npm, and -wwm-regalloc-npm",
288 }
289
290 // 2. Legacy PM regalloc options are not compatible with NPM.
291 if (SGPRRegAlloc.getNumOccurrences() > 0 ||
292 VGPRRegAlloc.getNumOccurrences() > 0 ||
293 WWMRegAlloc.getNumOccurrences() > 0) {
295 "-sgpr-regalloc, -vgpr-regalloc, and -wwm-regalloc are legacy PM "
296 "options. Use -sgpr-regalloc-npm, -vgpr-regalloc-npm, and "
297 "-wwm-regalloc-npm with the new pass manager",
299 }
300
301 // 3. Only Fast and Greedy allocators are supported for AMDGPU.
302 if (auto Err = checkRegAllocSupported(SGPRRegAllocNPM, "SGPR"))
303 return Err;
304 if (auto Err = checkRegAllocSupported(WWMRegAllocNPM, "WWM"))
305 return Err;
306 if (auto Err = checkRegAllocSupported(VGPRRegAllocNPM, "VGPR"))
307 return Err;
308
309 return Error::success();
310}
311
312static void initializeDefaultSGPRRegisterAllocatorOnce() {
313 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
314
315 if (!Ctor) {
316 Ctor = SGPRRegAlloc;
317 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
318 }
319}
320
321static void initializeDefaultVGPRRegisterAllocatorOnce() {
322 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
323
324 if (!Ctor) {
325 Ctor = VGPRRegAlloc;
326 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
327 }
328}
329
330static void initializeDefaultWWMRegisterAllocatorOnce() {
331 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
332
333 if (!Ctor) {
334 Ctor = WWMRegAlloc;
335 WWMRegisterRegAlloc::setDefault(WWMRegAlloc);
336 }
337}
338
339static FunctionPass *createBasicSGPRRegisterAllocator() {
340 return createBasicRegisterAllocator(onlyAllocateSGPRs);
341}
342
343static FunctionPass *createGreedySGPRRegisterAllocator() {
344 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
345}
346
347static FunctionPass *createFastSGPRRegisterAllocator() {
348 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
349}
350
351static FunctionPass *createBasicVGPRRegisterAllocator() {
352 return createBasicRegisterAllocator(onlyAllocateVGPRs);
353}
354
355static FunctionPass *createGreedyVGPRRegisterAllocator() {
356 return createGreedyRegisterAllocator(onlyAllocateVGPRs);
357}
358
359static FunctionPass *createFastVGPRRegisterAllocator() {
360 return createFastRegisterAllocator(onlyAllocateVGPRs, true);
361}
362
363static FunctionPass *createBasicWWMRegisterAllocator() {
364 return createBasicRegisterAllocator(onlyAllocateWWMRegs);
365}
366
367static FunctionPass *createGreedyWWMRegisterAllocator() {
368 return createGreedyRegisterAllocator(onlyAllocateWWMRegs);
369}
370
371static FunctionPass *createFastWWMRegisterAllocator() {
372 return createFastRegisterAllocator(onlyAllocateWWMRegs, false);
373}
374
375static SGPRRegisterRegAlloc basicRegAllocSGPR(
376 "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
377static SGPRRegisterRegAlloc greedyRegAllocSGPR(
378 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
379
380static SGPRRegisterRegAlloc fastRegAllocSGPR(
381 "fast", "fast register allocator", createFastSGPRRegisterAllocator);
382
383
384static VGPRRegisterRegAlloc basicRegAllocVGPR(
385 "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
386static VGPRRegisterRegAlloc greedyRegAllocVGPR(
387 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
388
389static VGPRRegisterRegAlloc fastRegAllocVGPR(
390 "fast", "fast register allocator", createFastVGPRRegisterAllocator);
391static WWMRegisterRegAlloc basicRegAllocWWMReg("basic",
392 "basic register allocator",
393 createBasicWWMRegisterAllocator);
394static WWMRegisterRegAlloc
395 greedyRegAllocWWMReg("greedy", "greedy register allocator",
396 createGreedyWWMRegisterAllocator);
397static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator",
398 createFastWWMRegisterAllocator);
399
401 return Phase == ThinOrFullLTOPhase::FullLTOPreLink ||
402 Phase == ThinOrFullLTOPhase::ThinLTOPreLink;
403}
404} // anonymous namespace
405
406static cl::opt<bool>
408 cl::desc("Run early if-conversion"),
409 cl::init(false));
410
411static cl::opt<bool>
412OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
413 cl::desc("Run pre-RA exec mask optimizations"),
414 cl::init(true));
415
416static cl::opt<bool>
417 LowerCtorDtor("amdgpu-lower-global-ctor-dtor",
418 cl::desc("Lower GPU ctor / dtors to globals on the device."),
419 cl::init(true), cl::Hidden);
420
421// Option to disable vectorizer for tests.
423 "amdgpu-load-store-vectorizer",
424 cl::desc("Enable load store vectorizer"),
425 cl::init(true),
426 cl::Hidden);
427
428// Option to control global loads scalarization
430 "amdgpu-scalarize-global-loads",
431 cl::desc("Enable global load scalarization"),
432 cl::init(true),
433 cl::Hidden);
434
435// Option to run internalize pass.
437 "amdgpu-internalize-symbols",
438 cl::desc("Enable elimination of non-kernel functions and unused globals"),
439 cl::init(false),
440 cl::Hidden);
441
442// Option to inline all early.
444 "amdgpu-early-inline-all",
445 cl::desc("Inline all functions early"),
446 cl::init(false),
447 cl::Hidden);
448
450 "amdgpu-enable-remove-incompatible-functions", cl::Hidden,
451 cl::desc("Enable removal of functions when they"
452 "use features not supported by the target GPU"),
453 cl::init(true));
454
456 "amdgpu-sdwa-peephole",
457 cl::desc("Enable SDWA peepholer"),
458 cl::init(true));
459
461 "amdgpu-dpp-combine",
462 cl::desc("Enable DPP combiner"),
463 cl::init(true));
464
465// Enable address space based alias analysis
467 cl::desc("Enable AMDGPU Alias Analysis"),
468 cl::init(true));
469
470// Enable lib calls simplifications
472 "amdgpu-simplify-libcall",
473 cl::desc("Enable amdgpu library simplifications"),
474 cl::init(true),
475 cl::Hidden);
476
478 "amdgpu-ir-lower-kernel-arguments",
479 cl::desc("Lower kernel argument loads in IR pass"),
480 cl::init(true),
481 cl::Hidden);
482
484 "amdgpu-reassign-regs",
485 cl::desc("Enable register reassign optimizations on gfx10+"),
486 cl::init(true),
487 cl::Hidden);
488
490 "amdgpu-opt-vgpr-liverange",
491 cl::desc("Enable VGPR liverange optimizations for if-else structure"),
492 cl::init(true), cl::Hidden);
493
495 "amdgpu-atomic-optimizer-strategy",
496 cl::desc("Select DPP or Iterative strategy for scan"),
499 clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"),
501 "Use Iterative approach for scan"),
502 clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")));
503
504// Enable Mode register optimization
506 "amdgpu-mode-register",
507 cl::desc("Enable mode register pass"),
508 cl::init(true),
509 cl::Hidden);
510
511// Enable GFX11+ s_delay_alu insertion
512static cl::opt<bool>
513 EnableInsertDelayAlu("amdgpu-enable-delay-alu",
514 cl::desc("Enable s_delay_alu insertion"),
515 cl::init(true), cl::Hidden);
516
517// Enable GFX11+ VOPD
518static cl::opt<bool>
519 EnableVOPD("amdgpu-enable-vopd",
520 cl::desc("Enable VOPD, dual issue of VALU in wave32"),
521 cl::init(true), cl::Hidden);
522
523// Option is used in lit tests to prevent deadcoding of patterns inspected.
524static cl::opt<bool>
525EnableDCEInRA("amdgpu-dce-in-ra",
526 cl::init(true), cl::Hidden,
527 cl::desc("Enable machine DCE inside regalloc"));
528
529static cl::opt<bool> EnableSetWavePriority("amdgpu-set-wave-priority",
530 cl::desc("Adjust wave priority"),
531 cl::init(false), cl::Hidden);
532
534 "amdgpu-scalar-ir-passes",
535 cl::desc("Enable scalar IR passes"),
536 cl::init(true),
537 cl::Hidden);
538
540 "amdgpu-enable-lower-exec-sync",
541 cl::desc("Enable lowering of execution synchronization."), cl::init(true),
542 cl::Hidden);
543
544static cl::opt<bool>
545 EnableSwLowerLDS("amdgpu-enable-sw-lower-lds",
546 cl::desc("Enable lowering of lds to global memory pass "
547 "and asan instrument resulting IR."),
548 cl::init(true), cl::Hidden);
549
551 "amdgpu-enable-object-linking",
552 cl::desc("Enable object linking for cross-TU LDS and ABI support"),
554 cl::Hidden);
555
557 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
559 cl::Hidden);
560
562 "amdgpu-enable-pre-ra-optimizations",
563 cl::desc("Enable Pre-RA optimizations pass"), cl::init(true),
564 cl::Hidden);
565
567 "amdgpu-enable-promote-kernel-arguments",
568 cl::desc("Enable promotion of flat kernel pointer arguments to global"),
569 cl::Hidden, cl::init(true));
570
572 "amdgpu-enable-image-intrinsic-optimizer",
573 cl::desc("Enable image intrinsic optimizer pass"), cl::init(true),
574 cl::Hidden);
575
576static cl::opt<bool>
577 EnableLoopPrefetch("amdgpu-loop-prefetch",
578 cl::desc("Enable loop data prefetch on AMDGPU"),
579 cl::Hidden, cl::init(false));
580
582 AMDGPUSchedStrategy("amdgpu-sched-strategy",
583 cl::desc("Select custom AMDGPU scheduling strategy."),
584 cl::Hidden, cl::init(""));
585
586// Scheduler selection is consulted both when creating the scheduler and from
587// overrideSchedPolicy(), so keep the attribute and global command line handling
588// in one helper.
590 Attribute SchedStrategyAttr = F.getFnAttribute("amdgpu-sched-strategy");
591 if (SchedStrategyAttr.isValid())
592 return SchedStrategyAttr.getValueAsString();
593
594 if (!AMDGPUSchedStrategy.empty())
595 return AMDGPUSchedStrategy;
596
597 return "";
598}
599
600static void
602 const GCNSubtarget &ST) {
603 if (ST.hasGFX1250Insts())
604 return;
605
606 F.getContext().diagnose(DiagnosticInfoUnsupported(
607 F, "'amdgpu-sched-strategy'='coexec' is only supported for gfx1250",
609}
610
611static bool useNoopPostScheduler(const Function &F) {
612 Attribute PostSchedStrategyAttr =
613 F.getFnAttribute("amdgpu-post-sched-strategy");
614 return PostSchedStrategyAttr.isValid() &&
615 PostSchedStrategyAttr.getValueAsString() == "nop";
616}
617
619 "amdgpu-enable-rewrite-partial-reg-uses",
620 cl::desc("Enable rewrite partial reg uses pass"), cl::init(true),
621 cl::Hidden);
622
624 "amdgpu-enable-hipstdpar",
625 cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false),
626 cl::Hidden);
627
628static cl::opt<bool>
629 EnableAMDGPUAttributor("amdgpu-attributor-enable",
630 cl::desc("Enable AMDGPUAttributorPass"),
631 cl::init(true), cl::Hidden);
632
634 "new-reg-bank-select",
635 cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of "
636 "regbankselect"),
637 cl::init(false), cl::Hidden);
638
640 "amdgpu-link-time-closed-world",
641 cl::desc("Whether has closed-world assumption at link time"),
642 cl::init(false), cl::Hidden);
643
645 "amdgpu-enable-uniform-intrinsic-combine",
646 cl::desc("Enable/Disable the Uniform Intrinsic Combine Pass"),
647 cl::init(true), cl::Hidden);
648
650 // Register the target
653
739}
740
741static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
742 return std::make_unique<AMDGPUTargetObjectFile>();
743}
744
748
749static ScheduleDAGInstrs *
751 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
752 ScheduleDAGMILive *DAG =
753 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
754 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
755 if (ST.shouldClusterStores())
756 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
758 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
759 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
760 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
761 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
762 return DAG;
763}
764
765static ScheduleDAGInstrs *
767 ScheduleDAGMILive *DAG =
768 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C));
770 return DAG;
771}
772
773static ScheduleDAGInstrs *
775 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
777 C, std::make_unique<GCNMaxMemoryClauseSchedStrategy>(C));
778 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
779 if (ST.shouldClusterStores())
780 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
781 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
782 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
783 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
784 return DAG;
785}
786
787static ScheduleDAGInstrs *
789 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
790 auto *DAG = new GCNIterativeScheduler(
792 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
793 if (ST.shouldClusterStores())
794 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
796 return DAG;
797}
798
805
806static ScheduleDAGInstrs *
808 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
810 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
811 if (ST.shouldClusterStores())
812 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
813 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
815 return DAG;
816}
817
818static MachineSchedRegistry
819SISchedRegistry("si", "Run SI's custom scheduler",
821
824 "Run GCN scheduler to maximize occupancy",
826
828 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp",
830
832 "gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause",
834
836 "gcn-iterative-max-occupancy-experimental",
837 "Run GCN scheduler to maximize occupancy (experimental)",
839
841 "gcn-iterative-minreg",
842 "Run GCN iterative scheduler for minimal register usage (experimental)",
844
846 "gcn-iterative-ilp",
847 "Run GCN iterative scheduler for ILP scheduling (experimental)",
849
852 if (!GPU.empty())
853 return GPU;
854
855 // Need to default to a target with flat support for HSA.
856 if (TT.isAMDGCN())
857 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
858
859 return "r600";
860}
861
863 // The AMDGPU toolchain only supports generating shared objects, so we
864 // must always use PIC.
865 return Reloc::PIC_;
866}
867
869 StringRef CPU, StringRef FS,
870 const TargetOptions &Options,
871 std::optional<Reloc::Model> RM,
872 std::optional<CodeModel::Model> CM,
875 T, TT.computeDataLayout(), TT, getGPUOrDefault(TT, CPU), FS, Options,
877 OptLevel),
879 initAsmInfo();
880 if (TT.isAMDGCN()) {
881 if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize64"))
883 else if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize32"))
885 }
886}
887
891
893
895 Attribute GPUAttr = F.getFnAttribute("target-cpu");
896 return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU();
897}
898
900 Attribute FSAttr = F.getFnAttribute("target-features");
901
902 return FSAttr.isValid() ? FSAttr.getValueAsString()
904}
905
908 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
910 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
911 if (ST.shouldClusterStores())
912 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
913 return DAG;
914}
915
916/// Predicate for Internalize pass.
917static bool mustPreserveGV(const GlobalValue &GV) {
918 if (const Function *F = dyn_cast<Function>(&GV))
919 return F->isDeclaration() || F->getName().starts_with("__asan_") ||
920 F->getName().starts_with("__sanitizer_") ||
921 AMDGPU::isEntryFunctionCC(F->getCallingConv());
922
924 return !GV.use_empty();
925}
926
931
934 if (Params.empty())
936 Params.consume_front("strategy=");
937 auto Result = StringSwitch<std::optional<ScanOptions>>(Params)
938 .Case("dpp", ScanOptions::DPP)
939 .Cases({"iterative", ""}, ScanOptions::Iterative)
940 .Case("none", ScanOptions::None)
941 .Default(std::nullopt);
942 if (Result)
943 return *Result;
944 return make_error<StringError>("invalid parameter", inconvertibleErrorCode());
945}
946
950 while (!Params.empty()) {
951 StringRef ParamName;
952 std::tie(ParamName, Params) = Params.split(';');
953 if (ParamName == "closed-world") {
954 Result.IsClosedWorld = true;
955 } else {
957 formatv("invalid AMDGPUAttributor pass parameter '{0}' ", ParamName)
958 .str(),
960 }
961 }
962 return Result;
963}
964
966
967#define GET_PASS_REGISTRY "AMDGPUPassRegistry.def"
969
970 PB.registerPipelineParsingCallback(
971 [this](StringRef Name, CGSCCPassManager &PM,
973 if (Name == "amdgpu-attributor-cgscc" && getTargetTriple().isAMDGCN()) {
975 *static_cast<GCNTargetMachine *>(this)));
976 return true;
977 }
978 return false;
979 });
980
981 PB.registerScalarOptimizerLateEPCallback(
982 [](FunctionPassManager &FPM, OptimizationLevel Level) {
983 if (Level == OptimizationLevel::O0)
984 return;
985
987 });
988
989 PB.registerVectorizerEndEPCallback(
990 [](FunctionPassManager &FPM, OptimizationLevel Level) {
991 if (Level == OptimizationLevel::O0)
992 return;
993
995 });
996
997 PB.registerPipelineEarlySimplificationEPCallback(
998 [this](ModulePassManager &PM, OptimizationLevel Level,
1000 if (!isLTOPreLink(Phase) && getTargetTriple().isAMDGCN()) {
1001 // When we are not using -fgpu-rdc, we can run accelerator code
1002 // selection relatively early, but still after linking to prevent
1003 // eager removal of potentially reachable symbols.
1004 if (EnableHipStdPar) {
1007 }
1008
1010 }
1011
1012 if (Level == OptimizationLevel::O0)
1013 return;
1014
1015 // We don't want to run internalization at per-module stage.
1018 PM.addPass(GlobalDCEPass());
1019 }
1020
1023 });
1024
1025 PB.registerPeepholeEPCallback(
1026 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1027 if (Level == OptimizationLevel::O0)
1028 return;
1029
1033
1036 });
1037
1038 PB.registerCGSCCOptimizerLateEPCallback(
1039 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
1040 if (Level == OptimizationLevel::O0)
1041 return;
1042
1044
1045 // Add promote kernel arguments pass to the opt pipeline right before
1046 // infer address spaces which is needed to do actual address space
1047 // rewriting.
1048 if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
1051
1052 // Add infer address spaces pass to the opt pipeline after inlining
1053 // but before SROA to increase SROA opportunities.
1055
1056 // This should run after inlining to have any chance of doing
1057 // anything, and before other cleanup optimizations.
1059
1060 if (Level != OptimizationLevel::O0) {
1061 // Promote alloca to vector before SROA and loop unroll. If we
1062 // manage to eliminate allocas before unroll we may choose to unroll
1063 // less.
1065 }
1066
1067 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1068 });
1069
1070 // FIXME: Why is AMDGPUAttributor not in CGSCC?
1071 PB.registerOptimizerLastEPCallback([this](ModulePassManager &MPM,
1072 OptimizationLevel Level,
1074 if (Level != OptimizationLevel::O0) {
1075 if (!isLTOPreLink(Phase)) {
1076 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1078 MPM.addPass(AMDGPUAttributorPass(*this, Opts, Phase));
1079 }
1080 }
1081 }
1082 });
1083
1084 PB.registerFullLinkTimeOptimizationLastEPCallback(
1085 [this](ModulePassManager &PM, OptimizationLevel Level) {
1086 // When we are using -fgpu-rdc, we can only run accelerator code
1087 // selection after linking to prevent, otherwise we end up removing
1088 // potentially reachable symbols that were exported as external in other
1089 // modules.
1090 if (EnableHipStdPar) {
1093 }
1094 // We want to support the -lto-partitions=N option as "best effort".
1095 // For that, we need to lower LDS earlier in the pipeline before the
1096 // module is partitioned for codegen.
1099 if (EnableSwLowerLDS)
1100 PM.addPass(AMDGPUSwLowerLDSPass(*this));
1103 if (Level != OptimizationLevel::O0) {
1104 // We only want to run this with O2 or higher since inliner and SROA
1105 // don't run in O1.
1106 if (Level != OptimizationLevel::O1) {
1107 PM.addPass(
1109 }
1110 // Do we really need internalization in LTO?
1111 if (InternalizeSymbols) {
1113 PM.addPass(GlobalDCEPass());
1114 }
1115 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1118 Opt.IsClosedWorld = true;
1121 }
1122 }
1123 if (!NoKernelInfoEndLTO) {
1125 FPM.addPass(KernelInfoPrinter(this));
1126 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1127 }
1128 });
1129
1130 PB.registerRegClassFilterParsingCallback(
1131 [](StringRef FilterName) -> RegAllocFilterFunc {
1132 if (FilterName == "sgpr")
1133 return onlyAllocateSGPRs;
1134 if (FilterName == "vgpr")
1135 return onlyAllocateVGPRs;
1136 if (FilterName == "wwm")
1137 return onlyAllocateWWMRegs;
1138 return nullptr;
1139 });
1140}
1141
1143 unsigned DestAS) const {
1144 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
1146}
1147
1149 if (auto *Arg = dyn_cast<Argument>(V);
1150 Arg &&
1151 AMDGPU::isModuleEntryFunctionCC(Arg->getParent()->getCallingConv()) &&
1152 !Arg->hasByRefAttr())
1154
1155 const auto *LD = dyn_cast<LoadInst>(V);
1156 if (!LD) // TODO: Handle invariant load like constant.
1158
1159 // It must be a generic pointer loaded.
1160 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
1161
1162 const auto *Ptr = LD->getPointerOperand();
1163 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1165 // For a generic pointer loaded from the constant memory, it could be assumed
1166 // as a global pointer since the constant memory is only populated on the
1167 // host side. As implied by the offload programming model, only global
1168 // pointers could be referenced on the host side.
1170}
1171
1172std::pair<const Value *, unsigned>
1174 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1175 switch (II->getIntrinsicID()) {
1176 case Intrinsic::amdgcn_is_shared:
1177 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
1178 case Intrinsic::amdgcn_is_private:
1179 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
1180 default:
1181 break;
1182 }
1183 return std::pair(nullptr, -1);
1184 }
1185 // Check the global pointer predication based on
1186 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
1187 // the order of 'is_shared' and 'is_private' is not significant.
1188 Value *Ptr;
1189 if (match(
1190 const_cast<Value *>(V),
1193 m_Deferred(Ptr))))))
1194 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
1195
1196 return std::pair(nullptr, -1);
1197}
1198
1199unsigned
1214
1216 Module &M, unsigned NumParts,
1217 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1218 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
1219 // but all current users of this API don't have one ready and would need to
1220 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1221
1226
1227 PassBuilder PB(this);
1228 PB.registerModuleAnalyses(MAM);
1229 PB.registerFunctionAnalyses(FAM);
1230 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1231
1233 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1234 MPM.run(M, MAM);
1235 return true;
1236}
1237
1238//===----------------------------------------------------------------------===//
1239// GCN Target Machine (SI+)
1240//===----------------------------------------------------------------------===//
1241
1243 StringRef CPU, StringRef FS,
1244 const TargetOptions &Options,
1245 std::optional<Reloc::Model> RM,
1246 std::optional<CodeModel::Model> CM,
1247 CodeGenOptLevel OL, bool JIT)
1248 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
1249
1250const TargetSubtargetInfo *
1252 StringRef GPU = getGPUName(F);
1254
1255 SmallString<128> SubtargetKey(GPU);
1256 SubtargetKey.append(FS);
1257
1258 auto &I = SubtargetMap[SubtargetKey];
1259 if (!I) {
1260 // This needs to be done before we create a new subtarget since any
1261 // creation will depend on the TM and the code generation flags on the
1262 // function that reside in TargetOptions.
1264 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
1265 }
1266
1267 I->setScalarizeGlobalBehavior(ScalarizeGlobal);
1268
1269 return I.get();
1270}
1271
1274 return TargetTransformInfo(std::make_unique<GCNTTIImpl>(this, F));
1275}
1276
1279 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
1280 const CGPassBuilderOption &Opts, MCContext &Ctx,
1282 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1283 return CGPB.buildPipeline(MPM, MAM, Out, DwoOut, FileType, Ctx);
1284}
1285
1288 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1289 if (ST.enableSIScheduler())
1291
1292 StringRef SchedStrategy = AMDGPU::getSchedStrategy(C->MF->getFunction());
1293
1294 if (SchedStrategy == "max-ilp")
1296
1297 if (SchedStrategy == "max-memory-clause")
1299
1300 if (SchedStrategy == "iterative-ilp")
1302
1303 if (SchedStrategy == "iterative-minreg")
1304 return createMinRegScheduler(C);
1305
1306 if (SchedStrategy == "iterative-maxocc")
1308
1309 if (SchedStrategy == "coexec") {
1310 diagnoseUnsupportedCoExecSchedulerSelection(C->MF->getFunction(), ST);
1312 }
1313
1315}
1316
1319 if (useNoopPostScheduler(C->MF->getFunction()))
1321
1322 ScheduleDAGMI *DAG =
1323 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1324 /*RemoveKillFlags=*/true);
1325 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1327 if (ST.shouldClusterStores())
1330 if ((EnableVOPD.getNumOccurrences() ||
1332 EnableVOPD)
1337 return DAG;
1338}
1339//===----------------------------------------------------------------------===//
1340// AMDGPU Legacy Pass Setup
1341//===----------------------------------------------------------------------===//
1342
1343std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1344 return getStandardCSEConfigForOpt(TM->getOptLevel());
1345}
1346
1347namespace {
1348
1349class GCNPassConfig final : public AMDGPUPassConfig {
1350public:
1351 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1352 : AMDGPUPassConfig(TM, PM) {
1353 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1354 }
1355
1356 GCNTargetMachine &getGCNTargetMachine() const {
1357 return getTM<GCNTargetMachine>();
1358 }
1359
1360 bool addPreISel() override;
1361 void addMachineSSAOptimization() override;
1362 bool addILPOpts() override;
1363 bool addInstSelector() override;
1364 bool addIRTranslator() override;
1365 void addPreLegalizeMachineIR() override;
1366 bool addLegalizeMachineIR() override;
1367 void addPreRegBankSelect() override;
1368 bool addRegBankSelect() override;
1369 void addPreGlobalInstructionSelect() override;
1370 bool addGlobalInstructionSelect() override;
1371 void addPreRegAlloc() override;
1372 void addFastRegAlloc() override;
1373 void addOptimizedRegAlloc() override;
1374
1375 FunctionPass *createSGPRAllocPass(bool Optimized);
1376 FunctionPass *createVGPRAllocPass(bool Optimized);
1377 FunctionPass *createWWMRegAllocPass(bool Optimized);
1378 FunctionPass *createRegAllocPass(bool Optimized) override;
1379
1380 bool addRegAssignAndRewriteFast() override;
1381 bool addRegAssignAndRewriteOptimized() override;
1382
1383 bool addPreRewrite() override;
1384 void addPostRegAlloc() override;
1385 void addPreSched2() override;
1386 void addPreEmitPass() override;
1387 void addPostBBSections() override;
1388};
1389
1390} // end anonymous namespace
1391
1393 : TargetPassConfig(TM, PM) {
1394 // Exceptions and StackMaps are not supported, so these passes will never do
1395 // anything.
1398 // Garbage collection is not supported.
1401}
1402
1409
1414 // ReassociateGEPs exposes more opportunities for SLSR. See
1415 // the example in reassociate-geps-and-slsr.ll.
1417 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1418 // EarlyCSE can reuse.
1420 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1422 // NaryReassociate on GEPs creates redundant common expressions, so run
1423 // EarlyCSE after it.
1425}
1426
1429
1430 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN())
1432
1433 // There is no reason to run these.
1437
1438 if (TM.getTargetTriple().isAMDGCN())
1440
1441 if (LowerCtorDtor)
1443
1444 if (TM.getTargetTriple().isAMDGCN() &&
1447
1450
1451 // This can be disabled by passing ::Disable here or on the command line
1452 // with --expand-variadics-override=disable.
1454
1455 // Function calls are not supported, so make sure we inline everything.
1458
1459 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1460 if (TM.getTargetTriple().getArch() == Triple::r600)
1462
1463 // Make enqueued block runtime handles externally visible.
1465
1466 // Lower special LDS accesses.
1469
1470 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1471 if (EnableSwLowerLDS)
1473
1474 // Runs before PromoteAlloca so the latter can account for function uses
1477 }
1478
1479 // Run atomic optimizer before Atomic Expand
1480 if ((TM.getTargetTriple().isAMDGCN()) &&
1481 (TM.getOptLevel() >= CodeGenOptLevel::Less) &&
1484 }
1485
1487
1488 if (TM.getOptLevel() > CodeGenOptLevel::None) {
1490
1493
1497 AAResults &AAR) {
1498 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1499 AAR.addAAResult(WrapperPass->getResult());
1500 }));
1501 }
1502
1503 if (TM.getTargetTriple().isAMDGCN()) {
1504 // TODO: May want to move later or split into an early and late one.
1506 }
1507
1508 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1509 // have expanded.
1510 if (TM.getOptLevel() > CodeGenOptLevel::Less)
1512 }
1513
1515
1516 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1517 // example, GVN can combine
1518 //
1519 // %0 = add %a, %b
1520 // %1 = add %b, %a
1521 //
1522 // and
1523 //
1524 // %0 = shl nsw %a, 2
1525 // %1 = shl %a, 2
1526 //
1527 // but EarlyCSE can do neither of them.
1530}
1531
1533 if (TM->getTargetTriple().isAMDGCN() &&
1534 TM->getOptLevel() > CodeGenOptLevel::None)
1536
1537 if (TM->getTargetTriple().isAMDGCN() && EnableLowerKernelArguments)
1539
1541
1544
1545 if (TM->getTargetTriple().isAMDGCN()) {
1546 // This lowering has been placed after codegenprepare to take advantage of
1547 // address mode matching (which is why it isn't put with the LDS lowerings).
1548 // It could be placed anywhere before uniformity annotations (an analysis
1549 // that it changes by splitting up fat pointers into their components)
1550 // but has been put before switch lowering and CFG flattening so that those
1551 // passes can run on the more optimized control flow this pass creates in
1552 // many cases.
1555 }
1556
1557 // LowerSwitch pass may introduce unreachable blocks that can
1558 // cause unexpected behavior for subsequent passes. Placing it
1559 // here seems better that these blocks would get cleaned up by
1560 // UnreachableBlockElim inserted next in the pass flow.
1562}
1563
1565 if (TM->getOptLevel() > CodeGenOptLevel::None)
1567 return false;
1568}
1569
1574
1576 // Do nothing. GC is not supported.
1577 return false;
1578}
1579
1580//===----------------------------------------------------------------------===//
1581// GCN Legacy Pass Setup
1582//===----------------------------------------------------------------------===//
1583
1584bool GCNPassConfig::addPreISel() {
1586
1587 if (TM->getOptLevel() > CodeGenOptLevel::None)
1588 addPass(createSinkingPass());
1589
1590 if (TM->getOptLevel() > CodeGenOptLevel::None)
1592
1593 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1594 // regions formed by them.
1596 addPass(createFixIrreduciblePass());
1597 addPass(createUnifyLoopExitsPass());
1598 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1599
1602 // TODO: Move this right after structurizeCFG to avoid extra divergence
1603 // analysis. This depends on stopping SIAnnotateControlFlow from making
1604 // control flow modifications.
1606
1607 // SDAG requires LCSSA, GlobalISel does not. Disable LCSSA for -global-isel
1608 // with -new-reg-bank-select and without any of the fallback options.
1610 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
1611 addPass(createLCSSAPass());
1612
1613 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1615
1616 return false;
1617}
1618
1619void GCNPassConfig::addMachineSSAOptimization() {
1621
1622 // We want to fold operands after PeepholeOptimizer has run (or as part of
1623 // it), because it will eliminate extra copies making it easier to fold the
1624 // real source operand. We want to eliminate dead instructions after, so that
1625 // we see fewer uses of the copies. We then need to clean up the dead
1626 // instructions leftover after the operands are folded as well.
1627 //
1628 // XXX - Can we get away without running DeadMachineInstructionElim again?
1629 addPass(&SIFoldOperandsLegacyID);
1630 if (EnableDPPCombine)
1631 addPass(&GCNDPPCombineLegacyID);
1633 if (isPassEnabled(EnableSDWAPeephole)) {
1634 addPass(&SIPeepholeSDWALegacyID);
1635 addPass(&EarlyMachineLICMID);
1636 addPass(&MachineCSELegacyID);
1637 addPass(&SIFoldOperandsLegacyID);
1638 }
1641}
1642
1643bool GCNPassConfig::addILPOpts() {
1645 addPass(&EarlyIfConverterLegacyID);
1646
1648 return false;
1649}
1650
1651bool GCNPassConfig::addInstSelector() {
1653 addPass(&SIFixSGPRCopiesLegacyID);
1655 return false;
1656}
1657
1658bool GCNPassConfig::addIRTranslator() {
1659 addPass(new IRTranslator(getOptLevel()));
1660 return false;
1661}
1662
1663void GCNPassConfig::addPreLegalizeMachineIR() {
1664 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1665 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1666 addPass(new Localizer());
1667}
1668
1669bool GCNPassConfig::addLegalizeMachineIR() {
1670 addPass(new Legalizer());
1671 return false;
1672}
1673
1674void GCNPassConfig::addPreRegBankSelect() {
1675 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1676 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1678}
1679
1680bool GCNPassConfig::addRegBankSelect() {
1681 if (NewRegBankSelect) {
1684 } else {
1685 addPass(new RegBankSelect());
1686 }
1687 return false;
1688}
1689
1690void GCNPassConfig::addPreGlobalInstructionSelect() {
1691 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1692 addPass(createAMDGPURegBankCombiner(IsOptNone));
1693}
1694
1695bool GCNPassConfig::addGlobalInstructionSelect() {
1696 addPass(new InstructionSelect(getOptLevel()));
1697 return false;
1698}
1699
1700void GCNPassConfig::addFastRegAlloc() {
1701 // FIXME: We have to disable the verifier here because of PHIElimination +
1702 // TwoAddressInstructions disabling it.
1703
1704 // This must be run immediately after phi elimination and before
1705 // TwoAddressInstructions, otherwise the processing of the tied operand of
1706 // SI_ELSE will introduce a copy of the tied operand source after the else.
1708
1710
1712}
1713
1714void GCNPassConfig::addPreRegAlloc() {
1715 if (getOptLevel() != CodeGenOptLevel::None)
1717}
1718
1719void GCNPassConfig::addOptimizedRegAlloc() {
1720 if (EnableDCEInRA)
1722
1723 // FIXME: when an instruction has a Killed operand, and the instruction is
1724 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1725 // the register in LiveVariables, this would trigger a failure in verifier,
1726 // we should fix it and enable the verifier.
1727 if (OptVGPRLiveRange)
1729
1730 // This must be run immediately after phi elimination and before
1731 // TwoAddressInstructions, otherwise the processing of the tied operand of
1732 // SI_ELSE will introduce a copy of the tied operand source after the else.
1734
1737
1738 if (isPassEnabled(EnablePreRAOptimizations))
1740
1741 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1742 // instructions that cause scheduling barriers.
1744
1745 if (OptExecMaskPreRA)
1747
1748 // This is not an essential optimization and it has a noticeable impact on
1749 // compilation time, so we only enable it from O2.
1750 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1752
1754}
1755
1756bool GCNPassConfig::addPreRewrite() {
1758 addPass(&GCNNSAReassignID);
1759
1761 return true;
1762}
1763
1764FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1765 // Initialize the global default.
1766 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1767 initializeDefaultSGPRRegisterAllocatorOnce);
1768
1769 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1770 if (Ctor != useDefaultRegisterAllocator)
1771 return Ctor();
1772
1773 if (Optimized)
1774 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1775
1776 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1777}
1778
1779FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1780 // Initialize the global default.
1781 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1782 initializeDefaultVGPRRegisterAllocatorOnce);
1783
1784 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1785 if (Ctor != useDefaultRegisterAllocator)
1786 return Ctor();
1787
1788 if (Optimized)
1789 return createGreedyVGPRRegisterAllocator();
1790
1791 return createFastVGPRRegisterAllocator();
1792}
1793
1794FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1795 // Initialize the global default.
1796 llvm::call_once(InitializeDefaultWWMRegisterAllocatorFlag,
1797 initializeDefaultWWMRegisterAllocatorOnce);
1798
1799 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1800 if (Ctor != useDefaultRegisterAllocator)
1801 return Ctor();
1802
1803 if (Optimized)
1804 return createGreedyWWMRegisterAllocator();
1805
1806 return createFastWWMRegisterAllocator();
1807}
1808
1809FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1810 llvm_unreachable("should not be used");
1811}
1812
1814 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1815 "and -vgpr-regalloc";
1816
1817bool GCNPassConfig::addRegAssignAndRewriteFast() {
1818 if (!usingDefaultRegAlloc())
1820
1821 addPass(&GCNPreRALongBranchRegID);
1822
1823 addPass(createSGPRAllocPass(false));
1824
1825 // Equivalent of PEI for SGPRs.
1826 addPass(&SILowerSGPRSpillsLegacyID);
1827
1828 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1830
1831 // For allocating other wwm register operands.
1832 addPass(createWWMRegAllocPass(false));
1833
1834 addPass(&SILowerWWMCopiesLegacyID);
1836
1837 // For allocating per-thread VGPRs.
1838 addPass(createVGPRAllocPass(false));
1839
1840 return true;
1841}
1842
1843bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1844 if (!usingDefaultRegAlloc())
1846
1847 addPass(&GCNPreRALongBranchRegID);
1848
1849 addPass(createSGPRAllocPass(true));
1850
1851 // Commit allocated register changes. This is mostly necessary because too
1852 // many things rely on the use lists of the physical registers, such as the
1853 // verifier. This is only necessary with allocators which use LiveIntervals,
1854 // since FastRegAlloc does the replacements itself.
1855 addPass(createVirtRegRewriter(false));
1856
1857 // At this point, the sgpr-regalloc has been done and it is good to have the
1858 // stack slot coloring to try to optimize the SGPR spill stack indices before
1859 // attempting the custom SGPR spill lowering.
1860 addPass(&StackSlotColoringID);
1861
1862 // Equivalent of PEI for SGPRs.
1863 addPass(&SILowerSGPRSpillsLegacyID);
1864
1865 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1867
1868 // For allocating other whole wave mode registers.
1869 addPass(createWWMRegAllocPass(true));
1870 addPass(&SILowerWWMCopiesLegacyID);
1871 addPass(createVirtRegRewriter(false));
1873
1874 // For allocating per-thread VGPRs.
1875 addPass(createVGPRAllocPass(true));
1876
1877 addPreRewrite();
1878 addPass(&VirtRegRewriterID);
1879
1881
1882 return true;
1883}
1884
1885void GCNPassConfig::addPostRegAlloc() {
1886 addPass(&SIFixVGPRCopiesID);
1887 if (getOptLevel() > CodeGenOptLevel::None)
1890}
1891
1892void GCNPassConfig::addPreSched2() {
1893 if (TM->getOptLevel() > CodeGenOptLevel::None)
1895 addPass(&SIPostRABundlerLegacyID);
1896}
1897
1898void GCNPassConfig::addPreEmitPass() {
1899 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1900 addPass(&GCNCreateVOPDID);
1901 addPass(createSIMemoryLegalizerPass());
1902 addPass(createSIInsertWaitcntsPass());
1903
1904 addPass(createSIModeRegisterPass());
1905
1906 if (getOptLevel() > CodeGenOptLevel::None)
1907 addPass(&SIInsertHardClausesID);
1908
1910 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
1912 if (getOptLevel() > CodeGenOptLevel::None)
1913 addPass(&SIPreEmitPeepholeID);
1914 // The hazard recognizer that runs as part of the post-ra scheduler does not
1915 // guarantee to be able handle all hazards correctly. This is because if there
1916 // are multiple scheduling regions in a basic block, the regions are scheduled
1917 // bottom up, so when we begin to schedule a region we don't know what
1918 // instructions were emitted directly before it.
1919 //
1920 // Here we add a stand-alone hazard recognizer pass which can handle all
1921 // cases.
1922 addPass(&PostRAHazardRecognizerID);
1923
1925
1927
1928 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less))
1929 addPass(&AMDGPUInsertDelayAluID);
1930
1931 addPass(&BranchRelaxationPassID);
1932}
1933
1934void GCNPassConfig::addPostBBSections() {
1935 // We run this later to avoid passes like livedebugvalues and BBSections
1936 // having to deal with the apparent multi-entry functions we may generate.
1938}
1939
1941 return new GCNPassConfig(*this, PM);
1942}
1943
1949
1956
1960
1967
1970 SMDiagnostic &Error, SMRange &SourceRange) const {
1971 const yaml::SIMachineFunctionInfo &YamlMFI =
1972 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1973 MachineFunction &MF = PFS.MF;
1975 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1976
1977 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1978 return true;
1979
1980 if (MFI->Occupancy == 0) {
1981 // Fixup the subtarget dependent default value.
1982 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1983 }
1984
1985 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1986 Register TempReg;
1987 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1988 SourceRange = RegName.SourceRange;
1989 return true;
1990 }
1991 RegVal = TempReg;
1992
1993 return false;
1994 };
1995
1996 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1997 Register &RegVal) {
1998 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1999 };
2000
2001 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
2002 return true;
2003
2004 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
2005 return true;
2006
2007 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
2008 MFI->LongBranchReservedReg))
2009 return true;
2010
2011 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
2012 // Create a diagnostic for a the register string literal.
2013 const MemoryBuffer &Buffer =
2014 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2015 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
2016 RegName.Value.size(), SourceMgr::DK_Error,
2017 "incorrect register class for field", RegName.Value,
2018 {}, {});
2019 SourceRange = RegName.SourceRange;
2020 return true;
2021 };
2022
2023 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
2024 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
2025 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
2026 return true;
2027
2028 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
2029 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
2030 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
2031 }
2032
2033 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
2034 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
2035 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
2036 }
2037
2038 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
2039 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
2040 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
2041 }
2042
2043 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
2044 Register ParsedReg;
2045 if (parseRegister(YamlReg, ParsedReg))
2046 return true;
2047
2048 MFI->reserveWWMRegister(ParsedReg);
2049 }
2050
2051 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
2052 MFI->setFlag(Info->VReg, Info->Flags);
2053 }
2054 for (const auto &[_, Info] : PFS.VRegInfos) {
2055 MFI->setFlag(Info->VReg, Info->Flags);
2056 }
2057
2058 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
2059 Register ParsedReg;
2060 if (parseRegister(YamlRegStr, ParsedReg))
2061 return true;
2062 MFI->SpillPhysVGPRs.push_back(ParsedReg);
2063 }
2064
2065 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
2066 const TargetRegisterClass &RC,
2067 ArgDescriptor &Arg, unsigned UserSGPRs,
2068 unsigned SystemSGPRs) {
2069 // Skip parsing if it's not present.
2070 if (!A)
2071 return false;
2072
2073 if (A->IsRegister) {
2074 Register Reg;
2075 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
2076 SourceRange = A->RegisterName.SourceRange;
2077 return true;
2078 }
2079 if (!RC.contains(Reg))
2080 return diagnoseRegisterClass(A->RegisterName);
2082 } else
2083 Arg = ArgDescriptor::createStack(A->StackOffset);
2084 // Check and apply the optional mask.
2085 if (A->Mask)
2086 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
2087
2088 MFI->NumUserSGPRs += UserSGPRs;
2089 MFI->NumSystemSGPRs += SystemSGPRs;
2090 return false;
2091 };
2092
2093 if (YamlMFI.ArgInfo &&
2094 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
2095 AMDGPU::SGPR_128RegClass,
2096 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
2097 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
2098 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
2099 2, 0) ||
2100 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
2101 MFI->ArgInfo.QueuePtr, 2, 0) ||
2102 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
2103 AMDGPU::SReg_64RegClass,
2104 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
2105 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
2106 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
2107 2, 0) ||
2108 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
2109 AMDGPU::SReg_64RegClass,
2110 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
2111 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
2112 AMDGPU::SGPR_32RegClass,
2113 MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
2114 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
2115 AMDGPU::SGPR_32RegClass,
2116 MFI->ArgInfo.LDSKernelId, 0, 1) ||
2117 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
2118 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
2119 0, 1) ||
2120 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
2121 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
2122 0, 1) ||
2123 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
2124 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
2125 0, 1) ||
2126 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
2127 AMDGPU::SGPR_32RegClass,
2128 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
2129 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
2130 AMDGPU::SGPR_32RegClass,
2131 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
2132 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
2133 AMDGPU::SReg_64RegClass,
2134 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
2135 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
2136 AMDGPU::SReg_64RegClass,
2137 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
2138 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
2139 AMDGPU::VGPR_32RegClass,
2140 MFI->ArgInfo.WorkItemIDX, 0, 0) ||
2141 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
2142 AMDGPU::VGPR_32RegClass,
2143 MFI->ArgInfo.WorkItemIDY, 0, 0) ||
2144 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
2145 AMDGPU::VGPR_32RegClass,
2146 MFI->ArgInfo.WorkItemIDZ, 0, 0)))
2147 return true;
2148
2149 // Parse FirstKernArgPreloadReg separately, since it's a Register,
2150 // not ArgDescriptor.
2151 if (YamlMFI.ArgInfo && YamlMFI.ArgInfo->FirstKernArgPreloadReg) {
2152 const yaml::SIArgument &A = *YamlMFI.ArgInfo->FirstKernArgPreloadReg;
2153
2154 if (!A.IsRegister) {
2155 // For stack arguments, we don't have RegisterName.SourceRange,
2156 // but we should have some location info from the YAML parser
2157 const MemoryBuffer &Buffer =
2158 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2159 // Create a minimal valid source range
2161 SMRange Range(Loc, Loc);
2162
2164 *PFS.SM, Loc, Buffer.getBufferIdentifier(), 1, 0, SourceMgr::DK_Error,
2165 "firstKernArgPreloadReg must be a register, not a stack location", "",
2166 {}, {});
2167
2168 SourceRange = Range;
2169 return true;
2170 }
2171
2172 Register Reg;
2173 if (parseNamedRegisterReference(PFS, Reg, A.RegisterName.Value, Error)) {
2174 SourceRange = A.RegisterName.SourceRange;
2175 return true;
2176 }
2177
2178 if (!AMDGPU::SGPR_32RegClass.contains(Reg))
2179 return diagnoseRegisterClass(A.RegisterName);
2180
2181 MFI->ArgInfo.FirstKernArgPreloadReg = Reg;
2182 MFI->NumUserSGPRs += YamlMFI.NumKernargPreloadSGPRs;
2183 }
2184
2185 if (ST.hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode)) {
2186 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
2187 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
2188 }
2189
2190 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
2191 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
2194 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
2197
2204
2205 if (YamlMFI.HasInitWholeWave)
2206 MFI->setInitWholeWave();
2207
2208 return false;
2209}
2210
2211//===----------------------------------------------------------------------===//
2212// AMDGPU CodeGen Pass Builder interface.
2213//===----------------------------------------------------------------------===//
2214
2215AMDGPUCodeGenPassBuilder::AMDGPUCodeGenPassBuilder(
2216 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
2218 : CodeGenPassBuilder(TM, Opts, PIC) {
2219 Opt.MISchedPostRA = true;
2220 Opt.RequiresCodeGenSCCOrder = true;
2221 // Exceptions and StackMaps are not supported, so these passes will never do
2222 // anything.
2223 // Garbage collection is not supported.
2224 disablePass<StackMapLivenessPass, FuncletLayoutPass, PatchableFunctionPass,
2226}
2227
2228void AMDGPUCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) const {
2229 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN()) {
2230 flushFPMsToMPM(PMW);
2231 addModulePass(AMDGPURemoveIncompatibleFunctionsPass(TM), PMW);
2232 }
2233
2234 flushFPMsToMPM(PMW);
2235
2236 if (TM.getTargetTriple().isAMDGCN())
2237 addModulePass(AMDGPUPrintfRuntimeBindingPass(), PMW);
2238
2239 if (LowerCtorDtor)
2240 addModulePass(AMDGPUCtorDtorLoweringPass(), PMW);
2241
2242 if (isPassEnabled(EnableImageIntrinsicOptimizer))
2243 addFunctionPass(AMDGPUImageIntrinsicOptimizerPass(TM), PMW);
2244
2246 addFunctionPass(AMDGPUUniformIntrinsicCombinePass(), PMW);
2247 // This can be disabled by passing ::Disable here or on the command line
2248 // with --expand-variadics-override=disable.
2249 flushFPMsToMPM(PMW);
2251
2252 addModulePass(AMDGPUAlwaysInlinePass(), PMW);
2253 addModulePass(AlwaysInlinerPass(), PMW);
2254
2255 addModulePass(AMDGPUExportKernelRuntimeHandlesPass(), PMW);
2256
2258 addModulePass(AMDGPULowerExecSyncPass(), PMW);
2259
2260 if (EnableSwLowerLDS)
2261 addModulePass(AMDGPUSwLowerLDSPass(TM), PMW);
2262
2263 // Runs before PromoteAlloca so the latter can account for function uses
2265 addModulePass(AMDGPULowerModuleLDSPass(TM), PMW);
2266
2267 // Run atomic optimizer before Atomic Expand
2268 if (TM.getOptLevel() >= CodeGenOptLevel::Less &&
2270 addFunctionPass(
2272
2273 addFunctionPass(AtomicExpandPass(TM), PMW);
2274
2275 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2276 addFunctionPass(AMDGPUPromoteAllocaPass(TM), PMW);
2277 if (isPassEnabled(EnableScalarIRPasses))
2278 addStraightLineScalarOptimizationPasses(PMW);
2279
2280 // TODO: Handle EnableAMDGPUAliasAnalysis
2281
2282 // TODO: May want to move later or split into an early and late one.
2283 addFunctionPass(AMDGPUCodeGenPreparePass(TM), PMW);
2284
2285 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
2286 // have expanded.
2287 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2289 /*UseMemorySSA=*/true),
2290 PMW);
2291 }
2292 }
2293
2294 Base::addIRPasses(PMW);
2295
2296 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2297 // example, GVN can combine
2298 //
2299 // %0 = add %a, %b
2300 // %1 = add %b, %a
2301 //
2302 // and
2303 //
2304 // %0 = shl nsw %a, 2
2305 // %1 = shl %a, 2
2306 //
2307 // but EarlyCSE can do neither of them.
2308 if (isPassEnabled(EnableScalarIRPasses))
2309 addEarlyCSEOrGVNPass(PMW);
2310}
2311
2312void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(
2313 PassManagerWrapper &PMW) const {
2314 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2315 flushFPMsToMPM(PMW);
2316 addModulePass(AMDGPUPreloadKernelArgumentsPass(TM), PMW);
2317 }
2318
2320 addFunctionPass(AMDGPULowerKernelArgumentsPass(TM), PMW);
2321
2322 Base::addCodeGenPrepare(PMW);
2323
2324 if (isPassEnabled(EnableLoadStoreVectorizer))
2325 addFunctionPass(LoadStoreVectorizerPass(), PMW);
2326
2327 // This lowering has been placed after codegenprepare to take advantage of
2328 // address mode matching (which is why it isn't put with the LDS lowerings).
2329 // It could be placed anywhere before uniformity annotations (an analysis
2330 // that it changes by splitting up fat pointers into their components)
2331 // but has been put before switch lowering and CFG flattening so that those
2332 // passes can run on the more optimized control flow this pass creates in
2333 // many cases.
2334 flushFPMsToMPM(PMW);
2335 addModulePass(AMDGPULowerBufferFatPointersPass(TM), PMW);
2336 flushFPMsToMPM(PMW);
2337 requireCGSCCOrder(PMW);
2338
2339 addModulePass(AMDGPULowerIntrinsicsPass(TM), PMW);
2340
2341 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2342 // behavior for subsequent passes. Placing it here seems better that these
2343 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2344 // pass flow.
2345 addFunctionPass(LowerSwitchPass(), PMW);
2346}
2347
2348void AMDGPUCodeGenPassBuilder::addPreISel(PassManagerWrapper &PMW) const {
2349
2350 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2351 addFunctionPass(FlattenCFGPass(), PMW);
2352 addFunctionPass(SinkingPass(), PMW);
2353 addFunctionPass(AMDGPULateCodeGenPreparePass(TM), PMW);
2354 }
2355
2356 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2357 // regions formed by them.
2358
2359 addFunctionPass(AMDGPUUnifyDivergentExitNodesPass(), PMW);
2360 addFunctionPass(FixIrreduciblePass(), PMW);
2361 addFunctionPass(UnifyLoopExitsPass(), PMW);
2362 addFunctionPass(StructurizeCFGPass(/*SkipUniformRegions=*/false), PMW);
2363
2364 addFunctionPass(AMDGPUAnnotateUniformValuesPass(), PMW);
2365
2366 addFunctionPass(SIAnnotateControlFlowPass(TM), PMW);
2367
2368 // TODO: Move this right after structurizeCFG to avoid extra divergence
2369 // analysis. This depends on stopping SIAnnotateControlFlow from making
2370 // control flow modifications.
2371 addFunctionPass(AMDGPURewriteUndefForPHIPass(), PMW);
2372
2374 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
2375 addFunctionPass(LCSSAPass(), PMW);
2376
2377 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2378 flushFPMsToMPM(PMW);
2379 addModulePass(AMDGPUPerfHintAnalysisPass(TM), PMW);
2380 }
2381
2382 // FIXME: Why isn't this queried as required from AMDGPUISelDAGToDAG, and why
2383 // isn't this in addInstSelector?
2385 /*Force=*/true);
2386}
2387
2388void AMDGPUCodeGenPassBuilder::addILPOpts(PassManagerWrapper &PMW) const {
2390 addMachineFunctionPass(EarlyIfConverterPass(), PMW);
2391
2392 Base::addILPOpts(PMW);
2393}
2394
2395void AMDGPUCodeGenPassBuilder::addAsmPrinterBegin(
2396 PassManagerWrapper &PMW) const {
2397 // TODO: Add AsmPrinterBegin
2398}
2399
2400void AMDGPUCodeGenPassBuilder::addAsmPrinter(PassManagerWrapper &PMW) const {
2401 // TODO: Add AsmPrinter.
2402}
2403
2404void AMDGPUCodeGenPassBuilder::addAsmPrinterEnd(PassManagerWrapper &PMW) const {
2405 // TODO: Add AsmPrinterEnd
2406}
2407
2408Error AMDGPUCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) const {
2409 addMachineFunctionPass(AMDGPUISelDAGToDAGPass(TM), PMW);
2410 addMachineFunctionPass(SIFixSGPRCopiesPass(), PMW);
2411 addMachineFunctionPass(SILowerI1CopiesPass(), PMW);
2412 return Error::success();
2413}
2414
2415void AMDGPUCodeGenPassBuilder::addPreRewrite(PassManagerWrapper &PMW) const {
2416 if (EnableRegReassign) {
2417 addMachineFunctionPass(GCNNSAReassignPass(), PMW);
2418 }
2419
2420 addMachineFunctionPass(AMDGPURewriteAGPRCopyMFMAPass(), PMW);
2421}
2422
2423void AMDGPUCodeGenPassBuilder::addMachineSSAOptimization(
2424 PassManagerWrapper &PMW) const {
2425 Base::addMachineSSAOptimization(PMW);
2426
2427 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2428 if (EnableDPPCombine) {
2429 addMachineFunctionPass(GCNDPPCombinePass(), PMW);
2430 }
2431 addMachineFunctionPass(SILoadStoreOptimizerPass(), PMW);
2432 if (isPassEnabled(EnableSDWAPeephole)) {
2433 addMachineFunctionPass(SIPeepholeSDWAPass(), PMW);
2434 addMachineFunctionPass(EarlyMachineLICMPass(), PMW);
2435 addMachineFunctionPass(MachineCSEPass(), PMW);
2436 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2437 }
2438 addMachineFunctionPass(DeadMachineInstructionElimPass(), PMW);
2439 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2440}
2441
2442Error AMDGPUCodeGenPassBuilder::addFastRegAlloc(PassManagerWrapper &PMW) const {
2443 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2444
2445 insertPass<TwoAddressInstructionPass>(SIWholeQuadModePass());
2446
2447 return Base::addFastRegAlloc(PMW);
2448}
2449
2450Error AMDGPUCodeGenPassBuilder::addRegAssignmentFast(
2451 PassManagerWrapper &PMW) const {
2452 if (auto Err = validateRegAllocOptions())
2453 return Err;
2454
2455 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2456
2457 // SGPR allocation - default to fast at -O0.
2458 if (SGPRRegAllocNPM == RegAllocType::Greedy)
2459 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2460 else
2461 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2462 PMW);
2463
2464 // Equivalent of PEI for SGPRs.
2465 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2466
2467 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2468 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2469
2470 // WWM allocation - default to fast at -O0.
2471 if (WWMRegAllocNPM == RegAllocType::Greedy)
2472 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2473 else
2474 addMachineFunctionPass(
2475 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2476
2477 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2478 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2479
2480 // VGPR allocation - default to fast at -O0.
2481 if (VGPRRegAllocNPM == RegAllocType::Greedy)
2482 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2483 else
2484 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2485
2486 return Error::success();
2487}
2488
2489Error AMDGPUCodeGenPassBuilder::addOptimizedRegAlloc(
2490 PassManagerWrapper &PMW) const {
2491 if (EnableDCEInRA)
2492 insertPass<DetectDeadLanesPass>(DeadMachineInstructionElimPass());
2493
2494 // FIXME: when an instruction has a Killed operand, and the instruction is
2495 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
2496 // the register in LiveVariables, this would trigger a failure in verifier,
2497 // we should fix it and enable the verifier.
2498 if (OptVGPRLiveRange)
2499 insertPass<RequireAnalysisPass<LiveVariablesAnalysis, MachineFunction>>(
2501
2502 // This must be run immediately after phi elimination and before
2503 // TwoAddressInstructions, otherwise the processing of the tied operand of
2504 // SI_ELSE will introduce a copy of the tied operand source after the else.
2505 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2506
2508 insertPass<RenameIndependentSubregsPass>(GCNRewritePartialRegUsesPass());
2509
2510 if (isPassEnabled(EnablePreRAOptimizations))
2511 insertPass<MachineSchedulerPass>(GCNPreRAOptimizationsPass());
2512
2513 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
2514 // instructions that cause scheduling barriers.
2515 insertPass<MachineSchedulerPass>(SIWholeQuadModePass());
2516
2517 if (OptExecMaskPreRA)
2518 insertPass<MachineSchedulerPass>(SIOptimizeExecMaskingPreRAPass());
2519
2520 // This is not an essential optimization and it has a noticeable impact on
2521 // compilation time, so we only enable it from O2.
2522 if (TM.getOptLevel() > CodeGenOptLevel::Less)
2523 insertPass<MachineSchedulerPass>(SIFormMemoryClausesPass());
2524
2525 return Base::addOptimizedRegAlloc(PMW);
2526}
2527
2528void AMDGPUCodeGenPassBuilder::addPreRegAlloc(PassManagerWrapper &PMW) const {
2529 if (getOptLevel() != CodeGenOptLevel::None)
2530 addMachineFunctionPass(AMDGPUPrepareAGPRAllocPass(), PMW);
2531}
2532
2533Error AMDGPUCodeGenPassBuilder::addRegAssignmentOptimized(
2534 PassManagerWrapper &PMW) const {
2535 if (auto Err = validateRegAllocOptions())
2536 return Err;
2537
2538 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2539
2540 // SGPR allocation - default to greedy at -O1 and above.
2541 if (SGPRRegAllocNPM == RegAllocType::Fast)
2542 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2543 PMW);
2544 else
2545 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2546
2547 // Commit allocated register changes. This is mostly necessary because too
2548 // many things rely on the use lists of the physical registers, such as the
2549 // verifier. This is only necessary with allocators which use LiveIntervals,
2550 // since FastRegAlloc does the replacements itself.
2551 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2552
2553 // At this point, the sgpr-regalloc has been done and it is good to have the
2554 // stack slot coloring to try to optimize the SGPR spill stack indices before
2555 // attempting the custom SGPR spill lowering.
2556 addMachineFunctionPass(StackSlotColoringPass(), PMW);
2557
2558 // Equivalent of PEI for SGPRs.
2559 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2560
2561 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2562 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2563
2564 // WWM allocation - default to greedy at -O1 and above.
2565 if (WWMRegAllocNPM == RegAllocType::Fast)
2566 addMachineFunctionPass(
2567 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2568 else
2569 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2570 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2571 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2572 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2573
2574 // VGPR allocation - default to greedy at -O1 and above.
2575 if (VGPRRegAllocNPM == RegAllocType::Fast)
2576 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2577 else
2578 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2579
2580 addPreRewrite(PMW);
2581 addMachineFunctionPass(VirtRegRewriterPass(true), PMW);
2582
2583 addMachineFunctionPass(AMDGPUMarkLastScratchLoadPass(), PMW);
2584 return Error::success();
2585}
2586
2587void AMDGPUCodeGenPassBuilder::addPostRegAlloc(PassManagerWrapper &PMW) const {
2588 addMachineFunctionPass(SIFixVGPRCopiesPass(), PMW);
2589 if (TM.getOptLevel() > CodeGenOptLevel::None)
2590 addMachineFunctionPass(SIOptimizeExecMaskingPass(), PMW);
2591 Base::addPostRegAlloc(PMW);
2592}
2593
2594void AMDGPUCodeGenPassBuilder::addPreSched2(PassManagerWrapper &PMW) const {
2595 if (TM.getOptLevel() > CodeGenOptLevel::None)
2596 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2597 addMachineFunctionPass(SIPostRABundlerPass(), PMW);
2598}
2599
2600void AMDGPUCodeGenPassBuilder::addPostBBSections(
2601 PassManagerWrapper &PMW) const {
2602 // We run this later to avoid passes like livedebugvalues and BBSections
2603 // having to deal with the apparent multi-entry functions we may generate.
2604 addMachineFunctionPass(AMDGPUPreloadKernArgPrologPass(), PMW);
2605}
2606
2607void AMDGPUCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) const {
2608 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less)) {
2609 addMachineFunctionPass(GCNCreateVOPDPass(), PMW);
2610 }
2611
2612 addMachineFunctionPass(SIMemoryLegalizerPass(), PMW);
2613 addMachineFunctionPass(SIInsertWaitcntsPass(), PMW);
2614
2615 addMachineFunctionPass(SIModeRegisterPass(), PMW);
2616
2617 if (TM.getOptLevel() > CodeGenOptLevel::None)
2618 addMachineFunctionPass(SIInsertHardClausesPass(), PMW);
2619
2620 addMachineFunctionPass(SILateBranchLoweringPass(), PMW);
2621
2622 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
2623 addMachineFunctionPass(AMDGPUSetWavePriorityPass(), PMW);
2624
2625 if (TM.getOptLevel() > CodeGenOptLevel::None)
2626 addMachineFunctionPass(SIPreEmitPeepholePass(), PMW);
2627
2628 // The hazard recognizer that runs as part of the post-ra scheduler does not
2629 // guarantee to be able handle all hazards correctly. This is because if there
2630 // are multiple scheduling regions in a basic block, the regions are scheduled
2631 // bottom up, so when we begin to schedule a region we don't know what
2632 // instructions were emitted directly before it.
2633 //
2634 // Here we add a stand-alone hazard recognizer pass which can handle all
2635 // cases.
2636 addMachineFunctionPass(PostRAHazardRecognizerPass(), PMW);
2637 addMachineFunctionPass(AMDGPUWaitSGPRHazardsPass(), PMW);
2638 addMachineFunctionPass(AMDGPULowerVGPREncodingPass(), PMW);
2639
2640 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less)) {
2641 addMachineFunctionPass(AMDGPUInsertDelayAluPass(), PMW);
2642 }
2643
2644 addMachineFunctionPass(BranchRelaxationPass(), PMW);
2645}
2646
2647bool AMDGPUCodeGenPassBuilder::isPassEnabled(const cl::opt<bool> &Opt,
2648 CodeGenOptLevel Level) const {
2649 if (Opt.getNumOccurrences())
2650 return Opt;
2651 if (TM.getOptLevel() < Level)
2652 return false;
2653 return Opt;
2654}
2655
2656void AMDGPUCodeGenPassBuilder::addEarlyCSEOrGVNPass(
2657 PassManagerWrapper &PMW) const {
2658 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive)
2659 addFunctionPass(GVNPass(), PMW);
2660 else
2661 addFunctionPass(EarlyCSEPass(), PMW);
2662}
2663
2664void AMDGPUCodeGenPassBuilder::addStraightLineScalarOptimizationPasses(
2665 PassManagerWrapper &PMW) const {
2667 addFunctionPass(LoopDataPrefetchPass(), PMW);
2668
2669 addFunctionPass(SeparateConstOffsetFromGEPPass(), PMW);
2670
2671 // ReassociateGEPs exposes more opportunities for SLSR. See
2672 // the example in reassociate-geps-and-slsr.ll.
2673 addFunctionPass(StraightLineStrengthReducePass(), PMW);
2674
2675 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2676 // EarlyCSE can reuse.
2677 addEarlyCSEOrGVNPass(PMW);
2678
2679 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2680 addFunctionPass(NaryReassociatePass(), PMW);
2681
2682 // NaryReassociate on GEPs creates redundant common expressions, so run
2683 // EarlyCSE after it.
2684 addFunctionPass(EarlyCSEPass(), PMW);
2685}
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< bool > EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden, cl::desc("Run early if-conversion"), cl::init(true))
static std::unique_ptr< TargetLoweringObjectFile > createTLOF(const Triple &TT)
This is the AMGPU address space based alias analysis pass.
Coexecution-focused scheduling strategy for AMDGPU.
Defines an instruction selector for the AMDGPU target.
Analyzes if a function potentially memory bound and if a kernel kernel may benefit from limiting numb...
Analyzes how many registers and other resources are used by functions.
static cl::opt< 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 Reloc::Model getEffectiveRelocModel()
static cl::opt< bool > EnableUniformIntrinsicCombine("amdgpu-enable-uniform-intrinsic-combine", cl::desc("Enable/Disable the Uniform Intrinsic Combine Pass"), cl::init(true), cl::Hidden)
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 cl::opt< bool, true > EnableObjectLinking("amdgpu-enable-object-linking", cl::desc("Enable object linking for cross-TU LDS and ABI support"), cl::location(AMDGPUTargetMachine::EnableObjectLinking), cl::init(false), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxILPMachineScheduler(MachineSchedContext *C)
static 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 void diagnoseUnsupportedCoExecSchedulerSelection(const Function &F, const GCNSubtarget &ST)
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 bool useNoopPostScheduler(const Function &F)
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))
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget()
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)
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))
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 ScheduleDAGInstrs * createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableLowerExecSync("amdgpu-enable-lower-exec-sync", cl::desc("Enable lowering of execution synchronization."), cl::init(true), cl::Hidden)
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 TargetTransformInfoImplBase conforming object specific to the AMDGPU target machine.
Provides passes to inlining "always_inline" functions.
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This header provides classes for managing passes over SCCs of the call graph.
Provides analysis for continuously CSEing during GISel passes.
Interfaces for producing common pass manager configurations.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_READNONE
Definition Compiler.h:315
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
DXIL Legalizer
This file provides the interface for a simple, fast CSE pass.
This file defines the class GCNIterativeScheduler, which uses an iterative approach to find a best sc...
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
#define _
AcceleratorCodeSelection - Identify all functions reachable from a kernel, removing those that are un...
This file declares the IRTranslator pass.
This header defines various interfaces for pass management in LLVM.
#define RegName(no)
This file provides the interface for LLVM's Loop Data Prefetching Pass.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
CGSCCAnalysisManager CGAM
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
The AMDGPU TargetMachine interface definition for hw codegen targets.
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
SI Machine Scheduler interface.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:483
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static FunctionPass * useDefaultRegisterAllocator()
-regalloc=... command line option.
static cl::opt< cl::boolOrDefault > EnableGlobalISelOption("global-isel", cl::Hidden, cl::desc("Enable the \"global\" instruction selector"))
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.
Lower llvm.global_ctors and llvm.global_dtors to special kernels.
AMDGPUTargetMachine & getAMDGPUTargetMachine() const
std::unique_ptr< CSEConfigBase > getCSEConfig() const override
Returns the CSEConfig object to use for the current optimization level.
bool isPassEnabled(const cl::opt< bool > &Opt, CodeGenOptLevel Level=CodeGenOptLevel::Default) const
Check if a pass is enabled given Opt option.
bool addPreISel() override
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
bool addInstSelector() override
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
bool addGCPasses() override
addGCPasses - Add late codegen passes that analyze code for garbage collection.
AMDGPUPassConfig(TargetMachine &TM, PassManagerBase &PM)
void addIRPasses() override
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
void addCodeGenPrepare() override
Add pass to prepare the LLVM IR for code generation.
Splits the module M into N linkable partitions.
std::unique_ptr< TargetLoweringObjectFile > TLOF
unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const override
getAddressSpaceForPseudoSourceKind - Given the kind of memory (e.g.
const TargetSubtargetInfo * getSubtargetImpl() const
void registerDefaultAliasAnalyses(AAManager &) override
Allow the target to register alias analyses with the AAManager for use with the new pass manager.
std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const override
If the specified predicate checks whether a generic pointer falls within a specified address space,...
StringRef getFeatureString(const Function &F) const
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
AMDGPUTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL)
bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
StringRef getGPUName(const Function &F) const
unsigned getAssumedAddrSpace(const Value *V) const override
If the specified generic pointer could be assumed as a pointer to a specific address space,...
bool splitModule(Module &M, unsigned NumParts, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback) override
Entry point for module splitting.
Inlines functions marked as "always_inline".
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
This class provides access to building LLVM's passes.
CodeGenTargetMachineImpl(const Target &T, StringRef DataLayoutString, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Diagnostic information for unsupported feature in backend.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LowerIntrinsics - This pass rewrites calls to the llvm.gcread or llvm.gcwrite intrinsics,...
Definition GCMetadata.h:229
const SIRegisterInfo * getRegisterInfo() const override
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
ScheduleDAGInstrs * createPostMachineScheduler(MachineSchedContext *C) const override
Similar to createMachineScheduler but used when postRA machine scheduling is enabled.
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
void registerMachineRegisterInfoCallback(MachineFunction &MF) const override
bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange) const override
Parse out the target's MachineFunctionInfo from the YAML reprsentation.
yaml::MachineFunctionInfo * convertFuncInfoToYAML(const MachineFunction &MF) const override
Allocate and initialize an instance of the YAML representation of the MachineFunctionInfo.
yaml::MachineFunctionInfo * createDefaultFuncInfoYAML() const override
Allocate and return a default initialized instance of the YAML representation for the MachineFunction...
Error buildCodeGenPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, const CGPassBuilderOption &Opts, MCContext &Ctx, PassInstrumentationCallbacks *PIC) override
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
GCNTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
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:128
Pass to remove unused function declarations.
Definition GlobalDCE.h:38
This pass is responsible for selecting generic machine instructions to target-specific instructions.
A pass that internalizes all functions and variables other than those that must be preserved accordin...
Definition Internalize.h:37
Converts loops into loop-closed SSA form.
Definition LCSSA.h:38
Performs Loop Invariant Code Motion Pass.
Definition LICM.h:66
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.
Context object for machine code objects.
Definition MCContext.h:83
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,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
void addDelegate(Delegate *delegate)
const MachineFunction & getMF() const
MachineSchedRegistry provides a selection of available machine instruction schedulers.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
const char * getBufferStart() const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static LLVM_ABI const OptimizationLevel O0
Disable as many optimizations as possible.
static LLVM_ABI const OptimizationLevel O1
Optimize quickly without destroying debuggability.
This class provides access to building LLVM's passes.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
RegisterPassParser class - Handle the addition of new machine passes.
RegisterRegAllocBase class - Track the registration of register allocators.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
bool initializeBaseYamlFields(const yaml::SIMachineFunctionInfo &YamlMFI, const MachineFunction &MF, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange)
void setFlag(Register Reg, uint8_t Flag)
bool checkFlag(Register Reg, uint8_t Flag) const
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:297
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
Represents a range in source code.
Definition SMLoc.h:47
A ScheduleDAG for scheduling lists of MachineInstr.
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.
const TargetInstrInfo * TII
Target instruction information.
const TargetRegisterInfo * TRI
Target processor register info.
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:148
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:655
A switch()-like statement whose cases are string literals.
StringSwitch & Cases(std::initializer_list< StringLiteral > CaseStrings, T Value)
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with.
const Triple & getTargetTriple() const
const MCSubtargetInfo * getMCSubtargetInfo() const
StringRef getTargetFeatureString() const
StringRef getTargetCPU() const
std::unique_ptr< const MCSubtargetInfo > STI
TargetOptions Options
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
std::unique_ptr< const MCRegisterInfo > MRI
CodeGenOptLevel OptLevel
Target-Independent Code Generator Pass Configuration Options.
virtual void addCodeGenPrepare()
Add pass to prepare the LLVM IR for code generation.
virtual bool addILPOpts()
Add passes that optimize instruction level parallelism for out-of-order targets.
virtual void addPostRegAlloc()
This method may be implemented by targets that want to run passes after register allocation pass pipe...
CodeGenOptLevel getOptLevel() const
virtual void addOptimizedRegAlloc()
addOptimizedRegAlloc - Add passes related to register allocation.
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void addFastRegAlloc()
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
virtual void addMachineSSAOptimization()
addMachineSSAOptimization - Add standard passes that optimize machine instructions in SSA form.
void disablePass(AnalysisID PassID)
Allow the target to disable a specific standard pass by default.
AnalysisID addPass(AnalysisID PassID)
Utilities for targets to add passes to the pass manager.
TargetPassConfig(TargetMachine &TM, PassManagerBase &PM)
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:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
bool use_empty() const
Definition Value.h:346
int getNumOccurrences() const
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.
Interfaces for registering analysis passes, producing common pass manager configurations,...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
StringRef getSchedStrategy(const Function &F)
bool isFlatGlobalAddrSpace(unsigned AS)
LLVM_READNONE constexpr bool isModuleEntryFunctionCC(CallingConv::ID CC)
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Value()
Match an arbitrary value and ignore it.
template class LLVM_TEMPLATE_ABI opt< bool >
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
This is an optimization pass for GlobalISel generic memory operations.
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
LLVM_ABI FunctionPass * createFlattenCFGPass()
std::unique_ptr< ScheduleDAGMutation > createAMDGPUBarrierLatencyDAGMutation(MachineFunction *MF)
LLVM_ABI FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
LLVM_ABI char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
ImmutablePass * createAMDGPUAAWrapperPass()
LLVM_ABI char & PostRAHazardRecognizerID
PostRAHazardRecognizer - This pass runs the post-ra hazard recognizer.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
FunctionPass * createAMDGPUSetWavePriorityPass()
LLVM_ABI Pass * createLCSSAPass()
Definition LCSSA.cpp:525
void initializeAMDGPUMarkLastScratchLoadLegacyPass(PassRegistry &)
void initializeAMDGPUInsertDelayAluLegacyPass(PassRegistry &)
void initializeSIOptimizeExecMaskingPreRALegacyPass(PassRegistry &)
char & GCNPreRAOptimizationsID
LLVM_ABI char & GCLoweringID
GCLowering Pass - Used by gc.root to perform its default lowering operations.
void initializeSIInsertHardClausesLegacyPass(PassRegistry &)
ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
FunctionPass * createSIAnnotateControlFlowLegacyPass()
Create the annotation pass.
FunctionPass * createSIModeRegisterPass()
void initializeGCNPreRAOptimizationsLegacyPass(PassRegistry &)
void initializeSILowerWWMCopiesLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGreedyRegisterAllocator()
Greedy register allocation pass - This pass implements a global register allocator for optimized buil...
void initializeAMDGPUAAWrapperPassPass(PassRegistry &)
void initializeSIShrinkInstructionsLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerBufferFatPointersPass()
void initializeR600ClauseMergePassPass(PassRegistry &)
ModulePass * createAMDGPUCtorDtorLoweringLegacyPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
ModulePass * createAMDGPUSwLowerLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
void initializeGCNRewritePartialRegUsesLegacyPass(llvm::PassRegistry &)
void initializeAMDGPURewriteUndefForPHILegacyPass(PassRegistry &)
char & GCNRewritePartialRegUsesID
void initializeAMDGPUSwLowerLDSLegacyPass(PassRegistry &)
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
void initializeAMDGPULowerVGPREncodingLegacyPass(PassRegistry &)
char & AMDGPUWaitSGPRHazardsLegacyID
void initializeSILowerSGPRSpillsLegacyPass(PassRegistry &)
LLVM_ABI Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
void initializeAMDGPUDAGToDAGISelLegacyPass(PassRegistry &)
FunctionPass * createAMDGPURegBankCombiner(bool IsOptNone)
LLVM_ABI FunctionPass * createNaryReassociatePass()
char & AMDGPUReserveWWMRegsLegacyID
void initializeAMDGPUWaitSGPRHazardsLegacyPass(PassRegistry &)
LLVM_ABI char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
char & SIOptimizeExecMaskingLegacyID
LLVM_ABI char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
void initializeAMDGPUNextUseAnalysisLegacyPassPass(PassRegistry &)
void initializeR600ExpandSpecialInstrsPassPass(PassRegistry &)
void initializeR600PacketizerPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createVOPDPairingMutation()
ModulePass * createAMDGPUExportKernelRuntimeHandlesLegacyPass()
ModulePass * createAMDGPUAlwaysInlinePass(bool GlobalOpt=true)
void initializeAMDGPUAsmPrinterPass(PassRegistry &)
void initializeSIFoldOperandsLegacyPass(PassRegistry &)
char & SILoadStoreOptimizerLegacyID
void initializeAMDGPUGlobalISelDivergenceLoweringPass(PassRegistry &)
PassManager< LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, CGSCCUpdateResult & > CGSCCPassManager
The CGSCC pass manager.
LLVM_ABI std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition CSEInfo.cpp:85
Target & getTheR600Target()
The target for R600 GPUs.
LLVM_ABI char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
LLVM_ABI Pass * createStructurizeCFGPass(bool SkipUniformRegions=false)
When SkipUniformRegions is true the structizer will not structurize regions that only contain uniform...
LLVM_ABI char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
LLVM_ABI Pass * createLICMPass()
Definition LICM.cpp:386
char & SIFormMemoryClausesID
void initializeSILoadStoreOptimizerLegacyPass(PassRegistry &)
void initializeAMDGPULowerModuleLDSLegacyPass(PassRegistry &)
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
void initializeAMDGPUCtorDtorLoweringLegacyPass(PassRegistry &)
LLVM_ABI char & EarlyIfConverterLegacyID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
FunctionPass * createAMDGPUUniformIntrinsicCombineLegacyPass()
void initializeAMDGPURegBankCombinerPass(PassRegistry &)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:77
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:87
char & AMDGPUUnifyDivergentExitNodesID
void initializeAMDGPUPrepareAGPRAllocLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUAtomicOptimizerPass(ScanOptions ScanStrategy)
FunctionPass * createAMDGPUPreloadKernArgPrologLegacyPass()
char & SIOptimizeVGPRLiveRangeLegacyID
LLVM_ABI char & ShadowStackGCLoweringID
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
char & GCNNSAReassignID
void initializeAMDGPURewriteOutArgumentsPass(PassRegistry &)
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
void initializeAMDGPUExternalAAWrapperPass(PassRegistry &)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void initializeAMDGPULowerKernelArgumentsPass(PassRegistry &)
void initializeSIModeRegisterLegacyPass(PassRegistry &)
CodeModel::Model getEffectiveCodeModel(std::optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
void initializeAMDGPUPreloadKernelArgumentsLegacyPass(PassRegistry &)
char & SILateBranchLoweringPassID
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
LLVM_ABI char & BranchRelaxationPassID
BranchRelaxation - This pass replaces branches that need to jump further than is supported by a branc...
LLVM_ABI FunctionPass * createSinkingPass()
Definition Sink.cpp:275
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
void initializeSIMemoryLegalizerLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerIntrinsicsLegacyPass()
void initializeR600MachineCFGStructurizerPass(PassRegistry &)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:111
char & GCNDPPCombineLegacyID
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI 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...
LLVM_ABI FunctionPass * createLoopDataPrefetchPass()
FunctionPass * createAMDGPULowerKernelArgumentsPass()
char & AMDGPUInsertDelayAluID
std::unique_ptr< ScheduleDAGMutation > createAMDGPUMacroFusionDAGMutation()
Note that you have to add: DAG.addMutation(createAMDGPUMacroFusionDAGMutation()); to AMDGPUTargetMach...
LLVM_ABI char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
void initializeGCNPreRALongBranchRegLegacyPass(PassRegistry &)
char & SILowerWWMCopiesLegacyID
LLVM_ABI FunctionPass * createUnifyLoopExitsPass()
char & SIOptimizeExecMaskingPreRAID
LLVM_ABI FunctionPass * createFixIrreduciblePass()
void initializeR600EmitClauseMarkersPass(PassRegistry &)
LLVM_ABI char & FuncletLayoutID
This pass lays out funclets contiguously.
LLVM_ABI char & DetectDeadLanesID
This pass adds dead/undef flags after analyzing subregister lanes.
void initializeAMDGPULowerExecSyncLegacyPass(PassRegistry &)
void initializeAMDGPUPostLegalizerCombinerPass(PassRegistry &)
ScheduleDAGInstrs * createGCNNoopPostMachineScheduler(MachineSchedContext *C)
void initializeAMDGPUExportKernelRuntimeHandlesLegacyPass(PassRegistry &)
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
void initializeSIInsertWaitcntsLegacyPass(PassRegistry &)
ModulePass * createAMDGPUPreloadKernelArgumentsLegacyPass(const TargetMachine *)
ModulePass * createAMDGPUPrintfRuntimeBinding()
LLVM_ABI char & StackSlotColoringID
StackSlotColoring - This pass performs stack slot coloring.
LLVM_ABI Pass * createAlwaysInlinerLegacyPass(bool InsertLifetime=true)
Create a legacy pass manager instance of a pass to inline and remove functions marked as "always_inli...
void initializeR600ControlFlowFinalizerPass(PassRegistry &)
void initializeAMDGPUImageIntrinsicOptimizerPass(PassRegistry &)
void initializeSILateBranchLoweringLegacyPass(PassRegistry &)
void initializeSILowerControlFlowLegacyPass(PassRegistry &)
void initializeSIFormMemoryClausesLegacyPass(PassRegistry &)
char & SIPreAllocateWWMRegsLegacyID
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
ModulePass * createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
void initializeAMDGPUPreLegalizerCombinerPass(PassRegistry &)
FunctionPass * createAMDGPUPromoteAlloca()
LLVM_ABI FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
void initializeAMDGPUReserveWWMRegsLegacyPass(PassRegistry &)
char & SIPreEmitPeepholeID
char & SIPostRABundlerLegacyID
ModulePass * createAMDGPURemoveIncompatibleFunctionsPass(const TargetMachine *)
void initializeGCNRegPressurePrinterPass(PassRegistry &)
void initializeSILowerI1CopiesLegacyPass(PassRegistry &)
char & SILowerSGPRSpillsLegacyID
LLVM_ABI FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
LLVM_ABI void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
char & SILowerControlFlowLegacyID
ModulePass * createR600OpenCLImageTypeLoweringPass()
FunctionPass * createAMDGPUCodeGenPreparePass()
void initializeSIAnnotateControlFlowLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUISelDag(TargetMachine &TM, CodeGenOptLevel OptLevel)
This pass converts a legalized DAG into a AMDGPU-specific.
void initializeGCNCreateVOPDLegacyPass(PassRegistry &)
void initializeAMDGPUUniformIntrinsicCombineLegacyPass(PassRegistry &)
ScheduleDAGInstrs * createGCNCoExecMachineScheduler(MachineSchedContext *C)
void initializeSIPreAllocateWWMRegsLegacyPass(PassRegistry &)
void initializeSIFixVGPRCopiesLegacyPass(PassRegistry &)
Target & getTheGCNTarget()
The target for GCN GPUs.
void initializeSIFixSGPRCopiesLegacyPass(PassRegistry &)
void initializeAMDGPUAtomicOptimizerPass(PassRegistry &)
void initializeAMDGPULowerIntrinsicsLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGVNPass()
Create a legacy GVN pass.
Definition GVN.cpp:3398
void initializeAMDGPURewriteAGPRCopyMFMALegacyPass(PassRegistry &)
void initializeAMDGPUNextUseAnalysisPrinterLegacyPassPass(PassRegistry &)
void initializeSIPostRABundlerLegacyPass(PassRegistry &)
FunctionPass * createAMDGPURegBankSelectPass()
FunctionPass * createAMDGPURegBankLegalizePass()
LLVM_ABI char & MachineCSELegacyID
MachineCSE - This pass performs global CSE on machine instructions.
char & SIWholeQuadModeID
LLVM_ABI 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...
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
LLVM_ABI 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()
FunctionPass * createAMDGPUPostLegalizeCombiner(bool IsOptNone)
void initializeAMDGPULowerKernelAttributesPass(PassRegistry &)
char & SIInsertHardClausesID
char & SIFixSGPRCopiesLegacyID
void initializeGCNDPPCombineLegacyPass(PassRegistry &)
char & GCNCreateVOPDID
char & SIPeepholeSDWALegacyID
LLVM_ABI char & VirtRegRewriterID
VirtRegRewriter pass.
char & SIFixVGPRCopiesID
char & SIFoldOperandsLegacyID
void initializeGCNNSAReassignLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createLowerSwitchPass()
void initializeAMDGPUPreloadKernArgPrologLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
void initializeR600VectorRegMergerPass(PassRegistry &)
char & AMDGPURewriteAGPRCopyMFMALegacyID
ModulePass * createAMDGPULowerExecSyncLegacyPass()
char & AMDGPULowerVGPREncodingLegacyID
FunctionPass * createAMDGPUGlobalISelDivergenceLoweringPass()
FunctionPass * createSIMemoryLegalizerPass()
void initializeAMDGPULateCodeGenPrepareLegacyPass(PassRegistry &)
void initializeSIOptimizeVGPRLiveRangeLegacyPass(PassRegistry &)
void initializeSIPeepholeSDWALegacyPass(PassRegistry &)
void initializeAMDGPURegBankLegalizePass(PassRegistry &)
LLVM_ABI char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
FunctionPass * createAMDGPUPreLegalizeCombiner(bool IsOptNone)
void initializeAMDGPURegBankSelectPass(PassRegistry &)
FunctionPass * createAMDGPULateCodeGenPrepareLegacyPass()
LLVM_ABI FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
MCRegisterInfo * createGCNMCRegisterInfo(AMDGPUDwarfFlavour DwarfFlavour)
LLVM_ABI FunctionPass * createStraightLineStrengthReducePass()
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
FunctionPass * createAMDGPUImageIntrinsicOptimizerPass(const TargetMachine *)
void initializeAMDGPULowerBufferFatPointersPass(PassRegistry &)
void initializeAMDGPUUnifyDivergentExitNodesLegacyPass(PassRegistry &)
FunctionPass * createSIInsertWaitcntsPass()
FunctionPass * createAMDGPUAnnotateUniformValuesLegacy()
LLVM_ABI FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
void initializeSIWholeQuadModeLegacyPass(PassRegistry &)
LLVM_ABI char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
LLVM_ABI llvm::cl::opt< bool > NoKernelInfoEndLTO
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
void initializeAMDGPUResourceUsageAnalysisWrapperPassPass(PassRegistry &)
FunctionPass * createSIShrinkInstructionsLegacyPass()
char & AMDGPUPrepareAGPRAllocLegacyID
char & AMDGPUMarkLastScratchLoadID
LLVM_ABI char & RenameIndependentSubregsID
This pass detects subregister lanes in a virtual register that are used independently of other lanes ...
void initializeAMDGPUAnnotateUniformValuesLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createAMDGPUExportClusteringDAGMutation()
void initializeAMDGPUPrintfRuntimeBindingPass(PassRegistry &)
void initializeAMDGPUPromoteAllocaPass(PassRegistry &)
void initializeAMDGPURemoveIncompatibleFunctionsLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createAMDGPUHazardLatencyDAGMutation(MachineFunction *MF)
void initializeAMDGPUAlwaysInlinePass(PassRegistry &)
LLVM_ABI char & DeadMachineInstructionElimID
DeadMachineInstructionElim - This pass removes dead machine instructions.
void initializeSIPreEmitPeepholeLegacyPass(PassRegistry &)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
char & AMDGPUPerfHintAnalysisLegacyID
LLVM_ABI 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...
char & GCNPreRALongBranchRegID
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption()
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void initializeAMDGPUPromoteKernelArgumentsPass(PassRegistry &)
#define N
static ArgDescriptor createStack(unsigned Offset, unsigned Mask=~0u)
static ArgDescriptor createArg(const ArgDescriptor &Arg, unsigned Mask)
static ArgDescriptor createRegister(Register Reg, unsigned Mask=~0u)
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ IEEE
IEEE-754 denormal numbers preserved.
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
A simple and fast domtree-based CSE pass.
Definition EarlyCSE.h:31
MachineFunctionInfo - This class can be derived from and used by targets to hold private target-speci...
static FuncInfoTy * create(BumpPtrAllocator &Allocator, const Function &F, const SubtargetTy *STI)
Factory function: default behavior is to call new using the supplied allocator.
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:178
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:177
RegisterTargetMachine - Helper template for registering a target machine implementation,...
A utility pass template to force an analysis result to be available.
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.