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 "AMDGPUCallLowering.h"
19 #include "AMDGPUInstructionSelector.h"
20 #include "AMDGPULegalizerInfo.h"
21 #include "AMDGPUMacroFusion.h"
22 #include "AMDGPUTargetObjectFile.h"
23 #include "AMDGPUTargetTransformInfo.h"
24 #include "GCNIterativeScheduler.h"
25 #include "GCNSchedStrategy.h"
26 #include "R600MachineScheduler.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIMachineScheduler.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/RegBankSelect.h"
33 #include "llvm/CodeGen/MIRParser/MIParser.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/TargetPassConfig.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/LegacyPassManager.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Transforms/IPO.h"
45 #include "llvm/Transforms/IPO/AlwaysInliner.h"
46 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Transforms/Scalar/GVN.h"
49 #include "llvm/Transforms/Utils.h"
50 #include "llvm/Transforms/Vectorize.h"
51 #include <memory>
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> EnableR600IfConvert(
72   "r600-if-convert",
73   cl::desc("Use if conversion pass"),
74   cl::ReallyHidden,
75   cl::init(true));
76 
77 // Option to disable vectorizer for tests.
78 static cl::opt<bool> EnableLoadStoreVectorizer(
79   "amdgpu-load-store-vectorizer",
80   cl::desc("Enable load store vectorizer"),
81   cl::init(true),
82   cl::Hidden);
83 
84 // Option to control global loads scalarization
85 static cl::opt<bool> ScalarizeGlobal(
86   "amdgpu-scalarize-global-loads",
87   cl::desc("Enable global load scalarization"),
88   cl::init(true),
89   cl::Hidden);
90 
91 // Option to run internalize pass.
92 static cl::opt<bool> InternalizeSymbols(
93   "amdgpu-internalize-symbols",
94   cl::desc("Enable elimination of non-kernel functions and unused globals"),
95   cl::init(false),
96   cl::Hidden);
97 
98 // Option to inline all early.
99 static cl::opt<bool> EarlyInlineAll(
100   "amdgpu-early-inline-all",
101   cl::desc("Inline all functions early"),
102   cl::init(false),
103   cl::Hidden);
104 
105 static cl::opt<bool> EnableSDWAPeephole(
106   "amdgpu-sdwa-peephole",
107   cl::desc("Enable SDWA peepholer"),
108   cl::init(true));
109 
110 static cl::opt<bool> EnableDPPCombine(
111   "amdgpu-dpp-combine",
112   cl::desc("Enable DPP combiner"),
113   cl::init(true));
114 
115 // Enable address space based alias analysis
116 static cl::opt<bool> EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden,
117   cl::desc("Enable AMDGPU Alias Analysis"),
118   cl::init(true));
119 
120 // Option to run late CFG structurizer
121 static cl::opt<bool, true> LateCFGStructurize(
122   "amdgpu-late-structurize",
123   cl::desc("Enable late CFG structurization"),
124   cl::location(AMDGPUTargetMachine::EnableLateStructurizeCFG),
125   cl::Hidden);
126 
127 static cl::opt<bool, true> EnableAMDGPUFunctionCallsOpt(
128   "amdgpu-function-calls",
129   cl::desc("Enable AMDGPU function call support"),
130   cl::location(AMDGPUTargetMachine::EnableFunctionCalls),
131   cl::init(true),
132   cl::Hidden);
133 
134 // Enable lib calls simplifications
135 static cl::opt<bool> EnableLibCallSimplify(
136   "amdgpu-simplify-libcall",
137   cl::desc("Enable amdgpu library simplifications"),
138   cl::init(true),
139   cl::Hidden);
140 
141 static cl::opt<bool> EnableLowerKernelArguments(
142   "amdgpu-ir-lower-kernel-arguments",
143   cl::desc("Lower kernel argument loads in IR pass"),
144   cl::init(true),
145   cl::Hidden);
146 
147 // Enable atomic optimization
148 static cl::opt<bool> EnableAtomicOptimizations(
149   "amdgpu-atomic-optimizations",
150   cl::desc("Enable atomic optimizations"),
151   cl::init(false),
152   cl::Hidden);
153 
154 // Enable Mode register optimization
155 static cl::opt<bool> EnableSIModeRegisterPass(
156   "amdgpu-mode-register",
157   cl::desc("Enable mode register pass"),
158   cl::init(true),
159   cl::Hidden);
160 
161 extern "C" void LLVMInitializeAMDGPUTarget() {
162   // Register the target
163   RegisterTargetMachine<R600TargetMachine> X(getTheAMDGPUTarget());
164   RegisterTargetMachine<GCNTargetMachine> Y(getTheGCNTarget());
165 
166   PassRegistry *PR = PassRegistry::getPassRegistry();
167   initializeR600ClauseMergePassPass(*PR);
168   initializeR600ControlFlowFinalizerPass(*PR);
169   initializeR600PacketizerPass(*PR);
170   initializeR600ExpandSpecialInstrsPassPass(*PR);
171   initializeR600VectorRegMergerPass(*PR);
172   initializeGlobalISel(*PR);
173   initializeAMDGPUDAGToDAGISelPass(*PR);
174   initializeGCNDPPCombinePass(*PR);
175   initializeSILowerI1CopiesPass(*PR);
176   initializeSIFixSGPRCopiesPass(*PR);
177   initializeSIFixVGPRCopiesPass(*PR);
178   initializeSIFixupVectorISelPass(*PR);
179   initializeSIFoldOperandsPass(*PR);
180   initializeSIPeepholeSDWAPass(*PR);
181   initializeSIShrinkInstructionsPass(*PR);
182   initializeSIOptimizeExecMaskingPreRAPass(*PR);
183   initializeSILoadStoreOptimizerPass(*PR);
184   initializeAMDGPUFixFunctionBitcastsPass(*PR);
185   initializeAMDGPUAlwaysInlinePass(*PR);
186   initializeAMDGPUAnnotateKernelFeaturesPass(*PR);
187   initializeAMDGPUAnnotateUniformValuesPass(*PR);
188   initializeAMDGPUArgumentUsageInfoPass(*PR);
189   initializeAMDGPUAtomicOptimizerPass(*PR);
190   initializeAMDGPULowerKernelArgumentsPass(*PR);
191   initializeAMDGPULowerKernelAttributesPass(*PR);
192   initializeAMDGPULowerIntrinsicsPass(*PR);
193   initializeAMDGPUOpenCLEnqueuedBlockLoweringPass(*PR);
194   initializeAMDGPUPromoteAllocaPass(*PR);
195   initializeAMDGPUCodeGenPreparePass(*PR);
196   initializeAMDGPURewriteOutArgumentsPass(*PR);
197   initializeAMDGPUUnifyMetadataPass(*PR);
198   initializeSIAnnotateControlFlowPass(*PR);
199   initializeSIInsertWaitcntsPass(*PR);
200   initializeSIModeRegisterPass(*PR);
201   initializeSIWholeQuadModePass(*PR);
202   initializeSILowerControlFlowPass(*PR);
203   initializeSIInsertSkipsPass(*PR);
204   initializeSIMemoryLegalizerPass(*PR);
205   initializeSIOptimizeExecMaskingPass(*PR);
206   initializeSIFixWWMLivenessPass(*PR);
207   initializeSIFormMemoryClausesPass(*PR);
208   initializeAMDGPUUnifyDivergentExitNodesPass(*PR);
209   initializeAMDGPUAAWrapperPassPass(*PR);
210   initializeAMDGPUExternalAAWrapperPass(*PR);
211   initializeAMDGPUUseNativeCallsPass(*PR);
212   initializeAMDGPUSimplifyLibCallsPass(*PR);
213   initializeAMDGPUInlinerPass(*PR);
214 }
215 
216 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
217   return llvm::make_unique<AMDGPUTargetObjectFile>();
218 }
219 
220 static ScheduleDAGInstrs *createR600MachineScheduler(MachineSchedContext *C) {
221   return new ScheduleDAGMILive(C, llvm::make_unique<R600SchedStrategy>());
222 }
223 
224 static ScheduleDAGInstrs *createSIMachineScheduler(MachineSchedContext *C) {
225   return new SIScheduleDAGMI(C);
226 }
227 
228 static ScheduleDAGInstrs *
229 createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
230   ScheduleDAGMILive *DAG =
231     new GCNScheduleDAGMILive(C, make_unique<GCNMaxOccupancySchedStrategy>(C));
232   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
233   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
234   DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
235   return DAG;
236 }
237 
238 static ScheduleDAGInstrs *
239 createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
240   auto DAG = new GCNIterativeScheduler(C,
241     GCNIterativeScheduler::SCHEDULE_LEGACYMAXOCCUPANCY);
242   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
243   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
244   return DAG;
245 }
246 
247 static ScheduleDAGInstrs *createMinRegScheduler(MachineSchedContext *C) {
248   return new GCNIterativeScheduler(C,
249     GCNIterativeScheduler::SCHEDULE_MINREGFORCED);
250 }
251 
252 static ScheduleDAGInstrs *
253 createIterativeILPMachineScheduler(MachineSchedContext *C) {
254   auto DAG = new GCNIterativeScheduler(C,
255     GCNIterativeScheduler::SCHEDULE_ILP);
256   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
257   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
258   DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
259   return DAG;
260 }
261 
262 static MachineSchedRegistry
263 R600SchedRegistry("r600", "Run R600's custom scheduler",
264                    createR600MachineScheduler);
265 
266 static MachineSchedRegistry
267 SISchedRegistry("si", "Run SI's custom scheduler",
268                 createSIMachineScheduler);
269 
270 static MachineSchedRegistry
271 GCNMaxOccupancySchedRegistry("gcn-max-occupancy",
272                              "Run GCN scheduler to maximize occupancy",
273                              createGCNMaxOccupancyMachineScheduler);
274 
275 static MachineSchedRegistry
276 IterativeGCNMaxOccupancySchedRegistry("gcn-max-occupancy-experimental",
277   "Run GCN scheduler to maximize occupancy (experimental)",
278   createIterativeGCNMaxOccupancyMachineScheduler);
279 
280 static MachineSchedRegistry
281 GCNMinRegSchedRegistry("gcn-minreg",
282   "Run GCN iterative scheduler for minimal register usage (experimental)",
283   createMinRegScheduler);
284 
285 static MachineSchedRegistry
286 GCNILPSchedRegistry("gcn-ilp",
287   "Run GCN iterative scheduler for ILP scheduling (experimental)",
288   createIterativeILPMachineScheduler);
289 
290 static StringRef computeDataLayout(const Triple &TT) {
291   if (TT.getArch() == Triple::r600) {
292     // 32-bit pointers.
293       return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
294              "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5";
295   }
296 
297   // 32-bit private, local, and region pointers. 64-bit global, constant and
298   // flat, non-integral buffer fat pointers.
299     return "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
300          "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
301          "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5"
302          "-ni:7";
303 }
304 
305 LLVM_READNONE
306 static StringRef getGPUOrDefault(const Triple &TT, StringRef GPU) {
307   if (!GPU.empty())
308     return GPU;
309 
310   // Need to default to a target with flat support for HSA.
311   if (TT.getArch() == Triple::amdgcn)
312     return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
313 
314   return "r600";
315 }
316 
317 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
318   // The AMDGPU toolchain only supports generating shared objects, so we
319   // must always use PIC.
320   return Reloc::PIC_;
321 }
322 
323 AMDGPUTargetMachine::AMDGPUTargetMachine(const Target &T, const Triple &TT,
324                                          StringRef CPU, StringRef FS,
325                                          TargetOptions Options,
326                                          Optional<Reloc::Model> RM,
327                                          Optional<CodeModel::Model> CM,
328                                          CodeGenOpt::Level OptLevel)
329     : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU),
330                         FS, Options, getEffectiveRelocModel(RM),
331                         getEffectiveCodeModel(CM, CodeModel::Small), OptLevel),
332       TLOF(createTLOF(getTargetTriple())) {
333   initAsmInfo();
334 }
335 
336 bool AMDGPUTargetMachine::EnableLateStructurizeCFG = false;
337 bool AMDGPUTargetMachine::EnableFunctionCalls = false;
338 
339 AMDGPUTargetMachine::~AMDGPUTargetMachine() = default;
340 
341 StringRef AMDGPUTargetMachine::getGPUName(const Function &F) const {
342   Attribute GPUAttr = F.getFnAttribute("target-cpu");
343   return GPUAttr.hasAttribute(Attribute::None) ?
344     getTargetCPU() : GPUAttr.getValueAsString();
345 }
346 
347 StringRef AMDGPUTargetMachine::getFeatureString(const Function &F) const {
348   Attribute FSAttr = F.getFnAttribute("target-features");
349 
350   return FSAttr.hasAttribute(Attribute::None) ?
351     getTargetFeatureString() :
352     FSAttr.getValueAsString();
353 }
354 
355 /// Predicate for Internalize pass.
356 static bool mustPreserveGV(const GlobalValue &GV) {
357   if (const Function *F = dyn_cast<Function>(&GV))
358     return F->isDeclaration() || AMDGPU::isEntryFunctionCC(F->getCallingConv());
359 
360   return !GV.use_empty();
361 }
362 
363 void AMDGPUTargetMachine::adjustPassManager(PassManagerBuilder &Builder) {
364   Builder.DivergentTarget = true;
365 
366   bool EnableOpt = getOptLevel() > CodeGenOpt::None;
367   bool Internalize = InternalizeSymbols;
368   bool EarlyInline = EarlyInlineAll && EnableOpt && !EnableFunctionCalls;
369   bool AMDGPUAA = EnableAMDGPUAliasAnalysis && EnableOpt;
370   bool LibCallSimplify = EnableLibCallSimplify && EnableOpt;
371 
372   if (EnableFunctionCalls) {
373     delete Builder.Inliner;
374     Builder.Inliner = createAMDGPUFunctionInliningPass();
375   }
376 
377   Builder.addExtension(
378     PassManagerBuilder::EP_ModuleOptimizerEarly,
379     [Internalize, EarlyInline, AMDGPUAA](const PassManagerBuilder &,
380                                          legacy::PassManagerBase &PM) {
381       if (AMDGPUAA) {
382         PM.add(createAMDGPUAAWrapperPass());
383         PM.add(createAMDGPUExternalAAWrapperPass());
384       }
385       PM.add(createAMDGPUUnifyMetadataPass());
386       if (Internalize) {
387         PM.add(createInternalizePass(mustPreserveGV));
388         PM.add(createGlobalDCEPass());
389       }
390       if (EarlyInline)
391         PM.add(createAMDGPUAlwaysInlinePass(false));
392   });
393 
394   const auto &Opt = Options;
395   Builder.addExtension(
396     PassManagerBuilder::EP_EarlyAsPossible,
397     [AMDGPUAA, LibCallSimplify, &Opt](const PassManagerBuilder &,
398                                       legacy::PassManagerBase &PM) {
399       if (AMDGPUAA) {
400         PM.add(createAMDGPUAAWrapperPass());
401         PM.add(createAMDGPUExternalAAWrapperPass());
402       }
403       PM.add(llvm::createAMDGPUUseNativeCallsPass());
404       if (LibCallSimplify)
405         PM.add(llvm::createAMDGPUSimplifyLibCallsPass(Opt));
406   });
407 
408   Builder.addExtension(
409     PassManagerBuilder::EP_CGSCCOptimizerLate,
410     [](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
411       // Add infer address spaces pass to the opt pipeline after inlining
412       // but before SROA to increase SROA opportunities.
413       PM.add(createInferAddressSpacesPass());
414 
415       // This should run after inlining to have any chance of doing anything,
416       // and before other cleanup optimizations.
417       PM.add(createAMDGPULowerKernelAttributesPass());
418   });
419 }
420 
421 //===----------------------------------------------------------------------===//
422 // R600 Target Machine (R600 -> Cayman)
423 //===----------------------------------------------------------------------===//
424 
425 R600TargetMachine::R600TargetMachine(const Target &T, const Triple &TT,
426                                      StringRef CPU, StringRef FS,
427                                      TargetOptions Options,
428                                      Optional<Reloc::Model> RM,
429                                      Optional<CodeModel::Model> CM,
430                                      CodeGenOpt::Level OL, bool JIT)
431     : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
432   setRequiresStructuredCFG(true);
433 
434   // Override the default since calls aren't supported for r600.
435   if (EnableFunctionCalls &&
436       EnableAMDGPUFunctionCallsOpt.getNumOccurrences() == 0)
437     EnableFunctionCalls = false;
438 }
439 
440 const R600Subtarget *R600TargetMachine::getSubtargetImpl(
441   const Function &F) const {
442   StringRef GPU = getGPUName(F);
443   StringRef FS = getFeatureString(F);
444 
445   SmallString<128> SubtargetKey(GPU);
446   SubtargetKey.append(FS);
447 
448   auto &I = SubtargetMap[SubtargetKey];
449   if (!I) {
450     // This needs to be done before we create a new subtarget since any
451     // creation will depend on the TM and the code generation flags on the
452     // function that reside in TargetOptions.
453     resetTargetOptions(F);
454     I = llvm::make_unique<R600Subtarget>(TargetTriple, GPU, FS, *this);
455   }
456 
457   return I.get();
458 }
459 
460 TargetTransformInfo
461 R600TargetMachine::getTargetTransformInfo(const Function &F) {
462   return TargetTransformInfo(R600TTIImpl(this, F));
463 }
464 
465 //===----------------------------------------------------------------------===//
466 // GCN Target Machine (SI+)
467 //===----------------------------------------------------------------------===//
468 
469 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT,
470                                    StringRef CPU, StringRef FS,
471                                    TargetOptions Options,
472                                    Optional<Reloc::Model> RM,
473                                    Optional<CodeModel::Model> CM,
474                                    CodeGenOpt::Level OL, bool JIT)
475     : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
476 
477 const GCNSubtarget *GCNTargetMachine::getSubtargetImpl(const Function &F) const {
478   StringRef GPU = getGPUName(F);
479   StringRef FS = getFeatureString(F);
480 
481   SmallString<128> SubtargetKey(GPU);
482   SubtargetKey.append(FS);
483 
484   auto &I = SubtargetMap[SubtargetKey];
485   if (!I) {
486     // This needs to be done before we create a new subtarget since any
487     // creation will depend on the TM and the code generation flags on the
488     // function that reside in TargetOptions.
489     resetTargetOptions(F);
490     I = llvm::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
491   }
492 
493   I->setScalarizeGlobalBehavior(ScalarizeGlobal);
494 
495   return I.get();
496 }
497 
498 TargetTransformInfo
499 GCNTargetMachine::getTargetTransformInfo(const Function &F) {
500   return TargetTransformInfo(GCNTTIImpl(this, F));
501 }
502 
503 //===----------------------------------------------------------------------===//
504 // AMDGPU Pass Setup
505 //===----------------------------------------------------------------------===//
506 
507 namespace {
508 
509 class AMDGPUPassConfig : public TargetPassConfig {
510 public:
511   AMDGPUPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
512     : TargetPassConfig(TM, PM) {
513     // Exceptions and StackMaps are not supported, so these passes will never do
514     // anything.
515     disablePass(&StackMapLivenessID);
516     disablePass(&FuncletLayoutID);
517   }
518 
519   AMDGPUTargetMachine &getAMDGPUTargetMachine() const {
520     return getTM<AMDGPUTargetMachine>();
521   }
522 
523   ScheduleDAGInstrs *
524   createMachineScheduler(MachineSchedContext *C) const override {
525     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
526     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
527     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
528     return DAG;
529   }
530 
531   void addEarlyCSEOrGVNPass();
532   void addStraightLineScalarOptimizationPasses();
533   void addIRPasses() override;
534   void addCodeGenPrepare() override;
535   bool addPreISel() override;
536   bool addInstSelector() override;
537   bool addGCPasses() override;
538 };
539 
540 class R600PassConfig final : public AMDGPUPassConfig {
541 public:
542   R600PassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
543     : AMDGPUPassConfig(TM, PM) {}
544 
545   ScheduleDAGInstrs *createMachineScheduler(
546     MachineSchedContext *C) const override {
547     return createR600MachineScheduler(C);
548   }
549 
550   bool addPreISel() override;
551   bool addInstSelector() override;
552   void addPreRegAlloc() override;
553   void addPreSched2() override;
554   void addPreEmitPass() override;
555 };
556 
557 class GCNPassConfig final : public AMDGPUPassConfig {
558 public:
559   GCNPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
560     : AMDGPUPassConfig(TM, PM) {
561     // It is necessary to know the register usage of the entire call graph.  We
562     // allow calls without EnableAMDGPUFunctionCalls if they are marked
563     // noinline, so this is always required.
564     setRequiresCodeGenSCCOrder(true);
565   }
566 
567   GCNTargetMachine &getGCNTargetMachine() const {
568     return getTM<GCNTargetMachine>();
569   }
570 
571   ScheduleDAGInstrs *
572   createMachineScheduler(MachineSchedContext *C) const override;
573 
574   bool addPreISel() override;
575   void addMachineSSAOptimization() override;
576   bool addILPOpts() override;
577   bool addInstSelector() override;
578   bool addIRTranslator() override;
579   bool addLegalizeMachineIR() override;
580   bool addRegBankSelect() override;
581   bool addGlobalInstructionSelect() override;
582   void addFastRegAlloc() override;
583   void addOptimizedRegAlloc() override;
584   void addPreRegAlloc() override;
585   void addPostRegAlloc() override;
586   void addPreSched2() override;
587   void addPreEmitPass() override;
588 };
589 
590 } // end anonymous namespace
591 
592 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() {
593   if (getOptLevel() == CodeGenOpt::Aggressive)
594     addPass(createGVNPass());
595   else
596     addPass(createEarlyCSEPass());
597 }
598 
599 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() {
600   addPass(createLICMPass());
601   addPass(createSeparateConstOffsetFromGEPPass());
602   addPass(createSpeculativeExecutionPass());
603   // ReassociateGEPs exposes more opportunites for SLSR. See
604   // the example in reassociate-geps-and-slsr.ll.
605   addPass(createStraightLineStrengthReducePass());
606   // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
607   // EarlyCSE can reuse.
608   addEarlyCSEOrGVNPass();
609   // Run NaryReassociate after EarlyCSE/GVN to be more effective.
610   addPass(createNaryReassociatePass());
611   // NaryReassociate on GEPs creates redundant common expressions, so run
612   // EarlyCSE after it.
613   addPass(createEarlyCSEPass());
614 }
615 
616 void AMDGPUPassConfig::addIRPasses() {
617   const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine();
618 
619   // There is no reason to run these.
620   disablePass(&StackMapLivenessID);
621   disablePass(&FuncletLayoutID);
622   disablePass(&PatchableFunctionID);
623 
624   addPass(createAtomicExpandPass());
625 
626   // This must occur before inlining, as the inliner will not look through
627   // bitcast calls.
628   addPass(createAMDGPUFixFunctionBitcastsPass());
629 
630   addPass(createAMDGPULowerIntrinsicsPass());
631 
632   // Function calls are not supported, so make sure we inline everything.
633   addPass(createAMDGPUAlwaysInlinePass());
634   addPass(createAlwaysInlinerLegacyPass());
635   // We need to add the barrier noop pass, otherwise adding the function
636   // inlining pass will cause all of the PassConfigs passes to be run
637   // one function at a time, which means if we have a nodule with two
638   // functions, then we will generate code for the first function
639   // without ever running any passes on the second.
640   addPass(createBarrierNoopPass());
641 
642   if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
643     // TODO: May want to move later or split into an early and late one.
644 
645     addPass(createAMDGPUCodeGenPreparePass());
646   }
647 
648   // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
649   if (TM.getTargetTriple().getArch() == Triple::r600)
650     addPass(createR600OpenCLImageTypeLoweringPass());
651 
652   // Replace OpenCL enqueued block function pointers with global variables.
653   addPass(createAMDGPUOpenCLEnqueuedBlockLoweringPass());
654 
655   if (TM.getOptLevel() > CodeGenOpt::None) {
656     addPass(createInferAddressSpacesPass());
657     addPass(createAMDGPUPromoteAlloca());
658 
659     if (EnableSROA)
660       addPass(createSROAPass());
661 
662     addStraightLineScalarOptimizationPasses();
663 
664     if (EnableAMDGPUAliasAnalysis) {
665       addPass(createAMDGPUAAWrapperPass());
666       addPass(createExternalAAWrapperPass([](Pass &P, Function &,
667                                              AAResults &AAR) {
668         if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
669           AAR.addAAResult(WrapperPass->getResult());
670         }));
671     }
672   }
673 
674   TargetPassConfig::addIRPasses();
675 
676   // EarlyCSE is not always strong enough to clean up what LSR produces. For
677   // example, GVN can combine
678   //
679   //   %0 = add %a, %b
680   //   %1 = add %b, %a
681   //
682   // and
683   //
684   //   %0 = shl nsw %a, 2
685   //   %1 = shl %a, 2
686   //
687   // but EarlyCSE can do neither of them.
688   if (getOptLevel() != CodeGenOpt::None)
689     addEarlyCSEOrGVNPass();
690 }
691 
692 void AMDGPUPassConfig::addCodeGenPrepare() {
693   if (TM->getTargetTriple().getArch() == Triple::amdgcn)
694     addPass(createAMDGPUAnnotateKernelFeaturesPass());
695 
696   if (TM->getTargetTriple().getArch() == Triple::amdgcn &&
697       EnableLowerKernelArguments)
698     addPass(createAMDGPULowerKernelArgumentsPass());
699 
700   TargetPassConfig::addCodeGenPrepare();
701 
702   if (EnableLoadStoreVectorizer)
703     addPass(createLoadStoreVectorizerPass());
704 }
705 
706 bool AMDGPUPassConfig::addPreISel() {
707   addPass(createLowerSwitchPass());
708   addPass(createFlattenCFGPass());
709   return false;
710 }
711 
712 bool AMDGPUPassConfig::addInstSelector() {
713   addPass(createAMDGPUISelDag(&getAMDGPUTargetMachine(), getOptLevel()));
714   return false;
715 }
716 
717 bool AMDGPUPassConfig::addGCPasses() {
718   // Do nothing. GC is not supported.
719   return false;
720 }
721 
722 //===----------------------------------------------------------------------===//
723 // R600 Pass Setup
724 //===----------------------------------------------------------------------===//
725 
726 bool R600PassConfig::addPreISel() {
727   AMDGPUPassConfig::addPreISel();
728 
729   if (EnableR600StructurizeCFG)
730     addPass(createStructurizeCFGPass());
731   return false;
732 }
733 
734 bool R600PassConfig::addInstSelector() {
735   addPass(createR600ISelDag(&getAMDGPUTargetMachine(), getOptLevel()));
736   return false;
737 }
738 
739 void R600PassConfig::addPreRegAlloc() {
740   addPass(createR600VectorRegMerger());
741 }
742 
743 void R600PassConfig::addPreSched2() {
744   addPass(createR600EmitClauseMarkers(), false);
745   if (EnableR600IfConvert)
746     addPass(&IfConverterID, false);
747   addPass(createR600ClauseMergePass(), false);
748 }
749 
750 void R600PassConfig::addPreEmitPass() {
751   addPass(createAMDGPUCFGStructurizerPass(), false);
752   addPass(createR600ExpandSpecialInstrsPass(), false);
753   addPass(&FinalizeMachineBundlesID, false);
754   addPass(createR600Packetizer(), false);
755   addPass(createR600ControlFlowFinalizer(), false);
756 }
757 
758 TargetPassConfig *R600TargetMachine::createPassConfig(PassManagerBase &PM) {
759   return new R600PassConfig(*this, PM);
760 }
761 
762 //===----------------------------------------------------------------------===//
763 // GCN Pass Setup
764 //===----------------------------------------------------------------------===//
765 
766 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler(
767   MachineSchedContext *C) const {
768   const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
769   if (ST.enableSIScheduler())
770     return createSIMachineScheduler(C);
771   return createGCNMaxOccupancyMachineScheduler(C);
772 }
773 
774 bool GCNPassConfig::addPreISel() {
775   AMDGPUPassConfig::addPreISel();
776 
777   if (EnableAtomicOptimizations) {
778     addPass(createAMDGPUAtomicOptimizerPass());
779   }
780 
781   // FIXME: We need to run a pass to propagate the attributes when calls are
782   // supported.
783 
784   // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
785   // regions formed by them.
786   addPass(&AMDGPUUnifyDivergentExitNodesID);
787   if (!LateCFGStructurize) {
788     addPass(createStructurizeCFGPass(true)); // true -> SkipUniformRegions
789   }
790   addPass(createSinkingPass());
791   addPass(createAMDGPUAnnotateUniformValues());
792   if (!LateCFGStructurize) {
793     addPass(createSIAnnotateControlFlowPass());
794   }
795 
796   return false;
797 }
798 
799 void GCNPassConfig::addMachineSSAOptimization() {
800   TargetPassConfig::addMachineSSAOptimization();
801 
802   // We want to fold operands after PeepholeOptimizer has run (or as part of
803   // it), because it will eliminate extra copies making it easier to fold the
804   // real source operand. We want to eliminate dead instructions after, so that
805   // we see fewer uses of the copies. We then need to clean up the dead
806   // instructions leftover after the operands are folded as well.
807   //
808   // XXX - Can we get away without running DeadMachineInstructionElim again?
809   addPass(&SIFoldOperandsID);
810   if (EnableDPPCombine)
811     addPass(&GCNDPPCombineID);
812   addPass(&DeadMachineInstructionElimID);
813   addPass(&SILoadStoreOptimizerID);
814   if (EnableSDWAPeephole) {
815     addPass(&SIPeepholeSDWAID);
816     addPass(&EarlyMachineLICMID);
817     addPass(&MachineCSEID);
818     addPass(&SIFoldOperandsID);
819     addPass(&DeadMachineInstructionElimID);
820   }
821   addPass(createSIShrinkInstructionsPass());
822 }
823 
824 bool GCNPassConfig::addILPOpts() {
825   if (EnableEarlyIfConversion)
826     addPass(&EarlyIfConverterID);
827 
828   TargetPassConfig::addILPOpts();
829   return false;
830 }
831 
832 bool GCNPassConfig::addInstSelector() {
833   AMDGPUPassConfig::addInstSelector();
834   addPass(&SIFixSGPRCopiesID);
835   addPass(createSILowerI1CopiesPass());
836   addPass(createSIFixupVectorISelPass());
837   addPass(createSIAddIMGInitPass());
838   return false;
839 }
840 
841 bool GCNPassConfig::addIRTranslator() {
842   addPass(new IRTranslator());
843   return false;
844 }
845 
846 bool GCNPassConfig::addLegalizeMachineIR() {
847   addPass(new Legalizer());
848   return false;
849 }
850 
851 bool GCNPassConfig::addRegBankSelect() {
852   addPass(new RegBankSelect());
853   return false;
854 }
855 
856 bool GCNPassConfig::addGlobalInstructionSelect() {
857   addPass(new InstructionSelect());
858   return false;
859 }
860 
861 void GCNPassConfig::addPreRegAlloc() {
862   if (LateCFGStructurize) {
863     addPass(createAMDGPUMachineCFGStructurizerPass());
864   }
865   addPass(createSIWholeQuadModePass());
866 }
867 
868 void GCNPassConfig::addFastRegAlloc() {
869   // FIXME: We have to disable the verifier here because of PHIElimination +
870   // TwoAddressInstructions disabling it.
871 
872   // This must be run immediately after phi elimination and before
873   // TwoAddressInstructions, otherwise the processing of the tied operand of
874   // SI_ELSE will introduce a copy of the tied operand source after the else.
875   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
876 
877   // This must be run after SILowerControlFlow, since it needs to use the
878   // machine-level CFG, but before register allocation.
879   insertPass(&SILowerControlFlowID, &SIFixWWMLivenessID, false);
880 
881   TargetPassConfig::addFastRegAlloc();
882 }
883 
884 void GCNPassConfig::addOptimizedRegAlloc() {
885   insertPass(&MachineSchedulerID, &SIOptimizeExecMaskingPreRAID);
886 
887   insertPass(&SIOptimizeExecMaskingPreRAID, &SIFormMemoryClausesID);
888 
889   // This must be run immediately after phi elimination and before
890   // TwoAddressInstructions, otherwise the processing of the tied operand of
891   // SI_ELSE will introduce a copy of the tied operand source after the else.
892   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
893 
894   // This must be run after SILowerControlFlow, since it needs to use the
895   // machine-level CFG, but before register allocation.
896   insertPass(&SILowerControlFlowID, &SIFixWWMLivenessID, false);
897 
898   TargetPassConfig::addOptimizedRegAlloc();
899 }
900 
901 void GCNPassConfig::addPostRegAlloc() {
902   addPass(&SIFixVGPRCopiesID);
903   if (getOptLevel() > CodeGenOpt::None)
904     addPass(&SIOptimizeExecMaskingID);
905   TargetPassConfig::addPostRegAlloc();
906 }
907 
908 void GCNPassConfig::addPreSched2() {
909 }
910 
911 void GCNPassConfig::addPreEmitPass() {
912   addPass(createSIMemoryLegalizerPass());
913   addPass(createSIInsertWaitcntsPass());
914   addPass(createSIShrinkInstructionsPass());
915   addPass(createSIModeRegisterPass());
916 
917   // The hazard recognizer that runs as part of the post-ra scheduler does not
918   // guarantee to be able handle all hazards correctly. This is because if there
919   // are multiple scheduling regions in a basic block, the regions are scheduled
920   // bottom up, so when we begin to schedule a region we don't know what
921   // instructions were emitted directly before it.
922   //
923   // Here we add a stand-alone hazard recognizer pass which can handle all
924   // cases.
925   //
926   // FIXME: This stand-alone pass will emit indiv. S_NOP 0, as needed. It would
927   // be better for it to emit S_NOP <N> when possible.
928   addPass(&PostRAHazardRecognizerID);
929 
930   addPass(&SIInsertSkipsPassID);
931   addPass(&BranchRelaxationPassID);
932 }
933 
934 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) {
935   return new GCNPassConfig(*this, PM);
936 }
937 
938 yaml::MachineFunctionInfo *GCNTargetMachine::createDefaultFuncInfoYAML() const {
939   return new yaml::SIMachineFunctionInfo();
940 }
941 
942 yaml::MachineFunctionInfo *
943 GCNTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
944   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
945   return new yaml::SIMachineFunctionInfo(*MFI,
946                                          *MF.getSubtarget().getRegisterInfo());
947 }
948 
949 bool GCNTargetMachine::parseMachineFunctionInfo(
950     const yaml::MachineFunctionInfo &MFI_, PerFunctionMIParsingState &PFS,
951     SMDiagnostic &Error, SMRange &SourceRange) const {
952   const yaml::SIMachineFunctionInfo &YamlMFI =
953       reinterpret_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
954   MachineFunction &MF = PFS.MF;
955   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
956 
957   MFI->initializeBaseYamlFields(YamlMFI);
958 
959   auto parseRegister = [&](const yaml::StringValue &RegName, unsigned &RegVal) {
960     if (parseNamedRegisterReference(PFS, RegVal, RegName.Value, Error)) {
961       SourceRange = RegName.SourceRange;
962       return true;
963     }
964 
965     return false;
966   };
967 
968   auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
969     // Create a diagnostic for a the register string literal.
970     const MemoryBuffer &Buffer =
971         *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
972     Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
973                          RegName.Value.size(), SourceMgr::DK_Error,
974                          "incorrect register class for field", RegName.Value,
975                          None, None);
976     SourceRange = RegName.SourceRange;
977     return true;
978   };
979 
980   if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
981       parseRegister(YamlMFI.ScratchWaveOffsetReg, MFI->ScratchWaveOffsetReg) ||
982       parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
983       parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
984     return true;
985 
986   if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
987       !AMDGPU::SReg_128RegClass.contains(MFI->ScratchRSrcReg)) {
988     return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
989   }
990 
991   if (MFI->ScratchWaveOffsetReg != AMDGPU::SCRATCH_WAVE_OFFSET_REG &&
992       !AMDGPU::SGPR_32RegClass.contains(MFI->ScratchWaveOffsetReg)) {
993     return diagnoseRegisterClass(YamlMFI.ScratchWaveOffsetReg);
994   }
995 
996   if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
997       !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
998     return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
999   }
1000 
1001   if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1002       !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1003     return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1004   }
1005 
1006   return false;
1007 }
1008