30 #define DEBUG_TYPE "bypass-slow-division"
38 DivOpInfo(
bool InSignedOp,
Value *InDividend,
Value *InDivisor)
39 : SignedOp(InSignedOp), Dividend(InDividend), Divisor(InDivisor) {}
46 QuotRemPair(
Value *InQuotient,
Value *InRemainder)
47 : Quotient(InQuotient), Remainder(InRemainder) {}
53 struct QuotRemWithBB {
55 Value *Quotient =
nullptr;
56 Value *Remainder =
nullptr;
63 static bool isEqual(
const DivOpInfo &Val1,
const DivOpInfo &Val2) {
64 return Val1.SignedOp == Val2.SignedOp &&
65 Val1.Dividend == Val2.Dividend &&
66 Val1.Divisor == Val2.Divisor;
70 return DivOpInfo(
false,
nullptr,
nullptr);
74 return DivOpInfo(
true,
nullptr,
nullptr);
78 return (
unsigned)(
reinterpret_cast<uintptr_t
>(Val.Dividend) ^
79 reinterpret_cast<uintptr_t>(Val.Divisor)) ^
80 (
unsigned)Val.SignedOp;
100 class FastDivInsertionTask {
101 bool IsValidTask =
false;
110 QuotRemPair createDivRemPhiNodes(QuotRemWithBB &LHS, QuotRemWithBB &RHS,
116 return SlowDivOrRem->getOpcode() == Instruction::SDiv ||
117 SlowDivOrRem->getOpcode() == Instruction::SRem;
119 bool isDivisionOp() {
120 return SlowDivOrRem->getOpcode() == Instruction::SDiv ||
121 SlowDivOrRem->getOpcode() == Instruction::UDiv;
123 Type *getSlowType() {
return SlowDivOrRem->getType(); }
131 FastDivInsertionTask::FastDivInsertionTask(
Instruction *
I,
134 case Instruction::UDiv:
135 case Instruction::SDiv:
136 case Instruction::URem:
137 case Instruction::SRem:
152 if (BI == BypassWidths.
end())
176 Value *Dividend = SlowDivOrRem->getOperand(0);
177 Value *Divisor = SlowDivOrRem->getOperand(1);
178 DivOpInfo Key(
isSignedOp(), Dividend, Divisor);
179 auto CacheI = Cache.
find(Key);
181 if (CacheI == Cache.
end()) {
190 QuotRemPair &
Value = CacheI->second;
191 return isDivisionOp() ? Value.Quotient : Value.Remainder;
215 case Instruction::Xor:
217 case Instruction::Mul: {
224 if (!C && isa<BitCastInst>(Op1))
225 C = dyn_cast<ConstantInt>(cast<BitCastInst>(Op1)->getOperand(0));
228 case Instruction::PHI: {
231 if (Visited.
size() >= 16)
235 if (Visited.
find(I) != Visited.
end())
241 return getValueRange(V, Visited) == VALRNG_LIKELY_LONG ||
253 unsigned ShortLen = BypassType->getBitWidth();
256 assert(LongLen > ShortLen &&
"Value type must be wider than BypassType");
257 unsigned HiBits = LongLen - ShortLen;
259 const DataLayout &
DL = SlowDivOrRem->getModule()->getDataLayout();
264 if (Known.countMinLeadingZeros() >= HiBits)
265 return VALRNG_KNOWN_SHORT;
267 if (Known.countMaxLeadingZeros() < HiBits)
268 return VALRNG_LIKELY_LONG;
274 if (isHashLikeValue(V, Visited))
275 return VALRNG_LIKELY_LONG;
277 return VALRNG_UNKNOWN;
282 QuotRemWithBB FastDivInsertionTask::createSlowBB(
BasicBlock *SuccessorBB) {
283 QuotRemWithBB DivRemPair;
285 MainBB->getParent(), SuccessorBB);
286 IRBuilder<> Builder(DivRemPair.BB, DivRemPair.BB->begin());
288 Value *Dividend = SlowDivOrRem->getOperand(0);
289 Value *Divisor = SlowDivOrRem->getOperand(1);
292 DivRemPair.Quotient = Builder.CreateSDiv(Dividend, Divisor);
293 DivRemPair.Remainder = Builder.CreateSRem(Dividend, Divisor);
295 DivRemPair.Quotient = Builder.CreateUDiv(Dividend, Divisor);
296 DivRemPair.Remainder = Builder.CreateURem(Dividend, Divisor);
299 Builder.CreateBr(SuccessorBB);
305 QuotRemWithBB FastDivInsertionTask::createFastBB(
BasicBlock *SuccessorBB) {
306 QuotRemWithBB DivRemPair;
308 MainBB->getParent(), SuccessorBB);
309 IRBuilder<> Builder(DivRemPair.BB, DivRemPair.BB->begin());
311 Value *Dividend = SlowDivOrRem->getOperand(0);
312 Value *Divisor = SlowDivOrRem->getOperand(1);
313 Value *ShortDivisorV =
314 Builder.CreateCast(Instruction::Trunc, Divisor, BypassType);
315 Value *ShortDividendV =
316 Builder.CreateCast(Instruction::Trunc, Dividend, BypassType);
319 Value *ShortQV = Builder.CreateUDiv(ShortDividendV, ShortDivisorV);
320 Value *ShortRV = Builder.CreateURem(ShortDividendV, ShortDivisorV);
321 DivRemPair.Quotient =
322 Builder.CreateCast(Instruction::ZExt, ShortQV, getSlowType());
323 DivRemPair.Remainder =
324 Builder.CreateCast(Instruction::ZExt, ShortRV, getSlowType());
325 Builder.CreateBr(SuccessorBB);
331 QuotRemPair FastDivInsertionTask::createDivRemPhiNodes(QuotRemWithBB &LHS,
335 PHINode *QuoPhi = Builder.CreatePHI(getSlowType(), 2);
336 QuoPhi->addIncoming(LHS.Quotient, LHS.BB);
337 QuoPhi->addIncoming(RHS.Quotient, RHS.BB);
338 PHINode *RemPhi = Builder.CreatePHI(getSlowType(), 2);
341 return QuotRemPair(QuoPhi, RemPhi);
348 Value *FastDivInsertionTask::insertOperandRuntimeCheck(
Value *Op1,
Value *Op2) {
349 assert((Op1 || Op2) &&
"Nothing to check");
356 OrV = Op1 ? Op1 : Op2;
360 uint64_t BitMask = ~BypassType->getBitMask();
361 Value *AndV = Builder.CreateAnd(OrV, BitMask);
365 return Builder.CreateICmpEQ(AndV, ZeroV);
371 Value *Dividend = SlowDivOrRem->getOperand(0);
372 Value *Divisor = SlowDivOrRem->getOperand(1);
374 if (isa<ConstantInt>(Divisor)) {
380 ValueRange DividendRange = getValueRange(Dividend, SetL);
381 if (DividendRange == VALRNG_LIKELY_LONG)
385 ValueRange DivisorRange = getValueRange(Divisor, SetR);
386 if (DivisorRange == VALRNG_LIKELY_LONG)
389 bool DividendShort = (DividendRange == VALRNG_KNOWN_SHORT);
390 bool DivisorShort = (DivisorRange == VALRNG_KNOWN_SHORT);
392 if (DividendShort && DivisorShort) {
397 Value *TruncDividend = Builder.CreateTrunc(Dividend, BypassType);
398 Value *TruncDivisor = Builder.CreateTrunc(Divisor, BypassType);
399 Value *TruncDiv = Builder.CreateUDiv(TruncDividend, TruncDivisor);
400 Value *TruncRem = Builder.CreateURem(TruncDividend, TruncDivisor);
401 Value *ExtDiv = Builder.CreateZExt(TruncDiv, getSlowType());
402 Value *ExtRem = Builder.CreateZExt(TruncRem, getSlowType());
403 return QuotRemPair(ExtDiv, ExtRem);
423 Long.Remainder = Dividend;
424 QuotRemWithBB
Fast = createFastBB(SuccessorBB);
425 QuotRemPair Result = createDivRemPhiNodes(Fast, Long, SuccessorBB);
427 Value *CmpV = Builder.CreateICmpUGE(Dividend, Divisor);
428 Builder.CreateCondBr(CmpV, Fast.BB, SuccessorBB);
438 QuotRemWithBB Fast = createFastBB(SuccessorBB);
439 QuotRemWithBB Slow = createSlowBB(SuccessorBB);
440 QuotRemPair Result = createDivRemPhiNodes(Fast, Slow, SuccessorBB);
441 Value *CmpV = insertOperandRuntimeCheck(DividendShort ?
nullptr : Dividend,
442 DivisorShort ?
nullptr : Divisor);
455 bool MadeChange =
false;
457 while (Next !=
nullptr) {
463 FastDivInsertionTask Task(I, BypassWidths);
464 if (
Value *Replacement = Task.getReplacement(PerBBDivCache)) {
474 for (
auto &KV : PerBBDivCache)
475 for (
Value *V : {KV.second.Quotient, KV.second.Remainder})
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
DenseMap< unsigned, unsigned > BypassWidthsTy
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
iterator begin()
Instruction iterator methods.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static DivOpInfo getEmptyKey()
const APInt & getValue() const
Return the constant as an APInt value reference.
bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
iterator find(const_arg_type_t< KeyT > Val)
static DivOpInfo getTombstoneKey()
SmallPtrSet< Instruction *, 4 > VisitedSetTy
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const InstListType & getInstList() const
Return the underlying instruction list container.
DenseMap< DivOpInfo, QuotRemPair > DivCacheTy
Value * getOperand(unsigned i) const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
unsigned getIntegerBitWidth() const
Class to represent integer types.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
LLVMContext & getContext() const
All values hold a context through their type.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
This is the shared class of boolean and integer constants.
Type * getType() const
All values are typed, get the type of this value.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
iterator find(ConstPtrType Ptr) const
Fast - This calling convention attempts to make calls as fast as possible (e.g.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static int isSignedOp(ISD::CondCode Opcode)
For an integer comparison, return 1 if the comparison is a signed operation and 2 if the result is an...
static bool isEqual(const DivOpInfo &Val1, const DivOpInfo &Val2)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static unsigned getHashValue(const DivOpInfo &Val)
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
const BasicBlock * getParent() const