div.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // The functions are complex with many branches, and explicit
  2. // `return`s makes it clear where function exit points are
  3. #![allow(clippy::needless_return)]
  4. use float::Float;
  5. use int::{CastInto, DInt, HInt, Int};
  6. fn div32<F: Float>(a: F, b: F) -> F
  7. where
  8. u32: CastInto<F::Int>,
  9. F::Int: CastInto<u32>,
  10. i32: CastInto<F::Int>,
  11. F::Int: CastInto<i32>,
  12. F::Int: HInt,
  13. {
  14. let one = F::Int::ONE;
  15. let zero = F::Int::ZERO;
  16. // let bits = F::BITS;
  17. let significand_bits = F::SIGNIFICAND_BITS;
  18. let max_exponent = F::EXPONENT_MAX;
  19. let exponent_bias = F::EXPONENT_BIAS;
  20. let implicit_bit = F::IMPLICIT_BIT;
  21. let significand_mask = F::SIGNIFICAND_MASK;
  22. let sign_bit = F::SIGN_MASK as F::Int;
  23. let abs_mask = sign_bit - one;
  24. let exponent_mask = F::EXPONENT_MASK;
  25. let inf_rep = exponent_mask;
  26. let quiet_bit = implicit_bit >> 1;
  27. let qnan_rep = exponent_mask | quiet_bit;
  28. #[inline(always)]
  29. fn negate_u32(a: u32) -> u32 {
  30. (<i32>::wrapping_neg(a as i32)) as u32
  31. }
  32. let a_rep = a.repr();
  33. let b_rep = b.repr();
  34. let a_exponent = (a_rep >> significand_bits) & max_exponent.cast();
  35. let b_exponent = (b_rep >> significand_bits) & max_exponent.cast();
  36. let quotient_sign = (a_rep ^ b_rep) & sign_bit;
  37. let mut a_significand = a_rep & significand_mask;
  38. let mut b_significand = b_rep & significand_mask;
  39. let mut scale = 0;
  40. // Detect if a or b is zero, denormal, infinity, or NaN.
  41. if a_exponent.wrapping_sub(one) >= (max_exponent - 1).cast()
  42. || b_exponent.wrapping_sub(one) >= (max_exponent - 1).cast()
  43. {
  44. let a_abs = a_rep & abs_mask;
  45. let b_abs = b_rep & abs_mask;
  46. // NaN / anything = qNaN
  47. if a_abs > inf_rep {
  48. return F::from_repr(a_rep | quiet_bit);
  49. }
  50. // anything / NaN = qNaN
  51. if b_abs > inf_rep {
  52. return F::from_repr(b_rep | quiet_bit);
  53. }
  54. if a_abs == inf_rep {
  55. if b_abs == inf_rep {
  56. // infinity / infinity = NaN
  57. return F::from_repr(qnan_rep);
  58. } else {
  59. // infinity / anything else = +/- infinity
  60. return F::from_repr(a_abs | quotient_sign);
  61. }
  62. }
  63. // anything else / infinity = +/- 0
  64. if b_abs == inf_rep {
  65. return F::from_repr(quotient_sign);
  66. }
  67. if a_abs == zero {
  68. if b_abs == zero {
  69. // zero / zero = NaN
  70. return F::from_repr(qnan_rep);
  71. } else {
  72. // zero / anything else = +/- zero
  73. return F::from_repr(quotient_sign);
  74. }
  75. }
  76. // anything else / zero = +/- infinity
  77. if b_abs == zero {
  78. return F::from_repr(inf_rep | quotient_sign);
  79. }
  80. // one or both of a or b is denormal, the other (if applicable) is a
  81. // normal number. Renormalize one or both of a and b, and set scale to
  82. // include the necessary exponent adjustment.
  83. if a_abs < implicit_bit {
  84. let (exponent, significand) = F::normalize(a_significand);
  85. scale += exponent;
  86. a_significand = significand;
  87. }
  88. if b_abs < implicit_bit {
  89. let (exponent, significand) = F::normalize(b_significand);
  90. scale -= exponent;
  91. b_significand = significand;
  92. }
  93. }
  94. // Or in the implicit significand bit. (If we fell through from the
  95. // denormal path it was already set by normalize( ), but setting it twice
  96. // won't hurt anything.)
  97. a_significand |= implicit_bit;
  98. b_significand |= implicit_bit;
  99. let mut quotient_exponent: i32 = CastInto::<i32>::cast(a_exponent)
  100. .wrapping_sub(CastInto::<i32>::cast(b_exponent))
  101. .wrapping_add(scale);
  102. // Align the significand of b as a Q31 fixed-point number in the range
  103. // [1, 2.0) and get a Q32 approximate reciprocal using a small minimax
  104. // polynomial approximation: reciprocal = 3/4 + 1/sqrt(2) - b/2. This
  105. // is accurate to about 3.5 binary digits.
  106. let q31b = CastInto::<u32>::cast(b_significand << 8.cast());
  107. let mut reciprocal = (0x7504f333u32).wrapping_sub(q31b);
  108. // Now refine the reciprocal estimate using a Newton-Raphson iteration:
  109. //
  110. // x1 = x0 * (2 - x0 * b)
  111. //
  112. // This doubles the number of correct binary digits in the approximation
  113. // with each iteration, so after three iterations, we have about 28 binary
  114. // digits of accuracy.
  115. let mut correction: u32 =
  116. negate_u32(((reciprocal as u64).wrapping_mul(q31b as u64) >> 32) as u32);
  117. reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) as u64 >> 31) as u32;
  118. correction = negate_u32(((reciprocal as u64).wrapping_mul(q31b as u64) >> 32) as u32);
  119. reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) as u64 >> 31) as u32;
  120. correction = negate_u32(((reciprocal as u64).wrapping_mul(q31b as u64) >> 32) as u32);
  121. reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) as u64 >> 31) as u32;
  122. // Exhaustive testing shows that the error in reciprocal after three steps
  123. // is in the interval [-0x1.f58108p-31, 0x1.d0e48cp-29], in line with our
  124. // expectations. We bump the reciprocal by a tiny value to force the error
  125. // to be strictly positive (in the range [0x1.4fdfp-37,0x1.287246p-29], to
  126. // be specific). This also causes 1/1 to give a sensible approximation
  127. // instead of zero (due to overflow).
  128. reciprocal = reciprocal.wrapping_sub(2);
  129. // The numerical reciprocal is accurate to within 2^-28, lies in the
  130. // interval [0x1.000000eep-1, 0x1.fffffffcp-1], and is strictly smaller
  131. // than the true reciprocal of b. Multiplying a by this reciprocal thus
  132. // gives a numerical q = a/b in Q24 with the following properties:
  133. //
  134. // 1. q < a/b
  135. // 2. q is in the interval [0x1.000000eep-1, 0x1.fffffffcp0)
  136. // 3. the error in q is at most 2^-24 + 2^-27 -- the 2^24 term comes
  137. // from the fact that we truncate the product, and the 2^27 term
  138. // is the error in the reciprocal of b scaled by the maximum
  139. // possible value of a. As a consequence of this error bound,
  140. // either q or nextafter(q) is the correctly rounded
  141. let mut quotient = (a_significand << 1).widen_mul(reciprocal.cast()).hi();
  142. // Two cases: quotient is in [0.5, 1.0) or quotient is in [1.0, 2.0).
  143. // In either case, we are going to compute a residual of the form
  144. //
  145. // r = a - q*b
  146. //
  147. // We know from the construction of q that r satisfies:
  148. //
  149. // 0 <= r < ulp(q)*b
  150. //
  151. // if r is greater than 1/2 ulp(q)*b, then q rounds up. Otherwise, we
  152. // already have the correct result. The exact halfway case cannot occur.
  153. // We also take this time to right shift quotient if it falls in the [1,2)
  154. // range and adjust the exponent accordingly.
  155. let residual = if quotient < (implicit_bit << 1) {
  156. quotient_exponent = quotient_exponent.wrapping_sub(1);
  157. (a_significand << (significand_bits + 1)).wrapping_sub(quotient.wrapping_mul(b_significand))
  158. } else {
  159. quotient >>= 1;
  160. (a_significand << significand_bits).wrapping_sub(quotient.wrapping_mul(b_significand))
  161. };
  162. let written_exponent = quotient_exponent.wrapping_add(exponent_bias as i32);
  163. if written_exponent >= max_exponent as i32 {
  164. // If we have overflowed the exponent, return infinity.
  165. return F::from_repr(inf_rep | quotient_sign);
  166. } else if written_exponent < 1 {
  167. // Flush denormals to zero. In the future, it would be nice to add
  168. // code to round them correctly.
  169. return F::from_repr(quotient_sign);
  170. } else {
  171. let round = ((residual << 1) > b_significand) as u32;
  172. // Clear the implicit bits
  173. let mut abs_result = quotient & significand_mask;
  174. // Insert the exponent
  175. abs_result |= written_exponent.cast() << significand_bits;
  176. // Round
  177. abs_result = abs_result.wrapping_add(round.cast());
  178. // Insert the sign and return
  179. return F::from_repr(abs_result | quotient_sign);
  180. }
  181. }
  182. fn div64<F: Float>(a: F, b: F) -> F
  183. where
  184. u32: CastInto<F::Int>,
  185. F::Int: CastInto<u32>,
  186. i32: CastInto<F::Int>,
  187. F::Int: CastInto<i32>,
  188. u64: CastInto<F::Int>,
  189. F::Int: CastInto<u64>,
  190. i64: CastInto<F::Int>,
  191. F::Int: CastInto<i64>,
  192. F::Int: HInt,
  193. {
  194. let one = F::Int::ONE;
  195. let zero = F::Int::ZERO;
  196. // let bits = F::BITS;
  197. let significand_bits = F::SIGNIFICAND_BITS;
  198. let max_exponent = F::EXPONENT_MAX;
  199. let exponent_bias = F::EXPONENT_BIAS;
  200. let implicit_bit = F::IMPLICIT_BIT;
  201. let significand_mask = F::SIGNIFICAND_MASK;
  202. let sign_bit = F::SIGN_MASK as F::Int;
  203. let abs_mask = sign_bit - one;
  204. let exponent_mask = F::EXPONENT_MASK;
  205. let inf_rep = exponent_mask;
  206. let quiet_bit = implicit_bit >> 1;
  207. let qnan_rep = exponent_mask | quiet_bit;
  208. // let exponent_bits = F::EXPONENT_BITS;
  209. #[inline(always)]
  210. fn negate_u32(a: u32) -> u32 {
  211. (<i32>::wrapping_neg(a as i32)) as u32
  212. }
  213. #[inline(always)]
  214. fn negate_u64(a: u64) -> u64 {
  215. (<i64>::wrapping_neg(a as i64)) as u64
  216. }
  217. let a_rep = a.repr();
  218. let b_rep = b.repr();
  219. let a_exponent = (a_rep >> significand_bits) & max_exponent.cast();
  220. let b_exponent = (b_rep >> significand_bits) & max_exponent.cast();
  221. let quotient_sign = (a_rep ^ b_rep) & sign_bit;
  222. let mut a_significand = a_rep & significand_mask;
  223. let mut b_significand = b_rep & significand_mask;
  224. let mut scale = 0;
  225. // Detect if a or b is zero, denormal, infinity, or NaN.
  226. if a_exponent.wrapping_sub(one) >= (max_exponent - 1).cast()
  227. || b_exponent.wrapping_sub(one) >= (max_exponent - 1).cast()
  228. {
  229. let a_abs = a_rep & abs_mask;
  230. let b_abs = b_rep & abs_mask;
  231. // NaN / anything = qNaN
  232. if a_abs > inf_rep {
  233. return F::from_repr(a_rep | quiet_bit);
  234. }
  235. // anything / NaN = qNaN
  236. if b_abs > inf_rep {
  237. return F::from_repr(b_rep | quiet_bit);
  238. }
  239. if a_abs == inf_rep {
  240. if b_abs == inf_rep {
  241. // infinity / infinity = NaN
  242. return F::from_repr(qnan_rep);
  243. } else {
  244. // infinity / anything else = +/- infinity
  245. return F::from_repr(a_abs | quotient_sign);
  246. }
  247. }
  248. // anything else / infinity = +/- 0
  249. if b_abs == inf_rep {
  250. return F::from_repr(quotient_sign);
  251. }
  252. if a_abs == zero {
  253. if b_abs == zero {
  254. // zero / zero = NaN
  255. return F::from_repr(qnan_rep);
  256. } else {
  257. // zero / anything else = +/- zero
  258. return F::from_repr(quotient_sign);
  259. }
  260. }
  261. // anything else / zero = +/- infinity
  262. if b_abs == zero {
  263. return F::from_repr(inf_rep | quotient_sign);
  264. }
  265. // one or both of a or b is denormal, the other (if applicable) is a
  266. // normal number. Renormalize one or both of a and b, and set scale to
  267. // include the necessary exponent adjustment.
  268. if a_abs < implicit_bit {
  269. let (exponent, significand) = F::normalize(a_significand);
  270. scale += exponent;
  271. a_significand = significand;
  272. }
  273. if b_abs < implicit_bit {
  274. let (exponent, significand) = F::normalize(b_significand);
  275. scale -= exponent;
  276. b_significand = significand;
  277. }
  278. }
  279. // Or in the implicit significand bit. (If we fell through from the
  280. // denormal path it was already set by normalize( ), but setting it twice
  281. // won't hurt anything.)
  282. a_significand |= implicit_bit;
  283. b_significand |= implicit_bit;
  284. let mut quotient_exponent: i32 = CastInto::<i32>::cast(a_exponent)
  285. .wrapping_sub(CastInto::<i32>::cast(b_exponent))
  286. .wrapping_add(scale);
  287. // Align the significand of b as a Q31 fixed-point number in the range
  288. // [1, 2.0) and get a Q32 approximate reciprocal using a small minimax
  289. // polynomial approximation: reciprocal = 3/4 + 1/sqrt(2) - b/2. This
  290. // is accurate to about 3.5 binary digits.
  291. let q31b = CastInto::<u32>::cast(b_significand >> 21.cast());
  292. let mut recip32 = (0x7504f333u32).wrapping_sub(q31b);
  293. // Now refine the reciprocal estimate using a Newton-Raphson iteration:
  294. //
  295. // x1 = x0 * (2 - x0 * b)
  296. //
  297. // This doubles the number of correct binary digits in the approximation
  298. // with each iteration, so after three iterations, we have about 28 binary
  299. // digits of accuracy.
  300. let mut correction32: u32 =
  301. negate_u32(((recip32 as u64).wrapping_mul(q31b as u64) >> 32) as u32);
  302. recip32 = ((recip32 as u64).wrapping_mul(correction32 as u64) >> 31) as u32;
  303. correction32 = negate_u32(((recip32 as u64).wrapping_mul(q31b as u64) >> 32) as u32);
  304. recip32 = ((recip32 as u64).wrapping_mul(correction32 as u64) >> 31) as u32;
  305. correction32 = negate_u32(((recip32 as u64).wrapping_mul(q31b as u64) >> 32) as u32);
  306. recip32 = ((recip32 as u64).wrapping_mul(correction32 as u64) >> 31) as u32;
  307. // recip32 might have overflowed to exactly zero in the preceeding
  308. // computation if the high word of b is exactly 1.0. This would sabotage
  309. // the full-width final stage of the computation that follows, so we adjust
  310. // recip32 downward by one bit.
  311. recip32 = recip32.wrapping_sub(1);
  312. // We need to perform one more iteration to get us to 56 binary digits;
  313. // The last iteration needs to happen with extra precision.
  314. let q63blo = CastInto::<u32>::cast(b_significand << 11.cast());
  315. let correction: u64 = negate_u64(
  316. (recip32 as u64)
  317. .wrapping_mul(q31b as u64)
  318. .wrapping_add((recip32 as u64).wrapping_mul(q63blo as u64) >> 32),
  319. );
  320. let c_hi = (correction >> 32) as u32;
  321. let c_lo = correction as u32;
  322. let mut reciprocal: u64 = (recip32 as u64)
  323. .wrapping_mul(c_hi as u64)
  324. .wrapping_add((recip32 as u64).wrapping_mul(c_lo as u64) >> 32);
  325. // We already adjusted the 32-bit estimate, now we need to adjust the final
  326. // 64-bit reciprocal estimate downward to ensure that it is strictly smaller
  327. // than the infinitely precise exact reciprocal. Because the computation
  328. // of the Newton-Raphson step is truncating at every step, this adjustment
  329. // is small; most of the work is already done.
  330. reciprocal = reciprocal.wrapping_sub(2);
  331. // The numerical reciprocal is accurate to within 2^-56, lies in the
  332. // interval [0.5, 1.0), and is strictly smaller than the true reciprocal
  333. // of b. Multiplying a by this reciprocal thus gives a numerical q = a/b
  334. // in Q53 with the following properties:
  335. //
  336. // 1. q < a/b
  337. // 2. q is in the interval [0.5, 2.0)
  338. // 3. the error in q is bounded away from 2^-53 (actually, we have a
  339. // couple of bits to spare, but this is all we need).
  340. // We need a 64 x 64 multiply high to compute q, which isn't a basic
  341. // operation in C, so we need to be a little bit fussy.
  342. // let mut quotient: F::Int = ((((reciprocal as u64)
  343. // .wrapping_mul(CastInto::<u32>::cast(a_significand << 1) as u64))
  344. // >> 32) as u32)
  345. // .cast();
  346. // We need a 64 x 64 multiply high to compute q, which isn't a basic
  347. // operation in C, so we need to be a little bit fussy.
  348. let mut quotient = (a_significand << 2).widen_mul(reciprocal.cast()).hi();
  349. // Two cases: quotient is in [0.5, 1.0) or quotient is in [1.0, 2.0).
  350. // In either case, we are going to compute a residual of the form
  351. //
  352. // r = a - q*b
  353. //
  354. // We know from the construction of q that r satisfies:
  355. //
  356. // 0 <= r < ulp(q)*b
  357. //
  358. // if r is greater than 1/2 ulp(q)*b, then q rounds up. Otherwise, we
  359. // already have the correct result. The exact halfway case cannot occur.
  360. // We also take this time to right shift quotient if it falls in the [1,2)
  361. // range and adjust the exponent accordingly.
  362. let residual = if quotient < (implicit_bit << 1) {
  363. quotient_exponent = quotient_exponent.wrapping_sub(1);
  364. (a_significand << (significand_bits + 1)).wrapping_sub(quotient.wrapping_mul(b_significand))
  365. } else {
  366. quotient >>= 1;
  367. (a_significand << significand_bits).wrapping_sub(quotient.wrapping_mul(b_significand))
  368. };
  369. let written_exponent = quotient_exponent.wrapping_add(exponent_bias as i32);
  370. if written_exponent >= max_exponent as i32 {
  371. // If we have overflowed the exponent, return infinity.
  372. return F::from_repr(inf_rep | quotient_sign);
  373. } else if written_exponent < 1 {
  374. // Flush denormals to zero. In the future, it would be nice to add
  375. // code to round them correctly.
  376. return F::from_repr(quotient_sign);
  377. } else {
  378. let round = ((residual << 1) > b_significand) as u32;
  379. // Clear the implicit bits
  380. let mut abs_result = quotient & significand_mask;
  381. // Insert the exponent
  382. abs_result |= written_exponent.cast() << significand_bits;
  383. // Round
  384. abs_result = abs_result.wrapping_add(round.cast());
  385. // Insert the sign and return
  386. return F::from_repr(abs_result | quotient_sign);
  387. }
  388. }
  389. intrinsics! {
  390. #[arm_aeabi_alias = __aeabi_fdiv]
  391. pub extern "C" fn __divsf3(a: f32, b: f32) -> f32 {
  392. div32(a, b)
  393. }
  394. #[arm_aeabi_alias = __aeabi_ddiv]
  395. pub extern "C" fn __divdf3(a: f64, b: f64) -> f64 {
  396. div64(a, b)
  397. }
  398. #[cfg(target_arch = "arm")]
  399. pub extern "C" fn __divsf3vfp(a: f32, b: f32) -> f32 {
  400. a / b
  401. }
  402. #[cfg(target_arch = "arm")]
  403. pub extern "C" fn __divdf3vfp(a: f64, b: f64) -> f64 {
  404. a / b
  405. }
  406. }