• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* Compile with:
2 *
3 * glsl_compiler --version 400 --dump-builder int64.glsl > builtin_int64.h
4 *
5 * Version 4.00+ is required for umulExtended.
6 */
7#version 400
8#extension GL_ARB_gpu_shader_int64: require
9#extension GL_ARB_shading_language_420pack: require
10
11uvec4
12udivmod64(uvec2 n, uvec2 d)
13{
14   uvec2 quot = uvec2(0U, 0U);
15   int log2_denom = findMSB(d.y) + 32;
16
17   /* If the upper 32 bits of denom are non-zero, it is impossible for shifts
18    * greater than 32 bits to occur.  If the upper 32 bits of the numerator
19    * are zero, it is impossible for (denom << [63, 32]) <= numer unless
20    * denom == 0.
21    */
22   if (d.y == 0 && n.y >= d.x) {
23      log2_denom = findMSB(d.x);
24
25      /* Since the upper 32 bits of denom are zero, log2_denom <= 31 and we
26       * don't have to compare log2_denom inside the loop as is done in the
27       * general case (below).
28       */
29      for (int i = 31; i >= 1; i--) {
30	 if (log2_denom <= 31 - i && (d.x << i) <= n.y) {
31	    n.y -= d.x << i;
32	    quot.y |= 1U << i;
33	 }
34      }
35
36      /* log2_denom is always <= 31, so manually peel the last loop
37       * iteration.
38       */
39      if (d.x <= n.y) {
40	 n.y -= d.x;
41	 quot.y |= 1U;
42      }
43   }
44
45   uint64_t d64 = packUint2x32(d);
46   uint64_t n64 = packUint2x32(n);
47   for (int i = 31; i >= 1; i--) {
48      if (log2_denom <= 63 - i && (d64 << i) <= n64) {
49	 n64 -= d64 << i;
50	 quot.x |= 1U << i;
51      }
52   }
53
54   /* log2_denom is always <= 63, so manually peel the last loop
55    * iteration.
56    */
57   if (d64 <= n64) {
58      n64 -= d64;
59      quot.x |= 1U;
60   }
61
62   return uvec4(quot, unpackUint2x32(n64));
63}
64
65uvec2
66udiv64(uvec2 n, uvec2 d)
67{
68   return udivmod64(n, d).xy;
69}
70
71ivec2
72idiv64(ivec2 _n, ivec2 _d)
73{
74   const bool negate = (_n.y < 0) != (_d.y < 0);
75   uvec2 n = unpackUint2x32(uint64_t(abs(packInt2x32(_n))));
76   uvec2 d = unpackUint2x32(uint64_t(abs(packInt2x32(_d))));
77
78   uvec2 quot = udivmod64(n, d).xy;
79
80   return negate ? unpackInt2x32(-int64_t(packUint2x32(quot))) : ivec2(quot);
81}
82
83uvec2
84umod64(uvec2 n, uvec2 d)
85{
86   return udivmod64(n, d).zw;
87}
88
89ivec2
90imod64(ivec2 _n, ivec2 _d)
91{
92   const bool negate = (_n.y < 0) != (_d.y < 0);
93   uvec2 n = unpackUint2x32(uint64_t(abs(packInt2x32(_n))));
94   uvec2 d = unpackUint2x32(uint64_t(abs(packInt2x32(_d))));
95
96   uvec2 rem = udivmod64(n, d).zw;
97
98   return negate ? unpackInt2x32(-int64_t(packUint2x32(rem))) : ivec2(rem);
99}
100