IntegerDivision.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. //===-- IntegerDivision.cpp - Expand integer division ---------------------===//
  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. // This file contains an implementation of 32bit and 64bit scalar integer
  10. // division for targets that don't have native support. It's largely derived
  11. // from compiler-rt's implementations of __udivsi3 and __udivmoddi4,
  12. // but hand-tuned for targets that prefer less control flow.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #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"
  20. using namespace llvm;
  21. #define DEBUG_TYPE "integer-division"
  22. /// Generate code to compute the remainder of two signed integers. Returns the
  23. /// remainder, which will have the sign of the dividend. Builder's insert point
  24. /// should be pointing where the caller wants code generated, e.g. at the srem
  25. /// instruction. This will generate a urem in the process, and Builder's insert
  26. /// point will be pointing at the uren (if present, i.e. not folded), ready to
  27. /// be expanded if the user wishes
  28. static Value *generateSignedRemainderCode(Value *Dividend, Value *Divisor,
  29. IRBuilder<> &Builder) {
  30. unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();
  31. ConstantInt *Shift = Builder.getIntN(BitWidth, BitWidth - 1);
  32. // Following instructions are generated for both i32 (shift 31) and
  33. // i64 (shift 63).
  34. // ; %dividend_sgn = ashr i32 %dividend, 31
  35. // ; %divisor_sgn = ashr i32 %divisor, 31
  36. // ; %dvd_xor = xor i32 %dividend, %dividend_sgn
  37. // ; %dvs_xor = xor i32 %divisor, %divisor_sgn
  38. // ; %u_dividend = sub i32 %dvd_xor, %dividend_sgn
  39. // ; %u_divisor = sub i32 %dvs_xor, %divisor_sgn
  40. // ; %urem = urem i32 %dividend, %divisor
  41. // ; %xored = xor i32 %urem, %dividend_sgn
  42. // ; %srem = sub i32 %xored, %dividend_sgn
  43. Dividend = Builder.CreateFreeze(Dividend);
  44. Divisor = Builder.CreateFreeze(Divisor);
  45. Value *DividendSign = Builder.CreateAShr(Dividend, Shift);
  46. Value *DivisorSign = Builder.CreateAShr(Divisor, Shift);
  47. Value *DvdXor = Builder.CreateXor(Dividend, DividendSign);
  48. Value *DvsXor = Builder.CreateXor(Divisor, DivisorSign);
  49. Value *UDividend = Builder.CreateSub(DvdXor, DividendSign);
  50. Value *UDivisor = Builder.CreateSub(DvsXor, DivisorSign);
  51. Value *URem = Builder.CreateURem(UDividend, UDivisor);
  52. Value *Xored = Builder.CreateXor(URem, DividendSign);
  53. Value *SRem = Builder.CreateSub(Xored, DividendSign);
  54. if (Instruction *URemInst = dyn_cast<Instruction>(URem))
  55. Builder.SetInsertPoint(URemInst);
  56. return SRem;
  57. }
  58. /// Generate code to compute the remainder of two unsigned integers. Returns the
  59. /// remainder. Builder's insert point should be pointing where the caller wants
  60. /// code generated, e.g. at the urem instruction. This will generate a udiv in
  61. /// the process, and Builder's insert point will be pointing at the udiv (if
  62. /// present, i.e. not folded), ready to be expanded if the user wishes
  63. static Value *generatedUnsignedRemainderCode(Value *Dividend, Value *Divisor,
  64. IRBuilder<> &Builder) {
  65. // Remainder = Dividend - Quotient*Divisor
  66. // Following instructions are generated for both i32 and i64
  67. // ; %quotient = udiv i32 %dividend, %divisor
  68. // ; %product = mul i32 %divisor, %quotient
  69. // ; %remainder = sub i32 %dividend, %product
  70. Dividend = Builder.CreateFreeze(Dividend);
  71. Divisor = Builder.CreateFreeze(Divisor);
  72. Value *Quotient = Builder.CreateUDiv(Dividend, Divisor);
  73. Value *Product = Builder.CreateMul(Divisor, Quotient);
  74. Value *Remainder = Builder.CreateSub(Dividend, Product);
  75. if (Instruction *UDiv = dyn_cast<Instruction>(Quotient))
  76. Builder.SetInsertPoint(UDiv);
  77. return Remainder;
  78. }
  79. /// Generate code to divide two signed integers. Returns the quotient, rounded
  80. /// towards 0. Builder's insert point should be pointing where the caller wants
  81. /// code generated, e.g. at the sdiv instruction. This will generate a udiv in
  82. /// the process, and Builder's insert point will be pointing at the udiv (if
  83. /// present, i.e. not folded), ready to be expanded if the user wishes.
  84. static Value *generateSignedDivisionCode(Value *Dividend, Value *Divisor,
  85. IRBuilder<> &Builder) {
  86. // Implementation taken from compiler-rt's __divsi3 and __divdi3
  87. unsigned BitWidth = Dividend->getType()->getIntegerBitWidth();
  88. ConstantInt *Shift = Builder.getIntN(BitWidth, BitWidth - 1);
  89. // Following instructions are generated for both i32 (shift 31) and
  90. // i64 (shift 63).
  91. // ; %tmp = ashr i32 %dividend, 31
  92. // ; %tmp1 = ashr i32 %divisor, 31
  93. // ; %tmp2 = xor i32 %tmp, %dividend
  94. // ; %u_dvnd = sub nsw i32 %tmp2, %tmp
  95. // ; %tmp3 = xor i32 %tmp1, %divisor
  96. // ; %u_dvsr = sub nsw i32 %tmp3, %tmp1
  97. // ; %q_sgn = xor i32 %tmp1, %tmp
  98. // ; %q_mag = udiv i32 %u_dvnd, %u_dvsr
  99. // ; %tmp4 = xor i32 %q_mag, %q_sgn
  100. // ; %q = sub i32 %tmp4, %q_sgn
  101. Dividend = Builder.CreateFreeze(Dividend);
  102. Divisor = Builder.CreateFreeze(Divisor);
  103. Value *Tmp = Builder.CreateAShr(Dividend, Shift);
  104. Value *Tmp1 = Builder.CreateAShr(Divisor, Shift);
  105. Value *Tmp2 = Builder.CreateXor(Tmp, Dividend);
  106. Value *U_Dvnd = Builder.CreateSub(Tmp2, Tmp);
  107. Value *Tmp3 = Builder.CreateXor(Tmp1, Divisor);
  108. Value *U_Dvsr = Builder.CreateSub(Tmp3, Tmp1);
  109. Value *Q_Sgn = Builder.CreateXor(Tmp1, Tmp);
  110. Value *Q_Mag = Builder.CreateUDiv(U_Dvnd, U_Dvsr);
  111. Value *Tmp4 = Builder.CreateXor(Q_Mag, Q_Sgn);
  112. Value *Q = Builder.CreateSub(Tmp4, Q_Sgn);
  113. if (Instruction *UDiv = dyn_cast<Instruction>(Q_Mag))
  114. Builder.SetInsertPoint(UDiv);
  115. return Q;
  116. }
  117. /// Generates code to divide two unsigned scalar 32-bit or 64-bit integers.
  118. /// Returns the quotient, rounded towards 0. Builder's insert point should
  119. /// point where the caller wants code generated, e.g. at the udiv instruction.
  120. static Value *generateUnsignedDivisionCode(Value *Dividend, Value *Divisor,
  121. IRBuilder<> &Builder) {
  122. // The basic algorithm can be found in the compiler-rt project's
  123. // implementation of __udivsi3.c. Here, we do a lower-level IR based approach
  124. // that's been hand-tuned to lessen the amount of control flow involved.
  125. // Some helper values
  126. IntegerType *DivTy = cast<IntegerType>(Dividend->getType());
  127. unsigned BitWidth = DivTy->getBitWidth();
  128. ConstantInt *Zero = ConstantInt::get(DivTy, 0);
  129. ConstantInt *One = ConstantInt::get(DivTy, 1);
  130. ConstantInt *NegOne = ConstantInt::getSigned(DivTy, -1);
  131. ConstantInt *MSB = ConstantInt::get(DivTy, BitWidth - 1);
  132. ConstantInt *True = Builder.getTrue();
  133. BasicBlock *IBB = Builder.GetInsertBlock();
  134. Function *F = IBB->getParent();
  135. Function *CTLZ = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
  136. DivTy);
  137. // Our CFG is going to look like:
  138. // +---------------------+
  139. // | special-cases |
  140. // | ... |
  141. // +---------------------+
  142. // | |
  143. // | +----------+
  144. // | | bb1 |
  145. // | | ... |
  146. // | +----------+
  147. // | | |
  148. // | | +------------+
  149. // | | | preheader |
  150. // | | | ... |
  151. // | | +------------+
  152. // | | |
  153. // | | | +---+
  154. // | | | | |
  155. // | | +------------+ |
  156. // | | | do-while | |
  157. // | | | ... | |
  158. // | | +------------+ |
  159. // | | | | |
  160. // | +-----------+ +---+
  161. // | | loop-exit |
  162. // | | ... |
  163. // | +-----------+
  164. // | |
  165. // +-------+
  166. // | ... |
  167. // | end |
  168. // +-------+
  169. BasicBlock *SpecialCases = Builder.GetInsertBlock();
  170. SpecialCases->setName(Twine(SpecialCases->getName(), "_udiv-special-cases"));
  171. BasicBlock *End = SpecialCases->splitBasicBlock(Builder.GetInsertPoint(),
  172. "udiv-end");
  173. BasicBlock *LoopExit = BasicBlock::Create(Builder.getContext(),
  174. "udiv-loop-exit", F, End);
  175. BasicBlock *DoWhile = BasicBlock::Create(Builder.getContext(),
  176. "udiv-do-while", F, End);
  177. BasicBlock *Preheader = BasicBlock::Create(Builder.getContext(),
  178. "udiv-preheader", F, End);
  179. BasicBlock *BB1 = BasicBlock::Create(Builder.getContext(),
  180. "udiv-bb1", F, End);
  181. // We'll be overwriting the terminator to insert our extra blocks
  182. SpecialCases->getTerminator()->eraseFromParent();
  183. // Same instructions are generated for both i32 (msb 31) and i64 (msb 63).
  184. // First off, check for special cases: dividend or divisor is zero, divisor
  185. // is greater than dividend, and divisor is 1.
  186. // ; special-cases:
  187. // ; %ret0_1 = icmp eq i32 %divisor, 0
  188. // ; %ret0_2 = icmp eq i32 %dividend, 0
  189. // ; %ret0_3 = or i1 %ret0_1, %ret0_2
  190. // ; %tmp0 = tail call i32 @llvm.ctlz.i32(i32 %divisor, i1 true)
  191. // ; %tmp1 = tail call i32 @llvm.ctlz.i32(i32 %dividend, i1 true)
  192. // ; %sr = sub nsw i32 %tmp0, %tmp1
  193. // ; %ret0_4 = icmp ugt i32 %sr, 31
  194. // ; %ret0 = select i1 %ret0_3, i1 true, i1 %ret0_4
  195. // ; %retDividend = icmp eq i32 %sr, 31
  196. // ; %retVal = select i1 %ret0, i32 0, i32 %dividend
  197. // ; %earlyRet = select i1 %ret0, i1 true, %retDividend
  198. // ; br i1 %earlyRet, label %end, label %bb1
  199. Builder.SetInsertPoint(SpecialCases);
  200. Divisor = Builder.CreateFreeze(Divisor);
  201. Dividend = Builder.CreateFreeze(Dividend);
  202. Value *Ret0_1 = Builder.CreateICmpEQ(Divisor, Zero);
  203. Value *Ret0_2 = Builder.CreateICmpEQ(Dividend, Zero);
  204. Value *Ret0_3 = Builder.CreateOr(Ret0_1, Ret0_2);
  205. Value *Tmp0 = Builder.CreateCall(CTLZ, {Divisor, True});
  206. Value *Tmp1 = Builder.CreateCall(CTLZ, {Dividend, True});
  207. Value *SR = Builder.CreateSub(Tmp0, Tmp1);
  208. Value *Ret0_4 = Builder.CreateICmpUGT(SR, MSB);
  209. Value *Ret0 = Builder.CreateLogicalOr(Ret0_3, Ret0_4);
  210. Value *RetDividend = Builder.CreateICmpEQ(SR, MSB);
  211. Value *RetVal = Builder.CreateSelect(Ret0, Zero, Dividend);
  212. Value *EarlyRet = Builder.CreateLogicalOr(Ret0, RetDividend);
  213. Builder.CreateCondBr(EarlyRet, End, BB1);
  214. // ; bb1: ; preds = %special-cases
  215. // ; %sr_1 = add i32 %sr, 1
  216. // ; %tmp2 = sub i32 31, %sr
  217. // ; %q = shl i32 %dividend, %tmp2
  218. // ; %skipLoop = icmp eq i32 %sr_1, 0
  219. // ; br i1 %skipLoop, label %loop-exit, label %preheader
  220. Builder.SetInsertPoint(BB1);
  221. Value *SR_1 = Builder.CreateAdd(SR, One);
  222. Value *Tmp2 = Builder.CreateSub(MSB, SR);
  223. Value *Q = Builder.CreateShl(Dividend, Tmp2);
  224. Value *SkipLoop = Builder.CreateICmpEQ(SR_1, Zero);
  225. Builder.CreateCondBr(SkipLoop, LoopExit, Preheader);
  226. // ; preheader: ; preds = %bb1
  227. // ; %tmp3 = lshr i32 %dividend, %sr_1
  228. // ; %tmp4 = add i32 %divisor, -1
  229. // ; br label %do-while
  230. Builder.SetInsertPoint(Preheader);
  231. Value *Tmp3 = Builder.CreateLShr(Dividend, SR_1);
  232. Value *Tmp4 = Builder.CreateAdd(Divisor, NegOne);
  233. Builder.CreateBr(DoWhile);
  234. // ; do-while: ; preds = %do-while, %preheader
  235. // ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
  236. // ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
  237. // ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
  238. // ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
  239. // ; %tmp5 = shl i32 %r_1, 1
  240. // ; %tmp6 = lshr i32 %q_2, 31
  241. // ; %tmp7 = or i32 %tmp5, %tmp6
  242. // ; %tmp8 = shl i32 %q_2, 1
  243. // ; %q_1 = or i32 %carry_1, %tmp8
  244. // ; %tmp9 = sub i32 %tmp4, %tmp7
  245. // ; %tmp10 = ashr i32 %tmp9, 31
  246. // ; %carry = and i32 %tmp10, 1
  247. // ; %tmp11 = and i32 %tmp10, %divisor
  248. // ; %r = sub i32 %tmp7, %tmp11
  249. // ; %sr_2 = add i32 %sr_3, -1
  250. // ; %tmp12 = icmp eq i32 %sr_2, 0
  251. // ; br i1 %tmp12, label %loop-exit, label %do-while
  252. Builder.SetInsertPoint(DoWhile);
  253. PHINode *Carry_1 = Builder.CreatePHI(DivTy, 2);
  254. PHINode *SR_3 = Builder.CreatePHI(DivTy, 2);
  255. PHINode *R_1 = Builder.CreatePHI(DivTy, 2);
  256. PHINode *Q_2 = Builder.CreatePHI(DivTy, 2);
  257. Value *Tmp5 = Builder.CreateShl(R_1, One);
  258. Value *Tmp6 = Builder.CreateLShr(Q_2, MSB);
  259. Value *Tmp7 = Builder.CreateOr(Tmp5, Tmp6);
  260. Value *Tmp8 = Builder.CreateShl(Q_2, One);
  261. Value *Q_1 = Builder.CreateOr(Carry_1, Tmp8);
  262. Value *Tmp9 = Builder.CreateSub(Tmp4, Tmp7);
  263. Value *Tmp10 = Builder.CreateAShr(Tmp9, MSB);
  264. Value *Carry = Builder.CreateAnd(Tmp10, One);
  265. Value *Tmp11 = Builder.CreateAnd(Tmp10, Divisor);
  266. Value *R = Builder.CreateSub(Tmp7, Tmp11);
  267. Value *SR_2 = Builder.CreateAdd(SR_3, NegOne);
  268. Value *Tmp12 = Builder.CreateICmpEQ(SR_2, Zero);
  269. Builder.CreateCondBr(Tmp12, LoopExit, DoWhile);
  270. // ; loop-exit: ; preds = %do-while, %bb1
  271. // ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
  272. // ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
  273. // ; %tmp13 = shl i32 %q_3, 1
  274. // ; %q_4 = or i32 %carry_2, %tmp13
  275. // ; br label %end
  276. Builder.SetInsertPoint(LoopExit);
  277. PHINode *Carry_2 = Builder.CreatePHI(DivTy, 2);
  278. PHINode *Q_3 = Builder.CreatePHI(DivTy, 2);
  279. Value *Tmp13 = Builder.CreateShl(Q_3, One);
  280. Value *Q_4 = Builder.CreateOr(Carry_2, Tmp13);
  281. Builder.CreateBr(End);
  282. // ; end: ; preds = %loop-exit, %special-cases
  283. // ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
  284. // ; ret i32 %q_5
  285. Builder.SetInsertPoint(End, End->begin());
  286. PHINode *Q_5 = Builder.CreatePHI(DivTy, 2);
  287. // Populate the Phis, since all values have now been created. Our Phis were:
  288. // ; %carry_1 = phi i32 [ 0, %preheader ], [ %carry, %do-while ]
  289. Carry_1->addIncoming(Zero, Preheader);
  290. Carry_1->addIncoming(Carry, DoWhile);
  291. // ; %sr_3 = phi i32 [ %sr_1, %preheader ], [ %sr_2, %do-while ]
  292. SR_3->addIncoming(SR_1, Preheader);
  293. SR_3->addIncoming(SR_2, DoWhile);
  294. // ; %r_1 = phi i32 [ %tmp3, %preheader ], [ %r, %do-while ]
  295. R_1->addIncoming(Tmp3, Preheader);
  296. R_1->addIncoming(R, DoWhile);
  297. // ; %q_2 = phi i32 [ %q, %preheader ], [ %q_1, %do-while ]
  298. Q_2->addIncoming(Q, Preheader);
  299. Q_2->addIncoming(Q_1, DoWhile);
  300. // ; %carry_2 = phi i32 [ 0, %bb1 ], [ %carry, %do-while ]
  301. Carry_2->addIncoming(Zero, BB1);
  302. Carry_2->addIncoming(Carry, DoWhile);
  303. // ; %q_3 = phi i32 [ %q, %bb1 ], [ %q_1, %do-while ]
  304. Q_3->addIncoming(Q, BB1);
  305. Q_3->addIncoming(Q_1, DoWhile);
  306. // ; %q_5 = phi i32 [ %q_4, %loop-exit ], [ %retVal, %special-cases ]
  307. Q_5->addIncoming(Q_4, LoopExit);
  308. Q_5->addIncoming(RetVal, SpecialCases);
  309. return Q_5;
  310. }
  311. /// Generate code to calculate the remainder of two integers, replacing Rem with
  312. /// the generated code. This currently generates code using the udiv expansion,
  313. /// but future work includes generating more specialized code, e.g. when more
  314. /// information about the operands are known.
  315. ///
  316. /// Replace Rem with generated code.
  317. bool llvm::expandRemainder(BinaryOperator *Rem) {
  318. assert((Rem->getOpcode() == Instruction::SRem ||
  319. Rem->getOpcode() == Instruction::URem) &&
  320. "Trying to expand remainder from a non-remainder function");
  321. IRBuilder<> Builder(Rem);
  322. assert(!Rem->getType()->isVectorTy() && "Div over vectors not supported");
  323. // First prepare the sign if it's a signed remainder
  324. if (Rem->getOpcode() == Instruction::SRem) {
  325. Value *Remainder = generateSignedRemainderCode(Rem->getOperand(0),
  326. Rem->getOperand(1), Builder);
  327. // Check whether this is the insert point while Rem is still valid.
  328. bool IsInsertPoint = Rem->getIterator() == Builder.GetInsertPoint();
  329. Rem->replaceAllUsesWith(Remainder);
  330. Rem->dropAllReferences();
  331. Rem->eraseFromParent();
  332. // If we didn't actually generate an urem instruction, we're done
  333. // This happens for example if the input were constant. In this case the
  334. // Builder insertion point was unchanged
  335. if (IsInsertPoint)
  336. return true;
  337. BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
  338. Rem = BO;
  339. }
  340. Value *Remainder = generatedUnsignedRemainderCode(Rem->getOperand(0),
  341. Rem->getOperand(1),
  342. Builder);
  343. Rem->replaceAllUsesWith(Remainder);
  344. Rem->dropAllReferences();
  345. Rem->eraseFromParent();
  346. // Expand the udiv
  347. if (BinaryOperator *UDiv = dyn_cast<BinaryOperator>(Builder.GetInsertPoint())) {
  348. assert(UDiv->getOpcode() == Instruction::UDiv && "Non-udiv in expansion?");
  349. expandDivision(UDiv);
  350. }
  351. return true;
  352. }
  353. /// Generate code to divide two integers, replacing Div with the generated
  354. /// code. This currently generates code similarly to compiler-rt's
  355. /// implementations, but future work includes generating more specialized code
  356. /// when more information about the operands are known.
  357. ///
  358. /// Replace Div with generated code.
  359. bool llvm::expandDivision(BinaryOperator *Div) {
  360. assert((Div->getOpcode() == Instruction::SDiv ||
  361. Div->getOpcode() == Instruction::UDiv) &&
  362. "Trying to expand division from a non-division function");
  363. IRBuilder<> Builder(Div);
  364. assert(!Div->getType()->isVectorTy() && "Div over vectors not supported");
  365. // First prepare the sign if it's a signed division
  366. if (Div->getOpcode() == Instruction::SDiv) {
  367. // Lower the code to unsigned division, and reset Div to point to the udiv.
  368. Value *Quotient = generateSignedDivisionCode(Div->getOperand(0),
  369. Div->getOperand(1), Builder);
  370. // Check whether this is the insert point while Div is still valid.
  371. bool IsInsertPoint = Div->getIterator() == Builder.GetInsertPoint();
  372. Div->replaceAllUsesWith(Quotient);
  373. Div->dropAllReferences();
  374. Div->eraseFromParent();
  375. // If we didn't actually generate an udiv instruction, we're done
  376. // This happens for example if the input were constant. In this case the
  377. // Builder insertion point was unchanged
  378. if (IsInsertPoint)
  379. return true;
  380. BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
  381. Div = BO;
  382. }
  383. // Insert the unsigned division code
  384. Value *Quotient = generateUnsignedDivisionCode(Div->getOperand(0),
  385. Div->getOperand(1),
  386. Builder);
  387. Div->replaceAllUsesWith(Quotient);
  388. Div->dropAllReferences();
  389. Div->eraseFromParent();
  390. return true;
  391. }
  392. /// Generate code to compute the remainder of two integers of bitwidth up to
  393. /// 32 bits. Uses the above routines and extends the inputs/truncates the
  394. /// outputs to operate in 32 bits; that is, these routines are good for targets
  395. /// that have no or very little suppport for smaller than 32 bit integer
  396. /// arithmetic.
  397. ///
  398. /// Replace Rem with emulation code.
  399. bool llvm::expandRemainderUpTo32Bits(BinaryOperator *Rem) {
  400. assert((Rem->getOpcode() == Instruction::SRem ||
  401. Rem->getOpcode() == Instruction::URem) &&
  402. "Trying to expand remainder from a non-remainder function");
  403. Type *RemTy = Rem->getType();
  404. assert(!RemTy->isVectorTy() && "Div over vectors not supported");
  405. unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
  406. assert(RemTyBitWidth <= 32 &&
  407. "Div of bitwidth greater than 32 not supported");
  408. if (RemTyBitWidth == 32)
  409. return expandRemainder(Rem);
  410. // If bitwidth smaller than 32 extend inputs, extend output and proceed
  411. // with 32 bit division.
  412. IRBuilder<> Builder(Rem);
  413. Value *ExtDividend;
  414. Value *ExtDivisor;
  415. Value *ExtRem;
  416. Value *Trunc;
  417. Type *Int32Ty = Builder.getInt32Ty();
  418. if (Rem->getOpcode() == Instruction::SRem) {
  419. ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int32Ty);
  420. ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int32Ty);
  421. ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
  422. } else {
  423. ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int32Ty);
  424. ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int32Ty);
  425. ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
  426. }
  427. Trunc = Builder.CreateTrunc(ExtRem, RemTy);
  428. Rem->replaceAllUsesWith(Trunc);
  429. Rem->dropAllReferences();
  430. Rem->eraseFromParent();
  431. return expandRemainder(cast<BinaryOperator>(ExtRem));
  432. }
  433. /// Generate code to compute the remainder of two integers of bitwidth up to
  434. /// 64 bits. Uses the above routines and extends the inputs/truncates the
  435. /// outputs to operate in 64 bits.
  436. ///
  437. /// Replace Rem with emulation code.
  438. bool llvm::expandRemainderUpTo64Bits(BinaryOperator *Rem) {
  439. assert((Rem->getOpcode() == Instruction::SRem ||
  440. Rem->getOpcode() == Instruction::URem) &&
  441. "Trying to expand remainder from a non-remainder function");
  442. Type *RemTy = Rem->getType();
  443. assert(!RemTy->isVectorTy() && "Div over vectors not supported");
  444. unsigned RemTyBitWidth = RemTy->getIntegerBitWidth();
  445. if (RemTyBitWidth >= 64)
  446. return expandRemainder(Rem);
  447. // If bitwidth smaller than 64 extend inputs, extend output and proceed
  448. // with 64 bit division.
  449. IRBuilder<> Builder(Rem);
  450. Value *ExtDividend;
  451. Value *ExtDivisor;
  452. Value *ExtRem;
  453. Value *Trunc;
  454. Type *Int64Ty = Builder.getInt64Ty();
  455. if (Rem->getOpcode() == Instruction::SRem) {
  456. ExtDividend = Builder.CreateSExt(Rem->getOperand(0), Int64Ty);
  457. ExtDivisor = Builder.CreateSExt(Rem->getOperand(1), Int64Ty);
  458. ExtRem = Builder.CreateSRem(ExtDividend, ExtDivisor);
  459. } else {
  460. ExtDividend = Builder.CreateZExt(Rem->getOperand(0), Int64Ty);
  461. ExtDivisor = Builder.CreateZExt(Rem->getOperand(1), Int64Ty);
  462. ExtRem = Builder.CreateURem(ExtDividend, ExtDivisor);
  463. }
  464. Trunc = Builder.CreateTrunc(ExtRem, RemTy);
  465. Rem->replaceAllUsesWith(Trunc);
  466. Rem->dropAllReferences();
  467. Rem->eraseFromParent();
  468. return expandRemainder(cast<BinaryOperator>(ExtRem));
  469. }
  470. /// Generate code to divide two integers of bitwidth up to 32 bits. Uses the
  471. /// above routines and extends the inputs/truncates the outputs to operate
  472. /// in 32 bits; that is, these routines are good for targets that have no
  473. /// or very little support for smaller than 32 bit integer arithmetic.
  474. ///
  475. /// Replace Div with emulation code.
  476. bool llvm::expandDivisionUpTo32Bits(BinaryOperator *Div) {
  477. assert((Div->getOpcode() == Instruction::SDiv ||
  478. Div->getOpcode() == Instruction::UDiv) &&
  479. "Trying to expand division from a non-division function");
  480. Type *DivTy = Div->getType();
  481. assert(!DivTy->isVectorTy() && "Div over vectors not supported");
  482. unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
  483. assert(DivTyBitWidth <= 32 && "Div of bitwidth greater than 32 not supported");
  484. if (DivTyBitWidth == 32)
  485. return expandDivision(Div);
  486. // If bitwidth smaller than 32 extend inputs, extend output and proceed
  487. // with 32 bit division.
  488. IRBuilder<> Builder(Div);
  489. Value *ExtDividend;
  490. Value *ExtDivisor;
  491. Value *ExtDiv;
  492. Value *Trunc;
  493. Type *Int32Ty = Builder.getInt32Ty();
  494. if (Div->getOpcode() == Instruction::SDiv) {
  495. ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int32Ty);
  496. ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int32Ty);
  497. ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
  498. } else {
  499. ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int32Ty);
  500. ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int32Ty);
  501. ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);
  502. }
  503. Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
  504. Div->replaceAllUsesWith(Trunc);
  505. Div->dropAllReferences();
  506. Div->eraseFromParent();
  507. return expandDivision(cast<BinaryOperator>(ExtDiv));
  508. }
  509. /// Generate code to divide two integers of bitwidth up to 64 bits. Uses the
  510. /// above routines and extends the inputs/truncates the outputs to operate
  511. /// in 64 bits.
  512. ///
  513. /// Replace Div with emulation code.
  514. bool llvm::expandDivisionUpTo64Bits(BinaryOperator *Div) {
  515. assert((Div->getOpcode() == Instruction::SDiv ||
  516. Div->getOpcode() == Instruction::UDiv) &&
  517. "Trying to expand division from a non-division function");
  518. Type *DivTy = Div->getType();
  519. assert(!DivTy->isVectorTy() && "Div over vectors not supported");
  520. unsigned DivTyBitWidth = DivTy->getIntegerBitWidth();
  521. if (DivTyBitWidth >= 64)
  522. return expandDivision(Div);
  523. // If bitwidth smaller than 64 extend inputs, extend output and proceed
  524. // with 64 bit division.
  525. IRBuilder<> Builder(Div);
  526. Value *ExtDividend;
  527. Value *ExtDivisor;
  528. Value *ExtDiv;
  529. Value *Trunc;
  530. Type *Int64Ty = Builder.getInt64Ty();
  531. if (Div->getOpcode() == Instruction::SDiv) {
  532. ExtDividend = Builder.CreateSExt(Div->getOperand(0), Int64Ty);
  533. ExtDivisor = Builder.CreateSExt(Div->getOperand(1), Int64Ty);
  534. ExtDiv = Builder.CreateSDiv(ExtDividend, ExtDivisor);
  535. } else {
  536. ExtDividend = Builder.CreateZExt(Div->getOperand(0), Int64Ty);
  537. ExtDivisor = Builder.CreateZExt(Div->getOperand(1), Int64Ty);
  538. ExtDiv = Builder.CreateUDiv(ExtDividend, ExtDivisor);
  539. }
  540. Trunc = Builder.CreateTrunc(ExtDiv, DivTy);
  541. Div->replaceAllUsesWith(Trunc);
  542. Div->dropAllReferences();
  543. Div->eraseFromParent();
  544. return expandDivision(cast<BinaryOperator>(ExtDiv));
  545. }