1 //===-- AMDGPUTargetMachine.cpp - TargetMachine for hw codegen targets-----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief The AMDGPU target machine contains all of the hardware specific
12 /// information  needed to emit code for R600 and SI GPUs.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPUTargetMachine.h"
17 #include "AMDGPU.h"
18 #include "AMDGPUAliasAnalysis.h"
19 #include "AMDGPUCallLowering.h"
20 #include "AMDGPUInstructionSelector.h"
21 #include "AMDGPULegalizerInfo.h"
22 #ifdef LLVM_BUILD_GLOBAL_ISEL
23 #include "AMDGPURegisterBankInfo.h"
24 #endif
25 #include "AMDGPUTargetObjectFile.h"
26 #include "AMDGPUTargetTransformInfo.h"
27 #include "GCNIterativeScheduler.h"
28 #include "GCNSchedStrategy.h"
29 #include "R600MachineScheduler.h"
30 #include "SIMachineScheduler.h"
31 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
32 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
33 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
34 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/TargetPassConfig.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Transforms/IPO.h"
39 #include "llvm/Transforms/IPO/AlwaysInliner.h"
40 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Transforms/Scalar/GVN.h"
43 #include "llvm/Transforms/Vectorize.h"
44 #include "llvm/IR/Attributes.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/LegacyPassManager.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Target/TargetLoweringObjectFile.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 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(false),
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 // Enable address space based alias analysis
111 static cl::opt<bool> EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden,
112   cl::desc("Enable AMDGPU Alias Analysis"),
113   cl::init(true));
114 
115 extern "C" void LLVMInitializeAMDGPUTarget() {
116   // Register the target
117   RegisterTargetMachine<R600TargetMachine> X(getTheAMDGPUTarget());
118   RegisterTargetMachine<GCNTargetMachine> Y(getTheGCNTarget());
119 
120   PassRegistry *PR = PassRegistry::getPassRegistry();
121   initializeSILowerI1CopiesPass(*PR);
122   initializeSIFixSGPRCopiesPass(*PR);
123   initializeSIFixVGPRCopiesPass(*PR);
124   initializeSIFoldOperandsPass(*PR);
125   initializeSIPeepholeSDWAPass(*PR);
126   initializeSIShrinkInstructionsPass(*PR);
127   initializeSIFixControlFlowLiveIntervalsPass(*PR);
128   initializeSILoadStoreOptimizerPass(*PR);
129   initializeAMDGPUAnnotateKernelFeaturesPass(*PR);
130   initializeAMDGPUAnnotateUniformValuesPass(*PR);
131   initializeAMDGPULowerIntrinsicsPass(*PR);
132   initializeAMDGPUPromoteAllocaPass(*PR);
133   initializeAMDGPUCodeGenPreparePass(*PR);
134   initializeAMDGPUUnifyMetadataPass(*PR);
135   initializeSIAnnotateControlFlowPass(*PR);
136   initializeSIInsertWaitsPass(*PR);
137   initializeSIWholeQuadModePass(*PR);
138   initializeSILowerControlFlowPass(*PR);
139   initializeSIInsertSkipsPass(*PR);
140   initializeSIDebuggerInsertNopsPass(*PR);
141   initializeSIOptimizeExecMaskingPass(*PR);
142   initializeAMDGPUUnifyDivergentExitNodesPass(*PR);
143   initializeAMDGPUAAWrapperPassPass(*PR);
144 }
145 
146 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
147   return llvm::make_unique<AMDGPUTargetObjectFile>();
148 }
149 
150 static ScheduleDAGInstrs *createR600MachineScheduler(MachineSchedContext *C) {
151   return new ScheduleDAGMILive(C, llvm::make_unique<R600SchedStrategy>());
152 }
153 
154 static ScheduleDAGInstrs *createSIMachineScheduler(MachineSchedContext *C) {
155   return new SIScheduleDAGMI(C);
156 }
157 
158 static ScheduleDAGInstrs *
159 createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
160   ScheduleDAGMILive *DAG =
161     new GCNScheduleDAGMILive(C, make_unique<GCNMaxOccupancySchedStrategy>(C));
162   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
163   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
164   return DAG;
165 }
166 
167 static ScheduleDAGInstrs *
168 createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
169   auto DAG = new GCNIterativeScheduler(C,
170     GCNIterativeScheduler::SCHEDULE_LEGACYMAXOCCUPANCY);
171   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
172   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
173   return DAG;
174 }
175 
176 static ScheduleDAGInstrs *createMinRegScheduler(MachineSchedContext *C) {
177   return new GCNIterativeScheduler(C,
178     GCNIterativeScheduler::SCHEDULE_MINREGFORCED);
179 }
180 
181 static MachineSchedRegistry
182 R600SchedRegistry("r600", "Run R600's custom scheduler",
183                    createR600MachineScheduler);
184 
185 static MachineSchedRegistry
186 SISchedRegistry("si", "Run SI's custom scheduler",
187                 createSIMachineScheduler);
188 
189 static MachineSchedRegistry
190 GCNMaxOccupancySchedRegistry("gcn-max-occupancy",
191                              "Run GCN scheduler to maximize occupancy",
192                              createGCNMaxOccupancyMachineScheduler);
193 
194 static MachineSchedRegistry
195 IterativeGCNMaxOccupancySchedRegistry("gcn-max-occupancy-experimental",
196   "Run GCN scheduler to maximize occupancy (experimental)",
197   createIterativeGCNMaxOccupancyMachineScheduler);
198 
199 static MachineSchedRegistry
200 GCNMinRegSchedRegistry("gcn-minreg",
201   "Run GCN iterative scheduler for minimal register usage (experimental)",
202   createMinRegScheduler);
203 
204 static StringRef computeDataLayout(const Triple &TT) {
205   if (TT.getArch() == Triple::r600) {
206     // 32-bit pointers.
207     return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
208             "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
209   }
210 
211   // 32-bit private, local, and region pointers. 64-bit global, constant and
212   // flat.
213   if (TT.getEnvironmentName() == "amdgiz" ||
214       TT.getEnvironmentName() == "amdgizcl")
215     return "e-p:64:64-p1:64:64-p2:64:64-p3:32:32-p4:32:32-p5:32:32"
216          "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
217          "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
218   return "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32"
219       "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
220       "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
221 }
222 
223 LLVM_READNONE
224 static StringRef getGPUOrDefault(const Triple &TT, StringRef GPU) {
225   if (!GPU.empty())
226     return GPU;
227 
228   // HSA only supports CI+, so change the default GPU to a CI for HSA.
229   if (TT.getArch() == Triple::amdgcn)
230     return (TT.getOS() == Triple::AMDHSA) ? "kaveri" : "tahiti";
231 
232   return "r600";
233 }
234 
235 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
236   // The AMDGPU toolchain only supports generating shared objects, so we
237   // must always use PIC.
238   return Reloc::PIC_;
239 }
240 
241 AMDGPUTargetMachine::AMDGPUTargetMachine(const Target &T, const Triple &TT,
242                                          StringRef CPU, StringRef FS,
243                                          TargetOptions Options,
244                                          Optional<Reloc::Model> RM,
245                                          CodeModel::Model CM,
246                                          CodeGenOpt::Level OptLevel)
247   : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU),
248                       FS, Options, getEffectiveRelocModel(RM), CM, OptLevel),
249     TLOF(createTLOF(getTargetTriple())) {
250   AS = AMDGPU::getAMDGPUAS(TT);
251   initAsmInfo();
252 }
253 
254 AMDGPUTargetMachine::~AMDGPUTargetMachine() = default;
255 
256 StringRef AMDGPUTargetMachine::getGPUName(const Function &F) const {
257   Attribute GPUAttr = F.getFnAttribute("target-cpu");
258   return GPUAttr.hasAttribute(Attribute::None) ?
259     getTargetCPU() : GPUAttr.getValueAsString();
260 }
261 
262 StringRef AMDGPUTargetMachine::getFeatureString(const Function &F) const {
263   Attribute FSAttr = F.getFnAttribute("target-features");
264 
265   return FSAttr.hasAttribute(Attribute::None) ?
266     getTargetFeatureString() :
267     FSAttr.getValueAsString();
268 }
269 
270 static ImmutablePass *createAMDGPUExternalAAWrapperPass() {
271   return createExternalAAWrapperPass([](Pass &P, Function &, AAResults &AAR) {
272       if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
273         AAR.addAAResult(WrapperPass->getResult());
274       });
275 }
276 
277 void AMDGPUTargetMachine::adjustPassManager(PassManagerBuilder &Builder) {
278   Builder.DivergentTarget = true;
279 
280   bool Internalize = InternalizeSymbols &&
281                      (getOptLevel() > CodeGenOpt::None) &&
282                      (getTargetTriple().getArch() == Triple::amdgcn);
283   bool EarlyInline = EarlyInlineAll &&
284                      (getOptLevel() > CodeGenOpt::None);
285   bool AMDGPUAA = EnableAMDGPUAliasAnalysis && getOptLevel() > CodeGenOpt::None;
286 
287   Builder.addExtension(
288     PassManagerBuilder::EP_ModuleOptimizerEarly,
289     [Internalize, EarlyInline, AMDGPUAA](const PassManagerBuilder &,
290                                          legacy::PassManagerBase &PM) {
291       if (AMDGPUAA) {
292         PM.add(createAMDGPUAAWrapperPass());
293         PM.add(createAMDGPUExternalAAWrapperPass());
294       }
295       PM.add(createAMDGPUUnifyMetadataPass());
296       if (Internalize) {
297         PM.add(createInternalizePass([=](const GlobalValue &GV) -> bool {
298           if (const Function *F = dyn_cast<Function>(&GV)) {
299             if (F->isDeclaration())
300                 return true;
301             switch (F->getCallingConv()) {
302             default:
303               return false;
304             case CallingConv::AMDGPU_VS:
305             case CallingConv::AMDGPU_GS:
306             case CallingConv::AMDGPU_PS:
307             case CallingConv::AMDGPU_CS:
308             case CallingConv::AMDGPU_KERNEL:
309             case CallingConv::SPIR_KERNEL:
310               return true;
311             }
312           }
313           return !GV.use_empty();
314         }));
315         PM.add(createGlobalDCEPass());
316       }
317       if (EarlyInline)
318         PM.add(createAMDGPUAlwaysInlinePass(false));
319   });
320 
321   Builder.addExtension(
322     PassManagerBuilder::EP_EarlyAsPossible,
323     [AMDGPUAA](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
324       if (AMDGPUAA) {
325         PM.add(createAMDGPUAAWrapperPass());
326         PM.add(createAMDGPUExternalAAWrapperPass());
327       }
328   });
329 }
330 
331 //===----------------------------------------------------------------------===//
332 // R600 Target Machine (R600 -> Cayman)
333 //===----------------------------------------------------------------------===//
334 
335 R600TargetMachine::R600TargetMachine(const Target &T, const Triple &TT,
336                                      StringRef CPU, StringRef FS,
337                                      TargetOptions Options,
338                                      Optional<Reloc::Model> RM,
339                                      CodeModel::Model CM, CodeGenOpt::Level OL)
340   : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
341   setRequiresStructuredCFG(true);
342 }
343 
344 const R600Subtarget *R600TargetMachine::getSubtargetImpl(
345   const Function &F) const {
346   StringRef GPU = getGPUName(F);
347   StringRef FS = getFeatureString(F);
348 
349   SmallString<128> SubtargetKey(GPU);
350   SubtargetKey.append(FS);
351 
352   auto &I = SubtargetMap[SubtargetKey];
353   if (!I) {
354     // This needs to be done before we create a new subtarget since any
355     // creation will depend on the TM and the code generation flags on the
356     // function that reside in TargetOptions.
357     resetTargetOptions(F);
358     I = llvm::make_unique<R600Subtarget>(TargetTriple, GPU, FS, *this);
359   }
360 
361   return I.get();
362 }
363 
364 //===----------------------------------------------------------------------===//
365 // GCN Target Machine (SI+)
366 //===----------------------------------------------------------------------===//
367 
368 #ifdef LLVM_BUILD_GLOBAL_ISEL
369 namespace {
370 
371 struct SIGISelActualAccessor : public GISelAccessor {
372   std::unique_ptr<AMDGPUCallLowering> CallLoweringInfo;
373   std::unique_ptr<InstructionSelector> InstSelector;
374   std::unique_ptr<LegalizerInfo> Legalizer;
375   std::unique_ptr<RegisterBankInfo> RegBankInfo;
376   const AMDGPUCallLowering *getCallLowering() const override {
377     return CallLoweringInfo.get();
378   }
379   const InstructionSelector *getInstructionSelector() const override {
380     return InstSelector.get();
381   }
382   const LegalizerInfo *getLegalizerInfo() const override {
383     return Legalizer.get();
384   }
385   const RegisterBankInfo *getRegBankInfo() const override {
386     return RegBankInfo.get();
387   }
388 };
389 
390 } // end anonymous namespace
391 #endif
392 
393 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT,
394                                    StringRef CPU, StringRef FS,
395                                    TargetOptions Options,
396                                    Optional<Reloc::Model> RM,
397                                    CodeModel::Model CM, CodeGenOpt::Level OL)
398   : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
399 
400 const SISubtarget *GCNTargetMachine::getSubtargetImpl(const Function &F) const {
401   StringRef GPU = getGPUName(F);
402   StringRef FS = getFeatureString(F);
403 
404   SmallString<128> SubtargetKey(GPU);
405   SubtargetKey.append(FS);
406 
407   auto &I = SubtargetMap[SubtargetKey];
408   if (!I) {
409     // This needs to be done before we create a new subtarget since any
410     // creation will depend on the TM and the code generation flags on the
411     // function that reside in TargetOptions.
412     resetTargetOptions(F);
413     I = llvm::make_unique<SISubtarget>(TargetTriple, GPU, FS, *this);
414 
415 #ifndef LLVM_BUILD_GLOBAL_ISEL
416     GISelAccessor *GISel = new GISelAccessor();
417 #else
418     SIGISelActualAccessor *GISel = new SIGISelActualAccessor();
419     GISel->CallLoweringInfo.reset(
420       new AMDGPUCallLowering(*I->getTargetLowering()));
421     GISel->Legalizer.reset(new AMDGPULegalizerInfo());
422 
423     GISel->RegBankInfo.reset(new AMDGPURegisterBankInfo(*I->getRegisterInfo()));
424     GISel->InstSelector.reset(new AMDGPUInstructionSelector(*I,
425 				*static_cast<AMDGPURegisterBankInfo*>(GISel->RegBankInfo.get())));
426 #endif
427 
428     I->setGISelAccessor(*GISel);
429   }
430 
431   I->setScalarizeGlobalBehavior(ScalarizeGlobal);
432 
433   return I.get();
434 }
435 
436 //===----------------------------------------------------------------------===//
437 // AMDGPU Pass Setup
438 //===----------------------------------------------------------------------===//
439 
440 namespace {
441 
442 class AMDGPUPassConfig : public TargetPassConfig {
443 public:
444   AMDGPUPassConfig(TargetMachine *TM, PassManagerBase &PM)
445     : TargetPassConfig(TM, PM) {
446     // Exceptions and StackMaps are not supported, so these passes will never do
447     // anything.
448     disablePass(&StackMapLivenessID);
449     disablePass(&FuncletLayoutID);
450   }
451 
452   AMDGPUTargetMachine &getAMDGPUTargetMachine() const {
453     return getTM<AMDGPUTargetMachine>();
454   }
455 
456   ScheduleDAGInstrs *
457   createMachineScheduler(MachineSchedContext *C) const override {
458     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
459     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
460     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
461     return DAG;
462   }
463 
464   void addEarlyCSEOrGVNPass();
465   void addStraightLineScalarOptimizationPasses();
466   void addIRPasses() override;
467   void addCodeGenPrepare() override;
468   bool addPreISel() override;
469   bool addInstSelector() override;
470   bool addGCPasses() override;
471 };
472 
473 class R600PassConfig final : public AMDGPUPassConfig {
474 public:
475   R600PassConfig(TargetMachine *TM, PassManagerBase &PM)
476     : AMDGPUPassConfig(TM, PM) {}
477 
478   ScheduleDAGInstrs *createMachineScheduler(
479     MachineSchedContext *C) const override {
480     return createR600MachineScheduler(C);
481   }
482 
483   bool addPreISel() override;
484   void addPreRegAlloc() override;
485   void addPreSched2() override;
486   void addPreEmitPass() override;
487 };
488 
489 class GCNPassConfig final : public AMDGPUPassConfig {
490 public:
491   GCNPassConfig(TargetMachine *TM, PassManagerBase &PM)
492     : AMDGPUPassConfig(TM, PM) {}
493 
494   GCNTargetMachine &getGCNTargetMachine() const {
495     return getTM<GCNTargetMachine>();
496   }
497 
498   ScheduleDAGInstrs *
499   createMachineScheduler(MachineSchedContext *C) const override;
500 
501   bool addPreISel() override;
502   void addMachineSSAOptimization() override;
503   bool addILPOpts() override;
504   bool addInstSelector() override;
505 #ifdef LLVM_BUILD_GLOBAL_ISEL
506   bool addIRTranslator() override;
507   bool addLegalizeMachineIR() override;
508   bool addRegBankSelect() override;
509   bool addGlobalInstructionSelect() override;
510 #endif
511   void addFastRegAlloc(FunctionPass *RegAllocPass) override;
512   void addOptimizedRegAlloc(FunctionPass *RegAllocPass) override;
513   void addPreRegAlloc() override;
514   void addPostRegAlloc() override;
515   void addPreSched2() override;
516   void addPreEmitPass() override;
517 };
518 
519 } // end anonymous namespace
520 
521 TargetIRAnalysis AMDGPUTargetMachine::getTargetIRAnalysis() {
522   return TargetIRAnalysis([this](const Function &F) {
523     return TargetTransformInfo(AMDGPUTTIImpl(this, F));
524   });
525 }
526 
527 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() {
528   if (getOptLevel() == CodeGenOpt::Aggressive)
529     addPass(createGVNPass());
530   else
531     addPass(createEarlyCSEPass());
532 }
533 
534 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() {
535   addPass(createSeparateConstOffsetFromGEPPass());
536   addPass(createSpeculativeExecutionPass());
537   // ReassociateGEPs exposes more opportunites for SLSR. See
538   // the example in reassociate-geps-and-slsr.ll.
539   addPass(createStraightLineStrengthReducePass());
540   // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
541   // EarlyCSE can reuse.
542   addEarlyCSEOrGVNPass();
543   // Run NaryReassociate after EarlyCSE/GVN to be more effective.
544   addPass(createNaryReassociatePass());
545   // NaryReassociate on GEPs creates redundant common expressions, so run
546   // EarlyCSE after it.
547   addPass(createEarlyCSEPass());
548 }
549 
550 void AMDGPUPassConfig::addIRPasses() {
551   // There is no reason to run these.
552   disablePass(&StackMapLivenessID);
553   disablePass(&FuncletLayoutID);
554   disablePass(&PatchableFunctionID);
555 
556   addPass(createAMDGPULowerIntrinsicsPass());
557 
558   // Function calls are not supported, so make sure we inline everything.
559   addPass(createAMDGPUAlwaysInlinePass());
560   addPass(createAlwaysInlinerLegacyPass());
561   // We need to add the barrier noop pass, otherwise adding the function
562   // inlining pass will cause all of the PassConfigs passes to be run
563   // one function at a time, which means if we have a nodule with two
564   // functions, then we will generate code for the first function
565   // without ever running any passes on the second.
566   addPass(createBarrierNoopPass());
567 
568   const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine();
569 
570   if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
571     // TODO: May want to move later or split into an early and late one.
572 
573     addPass(createAMDGPUCodeGenPreparePass(
574               static_cast<const GCNTargetMachine *>(&TM)));
575   }
576 
577   // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
578   addPass(createAMDGPUOpenCLImageTypeLoweringPass());
579 
580   if (TM.getOptLevel() > CodeGenOpt::None) {
581     addPass(createInferAddressSpacesPass());
582     addPass(createAMDGPUPromoteAlloca(&TM));
583 
584     if (EnableSROA)
585       addPass(createSROAPass());
586 
587     addStraightLineScalarOptimizationPasses();
588 
589     if (EnableAMDGPUAliasAnalysis) {
590       addPass(createAMDGPUAAWrapperPass());
591       addPass(createExternalAAWrapperPass([](Pass &P, Function &,
592                                              AAResults &AAR) {
593         if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
594           AAR.addAAResult(WrapperPass->getResult());
595         }));
596     }
597   }
598 
599   TargetPassConfig::addIRPasses();
600 
601   // EarlyCSE is not always strong enough to clean up what LSR produces. For
602   // example, GVN can combine
603   //
604   //   %0 = add %a, %b
605   //   %1 = add %b, %a
606   //
607   // and
608   //
609   //   %0 = shl nsw %a, 2
610   //   %1 = shl %a, 2
611   //
612   // but EarlyCSE can do neither of them.
613   if (getOptLevel() != CodeGenOpt::None)
614     addEarlyCSEOrGVNPass();
615 }
616 
617 void AMDGPUPassConfig::addCodeGenPrepare() {
618   TargetPassConfig::addCodeGenPrepare();
619 
620   if (EnableLoadStoreVectorizer)
621     addPass(createLoadStoreVectorizerPass());
622 }
623 
624 bool AMDGPUPassConfig::addPreISel() {
625   addPass(createFlattenCFGPass());
626   return false;
627 }
628 
629 bool AMDGPUPassConfig::addInstSelector() {
630   addPass(createAMDGPUISelDag(getAMDGPUTargetMachine(), getOptLevel()));
631   return false;
632 }
633 
634 bool AMDGPUPassConfig::addGCPasses() {
635   // Do nothing. GC is not supported.
636   return false;
637 }
638 
639 //===----------------------------------------------------------------------===//
640 // R600 Pass Setup
641 //===----------------------------------------------------------------------===//
642 
643 bool R600PassConfig::addPreISel() {
644   AMDGPUPassConfig::addPreISel();
645 
646   if (EnableR600StructurizeCFG)
647     addPass(createStructurizeCFGPass());
648   return false;
649 }
650 
651 void R600PassConfig::addPreRegAlloc() {
652   addPass(createR600VectorRegMerger(*TM));
653 }
654 
655 void R600PassConfig::addPreSched2() {
656   addPass(createR600EmitClauseMarkers(), false);
657   if (EnableR600IfConvert)
658     addPass(&IfConverterID, false);
659   addPass(createR600ClauseMergePass(*TM), false);
660 }
661 
662 void R600PassConfig::addPreEmitPass() {
663   addPass(createAMDGPUCFGStructurizerPass(), false);
664   addPass(createR600ExpandSpecialInstrsPass(*TM), false);
665   addPass(&FinalizeMachineBundlesID, false);
666   addPass(createR600Packetizer(*TM), false);
667   addPass(createR600ControlFlowFinalizer(*TM), false);
668 }
669 
670 TargetPassConfig *R600TargetMachine::createPassConfig(PassManagerBase &PM) {
671   return new R600PassConfig(this, PM);
672 }
673 
674 //===----------------------------------------------------------------------===//
675 // GCN Pass Setup
676 //===----------------------------------------------------------------------===//
677 
678 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler(
679   MachineSchedContext *C) const {
680   const SISubtarget &ST = C->MF->getSubtarget<SISubtarget>();
681   if (ST.enableSIScheduler())
682     return createSIMachineScheduler(C);
683   return createGCNMaxOccupancyMachineScheduler(C);
684 }
685 
686 bool GCNPassConfig::addPreISel() {
687   AMDGPUPassConfig::addPreISel();
688 
689   // FIXME: We need to run a pass to propagate the attributes when calls are
690   // supported.
691   const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine();
692   addPass(createAMDGPUAnnotateKernelFeaturesPass(&TM));
693 
694   // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
695   // regions formed by them.
696   addPass(&AMDGPUUnifyDivergentExitNodesID);
697   addPass(createStructurizeCFGPass(true)); // true -> SkipUniformRegions
698   addPass(createSinkingPass());
699   addPass(createSITypeRewriter());
700   addPass(createAMDGPUAnnotateUniformValues());
701   addPass(createSIAnnotateControlFlowPass());
702 
703   return false;
704 }
705 
706 void GCNPassConfig::addMachineSSAOptimization() {
707   TargetPassConfig::addMachineSSAOptimization();
708 
709   // We want to fold operands after PeepholeOptimizer has run (or as part of
710   // it), because it will eliminate extra copies making it easier to fold the
711   // real source operand. We want to eliminate dead instructions after, so that
712   // we see fewer uses of the copies. We then need to clean up the dead
713   // instructions leftover after the operands are folded as well.
714   //
715   // XXX - Can we get away without running DeadMachineInstructionElim again?
716   addPass(&SIFoldOperandsID);
717   addPass(&DeadMachineInstructionElimID);
718   addPass(&SILoadStoreOptimizerID);
719   addPass(createSIShrinkInstructionsPass());
720   if (EnableSDWAPeephole) {
721     addPass(&SIPeepholeSDWAID);
722     addPass(&DeadMachineInstructionElimID);
723   }
724 }
725 
726 bool GCNPassConfig::addILPOpts() {
727   if (EnableEarlyIfConversion)
728     addPass(&EarlyIfConverterID);
729 
730   TargetPassConfig::addILPOpts();
731   return false;
732 }
733 
734 bool GCNPassConfig::addInstSelector() {
735   AMDGPUPassConfig::addInstSelector();
736   addPass(createSILowerI1CopiesPass());
737   addPass(&SIFixSGPRCopiesID);
738   return false;
739 }
740 
741 #ifdef LLVM_BUILD_GLOBAL_ISEL
742 bool GCNPassConfig::addIRTranslator() {
743   addPass(new IRTranslator());
744   return false;
745 }
746 
747 bool GCNPassConfig::addLegalizeMachineIR() {
748   addPass(new Legalizer());
749   return false;
750 }
751 
752 bool GCNPassConfig::addRegBankSelect() {
753   addPass(new RegBankSelect());
754   return false;
755 }
756 
757 bool GCNPassConfig::addGlobalInstructionSelect() {
758   addPass(new InstructionSelect());
759   return false;
760 }
761 
762 #endif
763 
764 void GCNPassConfig::addPreRegAlloc() {
765   addPass(createSIWholeQuadModePass());
766 }
767 
768 void GCNPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
769   // FIXME: We have to disable the verifier here because of PHIElimination +
770   // TwoAddressInstructions disabling it.
771 
772   // This must be run immediately after phi elimination and before
773   // TwoAddressInstructions, otherwise the processing of the tied operand of
774   // SI_ELSE will introduce a copy of the tied operand source after the else.
775   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
776 
777   TargetPassConfig::addFastRegAlloc(RegAllocPass);
778 }
779 
780 void GCNPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
781   // This needs to be run directly before register allocation because earlier
782   // passes might recompute live intervals.
783   insertPass(&MachineSchedulerID, &SIFixControlFlowLiveIntervalsID);
784 
785   // This must be run immediately after phi elimination and before
786   // TwoAddressInstructions, otherwise the processing of the tied operand of
787   // SI_ELSE will introduce a copy of the tied operand source after the else.
788   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
789 
790   TargetPassConfig::addOptimizedRegAlloc(RegAllocPass);
791 }
792 
793 void GCNPassConfig::addPostRegAlloc() {
794   addPass(&SIFixVGPRCopiesID);
795   addPass(&SIOptimizeExecMaskingID);
796   TargetPassConfig::addPostRegAlloc();
797 }
798 
799 void GCNPassConfig::addPreSched2() {
800 }
801 
802 void GCNPassConfig::addPreEmitPass() {
803   // The hazard recognizer that runs as part of the post-ra scheduler does not
804   // guarantee to be able handle all hazards correctly. This is because if there
805   // are multiple scheduling regions in a basic block, the regions are scheduled
806   // bottom up, so when we begin to schedule a region we don't know what
807   // instructions were emitted directly before it.
808   //
809   // Here we add a stand-alone hazard recognizer pass which can handle all
810   // cases.
811   addPass(&PostRAHazardRecognizerID);
812 
813   addPass(createSIInsertWaitsPass());
814   addPass(createSIShrinkInstructionsPass());
815   addPass(&SIInsertSkipsPassID);
816   addPass(createSIDebuggerInsertNopsPass());
817   addPass(&BranchRelaxationPassID);
818 }
819 
820 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) {
821   return new GCNPassConfig(this, PM);
822 }
823 
824