IntegerDivision.cpp 26 KB

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