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