LLVM API Documentation

IntegerDivision.cpp
Go to the documentation of this file.
00001 //===-- IntegerDivision.cpp - Expand integer division ---------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains an implementation of 32bit scalar integer division for
00011 // targets that don't have native support. It's largely derived from
00012 // compiler-rt's implementation of __udivsi3, but hand-tuned to reduce the
00013 // amount of control flow
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #define DEBUG_TYPE "integer-division"
00018 #include "llvm/Transforms/Utils/IntegerDivision.h"
00019 #include "llvm/IR/Function.h"
00020 #include "llvm/IR/IRBuilder.h"
00021 #include "llvm/IR/Instructions.h"
00022 #include "llvm/IR/Intrinsics.h"
00023 
00024 using namespace llvm;
00025 
00026 /// Generate code to compute the remainder of two signed integers. Returns the
00027 /// remainder, which will have the sign of the dividend. Builder's insert point
00028 /// should be pointing where the caller wants code generated, e.g. at the srem
00029 /// instruction. This will generate a urem in the process, and Builder's insert
00030 /// point will be pointing at the uren (if present, i.e. not folded), ready to
00031 /// be expanded if the user wishes
00032 static Value *generateSignedRemainderCode(Value *Dividend, Value *Divisor,
00033                                           IRBuilder<> &Builder) {
00034   ConstantInt *ThirtyOne = Builder.getInt32(31);
00035 
00036   // ;   %dividend_sgn = ashr i32 %dividend, 31
00037   // ;   %divisor_sgn  = ashr i32 %divisor, 31
00038   // ;   %dvd_xor      = xor i32 %dividend, %dividend_sgn
00039   // ;   %dvs_xor      = xor i32 %divisor, %divisor_sgn
00040   // ;   %u_dividend   = sub i32 %dvd_xor, %dividend_sgn
00041   // ;   %u_divisor    = sub i32 %dvs_xor, %divisor_sgn
00042   // ;   %urem         = urem i32 %dividend, %divisor
00043   // ;   %xored        = xor i32 %urem, %dividend_sgn
00044   // ;   %srem         = sub i32 %xored, %dividend_sgn
00045   Value *DividendSign = Builder.CreateAShr(Dividend, ThirtyOne);
00046   Value *DivisorSign  = Builder.CreateAShr(Divisor, ThirtyOne);
00047   Value *DvdXor       = Builder.CreateXor(Dividend, DividendSign);
00048   Value *DvsXor       = Builder.CreateXor(Divisor, DivisorSign);
00049   Value *UDividend    = Builder.CreateSub(DvdXor, DividendSign);
00050   Value *UDivisor     = Builder.CreateSub(DvsXor, DivisorSign);
00051   Value *URem         = Builder.CreateURem(UDividend, UDivisor);
00052   Value *Xored        = Builder.CreateXor(URem, DividendSign);
00053   Value *SRem         = Builder.CreateSub(Xored, DividendSign);
00054 
00055   if (Instruction *URemInst = dyn_cast<Instruction>(URem))
00056     Builder.SetInsertPoint(URemInst);
00057 
00058   return SRem;
00059 }
00060 
00061 
00062 /// Generate code to compute the remainder of two unsigned integers. Returns the
00063 /// remainder. Builder's insert point should be pointing where the caller wants
00064 /// code generated, e.g. at the urem instruction. This will generate a udiv in
00065 /// the process, and Builder's insert point will be pointing at the udiv (if
00066 /// present, i.e. not folded), ready to be expanded if the user wishes
00067 static Value *generatedUnsignedRemainderCode(Value *Dividend, Value *Divisor,
00068                                              IRBuilder<> &Builder) {
00069   // Remainder = Dividend - Quotient*Divisor
00070 
00071   // ;   %quotient  = udiv i32 %dividend, %divisor
00072   // ;   %product   = mul i32 %divisor, %quotient
00073   // ;   %remainder = sub i32 %dividend, %product
00074   Value *Quotient  = Builder.CreateUDiv(Dividend, Divisor);
00075   Value *Product   = Builder.CreateMul(Divisor, Quotient);
00076   Value *Remainder = Builder.CreateSub(Dividend, Product);
00077 
00078   if (Instruction *UDiv = dyn_cast<Instruction>(Quotient))
00079     Builder.SetInsertPoint(UDiv);
00080 
00081   return Remainder;
00082 }
00083 
00084 /// Generate code to divide two signed integers. Returns the quotient, rounded
00085 /// towards 0. Builder's insert point should be pointing where the caller wants
00086 /// code generated, e.g. at the sdiv instruction. This will generate a udiv in
00087 /// the process, and Builder's insert point will be pointing at the udiv (if
00088 /// present, i.e. not folded), ready to be expanded if the user wishes.
00089 static Value *generateSignedDivisionCode(Value *Dividend, Value *Divisor,
00090                                          IRBuilder<> &Builder) {
00091   // Implementation taken from compiler-rt's __divsi3
00092 
00093   ConstantInt *ThirtyOne = Builder.getInt32(31);
00094 
00095   // ;   %tmp    = ashr i32 %dividend, 31
00096   // ;   %tmp1   = ashr i32 %divisor, 31
00097   // ;   %tmp2   = xor i32 %tmp, %dividend
00098   // ;   %u_dvnd = sub nsw i32 %tmp2, %tmp
00099   // ;   %tmp3   = xor i32 %tmp1, %divisor
00100   // ;   %u_dvsr = sub nsw i32 %tmp3, %tmp1
00101   // ;   %q_sgn  = xor i32 %tmp1, %tmp
00102   // ;   %q_mag  = udiv i32 %u_dvnd, %u_dvsr
00103   // ;   %tmp4   = xor i32 %q_mag, %q_sgn
00104   // ;   %q      = sub i32 %tmp4, %q_sgn
00105   Value *Tmp    = Builder.CreateAShr(Dividend, ThirtyOne);
00106   Value *Tmp1   = Builder.CreateAShr(Divisor, ThirtyOne);
00107   Value *Tmp2   = Builder.CreateXor(Tmp, Dividend);
00108   Value *U_Dvnd = Builder.CreateSub(Tmp2, Tmp);
00109   Value *Tmp3   = Builder.CreateXor(Tmp1, Divisor);
00110   Value *U_Dvsr = Builder.CreateSub(Tmp3, Tmp1);
00111   Value *Q_Sgn  = Builder.CreateXor(Tmp1, Tmp);
00112   Value *Q_Mag  = Builder.CreateUDiv(U_Dvnd, U_Dvsr);
00113   Value *Tmp4   = Builder.CreateXor(Q_Mag, Q_Sgn);
00114   Value *Q      = Builder.CreateSub(Tmp4, Q_Sgn);
00115 
00116   if (Instruction *UDiv = dyn_cast<Instruction>(Q_Mag))
00117     Builder.SetInsertPoint(UDiv);
00118 
00119   return Q;
00120 }
00121 
00122 /// Generates code to divide two unsigned scalar 32-bit integers. Returns the
00123 /// quotient, rounded towards 0. Builder's insert point should be pointing where
00124 /// the caller wants code generated, e.g. at the udiv instruction.
00125 static Value *generateUnsignedDivisionCode(Value *Dividend, Value *Divisor,
00126                                            IRBuilder<> &Builder) {
00127   // The basic algorithm can be found in the compiler-rt project's
00128   // implementation of __udivsi3.c. Here, we do a lower-level IR based approach
00129   // that's been hand-tuned to lessen the amount of control flow involved.
00130 
00131   // Some helper values
00132   IntegerType *I32Ty = Builder.getInt32Ty();
00133 
00134   ConstantInt *Zero      = Builder.getInt32(0);
00135   ConstantInt *One       = Builder.getInt32(1);
00136   ConstantInt *ThirtyOne = Builder.getInt32(31);
00137   ConstantInt *NegOne    = ConstantInt::getSigned(I32Ty, -1);
00138   ConstantInt *True      = Builder.getTrue();
00139 
00140   BasicBlock *IBB = Builder.GetInsertBlock();
00141   Function *F = IBB->getParent();
00142   Function *CTLZi32 = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
00143                                                 I32Ty);
00144 
00145   // Our CFG is going to look like:
00146   // +---------------------+
00147   // | special-cases       |
00148   // |   ...               |
00149   // +---------------------+
00150   //  |       |
00151   //  |   +----------+
00152   //  |   |  bb1     |
00153   //  |   |  ...     |
00154   //  |   +----------+
00155   //  |    |      |
00156   //  |    |  +------------+
00157   //  |    |  |  preheader |
00158   //  |    |  |  ...       |
00159   //  |    |  +------------+
00160   //  |    |      |
00161   //  |    |      |      +---+
00162   //  |    |      |      |   |
00163   //  |    |  +------------+ |
00164   //  |    |  |  do-while  | |
00165   //  |    |  |  ...       | |
00166   //  |    |  +------------+ |
00167   //  |    |      |      |   |
00168   //  |   +-----------+  +---+
00169   //  |   | loop-exit |
00170   //  |   |  ...      |
00171   //  |   +-----------+
00172   //  |     |
00173   // +-------+
00174   // | ...   |
00175   // | end   |
00176   // +-------+
00177   BasicBlock *SpecialCases = Builder.GetInsertBlock();
00178   SpecialCases->setName(Twine(SpecialCases->getName(), "_udiv-special-cases"));
00179   BasicBlock *End = SpecialCases->splitBasicBlock(Builder.GetInsertPoint(),
00180                                                   "udiv-end");
00181   BasicBlock *LoopExit  = BasicBlock::Create(Builder.getContext(),
00182                                              "udiv-loop-exit", F, End);
00183   BasicBlock *DoWhile   = BasicBlock::Create(Builder.getContext(),
00184                                              "udiv-do-while", F, End);
00185   BasicBlock *Preheader = BasicBlock::Create(Builder.getContext(),
00186                                              "udiv-preheader", F, End);
00187   BasicBlock *BB1       = BasicBlock::Create(Builder.getContext(),
00188                                              "udiv-bb1", F, End);
00189 
00190   // We'll be overwriting the terminator to insert our extra blocks
00191   SpecialCases->getTerminator()->eraseFromParent();
00192 
00193   // First off, check for special cases: dividend or divisor is zero, divisor
00194   // is greater than dividend, and divisor is 1.
00195   // ; special-cases:
00196   // ;   %ret0_1      = icmp eq i32 %divisor, 0
00197   // ;   %ret0_2      = icmp eq i32 %dividend, 0
00198   // ;   %ret0_3      = or i1 %ret0_1, %ret0_2
00199   // ;   %tmp0        = tail call i32 @llvm.ctlz.i32(i32 %divisor, i1 true)
00200   // ;   %tmp1        = tail call i32 @llvm.ctlz.i32(i32 %dividend, i1 true)
00201   // ;   %sr          = sub nsw i32 %tmp0, %tmp1
00202   // ;   %ret0_4      = icmp ugt i32 %sr, 31
00203   // ;   %ret0        = or i1 %ret0_3, %ret0_4
00204   // ;   %retDividend = icmp eq i32 %sr, 31
00205   // ;   %retVal      = select i1 %ret0, i32 0, i32 %dividend
00206   // ;   %earlyRet    = or i1 %ret0, %retDividend
00207   // ;   br i1 %earlyRet, label %end, label %bb1
00208   Builder.SetInsertPoint(SpecialCases);
00209   Value *Ret0_1      = Builder.CreateICmpEQ(Divisor, Zero);
00210   Value *Ret0_2      = Builder.CreateICmpEQ(Dividend, Zero);
00211   Value *Ret0_3      = Builder.CreateOr(Ret0_1, Ret0_2);
00212   Value *Tmp0        = Builder.CreateCall2(CTLZi32, Divisor, True);
00213   Value *Tmp1        = Builder.CreateCall2(CTLZi32, Dividend, True);
00214   Value *SR          = Builder.CreateSub(Tmp0, Tmp1);
00215   Value *Ret0_4      = Builder.CreateICmpUGT(SR, ThirtyOne);
00216   Value *Ret0        = Builder.CreateOr(Ret0_3, Ret0_4);
00217   Value *RetDividend = Builder.CreateICmpEQ(SR, ThirtyOne);
00218   Value *RetVal      = Builder.CreateSelect(Ret0, Zero, Dividend);
00219   Value *EarlyRet    = Builder.CreateOr(Ret0, RetDividend);
00220   Builder.CreateCondBr(EarlyRet, End, BB1);
00221 
00222   // ; bb1:                                             ; preds = %special-cases
00223   // ;   %sr_1     = add i32 %sr, 1
00224   // ;   %tmp2     = sub i32 31, %sr
00225   // ;   %q        = shl i32 %dividend, %tmp2
00226   // ;   %skipLoop = icmp eq i32 %sr_1, 0
00227   // ;   br i1 %skipLoop, label %loop-exit, label %preheader
00228   Builder.SetInsertPoint(BB1);
00229   Value *SR_1     = Builder.CreateAdd(SR, One);
00230   Value *Tmp2     = Builder.CreateSub(ThirtyOne, SR);
00231   Value *Q        = Builder.CreateShl(Dividend, Tmp2);
00232   Value *SkipLoop = Builder.CreateICmpEQ(SR_1, Zero);
00233   Builder.CreateCondBr(SkipLoop, LoopExit, Preheader);
00234 
00235   // ; preheader:                                           ; preds = %bb1
00236   // ;   %tmp3 = lshr i32 %dividend, %sr_1
00237   // ;   %tmp4 = add i32 %divisor, -1
00238   // ;   br label %do-while
00239   Builder.SetInsertPoint(Preheader);
00240   Value *Tmp3 = Builder.CreateLShr(Dividend, SR_1);
00241   Value *Tmp4 = Builder.CreateAdd(Divisor, NegOne);
00242   Builder.CreateBr(DoWhile);
00243 
00244   // ; do-while:                                 ; preds = %do-while, %preheader
00245   // ;   %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
00246   // ;   %sr_3    = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
00247   // ;   %r_1     = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
00248   // ;   %q_2     = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
00249   // ;   %tmp5  = shl i32 %r_1, 1
00250   // ;   %tmp6  = lshr i32 %q_2, 31
00251   // ;   %tmp7  = or i32 %tmp5, %tmp6
00252   // ;   %tmp8  = shl i32 %q_2, 1
00253   // ;   %q_1   = or i32 %carry_1, %tmp8
00254   // ;   %tmp9  = sub i32 %tmp4, %tmp7
00255   // ;   %tmp10 = ashr i32 %tmp9, 31
00256   // ;   %carry = and i32 %tmp10, 1
00257   // ;   %tmp11 = and i32 %tmp10, %divisor
00258   // ;   %r     = sub i32 %tmp7, %tmp11
00259   // ;   %sr_2  = add i32 %sr_3, -1
00260   // ;   %tmp12 = icmp eq i32 %sr_2, 0
00261   // ;   br i1 %tmp12, label %loop-exit, label %do-while
00262   Builder.SetInsertPoint(DoWhile);
00263   PHINode *Carry_1 = Builder.CreatePHI(I32Ty, 2);
00264   PHINode *SR_3    = Builder.CreatePHI(I32Ty, 2);
00265   PHINode *R_1     = Builder.CreatePHI(I32Ty, 2);
00266   PHINode *Q_2     = Builder.CreatePHI(I32Ty, 2);
00267   Value *Tmp5  = Builder.CreateShl(R_1, One);
00268   Value *Tmp6  = Builder.CreateLShr(Q_2, ThirtyOne);
00269   Value *Tmp7  = Builder.CreateOr(Tmp5, Tmp6);
00270   Value *Tmp8  = Builder.CreateShl(Q_2, One);
00271   Value *Q_1   = Builder.CreateOr(Carry_1, Tmp8);
00272   Value *Tmp9  = Builder.CreateSub(Tmp4, Tmp7);
00273   Value *Tmp10 = Builder.CreateAShr(Tmp9, 31);
00274   Value *Carry = Builder.CreateAnd(Tmp10, One);
00275   Value *Tmp11 = Builder.CreateAnd(Tmp10, Divisor);
00276   Value *R     = Builder.CreateSub(Tmp7, Tmp11);
00277   Value *SR_2  = Builder.CreateAdd(SR_3, NegOne);
00278   Value *Tmp12 = Builder.CreateICmpEQ(SR_2, Zero);
00279   Builder.CreateCondBr(Tmp12, LoopExit, DoWhile);
00280 
00281   // ; loop-exit:                                      ; preds = %do-while, %bb1
00282   // ;   %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
00283   // ;   %q_3     = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
00284   // ;   %tmp13 = shl i32 %q_3, 1
00285   // ;   %q_4   = or i32 %carry_2, %tmp13
00286   // ;   br label %end
00287   Builder.SetInsertPoint(LoopExit);
00288   PHINode *Carry_2 = Builder.CreatePHI(I32Ty, 2);
00289   PHINode *Q_3     = Builder.CreatePHI(I32Ty, 2);
00290   Value *Tmp13 = Builder.CreateShl(Q_3, One);
00291   Value *Q_4   = Builder.CreateOr(Carry_2, Tmp13);
00292   Builder.CreateBr(End);
00293 
00294   // ; end:                                 ; preds = %loop-exit, %special-cases
00295   // ;   %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
00296   // ;   ret i32 %q_5
00297   Builder.SetInsertPoint(End, End->begin());
00298   PHINode *Q_5 = Builder.CreatePHI(I32Ty, 2);
00299 
00300   // Populate the Phis, since all values have now been created. Our Phis were:
00301   // ;   %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
00302   Carry_1->addIncoming(Zero, Preheader);
00303   Carry_1->addIncoming(Carry, DoWhile);
00304   // ;   %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
00305   SR_3->addIncoming(SR_1, Preheader);
00306   SR_3->addIncoming(SR_2, DoWhile);
00307   // ;   %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
00308   R_1->addIncoming(Tmp3, Preheader);
00309   R_1->addIncoming(R, DoWhile);
00310   // ;   %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
00311   Q_2->addIncoming(Q, Preheader);
00312   Q_2->addIncoming(Q_1, DoWhile);
00313   // ;   %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
00314   Carry_2->addIncoming(Zero, BB1);
00315   Carry_2->addIncoming(Carry, DoWhile);
00316   // ;   %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
00317   Q_3->addIncoming(Q, BB1);
00318   Q_3->addIncoming(Q_1, DoWhile);
00319   // ;   %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
00320   Q_5->addIncoming(Q_4, LoopExit);
00321   Q_5->addIncoming(RetVal, SpecialCases);
00322 
00323   return Q_5;
00324 }
00325 
00326 /// Generate code to calculate the remainder of two integers, replacing Rem with
00327 /// the generated code. This currently generates code using the udiv expansion,
00328 /// but future work includes generating more specialized code, e.g. when more
00329 /// information about the operands are known. Currently only implements 32bit
00330 /// scalar division (due to udiv's limitation), but future work is removing this
00331 /// limitation.
00332 ///
00333 /// @brief Replace Rem with generated code.
00334 bool llvm::expandRemainder(BinaryOperator *Rem) {
00335   assert((Rem->getOpcode() == Instruction::SRem ||
00336           Rem->getOpcode() == Instruction::URem) &&
00337          "Trying to expand remainder from a non-remainder function");
00338 
00339   IRBuilder<> Builder(Rem);
00340 
00341   // First prepare the sign if it's a signed remainder
00342   if (Rem->getOpcode() == Instruction::SRem) {
00343     Value *Remainder = generateSignedRemainderCode(Rem->getOperand(0),
00344                                                    Rem->getOperand(1), Builder);
00345 
00346     Rem->replaceAllUsesWith(Remainder);
00347     Rem->dropAllReferences();
00348     Rem->eraseFromParent();
00349 
00350     // If we didn't actually generate a udiv instruction, we're done
00351     BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
00352     if (!BO || BO->getOpcode() != Instruction::URem)
00353       return true;
00354 
00355     Rem = BO;
00356   }
00357 
00358   Value *Remainder = generatedUnsignedRemainderCode(Rem->getOperand(0),
00359                                                     Rem->getOperand(1),
00360                                                     Builder);
00361 
00362   Rem->replaceAllUsesWith(Remainder);
00363   Rem->dropAllReferences();
00364   Rem->eraseFromParent();
00365 
00366   // Expand the udiv
00367   if (BinaryOperator *UDiv = dyn_cast<BinaryOperator>(Builder.GetInsertPoint())) {
00368     assert(UDiv->getOpcode() == Instruction::UDiv && "Non-udiv in expansion?");
00369     expandDivision(UDiv);
00370   }
00371 
00372   return true;
00373 }
00374 
00375 
00376 /// Generate code to divide two integers, replacing Div with the generated
00377 /// code. This currently generates code similarly to compiler-rt's
00378 /// implementations, but future work includes generating more specialized code
00379 /// when more information about the operands are known. Currently only
00380 /// implements 32bit scalar division, but future work is removing this
00381 /// limitation.
00382 ///
00383 /// @brief Replace Div with generated code.
00384 bool llvm::expandDivision(BinaryOperator *Div) {
00385   assert((Div->getOpcode() == Instruction::SDiv ||
00386           Div->getOpcode() == Instruction::UDiv) &&
00387          "Trying to expand division from a non-division function");
00388 
00389   IRBuilder<> Builder(Div);
00390 
00391   if (Div->getType()->isVectorTy())
00392     llvm_unreachable("Div over vectors not supported");
00393 
00394   // First prepare the sign if it's a signed division
00395   if (Div->getOpcode() == Instruction::SDiv) {
00396     // Lower the code to unsigned division, and reset Div to point to the udiv.
00397     Value *Quotient = generateSignedDivisionCode(Div->getOperand(0),
00398                                                  Div->getOperand(1), Builder);
00399     Div->replaceAllUsesWith(Quotient);
00400     Div->dropAllReferences();
00401     Div->eraseFromParent();
00402 
00403     // If we didn't actually generate a udiv instruction, we're done
00404     BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
00405     if (!BO || BO->getOpcode() != Instruction::UDiv)
00406       return true;
00407 
00408     Div = BO;
00409   }
00410 
00411   // Insert the unsigned division code
00412   Value *Quotient = generateUnsignedDivisionCode(Div->getOperand(0),
00413                                                  Div->getOperand(1),
00414                                                  Builder);
00415   Div->replaceAllUsesWith(Quotient);
00416   Div->dropAllReferences();
00417   Div->eraseFromParent();
00418 
00419   return true;
00420 }
00421 
00422 /// Generate code to compute the remainder of two integers of bitwidth up to 
00423 /// 32 bits. Uses the above routines and extends the inputs/truncates the
00424 /// outputs to operate in 32 bits; that is, these routines are good for targets
00425 /// that have no or very little suppport for smaller than 32 bit integer 
00426 /// arithmetic.
00427 ///
00428 /// @brief Replace Rem with emulation code.
00429 bool llvm::expandRemainderUpTo32Bits(BinaryOperator *Rem) {
00430   assert((Rem->getOpcode() == Instruction::SRem ||
00431           Rem->getOpcode() == Instruction::URem) &&
00432           "Trying to expand remainder from a non-remainder function");
00433 
00434   Type *RemTy = Rem->getType();
00435   if (RemTy->isVectorTy())
00436     llvm_unreachable("Div over vectors not supported");
00437 
00438   unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
00439 
00440   if (RemTyBitWidth > 32) 
00441     llvm_unreachable("Div of bitwidth greater than 32 not supported");
00442 
00443   if (RemTyBitWidth == 32) 
00444     return expandRemainder(Rem);
00445 
00446   // If bitwidth smaller than 32 extend inputs, truncate output and proceed
00447   // with 32 bit division.
00448   IRBuilder<> Builder(Rem);
00449 
00450   Value *ExtDividend;
00451   Value *ExtDivisor;
00452   Value *ExtRem;
00453   Value *Trunc;
00454   Type *Int32Ty = Builder.getInt32Ty();
00455 
00456   if (Rem->getOpcode() == Instruction::SRem) {
00457     ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int32Ty);
00458     ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int32Ty);
00459     ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
00460   } else {
00461     ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int32Ty);
00462     ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int32Ty);
00463     ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
00464   }
00465   Trunc = Builder.CreateTrunc(ExtRem, RemTy);
00466 
00467   Rem->replaceAllUsesWith(Trunc);
00468   Rem->dropAllReferences();
00469   Rem->eraseFromParent();
00470 
00471   return expandRemainder(cast<BinaryOperator>(ExtRem));
00472 }
00473 
00474 
00475 /// Generate code to divide two integers of bitwidth up to 32 bits. Uses the
00476 /// above routines and extends the inputs/truncates the outputs to operate
00477 /// in 32 bits; that is, these routines are good for targets that have no
00478 /// or very little support for smaller than 32 bit integer arithmetic.
00479 ///
00480 /// @brief Replace Div with emulation code.
00481 bool llvm::expandDivisionUpTo32Bits(BinaryOperator *Div) {
00482   assert((Div->getOpcode() == Instruction::SDiv ||
00483           Div->getOpcode() == Instruction::UDiv) &&
00484           "Trying to expand division from a non-division function");
00485 
00486   Type *DivTy = Div->getType();
00487   if (DivTy->isVectorTy())
00488     llvm_unreachable("Div over vectors not supported");
00489 
00490   unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
00491 
00492   if (DivTyBitWidth > 32)
00493     llvm_unreachable("Div of bitwidth greater than 32 not supported");
00494 
00495   if (DivTyBitWidth == 32)
00496     return expandDivision(Div);
00497 
00498   // If bitwidth smaller than 32 extend inputs, truncate output and proceed
00499   // with 32 bit division.
00500   IRBuilder<> Builder(Div);
00501 
00502   Value *ExtDividend;
00503   Value *ExtDivisor;
00504   Value *ExtDiv;
00505   Value *Trunc;
00506   Type *Int32Ty = Builder.getInt32Ty();
00507 
00508   if (Div->getOpcode() == Instruction::SDiv) {
00509     ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int32Ty);
00510     ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int32Ty);
00511     ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
00512   } else {
00513     ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int32Ty);
00514     ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int32Ty);
00515     ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);  
00516   }
00517   Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
00518 
00519   Div->replaceAllUsesWith(Trunc);
00520   Div->dropAllReferences();
00521   Div->eraseFromParent();
00522 
00523   return expandDivision(cast<BinaryOperator>(ExtDiv));
00524 }