1 //===-- AMDGPUCodeGenPrepare.cpp ------------------------------------------===// 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 /// This pass does misc. AMDGPU optimizations on IR before instruction 11 /// selection. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "AMDGPU.h" 16 #include "AMDGPUTargetMachine.h" 17 #include "llvm/Analysis/AssumptionCache.h" 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 20 #include "llvm/Analysis/ValueTracking.h" 21 #include "llvm/CodeGen/TargetPassConfig.h" 22 #include "llvm/IR/Dominators.h" 23 #include "llvm/IR/InstVisitor.h" 24 #include "llvm/IR/IntrinsicsAMDGPU.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/InitializePasses.h" 27 #include "llvm/Pass.h" 28 #include "llvm/Support/KnownBits.h" 29 #include "llvm/Transforms/Utils/IntegerDivision.h" 30 31 #define DEBUG_TYPE "amdgpu-codegenprepare" 32 33 using namespace llvm; 34 35 namespace { 36 37 static cl::opt<bool> WidenLoads( 38 "amdgpu-codegenprepare-widen-constant-loads", 39 cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"), 40 cl::ReallyHidden, 41 cl::init(false)); 42 43 static cl::opt<bool> Widen16BitOps( 44 "amdgpu-codegenprepare-widen-16-bit-ops", 45 cl::desc("Widen uniform 16-bit instructions to 32-bit in AMDGPUCodeGenPrepare"), 46 cl::ReallyHidden, 47 cl::init(true)); 48 49 static cl::opt<bool> UseMul24Intrin( 50 "amdgpu-codegenprepare-mul24", 51 cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"), 52 cl::ReallyHidden, 53 cl::init(true)); 54 55 // Legalize 64-bit division by using the generic IR expansion. 56 static cl::opt<bool> ExpandDiv64InIR( 57 "amdgpu-codegenprepare-expand-div64", 58 cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"), 59 cl::ReallyHidden, 60 cl::init(false)); 61 62 // Leave all division operations as they are. This supersedes ExpandDiv64InIR 63 // and is used for testing the legalizer. 64 static cl::opt<bool> DisableIDivExpand( 65 "amdgpu-codegenprepare-disable-idiv-expansion", 66 cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"), 67 cl::ReallyHidden, 68 cl::init(false)); 69 70 class AMDGPUCodeGenPrepare : public FunctionPass, 71 public InstVisitor<AMDGPUCodeGenPrepare, bool> { 72 const GCNSubtarget *ST = nullptr; 73 AssumptionCache *AC = nullptr; 74 DominatorTree *DT = nullptr; 75 LegacyDivergenceAnalysis *DA = nullptr; 76 Module *Mod = nullptr; 77 const DataLayout *DL = nullptr; 78 bool HasUnsafeFPMath = false; 79 bool HasFP32Denormals = false; 80 81 /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to 82 /// binary operation \p V. 83 /// 84 /// \returns Binary operation \p V. 85 /// \returns \p T's base element bit width. 86 unsigned getBaseElementBitWidth(const Type *T) const; 87 88 /// \returns Equivalent 32 bit integer type for given type \p T. For example, 89 /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32> 90 /// is returned. 91 Type *getI32Ty(IRBuilder<> &B, const Type *T) const; 92 93 /// \returns True if binary operation \p I is a signed binary operation, false 94 /// otherwise. 95 bool isSigned(const BinaryOperator &I) const; 96 97 /// \returns True if the condition of 'select' operation \p I comes from a 98 /// signed 'icmp' operation, false otherwise. 99 bool isSigned(const SelectInst &I) const; 100 101 /// \returns True if type \p T needs to be promoted to 32 bit integer type, 102 /// false otherwise. 103 bool needsPromotionToI32(const Type *T) const; 104 105 /// Promotes uniform binary operation \p I to equivalent 32 bit binary 106 /// operation. 107 /// 108 /// \details \p I's base element bit width must be greater than 1 and less 109 /// than or equal 16. Promotion is done by sign or zero extending operands to 110 /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and 111 /// truncating the result of 32 bit binary operation back to \p I's original 112 /// type. Division operation is not promoted. 113 /// 114 /// \returns True if \p I is promoted to equivalent 32 bit binary operation, 115 /// false otherwise. 116 bool promoteUniformOpToI32(BinaryOperator &I) const; 117 118 /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation. 119 /// 120 /// \details \p I's base element bit width must be greater than 1 and less 121 /// than or equal 16. Promotion is done by sign or zero extending operands to 122 /// 32 bits, and replacing \p I with 32 bit 'icmp' operation. 123 /// 124 /// \returns True. 125 bool promoteUniformOpToI32(ICmpInst &I) const; 126 127 /// Promotes uniform 'select' operation \p I to 32 bit 'select' 128 /// operation. 129 /// 130 /// \details \p I's base element bit width must be greater than 1 and less 131 /// than or equal 16. Promotion is done by sign or zero extending operands to 132 /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the 133 /// result of 32 bit 'select' operation back to \p I's original type. 134 /// 135 /// \returns True. 136 bool promoteUniformOpToI32(SelectInst &I) const; 137 138 /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse' 139 /// intrinsic. 140 /// 141 /// \details \p I's base element bit width must be greater than 1 and less 142 /// than or equal 16. Promotion is done by zero extending the operand to 32 143 /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the 144 /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the 145 /// shift amount is 32 minus \p I's base element bit width), and truncating 146 /// the result of the shift operation back to \p I's original type. 147 /// 148 /// \returns True. 149 bool promoteUniformBitreverseToI32(IntrinsicInst &I) const; 150 151 /// \returns The minimum number of bits needed to store the value of \Op as an 152 /// unsigned integer. Truncating to this size and then zero-extending to 153 /// ScalarSize will not change the value. 154 unsigned numBitsUnsigned(Value *Op, unsigned ScalarSize) const; 155 156 /// \returns The minimum number of bits needed to store the value of \Op as a 157 /// signed integer. Truncating to this size and then sign-extending to 158 /// ScalarSize will not change the value. 159 unsigned numBitsSigned(Value *Op, unsigned ScalarSize) const; 160 161 /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24. 162 /// SelectionDAG has an issue where an and asserting the bits are known 163 bool replaceMulWithMul24(BinaryOperator &I) const; 164 165 /// Perform same function as equivalently named function in DAGCombiner. Since 166 /// we expand some divisions here, we need to perform this before obscuring. 167 bool foldBinOpIntoSelect(BinaryOperator &I) const; 168 169 bool divHasSpecialOptimization(BinaryOperator &I, 170 Value *Num, Value *Den) const; 171 int getDivNumBits(BinaryOperator &I, 172 Value *Num, Value *Den, 173 unsigned AtLeast, bool Signed) const; 174 175 /// Expands 24 bit div or rem. 176 Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I, 177 Value *Num, Value *Den, 178 bool IsDiv, bool IsSigned) const; 179 180 Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I, 181 Value *Num, Value *Den, unsigned NumBits, 182 bool IsDiv, bool IsSigned) const; 183 184 /// Expands 32 bit div or rem. 185 Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I, 186 Value *Num, Value *Den) const; 187 188 Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I, 189 Value *Num, Value *Den) const; 190 void expandDivRem64(BinaryOperator &I) const; 191 192 /// Widen a scalar load. 193 /// 194 /// \details \p Widen scalar load for uniform, small type loads from constant 195 // memory / to a full 32-bits and then truncate the input to allow a scalar 196 // load instead of a vector load. 197 // 198 /// \returns True. 199 200 bool canWidenScalarExtLoad(LoadInst &I) const; 201 202 public: 203 static char ID; 204 205 AMDGPUCodeGenPrepare() : FunctionPass(ID) {} 206 207 bool visitFDiv(BinaryOperator &I); 208 bool visitXor(BinaryOperator &I); 209 210 bool visitInstruction(Instruction &I) { return false; } 211 bool visitBinaryOperator(BinaryOperator &I); 212 bool visitLoadInst(LoadInst &I); 213 bool visitICmpInst(ICmpInst &I); 214 bool visitSelectInst(SelectInst &I); 215 216 bool visitIntrinsicInst(IntrinsicInst &I); 217 bool visitBitreverseIntrinsicInst(IntrinsicInst &I); 218 219 bool doInitialization(Module &M) override; 220 bool runOnFunction(Function &F) override; 221 222 StringRef getPassName() const override { return "AMDGPU IR optimizations"; } 223 224 void getAnalysisUsage(AnalysisUsage &AU) const override { 225 AU.addRequired<AssumptionCacheTracker>(); 226 AU.addRequired<LegacyDivergenceAnalysis>(); 227 228 // FIXME: Division expansion needs to preserve the dominator tree. 229 if (!ExpandDiv64InIR) 230 AU.setPreservesAll(); 231 } 232 }; 233 234 } // end anonymous namespace 235 236 unsigned AMDGPUCodeGenPrepare::getBaseElementBitWidth(const Type *T) const { 237 assert(needsPromotionToI32(T) && "T does not need promotion to i32"); 238 239 if (T->isIntegerTy()) 240 return T->getIntegerBitWidth(); 241 return cast<VectorType>(T)->getElementType()->getIntegerBitWidth(); 242 } 243 244 Type *AMDGPUCodeGenPrepare::getI32Ty(IRBuilder<> &B, const Type *T) const { 245 assert(needsPromotionToI32(T) && "T does not need promotion to i32"); 246 247 if (T->isIntegerTy()) 248 return B.getInt32Ty(); 249 return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T)); 250 } 251 252 bool AMDGPUCodeGenPrepare::isSigned(const BinaryOperator &I) const { 253 return I.getOpcode() == Instruction::AShr || 254 I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem; 255 } 256 257 bool AMDGPUCodeGenPrepare::isSigned(const SelectInst &I) const { 258 return isa<ICmpInst>(I.getOperand(0)) ? 259 cast<ICmpInst>(I.getOperand(0))->isSigned() : false; 260 } 261 262 bool AMDGPUCodeGenPrepare::needsPromotionToI32(const Type *T) const { 263 if (!Widen16BitOps) 264 return false; 265 266 const IntegerType *IntTy = dyn_cast<IntegerType>(T); 267 if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16) 268 return true; 269 270 if (const VectorType *VT = dyn_cast<VectorType>(T)) { 271 // TODO: The set of packed operations is more limited, so may want to 272 // promote some anyway. 273 if (ST->hasVOP3PInsts()) 274 return false; 275 276 return needsPromotionToI32(VT->getElementType()); 277 } 278 279 return false; 280 } 281 282 // Return true if the op promoted to i32 should have nsw set. 283 static bool promotedOpIsNSW(const Instruction &I) { 284 switch (I.getOpcode()) { 285 case Instruction::Shl: 286 case Instruction::Add: 287 case Instruction::Sub: 288 return true; 289 case Instruction::Mul: 290 return I.hasNoUnsignedWrap(); 291 default: 292 return false; 293 } 294 } 295 296 // Return true if the op promoted to i32 should have nuw set. 297 static bool promotedOpIsNUW(const Instruction &I) { 298 switch (I.getOpcode()) { 299 case Instruction::Shl: 300 case Instruction::Add: 301 case Instruction::Mul: 302 return true; 303 case Instruction::Sub: 304 return I.hasNoUnsignedWrap(); 305 default: 306 return false; 307 } 308 } 309 310 bool AMDGPUCodeGenPrepare::canWidenScalarExtLoad(LoadInst &I) const { 311 Type *Ty = I.getType(); 312 const DataLayout &DL = Mod->getDataLayout(); 313 int TySize = DL.getTypeSizeInBits(Ty); 314 Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty); 315 316 return I.isSimple() && TySize < 32 && Alignment >= 4 && DA->isUniform(&I); 317 } 318 319 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(BinaryOperator &I) const { 320 assert(needsPromotionToI32(I.getType()) && 321 "I does not need promotion to i32"); 322 323 if (I.getOpcode() == Instruction::SDiv || 324 I.getOpcode() == Instruction::UDiv || 325 I.getOpcode() == Instruction::SRem || 326 I.getOpcode() == Instruction::URem) 327 return false; 328 329 IRBuilder<> Builder(&I); 330 Builder.SetCurrentDebugLocation(I.getDebugLoc()); 331 332 Type *I32Ty = getI32Ty(Builder, I.getType()); 333 Value *ExtOp0 = nullptr; 334 Value *ExtOp1 = nullptr; 335 Value *ExtRes = nullptr; 336 Value *TruncRes = nullptr; 337 338 if (isSigned(I)) { 339 ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty); 340 ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty); 341 } else { 342 ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty); 343 ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty); 344 } 345 346 ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1); 347 if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) { 348 if (promotedOpIsNSW(cast<Instruction>(I))) 349 Inst->setHasNoSignedWrap(); 350 351 if (promotedOpIsNUW(cast<Instruction>(I))) 352 Inst->setHasNoUnsignedWrap(); 353 354 if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 355 Inst->setIsExact(ExactOp->isExact()); 356 } 357 358 TruncRes = Builder.CreateTrunc(ExtRes, I.getType()); 359 360 I.replaceAllUsesWith(TruncRes); 361 I.eraseFromParent(); 362 363 return true; 364 } 365 366 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(ICmpInst &I) const { 367 assert(needsPromotionToI32(I.getOperand(0)->getType()) && 368 "I does not need promotion to i32"); 369 370 IRBuilder<> Builder(&I); 371 Builder.SetCurrentDebugLocation(I.getDebugLoc()); 372 373 Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType()); 374 Value *ExtOp0 = nullptr; 375 Value *ExtOp1 = nullptr; 376 Value *NewICmp = nullptr; 377 378 if (I.isSigned()) { 379 ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty); 380 ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty); 381 } else { 382 ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty); 383 ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty); 384 } 385 NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1); 386 387 I.replaceAllUsesWith(NewICmp); 388 I.eraseFromParent(); 389 390 return true; 391 } 392 393 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(SelectInst &I) const { 394 assert(needsPromotionToI32(I.getType()) && 395 "I does not need promotion to i32"); 396 397 IRBuilder<> Builder(&I); 398 Builder.SetCurrentDebugLocation(I.getDebugLoc()); 399 400 Type *I32Ty = getI32Ty(Builder, I.getType()); 401 Value *ExtOp1 = nullptr; 402 Value *ExtOp2 = nullptr; 403 Value *ExtRes = nullptr; 404 Value *TruncRes = nullptr; 405 406 if (isSigned(I)) { 407 ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty); 408 ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty); 409 } else { 410 ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty); 411 ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty); 412 } 413 ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2); 414 TruncRes = Builder.CreateTrunc(ExtRes, I.getType()); 415 416 I.replaceAllUsesWith(TruncRes); 417 I.eraseFromParent(); 418 419 return true; 420 } 421 422 bool AMDGPUCodeGenPrepare::promoteUniformBitreverseToI32( 423 IntrinsicInst &I) const { 424 assert(I.getIntrinsicID() == Intrinsic::bitreverse && 425 "I must be bitreverse intrinsic"); 426 assert(needsPromotionToI32(I.getType()) && 427 "I does not need promotion to i32"); 428 429 IRBuilder<> Builder(&I); 430 Builder.SetCurrentDebugLocation(I.getDebugLoc()); 431 432 Type *I32Ty = getI32Ty(Builder, I.getType()); 433 Function *I32 = 434 Intrinsic::getDeclaration(Mod, Intrinsic::bitreverse, { I32Ty }); 435 Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty); 436 Value *ExtRes = Builder.CreateCall(I32, { ExtOp }); 437 Value *LShrOp = 438 Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType())); 439 Value *TruncRes = 440 Builder.CreateTrunc(LShrOp, I.getType()); 441 442 I.replaceAllUsesWith(TruncRes); 443 I.eraseFromParent(); 444 445 return true; 446 } 447 448 unsigned AMDGPUCodeGenPrepare::numBitsUnsigned(Value *Op, 449 unsigned ScalarSize) const { 450 KnownBits Known = computeKnownBits(Op, *DL, 0, AC); 451 return ScalarSize - Known.countMinLeadingZeros(); 452 } 453 454 unsigned AMDGPUCodeGenPrepare::numBitsSigned(Value *Op, 455 unsigned ScalarSize) const { 456 // In order for this to be a signed 24-bit value, bit 23, must 457 // be a sign bit. 458 return ScalarSize - ComputeNumSignBits(Op, *DL, 0, AC) + 1; 459 } 460 461 static void extractValues(IRBuilder<> &Builder, 462 SmallVectorImpl<Value *> &Values, Value *V) { 463 auto *VT = dyn_cast<FixedVectorType>(V->getType()); 464 if (!VT) { 465 Values.push_back(V); 466 return; 467 } 468 469 for (int I = 0, E = VT->getNumElements(); I != E; ++I) 470 Values.push_back(Builder.CreateExtractElement(V, I)); 471 } 472 473 static Value *insertValues(IRBuilder<> &Builder, 474 Type *Ty, 475 SmallVectorImpl<Value *> &Values) { 476 if (Values.size() == 1) 477 return Values[0]; 478 479 Value *NewVal = UndefValue::get(Ty); 480 for (int I = 0, E = Values.size(); I != E; ++I) 481 NewVal = Builder.CreateInsertElement(NewVal, Values[I], I); 482 483 return NewVal; 484 } 485 486 // Returns 24-bit or 48-bit (as per `NumBits` and `Size`) mul of `LHS` and 487 // `RHS`. `NumBits` is the number of KnownBits of the result and `Size` is the 488 // width of the original destination. 489 static Value *getMul24(IRBuilder<> &Builder, Value *LHS, Value *RHS, 490 unsigned Size, unsigned NumBits, bool IsSigned) { 491 if (Size <= 32 || NumBits <= 32) { 492 Intrinsic::ID ID = 493 IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24; 494 return Builder.CreateIntrinsic(ID, {}, {LHS, RHS}); 495 } 496 497 assert(NumBits <= 48); 498 499 Intrinsic::ID LoID = 500 IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24; 501 Intrinsic::ID HiID = 502 IsSigned ? Intrinsic::amdgcn_mulhi_i24 : Intrinsic::amdgcn_mulhi_u24; 503 504 Value *Lo = Builder.CreateIntrinsic(LoID, {}, {LHS, RHS}); 505 Value *Hi = Builder.CreateIntrinsic(HiID, {}, {LHS, RHS}); 506 507 IntegerType *I64Ty = Builder.getInt64Ty(); 508 Lo = Builder.CreateZExtOrTrunc(Lo, I64Ty); 509 Hi = Builder.CreateZExtOrTrunc(Hi, I64Ty); 510 511 return Builder.CreateOr(Lo, Builder.CreateShl(Hi, 32)); 512 } 513 514 bool AMDGPUCodeGenPrepare::replaceMulWithMul24(BinaryOperator &I) const { 515 if (I.getOpcode() != Instruction::Mul) 516 return false; 517 518 Type *Ty = I.getType(); 519 unsigned Size = Ty->getScalarSizeInBits(); 520 if (Size <= 16 && ST->has16BitInsts()) 521 return false; 522 523 // Prefer scalar if this could be s_mul_i32 524 if (DA->isUniform(&I)) 525 return false; 526 527 Value *LHS = I.getOperand(0); 528 Value *RHS = I.getOperand(1); 529 IRBuilder<> Builder(&I); 530 Builder.SetCurrentDebugLocation(I.getDebugLoc()); 531 532 unsigned LHSBits = 0, RHSBits = 0; 533 bool IsSigned = false; 534 535 if (ST->hasMulU24() && (LHSBits = numBitsUnsigned(LHS, Size)) <= 24 && 536 (RHSBits = numBitsUnsigned(RHS, Size)) <= 24) { 537 IsSigned = false; 538 539 } else if (ST->hasMulI24() && (LHSBits = numBitsSigned(LHS, Size)) <= 24 && 540 (RHSBits = numBitsSigned(RHS, Size)) <= 24) { 541 IsSigned = true; 542 543 } else 544 return false; 545 546 SmallVector<Value *, 4> LHSVals; 547 SmallVector<Value *, 4> RHSVals; 548 SmallVector<Value *, 4> ResultVals; 549 extractValues(Builder, LHSVals, LHS); 550 extractValues(Builder, RHSVals, RHS); 551 552 IntegerType *I32Ty = Builder.getInt32Ty(); 553 for (int I = 0, E = LHSVals.size(); I != E; ++I) { 554 Value *LHS, *RHS; 555 if (IsSigned) { 556 LHS = Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty); 557 RHS = Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty); 558 } else { 559 LHS = Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty); 560 RHS = Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty); 561 } 562 563 Value *Result = 564 getMul24(Builder, LHS, RHS, Size, LHSBits + RHSBits, IsSigned); 565 566 if (IsSigned) { 567 ResultVals.push_back( 568 Builder.CreateSExtOrTrunc(Result, LHSVals[I]->getType())); 569 } else { 570 ResultVals.push_back( 571 Builder.CreateZExtOrTrunc(Result, LHSVals[I]->getType())); 572 } 573 } 574 575 Value *NewVal = insertValues(Builder, Ty, ResultVals); 576 NewVal->takeName(&I); 577 I.replaceAllUsesWith(NewVal); 578 I.eraseFromParent(); 579 580 return true; 581 } 582 583 // Find a select instruction, which may have been casted. This is mostly to deal 584 // with cases where i16 selects were promoted here to i32. 585 static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) { 586 Cast = nullptr; 587 if (SelectInst *Sel = dyn_cast<SelectInst>(V)) 588 return Sel; 589 590 if ((Cast = dyn_cast<CastInst>(V))) { 591 if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0))) 592 return Sel; 593 } 594 595 return nullptr; 596 } 597 598 bool AMDGPUCodeGenPrepare::foldBinOpIntoSelect(BinaryOperator &BO) const { 599 // Don't do this unless the old select is going away. We want to eliminate the 600 // binary operator, not replace a binop with a select. 601 int SelOpNo = 0; 602 603 CastInst *CastOp; 604 605 // TODO: Should probably try to handle some cases with multiple 606 // users. Duplicating the select may be profitable for division. 607 SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp); 608 if (!Sel || !Sel->hasOneUse()) { 609 SelOpNo = 1; 610 Sel = findSelectThroughCast(BO.getOperand(1), CastOp); 611 } 612 613 if (!Sel || !Sel->hasOneUse()) 614 return false; 615 616 Constant *CT = dyn_cast<Constant>(Sel->getTrueValue()); 617 Constant *CF = dyn_cast<Constant>(Sel->getFalseValue()); 618 Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1)); 619 if (!CBO || !CT || !CF) 620 return false; 621 622 if (CastOp) { 623 if (!CastOp->hasOneUse()) 624 return false; 625 CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), *DL); 626 CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), *DL); 627 } 628 629 // TODO: Handle special 0/-1 cases DAG combine does, although we only really 630 // need to handle divisions here. 631 Constant *FoldedT = SelOpNo ? 632 ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, *DL) : 633 ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, *DL); 634 if (isa<ConstantExpr>(FoldedT)) 635 return false; 636 637 Constant *FoldedF = SelOpNo ? 638 ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, *DL) : 639 ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, *DL); 640 if (isa<ConstantExpr>(FoldedF)) 641 return false; 642 643 IRBuilder<> Builder(&BO); 644 Builder.SetCurrentDebugLocation(BO.getDebugLoc()); 645 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO)) 646 Builder.setFastMathFlags(FPOp->getFastMathFlags()); 647 648 Value *NewSelect = Builder.CreateSelect(Sel->getCondition(), 649 FoldedT, FoldedF); 650 NewSelect->takeName(&BO); 651 BO.replaceAllUsesWith(NewSelect); 652 BO.eraseFromParent(); 653 if (CastOp) 654 CastOp->eraseFromParent(); 655 Sel->eraseFromParent(); 656 return true; 657 } 658 659 // Optimize fdiv with rcp: 660 // 661 // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is 662 // allowed with unsafe-fp-math or afn. 663 // 664 // a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn. 665 static Value *optimizeWithRcp(Value *Num, Value *Den, bool AllowInaccurateRcp, 666 bool RcpIsAccurate, IRBuilder<> &Builder, 667 Module *Mod) { 668 669 if (!AllowInaccurateRcp && !RcpIsAccurate) 670 return nullptr; 671 672 Type *Ty = Den->getType(); 673 if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) { 674 if (AllowInaccurateRcp || RcpIsAccurate) { 675 if (CLHS->isExactlyValue(1.0)) { 676 Function *Decl = Intrinsic::getDeclaration( 677 Mod, Intrinsic::amdgcn_rcp, Ty); 678 679 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 680 // the CI documentation has a worst case error of 1 ulp. 681 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 682 // use it as long as we aren't trying to use denormals. 683 // 684 // v_rcp_f16 and v_rsq_f16 DO support denormals. 685 686 // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't 687 // insert rsq intrinsic here. 688 689 // 1.0 / x -> rcp(x) 690 return Builder.CreateCall(Decl, { Den }); 691 } 692 693 // Same as for 1.0, but expand the sign out of the constant. 694 if (CLHS->isExactlyValue(-1.0)) { 695 Function *Decl = Intrinsic::getDeclaration( 696 Mod, Intrinsic::amdgcn_rcp, Ty); 697 698 // -1.0 / x -> rcp (fneg x) 699 Value *FNeg = Builder.CreateFNeg(Den); 700 return Builder.CreateCall(Decl, { FNeg }); 701 } 702 } 703 } 704 705 if (AllowInaccurateRcp) { 706 Function *Decl = Intrinsic::getDeclaration( 707 Mod, Intrinsic::amdgcn_rcp, Ty); 708 709 // Turn into multiply by the reciprocal. 710 // x / y -> x * (1.0 / y) 711 Value *Recip = Builder.CreateCall(Decl, { Den }); 712 return Builder.CreateFMul(Num, Recip); 713 } 714 return nullptr; 715 } 716 717 // optimize with fdiv.fast: 718 // 719 // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed. 720 // 721 // 1/x -> fdiv.fast(1,x) when !fpmath >= 2.5ulp. 722 // 723 // NOTE: optimizeWithRcp should be tried first because rcp is the preference. 724 static Value *optimizeWithFDivFast(Value *Num, Value *Den, float ReqdAccuracy, 725 bool HasDenormals, IRBuilder<> &Builder, 726 Module *Mod) { 727 // fdiv.fast can achieve 2.5 ULP accuracy. 728 if (ReqdAccuracy < 2.5f) 729 return nullptr; 730 731 // Only have fdiv.fast for f32. 732 Type *Ty = Den->getType(); 733 if (!Ty->isFloatTy()) 734 return nullptr; 735 736 bool NumIsOne = false; 737 if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) { 738 if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0)) 739 NumIsOne = true; 740 } 741 742 // fdiv does not support denormals. But 1.0/x is always fine to use it. 743 if (HasDenormals && !NumIsOne) 744 return nullptr; 745 746 Function *Decl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_fdiv_fast); 747 return Builder.CreateCall(Decl, { Num, Den }); 748 } 749 750 // Optimizations is performed based on fpmath, fast math flags as well as 751 // denormals to optimize fdiv with either rcp or fdiv.fast. 752 // 753 // With rcp: 754 // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is 755 // allowed with unsafe-fp-math or afn. 756 // 757 // a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn. 758 // 759 // With fdiv.fast: 760 // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed. 761 // 762 // 1/x -> fdiv.fast(1,x) when !fpmath >= 2.5ulp. 763 // 764 // NOTE: rcp is the preference in cases that both are legal. 765 bool AMDGPUCodeGenPrepare::visitFDiv(BinaryOperator &FDiv) { 766 767 Type *Ty = FDiv.getType()->getScalarType(); 768 769 // The f64 rcp/rsq approximations are pretty inaccurate. We can do an 770 // expansion around them in codegen. 771 if (Ty->isDoubleTy()) 772 return false; 773 774 // No intrinsic for fdiv16 if target does not support f16. 775 if (Ty->isHalfTy() && !ST->has16BitInsts()) 776 return false; 777 778 const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv); 779 const float ReqdAccuracy = FPOp->getFPAccuracy(); 780 781 // Inaccurate rcp is allowed with unsafe-fp-math or afn. 782 FastMathFlags FMF = FPOp->getFastMathFlags(); 783 const bool AllowInaccurateRcp = HasUnsafeFPMath || FMF.approxFunc(); 784 785 // rcp_f16 is accurate for !fpmath >= 1.0ulp. 786 // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed. 787 // rcp_f64 is never accurate. 788 const bool RcpIsAccurate = (Ty->isHalfTy() && ReqdAccuracy >= 1.0f) || 789 (Ty->isFloatTy() && !HasFP32Denormals && ReqdAccuracy >= 1.0f); 790 791 IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator())); 792 Builder.setFastMathFlags(FMF); 793 Builder.SetCurrentDebugLocation(FDiv.getDebugLoc()); 794 795 Value *Num = FDiv.getOperand(0); 796 Value *Den = FDiv.getOperand(1); 797 798 Value *NewFDiv = nullptr; 799 if (auto *VT = dyn_cast<FixedVectorType>(FDiv.getType())) { 800 NewFDiv = UndefValue::get(VT); 801 802 // FIXME: Doesn't do the right thing for cases where the vector is partially 803 // constant. This works when the scalarizer pass is run first. 804 for (unsigned I = 0, E = VT->getNumElements(); I != E; ++I) { 805 Value *NumEltI = Builder.CreateExtractElement(Num, I); 806 Value *DenEltI = Builder.CreateExtractElement(Den, I); 807 // Try rcp first. 808 Value *NewElt = optimizeWithRcp(NumEltI, DenEltI, AllowInaccurateRcp, 809 RcpIsAccurate, Builder, Mod); 810 if (!NewElt) // Try fdiv.fast. 811 NewElt = optimizeWithFDivFast(NumEltI, DenEltI, ReqdAccuracy, 812 HasFP32Denormals, Builder, Mod); 813 if (!NewElt) // Keep the original. 814 NewElt = Builder.CreateFDiv(NumEltI, DenEltI); 815 816 NewFDiv = Builder.CreateInsertElement(NewFDiv, NewElt, I); 817 } 818 } else { // Scalar FDiv. 819 // Try rcp first. 820 NewFDiv = optimizeWithRcp(Num, Den, AllowInaccurateRcp, RcpIsAccurate, 821 Builder, Mod); 822 if (!NewFDiv) { // Try fdiv.fast. 823 NewFDiv = optimizeWithFDivFast(Num, Den, ReqdAccuracy, HasFP32Denormals, 824 Builder, Mod); 825 } 826 } 827 828 if (NewFDiv) { 829 FDiv.replaceAllUsesWith(NewFDiv); 830 NewFDiv->takeName(&FDiv); 831 FDiv.eraseFromParent(); 832 } 833 834 return !!NewFDiv; 835 } 836 837 bool AMDGPUCodeGenPrepare::visitXor(BinaryOperator &I) { 838 // Match the Xor instruction, its type and its operands 839 IntrinsicInst *IntrinsicCall = dyn_cast<IntrinsicInst>(I.getOperand(0)); 840 ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)); 841 if (!RHS || !IntrinsicCall || RHS->getSExtValue() != -1) 842 return visitBinaryOperator(I); 843 844 // Check if the Call is an intrinsic instruction to amdgcn_class intrinsic 845 // has only one use 846 if (IntrinsicCall->getIntrinsicID() != Intrinsic::amdgcn_class || 847 !IntrinsicCall->hasOneUse()) 848 return visitBinaryOperator(I); 849 850 // "Not" the second argument of the intrinsic call 851 ConstantInt *Arg = dyn_cast<ConstantInt>(IntrinsicCall->getOperand(1)); 852 if (!Arg) 853 return visitBinaryOperator(I); 854 855 IntrinsicCall->setOperand( 856 1, ConstantInt::get(Arg->getType(), Arg->getZExtValue() ^ 0x3ff)); 857 I.replaceAllUsesWith(IntrinsicCall); 858 I.eraseFromParent(); 859 return true; 860 } 861 862 static bool hasUnsafeFPMath(const Function &F) { 863 Attribute Attr = F.getFnAttribute("unsafe-fp-math"); 864 return Attr.getValueAsBool(); 865 } 866 867 static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder, 868 Value *LHS, Value *RHS) { 869 Type *I32Ty = Builder.getInt32Ty(); 870 Type *I64Ty = Builder.getInt64Ty(); 871 872 Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty); 873 Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty); 874 Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64); 875 Value *Lo = Builder.CreateTrunc(MUL64, I32Ty); 876 Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32)); 877 Hi = Builder.CreateTrunc(Hi, I32Ty); 878 return std::make_pair(Lo, Hi); 879 } 880 881 static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) { 882 return getMul64(Builder, LHS, RHS).second; 883 } 884 885 /// Figure out how many bits are really needed for this ddivision. \p AtLeast is 886 /// an optimization hint to bypass the second ComputeNumSignBits call if we the 887 /// first one is insufficient. Returns -1 on failure. 888 int AMDGPUCodeGenPrepare::getDivNumBits(BinaryOperator &I, 889 Value *Num, Value *Den, 890 unsigned AtLeast, bool IsSigned) const { 891 const DataLayout &DL = Mod->getDataLayout(); 892 unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I); 893 if (LHSSignBits < AtLeast) 894 return -1; 895 896 unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I); 897 if (RHSSignBits < AtLeast) 898 return -1; 899 900 unsigned SignBits = std::min(LHSSignBits, RHSSignBits); 901 unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits; 902 if (IsSigned) 903 ++DivBits; 904 return DivBits; 905 } 906 907 // The fractional part of a float is enough to accurately represent up to 908 // a 24-bit signed integer. 909 Value *AMDGPUCodeGenPrepare::expandDivRem24(IRBuilder<> &Builder, 910 BinaryOperator &I, 911 Value *Num, Value *Den, 912 bool IsDiv, bool IsSigned) const { 913 int DivBits = getDivNumBits(I, Num, Den, 9, IsSigned); 914 if (DivBits == -1) 915 return nullptr; 916 return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned); 917 } 918 919 Value *AMDGPUCodeGenPrepare::expandDivRem24Impl(IRBuilder<> &Builder, 920 BinaryOperator &I, 921 Value *Num, Value *Den, 922 unsigned DivBits, 923 bool IsDiv, bool IsSigned) const { 924 Type *I32Ty = Builder.getInt32Ty(); 925 Num = Builder.CreateTrunc(Num, I32Ty); 926 Den = Builder.CreateTrunc(Den, I32Ty); 927 928 Type *F32Ty = Builder.getFloatTy(); 929 ConstantInt *One = Builder.getInt32(1); 930 Value *JQ = One; 931 932 if (IsSigned) { 933 // char|short jq = ia ^ ib; 934 JQ = Builder.CreateXor(Num, Den); 935 936 // jq = jq >> (bitsize - 2) 937 JQ = Builder.CreateAShr(JQ, Builder.getInt32(30)); 938 939 // jq = jq | 0x1 940 JQ = Builder.CreateOr(JQ, One); 941 } 942 943 // int ia = (int)LHS; 944 Value *IA = Num; 945 946 // int ib, (int)RHS; 947 Value *IB = Den; 948 949 // float fa = (float)ia; 950 Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty) 951 : Builder.CreateUIToFP(IA, F32Ty); 952 953 // float fb = (float)ib; 954 Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty) 955 : Builder.CreateUIToFP(IB,F32Ty); 956 957 Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp, 958 Builder.getFloatTy()); 959 Value *RCP = Builder.CreateCall(RcpDecl, { FB }); 960 Value *FQM = Builder.CreateFMul(FA, RCP); 961 962 // fq = trunc(fqm); 963 CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM); 964 FQ->copyFastMathFlags(Builder.getFastMathFlags()); 965 966 // float fqneg = -fq; 967 Value *FQNeg = Builder.CreateFNeg(FQ); 968 969 // float fr = mad(fqneg, fb, fa); 970 auto FMAD = !ST->hasMadMacF32Insts() 971 ? Intrinsic::fma 972 : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz; 973 Value *FR = Builder.CreateIntrinsic(FMAD, 974 {FQNeg->getType()}, {FQNeg, FB, FA}, FQ); 975 976 // int iq = (int)fq; 977 Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty) 978 : Builder.CreateFPToUI(FQ, I32Ty); 979 980 // fr = fabs(fr); 981 FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ); 982 983 // fb = fabs(fb); 984 FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ); 985 986 // int cv = fr >= fb; 987 Value *CV = Builder.CreateFCmpOGE(FR, FB); 988 989 // jq = (cv ? jq : 0); 990 JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0)); 991 992 // dst = iq + jq; 993 Value *Div = Builder.CreateAdd(IQ, JQ); 994 995 Value *Res = Div; 996 if (!IsDiv) { 997 // Rem needs compensation, it's easier to recompute it 998 Value *Rem = Builder.CreateMul(Div, Den); 999 Res = Builder.CreateSub(Num, Rem); 1000 } 1001 1002 if (DivBits != 0 && DivBits < 32) { 1003 // Extend in register from the number of bits this divide really is. 1004 if (IsSigned) { 1005 int InRegBits = 32 - DivBits; 1006 1007 Res = Builder.CreateShl(Res, InRegBits); 1008 Res = Builder.CreateAShr(Res, InRegBits); 1009 } else { 1010 ConstantInt *TruncMask 1011 = Builder.getInt32((UINT64_C(1) << DivBits) - 1); 1012 Res = Builder.CreateAnd(Res, TruncMask); 1013 } 1014 } 1015 1016 return Res; 1017 } 1018 1019 // Try to recognize special cases the DAG will emit special, better expansions 1020 // than the general expansion we do here. 1021 1022 // TODO: It would be better to just directly handle those optimizations here. 1023 bool AMDGPUCodeGenPrepare::divHasSpecialOptimization( 1024 BinaryOperator &I, Value *Num, Value *Den) const { 1025 if (Constant *C = dyn_cast<Constant>(Den)) { 1026 // Arbitrary constants get a better expansion as long as a wider mulhi is 1027 // legal. 1028 if (C->getType()->getScalarSizeInBits() <= 32) 1029 return true; 1030 1031 // TODO: Sdiv check for not exact for some reason. 1032 1033 // If there's no wider mulhi, there's only a better expansion for powers of 1034 // two. 1035 // TODO: Should really know for each vector element. 1036 if (isKnownToBeAPowerOfTwo(C, *DL, true, 0, AC, &I, DT)) 1037 return true; 1038 1039 return false; 1040 } 1041 1042 if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) { 1043 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 1044 if (BinOpDen->getOpcode() == Instruction::Shl && 1045 isa<Constant>(BinOpDen->getOperand(0)) && 1046 isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), *DL, true, 1047 0, AC, &I, DT)) { 1048 return true; 1049 } 1050 } 1051 1052 return false; 1053 } 1054 1055 static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout *DL) { 1056 // Check whether the sign can be determined statically. 1057 KnownBits Known = computeKnownBits(V, *DL); 1058 if (Known.isNegative()) 1059 return Constant::getAllOnesValue(V->getType()); 1060 if (Known.isNonNegative()) 1061 return Constant::getNullValue(V->getType()); 1062 return Builder.CreateAShr(V, Builder.getInt32(31)); 1063 } 1064 1065 Value *AMDGPUCodeGenPrepare::expandDivRem32(IRBuilder<> &Builder, 1066 BinaryOperator &I, Value *X, 1067 Value *Y) const { 1068 Instruction::BinaryOps Opc = I.getOpcode(); 1069 assert(Opc == Instruction::URem || Opc == Instruction::UDiv || 1070 Opc == Instruction::SRem || Opc == Instruction::SDiv); 1071 1072 FastMathFlags FMF; 1073 FMF.setFast(); 1074 Builder.setFastMathFlags(FMF); 1075 1076 if (divHasSpecialOptimization(I, X, Y)) 1077 return nullptr; // Keep it for later optimization. 1078 1079 bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv; 1080 bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv; 1081 1082 Type *Ty = X->getType(); 1083 Type *I32Ty = Builder.getInt32Ty(); 1084 Type *F32Ty = Builder.getFloatTy(); 1085 1086 if (Ty->getScalarSizeInBits() < 32) { 1087 if (IsSigned) { 1088 X = Builder.CreateSExt(X, I32Ty); 1089 Y = Builder.CreateSExt(Y, I32Ty); 1090 } else { 1091 X = Builder.CreateZExt(X, I32Ty); 1092 Y = Builder.CreateZExt(Y, I32Ty); 1093 } 1094 } 1095 1096 if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) { 1097 return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) : 1098 Builder.CreateZExtOrTrunc(Res, Ty); 1099 } 1100 1101 ConstantInt *Zero = Builder.getInt32(0); 1102 ConstantInt *One = Builder.getInt32(1); 1103 1104 Value *Sign = nullptr; 1105 if (IsSigned) { 1106 Value *SignX = getSign32(X, Builder, DL); 1107 Value *SignY = getSign32(Y, Builder, DL); 1108 // Remainder sign is the same as LHS 1109 Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX; 1110 1111 X = Builder.CreateAdd(X, SignX); 1112 Y = Builder.CreateAdd(Y, SignY); 1113 1114 X = Builder.CreateXor(X, SignX); 1115 Y = Builder.CreateXor(Y, SignY); 1116 } 1117 1118 // The algorithm here is based on ideas from "Software Integer Division", Tom 1119 // Rodeheffer, August 2008. 1120 // 1121 // unsigned udiv(unsigned x, unsigned y) { 1122 // // Initial estimate of inv(y). The constant is less than 2^32 to ensure 1123 // // that this is a lower bound on inv(y), even if some of the calculations 1124 // // round up. 1125 // unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y)); 1126 // 1127 // // One round of UNR (Unsigned integer Newton-Raphson) to improve z. 1128 // // Empirically this is guaranteed to give a "two-y" lower bound on 1129 // // inv(y). 1130 // z += umulh(z, -y * z); 1131 // 1132 // // Quotient/remainder estimate. 1133 // unsigned q = umulh(x, z); 1134 // unsigned r = x - q * y; 1135 // 1136 // // Two rounds of quotient/remainder refinement. 1137 // if (r >= y) { 1138 // ++q; 1139 // r -= y; 1140 // } 1141 // if (r >= y) { 1142 // ++q; 1143 // r -= y; 1144 // } 1145 // 1146 // return q; 1147 // } 1148 1149 // Initial estimate of inv(y). 1150 Value *FloatY = Builder.CreateUIToFP(Y, F32Ty); 1151 Function *Rcp = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp, F32Ty); 1152 Value *RcpY = Builder.CreateCall(Rcp, {FloatY}); 1153 Constant *Scale = ConstantFP::get(F32Ty, BitsToFloat(0x4F7FFFFE)); 1154 Value *ScaledY = Builder.CreateFMul(RcpY, Scale); 1155 Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty); 1156 1157 // One round of UNR. 1158 Value *NegY = Builder.CreateSub(Zero, Y); 1159 Value *NegYZ = Builder.CreateMul(NegY, Z); 1160 Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ)); 1161 1162 // Quotient/remainder estimate. 1163 Value *Q = getMulHu(Builder, X, Z); 1164 Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y)); 1165 1166 // First quotient/remainder refinement. 1167 Value *Cond = Builder.CreateICmpUGE(R, Y); 1168 if (IsDiv) 1169 Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q); 1170 R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R); 1171 1172 // Second quotient/remainder refinement. 1173 Cond = Builder.CreateICmpUGE(R, Y); 1174 Value *Res; 1175 if (IsDiv) 1176 Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q); 1177 else 1178 Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R); 1179 1180 if (IsSigned) { 1181 Res = Builder.CreateXor(Res, Sign); 1182 Res = Builder.CreateSub(Res, Sign); 1183 } 1184 1185 Res = Builder.CreateTrunc(Res, Ty); 1186 1187 return Res; 1188 } 1189 1190 Value *AMDGPUCodeGenPrepare::shrinkDivRem64(IRBuilder<> &Builder, 1191 BinaryOperator &I, 1192 Value *Num, Value *Den) const { 1193 if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den)) 1194 return nullptr; // Keep it for later optimization. 1195 1196 Instruction::BinaryOps Opc = I.getOpcode(); 1197 1198 bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv; 1199 bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem; 1200 1201 int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned); 1202 if (NumDivBits == -1) 1203 return nullptr; 1204 1205 Value *Narrowed = nullptr; 1206 if (NumDivBits <= 24) { 1207 Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits, 1208 IsDiv, IsSigned); 1209 } else if (NumDivBits <= 32) { 1210 Narrowed = expandDivRem32(Builder, I, Num, Den); 1211 } 1212 1213 if (Narrowed) { 1214 return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) : 1215 Builder.CreateZExt(Narrowed, Num->getType()); 1216 } 1217 1218 return nullptr; 1219 } 1220 1221 void AMDGPUCodeGenPrepare::expandDivRem64(BinaryOperator &I) const { 1222 Instruction::BinaryOps Opc = I.getOpcode(); 1223 // Do the general expansion. 1224 if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) { 1225 expandDivisionUpTo64Bits(&I); 1226 return; 1227 } 1228 1229 if (Opc == Instruction::URem || Opc == Instruction::SRem) { 1230 expandRemainderUpTo64Bits(&I); 1231 return; 1232 } 1233 1234 llvm_unreachable("not a division"); 1235 } 1236 1237 bool AMDGPUCodeGenPrepare::visitBinaryOperator(BinaryOperator &I) { 1238 if (foldBinOpIntoSelect(I)) 1239 return true; 1240 1241 if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) && 1242 DA->isUniform(&I) && promoteUniformOpToI32(I)) 1243 return true; 1244 1245 if (UseMul24Intrin && replaceMulWithMul24(I)) 1246 return true; 1247 1248 bool Changed = false; 1249 Instruction::BinaryOps Opc = I.getOpcode(); 1250 Type *Ty = I.getType(); 1251 Value *NewDiv = nullptr; 1252 unsigned ScalarSize = Ty->getScalarSizeInBits(); 1253 1254 SmallVector<BinaryOperator *, 8> Div64ToExpand; 1255 1256 if ((Opc == Instruction::URem || Opc == Instruction::UDiv || 1257 Opc == Instruction::SRem || Opc == Instruction::SDiv) && 1258 ScalarSize <= 64 && 1259 !DisableIDivExpand) { 1260 Value *Num = I.getOperand(0); 1261 Value *Den = I.getOperand(1); 1262 IRBuilder<> Builder(&I); 1263 Builder.SetCurrentDebugLocation(I.getDebugLoc()); 1264 1265 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1266 NewDiv = UndefValue::get(VT); 1267 1268 for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) { 1269 Value *NumEltN = Builder.CreateExtractElement(Num, N); 1270 Value *DenEltN = Builder.CreateExtractElement(Den, N); 1271 1272 Value *NewElt; 1273 if (ScalarSize <= 32) { 1274 NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN); 1275 if (!NewElt) 1276 NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN); 1277 } else { 1278 // See if this 64-bit division can be shrunk to 32/24-bits before 1279 // producing the general expansion. 1280 NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN); 1281 if (!NewElt) { 1282 // The general 64-bit expansion introduces control flow and doesn't 1283 // return the new value. Just insert a scalar copy and defer 1284 // expanding it. 1285 NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN); 1286 Div64ToExpand.push_back(cast<BinaryOperator>(NewElt)); 1287 } 1288 } 1289 1290 NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N); 1291 } 1292 } else { 1293 if (ScalarSize <= 32) 1294 NewDiv = expandDivRem32(Builder, I, Num, Den); 1295 else { 1296 NewDiv = shrinkDivRem64(Builder, I, Num, Den); 1297 if (!NewDiv) 1298 Div64ToExpand.push_back(&I); 1299 } 1300 } 1301 1302 if (NewDiv) { 1303 I.replaceAllUsesWith(NewDiv); 1304 I.eraseFromParent(); 1305 Changed = true; 1306 } 1307 } 1308 1309 if (ExpandDiv64InIR) { 1310 // TODO: We get much worse code in specially handled constant cases. 1311 for (BinaryOperator *Div : Div64ToExpand) { 1312 expandDivRem64(*Div); 1313 Changed = true; 1314 } 1315 } 1316 1317 return Changed; 1318 } 1319 1320 bool AMDGPUCodeGenPrepare::visitLoadInst(LoadInst &I) { 1321 if (!WidenLoads) 1322 return false; 1323 1324 if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 1325 I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 1326 canWidenScalarExtLoad(I)) { 1327 IRBuilder<> Builder(&I); 1328 Builder.SetCurrentDebugLocation(I.getDebugLoc()); 1329 1330 Type *I32Ty = Builder.getInt32Ty(); 1331 Type *PT = PointerType::get(I32Ty, I.getPointerAddressSpace()); 1332 Value *BitCast= Builder.CreateBitCast(I.getPointerOperand(), PT); 1333 LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, BitCast); 1334 WidenLoad->copyMetadata(I); 1335 1336 // If we have range metadata, we need to convert the type, and not make 1337 // assumptions about the high bits. 1338 if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) { 1339 ConstantInt *Lower = 1340 mdconst::extract<ConstantInt>(Range->getOperand(0)); 1341 1342 if (Lower->isNullValue()) { 1343 WidenLoad->setMetadata(LLVMContext::MD_range, nullptr); 1344 } else { 1345 Metadata *LowAndHigh[] = { 1346 ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))), 1347 // Don't make assumptions about the high bits. 1348 ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0)) 1349 }; 1350 1351 WidenLoad->setMetadata(LLVMContext::MD_range, 1352 MDNode::get(Mod->getContext(), LowAndHigh)); 1353 } 1354 } 1355 1356 int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType()); 1357 Type *IntNTy = Builder.getIntNTy(TySize); 1358 Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy); 1359 Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType()); 1360 I.replaceAllUsesWith(ValOrig); 1361 I.eraseFromParent(); 1362 return true; 1363 } 1364 1365 return false; 1366 } 1367 1368 bool AMDGPUCodeGenPrepare::visitICmpInst(ICmpInst &I) { 1369 bool Changed = false; 1370 1371 if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) && 1372 DA->isUniform(&I)) 1373 Changed |= promoteUniformOpToI32(I); 1374 1375 return Changed; 1376 } 1377 1378 bool AMDGPUCodeGenPrepare::visitSelectInst(SelectInst &I) { 1379 bool Changed = false; 1380 1381 if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) && 1382 DA->isUniform(&I)) 1383 Changed |= promoteUniformOpToI32(I); 1384 1385 return Changed; 1386 } 1387 1388 bool AMDGPUCodeGenPrepare::visitIntrinsicInst(IntrinsicInst &I) { 1389 switch (I.getIntrinsicID()) { 1390 case Intrinsic::bitreverse: 1391 return visitBitreverseIntrinsicInst(I); 1392 default: 1393 return false; 1394 } 1395 } 1396 1397 bool AMDGPUCodeGenPrepare::visitBitreverseIntrinsicInst(IntrinsicInst &I) { 1398 bool Changed = false; 1399 1400 if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) && 1401 DA->isUniform(&I)) 1402 Changed |= promoteUniformBitreverseToI32(I); 1403 1404 return Changed; 1405 } 1406 1407 bool AMDGPUCodeGenPrepare::doInitialization(Module &M) { 1408 Mod = &M; 1409 DL = &Mod->getDataLayout(); 1410 return false; 1411 } 1412 1413 bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) { 1414 if (skipFunction(F)) 1415 return false; 1416 1417 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>(); 1418 if (!TPC) 1419 return false; 1420 1421 const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>(); 1422 ST = &TM.getSubtarget<GCNSubtarget>(F); 1423 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1424 DA = &getAnalysis<LegacyDivergenceAnalysis>(); 1425 1426 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 1427 DT = DTWP ? &DTWP->getDomTree() : nullptr; 1428 1429 HasUnsafeFPMath = hasUnsafeFPMath(F); 1430 1431 AMDGPU::SIModeRegisterDefaults Mode(F); 1432 HasFP32Denormals = Mode.allFP32Denormals(); 1433 1434 bool MadeChange = false; 1435 1436 Function::iterator NextBB; 1437 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) { 1438 BasicBlock *BB = &*FI; 1439 NextBB = std::next(FI); 1440 1441 BasicBlock::iterator Next; 1442 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; I = Next) { 1443 Next = std::next(I); 1444 1445 MadeChange |= visit(*I); 1446 1447 if (Next != E) { // Control flow changed 1448 BasicBlock *NextInstBB = Next->getParent(); 1449 if (NextInstBB != BB) { 1450 BB = NextInstBB; 1451 E = BB->end(); 1452 FE = F.end(); 1453 } 1454 } 1455 } 1456 } 1457 1458 return MadeChange; 1459 } 1460 1461 INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE, 1462 "AMDGPU IR optimizations", false, false) 1463 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1464 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis) 1465 INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations", 1466 false, false) 1467 1468 char AMDGPUCodeGenPrepare::ID = 0; 1469 1470 FunctionPass *llvm::createAMDGPUCodeGenPreparePass() { 1471 return new AMDGPUCodeGenPrepare(); 1472 } 1473