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 /// The AMDGPU target machine contains all of the hardware specific
11 /// information  needed to emit code for SI+ GPUs.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPUTargetMachine.h"
16 #include "AMDGPU.h"
17 #include "AMDGPUAliasAnalysis.h"
18 #include "AMDGPUExportClustering.h"
19 #include "AMDGPUMacroFusion.h"
20 #include "AMDGPUTargetObjectFile.h"
21 #include "AMDGPUTargetTransformInfo.h"
22 #include "GCNIterativeScheduler.h"
23 #include "GCNSchedStrategy.h"
24 #include "R600.h"
25 #include "R600TargetMachine.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIMachineScheduler.h"
28 #include "TargetInfo/AMDGPUTargetInfo.h"
29 #include "llvm/Analysis/CGSCCPassManager.h"
30 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
31 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
32 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
33 #include "llvm/CodeGen/GlobalISel/Localizer.h"
34 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
35 #include "llvm/CodeGen/MIRParser/MIParser.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/CodeGen/RegAllocRegistry.h"
38 #include "llvm/CodeGen/TargetPassConfig.h"
39 #include "llvm/IR/LegacyPassManager.h"
40 #include "llvm/IR/PassManager.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/MC/TargetRegistry.h"
43 #include "llvm/Passes/PassBuilder.h"
44 #include "llvm/Transforms/IPO.h"
45 #include "llvm/Transforms/IPO/AlwaysInliner.h"
46 #include "llvm/Transforms/IPO/GlobalDCE.h"
47 #include "llvm/Transforms/IPO/Internalize.h"
48 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
49 #include "llvm/Transforms/Scalar.h"
50 #include "llvm/Transforms/Scalar/GVN.h"
51 #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
52 #include "llvm/Transforms/Utils.h"
53 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
54 #include "llvm/Transforms/Vectorize.h"
55 
56 using namespace llvm;
57 
58 namespace {
59 class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
60 public:
61   SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
62     : RegisterRegAllocBase(N, D, C) {}
63 };
64 
65 class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
66 public:
67   VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
68     : RegisterRegAllocBase(N, D, C) {}
69 };
70 
71 static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI,
72                               const TargetRegisterClass &RC) {
73   return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(&RC);
74 }
75 
76 static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI,
77                               const TargetRegisterClass &RC) {
78   return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(&RC);
79 }
80 
81 
82 /// -{sgpr|vgpr}-regalloc=... command line option.
83 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
84 
85 /// A dummy default pass factory indicates whether the register allocator is
86 /// overridden on the command line.
87 static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag;
88 static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag;
89 
90 static SGPRRegisterRegAlloc
91 defaultSGPRRegAlloc("default",
92                     "pick SGPR register allocator based on -O option",
93                     useDefaultRegisterAllocator);
94 
95 static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
96                RegisterPassParser<SGPRRegisterRegAlloc>>
97 SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
98              cl::desc("Register allocator to use for SGPRs"));
99 
100 static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
101                RegisterPassParser<VGPRRegisterRegAlloc>>
102 VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
103              cl::desc("Register allocator to use for VGPRs"));
104 
105 
106 static void initializeDefaultSGPRRegisterAllocatorOnce() {
107   RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
108 
109   if (!Ctor) {
110     Ctor = SGPRRegAlloc;
111     SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
112   }
113 }
114 
115 static void initializeDefaultVGPRRegisterAllocatorOnce() {
116   RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
117 
118   if (!Ctor) {
119     Ctor = VGPRRegAlloc;
120     VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
121   }
122 }
123 
124 static FunctionPass *createBasicSGPRRegisterAllocator() {
125   return createBasicRegisterAllocator(onlyAllocateSGPRs);
126 }
127 
128 static FunctionPass *createGreedySGPRRegisterAllocator() {
129   return createGreedyRegisterAllocator(onlyAllocateSGPRs);
130 }
131 
132 static FunctionPass *createFastSGPRRegisterAllocator() {
133   return createFastRegisterAllocator(onlyAllocateSGPRs, false);
134 }
135 
136 static FunctionPass *createBasicVGPRRegisterAllocator() {
137   return createBasicRegisterAllocator(onlyAllocateVGPRs);
138 }
139 
140 static FunctionPass *createGreedyVGPRRegisterAllocator() {
141   return createGreedyRegisterAllocator(onlyAllocateVGPRs);
142 }
143 
144 static FunctionPass *createFastVGPRRegisterAllocator() {
145   return createFastRegisterAllocator(onlyAllocateVGPRs, true);
146 }
147 
148 static SGPRRegisterRegAlloc basicRegAllocSGPR(
149   "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
150 static SGPRRegisterRegAlloc greedyRegAllocSGPR(
151   "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
152 
153 static SGPRRegisterRegAlloc fastRegAllocSGPR(
154   "fast", "fast register allocator", createFastSGPRRegisterAllocator);
155 
156 
157 static VGPRRegisterRegAlloc basicRegAllocVGPR(
158   "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
159 static VGPRRegisterRegAlloc greedyRegAllocVGPR(
160   "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
161 
162 static VGPRRegisterRegAlloc fastRegAllocVGPR(
163   "fast", "fast register allocator", createFastVGPRRegisterAllocator);
164 }
165 
166 static cl::opt<bool> EnableSROA(
167   "amdgpu-sroa",
168   cl::desc("Run SROA after promote alloca pass"),
169   cl::ReallyHidden,
170   cl::init(true));
171 
172 static cl::opt<bool>
173 EnableEarlyIfConversion("amdgpu-early-ifcvt", cl::Hidden,
174                         cl::desc("Run early if-conversion"),
175                         cl::init(false));
176 
177 static cl::opt<bool>
178 OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
179             cl::desc("Run pre-RA exec mask optimizations"),
180             cl::init(true));
181 
182 // Option to disable vectorizer for tests.
183 static cl::opt<bool> EnableLoadStoreVectorizer(
184   "amdgpu-load-store-vectorizer",
185   cl::desc("Enable load store vectorizer"),
186   cl::init(true),
187   cl::Hidden);
188 
189 // Option to control global loads scalarization
190 static cl::opt<bool> ScalarizeGlobal(
191   "amdgpu-scalarize-global-loads",
192   cl::desc("Enable global load scalarization"),
193   cl::init(true),
194   cl::Hidden);
195 
196 // Option to run internalize pass.
197 static cl::opt<bool> InternalizeSymbols(
198   "amdgpu-internalize-symbols",
199   cl::desc("Enable elimination of non-kernel functions and unused globals"),
200   cl::init(false),
201   cl::Hidden);
202 
203 // Option to inline all early.
204 static cl::opt<bool> EarlyInlineAll(
205   "amdgpu-early-inline-all",
206   cl::desc("Inline all functions early"),
207   cl::init(false),
208   cl::Hidden);
209 
210 static cl::opt<bool> EnableSDWAPeephole(
211   "amdgpu-sdwa-peephole",
212   cl::desc("Enable SDWA peepholer"),
213   cl::init(true));
214 
215 static cl::opt<bool> EnableDPPCombine(
216   "amdgpu-dpp-combine",
217   cl::desc("Enable DPP combiner"),
218   cl::init(true));
219 
220 // Enable address space based alias analysis
221 static cl::opt<bool> EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden,
222   cl::desc("Enable AMDGPU Alias Analysis"),
223   cl::init(true));
224 
225 // Option to run late CFG structurizer
226 static cl::opt<bool, true> LateCFGStructurize(
227   "amdgpu-late-structurize",
228   cl::desc("Enable late CFG structurization"),
229   cl::location(AMDGPUTargetMachine::EnableLateStructurizeCFG),
230   cl::Hidden);
231 
232 static cl::opt<bool, true> EnableAMDGPUFixedFunctionABIOpt(
233   "amdgpu-fixed-function-abi",
234   cl::desc("Enable all implicit function arguments"),
235   cl::location(AMDGPUTargetMachine::EnableFixedFunctionABI),
236   cl::init(false),
237   cl::Hidden);
238 
239 // Enable lib calls simplifications
240 static cl::opt<bool> EnableLibCallSimplify(
241   "amdgpu-simplify-libcall",
242   cl::desc("Enable amdgpu library simplifications"),
243   cl::init(true),
244   cl::Hidden);
245 
246 static cl::opt<bool> EnableLowerKernelArguments(
247   "amdgpu-ir-lower-kernel-arguments",
248   cl::desc("Lower kernel argument loads in IR pass"),
249   cl::init(true),
250   cl::Hidden);
251 
252 static cl::opt<bool> EnableRegReassign(
253   "amdgpu-reassign-regs",
254   cl::desc("Enable register reassign optimizations on gfx10+"),
255   cl::init(true),
256   cl::Hidden);
257 
258 static cl::opt<bool> OptVGPRLiveRange(
259     "amdgpu-opt-vgpr-liverange",
260     cl::desc("Enable VGPR liverange optimizations for if-else structure"),
261     cl::init(true), cl::Hidden);
262 
263 // Enable atomic optimization
264 static cl::opt<bool> EnableAtomicOptimizations(
265   "amdgpu-atomic-optimizations",
266   cl::desc("Enable atomic optimizations"),
267   cl::init(false),
268   cl::Hidden);
269 
270 // Enable Mode register optimization
271 static cl::opt<bool> EnableSIModeRegisterPass(
272   "amdgpu-mode-register",
273   cl::desc("Enable mode register pass"),
274   cl::init(true),
275   cl::Hidden);
276 
277 // Option is used in lit tests to prevent deadcoding of patterns inspected.
278 static cl::opt<bool>
279 EnableDCEInRA("amdgpu-dce-in-ra",
280     cl::init(true), cl::Hidden,
281     cl::desc("Enable machine DCE inside regalloc"));
282 
283 static cl::opt<bool> EnableScalarIRPasses(
284   "amdgpu-scalar-ir-passes",
285   cl::desc("Enable scalar IR passes"),
286   cl::init(true),
287   cl::Hidden);
288 
289 static cl::opt<bool> EnableStructurizerWorkarounds(
290     "amdgpu-enable-structurizer-workarounds",
291     cl::desc("Enable workarounds for the StructurizeCFG pass"), cl::init(true),
292     cl::Hidden);
293 
294 static cl::opt<bool> EnableLDSReplaceWithPointer(
295     "amdgpu-enable-lds-replace-with-pointer",
296     cl::desc("Enable LDS replace with pointer pass"), cl::init(false),
297     cl::Hidden);
298 
299 static cl::opt<bool, true> EnableLowerModuleLDS(
300     "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
301     cl::location(AMDGPUTargetMachine::EnableLowerModuleLDS), cl::init(true),
302     cl::Hidden);
303 
304 static cl::opt<bool> EnablePreRAOptimizations(
305     "amdgpu-enable-pre-ra-optimizations",
306     cl::desc("Enable Pre-RA optimizations pass"), cl::init(true),
307     cl::Hidden);
308 
309 static cl::opt<bool> EnablePromoteKernelArguments(
310     "amdgpu-enable-promote-kernel-arguments",
311     cl::desc("Enable promotion of flat kernel pointer arguments to global"),
312     cl::Hidden, cl::init(true));
313 
314 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget() {
315   // Register the target
316   RegisterTargetMachine<R600TargetMachine> X(getTheAMDGPUTarget());
317   RegisterTargetMachine<GCNTargetMachine> Y(getTheGCNTarget());
318 
319   PassRegistry *PR = PassRegistry::getPassRegistry();
320   initializeR600ClauseMergePassPass(*PR);
321   initializeR600ControlFlowFinalizerPass(*PR);
322   initializeR600PacketizerPass(*PR);
323   initializeR600ExpandSpecialInstrsPassPass(*PR);
324   initializeR600VectorRegMergerPass(*PR);
325   initializeGlobalISel(*PR);
326   initializeAMDGPUDAGToDAGISelPass(*PR);
327   initializeGCNDPPCombinePass(*PR);
328   initializeSILowerI1CopiesPass(*PR);
329   initializeSILowerSGPRSpillsPass(*PR);
330   initializeSIFixSGPRCopiesPass(*PR);
331   initializeSIFixVGPRCopiesPass(*PR);
332   initializeSIFoldOperandsPass(*PR);
333   initializeSIPeepholeSDWAPass(*PR);
334   initializeSIShrinkInstructionsPass(*PR);
335   initializeSIOptimizeExecMaskingPreRAPass(*PR);
336   initializeSIOptimizeVGPRLiveRangePass(*PR);
337   initializeSILoadStoreOptimizerPass(*PR);
338   initializeAMDGPUFixFunctionBitcastsPass(*PR);
339   initializeAMDGPUCtorDtorLoweringPass(*PR);
340   initializeAMDGPUAlwaysInlinePass(*PR);
341   initializeAMDGPUAttributorPass(*PR);
342   initializeAMDGPUAnnotateKernelFeaturesPass(*PR);
343   initializeAMDGPUAnnotateUniformValuesPass(*PR);
344   initializeAMDGPUArgumentUsageInfoPass(*PR);
345   initializeAMDGPUAtomicOptimizerPass(*PR);
346   initializeAMDGPULowerKernelArgumentsPass(*PR);
347   initializeAMDGPUPromoteKernelArgumentsPass(*PR);
348   initializeAMDGPULowerKernelAttributesPass(*PR);
349   initializeAMDGPULowerIntrinsicsPass(*PR);
350   initializeAMDGPUOpenCLEnqueuedBlockLoweringPass(*PR);
351   initializeAMDGPUPostLegalizerCombinerPass(*PR);
352   initializeAMDGPUPreLegalizerCombinerPass(*PR);
353   initializeAMDGPURegBankCombinerPass(*PR);
354   initializeAMDGPUPromoteAllocaPass(*PR);
355   initializeAMDGPUPromoteAllocaToVectorPass(*PR);
356   initializeAMDGPUCodeGenPreparePass(*PR);
357   initializeAMDGPULateCodeGenPreparePass(*PR);
358   initializeAMDGPUPropagateAttributesEarlyPass(*PR);
359   initializeAMDGPUPropagateAttributesLatePass(*PR);
360   initializeAMDGPUReplaceLDSUseWithPointerPass(*PR);
361   initializeAMDGPULowerModuleLDSPass(*PR);
362   initializeAMDGPURewriteOutArgumentsPass(*PR);
363   initializeAMDGPUUnifyMetadataPass(*PR);
364   initializeSIAnnotateControlFlowPass(*PR);
365   initializeSIInsertHardClausesPass(*PR);
366   initializeSIInsertWaitcntsPass(*PR);
367   initializeSIModeRegisterPass(*PR);
368   initializeSIWholeQuadModePass(*PR);
369   initializeSILowerControlFlowPass(*PR);
370   initializeSIPreEmitPeepholePass(*PR);
371   initializeSILateBranchLoweringPass(*PR);
372   initializeSIMemoryLegalizerPass(*PR);
373   initializeSIOptimizeExecMaskingPass(*PR);
374   initializeSIPreAllocateWWMRegsPass(*PR);
375   initializeSIFormMemoryClausesPass(*PR);
376   initializeSIPostRABundlerPass(*PR);
377   initializeAMDGPUUnifyDivergentExitNodesPass(*PR);
378   initializeAMDGPUAAWrapperPassPass(*PR);
379   initializeAMDGPUExternalAAWrapperPass(*PR);
380   initializeAMDGPUUseNativeCallsPass(*PR);
381   initializeAMDGPUSimplifyLibCallsPass(*PR);
382   initializeAMDGPUPrintfRuntimeBindingPass(*PR);
383   initializeAMDGPUResourceUsageAnalysisPass(*PR);
384   initializeGCNNSAReassignPass(*PR);
385   initializeGCNPreRAOptimizationsPass(*PR);
386 }
387 
388 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
389   return std::make_unique<AMDGPUTargetObjectFile>();
390 }
391 
392 static ScheduleDAGInstrs *createSIMachineScheduler(MachineSchedContext *C) {
393   return new SIScheduleDAGMI(C);
394 }
395 
396 static ScheduleDAGInstrs *
397 createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
398   ScheduleDAGMILive *DAG =
399     new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
400   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
401   DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
402   DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
403   return DAG;
404 }
405 
406 static ScheduleDAGInstrs *
407 createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
408   auto DAG = new GCNIterativeScheduler(C,
409     GCNIterativeScheduler::SCHEDULE_LEGACYMAXOCCUPANCY);
410   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
411   return DAG;
412 }
413 
414 static ScheduleDAGInstrs *createMinRegScheduler(MachineSchedContext *C) {
415   return new GCNIterativeScheduler(C,
416     GCNIterativeScheduler::SCHEDULE_MINREGFORCED);
417 }
418 
419 static ScheduleDAGInstrs *
420 createIterativeILPMachineScheduler(MachineSchedContext *C) {
421   auto DAG = new GCNIterativeScheduler(C,
422     GCNIterativeScheduler::SCHEDULE_ILP);
423   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
424   DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
425   return DAG;
426 }
427 
428 static MachineSchedRegistry
429 SISchedRegistry("si", "Run SI's custom scheduler",
430                 createSIMachineScheduler);
431 
432 static MachineSchedRegistry
433 GCNMaxOccupancySchedRegistry("gcn-max-occupancy",
434                              "Run GCN scheduler to maximize occupancy",
435                              createGCNMaxOccupancyMachineScheduler);
436 
437 static MachineSchedRegistry
438 IterativeGCNMaxOccupancySchedRegistry("gcn-max-occupancy-experimental",
439   "Run GCN scheduler to maximize occupancy (experimental)",
440   createIterativeGCNMaxOccupancyMachineScheduler);
441 
442 static MachineSchedRegistry
443 GCNMinRegSchedRegistry("gcn-minreg",
444   "Run GCN iterative scheduler for minimal register usage (experimental)",
445   createMinRegScheduler);
446 
447 static MachineSchedRegistry
448 GCNILPSchedRegistry("gcn-ilp",
449   "Run GCN iterative scheduler for ILP scheduling (experimental)",
450   createIterativeILPMachineScheduler);
451 
452 static StringRef computeDataLayout(const Triple &TT) {
453   if (TT.getArch() == Triple::r600) {
454     // 32-bit pointers.
455     return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
456            "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
457   }
458 
459   // 32-bit private, local, and region pointers. 64-bit global, constant and
460   // flat, non-integral buffer fat pointers.
461   return "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
462          "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
463          "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1"
464          "-ni:7";
465 }
466 
467 LLVM_READNONE
468 static StringRef getGPUOrDefault(const Triple &TT, StringRef GPU) {
469   if (!GPU.empty())
470     return GPU;
471 
472   // Need to default to a target with flat support for HSA.
473   if (TT.getArch() == Triple::amdgcn)
474     return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
475 
476   return "r600";
477 }
478 
479 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
480   // The AMDGPU toolchain only supports generating shared objects, so we
481   // must always use PIC.
482   return Reloc::PIC_;
483 }
484 
485 AMDGPUTargetMachine::AMDGPUTargetMachine(const Target &T, const Triple &TT,
486                                          StringRef CPU, StringRef FS,
487                                          TargetOptions Options,
488                                          Optional<Reloc::Model> RM,
489                                          Optional<CodeModel::Model> CM,
490                                          CodeGenOpt::Level OptLevel)
491     : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU),
492                         FS, Options, getEffectiveRelocModel(RM),
493                         getEffectiveCodeModel(CM, CodeModel::Small), OptLevel),
494       TLOF(createTLOF(getTargetTriple())) {
495   initAsmInfo();
496   if (TT.getArch() == Triple::amdgcn) {
497     if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize64"))
498       MRI.reset(llvm::createGCNMCRegisterInfo(AMDGPUDwarfFlavour::Wave64));
499     else if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize32"))
500       MRI.reset(llvm::createGCNMCRegisterInfo(AMDGPUDwarfFlavour::Wave32));
501   }
502 }
503 
504 bool AMDGPUTargetMachine::EnableLateStructurizeCFG = false;
505 bool AMDGPUTargetMachine::EnableFunctionCalls = false;
506 bool AMDGPUTargetMachine::EnableFixedFunctionABI = false;
507 bool AMDGPUTargetMachine::EnableLowerModuleLDS = true;
508 
509 AMDGPUTargetMachine::~AMDGPUTargetMachine() = default;
510 
511 StringRef AMDGPUTargetMachine::getGPUName(const Function &F) const {
512   Attribute GPUAttr = F.getFnAttribute("target-cpu");
513   return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU();
514 }
515 
516 StringRef AMDGPUTargetMachine::getFeatureString(const Function &F) const {
517   Attribute FSAttr = F.getFnAttribute("target-features");
518 
519   return FSAttr.isValid() ? FSAttr.getValueAsString()
520                           : getTargetFeatureString();
521 }
522 
523 /// Predicate for Internalize pass.
524 static bool mustPreserveGV(const GlobalValue &GV) {
525   if (const Function *F = dyn_cast<Function>(&GV))
526     return F->isDeclaration() || F->getName().startswith("__asan_") ||
527            F->getName().startswith("__sanitizer_") ||
528            AMDGPU::isEntryFunctionCC(F->getCallingConv());
529 
530   GV.removeDeadConstantUsers();
531   return !GV.use_empty();
532 }
533 
534 void AMDGPUTargetMachine::adjustPassManager(PassManagerBuilder &Builder) {
535   Builder.DivergentTarget = true;
536 
537   bool EnableOpt = getOptLevel() > CodeGenOpt::None;
538   bool Internalize = InternalizeSymbols;
539   bool EarlyInline = EarlyInlineAll && EnableOpt && !EnableFunctionCalls;
540   bool AMDGPUAA = EnableAMDGPUAliasAnalysis && EnableOpt;
541   bool LibCallSimplify = EnableLibCallSimplify && EnableOpt;
542   bool PromoteKernelArguments =
543       EnablePromoteKernelArguments && getOptLevel() > CodeGenOpt::Less;
544 
545   if (EnableFunctionCalls) {
546     delete Builder.Inliner;
547     Builder.Inliner = createFunctionInliningPass();
548   }
549 
550   Builder.addExtension(
551     PassManagerBuilder::EP_ModuleOptimizerEarly,
552     [Internalize, EarlyInline, AMDGPUAA, this](const PassManagerBuilder &,
553                                                legacy::PassManagerBase &PM) {
554       if (AMDGPUAA) {
555         PM.add(createAMDGPUAAWrapperPass());
556         PM.add(createAMDGPUExternalAAWrapperPass());
557       }
558       PM.add(createAMDGPUUnifyMetadataPass());
559       PM.add(createAMDGPUPrintfRuntimeBinding());
560       if (Internalize)
561         PM.add(createInternalizePass(mustPreserveGV));
562       PM.add(createAMDGPUPropagateAttributesLatePass(this));
563       if (Internalize)
564         PM.add(createGlobalDCEPass());
565       if (EarlyInline)
566         PM.add(createAMDGPUAlwaysInlinePass(false));
567   });
568 
569   Builder.addExtension(
570     PassManagerBuilder::EP_EarlyAsPossible,
571     [AMDGPUAA, LibCallSimplify, this](const PassManagerBuilder &,
572                                       legacy::PassManagerBase &PM) {
573       if (AMDGPUAA) {
574         PM.add(createAMDGPUAAWrapperPass());
575         PM.add(createAMDGPUExternalAAWrapperPass());
576       }
577       PM.add(llvm::createAMDGPUPropagateAttributesEarlyPass(this));
578       PM.add(llvm::createAMDGPUUseNativeCallsPass());
579       if (LibCallSimplify)
580         PM.add(llvm::createAMDGPUSimplifyLibCallsPass(this));
581   });
582 
583   Builder.addExtension(
584     PassManagerBuilder::EP_CGSCCOptimizerLate,
585     [EnableOpt, PromoteKernelArguments](const PassManagerBuilder &,
586                                         legacy::PassManagerBase &PM) {
587       // Add promote kernel arguments pass to the opt pipeline right before
588       // infer address spaces which is needed to do actual address space
589       // rewriting.
590       if (PromoteKernelArguments)
591         PM.add(createAMDGPUPromoteKernelArgumentsPass());
592 
593       // Add infer address spaces pass to the opt pipeline after inlining
594       // but before SROA to increase SROA opportunities.
595       PM.add(createInferAddressSpacesPass());
596 
597       // This should run after inlining to have any chance of doing anything,
598       // and before other cleanup optimizations.
599       PM.add(createAMDGPULowerKernelAttributesPass());
600 
601       // Promote alloca to vector before SROA and loop unroll. If we manage
602       // to eliminate allocas before unroll we may choose to unroll less.
603       if (EnableOpt)
604         PM.add(createAMDGPUPromoteAllocaToVector());
605   });
606 }
607 
608 void AMDGPUTargetMachine::registerDefaultAliasAnalyses(AAManager &AAM) {
609   AAM.registerFunctionAnalysis<AMDGPUAA>();
610 }
611 
612 void AMDGPUTargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) {
613   PB.registerPipelineParsingCallback(
614       [this](StringRef PassName, ModulePassManager &PM,
615              ArrayRef<PassBuilder::PipelineElement>) {
616         if (PassName == "amdgpu-propagate-attributes-late") {
617           PM.addPass(AMDGPUPropagateAttributesLatePass(*this));
618           return true;
619         }
620         if (PassName == "amdgpu-unify-metadata") {
621           PM.addPass(AMDGPUUnifyMetadataPass());
622           return true;
623         }
624         if (PassName == "amdgpu-printf-runtime-binding") {
625           PM.addPass(AMDGPUPrintfRuntimeBindingPass());
626           return true;
627         }
628         if (PassName == "amdgpu-always-inline") {
629           PM.addPass(AMDGPUAlwaysInlinePass());
630           return true;
631         }
632         if (PassName == "amdgpu-replace-lds-use-with-pointer") {
633           PM.addPass(AMDGPUReplaceLDSUseWithPointerPass());
634           return true;
635         }
636         if (PassName == "amdgpu-lower-module-lds") {
637           PM.addPass(AMDGPULowerModuleLDSPass());
638           return true;
639         }
640         return false;
641       });
642   PB.registerPipelineParsingCallback(
643       [this](StringRef PassName, FunctionPassManager &PM,
644              ArrayRef<PassBuilder::PipelineElement>) {
645         if (PassName == "amdgpu-simplifylib") {
646           PM.addPass(AMDGPUSimplifyLibCallsPass(*this));
647           return true;
648         }
649         if (PassName == "amdgpu-usenative") {
650           PM.addPass(AMDGPUUseNativeCallsPass());
651           return true;
652         }
653         if (PassName == "amdgpu-promote-alloca") {
654           PM.addPass(AMDGPUPromoteAllocaPass(*this));
655           return true;
656         }
657         if (PassName == "amdgpu-promote-alloca-to-vector") {
658           PM.addPass(AMDGPUPromoteAllocaToVectorPass(*this));
659           return true;
660         }
661         if (PassName == "amdgpu-lower-kernel-attributes") {
662           PM.addPass(AMDGPULowerKernelAttributesPass());
663           return true;
664         }
665         if (PassName == "amdgpu-propagate-attributes-early") {
666           PM.addPass(AMDGPUPropagateAttributesEarlyPass(*this));
667           return true;
668         }
669         if (PassName == "amdgpu-promote-kernel-arguments") {
670           PM.addPass(AMDGPUPromoteKernelArgumentsPass());
671           return true;
672         }
673         return false;
674       });
675 
676   PB.registerAnalysisRegistrationCallback([](FunctionAnalysisManager &FAM) {
677     FAM.registerPass([&] { return AMDGPUAA(); });
678   });
679 
680   PB.registerParseAACallback([](StringRef AAName, AAManager &AAM) {
681     if (AAName == "amdgpu-aa") {
682       AAM.registerFunctionAnalysis<AMDGPUAA>();
683       return true;
684     }
685     return false;
686   });
687 
688   PB.registerPipelineStartEPCallback(
689       [this](ModulePassManager &PM, OptimizationLevel Level) {
690         FunctionPassManager FPM;
691         FPM.addPass(AMDGPUPropagateAttributesEarlyPass(*this));
692         FPM.addPass(AMDGPUUseNativeCallsPass());
693         if (EnableLibCallSimplify && Level != OptimizationLevel::O0)
694           FPM.addPass(AMDGPUSimplifyLibCallsPass(*this));
695         PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
696       });
697 
698   PB.registerPipelineEarlySimplificationEPCallback(
699       [this](ModulePassManager &PM, OptimizationLevel Level) {
700         if (Level == OptimizationLevel::O0)
701           return;
702 
703         PM.addPass(AMDGPUUnifyMetadataPass());
704         PM.addPass(AMDGPUPrintfRuntimeBindingPass());
705 
706         if (InternalizeSymbols) {
707           PM.addPass(InternalizePass(mustPreserveGV));
708         }
709         PM.addPass(AMDGPUPropagateAttributesLatePass(*this));
710         if (InternalizeSymbols) {
711           PM.addPass(GlobalDCEPass());
712         }
713         if (EarlyInlineAll && !EnableFunctionCalls)
714           PM.addPass(AMDGPUAlwaysInlinePass());
715       });
716 
717   PB.registerCGSCCOptimizerLateEPCallback(
718       [this](CGSCCPassManager &PM, OptimizationLevel Level) {
719         if (Level == OptimizationLevel::O0)
720           return;
721 
722         FunctionPassManager FPM;
723 
724         // Add promote kernel arguments pass to the opt pipeline right before
725         // infer address spaces which is needed to do actual address space
726         // rewriting.
727         if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
728             EnablePromoteKernelArguments)
729           FPM.addPass(AMDGPUPromoteKernelArgumentsPass());
730 
731         // Add infer address spaces pass to the opt pipeline after inlining
732         // but before SROA to increase SROA opportunities.
733         FPM.addPass(InferAddressSpacesPass());
734 
735         // This should run after inlining to have any chance of doing
736         // anything, and before other cleanup optimizations.
737         FPM.addPass(AMDGPULowerKernelAttributesPass());
738 
739         if (Level != OptimizationLevel::O0) {
740           // Promote alloca to vector before SROA and loop unroll. If we
741           // manage to eliminate allocas before unroll we may choose to unroll
742           // less.
743           FPM.addPass(AMDGPUPromoteAllocaToVectorPass(*this));
744         }
745 
746         PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
747       });
748 }
749 
750 int64_t AMDGPUTargetMachine::getNullPointerValue(unsigned AddrSpace) {
751   return (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
752           AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
753           AddrSpace == AMDGPUAS::REGION_ADDRESS)
754              ? -1
755              : 0;
756 }
757 
758 bool AMDGPUTargetMachine::isNoopAddrSpaceCast(unsigned SrcAS,
759                                               unsigned DestAS) const {
760   return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
761          AMDGPU::isFlatGlobalAddrSpace(DestAS);
762 }
763 
764 unsigned AMDGPUTargetMachine::getAssumedAddrSpace(const Value *V) const {
765   const auto *LD = dyn_cast<LoadInst>(V);
766   if (!LD)
767     return AMDGPUAS::UNKNOWN_ADDRESS_SPACE;
768 
769   // It must be a generic pointer loaded.
770   assert(V->getType()->isPointerTy() &&
771          V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
772 
773   const auto *Ptr = LD->getPointerOperand();
774   if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
775     return AMDGPUAS::UNKNOWN_ADDRESS_SPACE;
776   // For a generic pointer loaded from the constant memory, it could be assumed
777   // as a global pointer since the constant memory is only populated on the
778   // host side. As implied by the offload programming model, only global
779   // pointers could be referenced on the host side.
780   return AMDGPUAS::GLOBAL_ADDRESS;
781 }
782 
783 //===----------------------------------------------------------------------===//
784 // GCN Target Machine (SI+)
785 //===----------------------------------------------------------------------===//
786 
787 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT,
788                                    StringRef CPU, StringRef FS,
789                                    TargetOptions Options,
790                                    Optional<Reloc::Model> RM,
791                                    Optional<CodeModel::Model> CM,
792                                    CodeGenOpt::Level OL, bool JIT)
793     : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
794 
795 const TargetSubtargetInfo *
796 GCNTargetMachine::getSubtargetImpl(const Function &F) const {
797   StringRef GPU = getGPUName(F);
798   StringRef FS = getFeatureString(F);
799 
800   SmallString<128> SubtargetKey(GPU);
801   SubtargetKey.append(FS);
802 
803   auto &I = SubtargetMap[SubtargetKey];
804   if (!I) {
805     // This needs to be done before we create a new subtarget since any
806     // creation will depend on the TM and the code generation flags on the
807     // function that reside in TargetOptions.
808     resetTargetOptions(F);
809     I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
810   }
811 
812   I->setScalarizeGlobalBehavior(ScalarizeGlobal);
813 
814   return I.get();
815 }
816 
817 TargetTransformInfo
818 GCNTargetMachine::getTargetTransformInfo(const Function &F) {
819   return TargetTransformInfo(GCNTTIImpl(this, F));
820 }
821 
822 //===----------------------------------------------------------------------===//
823 // AMDGPU Pass Setup
824 //===----------------------------------------------------------------------===//
825 
826 std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
827   return getStandardCSEConfigForOpt(TM->getOptLevel());
828 }
829 
830 namespace {
831 
832 class GCNPassConfig final : public AMDGPUPassConfig {
833 public:
834   GCNPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
835     : AMDGPUPassConfig(TM, PM) {
836     // It is necessary to know the register usage of the entire call graph.  We
837     // allow calls without EnableAMDGPUFunctionCalls if they are marked
838     // noinline, so this is always required.
839     setRequiresCodeGenSCCOrder(true);
840     substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
841   }
842 
843   GCNTargetMachine &getGCNTargetMachine() const {
844     return getTM<GCNTargetMachine>();
845   }
846 
847   ScheduleDAGInstrs *
848   createMachineScheduler(MachineSchedContext *C) const override;
849 
850   ScheduleDAGInstrs *
851   createPostMachineScheduler(MachineSchedContext *C) const override {
852     ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
853     const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
854     DAG->addMutation(ST.createFillMFMAShadowMutation(DAG->TII));
855     return DAG;
856   }
857 
858   bool addPreISel() override;
859   void addMachineSSAOptimization() override;
860   bool addILPOpts() override;
861   bool addInstSelector() override;
862   bool addIRTranslator() override;
863   void addPreLegalizeMachineIR() override;
864   bool addLegalizeMachineIR() override;
865   void addPreRegBankSelect() override;
866   bool addRegBankSelect() override;
867   void addPreGlobalInstructionSelect() override;
868   bool addGlobalInstructionSelect() override;
869   void addFastRegAlloc() override;
870   void addOptimizedRegAlloc() override;
871 
872   FunctionPass *createSGPRAllocPass(bool Optimized);
873   FunctionPass *createVGPRAllocPass(bool Optimized);
874   FunctionPass *createRegAllocPass(bool Optimized) override;
875 
876   bool addRegAssignAndRewriteFast() override;
877   bool addRegAssignAndRewriteOptimized() override;
878 
879   void addPreRegAlloc() override;
880   bool addPreRewrite() override;
881   void addPostRegAlloc() override;
882   void addPreSched2() override;
883   void addPreEmitPass() override;
884 };
885 
886 } // end anonymous namespace
887 
888 AMDGPUPassConfig::AMDGPUPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
889     : TargetPassConfig(TM, PM) {
890   // Exceptions and StackMaps are not supported, so these passes will never do
891   // anything.
892   disablePass(&StackMapLivenessID);
893   disablePass(&FuncletLayoutID);
894   // Garbage collection is not supported.
895   disablePass(&GCLoweringID);
896   disablePass(&ShadowStackGCLoweringID);
897 }
898 
899 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() {
900   if (getOptLevel() == CodeGenOpt::Aggressive)
901     addPass(createGVNPass());
902   else
903     addPass(createEarlyCSEPass());
904 }
905 
906 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() {
907   addPass(createLICMPass());
908   addPass(createSeparateConstOffsetFromGEPPass());
909   addPass(createSpeculativeExecutionPass());
910   // ReassociateGEPs exposes more opportunities for SLSR. See
911   // the example in reassociate-geps-and-slsr.ll.
912   addPass(createStraightLineStrengthReducePass());
913   // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
914   // EarlyCSE can reuse.
915   addEarlyCSEOrGVNPass();
916   // Run NaryReassociate after EarlyCSE/GVN to be more effective.
917   addPass(createNaryReassociatePass());
918   // NaryReassociate on GEPs creates redundant common expressions, so run
919   // EarlyCSE after it.
920   addPass(createEarlyCSEPass());
921 }
922 
923 void AMDGPUPassConfig::addIRPasses() {
924   const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine();
925 
926   // There is no reason to run these.
927   disablePass(&StackMapLivenessID);
928   disablePass(&FuncletLayoutID);
929   disablePass(&PatchableFunctionID);
930 
931   addPass(createAMDGPUPrintfRuntimeBinding());
932   addPass(createAMDGPUCtorDtorLoweringPass());
933 
934   // This must occur before inlining, as the inliner will not look through
935   // bitcast calls.
936   addPass(createAMDGPUFixFunctionBitcastsPass());
937 
938   // A call to propagate attributes pass in the backend in case opt was not run.
939   addPass(createAMDGPUPropagateAttributesEarlyPass(&TM));
940 
941   addPass(createAMDGPULowerIntrinsicsPass());
942 
943   // Function calls are not supported, so make sure we inline everything.
944   addPass(createAMDGPUAlwaysInlinePass());
945   addPass(createAlwaysInlinerLegacyPass());
946   // We need to add the barrier noop pass, otherwise adding the function
947   // inlining pass will cause all of the PassConfigs passes to be run
948   // one function at a time, which means if we have a nodule with two
949   // functions, then we will generate code for the first function
950   // without ever running any passes on the second.
951   addPass(createBarrierNoopPass());
952 
953   // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
954   if (TM.getTargetTriple().getArch() == Triple::r600)
955     addPass(createR600OpenCLImageTypeLoweringPass());
956 
957   // Replace OpenCL enqueued block function pointers with global variables.
958   addPass(createAMDGPUOpenCLEnqueuedBlockLoweringPass());
959 
960   // Can increase LDS used by kernel so runs before PromoteAlloca
961   if (EnableLowerModuleLDS) {
962     // The pass "amdgpu-replace-lds-use-with-pointer" need to be run before the
963     // pass "amdgpu-lower-module-lds", and also it required to be run only if
964     // "amdgpu-lower-module-lds" pass is enabled.
965     if (EnableLDSReplaceWithPointer)
966       addPass(createAMDGPUReplaceLDSUseWithPointerPass());
967 
968     addPass(createAMDGPULowerModuleLDSPass());
969   }
970 
971   if (TM.getOptLevel() > CodeGenOpt::None)
972     addPass(createInferAddressSpacesPass());
973 
974   addPass(createAtomicExpandPass());
975 
976   if (TM.getOptLevel() > CodeGenOpt::None) {
977     addPass(createAMDGPUPromoteAlloca());
978 
979     if (EnableSROA)
980       addPass(createSROAPass());
981     if (isPassEnabled(EnableScalarIRPasses))
982       addStraightLineScalarOptimizationPasses();
983 
984     if (EnableAMDGPUAliasAnalysis) {
985       addPass(createAMDGPUAAWrapperPass());
986       addPass(createExternalAAWrapperPass([](Pass &P, Function &,
987                                              AAResults &AAR) {
988         if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
989           AAR.addAAResult(WrapperPass->getResult());
990         }));
991     }
992 
993     if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
994       // TODO: May want to move later or split into an early and late one.
995       addPass(createAMDGPUCodeGenPreparePass());
996     }
997   }
998 
999   TargetPassConfig::addIRPasses();
1000 
1001   // EarlyCSE is not always strong enough to clean up what LSR produces. For
1002   // example, GVN can combine
1003   //
1004   //   %0 = add %a, %b
1005   //   %1 = add %b, %a
1006   //
1007   // and
1008   //
1009   //   %0 = shl nsw %a, 2
1010   //   %1 = shl %a, 2
1011   //
1012   // but EarlyCSE can do neither of them.
1013   if (isPassEnabled(EnableScalarIRPasses))
1014     addEarlyCSEOrGVNPass();
1015 }
1016 
1017 void AMDGPUPassConfig::addCodeGenPrepare() {
1018   if (TM->getTargetTriple().getArch() == Triple::amdgcn) {
1019     addPass(createAMDGPUAttributorPass());
1020 
1021     // FIXME: This pass adds 2 hacky attributes that can be replaced with an
1022     // analysis, and should be removed.
1023     addPass(createAMDGPUAnnotateKernelFeaturesPass());
1024   }
1025 
1026   if (TM->getTargetTriple().getArch() == Triple::amdgcn &&
1027       EnableLowerKernelArguments)
1028     addPass(createAMDGPULowerKernelArgumentsPass());
1029 
1030   TargetPassConfig::addCodeGenPrepare();
1031 
1032   if (isPassEnabled(EnableLoadStoreVectorizer))
1033     addPass(createLoadStoreVectorizerPass());
1034 
1035   // LowerSwitch pass may introduce unreachable blocks that can
1036   // cause unexpected behavior for subsequent passes. Placing it
1037   // here seems better that these blocks would get cleaned up by
1038   // UnreachableBlockElim inserted next in the pass flow.
1039   addPass(createLowerSwitchPass());
1040 }
1041 
1042 bool AMDGPUPassConfig::addPreISel() {
1043   if (TM->getOptLevel() > CodeGenOpt::None)
1044     addPass(createFlattenCFGPass());
1045   return false;
1046 }
1047 
1048 bool AMDGPUPassConfig::addInstSelector() {
1049   addPass(createAMDGPUISelDag(&getAMDGPUTargetMachine(), getOptLevel()));
1050   return false;
1051 }
1052 
1053 bool AMDGPUPassConfig::addGCPasses() {
1054   // Do nothing. GC is not supported.
1055   return false;
1056 }
1057 
1058 llvm::ScheduleDAGInstrs *
1059 AMDGPUPassConfig::createMachineScheduler(MachineSchedContext *C) const {
1060   ScheduleDAGMILive *DAG = createGenericSchedLive(C);
1061   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1062   return DAG;
1063 }
1064 
1065 //===----------------------------------------------------------------------===//
1066 // GCN Pass Setup
1067 //===----------------------------------------------------------------------===//
1068 
1069 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler(
1070   MachineSchedContext *C) const {
1071   const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1072   if (ST.enableSIScheduler())
1073     return createSIMachineScheduler(C);
1074   return createGCNMaxOccupancyMachineScheduler(C);
1075 }
1076 
1077 bool GCNPassConfig::addPreISel() {
1078   AMDGPUPassConfig::addPreISel();
1079 
1080   if (TM->getOptLevel() > CodeGenOpt::None)
1081     addPass(createAMDGPULateCodeGenPreparePass());
1082 
1083   if (isPassEnabled(EnableAtomicOptimizations, CodeGenOpt::Less)) {
1084     addPass(createAMDGPUAtomicOptimizerPass());
1085   }
1086 
1087   if (TM->getOptLevel() > CodeGenOpt::None)
1088     addPass(createSinkingPass());
1089 
1090   // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1091   // regions formed by them.
1092   addPass(&AMDGPUUnifyDivergentExitNodesID);
1093   if (!LateCFGStructurize) {
1094     if (EnableStructurizerWorkarounds) {
1095       addPass(createFixIrreduciblePass());
1096       addPass(createUnifyLoopExitsPass());
1097     }
1098     addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1099   }
1100   addPass(createAMDGPUAnnotateUniformValues());
1101   if (!LateCFGStructurize) {
1102     addPass(createSIAnnotateControlFlowPass());
1103   }
1104   addPass(createLCSSAPass());
1105 
1106   if (TM->getOptLevel() > CodeGenOpt::Less)
1107     addPass(&AMDGPUPerfHintAnalysisID);
1108 
1109   return false;
1110 }
1111 
1112 void GCNPassConfig::addMachineSSAOptimization() {
1113   TargetPassConfig::addMachineSSAOptimization();
1114 
1115   // We want to fold operands after PeepholeOptimizer has run (or as part of
1116   // it), because it will eliminate extra copies making it easier to fold the
1117   // real source operand. We want to eliminate dead instructions after, so that
1118   // we see fewer uses of the copies. We then need to clean up the dead
1119   // instructions leftover after the operands are folded as well.
1120   //
1121   // XXX - Can we get away without running DeadMachineInstructionElim again?
1122   addPass(&SIFoldOperandsID);
1123   if (EnableDPPCombine)
1124     addPass(&GCNDPPCombineID);
1125   addPass(&SILoadStoreOptimizerID);
1126   if (isPassEnabled(EnableSDWAPeephole)) {
1127     addPass(&SIPeepholeSDWAID);
1128     addPass(&EarlyMachineLICMID);
1129     addPass(&MachineCSEID);
1130     addPass(&SIFoldOperandsID);
1131   }
1132   addPass(&DeadMachineInstructionElimID);
1133   addPass(createSIShrinkInstructionsPass());
1134 }
1135 
1136 bool GCNPassConfig::addILPOpts() {
1137   if (EnableEarlyIfConversion)
1138     addPass(&EarlyIfConverterID);
1139 
1140   TargetPassConfig::addILPOpts();
1141   return false;
1142 }
1143 
1144 bool GCNPassConfig::addInstSelector() {
1145   AMDGPUPassConfig::addInstSelector();
1146   addPass(&SIFixSGPRCopiesID);
1147   addPass(createSILowerI1CopiesPass());
1148   return false;
1149 }
1150 
1151 bool GCNPassConfig::addIRTranslator() {
1152   addPass(new IRTranslator(getOptLevel()));
1153   return false;
1154 }
1155 
1156 void GCNPassConfig::addPreLegalizeMachineIR() {
1157   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
1158   addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1159   addPass(new Localizer());
1160 }
1161 
1162 bool GCNPassConfig::addLegalizeMachineIR() {
1163   addPass(new Legalizer());
1164   return false;
1165 }
1166 
1167 void GCNPassConfig::addPreRegBankSelect() {
1168   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
1169   addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1170 }
1171 
1172 bool GCNPassConfig::addRegBankSelect() {
1173   addPass(new RegBankSelect());
1174   return false;
1175 }
1176 
1177 void GCNPassConfig::addPreGlobalInstructionSelect() {
1178   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
1179   addPass(createAMDGPURegBankCombiner(IsOptNone));
1180 }
1181 
1182 bool GCNPassConfig::addGlobalInstructionSelect() {
1183   addPass(new InstructionSelect(getOptLevel()));
1184   return false;
1185 }
1186 
1187 void GCNPassConfig::addPreRegAlloc() {
1188   if (LateCFGStructurize) {
1189     addPass(createAMDGPUMachineCFGStructurizerPass());
1190   }
1191 }
1192 
1193 void GCNPassConfig::addFastRegAlloc() {
1194   // FIXME: We have to disable the verifier here because of PHIElimination +
1195   // TwoAddressInstructions disabling it.
1196 
1197   // This must be run immediately after phi elimination and before
1198   // TwoAddressInstructions, otherwise the processing of the tied operand of
1199   // SI_ELSE will introduce a copy of the tied operand source after the else.
1200   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
1201 
1202   insertPass(&TwoAddressInstructionPassID, &SIWholeQuadModeID);
1203   insertPass(&TwoAddressInstructionPassID, &SIPreAllocateWWMRegsID);
1204 
1205   TargetPassConfig::addFastRegAlloc();
1206 }
1207 
1208 void GCNPassConfig::addOptimizedRegAlloc() {
1209   // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1210   // instructions that cause scheduling barriers.
1211   insertPass(&MachineSchedulerID, &SIWholeQuadModeID);
1212   insertPass(&MachineSchedulerID, &SIPreAllocateWWMRegsID);
1213 
1214   if (OptExecMaskPreRA)
1215     insertPass(&MachineSchedulerID, &SIOptimizeExecMaskingPreRAID);
1216 
1217   if (isPassEnabled(EnablePreRAOptimizations))
1218     insertPass(&RenameIndependentSubregsID, &GCNPreRAOptimizationsID);
1219 
1220   // This is not an essential optimization and it has a noticeable impact on
1221   // compilation time, so we only enable it from O2.
1222   if (TM->getOptLevel() > CodeGenOpt::Less)
1223     insertPass(&MachineSchedulerID, &SIFormMemoryClausesID);
1224 
1225   // FIXME: when an instruction has a Killed operand, and the instruction is
1226   // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1227   // the register in LiveVariables, this would trigger a failure in verifier,
1228   // we should fix it and enable the verifier.
1229   if (OptVGPRLiveRange)
1230     insertPass(&LiveVariablesID, &SIOptimizeVGPRLiveRangeID, false);
1231   // This must be run immediately after phi elimination and before
1232   // TwoAddressInstructions, otherwise the processing of the tied operand of
1233   // SI_ELSE will introduce a copy of the tied operand source after the else.
1234   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
1235 
1236   if (EnableDCEInRA)
1237     insertPass(&DetectDeadLanesID, &DeadMachineInstructionElimID);
1238 
1239   TargetPassConfig::addOptimizedRegAlloc();
1240 }
1241 
1242 bool GCNPassConfig::addPreRewrite() {
1243   if (EnableRegReassign)
1244     addPass(&GCNNSAReassignID);
1245   return true;
1246 }
1247 
1248 FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1249   // Initialize the global default.
1250   llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1251                   initializeDefaultSGPRRegisterAllocatorOnce);
1252 
1253   RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1254   if (Ctor != useDefaultRegisterAllocator)
1255     return Ctor();
1256 
1257   if (Optimized)
1258     return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1259 
1260   return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1261 }
1262 
1263 FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1264   // Initialize the global default.
1265   llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1266                   initializeDefaultVGPRRegisterAllocatorOnce);
1267 
1268   RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1269   if (Ctor != useDefaultRegisterAllocator)
1270     return Ctor();
1271 
1272   if (Optimized)
1273     return createGreedyVGPRRegisterAllocator();
1274 
1275   return createFastVGPRRegisterAllocator();
1276 }
1277 
1278 FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1279   llvm_unreachable("should not be used");
1280 }
1281 
1282 static const char RegAllocOptNotSupportedMessage[] =
1283   "-regalloc not supported with amdgcn. Use -sgpr-regalloc and -vgpr-regalloc";
1284 
1285 bool GCNPassConfig::addRegAssignAndRewriteFast() {
1286   if (!usingDefaultRegAlloc())
1287     report_fatal_error(RegAllocOptNotSupportedMessage);
1288 
1289   addPass(createSGPRAllocPass(false));
1290 
1291   // Equivalent of PEI for SGPRs.
1292   addPass(&SILowerSGPRSpillsID);
1293 
1294   addPass(createVGPRAllocPass(false));
1295   return true;
1296 }
1297 
1298 bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1299   if (!usingDefaultRegAlloc())
1300     report_fatal_error(RegAllocOptNotSupportedMessage);
1301 
1302   addPass(createSGPRAllocPass(true));
1303 
1304   // Commit allocated register changes. This is mostly necessary because too
1305   // many things rely on the use lists of the physical registers, such as the
1306   // verifier. This is only necessary with allocators which use LiveIntervals,
1307   // since FastRegAlloc does the replacements itself.
1308   addPass(createVirtRegRewriter(false));
1309 
1310   // Equivalent of PEI for SGPRs.
1311   addPass(&SILowerSGPRSpillsID);
1312 
1313   addPass(createVGPRAllocPass(true));
1314 
1315   addPreRewrite();
1316   addPass(&VirtRegRewriterID);
1317 
1318   return true;
1319 }
1320 
1321 void GCNPassConfig::addPostRegAlloc() {
1322   addPass(&SIFixVGPRCopiesID);
1323   if (getOptLevel() > CodeGenOpt::None)
1324     addPass(&SIOptimizeExecMaskingID);
1325   TargetPassConfig::addPostRegAlloc();
1326 }
1327 
1328 void GCNPassConfig::addPreSched2() {
1329   addPass(&SIPostRABundlerID);
1330 }
1331 
1332 void GCNPassConfig::addPreEmitPass() {
1333   addPass(createSIMemoryLegalizerPass());
1334   addPass(createSIInsertWaitcntsPass());
1335 
1336   if (TM->getOptLevel() > CodeGenOpt::None)
1337     addPass(createSIShrinkInstructionsPass());
1338 
1339   addPass(createSIModeRegisterPass());
1340 
1341   if (getOptLevel() > CodeGenOpt::None)
1342     addPass(&SIInsertHardClausesID);
1343 
1344   addPass(&SILateBranchLoweringPassID);
1345   if (getOptLevel() > CodeGenOpt::None)
1346     addPass(&SIPreEmitPeepholeID);
1347   // The hazard recognizer that runs as part of the post-ra scheduler does not
1348   // guarantee to be able handle all hazards correctly. This is because if there
1349   // are multiple scheduling regions in a basic block, the regions are scheduled
1350   // bottom up, so when we begin to schedule a region we don't know what
1351   // instructions were emitted directly before it.
1352   //
1353   // Here we add a stand-alone hazard recognizer pass which can handle all
1354   // cases.
1355   addPass(&PostRAHazardRecognizerID);
1356   addPass(&BranchRelaxationPassID);
1357 }
1358 
1359 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) {
1360   return new GCNPassConfig(*this, PM);
1361 }
1362 
1363 yaml::MachineFunctionInfo *GCNTargetMachine::createDefaultFuncInfoYAML() const {
1364   return new yaml::SIMachineFunctionInfo();
1365 }
1366 
1367 yaml::MachineFunctionInfo *
1368 GCNTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
1369   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1370   return new yaml::SIMachineFunctionInfo(
1371       *MFI, *MF.getSubtarget().getRegisterInfo(), MF);
1372 }
1373 
1374 bool GCNTargetMachine::parseMachineFunctionInfo(
1375     const yaml::MachineFunctionInfo &MFI_, PerFunctionMIParsingState &PFS,
1376     SMDiagnostic &Error, SMRange &SourceRange) const {
1377   const yaml::SIMachineFunctionInfo &YamlMFI =
1378       reinterpret_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1379   MachineFunction &MF = PFS.MF;
1380   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1381 
1382   if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1383     return true;
1384 
1385   if (MFI->Occupancy == 0) {
1386     // Fixup the subtarget dependent default value.
1387     const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1388     MFI->Occupancy = ST.computeOccupancy(MF.getFunction(), MFI->getLDSSize());
1389   }
1390 
1391   auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1392     Register TempReg;
1393     if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1394       SourceRange = RegName.SourceRange;
1395       return true;
1396     }
1397     RegVal = TempReg;
1398 
1399     return false;
1400   };
1401 
1402   auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1403     // Create a diagnostic for a the register string literal.
1404     const MemoryBuffer &Buffer =
1405         *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1406     Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1407                          RegName.Value.size(), SourceMgr::DK_Error,
1408                          "incorrect register class for field", RegName.Value,
1409                          None, None);
1410     SourceRange = RegName.SourceRange;
1411     return true;
1412   };
1413 
1414   if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1415       parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1416       parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1417     return true;
1418 
1419   if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1420       !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1421     return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1422   }
1423 
1424   if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1425       !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1426     return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1427   }
1428 
1429   if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1430       !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1431     return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1432   }
1433 
1434   auto parseAndCheckArgument = [&](const Optional<yaml::SIArgument> &A,
1435                                    const TargetRegisterClass &RC,
1436                                    ArgDescriptor &Arg, unsigned UserSGPRs,
1437                                    unsigned SystemSGPRs) {
1438     // Skip parsing if it's not present.
1439     if (!A)
1440       return false;
1441 
1442     if (A->IsRegister) {
1443       Register Reg;
1444       if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
1445         SourceRange = A->RegisterName.SourceRange;
1446         return true;
1447       }
1448       if (!RC.contains(Reg))
1449         return diagnoseRegisterClass(A->RegisterName);
1450       Arg = ArgDescriptor::createRegister(Reg);
1451     } else
1452       Arg = ArgDescriptor::createStack(A->StackOffset);
1453     // Check and apply the optional mask.
1454     if (A->Mask)
1455       Arg = ArgDescriptor::createArg(Arg, A->Mask.getValue());
1456 
1457     MFI->NumUserSGPRs += UserSGPRs;
1458     MFI->NumSystemSGPRs += SystemSGPRs;
1459     return false;
1460   };
1461 
1462   if (YamlMFI.ArgInfo &&
1463       (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
1464                              AMDGPU::SGPR_128RegClass,
1465                              MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
1466        parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
1467                              AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
1468                              2, 0) ||
1469        parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
1470                              MFI->ArgInfo.QueuePtr, 2, 0) ||
1471        parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
1472                              AMDGPU::SReg_64RegClass,
1473                              MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
1474        parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
1475                              AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
1476                              2, 0) ||
1477        parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
1478                              AMDGPU::SReg_64RegClass,
1479                              MFI->ArgInfo.FlatScratchInit, 2, 0) ||
1480        parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
1481                              AMDGPU::SGPR_32RegClass,
1482                              MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
1483        parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
1484                              AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
1485                              0, 1) ||
1486        parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
1487                              AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
1488                              0, 1) ||
1489        parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
1490                              AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
1491                              0, 1) ||
1492        parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
1493                              AMDGPU::SGPR_32RegClass,
1494                              MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
1495        parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
1496                              AMDGPU::SGPR_32RegClass,
1497                              MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
1498        parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
1499                              AMDGPU::SReg_64RegClass,
1500                              MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
1501        parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
1502                              AMDGPU::SReg_64RegClass,
1503                              MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
1504        parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
1505                              AMDGPU::VGPR_32RegClass,
1506                              MFI->ArgInfo.WorkItemIDX, 0, 0) ||
1507        parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
1508                              AMDGPU::VGPR_32RegClass,
1509                              MFI->ArgInfo.WorkItemIDY, 0, 0) ||
1510        parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
1511                              AMDGPU::VGPR_32RegClass,
1512                              MFI->ArgInfo.WorkItemIDZ, 0, 0)))
1513     return true;
1514 
1515   MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
1516   MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
1517   MFI->Mode.FP32InputDenormals = YamlMFI.Mode.FP32InputDenormals;
1518   MFI->Mode.FP32OutputDenormals = YamlMFI.Mode.FP32OutputDenormals;
1519   MFI->Mode.FP64FP16InputDenormals = YamlMFI.Mode.FP64FP16InputDenormals;
1520   MFI->Mode.FP64FP16OutputDenormals = YamlMFI.Mode.FP64FP16OutputDenormals;
1521 
1522   return false;
1523 }
1524