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