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