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 and 64bit scalar integer
00011 // division for targets that don't have native support. It's largely derived
00012 // from compiler-rt's implementations of __udivsi3 and __udivmoddi4,
00013 // but hand-tuned for targets that prefer less 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 #include <utility>
00024 
00025 using namespace llvm;
00026 
00027 /// Generate code to compute the remainder of two signed integers. Returns the
00028 /// remainder, which will have the sign of the dividend. Builder's insert point
00029 /// should be pointing where the caller wants code generated, e.g. at the srem
00030 /// instruction. This will generate a urem in the process, and Builder's insert
00031 /// point will be pointing at the uren (if present, i.e. not folded), ready to
00032 /// be expanded if the user wishes
00033 static Value *generateSignedRemainderCode(Value *Dividend, Value *Divisor,
00034                                           IRBuilder<> &Builder) {
00035   unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();
00036   ConstantInt *Shift;
00037 
00038   if (BitWidth == 64) {
00039     Shift = Builder.getInt64(63);
00040   } else {
00041     assert(BitWidth == 32 && "Unexpected bit width");
00042     Shift = Builder.getInt32(31);
00043   }
00044 
00045   // Following instructions are generated for both i32 (shift 31) and
00046   // i64 (shift 63).
00047 
00048   // ;   %dividend_sgn = ashr i32 %dividend, 31
00049   // ;   %divisor_sgn  = ashr i32 %divisor, 31
00050   // ;   %dvd_xor      = xor i32 %dividend, %dividend_sgn
00051   // ;   %dvs_xor      = xor i32 %divisor, %divisor_sgn
00052   // ;   %u_dividend   = sub i32 %dvd_xor, %dividend_sgn
00053   // ;   %u_divisor    = sub i32 %dvs_xor, %divisor_sgn
00054   // ;   %urem         = urem i32 %dividend, %divisor
00055   // ;   %xored        = xor i32 %urem, %dividend_sgn
00056   // ;   %srem         = sub i32 %xored, %dividend_sgn
00057   Value *DividendSign = Builder.CreateAShr(Dividend, Shift);
00058   Value *DivisorSign  = Builder.CreateAShr(Divisor, Shift);
00059   Value *DvdXor       = Builder.CreateXor(Dividend, DividendSign);
00060   Value *DvsXor       = Builder.CreateXor(Divisor, DivisorSign);
00061   Value *UDividend    = Builder.CreateSub(DvdXor, DividendSign);
00062   Value *UDivisor     = Builder.CreateSub(DvsXor, DivisorSign);
00063   Value *URem         = Builder.CreateURem(UDividend, UDivisor);
00064   Value *Xored        = Builder.CreateXor(URem, DividendSign);
00065   Value *SRem         = Builder.CreateSub(Xored, DividendSign);
00066 
00067   if (Instruction *URemInst = dyn_cast<Instruction>(URem))
00068     Builder.SetInsertPoint(URemInst);
00069 
00070   return SRem;
00071 }
00072 
00073 
00074 /// Generate code to compute the remainder of two unsigned integers. Returns the
00075 /// remainder. Builder's insert point should be pointing where the caller wants
00076 /// code generated, e.g. at the urem instruction. This will generate a udiv in
00077 /// the process, and Builder's insert point will be pointing at the udiv (if
00078 /// present, i.e. not folded), ready to be expanded if the user wishes
00079 static Value *generatedUnsignedRemainderCode(Value *Dividend, Value *Divisor,
00080                                              IRBuilder<> &Builder) {
00081   // Remainder = Dividend - Quotient*Divisor
00082 
00083   // Following instructions are generated for both i32 and i64
00084 
00085   // ;   %quotient  = udiv i32 %dividend, %divisor
00086   // ;   %product   = mul i32 %divisor, %quotient
00087   // ;   %remainder = sub i32 %dividend, %product
00088   Value *Quotient  = Builder.CreateUDiv(Dividend, Divisor);
00089   Value *Product   = Builder.CreateMul(Divisor, Quotient);
00090   Value *Remainder = Builder.CreateSub(Dividend, Product);
00091 
00092   if (Instruction *UDiv = dyn_cast<Instruction>(Quotient))
00093     Builder.SetInsertPoint(UDiv);
00094 
00095   return Remainder;
00096 }
00097 
00098 /// Generate code to divide two signed integers. Returns the quotient, rounded
00099 /// towards 0. Builder's insert point should be pointing where the caller wants
00100 /// code generated, e.g. at the sdiv instruction. This will generate a udiv in
00101 /// the process, and Builder's insert point will be pointing at the udiv (if
00102 /// present, i.e. not folded), ready to be expanded if the user wishes.
00103 static Value *generateSignedDivisionCode(Value *Dividend, Value *Divisor,
00104                                          IRBuilder<> &Builder) {
00105   // Implementation taken from compiler-rt's __divsi3 and __divdi3
00106 
00107   unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();
00108   ConstantInt *Shift;
00109 
00110   if (BitWidth == 64) {
00111     Shift = Builder.getInt64(63);
00112   } else {
00113     assert(BitWidth == 32 && "Unexpected bit width");
00114     Shift = Builder.getInt32(31);
00115   }
00116 
00117   // Following instructions are generated for both i32 (shift 31) and
00118   // i64 (shift 63).
00119 
00120   // ;   %tmp    = ashr i32 %dividend, 31
00121   // ;   %tmp1   = ashr i32 %divisor, 31
00122   // ;   %tmp2   = xor i32 %tmp, %dividend
00123   // ;   %u_dvnd = sub nsw i32 %tmp2, %tmp
00124   // ;   %tmp3   = xor i32 %tmp1, %divisor
00125   // ;   %u_dvsr = sub nsw i32 %tmp3, %tmp1
00126   // ;   %q_sgn  = xor i32 %tmp1, %tmp
00127   // ;   %q_mag  = udiv i32 %u_dvnd, %u_dvsr
00128   // ;   %tmp4   = xor i32 %q_mag, %q_sgn
00129   // ;   %q      = sub i32 %tmp4, %q_sgn
00130   Value *Tmp    = Builder.CreateAShr(Dividend, Shift);
00131   Value *Tmp1   = Builder.CreateAShr(Divisor, Shift);
00132   Value *Tmp2   = Builder.CreateXor(Tmp, Dividend);
00133   Value *U_Dvnd = Builder.CreateSub(Tmp2, Tmp);
00134   Value *Tmp3   = Builder.CreateXor(Tmp1, Divisor);
00135   Value *U_Dvsr = Builder.CreateSub(Tmp3, Tmp1);
00136   Value *Q_Sgn  = Builder.CreateXor(Tmp1, Tmp);
00137   Value *Q_Mag  = Builder.CreateUDiv(U_Dvnd, U_Dvsr);
00138   Value *Tmp4   = Builder.CreateXor(Q_Mag, Q_Sgn);
00139   Value *Q      = Builder.CreateSub(Tmp4, Q_Sgn);
00140 
00141   if (Instruction *UDiv = dyn_cast<Instruction>(Q_Mag))
00142     Builder.SetInsertPoint(UDiv);
00143 
00144   return Q;
00145 }
00146 
00147 /// Generates code to divide two unsigned scalar 32-bit or 64-bit integers.
00148 /// Returns the quotient, rounded towards 0. Builder's insert point should
00149 /// point where the caller wants code generated, e.g. at the udiv instruction.
00150 static Value *generateUnsignedDivisionCode(Value *Dividend, Value *Divisor,
00151                                            IRBuilder<> &Builder) {
00152   // The basic algorithm can be found in the compiler-rt project's
00153   // implementation of __udivsi3.c. Here, we do a lower-level IR based approach
00154   // that's been hand-tuned to lessen the amount of control flow involved.
00155 
00156   // Some helper values
00157   IntegerType *DivTy = cast<IntegerType>(Dividend->getType());
00158   unsigned BitWidth = DivTy->getBitWidth();
00159 
00160   ConstantInt *Zero;
00161   ConstantInt *One;
00162   ConstantInt *NegOne;
00163   ConstantInt *MSB;
00164 
00165   if (BitWidth == 64) {
00166     Zero      = Builder.getInt64(0);
00167     One       = Builder.getInt64(1);
00168     NegOne    = ConstantInt::getSigned(DivTy, -1);
00169     MSB       = Builder.getInt64(63);
00170   } else {
00171     assert(BitWidth == 32 && "Unexpected bit width");
00172     Zero      = Builder.getInt32(0);
00173     One       = Builder.getInt32(1);
00174     NegOne    = ConstantInt::getSigned(DivTy, -1);
00175     MSB       = Builder.getInt32(31);
00176   }
00177 
00178   ConstantInt *True = Builder.getTrue();
00179 
00180   BasicBlock *IBB = Builder.GetInsertBlock();
00181   Function *F = IBB->getParent();
00182   Function *CTLZ = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
00183                                              DivTy);
00184 
00185   // Our CFG is going to look like:
00186   // +---------------------+
00187   // | special-cases       |
00188   // |   ...               |
00189   // +---------------------+
00190   //  |       |
00191   //  |   +----------+
00192   //  |   |  bb1     |
00193   //  |   |  ...     |
00194   //  |   +----------+
00195   //  |    |      |
00196   //  |    |  +------------+
00197   //  |    |  |  preheader |
00198   //  |    |  |  ...       |
00199   //  |    |  +------------+
00200   //  |    |      |
00201   //  |    |      |      +---+
00202   //  |    |      |      |   |
00203   //  |    |  +------------+ |
00204   //  |    |  |  do-while  | |
00205   //  |    |  |  ...       | |
00206   //  |    |  +------------+ |
00207   //  |    |      |      |   |
00208   //  |   +-----------+  +---+
00209   //  |   | loop-exit |
00210   //  |   |  ...      |
00211   //  |   +-----------+
00212   //  |     |
00213   // +-------+
00214   // | ...   |
00215   // | end   |
00216   // +-------+
00217   BasicBlock *SpecialCases = Builder.GetInsertBlock();
00218   SpecialCases->setName(Twine(SpecialCases->getName(), "_udiv-special-cases"));
00219   BasicBlock *End = SpecialCases->splitBasicBlock(Builder.GetInsertPoint(),
00220                                                   "udiv-end");
00221   BasicBlock *LoopExit  = BasicBlock::Create(Builder.getContext(),
00222                                              "udiv-loop-exit", F, End);
00223   BasicBlock *DoWhile   = BasicBlock::Create(Builder.getContext(),
00224                                              "udiv-do-while", F, End);
00225   BasicBlock *Preheader = BasicBlock::Create(Builder.getContext(),
00226                                              "udiv-preheader", F, End);
00227   BasicBlock *BB1       = BasicBlock::Create(Builder.getContext(),
00228                                              "udiv-bb1", F, End);
00229 
00230   // We'll be overwriting the terminator to insert our extra blocks
00231   SpecialCases->getTerminator()->eraseFromParent();
00232 
00233   // Same instructions are generated for both i32 (msb 31) and i64 (msb 63).
00234 
00235   // First off, check for special cases: dividend or divisor is zero, divisor
00236   // is greater than dividend, and divisor is 1.
00237   // ; special-cases:
00238   // ;   %ret0_1      = icmp eq i32 %divisor, 0
00239   // ;   %ret0_2      = icmp eq i32 %dividend, 0
00240   // ;   %ret0_3      = or i1 %ret0_1, %ret0_2
00241   // ;   %tmp0        = tail call i32 @llvm.ctlz.i32(i32 %divisor, i1 true)
00242   // ;   %tmp1        = tail call i32 @llvm.ctlz.i32(i32 %dividend, i1 true)
00243   // ;   %sr          = sub nsw i32 %tmp0, %tmp1
00244   // ;   %ret0_4      = icmp ugt i32 %sr, 31
00245   // ;   %ret0        = or i1 %ret0_3, %ret0_4
00246   // ;   %retDividend = icmp eq i32 %sr, 31
00247   // ;   %retVal      = select i1 %ret0, i32 0, i32 %dividend
00248   // ;   %earlyRet    = or i1 %ret0, %retDividend
00249   // ;   br i1 %earlyRet, label %end, label %bb1
00250   Builder.SetInsertPoint(SpecialCases);
00251   Value *Ret0_1      = Builder.CreateICmpEQ(Divisor, Zero);
00252   Value *Ret0_2      = Builder.CreateICmpEQ(Dividend, Zero);
00253   Value *Ret0_3      = Builder.CreateOr(Ret0_1, Ret0_2);
00254   Value *Tmp0        = Builder.CreateCall2(CTLZ, Divisor, True);
00255   Value *Tmp1        = Builder.CreateCall2(CTLZ, Dividend, True);
00256   Value *SR          = Builder.CreateSub(Tmp0, Tmp1);
00257   Value *Ret0_4      = Builder.CreateICmpUGT(SR, MSB);
00258   Value *Ret0        = Builder.CreateOr(Ret0_3, Ret0_4);
00259   Value *RetDividend = Builder.CreateICmpEQ(SR, MSB);
00260   Value *RetVal      = Builder.CreateSelect(Ret0, Zero, Dividend);
00261   Value *EarlyRet    = Builder.CreateOr(Ret0, RetDividend);
00262   Builder.CreateCondBr(EarlyRet, End, BB1);
00263 
00264   // ; bb1:                                             ; preds = %special-cases
00265   // ;   %sr_1     = add i32 %sr, 1
00266   // ;   %tmp2     = sub i32 31, %sr
00267   // ;   %q        = shl i32 %dividend, %tmp2
00268   // ;   %skipLoop = icmp eq i32 %sr_1, 0
00269   // ;   br i1 %skipLoop, label %loop-exit, label %preheader
00270   Builder.SetInsertPoint(BB1);
00271   Value *SR_1     = Builder.CreateAdd(SR, One);
00272   Value *Tmp2     = Builder.CreateSub(MSB, SR);
00273   Value *Q        = Builder.CreateShl(Dividend, Tmp2);
00274   Value *SkipLoop = Builder.CreateICmpEQ(SR_1, Zero);
00275   Builder.CreateCondBr(SkipLoop, LoopExit, Preheader);
00276 
00277   // ; preheader:                                           ; preds = %bb1
00278   // ;   %tmp3 = lshr i32 %dividend, %sr_1
00279   // ;   %tmp4 = add i32 %divisor, -1
00280   // ;   br label %do-while
00281   Builder.SetInsertPoint(Preheader);
00282   Value *Tmp3 = Builder.CreateLShr(Dividend, SR_1);
00283   Value *Tmp4 = Builder.CreateAdd(Divisor, NegOne);
00284   Builder.CreateBr(DoWhile);
00285 
00286   // ; do-while:                                 ; preds = %do-while, %preheader
00287   // ;   %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
00288   // ;   %sr_3    = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
00289   // ;   %r_1     = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
00290   // ;   %q_2     = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
00291   // ;   %tmp5  = shl i32 %r_1, 1
00292   // ;   %tmp6  = lshr i32 %q_2, 31
00293   // ;   %tmp7  = or i32 %tmp5, %tmp6
00294   // ;   %tmp8  = shl i32 %q_2, 1
00295   // ;   %q_1   = or i32 %carry_1, %tmp8
00296   // ;   %tmp9  = sub i32 %tmp4, %tmp7
00297   // ;   %tmp10 = ashr i32 %tmp9, 31
00298   // ;   %carry = and i32 %tmp10, 1
00299   // ;   %tmp11 = and i32 %tmp10, %divisor
00300   // ;   %r     = sub i32 %tmp7, %tmp11
00301   // ;   %sr_2  = add i32 %sr_3, -1
00302   // ;   %tmp12 = icmp eq i32 %sr_2, 0
00303   // ;   br i1 %tmp12, label %loop-exit, label %do-while
00304   Builder.SetInsertPoint(DoWhile);
00305   PHINode *Carry_1 = Builder.CreatePHI(DivTy, 2);
00306   PHINode *SR_3    = Builder.CreatePHI(DivTy, 2);
00307   PHINode *R_1     = Builder.CreatePHI(DivTy, 2);
00308   PHINode *Q_2     = Builder.CreatePHI(DivTy, 2);
00309   Value *Tmp5  = Builder.CreateShl(R_1, One);
00310   Value *Tmp6  = Builder.CreateLShr(Q_2, MSB);
00311   Value *Tmp7  = Builder.CreateOr(Tmp5, Tmp6);
00312   Value *Tmp8  = Builder.CreateShl(Q_2, One);
00313   Value *Q_1   = Builder.CreateOr(Carry_1, Tmp8);
00314   Value *Tmp9  = Builder.CreateSub(Tmp4, Tmp7);
00315   Value *Tmp10 = Builder.CreateAShr(Tmp9, MSB);
00316   Value *Carry = Builder.CreateAnd(Tmp10, One);
00317   Value *Tmp11 = Builder.CreateAnd(Tmp10, Divisor);
00318   Value *R     = Builder.CreateSub(Tmp7, Tmp11);
00319   Value *SR_2  = Builder.CreateAdd(SR_3, NegOne);
00320   Value *Tmp12 = Builder.CreateICmpEQ(SR_2, Zero);
00321   Builder.CreateCondBr(Tmp12, LoopExit, DoWhile);
00322 
00323   // ; loop-exit:                                      ; preds = %do-while, %bb1
00324   // ;   %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
00325   // ;   %q_3     = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
00326   // ;   %tmp13 = shl i32 %q_3, 1
00327   // ;   %q_4   = or i32 %carry_2, %tmp13
00328   // ;   br label %end
00329   Builder.SetInsertPoint(LoopExit);
00330   PHINode *Carry_2 = Builder.CreatePHI(DivTy, 2);
00331   PHINode *Q_3     = Builder.CreatePHI(DivTy, 2);
00332   Value *Tmp13 = Builder.CreateShl(Q_3, One);
00333   Value *Q_4   = Builder.CreateOr(Carry_2, Tmp13);
00334   Builder.CreateBr(End);
00335 
00336   // ; end:                                 ; preds = %loop-exit, %special-cases
00337   // ;   %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
00338   // ;   ret i32 %q_5
00339   Builder.SetInsertPoint(End, End->begin());
00340   PHINode *Q_5 = Builder.CreatePHI(DivTy, 2);
00341 
00342   // Populate the Phis, since all values have now been created. Our Phis were:
00343   // ;   %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
00344   Carry_1->addIncoming(Zero, Preheader);
00345   Carry_1->addIncoming(Carry, DoWhile);
00346   // ;   %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
00347   SR_3->addIncoming(SR_1, Preheader);
00348   SR_3->addIncoming(SR_2, DoWhile);
00349   // ;   %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
00350   R_1->addIncoming(Tmp3, Preheader);
00351   R_1->addIncoming(R, DoWhile);
00352   // ;   %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
00353   Q_2->addIncoming(Q, Preheader);
00354   Q_2->addIncoming(Q_1, DoWhile);
00355   // ;   %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
00356   Carry_2->addIncoming(Zero, BB1);
00357   Carry_2->addIncoming(Carry, DoWhile);
00358   // ;   %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
00359   Q_3->addIncoming(Q, BB1);
00360   Q_3->addIncoming(Q_1, DoWhile);
00361   // ;   %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
00362   Q_5->addIncoming(Q_4, LoopExit);
00363   Q_5->addIncoming(RetVal, SpecialCases);
00364 
00365   return Q_5;
00366 }
00367 
00368 /// Generate code to calculate the remainder of two integers, replacing Rem with
00369 /// the generated code. This currently generates code using the udiv expansion,
00370 /// but future work includes generating more specialized code, e.g. when more
00371 /// information about the operands are known. Implements both 32bit and 64bit
00372 /// scalar division.
00373 ///
00374 /// @brief Replace Rem with generated code.
00375 bool llvm::expandRemainder(BinaryOperator *Rem) {
00376   assert((Rem->getOpcode() == Instruction::SRem ||
00377           Rem->getOpcode() == Instruction::URem) &&
00378          "Trying to expand remainder from a non-remainder function");
00379 
00380   IRBuilder<> Builder(Rem);
00381 
00382   Type *RemTy = Rem->getType();
00383   if (RemTy->isVectorTy())
00384     llvm_unreachable("Div over vectors not supported");
00385 
00386   unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
00387 
00388   if (RemTyBitWidth != 32 && RemTyBitWidth != 64)
00389     llvm_unreachable("Div of bitwidth other than 32 or 64 not supported");
00390 
00391   // First prepare the sign if it's a signed remainder
00392   if (Rem->getOpcode() == Instruction::SRem) {
00393     Value *Remainder = generateSignedRemainderCode(Rem->getOperand(0),
00394                                                    Rem->getOperand(1), Builder);
00395 
00396     Rem->replaceAllUsesWith(Remainder);
00397     Rem->dropAllReferences();
00398     Rem->eraseFromParent();
00399 
00400     // If we didn't actually generate a udiv instruction, we're done
00401     BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
00402     if (!BO || BO->getOpcode() != Instruction::URem)
00403       return true;
00404 
00405     Rem = BO;
00406   }
00407 
00408   Value *Remainder = generatedUnsignedRemainderCode(Rem->getOperand(0),
00409                                                     Rem->getOperand(1),
00410                                                     Builder);
00411 
00412   Rem->replaceAllUsesWith(Remainder);
00413   Rem->dropAllReferences();
00414   Rem->eraseFromParent();
00415 
00416   // Expand the udiv
00417   if (BinaryOperator *UDiv = dyn_cast<BinaryOperator>(Builder.GetInsertPoint())) {
00418     assert(UDiv->getOpcode() == Instruction::UDiv && "Non-udiv in expansion?");
00419     expandDivision(UDiv);
00420   }
00421 
00422   return true;
00423 }
00424 
00425 
00426 /// Generate code to divide two integers, replacing Div with the generated
00427 /// code. This currently generates code similarly to compiler-rt's
00428 /// implementations, but future work includes generating more specialized code
00429 /// when more information about the operands are known. Implements both
00430 /// 32bit and 64bit scalar division.
00431 ///
00432 /// @brief Replace Div with generated code.
00433 bool llvm::expandDivision(BinaryOperator *Div) {
00434   assert((Div->getOpcode() == Instruction::SDiv ||
00435           Div->getOpcode() == Instruction::UDiv) &&
00436          "Trying to expand division from a non-division function");
00437 
00438   IRBuilder<> Builder(Div);
00439 
00440   Type *DivTy = Div->getType();
00441   if (DivTy->isVectorTy())
00442     llvm_unreachable("Div over vectors not supported");
00443 
00444   unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
00445 
00446   if (DivTyBitWidth != 32 && DivTyBitWidth != 64)
00447     llvm_unreachable("Div of bitwidth other than 32 or 64 not supported");
00448 
00449   // First prepare the sign if it's a signed division
00450   if (Div->getOpcode() == Instruction::SDiv) {
00451     // Lower the code to unsigned division, and reset Div to point to the udiv.
00452     Value *Quotient = generateSignedDivisionCode(Div->getOperand(0),
00453                                                  Div->getOperand(1), Builder);
00454     Div->replaceAllUsesWith(Quotient);
00455     Div->dropAllReferences();
00456     Div->eraseFromParent();
00457 
00458     // If we didn't actually generate a udiv instruction, we're done
00459     BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
00460     if (!BO || BO->getOpcode() != Instruction::UDiv)
00461       return true;
00462 
00463     Div = BO;
00464   }
00465 
00466   // Insert the unsigned division code
00467   Value *Quotient = generateUnsignedDivisionCode(Div->getOperand(0),
00468                                                  Div->getOperand(1),
00469                                                  Builder);
00470   Div->replaceAllUsesWith(Quotient);
00471   Div->dropAllReferences();
00472   Div->eraseFromParent();
00473 
00474   return true;
00475 }
00476 
00477 /// Generate code to compute the remainder of two integers of bitwidth up to 
00478 /// 32 bits. Uses the above routines and extends the inputs/truncates the
00479 /// outputs to operate in 32 bits; that is, these routines are good for targets
00480 /// that have no or very little suppport for smaller than 32 bit integer 
00481 /// arithmetic.
00482 ///
00483 /// @brief Replace Rem with emulation code.
00484 bool llvm::expandRemainderUpTo32Bits(BinaryOperator *Rem) {
00485   assert((Rem->getOpcode() == Instruction::SRem ||
00486           Rem->getOpcode() == Instruction::URem) &&
00487           "Trying to expand remainder from a non-remainder function");
00488 
00489   Type *RemTy = Rem->getType();
00490   if (RemTy->isVectorTy())
00491     llvm_unreachable("Div over vectors not supported");
00492 
00493   unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
00494 
00495   if (RemTyBitWidth > 32) 
00496     llvm_unreachable("Div of bitwidth greater than 32 not supported");
00497 
00498   if (RemTyBitWidth == 32) 
00499     return expandRemainder(Rem);
00500 
00501   // If bitwidth smaller than 32 extend inputs, extend output and proceed
00502   // with 32 bit division.
00503   IRBuilder<> Builder(Rem);
00504 
00505   Value *ExtDividend;
00506   Value *ExtDivisor;
00507   Value *ExtRem;
00508   Value *Trunc;
00509   Type *Int32Ty = Builder.getInt32Ty();
00510 
00511   if (Rem->getOpcode() == Instruction::SRem) {
00512     ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int32Ty);
00513     ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int32Ty);
00514     ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
00515   } else {
00516     ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int32Ty);
00517     ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int32Ty);
00518     ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
00519   }
00520   Trunc = Builder.CreateTrunc(ExtRem, RemTy);
00521 
00522   Rem->replaceAllUsesWith(Trunc);
00523   Rem->dropAllReferences();
00524   Rem->eraseFromParent();
00525 
00526   return expandRemainder(cast<BinaryOperator>(ExtRem));
00527 }
00528 
00529 /// Generate code to compute the remainder of two integers of bitwidth up to 
00530 /// 64 bits. Uses the above routines and extends the inputs/truncates the
00531 /// outputs to operate in 64 bits.
00532 ///
00533 /// @brief Replace Rem with emulation code.
00534 bool llvm::expandRemainderUpTo64Bits(BinaryOperator *Rem) {
00535   assert((Rem->getOpcode() == Instruction::SRem ||
00536           Rem->getOpcode() == Instruction::URem) &&
00537           "Trying to expand remainder from a non-remainder function");
00538 
00539   Type *RemTy = Rem->getType();
00540   if (RemTy->isVectorTy())
00541     llvm_unreachable("Div over vectors not supported");
00542 
00543   unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
00544 
00545   if (RemTyBitWidth > 64) 
00546     llvm_unreachable("Div of bitwidth greater than 64 not supported");
00547 
00548   if (RemTyBitWidth == 64) 
00549     return expandRemainder(Rem);
00550 
00551   // If bitwidth smaller than 64 extend inputs, extend output and proceed
00552   // with 64 bit division.
00553   IRBuilder<> Builder(Rem);
00554 
00555   Value *ExtDividend;
00556   Value *ExtDivisor;
00557   Value *ExtRem;
00558   Value *Trunc;
00559   Type *Int64Ty = Builder.getInt64Ty();
00560 
00561   if (Rem->getOpcode() == Instruction::SRem) {
00562     ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int64Ty);
00563     ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int64Ty);
00564     ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
00565   } else {
00566     ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int64Ty);
00567     ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int64Ty);
00568     ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
00569   }
00570   Trunc = Builder.CreateTrunc(ExtRem, RemTy);
00571 
00572   Rem->replaceAllUsesWith(Trunc);
00573   Rem->dropAllReferences();
00574   Rem->eraseFromParent();
00575 
00576   return expandRemainder(cast<BinaryOperator>(ExtRem));
00577 }
00578 
00579 /// Generate code to divide two integers of bitwidth up to 32 bits. Uses the
00580 /// above routines and extends the inputs/truncates the outputs to operate
00581 /// in 32 bits; that is, these routines are good for targets that have no
00582 /// or very little support for smaller than 32 bit integer arithmetic.
00583 ///
00584 /// @brief Replace Div with emulation code.
00585 bool llvm::expandDivisionUpTo32Bits(BinaryOperator *Div) {
00586   assert((Div->getOpcode() == Instruction::SDiv ||
00587           Div->getOpcode() == Instruction::UDiv) &&
00588           "Trying to expand division from a non-division function");
00589 
00590   Type *DivTy = Div->getType();
00591   if (DivTy->isVectorTy())
00592     llvm_unreachable("Div over vectors not supported");
00593 
00594   unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
00595 
00596   if (DivTyBitWidth > 32)
00597     llvm_unreachable("Div of bitwidth greater than 32 not supported");
00598 
00599   if (DivTyBitWidth == 32)
00600     return expandDivision(Div);
00601 
00602   // If bitwidth smaller than 32 extend inputs, extend output and proceed
00603   // with 32 bit division.
00604   IRBuilder<> Builder(Div);
00605 
00606   Value *ExtDividend;
00607   Value *ExtDivisor;
00608   Value *ExtDiv;
00609   Value *Trunc;
00610   Type *Int32Ty = Builder.getInt32Ty();
00611 
00612   if (Div->getOpcode() == Instruction::SDiv) {
00613     ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int32Ty);
00614     ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int32Ty);
00615     ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
00616   } else {
00617     ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int32Ty);
00618     ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int32Ty);
00619     ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);  
00620   }
00621   Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
00622 
00623   Div->replaceAllUsesWith(Trunc);
00624   Div->dropAllReferences();
00625   Div->eraseFromParent();
00626 
00627   return expandDivision(cast<BinaryOperator>(ExtDiv));
00628 }
00629 
00630 /// Generate code to divide two integers of bitwidth up to 64 bits. Uses the
00631 /// above routines and extends the inputs/truncates the outputs to operate
00632 /// in 64 bits.
00633 ///
00634 /// @brief Replace Div with emulation code.
00635 bool llvm::expandDivisionUpTo64Bits(BinaryOperator *Div) {
00636   assert((Div->getOpcode() == Instruction::SDiv ||
00637           Div->getOpcode() == Instruction::UDiv) &&
00638           "Trying to expand division from a non-division function");
00639 
00640   Type *DivTy = Div->getType();
00641   if (DivTy->isVectorTy())
00642     llvm_unreachable("Div over vectors not supported");
00643 
00644   unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
00645 
00646   if (DivTyBitWidth > 64)
00647     llvm_unreachable("Div of bitwidth greater than 64 not supported");
00648 
00649   if (DivTyBitWidth == 64)
00650     return expandDivision(Div);
00651 
00652   // If bitwidth smaller than 64 extend inputs, extend output and proceed
00653   // with 64 bit division.
00654   IRBuilder<> Builder(Div);
00655 
00656   Value *ExtDividend;
00657   Value *ExtDivisor;
00658   Value *ExtDiv;
00659   Value *Trunc;
00660   Type *Int64Ty = Builder.getInt64Ty();
00661 
00662   if (Div->getOpcode() == Instruction::SDiv) {
00663     ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int64Ty);
00664     ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int64Ty);
00665     ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
00666   } else {
00667     ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int64Ty);
00668     ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int64Ty);
00669     ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);  
00670   }
00671   Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
00672 
00673   Div->replaceAllUsesWith(Trunc);
00674   Div->dropAllReferences();
00675   Div->eraseFromParent();
00676 
00677   return expandDivision(cast<BinaryOperator>(ExtDiv));
00678 }