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