Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/IntegerDivision.cpp
35271 views
//===-- IntegerDivision.cpp - Expand integer division ---------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains an implementation of 32bit and 64bit scalar integer9// division for targets that don't have native support. It's largely derived10// from compiler-rt's implementations of __udivsi3 and __udivmoddi4,11// but hand-tuned for targets that prefer less control flow.12//13//===----------------------------------------------------------------------===//1415#include "llvm/Transforms/Utils/IntegerDivision.h"16#include "llvm/IR/Function.h"17#include "llvm/IR/IRBuilder.h"18#include "llvm/IR/Instructions.h"19#include "llvm/IR/Intrinsics.h"2021using namespace llvm;2223#define DEBUG_TYPE "integer-division"2425/// Generate code to compute the remainder of two signed integers. Returns the26/// remainder, which will have the sign of the dividend. Builder's insert point27/// should be pointing where the caller wants code generated, e.g. at the srem28/// instruction. This will generate a urem in the process, and Builder's insert29/// point will be pointing at the uren (if present, i.e. not folded), ready to30/// be expanded if the user wishes31static Value *generateSignedRemainderCode(Value *Dividend, Value *Divisor,32IRBuilder<> &Builder) {33unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();34ConstantInt *Shift = Builder.getIntN(BitWidth, BitWidth - 1);3536// Following instructions are generated for both i32 (shift 31) and37// i64 (shift 63).3839// ; %dividend_sgn = ashr i32 %dividend, 3140// ; %divisor_sgn = ashr i32 %divisor, 3141// ; %dvd_xor = xor i32 %dividend, %dividend_sgn42// ; %dvs_xor = xor i32 %divisor, %divisor_sgn43// ; %u_dividend = sub i32 %dvd_xor, %dividend_sgn44// ; %u_divisor = sub i32 %dvs_xor, %divisor_sgn45// ; %urem = urem i32 %dividend, %divisor46// ; %xored = xor i32 %urem, %dividend_sgn47// ; %srem = sub i32 %xored, %dividend_sgn48Dividend = Builder.CreateFreeze(Dividend);49Divisor = Builder.CreateFreeze(Divisor);50Value *DividendSign = Builder.CreateAShr(Dividend, Shift);51Value *DivisorSign = Builder.CreateAShr(Divisor, Shift);52Value *DvdXor = Builder.CreateXor(Dividend, DividendSign);53Value *DvsXor = Builder.CreateXor(Divisor, DivisorSign);54Value *UDividend = Builder.CreateSub(DvdXor, DividendSign);55Value *UDivisor = Builder.CreateSub(DvsXor, DivisorSign);56Value *URem = Builder.CreateURem(UDividend, UDivisor);57Value *Xored = Builder.CreateXor(URem, DividendSign);58Value *SRem = Builder.CreateSub(Xored, DividendSign);5960if (Instruction *URemInst = dyn_cast<Instruction>(URem))61Builder.SetInsertPoint(URemInst);6263return SRem;64}656667/// Generate code to compute the remainder of two unsigned integers. Returns the68/// remainder. Builder's insert point should be pointing where the caller wants69/// code generated, e.g. at the urem instruction. This will generate a udiv in70/// the process, and Builder's insert point will be pointing at the udiv (if71/// present, i.e. not folded), ready to be expanded if the user wishes72static Value *generatedUnsignedRemainderCode(Value *Dividend, Value *Divisor,73IRBuilder<> &Builder) {74// Remainder = Dividend - Quotient*Divisor7576// Following instructions are generated for both i32 and i647778// ; %quotient = udiv i32 %dividend, %divisor79// ; %product = mul i32 %divisor, %quotient80// ; %remainder = sub i32 %dividend, %product81Dividend = Builder.CreateFreeze(Dividend);82Divisor = Builder.CreateFreeze(Divisor);83Value *Quotient = Builder.CreateUDiv(Dividend, Divisor);84Value *Product = Builder.CreateMul(Divisor, Quotient);85Value *Remainder = Builder.CreateSub(Dividend, Product);8687if (Instruction *UDiv = dyn_cast<Instruction>(Quotient))88Builder.SetInsertPoint(UDiv);8990return Remainder;91}9293/// Generate code to divide two signed integers. Returns the quotient, rounded94/// towards 0. Builder's insert point should be pointing where the caller wants95/// code generated, e.g. at the sdiv instruction. This will generate a udiv in96/// the process, and Builder's insert point will be pointing at the udiv (if97/// present, i.e. not folded), ready to be expanded if the user wishes.98static Value *generateSignedDivisionCode(Value *Dividend, Value *Divisor,99IRBuilder<> &Builder) {100// Implementation taken from compiler-rt's __divsi3 and __divdi3101102unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();103ConstantInt *Shift = Builder.getIntN(BitWidth, BitWidth - 1);104105// Following instructions are generated for both i32 (shift 31) and106// i64 (shift 63).107108// ; %tmp = ashr i32 %dividend, 31109// ; %tmp1 = ashr i32 %divisor, 31110// ; %tmp2 = xor i32 %tmp, %dividend111// ; %u_dvnd = sub nsw i32 %tmp2, %tmp112// ; %tmp3 = xor i32 %tmp1, %divisor113// ; %u_dvsr = sub nsw i32 %tmp3, %tmp1114// ; %q_sgn = xor i32 %tmp1, %tmp115// ; %q_mag = udiv i32 %u_dvnd, %u_dvsr116// ; %tmp4 = xor i32 %q_mag, %q_sgn117// ; %q = sub i32 %tmp4, %q_sgn118Dividend = Builder.CreateFreeze(Dividend);119Divisor = Builder.CreateFreeze(Divisor);120Value *Tmp = Builder.CreateAShr(Dividend, Shift);121Value *Tmp1 = Builder.CreateAShr(Divisor, Shift);122Value *Tmp2 = Builder.CreateXor(Tmp, Dividend);123Value *U_Dvnd = Builder.CreateSub(Tmp2, Tmp);124Value *Tmp3 = Builder.CreateXor(Tmp1, Divisor);125Value *U_Dvsr = Builder.CreateSub(Tmp3, Tmp1);126Value *Q_Sgn = Builder.CreateXor(Tmp1, Tmp);127Value *Q_Mag = Builder.CreateUDiv(U_Dvnd, U_Dvsr);128Value *Tmp4 = Builder.CreateXor(Q_Mag, Q_Sgn);129Value *Q = Builder.CreateSub(Tmp4, Q_Sgn);130131if (Instruction *UDiv = dyn_cast<Instruction>(Q_Mag))132Builder.SetInsertPoint(UDiv);133134return Q;135}136137/// Generates code to divide two unsigned scalar 32-bit or 64-bit integers.138/// Returns the quotient, rounded towards 0. Builder's insert point should139/// point where the caller wants code generated, e.g. at the udiv instruction.140static Value *generateUnsignedDivisionCode(Value *Dividend, Value *Divisor,141IRBuilder<> &Builder) {142// The basic algorithm can be found in the compiler-rt project's143// implementation of __udivsi3.c. Here, we do a lower-level IR based approach144// that's been hand-tuned to lessen the amount of control flow involved.145146// Some helper values147IntegerType *DivTy = cast<IntegerType>(Dividend->getType());148unsigned BitWidth = DivTy->getBitWidth();149150ConstantInt *Zero = ConstantInt::get(DivTy, 0);151ConstantInt *One = ConstantInt::get(DivTy, 1);152ConstantInt *NegOne = ConstantInt::getSigned(DivTy, -1);153ConstantInt *MSB = ConstantInt::get(DivTy, BitWidth - 1);154155ConstantInt *True = Builder.getTrue();156157BasicBlock *IBB = Builder.GetInsertBlock();158Function *F = IBB->getParent();159Function *CTLZ = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,160DivTy);161162// Our CFG is going to look like:163// +---------------------+164// | special-cases |165// | ... |166// +---------------------+167// | |168// | +----------+169// | | bb1 |170// | | ... |171// | +----------+172// | | |173// | | +------------+174// | | | preheader |175// | | | ... |176// | | +------------+177// | | |178// | | | +---+179// | | | | |180// | | +------------+ |181// | | | do-while | |182// | | | ... | |183// | | +------------+ |184// | | | | |185// | +-----------+ +---+186// | | loop-exit |187// | | ... |188// | +-----------+189// | |190// +-------+191// | ... |192// | end |193// +-------+194BasicBlock *SpecialCases = Builder.GetInsertBlock();195SpecialCases->setName(Twine(SpecialCases->getName(), "_udiv-special-cases"));196BasicBlock *End = SpecialCases->splitBasicBlock(Builder.GetInsertPoint(),197"udiv-end");198BasicBlock *LoopExit = BasicBlock::Create(Builder.getContext(),199"udiv-loop-exit", F, End);200BasicBlock *DoWhile = BasicBlock::Create(Builder.getContext(),201"udiv-do-while", F, End);202BasicBlock *Preheader = BasicBlock::Create(Builder.getContext(),203"udiv-preheader", F, End);204BasicBlock *BB1 = BasicBlock::Create(Builder.getContext(),205"udiv-bb1", F, End);206207// We'll be overwriting the terminator to insert our extra blocks208SpecialCases->getTerminator()->eraseFromParent();209210// Same instructions are generated for both i32 (msb 31) and i64 (msb 63).211212// First off, check for special cases: dividend or divisor is zero, divisor213// is greater than dividend, and divisor is 1.214// ; special-cases:215// ; %ret0_1 = icmp eq i32 %divisor, 0216// ; %ret0_2 = icmp eq i32 %dividend, 0217// ; %ret0_3 = or i1 %ret0_1, %ret0_2218// ; %tmp0 = tail call i32 @llvm.ctlz.i32(i32 %divisor, i1 true)219// ; %tmp1 = tail call i32 @llvm.ctlz.i32(i32 %dividend, i1 true)220// ; %sr = sub nsw i32 %tmp0, %tmp1221// ; %ret0_4 = icmp ugt i32 %sr, 31222// ; %ret0 = select i1 %ret0_3, i1 true, i1 %ret0_4223// ; %retDividend = icmp eq i32 %sr, 31224// ; %retVal = select i1 %ret0, i32 0, i32 %dividend225// ; %earlyRet = select i1 %ret0, i1 true, %retDividend226// ; br i1 %earlyRet, label %end, label %bb1227Builder.SetInsertPoint(SpecialCases);228Divisor = Builder.CreateFreeze(Divisor);229Dividend = Builder.CreateFreeze(Dividend);230Value *Ret0_1 = Builder.CreateICmpEQ(Divisor, Zero);231Value *Ret0_2 = Builder.CreateICmpEQ(Dividend, Zero);232Value *Ret0_3 = Builder.CreateOr(Ret0_1, Ret0_2);233Value *Tmp0 = Builder.CreateCall(CTLZ, {Divisor, True});234Value *Tmp1 = Builder.CreateCall(CTLZ, {Dividend, True});235Value *SR = Builder.CreateSub(Tmp0, Tmp1);236Value *Ret0_4 = Builder.CreateICmpUGT(SR, MSB);237Value *Ret0 = Builder.CreateLogicalOr(Ret0_3, Ret0_4);238Value *RetDividend = Builder.CreateICmpEQ(SR, MSB);239Value *RetVal = Builder.CreateSelect(Ret0, Zero, Dividend);240Value *EarlyRet = Builder.CreateLogicalOr(Ret0, RetDividend);241Builder.CreateCondBr(EarlyRet, End, BB1);242243// ; bb1: ; preds = %special-cases244// ; %sr_1 = add i32 %sr, 1245// ; %tmp2 = sub i32 31, %sr246// ; %q = shl i32 %dividend, %tmp2247// ; %skipLoop = icmp eq i32 %sr_1, 0248// ; br i1 %skipLoop, label %loop-exit, label %preheader249Builder.SetInsertPoint(BB1);250Value *SR_1 = Builder.CreateAdd(SR, One);251Value *Tmp2 = Builder.CreateSub(MSB, SR);252Value *Q = Builder.CreateShl(Dividend, Tmp2);253Value *SkipLoop = Builder.CreateICmpEQ(SR_1, Zero);254Builder.CreateCondBr(SkipLoop, LoopExit, Preheader);255256// ; preheader: ; preds = %bb1257// ; %tmp3 = lshr i32 %dividend, %sr_1258// ; %tmp4 = add i32 %divisor, -1259// ; br label %do-while260Builder.SetInsertPoint(Preheader);261Value *Tmp3 = Builder.CreateLShr(Dividend, SR_1);262Value *Tmp4 = Builder.CreateAdd(Divisor, NegOne);263Builder.CreateBr(DoWhile);264265// ; do-while: ; preds = %do-while, %preheader266// ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]267// ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]268// ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]269// ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]270// ; %tmp5 = shl i32 %r_1, 1271// ; %tmp6 = lshr i32 %q_2, 31272// ; %tmp7 = or i32 %tmp5, %tmp6273// ; %tmp8 = shl i32 %q_2, 1274// ; %q_1 = or i32 %carry_1, %tmp8275// ; %tmp9 = sub i32 %tmp4, %tmp7276// ; %tmp10 = ashr i32 %tmp9, 31277// ; %carry = and i32 %tmp10, 1278// ; %tmp11 = and i32 %tmp10, %divisor279// ; %r = sub i32 %tmp7, %tmp11280// ; %sr_2 = add i32 %sr_3, -1281// ; %tmp12 = icmp eq i32 %sr_2, 0282// ; br i1 %tmp12, label %loop-exit, label %do-while283Builder.SetInsertPoint(DoWhile);284PHINode *Carry_1 = Builder.CreatePHI(DivTy, 2);285PHINode *SR_3 = Builder.CreatePHI(DivTy, 2);286PHINode *R_1 = Builder.CreatePHI(DivTy, 2);287PHINode *Q_2 = Builder.CreatePHI(DivTy, 2);288Value *Tmp5 = Builder.CreateShl(R_1, One);289Value *Tmp6 = Builder.CreateLShr(Q_2, MSB);290Value *Tmp7 = Builder.CreateOr(Tmp5, Tmp6);291Value *Tmp8 = Builder.CreateShl(Q_2, One);292Value *Q_1 = Builder.CreateOr(Carry_1, Tmp8);293Value *Tmp9 = Builder.CreateSub(Tmp4, Tmp7);294Value *Tmp10 = Builder.CreateAShr(Tmp9, MSB);295Value *Carry = Builder.CreateAnd(Tmp10, One);296Value *Tmp11 = Builder.CreateAnd(Tmp10, Divisor);297Value *R = Builder.CreateSub(Tmp7, Tmp11);298Value *SR_2 = Builder.CreateAdd(SR_3, NegOne);299Value *Tmp12 = Builder.CreateICmpEQ(SR_2, Zero);300Builder.CreateCondBr(Tmp12, LoopExit, DoWhile);301302// ; loop-exit: ; preds = %do-while, %bb1303// ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]304// ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]305// ; %tmp13 = shl i32 %q_3, 1306// ; %q_4 = or i32 %carry_2, %tmp13307// ; br label %end308Builder.SetInsertPoint(LoopExit);309PHINode *Carry_2 = Builder.CreatePHI(DivTy, 2);310PHINode *Q_3 = Builder.CreatePHI(DivTy, 2);311Value *Tmp13 = Builder.CreateShl(Q_3, One);312Value *Q_4 = Builder.CreateOr(Carry_2, Tmp13);313Builder.CreateBr(End);314315// ; end: ; preds = %loop-exit, %special-cases316// ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]317// ; ret i32 %q_5318Builder.SetInsertPoint(End, End->begin());319PHINode *Q_5 = Builder.CreatePHI(DivTy, 2);320321// Populate the Phis, since all values have now been created. Our Phis were:322// ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]323Carry_1->addIncoming(Zero, Preheader);324Carry_1->addIncoming(Carry, DoWhile);325// ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]326SR_3->addIncoming(SR_1, Preheader);327SR_3->addIncoming(SR_2, DoWhile);328// ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]329R_1->addIncoming(Tmp3, Preheader);330R_1->addIncoming(R, DoWhile);331// ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]332Q_2->addIncoming(Q, Preheader);333Q_2->addIncoming(Q_1, DoWhile);334// ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]335Carry_2->addIncoming(Zero, BB1);336Carry_2->addIncoming(Carry, DoWhile);337// ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]338Q_3->addIncoming(Q, BB1);339Q_3->addIncoming(Q_1, DoWhile);340// ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]341Q_5->addIncoming(Q_4, LoopExit);342Q_5->addIncoming(RetVal, SpecialCases);343344return Q_5;345}346347/// Generate code to calculate the remainder of two integers, replacing Rem with348/// the generated code. This currently generates code using the udiv expansion,349/// but future work includes generating more specialized code, e.g. when more350/// information about the operands are known.351///352/// Replace Rem with generated code.353bool llvm::expandRemainder(BinaryOperator *Rem) {354assert((Rem->getOpcode() == Instruction::SRem ||355Rem->getOpcode() == Instruction::URem) &&356"Trying to expand remainder from a non-remainder function");357358IRBuilder<> Builder(Rem);359360assert(!Rem->getType()->isVectorTy() && "Div over vectors not supported");361362// First prepare the sign if it's a signed remainder363if (Rem->getOpcode() == Instruction::SRem) {364Value *Remainder = generateSignedRemainderCode(Rem->getOperand(0),365Rem->getOperand(1), Builder);366367// Check whether this is the insert point while Rem is still valid.368bool IsInsertPoint = Rem->getIterator() == Builder.GetInsertPoint();369Rem->replaceAllUsesWith(Remainder);370Rem->dropAllReferences();371Rem->eraseFromParent();372373// If we didn't actually generate an urem instruction, we're done374// This happens for example if the input were constant. In this case the375// Builder insertion point was unchanged376if (IsInsertPoint)377return true;378379BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());380Rem = BO;381}382383Value *Remainder = generatedUnsignedRemainderCode(Rem->getOperand(0),384Rem->getOperand(1),385Builder);386387Rem->replaceAllUsesWith(Remainder);388Rem->dropAllReferences();389Rem->eraseFromParent();390391// Expand the udiv392if (BinaryOperator *UDiv = dyn_cast<BinaryOperator>(Builder.GetInsertPoint())) {393assert(UDiv->getOpcode() == Instruction::UDiv && "Non-udiv in expansion?");394expandDivision(UDiv);395}396397return true;398}399400/// Generate code to divide two integers, replacing Div with the generated401/// code. This currently generates code similarly to compiler-rt's402/// implementations, but future work includes generating more specialized code403/// when more information about the operands are known.404///405/// Replace Div with generated code.406bool llvm::expandDivision(BinaryOperator *Div) {407assert((Div->getOpcode() == Instruction::SDiv ||408Div->getOpcode() == Instruction::UDiv) &&409"Trying to expand division from a non-division function");410411IRBuilder<> Builder(Div);412413assert(!Div->getType()->isVectorTy() && "Div over vectors not supported");414415// First prepare the sign if it's a signed division416if (Div->getOpcode() == Instruction::SDiv) {417// Lower the code to unsigned division, and reset Div to point to the udiv.418Value *Quotient = generateSignedDivisionCode(Div->getOperand(0),419Div->getOperand(1), Builder);420421// Check whether this is the insert point while Div is still valid.422bool IsInsertPoint = Div->getIterator() == Builder.GetInsertPoint();423Div->replaceAllUsesWith(Quotient);424Div->dropAllReferences();425Div->eraseFromParent();426427// If we didn't actually generate an udiv instruction, we're done428// This happens for example if the input were constant. In this case the429// Builder insertion point was unchanged430if (IsInsertPoint)431return true;432433BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());434Div = BO;435}436437// Insert the unsigned division code438Value *Quotient = generateUnsignedDivisionCode(Div->getOperand(0),439Div->getOperand(1),440Builder);441Div->replaceAllUsesWith(Quotient);442Div->dropAllReferences();443Div->eraseFromParent();444445return true;446}447448/// Generate code to compute the remainder of two integers of bitwidth up to449/// 32 bits. Uses the above routines and extends the inputs/truncates the450/// outputs to operate in 32 bits; that is, these routines are good for targets451/// that have no or very little suppport for smaller than 32 bit integer452/// arithmetic.453///454/// Replace Rem with emulation code.455bool llvm::expandRemainderUpTo32Bits(BinaryOperator *Rem) {456assert((Rem->getOpcode() == Instruction::SRem ||457Rem->getOpcode() == Instruction::URem) &&458"Trying to expand remainder from a non-remainder function");459460Type *RemTy = Rem->getType();461assert(!RemTy->isVectorTy() && "Div over vectors not supported");462463unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();464465assert(RemTyBitWidth <= 32 &&466"Div of bitwidth greater than 32 not supported");467468if (RemTyBitWidth == 32)469return expandRemainder(Rem);470471// If bitwidth smaller than 32 extend inputs, extend output and proceed472// with 32 bit division.473IRBuilder<> Builder(Rem);474475Value *ExtDividend;476Value *ExtDivisor;477Value *ExtRem;478Value *Trunc;479Type *Int32Ty = Builder.getInt32Ty();480481if (Rem->getOpcode() == Instruction::SRem) {482ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int32Ty);483ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int32Ty);484ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);485} else {486ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int32Ty);487ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int32Ty);488ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);489}490Trunc = Builder.CreateTrunc(ExtRem, RemTy);491492Rem->replaceAllUsesWith(Trunc);493Rem->dropAllReferences();494Rem->eraseFromParent();495496return expandRemainder(cast<BinaryOperator>(ExtRem));497}498499/// Generate code to compute the remainder of two integers of bitwidth up to500/// 64 bits. Uses the above routines and extends the inputs/truncates the501/// outputs to operate in 64 bits.502///503/// Replace Rem with emulation code.504bool llvm::expandRemainderUpTo64Bits(BinaryOperator *Rem) {505assert((Rem->getOpcode() == Instruction::SRem ||506Rem->getOpcode() == Instruction::URem) &&507"Trying to expand remainder from a non-remainder function");508509Type *RemTy = Rem->getType();510assert(!RemTy->isVectorTy() && "Div over vectors not supported");511512unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();513514if (RemTyBitWidth >= 64)515return expandRemainder(Rem);516517// If bitwidth smaller than 64 extend inputs, extend output and proceed518// with 64 bit division.519IRBuilder<> Builder(Rem);520521Value *ExtDividend;522Value *ExtDivisor;523Value *ExtRem;524Value *Trunc;525Type *Int64Ty = Builder.getInt64Ty();526527if (Rem->getOpcode() == Instruction::SRem) {528ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int64Ty);529ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int64Ty);530ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);531} else {532ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int64Ty);533ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int64Ty);534ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);535}536Trunc = Builder.CreateTrunc(ExtRem, RemTy);537538Rem->replaceAllUsesWith(Trunc);539Rem->dropAllReferences();540Rem->eraseFromParent();541542return expandRemainder(cast<BinaryOperator>(ExtRem));543}544545/// Generate code to divide two integers of bitwidth up to 32 bits. Uses the546/// above routines and extends the inputs/truncates the outputs to operate547/// in 32 bits; that is, these routines are good for targets that have no548/// or very little support for smaller than 32 bit integer arithmetic.549///550/// Replace Div with emulation code.551bool llvm::expandDivisionUpTo32Bits(BinaryOperator *Div) {552assert((Div->getOpcode() == Instruction::SDiv ||553Div->getOpcode() == Instruction::UDiv) &&554"Trying to expand division from a non-division function");555556Type *DivTy = Div->getType();557assert(!DivTy->isVectorTy() && "Div over vectors not supported");558559unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();560561assert(DivTyBitWidth <= 32 && "Div of bitwidth greater than 32 not supported");562563if (DivTyBitWidth == 32)564return expandDivision(Div);565566// If bitwidth smaller than 32 extend inputs, extend output and proceed567// with 32 bit division.568IRBuilder<> Builder(Div);569570Value *ExtDividend;571Value *ExtDivisor;572Value *ExtDiv;573Value *Trunc;574Type *Int32Ty = Builder.getInt32Ty();575576if (Div->getOpcode() == Instruction::SDiv) {577ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int32Ty);578ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int32Ty);579ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);580} else {581ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int32Ty);582ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int32Ty);583ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);584}585Trunc = Builder.CreateTrunc(ExtDiv, DivTy);586587Div->replaceAllUsesWith(Trunc);588Div->dropAllReferences();589Div->eraseFromParent();590591return expandDivision(cast<BinaryOperator>(ExtDiv));592}593594/// Generate code to divide two integers of bitwidth up to 64 bits. Uses the595/// above routines and extends the inputs/truncates the outputs to operate596/// in 64 bits.597///598/// Replace Div with emulation code.599bool llvm::expandDivisionUpTo64Bits(BinaryOperator *Div) {600assert((Div->getOpcode() == Instruction::SDiv ||601Div->getOpcode() == Instruction::UDiv) &&602"Trying to expand division from a non-division function");603604Type *DivTy = Div->getType();605assert(!DivTy->isVectorTy() && "Div over vectors not supported");606607unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();608609if (DivTyBitWidth >= 64)610return expandDivision(Div);611612// If bitwidth smaller than 64 extend inputs, extend output and proceed613// with 64 bit division.614IRBuilder<> Builder(Div);615616Value *ExtDividend;617Value *ExtDivisor;618Value *ExtDiv;619Value *Trunc;620Type *Int64Ty = Builder.getInt64Ty();621622if (Div->getOpcode() == Instruction::SDiv) {623ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int64Ty);624ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int64Ty);625ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);626} else {627ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int64Ty);628ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int64Ty);629ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);630}631Trunc = Builder.CreateTrunc(ExtDiv, DivTy);632633Div->replaceAllUsesWith(Trunc);634Div->dropAllReferences();635Div->eraseFromParent();636637return expandDivision(cast<BinaryOperator>(ExtDiv));638}639640641