• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2015 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include <math.h>
25 
26 #include "nir/nir_builtin_builder.h"
27 
28 #include "vtn_private.h"
29 #include "GLSL.std.450.h"
30 
31 #ifndef M_PIf
32 #define M_PIf   ((float) M_PI)
33 #endif
34 #ifndef M_PI_2f
35 #define M_PI_2f ((float) M_PI_2)
36 #endif
37 #ifndef M_PI_4f
38 #define M_PI_4f ((float) M_PI_4)
39 #endif
40 
41 static nir_def *build_det(nir_builder *b, nir_def **col, unsigned cols);
42 
43 /* Computes the determinate of the submatrix given by taking src and
44  * removing the specified row and column.
45  */
46 static nir_def *
build_mat_subdet(struct nir_builder * b,struct nir_def ** src,unsigned size,unsigned row,unsigned col)47 build_mat_subdet(struct nir_builder *b, struct nir_def **src,
48                  unsigned size, unsigned row, unsigned col)
49 {
50    assert(row < size && col < size);
51    if (size == 2) {
52       return nir_channel(b, src[1 - col], 1 - row);
53    } else {
54       /* Swizzle to get all but the specified row */
55       unsigned swiz[NIR_MAX_VEC_COMPONENTS] = {0};
56       for (unsigned j = 0; j < 3; j++)
57          swiz[j] = j + (j >= row);
58 
59       /* Grab all but the specified column */
60       nir_def *subcol[3];
61       for (unsigned j = 0; j < size; j++) {
62          if (j != col) {
63             subcol[j - (j > col)] = nir_swizzle(b, src[j], swiz, size - 1);
64          }
65       }
66 
67       return build_det(b, subcol, size - 1);
68    }
69 }
70 
71 static nir_def *
build_det(nir_builder * b,nir_def ** col,unsigned size)72 build_det(nir_builder *b, nir_def **col, unsigned size)
73 {
74    assert(size <= 4);
75    nir_def *subdet[4];
76    for (unsigned i = 0; i < size; i++)
77       subdet[i] = build_mat_subdet(b, col, size, i, 0);
78 
79    nir_def *prod = nir_fmul(b, col[0], nir_vec(b, subdet, size));
80 
81    nir_def *result = NULL;
82    for (unsigned i = 0; i < size; i += 2) {
83       nir_def *term;
84       if (i + 1 < size) {
85          term = nir_fsub(b, nir_channel(b, prod, i),
86                             nir_channel(b, prod, i + 1));
87       } else {
88          term = nir_channel(b, prod, i);
89       }
90 
91       result = result ? nir_fadd(b, result, term) : term;
92    }
93 
94    return result;
95 }
96 
97 static nir_def *
build_mat_det(struct vtn_builder * b,struct vtn_ssa_value * src)98 build_mat_det(struct vtn_builder *b, struct vtn_ssa_value *src)
99 {
100    unsigned size = glsl_get_vector_elements(src->type);
101 
102    nir_def *cols[4];
103    for (unsigned i = 0; i < size; i++)
104       cols[i] = src->elems[i]->def;
105 
106    return build_det(&b->nb, cols, size);
107 }
108 
109 static struct vtn_ssa_value *
matrix_inverse(struct vtn_builder * b,struct vtn_ssa_value * src)110 matrix_inverse(struct vtn_builder *b, struct vtn_ssa_value *src)
111 {
112    nir_def *adj_col[4];
113    unsigned size = glsl_get_vector_elements(src->type);
114 
115    nir_def *cols[4];
116    for (unsigned i = 0; i < size; i++)
117       cols[i] = src->elems[i]->def;
118 
119    /* Build up an adjugate matrix */
120    for (unsigned c = 0; c < size; c++) {
121       nir_def *elem[4];
122       for (unsigned r = 0; r < size; r++) {
123          elem[r] = build_mat_subdet(&b->nb, cols, size, c, r);
124 
125          if ((r + c) % 2)
126             elem[r] = nir_fneg(&b->nb, elem[r]);
127       }
128 
129       adj_col[c] = nir_vec(&b->nb, elem, size);
130    }
131 
132    nir_def *det_inv = nir_frcp(&b->nb, build_det(&b->nb, cols, size));
133 
134    struct vtn_ssa_value *val = vtn_create_ssa_value(b, src->type);
135    for (unsigned i = 0; i < size; i++)
136       val->elems[i]->def = nir_fmul(&b->nb, adj_col[i], det_inv);
137 
138    return val;
139 }
140 
141 /**
142  * Approximate asin(x) by the piecewise formula:
143  * for |x| < 0.5, asin~(x) = x * (1 + x²(pS0 + x²(pS1 + x²*pS2)) / (1 + x²*qS1))
144  * for |x| ≥ 0.5, asin~(x) = sign(x) * (π/2 - sqrt(1 - |x|) * (π/2 + |x|(π/4 - 1 + |x|(p0 + |x|p1))))
145  *
146  * The latter is correct to first order at x=0 and x=±1 regardless of the p
147  * coefficients but can be made second-order correct at both ends by selecting
148  * the fit coefficients appropriately.  Different p coefficients can be used
149  * in the asin and acos implementation to minimize some relative error metric
150  * in each case.
151  */
152 static nir_def *
build_asin(nir_builder * b,nir_def * x,float p0,float p1,bool piecewise)153 build_asin(nir_builder *b, nir_def *x, float p0, float p1, bool piecewise)
154 {
155    if (x->bit_size == 16) {
156       /* The polynomial approximation isn't precise enough to meet half-float
157        * precision requirements. Alternatively, we could implement this using
158        * the formula:
159        *
160        * asin(x) = atan2(x, sqrt(1 - x*x))
161        *
162        * But that is very expensive, so instead we just do the polynomial
163        * approximation in 32-bit math and then we convert the result back to
164        * 16-bit.
165        */
166       return nir_f2f16(b, build_asin(b, nir_f2f32(b, x), p0, p1, piecewise));
167    }
168    nir_def *one = nir_imm_floatN_t(b, 1.0f, x->bit_size);
169    nir_def *half = nir_imm_floatN_t(b, 0.5f, x->bit_size);
170    nir_def *abs_x = nir_fabs(b, x);
171 
172    nir_def *p0_plus_xp1 = nir_ffma_imm12(b, abs_x, p1, p0);
173 
174    nir_def *expr_tail =
175       nir_ffma_imm2(b, abs_x,
176                        nir_ffma_imm2(b, abs_x, p0_plus_xp1, M_PI_4f - 1.0f),
177                        M_PI_2f);
178 
179    nir_def *result0 = nir_fmul(b, nir_fsign(b, x),
180                       nir_a_minus_bc(b, nir_imm_floatN_t(b, M_PI_2f, x->bit_size),
181                                         nir_fsqrt(b, nir_fsub(b, one, abs_x)),
182                                         expr_tail));
183    if (piecewise) {
184       /* approximation for |x| < 0.5 */
185       const float pS0 =  1.6666586697e-01f;
186       const float pS1 = -4.2743422091e-02f;
187       const float pS2 = -8.6563630030e-03f;
188       const float qS1 = -7.0662963390e-01f;
189 
190       nir_def *x2 = nir_fmul(b, x, x);
191       nir_def *p = nir_fmul(b,
192                                 x2,
193                                 nir_ffma_imm2(b, x2,
194                                                  nir_ffma_imm12(b, x2, pS2, pS1),
195                                                  pS0));
196 
197       nir_def *q = nir_ffma_imm1(b, x2, qS1, one);
198       nir_def *result1 = nir_ffma(b, x, nir_fdiv(b, p, q), x);
199       return nir_bcsel(b, nir_flt(b, abs_x, half), result1, result0);
200    } else {
201       return result0;
202    }
203 }
204 
205 static nir_op
vtn_nir_alu_op_for_spirv_glsl_opcode(struct vtn_builder * b,enum GLSLstd450 opcode,unsigned execution_mode,bool * exact)206 vtn_nir_alu_op_for_spirv_glsl_opcode(struct vtn_builder *b,
207                                      enum GLSLstd450 opcode,
208                                      unsigned execution_mode,
209                                      bool *exact)
210 {
211    *exact = false;
212    switch (opcode) {
213    case GLSLstd450Round:         return nir_op_fround_even;
214    case GLSLstd450RoundEven:     return nir_op_fround_even;
215    case GLSLstd450Trunc:         return nir_op_ftrunc;
216    case GLSLstd450FAbs:          return nir_op_fabs;
217    case GLSLstd450SAbs:          return nir_op_iabs;
218    case GLSLstd450FSign:         return nir_op_fsign;
219    case GLSLstd450SSign:         return nir_op_isign;
220    case GLSLstd450Floor:         return nir_op_ffloor;
221    case GLSLstd450Ceil:          return nir_op_fceil;
222    case GLSLstd450Fract:         return nir_op_ffract;
223    case GLSLstd450Sin:           return nir_op_fsin;
224    case GLSLstd450Cos:           return nir_op_fcos;
225    case GLSLstd450Pow:           return nir_op_fpow;
226    case GLSLstd450Exp2:          return nir_op_fexp2;
227    case GLSLstd450Log2:          return nir_op_flog2;
228    case GLSLstd450Sqrt:          return nir_op_fsqrt;
229    case GLSLstd450InverseSqrt:   return nir_op_frsq;
230    case GLSLstd450NMin:          *exact = true; return nir_op_fmin;
231    case GLSLstd450FMin:          return nir_op_fmin;
232    case GLSLstd450UMin:          return nir_op_umin;
233    case GLSLstd450SMin:          return nir_op_imin;
234    case GLSLstd450NMax:          *exact = true; return nir_op_fmax;
235    case GLSLstd450FMax:          return nir_op_fmax;
236    case GLSLstd450UMax:          return nir_op_umax;
237    case GLSLstd450SMax:          return nir_op_imax;
238    case GLSLstd450FMix:          return nir_op_flrp;
239    case GLSLstd450Fma:           return nir_op_ffma;
240    case GLSLstd450Ldexp:         return nir_op_ldexp;
241    case GLSLstd450FindILsb:      return nir_op_find_lsb;
242    case GLSLstd450FindSMsb:      return nir_op_ifind_msb;
243    case GLSLstd450FindUMsb:      return nir_op_ufind_msb;
244 
245    /* Packing/Unpacking functions */
246    case GLSLstd450PackSnorm4x8:     return nir_op_pack_snorm_4x8;
247    case GLSLstd450PackUnorm4x8:     return nir_op_pack_unorm_4x8;
248    case GLSLstd450PackSnorm2x16:    return nir_op_pack_snorm_2x16;
249    case GLSLstd450PackUnorm2x16:    return nir_op_pack_unorm_2x16;
250    case GLSLstd450PackHalf2x16:     return nir_op_pack_half_2x16;
251    case GLSLstd450PackDouble2x32:   return nir_op_pack_64_2x32;
252    case GLSLstd450UnpackSnorm4x8:   return nir_op_unpack_snorm_4x8;
253    case GLSLstd450UnpackUnorm4x8:   return nir_op_unpack_unorm_4x8;
254    case GLSLstd450UnpackSnorm2x16:  return nir_op_unpack_snorm_2x16;
255    case GLSLstd450UnpackUnorm2x16:  return nir_op_unpack_unorm_2x16;
256    case GLSLstd450UnpackHalf2x16:
257       if (execution_mode & FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP16)
258          return nir_op_unpack_half_2x16_flush_to_zero;
259       else
260          return nir_op_unpack_half_2x16;
261    case GLSLstd450UnpackDouble2x32: return nir_op_unpack_64_2x32;
262 
263    default:
264       vtn_fail("No NIR equivalent");
265    }
266 }
267 
268 #define NIR_IMM_FP(n, v) (nir_imm_floatN_t(n, v, src[0]->bit_size))
269 
270 static void
handle_glsl450_alu(struct vtn_builder * b,enum GLSLstd450 entrypoint,const uint32_t * w,unsigned count)271 handle_glsl450_alu(struct vtn_builder *b, enum GLSLstd450 entrypoint,
272                    const uint32_t *w, unsigned count)
273 {
274    struct nir_builder *nb = &b->nb;
275    const struct glsl_type *dest_type = vtn_get_type(b, w[1])->type;
276    struct vtn_value *dest_val = vtn_untyped_value(b, w[2]);
277 
278    bool mediump_16bit;
279    switch (entrypoint) {
280    case GLSLstd450PackSnorm4x8:
281    case GLSLstd450PackUnorm4x8:
282    case GLSLstd450PackSnorm2x16:
283    case GLSLstd450PackUnorm2x16:
284    case GLSLstd450PackHalf2x16:
285    case GLSLstd450PackDouble2x32:
286    case GLSLstd450UnpackSnorm4x8:
287    case GLSLstd450UnpackUnorm4x8:
288    case GLSLstd450UnpackSnorm2x16:
289    case GLSLstd450UnpackUnorm2x16:
290    case GLSLstd450UnpackHalf2x16:
291    case GLSLstd450UnpackDouble2x32:
292       /* Asking for relaxed precision snorm 4x8 pack results (for example)
293        * doesn't even make sense.  The NIR opcodes have a fixed output size, so
294        * no trying to reduce precision.
295        */
296       mediump_16bit = false;
297       break;
298 
299    case GLSLstd450Frexp:
300    case GLSLstd450FrexpStruct:
301    case GLSLstd450Modf:
302    case GLSLstd450ModfStruct:
303       /* Not sure how to detect the ->elems[i] destinations on these in vtn_upconvert_value(). */
304       mediump_16bit = false;
305       break;
306 
307    default:
308       mediump_16bit = b->options->mediump_16bit_alu && vtn_value_is_relaxed_precision(b, dest_val);
309       break;
310    }
311 
312    /* Collect the various SSA sources */
313    unsigned num_inputs = count - 5;
314    nir_def *src[3] = { NULL, };
315    for (unsigned i = 0; i < num_inputs; i++) {
316       /* These are handled specially below */
317       if (vtn_untyped_value(b, w[i + 5])->value_type == vtn_value_type_pointer)
318          continue;
319 
320       src[i] = vtn_get_nir_ssa(b, w[i + 5]);
321       if (mediump_16bit) {
322          struct vtn_ssa_value *vtn_src = vtn_ssa_value(b, w[i + 5]);
323          src[i] = vtn_mediump_downconvert(b, glsl_get_base_type(vtn_src->type), src[i]);
324       }
325    }
326 
327    struct vtn_ssa_value *dest = vtn_create_ssa_value(b, dest_type);
328 
329    vtn_handle_no_contraction(b, vtn_untyped_value(b, w[2]));
330    switch (entrypoint) {
331    case GLSLstd450Radians:
332       dest->def = nir_radians(nb, src[0]);
333       break;
334    case GLSLstd450Degrees:
335       dest->def = nir_degrees(nb, src[0]);
336       break;
337    case GLSLstd450Tan:
338       dest->def = nir_ftan(nb, src[0]);
339       break;
340 
341    case GLSLstd450Modf: {
342       nir_def *inf = nir_imm_floatN_t(&b->nb, INFINITY, src[0]->bit_size);
343       nir_def *sign_bit =
344          nir_imm_intN_t(&b->nb, (uint64_t)1 << (src[0]->bit_size - 1),
345                         src[0]->bit_size);
346       nir_def *sign = nir_fsign(nb, src[0]);
347       nir_def *abs = nir_fabs(nb, src[0]);
348 
349       /* NaN input should produce a NaN results, and ±Inf input should provide
350        * ±0 result.  The fmul(sign(x), ffract(x)) calculation will already
351        * produce the expected NaN.  To get ±0, directly compare for equality
352        * with Inf instead of using fisfinite (which is false for NaN).
353        */
354       dest->def = nir_bcsel(nb,
355                             nir_ieq(nb, abs, inf),
356                             nir_iand(nb, src[0], sign_bit),
357                             nir_fmul(nb, sign, nir_ffract(nb, abs)));
358 
359       struct vtn_pointer *i_ptr = vtn_value(b, w[6], vtn_value_type_pointer)->pointer;
360       struct vtn_ssa_value *whole = vtn_create_ssa_value(b, i_ptr->type->type);
361       whole->def = nir_fmul(nb, sign, nir_ffloor(nb, abs));
362       vtn_variable_store(b, whole, i_ptr, 0);
363       break;
364    }
365 
366    case GLSLstd450ModfStruct: {
367       nir_def *inf = nir_imm_floatN_t(&b->nb, INFINITY, src[0]->bit_size);
368       nir_def *sign_bit =
369          nir_imm_intN_t(&b->nb, (uint64_t)1 << (src[0]->bit_size - 1),
370                         src[0]->bit_size);
371       nir_def *sign = nir_fsign(nb, src[0]);
372       nir_def *abs = nir_fabs(nb, src[0]);
373       vtn_assert(glsl_type_is_struct_or_ifc(dest_type));
374 
375       /* See GLSLstd450Modf for explanation of the Inf and NaN handling. */
376       dest->elems[0]->def = nir_bcsel(nb,
377                                       nir_ieq(nb, abs, inf),
378                                       nir_iand(nb, src[0], sign_bit),
379                                       nir_fmul(nb, sign, nir_ffract(nb, abs)));
380       dest->elems[1]->def = nir_fmul(nb, sign, nir_ffloor(nb, abs));
381       break;
382    }
383 
384    case GLSLstd450Step: {
385       /* The SPIR-V Extended Instructions for GLSL spec says:
386        *
387        *    Result is 0.0 if x < edge; otherwise result is 1.0.
388        *
389        * Here src[1] is x, and src[0] is edge.  The direct implementation is
390        *
391        *    bcsel(src[1] < src[0], 0.0, 1.0)
392        *
393        * This is effectively b2f(!(src1 < src0)).  Previously this was
394        * implemented using sge(src1, src0), but that produces incorrect
395        * results for NaN.  Instead, we use the identity b2f(!x) = 1 - b2f(x).
396        */
397       const bool exact = nb->exact;
398       nb->exact = true;
399 
400       nir_def *cmp = nir_slt(nb, src[1], src[0]);
401 
402       nb->exact = exact;
403       dest->def = nir_fsub_imm(nb, 1.0f, cmp);
404       break;
405    }
406 
407    case GLSLstd450Length:
408       dest->def = nir_fast_length(nb, src[0]);
409       break;
410    case GLSLstd450Distance:
411       dest->def = nir_fast_distance(nb, src[0], src[1]);
412       break;
413    case GLSLstd450Normalize:
414       dest->def = nir_fast_normalize(nb, src[0]);
415       break;
416 
417    case GLSLstd450Exp:
418       dest->def = nir_fexp(nb, src[0]);
419       break;
420 
421    case GLSLstd450Log:
422       dest->def = nir_flog(nb, src[0]);
423       break;
424 
425    case GLSLstd450FClamp:
426       dest->def = nir_fclamp(nb, src[0], src[1], src[2]);
427       break;
428    case GLSLstd450NClamp:
429       nb->exact = true;
430       dest->def = nir_fclamp(nb, src[0], src[1], src[2]);
431       nb->exact = false;
432       break;
433    case GLSLstd450UClamp:
434       dest->def = nir_uclamp(nb, src[0], src[1], src[2]);
435       break;
436    case GLSLstd450SClamp:
437       dest->def = nir_iclamp(nb, src[0], src[1], src[2]);
438       break;
439 
440    case GLSLstd450Cross: {
441       dest->def = nir_cross3(nb, src[0], src[1]);
442       break;
443    }
444 
445    case GLSLstd450SmoothStep: {
446       dest->def = nir_smoothstep(nb, src[0], src[1], src[2]);
447       break;
448    }
449 
450    case GLSLstd450FaceForward:
451       dest->def =
452          nir_bcsel(nb, nir_flt(nb, nir_fdot(nb, src[2], src[1]),
453                                    NIR_IMM_FP(nb, 0.0)),
454                        src[0], nir_fneg(nb, src[0]));
455       break;
456 
457    case GLSLstd450Reflect:
458       /* I - 2 * dot(N, I) * N */
459       dest->def =
460          nir_a_minus_bc(nb, src[0],
461                             src[1],
462                             nir_fmul(nb, nir_fdot(nb, src[0], src[1]),
463                                          NIR_IMM_FP(nb, 2.0)));
464       break;
465 
466    case GLSLstd450Refract: {
467       nir_def *I = src[0];
468       nir_def *N = src[1];
469       nir_def *eta = src[2];
470       nir_def *n_dot_i = nir_fdot(nb, N, I);
471       nir_def *one = NIR_IMM_FP(nb, 1.0);
472       nir_def *zero = NIR_IMM_FP(nb, 0.0);
473       /* According to the SPIR-V and GLSL specs, eta is always a float
474        * regardless of the type of the other operands. However in practice it
475        * seems that if you try to pass it a float then glslang will just
476        * promote it to a double and generate invalid SPIR-V. In order to
477        * support a hypothetical fixed version of glslang we’ll promote eta to
478        * double if the other operands are double also.
479        */
480       if (I->bit_size != eta->bit_size) {
481          eta = nir_type_convert(nb, eta, nir_type_float,
482                                 nir_type_float | I->bit_size,
483                                 nir_rounding_mode_undef);
484       }
485       /* k = 1.0 - eta * eta * (1.0 - dot(N, I) * dot(N, I)) */
486       nir_def *k =
487          nir_a_minus_bc(nb, one, eta,
488                             nir_fmul(nb, eta, nir_a_minus_bc(nb, one, n_dot_i, n_dot_i)));
489       nir_def *result =
490          nir_a_minus_bc(nb, nir_fmul(nb, eta, I),
491                             nir_ffma(nb, eta, n_dot_i, nir_fsqrt(nb, k)),
492                             N);
493       /* XXX: bcsel, or if statement? */
494       dest->def = nir_bcsel(nb, nir_flt(nb, k, zero), zero, result);
495       break;
496    }
497 
498    case GLSLstd450Sinh:
499       /* 0.5 * (e^x - e^(-x)) */
500       dest->def =
501          nir_fmul_imm(nb, nir_fsub(nb, nir_fexp(nb, src[0]),
502                                        nir_fexp(nb, nir_fneg(nb, src[0]))),
503                           0.5f);
504       break;
505 
506    case GLSLstd450Cosh:
507       /* 0.5 * (e^x + e^(-x)) */
508       dest->def =
509          nir_fmul_imm(nb, nir_fadd(nb, nir_fexp(nb, src[0]),
510                                        nir_fexp(nb, nir_fneg(nb, src[0]))),
511                           0.5f);
512       break;
513 
514    case GLSLstd450Tanh: {
515       /* tanh(x) := (e^x - e^(-x)) / (e^x + e^(-x))
516        *
517        * We clamp x to [-10, +10] to avoid precision problems.  When x > 10,
518        * e^x dominates the sum, e^(-x) is lost and tanh(x) is 1.0 for 32 bit
519        * floating point.
520        *
521        * For 16-bit precision this we clamp x to [-4.2, +4.2].
522        */
523       const uint32_t bit_size = src[0]->bit_size;
524       const double clamped_x = bit_size > 16 ? 10.0 : 4.2;
525       nir_def *x = nir_fclamp(nb, src[0],
526                                   nir_imm_floatN_t(nb, -clamped_x, bit_size),
527                                   nir_imm_floatN_t(nb, clamped_x, bit_size));
528 
529       /* The clamping will filter out NaN values causing an incorrect result.
530        * The comparison is carefully structured to get NaN result for NaN and
531        * get -0 for -0.
532        *
533        *    result = abs(s) > 0.0 ? ... : s;
534        */
535       const bool exact = nb->exact;
536 
537       nb->exact = true;
538       nir_def *is_regular = nir_flt(nb,
539                                         nir_imm_floatN_t(nb, 0, bit_size),
540                                         nir_fabs(nb, src[0]));
541 
542       /* The extra 1.0*s ensures that subnormal inputs are flushed to zero
543        * when that is selected by the shader.
544        */
545       nir_def *flushed = nir_fmul(nb,
546                                       src[0],
547                                       nir_imm_floatN_t(nb, 1.0, bit_size));
548       nb->exact = exact;
549 
550       dest->def = nir_bcsel(nb,
551                             is_regular,
552                             nir_fdiv(nb, nir_fsub(nb, nir_fexp(nb, x),
553                                                   nir_fexp(nb, nir_fneg(nb, x))),
554                                      nir_fadd(nb, nir_fexp(nb, x),
555                                               nir_fexp(nb, nir_fneg(nb, x)))),
556                             flushed);
557       break;
558    }
559 
560    case GLSLstd450Asinh:
561       dest->def = nir_fmul(nb, nir_fsign(nb, src[0]),
562          nir_flog(nb, nir_fadd(nb, nir_fabs(nb, src[0]),
563                       nir_fsqrt(nb, nir_ffma_imm2(nb, src[0], src[0], 1.0f)))));
564       break;
565    case GLSLstd450Acosh:
566       dest->def = nir_flog(nb, nir_fadd(nb, src[0],
567          nir_fsqrt(nb, nir_ffma_imm2(nb, src[0], src[0], -1.0f))));
568       break;
569    case GLSLstd450Atanh: {
570       dest->def =
571          nir_fmul_imm(nb, nir_flog(nb, nir_fdiv(nb, nir_fadd_imm(nb, src[0], 1.0),
572                                        nir_fsub_imm(nb, 1.0, src[0]))),
573                           0.5f);
574       break;
575    }
576 
577    case GLSLstd450Asin:
578       dest->def = build_asin(nb, src[0], 0.086566724, -0.03102955, true);
579       break;
580 
581    case GLSLstd450Acos:
582       dest->def =
583          nir_fsub_imm(nb, M_PI_2f,
584                           build_asin(nb, src[0], 0.08132463, -0.02363318, false));
585       break;
586 
587    case GLSLstd450Atan:
588       dest->def = nir_atan(nb, src[0]);
589       break;
590 
591    case GLSLstd450Atan2:
592       dest->def = nir_atan2(nb, src[0], src[1]);
593       break;
594 
595    case GLSLstd450Frexp: {
596       dest->def = nir_frexp_sig(nb, src[0]);
597 
598       struct vtn_pointer *i_ptr = vtn_value(b, w[6], vtn_value_type_pointer)->pointer;
599       struct vtn_ssa_value *exp = vtn_create_ssa_value(b, i_ptr->type->type);
600       exp->def = nir_frexp_exp(nb, src[0]);
601       vtn_variable_store(b, exp, i_ptr, 0);
602       break;
603    }
604 
605    case GLSLstd450FrexpStruct: {
606       vtn_assert(glsl_type_is_struct_or_ifc(dest_type));
607       dest->elems[0]->def = nir_frexp_sig(nb, src[0]);
608       dest->elems[1]->def = nir_frexp_exp(nb, src[0]);
609       break;
610    }
611 
612    default: {
613       unsigned execution_mode =
614          b->shader->info.float_controls_execution_mode;
615       bool exact;
616       nir_op op = vtn_nir_alu_op_for_spirv_glsl_opcode(b, entrypoint, execution_mode, &exact);
617       /* don't override explicit decoration */
618       b->nb.exact |= exact;
619       dest->def = nir_build_alu(&b->nb, op, src[0], src[1], src[2], NULL);
620       break;
621    }
622    }
623    b->nb.exact = false;
624 
625    if (mediump_16bit)
626       vtn_mediump_upconvert_value(b, dest);
627 
628    vtn_push_ssa_value(b, w[2], dest);
629 }
630 
631 static void
handle_glsl450_interpolation(struct vtn_builder * b,enum GLSLstd450 opcode,const uint32_t * w,unsigned count)632 handle_glsl450_interpolation(struct vtn_builder *b, enum GLSLstd450 opcode,
633                              const uint32_t *w, unsigned count)
634 {
635    nir_intrinsic_op op;
636    switch (opcode) {
637    case GLSLstd450InterpolateAtCentroid:
638       op = nir_intrinsic_interp_deref_at_centroid;
639       break;
640    case GLSLstd450InterpolateAtSample:
641       op = nir_intrinsic_interp_deref_at_sample;
642       break;
643    case GLSLstd450InterpolateAtOffset:
644       op = nir_intrinsic_interp_deref_at_offset;
645       break;
646    default:
647       vtn_fail("Invalid opcode");
648    }
649 
650    nir_intrinsic_instr *intrin = nir_intrinsic_instr_create(b->nb.shader, op);
651 
652    struct vtn_pointer *ptr =
653       vtn_value(b, w[5], vtn_value_type_pointer)->pointer;
654    nir_deref_instr *deref = vtn_pointer_to_deref(b, ptr);
655 
656    /* If the value we are interpolating has an index into a vector then
657     * interpolate the vector and index the result of that instead. This is
658     * necessary because the index will get generated as a series of nir_bcsel
659     * instructions so it would no longer be an input variable.
660     */
661    const bool vec_array_deref = deref->deref_type == nir_deref_type_array &&
662       glsl_type_is_vector(nir_deref_instr_parent(deref)->type);
663 
664    nir_deref_instr *vec_deref = NULL;
665    if (vec_array_deref) {
666       vec_deref = deref;
667       deref = nir_deref_instr_parent(deref);
668    }
669    intrin->src[0] = nir_src_for_ssa(&deref->def);
670 
671    switch (opcode) {
672    case GLSLstd450InterpolateAtCentroid:
673       break;
674    case GLSLstd450InterpolateAtSample:
675    case GLSLstd450InterpolateAtOffset:
676       intrin->src[1] = nir_src_for_ssa(vtn_get_nir_ssa(b, w[6]));
677       break;
678    default:
679       vtn_fail("Invalid opcode");
680    }
681 
682    intrin->num_components = glsl_get_vector_elements(deref->type);
683    nir_def_init(&intrin->instr, &intrin->def,
684                 glsl_get_vector_elements(deref->type),
685                 glsl_get_bit_size(deref->type));
686 
687    nir_builder_instr_insert(&b->nb, &intrin->instr);
688 
689    nir_def *def = &intrin->def;
690    if (vec_array_deref)
691       def = nir_vector_extract(&b->nb, def, vec_deref->arr.index.ssa);
692 
693    vtn_push_nir_ssa(b, w[2], def);
694 }
695 
696 bool
vtn_handle_glsl450_instruction(struct vtn_builder * b,SpvOp ext_opcode,const uint32_t * w,unsigned count)697 vtn_handle_glsl450_instruction(struct vtn_builder *b, SpvOp ext_opcode,
698                                const uint32_t *w, unsigned count)
699 {
700    switch ((enum GLSLstd450)ext_opcode) {
701    case GLSLstd450Determinant: {
702       vtn_push_nir_ssa(b, w[2], build_mat_det(b, vtn_ssa_value(b, w[5])));
703       break;
704    }
705 
706    case GLSLstd450MatrixInverse: {
707       vtn_push_ssa_value(b, w[2], matrix_inverse(b, vtn_ssa_value(b, w[5])));
708       break;
709    }
710 
711    case GLSLstd450InterpolateAtCentroid:
712    case GLSLstd450InterpolateAtSample:
713    case GLSLstd450InterpolateAtOffset:
714       handle_glsl450_interpolation(b, (enum GLSLstd450)ext_opcode, w, count);
715       break;
716 
717    default:
718       handle_glsl450_alu(b, (enum GLSLstd450)ext_opcode, w, count);
719    }
720 
721    return true;
722 }
723