OSDN Git Service

vc4: Actually allow math results to allocate into r4.
[android-x86/external-mesa.git] / src / gallium / drivers / vc4 / vc4_program.c
1 /*
2  * Copyright (c) 2014 Scott Mansell
3  * Copyright © 2014 Broadcom
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  */
24
25 #include <inttypes.h>
26 #include "util/u_format.h"
27 #include "util/u_hash.h"
28 #include "util/u_math.h"
29 #include "util/u_memory.h"
30 #include "util/ralloc.h"
31 #include "util/hash_table.h"
32 #include "tgsi/tgsi_dump.h"
33 #include "tgsi/tgsi_info.h"
34 #include "tgsi/tgsi_lowering.h"
35 #include "tgsi/tgsi_parse.h"
36 #include "glsl/nir/nir.h"
37 #include "glsl/nir/nir_builder.h"
38 #include "nir/tgsi_to_nir.h"
39 #include "vc4_context.h"
40 #include "vc4_qpu.h"
41 #include "vc4_qir.h"
42 #ifdef USE_VC4_SIMULATOR
43 #include "simpenrose/simpenrose.h"
44 #endif
45
46 static struct qreg
47 ntq_get_src(struct vc4_compile *c, nir_src src, int i);
48
49 static void
50 resize_qreg_array(struct vc4_compile *c,
51                   struct qreg **regs,
52                   uint32_t *size,
53                   uint32_t decl_size)
54 {
55         if (*size >= decl_size)
56                 return;
57
58         uint32_t old_size = *size;
59         *size = MAX2(*size * 2, decl_size);
60         *regs = reralloc(c, *regs, struct qreg, *size);
61         if (!*regs) {
62                 fprintf(stderr, "Malloc failure\n");
63                 abort();
64         }
65
66         for (uint32_t i = old_size; i < *size; i++)
67                 (*regs)[i] = c->undef;
68 }
69
70 static struct qreg
71 indirect_uniform_load(struct vc4_compile *c, nir_intrinsic_instr *intr)
72 {
73         struct qreg indirect_offset = ntq_get_src(c, intr->src[0], 0);
74         uint32_t offset = intr->const_index[0];
75         struct vc4_compiler_ubo_range *range = NULL;
76         unsigned i;
77         for (i = 0; i < c->num_uniform_ranges; i++) {
78                 range = &c->ubo_ranges[i];
79                 if (offset >= range->src_offset &&
80                     offset < range->src_offset + range->size) {
81                         break;
82                 }
83         }
84         /* The driver-location-based offset always has to be within a declared
85          * uniform range.
86          */
87         assert(range);
88         if (!range->used) {
89                 range->used = true;
90                 range->dst_offset = c->next_ubo_dst_offset;
91                 c->next_ubo_dst_offset += range->size;
92                 c->num_ubo_ranges++;
93         };
94
95         offset -= range->src_offset;
96
97         /* Adjust for where we stored the TGSI register base. */
98         indirect_offset = qir_ADD(c, indirect_offset,
99                                   qir_uniform_ui(c, (range->dst_offset +
100                                                      offset)));
101
102         /* Clamp to [0, array size).  Note that MIN/MAX are signed. */
103         indirect_offset = qir_MAX(c, indirect_offset, qir_uniform_ui(c, 0));
104         indirect_offset = qir_MIN(c, indirect_offset,
105                                   qir_uniform_ui(c, (range->dst_offset +
106                                                      range->size - 4)));
107
108         qir_TEX_DIRECT(c, indirect_offset, qir_uniform(c, QUNIFORM_UBO_ADDR, 0));
109         c->num_texture_samples++;
110         return qir_TEX_RESULT(c);
111 }
112
113 nir_ssa_def *vc4_nir_get_state_uniform(struct nir_builder *b,
114                                        enum quniform_contents contents)
115 {
116         nir_intrinsic_instr *intr =
117                 nir_intrinsic_instr_create(b->shader,
118                                            nir_intrinsic_load_uniform);
119         intr->const_index[0] = VC4_NIR_STATE_UNIFORM_OFFSET + contents;
120         intr->num_components = 1;
121         nir_ssa_dest_init(&intr->instr, &intr->dest, 1, NULL);
122         nir_builder_instr_insert(b, &intr->instr);
123         return &intr->dest.ssa;
124 }
125
126 nir_ssa_def *
127 vc4_nir_get_swizzled_channel(nir_builder *b, nir_ssa_def **srcs, int swiz)
128 {
129         switch (swiz) {
130         default:
131         case UTIL_FORMAT_SWIZZLE_NONE:
132                 fprintf(stderr, "warning: unknown swizzle\n");
133                 /* FALLTHROUGH */
134         case UTIL_FORMAT_SWIZZLE_0:
135                 return nir_imm_float(b, 0.0);
136         case UTIL_FORMAT_SWIZZLE_1:
137                 return nir_imm_float(b, 1.0);
138         case UTIL_FORMAT_SWIZZLE_X:
139         case UTIL_FORMAT_SWIZZLE_Y:
140         case UTIL_FORMAT_SWIZZLE_Z:
141         case UTIL_FORMAT_SWIZZLE_W:
142                 return srcs[swiz];
143         }
144 }
145
146 static struct qreg *
147 ntq_init_ssa_def(struct vc4_compile *c, nir_ssa_def *def)
148 {
149         struct qreg *qregs = ralloc_array(c->def_ht, struct qreg,
150                                           def->num_components);
151         _mesa_hash_table_insert(c->def_ht, def, qregs);
152         return qregs;
153 }
154
155 static struct qreg *
156 ntq_get_dest(struct vc4_compile *c, nir_dest *dest)
157 {
158         if (dest->is_ssa) {
159                 struct qreg *qregs = ntq_init_ssa_def(c, &dest->ssa);
160                 for (int i = 0; i < dest->ssa.num_components; i++)
161                         qregs[i] = c->undef;
162                 return qregs;
163         } else {
164                 nir_register *reg = dest->reg.reg;
165                 assert(dest->reg.base_offset == 0);
166                 assert(reg->num_array_elems == 0);
167                 struct hash_entry *entry =
168                         _mesa_hash_table_search(c->def_ht, reg);
169                 return entry->data;
170         }
171 }
172
173 static struct qreg
174 ntq_get_src(struct vc4_compile *c, nir_src src, int i)
175 {
176         struct hash_entry *entry;
177         if (src.is_ssa) {
178                 entry = _mesa_hash_table_search(c->def_ht, src.ssa);
179                 assert(i < src.ssa->num_components);
180         } else {
181                 nir_register *reg = src.reg.reg;
182                 entry = _mesa_hash_table_search(c->def_ht, reg);
183                 assert(reg->num_array_elems == 0);
184                 assert(src.reg.base_offset == 0);
185                 assert(i < reg->num_components);
186         }
187
188         struct qreg *qregs = entry->data;
189         return qregs[i];
190 }
191
192 static struct qreg
193 ntq_get_alu_src(struct vc4_compile *c, nir_alu_instr *instr,
194                 unsigned src)
195 {
196         assert(util_is_power_of_two(instr->dest.write_mask));
197         unsigned chan = ffs(instr->dest.write_mask) - 1;
198         struct qreg r = ntq_get_src(c, instr->src[src].src,
199                                     instr->src[src].swizzle[chan]);
200
201         assert(!instr->src[src].abs);
202         assert(!instr->src[src].negate);
203
204         return r;
205 };
206
207 static struct qreg
208 get_swizzled_channel(struct vc4_compile *c,
209                      struct qreg *srcs, int swiz)
210 {
211         switch (swiz) {
212         default:
213         case UTIL_FORMAT_SWIZZLE_NONE:
214                 fprintf(stderr, "warning: unknown swizzle\n");
215                 /* FALLTHROUGH */
216         case UTIL_FORMAT_SWIZZLE_0:
217                 return qir_uniform_f(c, 0.0);
218         case UTIL_FORMAT_SWIZZLE_1:
219                 return qir_uniform_f(c, 1.0);
220         case UTIL_FORMAT_SWIZZLE_X:
221         case UTIL_FORMAT_SWIZZLE_Y:
222         case UTIL_FORMAT_SWIZZLE_Z:
223         case UTIL_FORMAT_SWIZZLE_W:
224                 return srcs[swiz];
225         }
226 }
227
228 static inline struct qreg
229 qir_SAT(struct vc4_compile *c, struct qreg val)
230 {
231         return qir_FMAX(c,
232                         qir_FMIN(c, val, qir_uniform_f(c, 1.0)),
233                         qir_uniform_f(c, 0.0));
234 }
235
236 static struct qreg
237 ntq_rcp(struct vc4_compile *c, struct qreg x)
238 {
239         struct qreg r = qir_RCP(c, x);
240
241         /* Apply a Newton-Raphson step to improve the accuracy. */
242         r = qir_FMUL(c, r, qir_FSUB(c,
243                                     qir_uniform_f(c, 2.0),
244                                     qir_FMUL(c, x, r)));
245
246         return r;
247 }
248
249 static struct qreg
250 ntq_rsq(struct vc4_compile *c, struct qreg x)
251 {
252         struct qreg r = qir_RSQ(c, x);
253
254         /* Apply a Newton-Raphson step to improve the accuracy. */
255         r = qir_FMUL(c, r, qir_FSUB(c,
256                                     qir_uniform_f(c, 1.5),
257                                     qir_FMUL(c,
258                                              qir_uniform_f(c, 0.5),
259                                              qir_FMUL(c, x,
260                                                       qir_FMUL(c, r, r)))));
261
262         return r;
263 }
264
265 static struct qreg
266 qir_srgb_decode(struct vc4_compile *c, struct qreg srgb)
267 {
268         struct qreg low = qir_FMUL(c, srgb, qir_uniform_f(c, 1.0 / 12.92));
269         struct qreg high = qir_POW(c,
270                                    qir_FMUL(c,
271                                             qir_FADD(c,
272                                                      srgb,
273                                                      qir_uniform_f(c, 0.055)),
274                                             qir_uniform_f(c, 1.0 / 1.055)),
275                                    qir_uniform_f(c, 2.4));
276
277         qir_SF(c, qir_FSUB(c, srgb, qir_uniform_f(c, 0.04045)));
278         return qir_SEL_X_Y_NS(c, low, high);
279 }
280
281 static struct qreg
282 ntq_umul(struct vc4_compile *c, struct qreg src0, struct qreg src1)
283 {
284         struct qreg src0_hi = qir_SHR(c, src0,
285                                       qir_uniform_ui(c, 24));
286         struct qreg src1_hi = qir_SHR(c, src1,
287                                       qir_uniform_ui(c, 24));
288
289         struct qreg hilo = qir_MUL24(c, src0_hi, src1);
290         struct qreg lohi = qir_MUL24(c, src0, src1_hi);
291         struct qreg lolo = qir_MUL24(c, src0, src1);
292
293         return qir_ADD(c, lolo, qir_SHL(c,
294                                         qir_ADD(c, hilo, lohi),
295                                         qir_uniform_ui(c, 24)));
296 }
297
298 static void
299 ntq_emit_tex(struct vc4_compile *c, nir_tex_instr *instr)
300 {
301         struct qreg s, t, r, lod, proj, compare;
302         bool is_txb = false, is_txl = false, has_proj = false;
303         unsigned unit = instr->sampler_index;
304
305         for (unsigned i = 0; i < instr->num_srcs; i++) {
306                 switch (instr->src[i].src_type) {
307                 case nir_tex_src_coord:
308                         s = ntq_get_src(c, instr->src[i].src, 0);
309                         if (instr->sampler_dim == GLSL_SAMPLER_DIM_1D)
310                                 t = qir_uniform_f(c, 0.5);
311                         else
312                                 t = ntq_get_src(c, instr->src[i].src, 1);
313                         if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE)
314                                 r = ntq_get_src(c, instr->src[i].src, 2);
315                         break;
316                 case nir_tex_src_bias:
317                         lod = ntq_get_src(c, instr->src[i].src, 0);
318                         is_txb = true;
319                         break;
320                 case nir_tex_src_lod:
321                         lod = ntq_get_src(c, instr->src[i].src, 0);
322                         is_txl = true;
323                         break;
324                 case nir_tex_src_comparitor:
325                         compare = ntq_get_src(c, instr->src[i].src, 0);
326                         break;
327                 case nir_tex_src_projector:
328                         proj = qir_RCP(c, ntq_get_src(c, instr->src[i].src, 0));
329                         s = qir_FMUL(c, s, proj);
330                         t = qir_FMUL(c, t, proj);
331                         has_proj = true;
332                         break;
333                 default:
334                         unreachable("unknown texture source");
335                 }
336         }
337
338         struct qreg texture_u[] = {
339                 qir_uniform(c, QUNIFORM_TEXTURE_CONFIG_P0, unit),
340                 qir_uniform(c, QUNIFORM_TEXTURE_CONFIG_P1, unit),
341                 qir_uniform(c, QUNIFORM_CONSTANT, 0),
342                 qir_uniform(c, QUNIFORM_CONSTANT, 0),
343         };
344         uint32_t next_texture_u = 0;
345
346         /* There is no native support for GL texture rectangle coordinates, so
347          * we have to rescale from ([0, width], [0, height]) to ([0, 1], [0,
348          * 1]).
349          */
350         if (instr->sampler_dim == GLSL_SAMPLER_DIM_RECT) {
351                 s = qir_FMUL(c, s,
352                              qir_uniform(c, QUNIFORM_TEXRECT_SCALE_X, unit));
353                 t = qir_FMUL(c, t,
354                              qir_uniform(c, QUNIFORM_TEXRECT_SCALE_Y, unit));
355         }
356
357         if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE || is_txl) {
358                 texture_u[2] = qir_uniform(c, QUNIFORM_TEXTURE_CONFIG_P2,
359                                            unit | (is_txl << 16));
360         }
361
362         if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
363                 struct qreg ma = qir_FMAXABS(c, qir_FMAXABS(c, s, t), r);
364                 struct qreg rcp_ma = qir_RCP(c, ma);
365                 s = qir_FMUL(c, s, rcp_ma);
366                 t = qir_FMUL(c, t, rcp_ma);
367                 r = qir_FMUL(c, r, rcp_ma);
368
369                 qir_TEX_R(c, r, texture_u[next_texture_u++]);
370         } else if (c->key->tex[unit].wrap_s == PIPE_TEX_WRAP_CLAMP_TO_BORDER ||
371                    c->key->tex[unit].wrap_s == PIPE_TEX_WRAP_CLAMP ||
372                    c->key->tex[unit].wrap_t == PIPE_TEX_WRAP_CLAMP_TO_BORDER ||
373                    c->key->tex[unit].wrap_t == PIPE_TEX_WRAP_CLAMP) {
374                 qir_TEX_R(c, qir_uniform(c, QUNIFORM_TEXTURE_BORDER_COLOR, unit),
375                           texture_u[next_texture_u++]);
376         }
377
378         if (c->key->tex[unit].wrap_s == PIPE_TEX_WRAP_CLAMP) {
379                 s = qir_SAT(c, s);
380         }
381
382         if (c->key->tex[unit].wrap_t == PIPE_TEX_WRAP_CLAMP) {
383                 t = qir_SAT(c, t);
384         }
385
386         qir_TEX_T(c, t, texture_u[next_texture_u++]);
387
388         if (is_txl || is_txb)
389                 qir_TEX_B(c, lod, texture_u[next_texture_u++]);
390
391         qir_TEX_S(c, s, texture_u[next_texture_u++]);
392
393         c->num_texture_samples++;
394         struct qreg tex = qir_TEX_RESULT(c);
395
396         enum pipe_format format = c->key->tex[unit].format;
397
398         struct qreg unpacked[4];
399         if (util_format_is_depth_or_stencil(format)) {
400                 struct qreg depthf = qir_ITOF(c, qir_SHR(c, tex,
401                                                          qir_uniform_ui(c, 8)));
402                 struct qreg normalized = qir_FMUL(c, depthf,
403                                                   qir_uniform_f(c, 1.0f/0xffffff));
404
405                 struct qreg depth_output;
406
407                 struct qreg one = qir_uniform_f(c, 1.0f);
408                 if (c->key->tex[unit].compare_mode) {
409                         if (has_proj)
410                                 compare = qir_FMUL(c, compare, proj);
411
412                         switch (c->key->tex[unit].compare_func) {
413                         case PIPE_FUNC_NEVER:
414                                 depth_output = qir_uniform_f(c, 0.0f);
415                                 break;
416                         case PIPE_FUNC_ALWAYS:
417                                 depth_output = one;
418                                 break;
419                         case PIPE_FUNC_EQUAL:
420                                 qir_SF(c, qir_FSUB(c, compare, normalized));
421                                 depth_output = qir_SEL_X_0_ZS(c, one);
422                                 break;
423                         case PIPE_FUNC_NOTEQUAL:
424                                 qir_SF(c, qir_FSUB(c, compare, normalized));
425                                 depth_output = qir_SEL_X_0_ZC(c, one);
426                                 break;
427                         case PIPE_FUNC_GREATER:
428                                 qir_SF(c, qir_FSUB(c, compare, normalized));
429                                 depth_output = qir_SEL_X_0_NC(c, one);
430                                 break;
431                         case PIPE_FUNC_GEQUAL:
432                                 qir_SF(c, qir_FSUB(c, normalized, compare));
433                                 depth_output = qir_SEL_X_0_NS(c, one);
434                                 break;
435                         case PIPE_FUNC_LESS:
436                                 qir_SF(c, qir_FSUB(c, compare, normalized));
437                                 depth_output = qir_SEL_X_0_NS(c, one);
438                                 break;
439                         case PIPE_FUNC_LEQUAL:
440                                 qir_SF(c, qir_FSUB(c, normalized, compare));
441                                 depth_output = qir_SEL_X_0_NC(c, one);
442                                 break;
443                         }
444                 } else {
445                         depth_output = normalized;
446                 }
447
448                 for (int i = 0; i < 4; i++)
449                         unpacked[i] = depth_output;
450         } else {
451                 for (int i = 0; i < 4; i++)
452                         unpacked[i] = qir_UNPACK_8_F(c, tex, i);
453         }
454
455         const uint8_t *format_swiz = vc4_get_format_swizzle(format);
456         struct qreg texture_output[4];
457         for (int i = 0; i < 4; i++) {
458                 texture_output[i] = get_swizzled_channel(c, unpacked,
459                                                          format_swiz[i]);
460         }
461
462         if (util_format_is_srgb(format)) {
463                 for (int i = 0; i < 3; i++)
464                         texture_output[i] = qir_srgb_decode(c,
465                                                             texture_output[i]);
466         }
467
468         struct qreg *dest = ntq_get_dest(c, &instr->dest);
469         for (int i = 0; i < 4; i++) {
470                 dest[i] = get_swizzled_channel(c, texture_output,
471                                                c->key->tex[unit].swizzle[i]);
472         }
473 }
474
475 /**
476  * Computes x - floor(x), which is tricky because our FTOI truncates (rounds
477  * to zero).
478  */
479 static struct qreg
480 ntq_ffract(struct vc4_compile *c, struct qreg src)
481 {
482         struct qreg trunc = qir_ITOF(c, qir_FTOI(c, src));
483         struct qreg diff = qir_FSUB(c, src, trunc);
484         qir_SF(c, diff);
485         return qir_SEL_X_Y_NS(c,
486                               qir_FADD(c, diff, qir_uniform_f(c, 1.0)),
487                               diff);
488 }
489
490 /**
491  * Computes floor(x), which is tricky because our FTOI truncates (rounds to
492  * zero).
493  */
494 static struct qreg
495 ntq_ffloor(struct vc4_compile *c, struct qreg src)
496 {
497         struct qreg trunc = qir_ITOF(c, qir_FTOI(c, src));
498
499         /* This will be < 0 if we truncated and the truncation was of a value
500          * that was < 0 in the first place.
501          */
502         qir_SF(c, qir_FSUB(c, src, trunc));
503
504         return qir_SEL_X_Y_NS(c,
505                               qir_FSUB(c, trunc, qir_uniform_f(c, 1.0)),
506                               trunc);
507 }
508
509 /**
510  * Computes ceil(x), which is tricky because our FTOI truncates (rounds to
511  * zero).
512  */
513 static struct qreg
514 ntq_fceil(struct vc4_compile *c, struct qreg src)
515 {
516         struct qreg trunc = qir_ITOF(c, qir_FTOI(c, src));
517
518         /* This will be < 0 if we truncated and the truncation was of a value
519          * that was > 0 in the first place.
520          */
521         qir_SF(c, qir_FSUB(c, trunc, src));
522
523         return qir_SEL_X_Y_NS(c,
524                               qir_FADD(c, trunc, qir_uniform_f(c, 1.0)),
525                               trunc);
526 }
527
528 static struct qreg
529 ntq_fsin(struct vc4_compile *c, struct qreg src)
530 {
531         float coeff[] = {
532                 -2.0 * M_PI,
533                 pow(2.0 * M_PI, 3) / (3 * 2 * 1),
534                 -pow(2.0 * M_PI, 5) / (5 * 4 * 3 * 2 * 1),
535                 pow(2.0 * M_PI, 7) / (7 * 6 * 5 * 4 * 3 * 2 * 1),
536                 -pow(2.0 * M_PI, 9) / (9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1),
537         };
538
539         struct qreg scaled_x =
540                 qir_FMUL(c,
541                          src,
542                          qir_uniform_f(c, 1.0 / (M_PI * 2.0)));
543
544         struct qreg x = qir_FADD(c,
545                                  ntq_ffract(c, scaled_x),
546                                  qir_uniform_f(c, -0.5));
547         struct qreg x2 = qir_FMUL(c, x, x);
548         struct qreg sum = qir_FMUL(c, x, qir_uniform_f(c, coeff[0]));
549         for (int i = 1; i < ARRAY_SIZE(coeff); i++) {
550                 x = qir_FMUL(c, x, x2);
551                 sum = qir_FADD(c,
552                                sum,
553                                qir_FMUL(c,
554                                         x,
555                                         qir_uniform_f(c, coeff[i])));
556         }
557         return sum;
558 }
559
560 static struct qreg
561 ntq_fcos(struct vc4_compile *c, struct qreg src)
562 {
563         float coeff[] = {
564                 -1.0f,
565                 pow(2.0 * M_PI, 2) / (2 * 1),
566                 -pow(2.0 * M_PI, 4) / (4 * 3 * 2 * 1),
567                 pow(2.0 * M_PI, 6) / (6 * 5 * 4 * 3 * 2 * 1),
568                 -pow(2.0 * M_PI, 8) / (8 * 7 * 6 * 5 * 4 * 3 * 2 * 1),
569                 pow(2.0 * M_PI, 10) / (10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1),
570         };
571
572         struct qreg scaled_x =
573                 qir_FMUL(c, src,
574                          qir_uniform_f(c, 1.0f / (M_PI * 2.0f)));
575         struct qreg x_frac = qir_FADD(c,
576                                       ntq_ffract(c, scaled_x),
577                                       qir_uniform_f(c, -0.5));
578
579         struct qreg sum = qir_uniform_f(c, coeff[0]);
580         struct qreg x2 = qir_FMUL(c, x_frac, x_frac);
581         struct qreg x = x2; /* Current x^2, x^4, or x^6 */
582         for (int i = 1; i < ARRAY_SIZE(coeff); i++) {
583                 if (i != 1)
584                         x = qir_FMUL(c, x, x2);
585
586                 struct qreg mul = qir_FMUL(c,
587                                            x,
588                                            qir_uniform_f(c, coeff[i]));
589                 if (i == 0)
590                         sum = mul;
591                 else
592                         sum = qir_FADD(c, sum, mul);
593         }
594         return sum;
595 }
596
597 static struct qreg
598 ntq_fsign(struct vc4_compile *c, struct qreg src)
599 {
600         qir_SF(c, src);
601         return qir_SEL_X_Y_NC(c,
602                               qir_SEL_X_0_ZC(c, qir_uniform_f(c, 1.0)),
603                               qir_uniform_f(c, -1.0));
604 }
605
606 static struct qreg
607 get_channel_from_vpm(struct vc4_compile *c,
608                      struct qreg *vpm_reads,
609                      uint8_t swiz,
610                      const struct util_format_description *desc)
611 {
612         const struct util_format_channel_description *chan =
613                 &desc->channel[swiz];
614         struct qreg temp;
615
616         if (swiz > UTIL_FORMAT_SWIZZLE_W)
617                 return get_swizzled_channel(c, vpm_reads, swiz);
618         else if (chan->size == 32 &&
619                  chan->type == UTIL_FORMAT_TYPE_FLOAT) {
620                 return get_swizzled_channel(c, vpm_reads, swiz);
621         } else if (chan->size == 32 &&
622                    chan->type == UTIL_FORMAT_TYPE_SIGNED) {
623                 if (chan->normalized) {
624                         return qir_FMUL(c,
625                                         qir_ITOF(c, vpm_reads[swiz]),
626                                         qir_uniform_f(c,
627                                                       1.0 / 0x7fffffff));
628                 } else {
629                         return qir_ITOF(c, vpm_reads[swiz]);
630                 }
631         } else if (chan->size == 8 &&
632                    (chan->type == UTIL_FORMAT_TYPE_UNSIGNED ||
633                     chan->type == UTIL_FORMAT_TYPE_SIGNED)) {
634                 struct qreg vpm = vpm_reads[0];
635                 if (chan->type == UTIL_FORMAT_TYPE_SIGNED) {
636                         temp = qir_XOR(c, vpm, qir_uniform_ui(c, 0x80808080));
637                         if (chan->normalized) {
638                                 return qir_FSUB(c, qir_FMUL(c,
639                                                             qir_UNPACK_8_F(c, temp, swiz),
640                                                             qir_uniform_f(c, 2.0)),
641                                                 qir_uniform_f(c, 1.0));
642                         } else {
643                                 return qir_FADD(c,
644                                                 qir_ITOF(c,
645                                                          qir_UNPACK_8_I(c, temp,
646                                                                         swiz)),
647                                                 qir_uniform_f(c, -128.0));
648                         }
649                 } else {
650                         if (chan->normalized) {
651                                 return qir_UNPACK_8_F(c, vpm, swiz);
652                         } else {
653                                 return qir_ITOF(c, qir_UNPACK_8_I(c, vpm, swiz));
654                         }
655                 }
656         } else if (chan->size == 16 &&
657                    (chan->type == UTIL_FORMAT_TYPE_UNSIGNED ||
658                     chan->type == UTIL_FORMAT_TYPE_SIGNED)) {
659                 struct qreg vpm = vpm_reads[swiz / 2];
660
661                 /* Note that UNPACK_16F eats a half float, not ints, so we use
662                  * UNPACK_16_I for all of these.
663                  */
664                 if (chan->type == UTIL_FORMAT_TYPE_SIGNED) {
665                         temp = qir_ITOF(c, qir_UNPACK_16_I(c, vpm, swiz % 2));
666                         if (chan->normalized) {
667                                 return qir_FMUL(c, temp,
668                                                 qir_uniform_f(c, 1/32768.0f));
669                         } else {
670                                 return temp;
671                         }
672                 } else {
673                         /* UNPACK_16I sign-extends, so we have to emit ANDs. */
674                         temp = vpm;
675                         if (swiz == 1 || swiz == 3)
676                                 temp = qir_UNPACK_16_I(c, temp, 1);
677                         temp = qir_AND(c, temp, qir_uniform_ui(c, 0xffff));
678                         temp = qir_ITOF(c, temp);
679
680                         if (chan->normalized) {
681                                 return qir_FMUL(c, temp,
682                                                 qir_uniform_f(c, 1 / 65535.0));
683                         } else {
684                                 return temp;
685                         }
686                 }
687         } else {
688                 return c->undef;
689         }
690 }
691
692 static void
693 emit_vertex_input(struct vc4_compile *c, int attr)
694 {
695         enum pipe_format format = c->vs_key->attr_formats[attr];
696         uint32_t attr_size = util_format_get_blocksize(format);
697         struct qreg vpm_reads[4];
698
699         c->vattr_sizes[attr] = align(attr_size, 4);
700         for (int i = 0; i < align(attr_size, 4) / 4; i++) {
701                 struct qreg vpm = { QFILE_VPM, attr * 4 + i };
702                 vpm_reads[i] = qir_MOV(c, vpm);
703                 c->num_inputs++;
704         }
705
706         bool format_warned = false;
707         const struct util_format_description *desc =
708                 util_format_description(format);
709
710         for (int i = 0; i < 4; i++) {
711                 uint8_t swiz = desc->swizzle[i];
712                 struct qreg result = get_channel_from_vpm(c, vpm_reads,
713                                                           swiz, desc);
714
715                 if (result.file == QFILE_NULL) {
716                         if (!format_warned) {
717                                 fprintf(stderr,
718                                         "vtx element %d unsupported type: %s\n",
719                                         attr, util_format_name(format));
720                                 format_warned = true;
721                         }
722                         result = qir_uniform_f(c, 0.0);
723                 }
724                 c->inputs[attr * 4 + i] = result;
725         }
726 }
727
728 static void
729 emit_fragcoord_input(struct vc4_compile *c, int attr)
730 {
731         c->inputs[attr * 4 + 0] = qir_FRAG_X(c);
732         c->inputs[attr * 4 + 1] = qir_FRAG_Y(c);
733         c->inputs[attr * 4 + 2] =
734                 qir_FMUL(c,
735                          qir_ITOF(c, qir_FRAG_Z(c)),
736                          qir_uniform_f(c, 1.0 / 0xffffff));
737         c->inputs[attr * 4 + 3] = qir_RCP(c, qir_FRAG_W(c));
738 }
739
740 static struct qreg
741 emit_fragment_varying(struct vc4_compile *c, uint8_t semantic,
742                       uint8_t index, uint8_t swizzle)
743 {
744         uint32_t i = c->num_input_semantics++;
745         struct qreg vary = {
746                 QFILE_VARY,
747                 i
748         };
749
750         if (c->num_input_semantics >= c->input_semantics_array_size) {
751                 c->input_semantics_array_size =
752                         MAX2(4, c->input_semantics_array_size * 2);
753
754                 c->input_semantics = reralloc(c, c->input_semantics,
755                                               struct vc4_varying_semantic,
756                                               c->input_semantics_array_size);
757         }
758
759         c->input_semantics[i].semantic = semantic;
760         c->input_semantics[i].index = index;
761         c->input_semantics[i].swizzle = swizzle;
762
763         return qir_VARY_ADD_C(c, qir_FMUL(c, vary, qir_FRAG_W(c)));
764 }
765
766 static void
767 emit_fragment_input(struct vc4_compile *c, int attr,
768                     unsigned semantic_name, unsigned semantic_index)
769 {
770         for (int i = 0; i < 4; i++) {
771                 c->inputs[attr * 4 + i] =
772                         emit_fragment_varying(c,
773                                               semantic_name,
774                                               semantic_index,
775                                               i);
776                 c->num_inputs++;
777         }
778 }
779
780 static void
781 add_output(struct vc4_compile *c,
782            uint32_t decl_offset,
783            uint8_t semantic_name,
784            uint8_t semantic_index,
785            uint8_t semantic_swizzle)
786 {
787         uint32_t old_array_size = c->outputs_array_size;
788         resize_qreg_array(c, &c->outputs, &c->outputs_array_size,
789                           decl_offset + 1);
790
791         if (old_array_size != c->outputs_array_size) {
792                 c->output_semantics = reralloc(c,
793                                                c->output_semantics,
794                                                struct vc4_varying_semantic,
795                                                c->outputs_array_size);
796         }
797
798         c->output_semantics[decl_offset].semantic = semantic_name;
799         c->output_semantics[decl_offset].index = semantic_index;
800         c->output_semantics[decl_offset].swizzle = semantic_swizzle;
801 }
802
803 static void
804 declare_uniform_range(struct vc4_compile *c, uint32_t start, uint32_t size)
805 {
806         unsigned array_id = c->num_uniform_ranges++;
807         if (array_id >= c->ubo_ranges_array_size) {
808                 c->ubo_ranges_array_size = MAX2(c->ubo_ranges_array_size * 2,
809                                                 array_id + 1);
810                 c->ubo_ranges = reralloc(c, c->ubo_ranges,
811                                          struct vc4_compiler_ubo_range,
812                                          c->ubo_ranges_array_size);
813         }
814
815         c->ubo_ranges[array_id].dst_offset = 0;
816         c->ubo_ranges[array_id].src_offset = start;
817         c->ubo_ranges[array_id].size = size;
818         c->ubo_ranges[array_id].used = false;
819 }
820
821 static bool
822 ntq_src_is_only_ssa_def_user(nir_src *src)
823 {
824         if (!src->is_ssa)
825                 return false;
826
827         if (!list_empty(&src->ssa->if_uses))
828                 return false;
829
830         return (src->ssa->uses.next == &src->use_link &&
831                 src->ssa->uses.next->next == &src->ssa->uses);
832 }
833
834 /**
835  * In general, emits a nir_pack_unorm_4x8 as a series of MOVs with the pack
836  * bit set.
837  *
838  * However, as an optimization, it tries to find the instructions generating
839  * the sources to be packed and just emit the pack flag there, if possible.
840  */
841 static void
842 ntq_emit_pack_unorm_4x8(struct vc4_compile *c, nir_alu_instr *instr)
843 {
844         struct qreg result = qir_get_temp(c);
845         struct nir_alu_instr *vec4 = NULL;
846
847         /* If packing from a vec4 op (as expected), identify it so that we can
848          * peek back at what generated its sources.
849          */
850         if (instr->src[0].src.is_ssa &&
851             instr->src[0].src.ssa->parent_instr->type == nir_instr_type_alu &&
852             nir_instr_as_alu(instr->src[0].src.ssa->parent_instr)->op ==
853             nir_op_vec4) {
854                 vec4 = nir_instr_as_alu(instr->src[0].src.ssa->parent_instr);
855         }
856
857         for (int i = 0; i < 4; i++) {
858                 int swiz = instr->src[0].swizzle[i];
859                 struct qreg src;
860                 if (vec4) {
861                         src = ntq_get_src(c, vec4->src[swiz].src,
862                                           vec4->src[swiz].swizzle[0]);
863                 } else {
864                         src = ntq_get_src(c, instr->src[0].src, swiz);
865                 }
866
867                 if (vec4 &&
868                     ntq_src_is_only_ssa_def_user(&vec4->src[swiz].src) &&
869                     src.file == QFILE_TEMP &&
870                     c->defs[src.index] &&
871                     qir_is_mul(c->defs[src.index]) &&
872                     !c->defs[src.index]->dst.pack) {
873                         struct qinst *rewrite = c->defs[src.index];
874                         c->defs[src.index] = NULL;
875                         rewrite->dst = result;
876                         rewrite->dst.pack = QPU_PACK_MUL_8A + i;
877                         continue;
878                 }
879
880                 qir_PACK_8_F(c, result, src, i);
881         }
882
883         struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
884         *dest = result;
885 }
886
887 static void
888 ntq_emit_alu(struct vc4_compile *c, nir_alu_instr *instr)
889 {
890         /* Vectors are special in that they have non-scalarized writemasks,
891          * and just take the first swizzle channel for each argument in order
892          * into each writemask channel.
893          */
894         if (instr->op == nir_op_vec2 ||
895             instr->op == nir_op_vec3 ||
896             instr->op == nir_op_vec4) {
897                 struct qreg srcs[4];
898                 for (int i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
899                         srcs[i] = ntq_get_src(c, instr->src[i].src,
900                                               instr->src[i].swizzle[0]);
901                 struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
902                 for (int i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
903                         dest[i] = srcs[i];
904                 return;
905         }
906
907         if (instr->op == nir_op_pack_unorm_4x8) {
908                 ntq_emit_pack_unorm_4x8(c, instr);
909                 return;
910         }
911
912         if (instr->op == nir_op_unpack_unorm_4x8) {
913                 struct qreg src = ntq_get_src(c, instr->src[0].src,
914                                               instr->src[0].swizzle[0]);
915                 struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
916                 for (int i = 0; i < 4; i++) {
917                         if (instr->dest.write_mask & (1 << i))
918                                 dest[i] = qir_UNPACK_8_F(c, src, i);
919                 }
920                 return;
921         }
922
923         /* General case: We can just grab the one used channel per src. */
924         struct qreg src[nir_op_infos[instr->op].num_inputs];
925         for (int i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
926                 src[i] = ntq_get_alu_src(c, instr, i);
927         }
928
929         /* Pick the channel to store the output in. */
930         assert(!instr->dest.saturate);
931         struct qreg *dest = ntq_get_dest(c, &instr->dest.dest);
932         assert(util_is_power_of_two(instr->dest.write_mask));
933         dest += ffs(instr->dest.write_mask) - 1;
934
935         switch (instr->op) {
936         case nir_op_fmov:
937         case nir_op_imov:
938                 *dest = qir_MOV(c, src[0]);
939                 break;
940         case nir_op_fmul:
941                 *dest = qir_FMUL(c, src[0], src[1]);
942                 break;
943         case nir_op_fadd:
944                 *dest = qir_FADD(c, src[0], src[1]);
945                 break;
946         case nir_op_fsub:
947                 *dest = qir_FSUB(c, src[0], src[1]);
948                 break;
949         case nir_op_fmin:
950                 *dest = qir_FMIN(c, src[0], src[1]);
951                 break;
952         case nir_op_fmax:
953                 *dest = qir_FMAX(c, src[0], src[1]);
954                 break;
955
956         case nir_op_f2i:
957         case nir_op_f2u:
958                 *dest = qir_FTOI(c, src[0]);
959                 break;
960         case nir_op_i2f:
961         case nir_op_u2f:
962                 *dest = qir_ITOF(c, src[0]);
963                 break;
964         case nir_op_b2f:
965                 *dest = qir_AND(c, src[0], qir_uniform_f(c, 1.0));
966                 break;
967         case nir_op_b2i:
968                 *dest = qir_AND(c, src[0], qir_uniform_ui(c, 1));
969                 break;
970         case nir_op_i2b:
971         case nir_op_f2b:
972                 qir_SF(c, src[0]);
973                 *dest = qir_SEL_X_0_ZC(c, qir_uniform_ui(c, ~0));
974                 break;
975
976         case nir_op_iadd:
977                 *dest = qir_ADD(c, src[0], src[1]);
978                 break;
979         case nir_op_ushr:
980                 *dest = qir_SHR(c, src[0], src[1]);
981                 break;
982         case nir_op_isub:
983                 *dest = qir_SUB(c, src[0], src[1]);
984                 break;
985         case nir_op_ishr:
986                 *dest = qir_ASR(c, src[0], src[1]);
987                 break;
988         case nir_op_ishl:
989                 *dest = qir_SHL(c, src[0], src[1]);
990                 break;
991         case nir_op_imin:
992                 *dest = qir_MIN(c, src[0], src[1]);
993                 break;
994         case nir_op_imax:
995                 *dest = qir_MAX(c, src[0], src[1]);
996                 break;
997         case nir_op_iand:
998                 *dest = qir_AND(c, src[0], src[1]);
999                 break;
1000         case nir_op_ior:
1001                 *dest = qir_OR(c, src[0], src[1]);
1002                 break;
1003         case nir_op_ixor:
1004                 *dest = qir_XOR(c, src[0], src[1]);
1005                 break;
1006         case nir_op_inot:
1007                 *dest = qir_NOT(c, src[0]);
1008                 break;
1009
1010         case nir_op_imul:
1011                 *dest = ntq_umul(c, src[0], src[1]);
1012                 break;
1013
1014         case nir_op_seq:
1015                 qir_SF(c, qir_FSUB(c, src[0], src[1]));
1016                 *dest = qir_SEL_X_0_ZS(c, qir_uniform_f(c, 1.0));
1017                 break;
1018         case nir_op_sne:
1019                 qir_SF(c, qir_FSUB(c, src[0], src[1]));
1020                 *dest = qir_SEL_X_0_ZC(c, qir_uniform_f(c, 1.0));
1021                 break;
1022         case nir_op_sge:
1023                 qir_SF(c, qir_FSUB(c, src[0], src[1]));
1024                 *dest = qir_SEL_X_0_NC(c, qir_uniform_f(c, 1.0));
1025                 break;
1026         case nir_op_slt:
1027                 qir_SF(c, qir_FSUB(c, src[0], src[1]));
1028                 *dest = qir_SEL_X_0_NS(c, qir_uniform_f(c, 1.0));
1029                 break;
1030         case nir_op_feq:
1031                 qir_SF(c, qir_FSUB(c, src[0], src[1]));
1032                 *dest = qir_SEL_X_0_ZS(c, qir_uniform_ui(c, ~0));
1033                 break;
1034         case nir_op_fne:
1035                 qir_SF(c, qir_FSUB(c, src[0], src[1]));
1036                 *dest = qir_SEL_X_0_ZC(c, qir_uniform_ui(c, ~0));
1037                 break;
1038         case nir_op_fge:
1039                 qir_SF(c, qir_FSUB(c, src[0], src[1]));
1040                 *dest = qir_SEL_X_0_NC(c, qir_uniform_ui(c, ~0));
1041                 break;
1042         case nir_op_flt:
1043                 qir_SF(c, qir_FSUB(c, src[0], src[1]));
1044                 *dest = qir_SEL_X_0_NS(c, qir_uniform_ui(c, ~0));
1045                 break;
1046         case nir_op_ieq:
1047                 qir_SF(c, qir_SUB(c, src[0], src[1]));
1048                 *dest = qir_SEL_X_0_ZS(c, qir_uniform_ui(c, ~0));
1049                 break;
1050         case nir_op_ine:
1051                 qir_SF(c, qir_SUB(c, src[0], src[1]));
1052                 *dest = qir_SEL_X_0_ZC(c, qir_uniform_ui(c, ~0));
1053                 break;
1054         case nir_op_ige:
1055                 qir_SF(c, qir_SUB(c, src[0], src[1]));
1056                 *dest = qir_SEL_X_0_NC(c, qir_uniform_ui(c, ~0));
1057                 break;
1058         case nir_op_ilt:
1059                 qir_SF(c, qir_SUB(c, src[0], src[1]));
1060                 *dest = qir_SEL_X_0_NS(c, qir_uniform_ui(c, ~0));
1061                 break;
1062
1063         case nir_op_bcsel:
1064                 qir_SF(c, src[0]);
1065                 *dest = qir_SEL_X_Y_NS(c, src[1], src[2]);
1066                 break;
1067         case nir_op_fcsel:
1068                 qir_SF(c, src[0]);
1069                 *dest = qir_SEL_X_Y_ZC(c, src[1], src[2]);
1070                 break;
1071
1072         case nir_op_frcp:
1073                 *dest = ntq_rcp(c, src[0]);
1074                 break;
1075         case nir_op_frsq:
1076                 *dest = ntq_rsq(c, src[0]);
1077                 break;
1078         case nir_op_fexp2:
1079                 *dest = qir_EXP2(c, src[0]);
1080                 break;
1081         case nir_op_flog2:
1082                 *dest = qir_LOG2(c, src[0]);
1083                 break;
1084
1085         case nir_op_ftrunc:
1086                 *dest = qir_ITOF(c, qir_FTOI(c, src[0]));
1087                 break;
1088         case nir_op_fceil:
1089                 *dest = ntq_fceil(c, src[0]);
1090                 break;
1091         case nir_op_ffract:
1092                 *dest = ntq_ffract(c, src[0]);
1093                 break;
1094         case nir_op_ffloor:
1095                 *dest = ntq_ffloor(c, src[0]);
1096                 break;
1097
1098         case nir_op_fsin:
1099                 *dest = ntq_fsin(c, src[0]);
1100                 break;
1101         case nir_op_fcos:
1102                 *dest = ntq_fcos(c, src[0]);
1103                 break;
1104
1105         case nir_op_fsign:
1106                 *dest = ntq_fsign(c, src[0]);
1107                 break;
1108
1109         case nir_op_fabs:
1110                 *dest = qir_FMAXABS(c, src[0], src[0]);
1111                 break;
1112         case nir_op_iabs:
1113                 *dest = qir_MAX(c, src[0],
1114                                 qir_SUB(c, qir_uniform_ui(c, 0), src[0]));
1115                 break;
1116
1117         default:
1118                 fprintf(stderr, "unknown NIR ALU inst: ");
1119                 nir_print_instr(&instr->instr, stderr);
1120                 fprintf(stderr, "\n");
1121                 abort();
1122         }
1123 }
1124
1125 static void
1126 clip_distance_discard(struct vc4_compile *c)
1127 {
1128         for (int i = 0; i < PIPE_MAX_CLIP_PLANES; i++) {
1129                 if (!(c->key->ucp_enables & (1 << i)))
1130                         continue;
1131
1132                 struct qreg dist = emit_fragment_varying(c,
1133                                                          TGSI_SEMANTIC_CLIPDIST,
1134                                                          i,
1135                                                          TGSI_SWIZZLE_X);
1136
1137                 qir_SF(c, dist);
1138
1139                 if (c->discard.file == QFILE_NULL)
1140                         c->discard = qir_uniform_ui(c, 0);
1141
1142                 c->discard = qir_SEL_X_Y_NS(c, qir_uniform_ui(c, ~0),
1143                                             c->discard);
1144         }
1145 }
1146
1147 static void
1148 emit_frag_end(struct vc4_compile *c)
1149 {
1150         clip_distance_discard(c);
1151
1152         struct qreg color;
1153         if (c->output_color_index != -1) {
1154                 color = c->outputs[c->output_color_index];
1155         } else {
1156                 color = qir_uniform_ui(c, 0);
1157         }
1158
1159         if (c->discard.file != QFILE_NULL)
1160                 qir_TLB_DISCARD_SETUP(c, c->discard);
1161
1162         if (c->fs_key->stencil_enabled) {
1163                 qir_TLB_STENCIL_SETUP(c, qir_uniform(c, QUNIFORM_STENCIL, 0));
1164                 if (c->fs_key->stencil_twoside) {
1165                         qir_TLB_STENCIL_SETUP(c, qir_uniform(c, QUNIFORM_STENCIL, 1));
1166                 }
1167                 if (c->fs_key->stencil_full_writemasks) {
1168                         qir_TLB_STENCIL_SETUP(c, qir_uniform(c, QUNIFORM_STENCIL, 2));
1169                 }
1170         }
1171
1172         if (c->fs_key->depth_enabled) {
1173                 struct qreg z;
1174                 if (c->output_position_index != -1) {
1175                         z = qir_FTOI(c, qir_FMUL(c, c->outputs[c->output_position_index + 2],
1176                                                  qir_uniform_f(c, 0xffffff)));
1177                 } else {
1178                         z = qir_FRAG_Z(c);
1179                 }
1180                 qir_TLB_Z_WRITE(c, z);
1181         }
1182
1183         qir_TLB_COLOR_WRITE(c, color);
1184 }
1185
1186 static void
1187 emit_scaled_viewport_write(struct vc4_compile *c, struct qreg rcp_w)
1188 {
1189         struct qreg packed = qir_get_temp(c);
1190
1191         for (int i = 0; i < 2; i++) {
1192                 struct qreg scale =
1193                         qir_uniform(c, QUNIFORM_VIEWPORT_X_SCALE + i, 0);
1194
1195                 struct qreg packed_chan = packed;
1196                 packed_chan.pack = QPU_PACK_A_16A + i;
1197
1198                 qir_FTOI_dest(c, packed_chan,
1199                               qir_FMUL(c,
1200                                        qir_FMUL(c,
1201                                                 c->outputs[c->output_position_index + i],
1202                                                 scale),
1203                                        rcp_w));
1204         }
1205
1206         qir_VPM_WRITE(c, packed);
1207 }
1208
1209 static void
1210 emit_zs_write(struct vc4_compile *c, struct qreg rcp_w)
1211 {
1212         struct qreg zscale = qir_uniform(c, QUNIFORM_VIEWPORT_Z_SCALE, 0);
1213         struct qreg zoffset = qir_uniform(c, QUNIFORM_VIEWPORT_Z_OFFSET, 0);
1214
1215         qir_VPM_WRITE(c, qir_FADD(c, qir_FMUL(c, qir_FMUL(c,
1216                                                           c->outputs[c->output_position_index + 2],
1217                                                           zscale),
1218                                               rcp_w),
1219                                   zoffset));
1220 }
1221
1222 static void
1223 emit_rcp_wc_write(struct vc4_compile *c, struct qreg rcp_w)
1224 {
1225         qir_VPM_WRITE(c, rcp_w);
1226 }
1227
1228 static void
1229 emit_point_size_write(struct vc4_compile *c)
1230 {
1231         struct qreg point_size;
1232
1233         if (c->output_point_size_index != -1)
1234                 point_size = c->outputs[c->output_point_size_index + 3];
1235         else
1236                 point_size = qir_uniform_f(c, 1.0);
1237
1238         /* Workaround: HW-2726 PTB does not handle zero-size points (BCM2835,
1239          * BCM21553).
1240          */
1241         point_size = qir_FMAX(c, point_size, qir_uniform_f(c, .125));
1242
1243         qir_VPM_WRITE(c, point_size);
1244 }
1245
1246 /**
1247  * Emits a VPM read of the stub vertex attribute set up by vc4_draw.c.
1248  *
1249  * The simulator insists that there be at least one vertex attribute, so
1250  * vc4_draw.c will emit one if it wouldn't have otherwise.  The simulator also
1251  * insists that all vertex attributes loaded get read by the VS/CS, so we have
1252  * to consume it here.
1253  */
1254 static void
1255 emit_stub_vpm_read(struct vc4_compile *c)
1256 {
1257         if (c->num_inputs)
1258                 return;
1259
1260         c->vattr_sizes[0] = 4;
1261         struct qreg vpm = { QFILE_VPM, 0 };
1262         (void)qir_MOV(c, vpm);
1263         c->num_inputs++;
1264 }
1265
1266 static void
1267 emit_ucp_clipdistance(struct vc4_compile *c)
1268 {
1269         unsigned cv;
1270         if (c->output_clipvertex_index != -1)
1271                 cv = c->output_clipvertex_index;
1272         else if (c->output_position_index != -1)
1273                 cv = c->output_position_index;
1274         else
1275                 return;
1276
1277         for (int plane = 0; plane < PIPE_MAX_CLIP_PLANES; plane++) {
1278                 if (!(c->key->ucp_enables & (1 << plane)))
1279                         continue;
1280
1281                 /* Pick the next outputs[] that hasn't been written to, since
1282                  * there are no other program writes left to be processed at
1283                  * this point.  If something had been declared but not written
1284                  * (like a w component), we'll just smash over the top of it.
1285                  */
1286                 uint32_t output_index = c->num_outputs++;
1287                 add_output(c, output_index,
1288                            TGSI_SEMANTIC_CLIPDIST,
1289                            plane,
1290                            TGSI_SWIZZLE_X);
1291
1292
1293                 struct qreg dist = qir_uniform_f(c, 0.0);
1294                 for (int i = 0; i < 4; i++) {
1295                         struct qreg pos_chan = c->outputs[cv + i];
1296                         struct qreg ucp =
1297                                 qir_uniform(c, QUNIFORM_USER_CLIP_PLANE,
1298                                             plane * 4 + i);
1299                         dist = qir_FADD(c, dist, qir_FMUL(c, pos_chan, ucp));
1300                 }
1301
1302                 c->outputs[output_index] = dist;
1303         }
1304 }
1305
1306 static void
1307 emit_vert_end(struct vc4_compile *c,
1308               struct vc4_varying_semantic *fs_inputs,
1309               uint32_t num_fs_inputs)
1310 {
1311         struct qreg rcp_w = qir_RCP(c, c->outputs[c->output_position_index + 3]);
1312
1313         emit_stub_vpm_read(c);
1314         emit_ucp_clipdistance(c);
1315
1316         emit_scaled_viewport_write(c, rcp_w);
1317         emit_zs_write(c, rcp_w);
1318         emit_rcp_wc_write(c, rcp_w);
1319         if (c->vs_key->per_vertex_point_size)
1320                 emit_point_size_write(c);
1321
1322         for (int i = 0; i < num_fs_inputs; i++) {
1323                 struct vc4_varying_semantic *input = &fs_inputs[i];
1324                 int j;
1325
1326                 for (j = 0; j < c->num_outputs; j++) {
1327                         struct vc4_varying_semantic *output =
1328                                 &c->output_semantics[j];
1329
1330                         if (input->semantic == output->semantic &&
1331                             input->index == output->index &&
1332                             input->swizzle == output->swizzle) {
1333                                 qir_VPM_WRITE(c, c->outputs[j]);
1334                                 break;
1335                         }
1336                 }
1337                 /* Emit padding if we didn't find a declared VS output for
1338                  * this FS input.
1339                  */
1340                 if (j == c->num_outputs)
1341                         qir_VPM_WRITE(c, qir_uniform_f(c, 0.0));
1342         }
1343 }
1344
1345 static void
1346 emit_coord_end(struct vc4_compile *c)
1347 {
1348         struct qreg rcp_w = qir_RCP(c, c->outputs[c->output_position_index + 3]);
1349
1350         emit_stub_vpm_read(c);
1351
1352         for (int i = 0; i < 4; i++)
1353                 qir_VPM_WRITE(c, c->outputs[c->output_position_index + i]);
1354
1355         emit_scaled_viewport_write(c, rcp_w);
1356         emit_zs_write(c, rcp_w);
1357         emit_rcp_wc_write(c, rcp_w);
1358         if (c->vs_key->per_vertex_point_size)
1359                 emit_point_size_write(c);
1360 }
1361
1362 static void
1363 vc4_optimize_nir(struct nir_shader *s)
1364 {
1365         bool progress;
1366
1367         do {
1368                 progress = false;
1369
1370                 nir_lower_vars_to_ssa(s);
1371                 nir_lower_alu_to_scalar(s);
1372
1373                 progress = nir_copy_prop(s) || progress;
1374                 progress = nir_opt_dce(s) || progress;
1375                 progress = nir_opt_cse(s) || progress;
1376                 progress = nir_opt_peephole_select(s) || progress;
1377                 progress = nir_opt_algebraic(s) || progress;
1378                 progress = nir_opt_constant_folding(s) || progress;
1379                 progress = nir_opt_undef(s) || progress;
1380         } while (progress);
1381 }
1382
1383 static int
1384 driver_location_compare(const void *in_a, const void *in_b)
1385 {
1386         const nir_variable *const *a = in_a;
1387         const nir_variable *const *b = in_b;
1388
1389         return (*a)->data.driver_location - (*b)->data.driver_location;
1390 }
1391
1392 static void
1393 ntq_setup_inputs(struct vc4_compile *c)
1394 {
1395         unsigned num_entries = 0;
1396         foreach_list_typed(nir_variable, var, node, &c->s->inputs)
1397                 num_entries++;
1398
1399         nir_variable *vars[num_entries];
1400
1401         unsigned i = 0;
1402         foreach_list_typed(nir_variable, var, node, &c->s->inputs)
1403                 vars[i++] = var;
1404
1405         /* Sort the variables so that we emit the input setup in
1406          * driver_location order.  This is required for VPM reads, whose data
1407          * is fetched into the VPM in driver_location (TGSI register index)
1408          * order.
1409          */
1410         qsort(&vars, num_entries, sizeof(*vars), driver_location_compare);
1411
1412         for (unsigned i = 0; i < num_entries; i++) {
1413                 nir_variable *var = vars[i];
1414                 unsigned array_len = MAX2(glsl_get_length(var->type), 1);
1415                 /* XXX: map loc slots to semantics */
1416                 unsigned semantic_name = var->data.location;
1417                 unsigned semantic_index = var->data.index;
1418                 unsigned loc = var->data.driver_location;
1419
1420                 assert(array_len == 1);
1421                 (void)array_len;
1422                 resize_qreg_array(c, &c->inputs, &c->inputs_array_size,
1423                                   (loc + 1) * 4);
1424
1425                 if (c->stage == QSTAGE_FRAG) {
1426                         if (semantic_name == TGSI_SEMANTIC_POSITION) {
1427                                 emit_fragcoord_input(c, loc);
1428                         } else if (semantic_name == TGSI_SEMANTIC_FACE) {
1429                                 c->inputs[loc * 4 + 0] = qir_FRAG_REV_FLAG(c);
1430                         } else if (semantic_name == TGSI_SEMANTIC_GENERIC &&
1431                                    (c->fs_key->point_sprite_mask &
1432                                     (1 << semantic_index))) {
1433                                 c->inputs[loc * 4 + 0] = c->point_x;
1434                                 c->inputs[loc * 4 + 1] = c->point_y;
1435                         } else {
1436                                 emit_fragment_input(c, loc,
1437                                                     semantic_name,
1438                                                     semantic_index);
1439                         }
1440                 } else {
1441                         emit_vertex_input(c, loc);
1442                 }
1443         }
1444 }
1445
1446 static void
1447 ntq_setup_outputs(struct vc4_compile *c)
1448 {
1449         foreach_list_typed(nir_variable, var, node, &c->s->outputs) {
1450                 unsigned array_len = MAX2(glsl_get_length(var->type), 1);
1451                 /* XXX: map loc slots to semantics */
1452                 unsigned semantic_name = var->data.location;
1453                 unsigned semantic_index = var->data.index;
1454                 unsigned loc = var->data.driver_location * 4;
1455
1456                 assert(array_len == 1);
1457                 (void)array_len;
1458
1459                 /* NIR hack to pass through
1460                  * TGSI_PROPERTY_FS_COLOR0_WRITES_ALL_CBUFS */
1461                 if (semantic_name == TGSI_SEMANTIC_COLOR &&
1462                     semantic_index == -1)
1463                         semantic_index = 0;
1464
1465                 for (int i = 0; i < 4; i++) {
1466                         add_output(c,
1467                                    loc + i,
1468                                    semantic_name,
1469                                    semantic_index,
1470                                    i);
1471                 }
1472
1473                 switch (semantic_name) {
1474                 case TGSI_SEMANTIC_POSITION:
1475                         c->output_position_index = loc;
1476                         break;
1477                 case TGSI_SEMANTIC_CLIPVERTEX:
1478                         c->output_clipvertex_index = loc;
1479                         break;
1480                 case TGSI_SEMANTIC_COLOR:
1481                         c->output_color_index = loc;
1482                         break;
1483                 case TGSI_SEMANTIC_PSIZE:
1484                         c->output_point_size_index = loc;
1485                         break;
1486                 }
1487
1488         }
1489 }
1490
1491 static void
1492 ntq_setup_uniforms(struct vc4_compile *c)
1493 {
1494         foreach_list_typed(nir_variable, var, node, &c->s->uniforms) {
1495                 unsigned array_len = MAX2(glsl_get_length(var->type), 1);
1496                 unsigned array_elem_size = 4 * sizeof(float);
1497
1498                 declare_uniform_range(c, var->data.driver_location * array_elem_size,
1499                                       array_len * array_elem_size);
1500
1501         }
1502 }
1503
1504 /**
1505  * Sets up the mapping from nir_register to struct qreg *.
1506  *
1507  * Each nir_register gets a struct qreg per 32-bit component being stored.
1508  */
1509 static void
1510 ntq_setup_registers(struct vc4_compile *c, struct exec_list *list)
1511 {
1512         foreach_list_typed(nir_register, nir_reg, node, list) {
1513                 unsigned array_len = MAX2(nir_reg->num_array_elems, 1);
1514                 struct qreg *qregs = ralloc_array(c->def_ht, struct qreg,
1515                                                   array_len *
1516                                                   nir_reg->num_components);
1517
1518                 _mesa_hash_table_insert(c->def_ht, nir_reg, qregs);
1519
1520                 for (int i = 0; i < array_len * nir_reg->num_components; i++)
1521                         qregs[i] = qir_uniform_ui(c, 0);
1522         }
1523 }
1524
1525 static void
1526 ntq_emit_load_const(struct vc4_compile *c, nir_load_const_instr *instr)
1527 {
1528         struct qreg *qregs = ntq_init_ssa_def(c, &instr->def);
1529         for (int i = 0; i < instr->def.num_components; i++)
1530                 qregs[i] = qir_uniform_ui(c, instr->value.u[i]);
1531
1532         _mesa_hash_table_insert(c->def_ht, &instr->def, qregs);
1533 }
1534
1535 static void
1536 ntq_emit_ssa_undef(struct vc4_compile *c, nir_ssa_undef_instr *instr)
1537 {
1538         struct qreg *qregs = ntq_init_ssa_def(c, &instr->def);
1539
1540         /* QIR needs there to be *some* value, so pick 0 (same as for
1541          * ntq_setup_registers().
1542          */
1543         for (int i = 0; i < instr->def.num_components; i++)
1544                 qregs[i] = qir_uniform_ui(c, 0);
1545 }
1546
1547 static void
1548 ntq_emit_intrinsic(struct vc4_compile *c, nir_intrinsic_instr *instr)
1549 {
1550         const nir_intrinsic_info *info = &nir_intrinsic_infos[instr->intrinsic];
1551         struct qreg *dest = NULL;
1552
1553         if (info->has_dest) {
1554                 dest = ntq_get_dest(c, &instr->dest);
1555         }
1556
1557         switch (instr->intrinsic) {
1558         case nir_intrinsic_load_uniform:
1559                 assert(instr->num_components == 1);
1560                 if (instr->const_index[0] < VC4_NIR_STATE_UNIFORM_OFFSET) {
1561                         *dest = qir_uniform(c, QUNIFORM_UNIFORM,
1562                                             instr->const_index[0]);
1563                 } else {
1564                         *dest = qir_uniform(c, instr->const_index[0] -
1565                                             VC4_NIR_STATE_UNIFORM_OFFSET,
1566                                             0);
1567                 }
1568                 break;
1569
1570         case nir_intrinsic_load_uniform_indirect:
1571                 *dest = indirect_uniform_load(c, instr);
1572
1573                 break;
1574
1575         case nir_intrinsic_load_input:
1576                 assert(instr->num_components == 1);
1577                 if (instr->const_index[0] == VC4_NIR_TLB_COLOR_READ_INPUT) {
1578                         *dest = qir_TLB_COLOR_READ(c);
1579                 } else {
1580                         *dest = c->inputs[instr->const_index[0]];
1581                 }
1582                 break;
1583
1584         case nir_intrinsic_store_output:
1585                 assert(instr->num_components == 1);
1586                 c->outputs[instr->const_index[0]] =
1587                         qir_MOV(c, ntq_get_src(c, instr->src[0], 0));
1588                 c->num_outputs = MAX2(c->num_outputs, instr->const_index[0] + 1);
1589                 break;
1590
1591         case nir_intrinsic_discard:
1592                 c->discard = qir_uniform_ui(c, ~0);
1593                 break;
1594
1595         case nir_intrinsic_discard_if:
1596                 if (c->discard.file == QFILE_NULL)
1597                         c->discard = qir_uniform_ui(c, 0);
1598                 c->discard = qir_OR(c, c->discard,
1599                                     ntq_get_src(c, instr->src[0], 0));
1600                 break;
1601
1602         default:
1603                 fprintf(stderr, "Unknown intrinsic: ");
1604                 nir_print_instr(&instr->instr, stderr);
1605                 fprintf(stderr, "\n");
1606                 break;
1607         }
1608 }
1609
1610 static void
1611 ntq_emit_if(struct vc4_compile *c, nir_if *if_stmt)
1612 {
1613         fprintf(stderr, "general IF statements not handled.\n");
1614 }
1615
1616 static void
1617 ntq_emit_instr(struct vc4_compile *c, nir_instr *instr)
1618 {
1619         switch (instr->type) {
1620         case nir_instr_type_alu:
1621                 ntq_emit_alu(c, nir_instr_as_alu(instr));
1622                 break;
1623
1624         case nir_instr_type_intrinsic:
1625                 ntq_emit_intrinsic(c, nir_instr_as_intrinsic(instr));
1626                 break;
1627
1628         case nir_instr_type_load_const:
1629                 ntq_emit_load_const(c, nir_instr_as_load_const(instr));
1630                 break;
1631
1632         case nir_instr_type_ssa_undef:
1633                 ntq_emit_ssa_undef(c, nir_instr_as_ssa_undef(instr));
1634                 break;
1635
1636         case nir_instr_type_tex:
1637                 ntq_emit_tex(c, nir_instr_as_tex(instr));
1638                 break;
1639
1640         default:
1641                 fprintf(stderr, "Unknown NIR instr type: ");
1642                 nir_print_instr(instr, stderr);
1643                 fprintf(stderr, "\n");
1644                 abort();
1645         }
1646 }
1647
1648 static void
1649 ntq_emit_block(struct vc4_compile *c, nir_block *block)
1650 {
1651         nir_foreach_instr(block, instr) {
1652                 ntq_emit_instr(c, instr);
1653         }
1654 }
1655
1656 static void
1657 ntq_emit_cf_list(struct vc4_compile *c, struct exec_list *list)
1658 {
1659         foreach_list_typed(nir_cf_node, node, node, list) {
1660                 switch (node->type) {
1661                         /* case nir_cf_node_loop: */
1662                 case nir_cf_node_block:
1663                         ntq_emit_block(c, nir_cf_node_as_block(node));
1664                         break;
1665
1666                 case nir_cf_node_if:
1667                         ntq_emit_if(c, nir_cf_node_as_if(node));
1668                         break;
1669
1670                 default:
1671                         assert(0);
1672                 }
1673         }
1674 }
1675
1676 static void
1677 ntq_emit_impl(struct vc4_compile *c, nir_function_impl *impl)
1678 {
1679         ntq_setup_registers(c, &impl->registers);
1680         ntq_emit_cf_list(c, &impl->body);
1681 }
1682
1683 static void
1684 nir_to_qir(struct vc4_compile *c)
1685 {
1686         ntq_setup_inputs(c);
1687         ntq_setup_outputs(c);
1688         ntq_setup_uniforms(c);
1689         ntq_setup_registers(c, &c->s->registers);
1690
1691         /* Find the main function and emit the body. */
1692         nir_foreach_overload(c->s, overload) {
1693                 assert(strcmp(overload->function->name, "main") == 0);
1694                 assert(overload->impl);
1695                 ntq_emit_impl(c, overload->impl);
1696         }
1697 }
1698
1699 static const nir_shader_compiler_options nir_options = {
1700         .lower_ffma = true,
1701         .lower_flrp = true,
1702         .lower_fpow = true,
1703         .lower_fsat = true,
1704         .lower_fsqrt = true,
1705         .lower_negate = true,
1706 };
1707
1708 static bool
1709 count_nir_instrs_in_block(nir_block *block, void *state)
1710 {
1711         int *count = (int *) state;
1712         nir_foreach_instr(block, instr) {
1713                 *count = *count + 1;
1714         }
1715         return true;
1716 }
1717
1718 static int
1719 count_nir_instrs(nir_shader *nir)
1720 {
1721         int count = 0;
1722         nir_foreach_overload(nir, overload) {
1723                 if (!overload->impl)
1724                         continue;
1725                 nir_foreach_block(overload->impl, count_nir_instrs_in_block, &count);
1726         }
1727         return count;
1728 }
1729
1730 static struct vc4_compile *
1731 vc4_shader_ntq(struct vc4_context *vc4, enum qstage stage,
1732                        struct vc4_key *key)
1733 {
1734         struct vc4_compile *c = qir_compile_init();
1735
1736         c->stage = stage;
1737         c->shader_state = &key->shader_state->base;
1738         c->program_id = key->shader_state->program_id;
1739         c->variant_id = key->shader_state->compiled_variant_count++;
1740
1741         c->key = key;
1742         switch (stage) {
1743         case QSTAGE_FRAG:
1744                 c->fs_key = (struct vc4_fs_key *)key;
1745                 if (c->fs_key->is_points) {
1746                         c->point_x = emit_fragment_varying(c, ~0, ~0, 0);
1747                         c->point_y = emit_fragment_varying(c, ~0, ~0, 0);
1748                 } else if (c->fs_key->is_lines) {
1749                         c->line_x = emit_fragment_varying(c, ~0, ~0, 0);
1750                 }
1751                 break;
1752         case QSTAGE_VERT:
1753                 c->vs_key = (struct vc4_vs_key *)key;
1754                 break;
1755         case QSTAGE_COORD:
1756                 c->vs_key = (struct vc4_vs_key *)key;
1757                 break;
1758         }
1759
1760         const struct tgsi_token *tokens = key->shader_state->base.tokens;
1761         if (c->fs_key && c->fs_key->light_twoside) {
1762                 if (!key->shader_state->twoside_tokens) {
1763                         const struct tgsi_lowering_config lowering_config = {
1764                                 .color_two_side = true,
1765                         };
1766                         struct tgsi_shader_info info;
1767                         key->shader_state->twoside_tokens =
1768                                 tgsi_transform_lowering(&lowering_config,
1769                                                         key->shader_state->base.tokens,
1770                                                         &info);
1771
1772                         /* If no transformation occurred, then NULL is
1773                          * returned and we just use our original tokens.
1774                          */
1775                         if (!key->shader_state->twoside_tokens) {
1776                                 key->shader_state->twoside_tokens =
1777                                         key->shader_state->base.tokens;
1778                         }
1779                 }
1780                 tokens = key->shader_state->twoside_tokens;
1781         }
1782
1783         if (vc4_debug & VC4_DEBUG_TGSI) {
1784                 fprintf(stderr, "%s prog %d/%d TGSI:\n",
1785                         qir_get_stage_name(c->stage),
1786                         c->program_id, c->variant_id);
1787                 tgsi_dump(tokens, 0);
1788         }
1789
1790         c->s = tgsi_to_nir(tokens, &nir_options);
1791         nir_opt_global_to_local(c->s);
1792         nir_convert_to_ssa(c->s);
1793         if (stage == QSTAGE_FRAG)
1794                 vc4_nir_lower_blend(c);
1795         vc4_nir_lower_io(c);
1796         nir_lower_idiv(c->s);
1797         nir_lower_load_const_to_scalar(c->s);
1798
1799         vc4_optimize_nir(c->s);
1800
1801         nir_remove_dead_variables(c->s);
1802
1803         nir_convert_from_ssa(c->s, true);
1804
1805         if (vc4_debug & VC4_DEBUG_SHADERDB) {
1806                 fprintf(stderr, "SHADER-DB: %s prog %d/%d: %d NIR instructions\n",
1807                         qir_get_stage_name(c->stage),
1808                         c->program_id, c->variant_id,
1809                         count_nir_instrs(c->s));
1810         }
1811
1812         if (vc4_debug & VC4_DEBUG_NIR) {
1813                 fprintf(stderr, "%s prog %d/%d NIR:\n",
1814                         qir_get_stage_name(c->stage),
1815                         c->program_id, c->variant_id);
1816                 nir_print_shader(c->s, stderr);
1817         }
1818
1819         nir_to_qir(c);
1820
1821         switch (stage) {
1822         case QSTAGE_FRAG:
1823                 emit_frag_end(c);
1824                 break;
1825         case QSTAGE_VERT:
1826                 emit_vert_end(c,
1827                               vc4->prog.fs->input_semantics,
1828                               vc4->prog.fs->num_inputs);
1829                 break;
1830         case QSTAGE_COORD:
1831                 emit_coord_end(c);
1832                 break;
1833         }
1834
1835         if (vc4_debug & VC4_DEBUG_QIR) {
1836                 fprintf(stderr, "%s prog %d/%d pre-opt QIR:\n",
1837                         qir_get_stage_name(c->stage),
1838                         c->program_id, c->variant_id);
1839                 qir_dump(c);
1840         }
1841
1842         qir_optimize(c);
1843         qir_lower_uniforms(c);
1844
1845         if (vc4_debug & VC4_DEBUG_QIR) {
1846                 fprintf(stderr, "%s prog %d/%d QIR:\n",
1847                         qir_get_stage_name(c->stage),
1848                         c->program_id, c->variant_id);
1849                 qir_dump(c);
1850         }
1851         qir_reorder_uniforms(c);
1852         vc4_generate_code(vc4, c);
1853
1854         if (vc4_debug & VC4_DEBUG_SHADERDB) {
1855                 fprintf(stderr, "SHADER-DB: %s prog %d/%d: %d instructions\n",
1856                         qir_get_stage_name(c->stage),
1857                         c->program_id, c->variant_id,
1858                         c->qpu_inst_count);
1859                 fprintf(stderr, "SHADER-DB: %s prog %d/%d: %d uniforms\n",
1860                         qir_get_stage_name(c->stage),
1861                         c->program_id, c->variant_id,
1862                         c->num_uniforms);
1863         }
1864
1865         ralloc_free(c->s);
1866
1867         return c;
1868 }
1869
1870 static void *
1871 vc4_shader_state_create(struct pipe_context *pctx,
1872                         const struct pipe_shader_state *cso)
1873 {
1874         struct vc4_context *vc4 = vc4_context(pctx);
1875         struct vc4_uncompiled_shader *so = CALLOC_STRUCT(vc4_uncompiled_shader);
1876         if (!so)
1877                 return NULL;
1878
1879         so->base.tokens = tgsi_dup_tokens(cso->tokens);
1880         so->program_id = vc4->next_uncompiled_program_id++;
1881
1882         return so;
1883 }
1884
1885 static void
1886 copy_uniform_state_to_shader(struct vc4_compiled_shader *shader,
1887                              struct vc4_compile *c)
1888 {
1889         int count = c->num_uniforms;
1890         struct vc4_shader_uniform_info *uinfo = &shader->uniforms;
1891
1892         uinfo->count = count;
1893         uinfo->data = ralloc_array(shader, uint32_t, count);
1894         memcpy(uinfo->data, c->uniform_data,
1895                count * sizeof(*uinfo->data));
1896         uinfo->contents = ralloc_array(shader, enum quniform_contents, count);
1897         memcpy(uinfo->contents, c->uniform_contents,
1898                count * sizeof(*uinfo->contents));
1899         uinfo->num_texture_samples = c->num_texture_samples;
1900
1901         vc4_set_shader_uniform_dirty_flags(shader);
1902 }
1903
1904 static struct vc4_compiled_shader *
1905 vc4_get_compiled_shader(struct vc4_context *vc4, enum qstage stage,
1906                         struct vc4_key *key)
1907 {
1908         struct hash_table *ht;
1909         uint32_t key_size;
1910         if (stage == QSTAGE_FRAG) {
1911                 ht = vc4->fs_cache;
1912                 key_size = sizeof(struct vc4_fs_key);
1913         } else {
1914                 ht = vc4->vs_cache;
1915                 key_size = sizeof(struct vc4_vs_key);
1916         }
1917
1918         struct vc4_compiled_shader *shader;
1919         struct hash_entry *entry = _mesa_hash_table_search(ht, key);
1920         if (entry)
1921                 return entry->data;
1922
1923         struct vc4_compile *c = vc4_shader_ntq(vc4, stage, key);
1924         shader = rzalloc(NULL, struct vc4_compiled_shader);
1925
1926         shader->program_id = vc4->next_compiled_program_id++;
1927         if (stage == QSTAGE_FRAG) {
1928                 bool input_live[c->num_input_semantics];
1929
1930                 memset(input_live, 0, sizeof(input_live));
1931                 list_for_each_entry(struct qinst, inst, &c->instructions, link) {
1932                         for (int i = 0; i < qir_get_op_nsrc(inst->op); i++) {
1933                                 if (inst->src[i].file == QFILE_VARY)
1934                                         input_live[inst->src[i].index] = true;
1935                         }
1936                 }
1937
1938                 shader->input_semantics = ralloc_array(shader,
1939                                                        struct vc4_varying_semantic,
1940                                                        c->num_input_semantics);
1941
1942                 for (int i = 0; i < c->num_input_semantics; i++) {
1943                         struct vc4_varying_semantic *sem = &c->input_semantics[i];
1944
1945                         if (!input_live[i])
1946                                 continue;
1947
1948                         /* Skip non-VS-output inputs. */
1949                         if (sem->semantic == (uint8_t)~0)
1950                                 continue;
1951
1952                         if (sem->semantic == TGSI_SEMANTIC_COLOR ||
1953                             sem->semantic == TGSI_SEMANTIC_BCOLOR) {
1954                                 shader->color_inputs |= (1 << shader->num_inputs);
1955                         }
1956
1957                         shader->input_semantics[shader->num_inputs] = *sem;
1958                         shader->num_inputs++;
1959                 }
1960         } else {
1961                 shader->num_inputs = c->num_inputs;
1962
1963                 shader->vattr_offsets[0] = 0;
1964                 for (int i = 0; i < 8; i++) {
1965                         shader->vattr_offsets[i + 1] =
1966                                 shader->vattr_offsets[i] + c->vattr_sizes[i];
1967
1968                         if (c->vattr_sizes[i])
1969                                 shader->vattrs_live |= (1 << i);
1970                 }
1971         }
1972
1973         copy_uniform_state_to_shader(shader, c);
1974         shader->bo = vc4_bo_alloc_shader(vc4->screen, c->qpu_insts,
1975                                          c->qpu_inst_count * sizeof(uint64_t));
1976
1977         /* Copy the compiler UBO range state to the compiled shader, dropping
1978          * out arrays that were never referenced by an indirect load.
1979          *
1980          * (Note that QIR dead code elimination of an array access still
1981          * leaves that array alive, though)
1982          */
1983         if (c->num_ubo_ranges) {
1984                 shader->num_ubo_ranges = c->num_ubo_ranges;
1985                 shader->ubo_ranges = ralloc_array(shader, struct vc4_ubo_range,
1986                                                   c->num_ubo_ranges);
1987                 uint32_t j = 0;
1988                 for (int i = 0; i < c->num_uniform_ranges; i++) {
1989                         struct vc4_compiler_ubo_range *range =
1990                                 &c->ubo_ranges[i];
1991                         if (!range->used)
1992                                 continue;
1993
1994                         shader->ubo_ranges[j].dst_offset = range->dst_offset;
1995                         shader->ubo_ranges[j].src_offset = range->src_offset;
1996                         shader->ubo_ranges[j].size = range->size;
1997                         shader->ubo_size += c->ubo_ranges[i].size;
1998                         j++;
1999                 }
2000         }
2001         if (shader->ubo_size) {
2002                 if (vc4_debug & VC4_DEBUG_SHADERDB) {
2003                         fprintf(stderr, "SHADER-DB: %s prog %d/%d: %d UBO uniforms\n",
2004                                 qir_get_stage_name(c->stage),
2005                                 c->program_id, c->variant_id,
2006                                 shader->ubo_size / 4);
2007                 }
2008         }
2009
2010         qir_compile_destroy(c);
2011
2012         struct vc4_key *dup_key;
2013         dup_key = ralloc_size(shader, key_size);
2014         memcpy(dup_key, key, key_size);
2015         _mesa_hash_table_insert(ht, dup_key, shader);
2016
2017         return shader;
2018 }
2019
2020 static void
2021 vc4_setup_shared_key(struct vc4_context *vc4, struct vc4_key *key,
2022                      struct vc4_texture_stateobj *texstate)
2023 {
2024         for (int i = 0; i < texstate->num_textures; i++) {
2025                 struct pipe_sampler_view *sampler = texstate->textures[i];
2026                 struct pipe_sampler_state *sampler_state =
2027                         texstate->samplers[i];
2028
2029                 if (sampler) {
2030                         key->tex[i].format = sampler->format;
2031                         key->tex[i].swizzle[0] = sampler->swizzle_r;
2032                         key->tex[i].swizzle[1] = sampler->swizzle_g;
2033                         key->tex[i].swizzle[2] = sampler->swizzle_b;
2034                         key->tex[i].swizzle[3] = sampler->swizzle_a;
2035                         key->tex[i].compare_mode = sampler_state->compare_mode;
2036                         key->tex[i].compare_func = sampler_state->compare_func;
2037                         key->tex[i].wrap_s = sampler_state->wrap_s;
2038                         key->tex[i].wrap_t = sampler_state->wrap_t;
2039                 }
2040         }
2041
2042         key->ucp_enables = vc4->rasterizer->base.clip_plane_enable;
2043 }
2044
2045 static void
2046 vc4_update_compiled_fs(struct vc4_context *vc4, uint8_t prim_mode)
2047 {
2048         struct vc4_fs_key local_key;
2049         struct vc4_fs_key *key = &local_key;
2050
2051         if (!(vc4->dirty & (VC4_DIRTY_PRIM_MODE |
2052                             VC4_DIRTY_BLEND |
2053                             VC4_DIRTY_FRAMEBUFFER |
2054                             VC4_DIRTY_ZSA |
2055                             VC4_DIRTY_RASTERIZER |
2056                             VC4_DIRTY_FRAGTEX |
2057                             VC4_DIRTY_TEXSTATE |
2058                             VC4_DIRTY_UNCOMPILED_FS))) {
2059                 return;
2060         }
2061
2062         memset(key, 0, sizeof(*key));
2063         vc4_setup_shared_key(vc4, &key->base, &vc4->fragtex);
2064         key->base.shader_state = vc4->prog.bind_fs;
2065         key->is_points = (prim_mode == PIPE_PRIM_POINTS);
2066         key->is_lines = (prim_mode >= PIPE_PRIM_LINES &&
2067                          prim_mode <= PIPE_PRIM_LINE_STRIP);
2068         key->blend = vc4->blend->rt[0];
2069         if (vc4->blend->logicop_enable) {
2070                 key->logicop_func = vc4->blend->logicop_func;
2071         } else {
2072                 key->logicop_func = PIPE_LOGICOP_COPY;
2073         }
2074         if (vc4->framebuffer.cbufs[0])
2075                 key->color_format = vc4->framebuffer.cbufs[0]->format;
2076
2077         key->stencil_enabled = vc4->zsa->stencil_uniforms[0] != 0;
2078         key->stencil_twoside = vc4->zsa->stencil_uniforms[1] != 0;
2079         key->stencil_full_writemasks = vc4->zsa->stencil_uniforms[2] != 0;
2080         key->depth_enabled = (vc4->zsa->base.depth.enabled ||
2081                               key->stencil_enabled);
2082         if (vc4->zsa->base.alpha.enabled) {
2083                 key->alpha_test = true;
2084                 key->alpha_test_func = vc4->zsa->base.alpha.func;
2085         }
2086
2087         if (key->is_points) {
2088                 key->point_sprite_mask =
2089                         vc4->rasterizer->base.sprite_coord_enable;
2090                 key->point_coord_upper_left =
2091                         (vc4->rasterizer->base.sprite_coord_mode ==
2092                          PIPE_SPRITE_COORD_UPPER_LEFT);
2093         }
2094
2095         key->light_twoside = vc4->rasterizer->base.light_twoside;
2096
2097         struct vc4_compiled_shader *old_fs = vc4->prog.fs;
2098         vc4->prog.fs = vc4_get_compiled_shader(vc4, QSTAGE_FRAG, &key->base);
2099         if (vc4->prog.fs == old_fs)
2100                 return;
2101
2102         vc4->dirty |= VC4_DIRTY_COMPILED_FS;
2103         if (vc4->rasterizer->base.flatshade &&
2104             old_fs && vc4->prog.fs->color_inputs != old_fs->color_inputs) {
2105                 vc4->dirty |= VC4_DIRTY_FLAT_SHADE_FLAGS;
2106         }
2107 }
2108
2109 static void
2110 vc4_update_compiled_vs(struct vc4_context *vc4, uint8_t prim_mode)
2111 {
2112         struct vc4_vs_key local_key;
2113         struct vc4_vs_key *key = &local_key;
2114
2115         if (!(vc4->dirty & (VC4_DIRTY_PRIM_MODE |
2116                             VC4_DIRTY_RASTERIZER |
2117                             VC4_DIRTY_VERTTEX |
2118                             VC4_DIRTY_TEXSTATE |
2119                             VC4_DIRTY_VTXSTATE |
2120                             VC4_DIRTY_UNCOMPILED_VS |
2121                             VC4_DIRTY_COMPILED_FS))) {
2122                 return;
2123         }
2124
2125         memset(key, 0, sizeof(*key));
2126         vc4_setup_shared_key(vc4, &key->base, &vc4->verttex);
2127         key->base.shader_state = vc4->prog.bind_vs;
2128         key->compiled_fs_id = vc4->prog.fs->program_id;
2129
2130         for (int i = 0; i < ARRAY_SIZE(key->attr_formats); i++)
2131                 key->attr_formats[i] = vc4->vtx->pipe[i].src_format;
2132
2133         key->per_vertex_point_size =
2134                 (prim_mode == PIPE_PRIM_POINTS &&
2135                  vc4->rasterizer->base.point_size_per_vertex);
2136
2137         struct vc4_compiled_shader *vs =
2138                 vc4_get_compiled_shader(vc4, QSTAGE_VERT, &key->base);
2139         if (vs != vc4->prog.vs) {
2140                 vc4->prog.vs = vs;
2141                 vc4->dirty |= VC4_DIRTY_COMPILED_VS;
2142         }
2143
2144         key->is_coord = true;
2145         struct vc4_compiled_shader *cs =
2146                 vc4_get_compiled_shader(vc4, QSTAGE_COORD, &key->base);
2147         if (cs != vc4->prog.cs) {
2148                 vc4->prog.cs = cs;
2149                 vc4->dirty |= VC4_DIRTY_COMPILED_CS;
2150         }
2151 }
2152
2153 void
2154 vc4_update_compiled_shaders(struct vc4_context *vc4, uint8_t prim_mode)
2155 {
2156         vc4_update_compiled_fs(vc4, prim_mode);
2157         vc4_update_compiled_vs(vc4, prim_mode);
2158 }
2159
2160 static uint32_t
2161 fs_cache_hash(const void *key)
2162 {
2163         return _mesa_hash_data(key, sizeof(struct vc4_fs_key));
2164 }
2165
2166 static uint32_t
2167 vs_cache_hash(const void *key)
2168 {
2169         return _mesa_hash_data(key, sizeof(struct vc4_vs_key));
2170 }
2171
2172 static bool
2173 fs_cache_compare(const void *key1, const void *key2)
2174 {
2175         return memcmp(key1, key2, sizeof(struct vc4_fs_key)) == 0;
2176 }
2177
2178 static bool
2179 vs_cache_compare(const void *key1, const void *key2)
2180 {
2181         return memcmp(key1, key2, sizeof(struct vc4_vs_key)) == 0;
2182 }
2183
2184 static void
2185 delete_from_cache_if_matches(struct hash_table *ht,
2186                              struct hash_entry *entry,
2187                              struct vc4_uncompiled_shader *so)
2188 {
2189         const struct vc4_key *key = entry->key;
2190
2191         if (key->shader_state == so) {
2192                 struct vc4_compiled_shader *shader = entry->data;
2193                 _mesa_hash_table_remove(ht, entry);
2194                 vc4_bo_unreference(&shader->bo);
2195                 ralloc_free(shader);
2196         }
2197 }
2198
2199 static void
2200 vc4_shader_state_delete(struct pipe_context *pctx, void *hwcso)
2201 {
2202         struct vc4_context *vc4 = vc4_context(pctx);
2203         struct vc4_uncompiled_shader *so = hwcso;
2204
2205         struct hash_entry *entry;
2206         hash_table_foreach(vc4->fs_cache, entry)
2207                 delete_from_cache_if_matches(vc4->fs_cache, entry, so);
2208         hash_table_foreach(vc4->vs_cache, entry)
2209                 delete_from_cache_if_matches(vc4->vs_cache, entry, so);
2210
2211         if (so->twoside_tokens != so->base.tokens)
2212                 free((void *)so->twoside_tokens);
2213         free((void *)so->base.tokens);
2214         free(so);
2215 }
2216
2217 static void
2218 vc4_fp_state_bind(struct pipe_context *pctx, void *hwcso)
2219 {
2220         struct vc4_context *vc4 = vc4_context(pctx);
2221         vc4->prog.bind_fs = hwcso;
2222         vc4->dirty |= VC4_DIRTY_UNCOMPILED_FS;
2223 }
2224
2225 static void
2226 vc4_vp_state_bind(struct pipe_context *pctx, void *hwcso)
2227 {
2228         struct vc4_context *vc4 = vc4_context(pctx);
2229         vc4->prog.bind_vs = hwcso;
2230         vc4->dirty |= VC4_DIRTY_UNCOMPILED_VS;
2231 }
2232
2233 void
2234 vc4_program_init(struct pipe_context *pctx)
2235 {
2236         struct vc4_context *vc4 = vc4_context(pctx);
2237
2238         pctx->create_vs_state = vc4_shader_state_create;
2239         pctx->delete_vs_state = vc4_shader_state_delete;
2240
2241         pctx->create_fs_state = vc4_shader_state_create;
2242         pctx->delete_fs_state = vc4_shader_state_delete;
2243
2244         pctx->bind_fs_state = vc4_fp_state_bind;
2245         pctx->bind_vs_state = vc4_vp_state_bind;
2246
2247         vc4->fs_cache = _mesa_hash_table_create(pctx, fs_cache_hash,
2248                                                 fs_cache_compare);
2249         vc4->vs_cache = _mesa_hash_table_create(pctx, vs_cache_hash,
2250                                                 vs_cache_compare);
2251 }
2252
2253 void
2254 vc4_program_fini(struct pipe_context *pctx)
2255 {
2256         struct vc4_context *vc4 = vc4_context(pctx);
2257
2258         struct hash_entry *entry;
2259         hash_table_foreach(vc4->fs_cache, entry) {
2260                 struct vc4_compiled_shader *shader = entry->data;
2261                 vc4_bo_unreference(&shader->bo);
2262                 ralloc_free(shader);
2263                 _mesa_hash_table_remove(vc4->fs_cache, entry);
2264         }
2265
2266         hash_table_foreach(vc4->vs_cache, entry) {
2267                 struct vc4_compiled_shader *shader = entry->data;
2268                 vc4_bo_unreference(&shader->bo);
2269                 ralloc_free(shader);
2270                 _mesa_hash_table_remove(vc4->vs_cache, entry);
2271         }
2272 }