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