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