st/glsl: move nir linking loop to new function st_link_nir()
[mesa.git] / src / mesa / state_tracker / st_glsl_to_nir.cpp
1 /*
2 * Copyright © 2015 Red Hat
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 * SOFTWARE.
22 */
23
24 #include "st_nir.h"
25
26 #include "pipe/p_defines.h"
27 #include "pipe/p_screen.h"
28 #include "pipe/p_context.h"
29
30 #include "program/program.h"
31 #include "program/prog_statevars.h"
32 #include "program/prog_parameter.h"
33 #include "program/ir_to_mesa.h"
34 #include "main/mtypes.h"
35 #include "main/errors.h"
36 #include "main/shaderapi.h"
37 #include "main/uniforms.h"
38
39 #include "st_context.h"
40 #include "st_program.h"
41
42 #include "compiler/nir/nir.h"
43 #include "compiler/glsl_types.h"
44 #include "compiler/glsl/glsl_to_nir.h"
45 #include "compiler/glsl/ir.h"
46 #include "compiler/glsl/string_to_uint_map.h"
47
48
49 static int
50 type_size(const struct glsl_type *type)
51 {
52 return type->count_attribute_slots(false);
53 }
54
55 /* Depending on PIPE_CAP_TGSI_TEXCOORD (st->needs_texcoord_semantic) we
56 * may need to fix up varying slots so the glsl->nir path is aligned
57 * with the anything->tgsi->nir path.
58 */
59 static void
60 st_nir_fixup_varying_slots(struct st_context *st, struct exec_list *var_list)
61 {
62 if (st->needs_texcoord_semantic)
63 return;
64
65 nir_foreach_variable(var, var_list) {
66 if (var->data.location >= VARYING_SLOT_VAR0) {
67 var->data.location += 9;
68 } else if ((var->data.location >= VARYING_SLOT_TEX0) &&
69 (var->data.location <= VARYING_SLOT_TEX7)) {
70 var->data.location += VARYING_SLOT_VAR0 - VARYING_SLOT_TEX0;
71 }
72 }
73 }
74
75 /* input location assignment for VS inputs must be handled specially, so
76 * that it is aligned w/ st's vbo state.
77 * (This isn't the case with, for ex, FS inputs, which only need to agree
78 * on varying-slot w/ the VS outputs)
79 */
80 static void
81 st_nir_assign_vs_in_locations(struct gl_program *prog, nir_shader *nir)
82 {
83 unsigned attr, num_inputs = 0;
84 unsigned input_to_index[VERT_ATTRIB_MAX] = {0};
85
86 /* TODO de-duplicate w/ similar code in st_translate_vertex_program()? */
87 for (attr = 0; attr < VERT_ATTRIB_MAX; attr++) {
88 if ((prog->info.inputs_read & BITFIELD64_BIT(attr)) != 0) {
89 input_to_index[attr] = num_inputs;
90 num_inputs++;
91 if ((prog->info.double_inputs_read & BITFIELD64_BIT(attr)) != 0) {
92 /* add placeholder for second part of a double attribute */
93 num_inputs++;
94 }
95 } else {
96 input_to_index[attr] = ~0;
97 }
98 }
99
100 /* bit of a hack, mirroring st_translate_vertex_program */
101 input_to_index[VERT_ATTRIB_EDGEFLAG] = num_inputs;
102
103 nir->num_inputs = 0;
104 nir_foreach_variable_safe(var, &nir->inputs) {
105 attr = var->data.location;
106 assert(attr < ARRAY_SIZE(input_to_index));
107
108 if (input_to_index[attr] != ~0u) {
109 var->data.driver_location = input_to_index[attr];
110 nir->num_inputs++;
111 } else {
112 /* Move unused input variables to the globals list (with no
113 * initialization), to avoid confusing drivers looking through the
114 * inputs array and expecting to find inputs with a driver_location
115 * set.
116 */
117 exec_node_remove(&var->node);
118 var->data.mode = nir_var_global;
119 exec_list_push_tail(&nir->globals, &var->node);
120 }
121 }
122 }
123
124 static void
125 st_nir_assign_var_locations(struct exec_list *var_list, unsigned *size)
126 {
127 unsigned location = 0;
128 unsigned assigned_locations[VARYING_SLOT_MAX];
129 uint64_t processed_locs = 0;
130
131 nir_foreach_variable(var, var_list) {
132 /* Because component packing allows varyings to share the same location
133 * we may have already have processed this location.
134 */
135 if (var->data.location >= VARYING_SLOT_VAR0 &&
136 processed_locs & ((uint64_t)1 << var->data.location)) {
137 var->data.driver_location = assigned_locations[var->data.location];
138 *size += type_size(var->type);
139 continue;
140 }
141
142 assigned_locations[var->data.location] = location;
143 var->data.driver_location = location;
144 location += type_size(var->type);
145
146 processed_locs |= ((uint64_t)1 << var->data.location);
147 }
148
149 *size += location;
150 }
151
152 static int
153 st_nir_lookup_parameter_index(const struct gl_program_parameter_list *params,
154 const char *name)
155 {
156 int loc = _mesa_lookup_parameter_index(params, name);
157
158 /* is there a better way to do this? If we have something like:
159 *
160 * struct S {
161 * float f;
162 * vec4 v;
163 * };
164 * uniform S color;
165 *
166 * Then what we get in prog->Parameters looks like:
167 *
168 * 0: Name=color.f, Type=6, DataType=1406, Size=1
169 * 1: Name=color.v, Type=6, DataType=8b52, Size=4
170 *
171 * So the name doesn't match up and _mesa_lookup_parameter_index()
172 * fails. In this case just find the first matching "color.*"..
173 *
174 * Note for arrays you could end up w/ color[n].f, for example.
175 *
176 * glsl_to_tgsi works slightly differently in this regard. It is
177 * emitting something more low level, so it just translates the
178 * params list 1:1 to CONST[] regs. Going from GLSL IR to TGSI,
179 * it just calculates the additional offset of struct field members
180 * in glsl_to_tgsi_visitor::visit(ir_dereference_record *ir) or
181 * glsl_to_tgsi_visitor::visit(ir_dereference_array *ir). It never
182 * needs to work backwards to get base var loc from the param-list
183 * which already has them separated out.
184 */
185 if (loc < 0) {
186 int namelen = strlen(name);
187 for (unsigned i = 0; i < params->NumParameters; i++) {
188 struct gl_program_parameter *p = &params->Parameters[i];
189 if ((strncmp(p->Name, name, namelen) == 0) &&
190 ((p->Name[namelen] == '.') || (p->Name[namelen] == '['))) {
191 loc = i;
192 break;
193 }
194 }
195 }
196
197 return loc;
198 }
199
200 static void
201 st_nir_assign_uniform_locations(struct gl_program *prog,
202 struct gl_shader_program *shader_program,
203 struct exec_list *uniform_list, unsigned *size)
204 {
205 int max = 0;
206 int shaderidx = 0;
207 int imageidx = 0;
208
209 nir_foreach_variable(uniform, uniform_list) {
210 int loc;
211
212 /*
213 * UBO's have their own address spaces, so don't count them towards the
214 * number of global uniforms
215 */
216 if ((uniform->data.mode == nir_var_uniform || uniform->data.mode == nir_var_shader_storage) &&
217 uniform->interface_type != NULL)
218 continue;
219
220 if (uniform->type->is_sampler() || uniform->type->is_image()) {
221 unsigned val = 0;
222 bool found = shader_program->UniformHash->get(val, uniform->name);
223 if (uniform->type->is_sampler())
224 loc = shaderidx++;
225 else
226 loc = imageidx++;
227 assert(found);
228 (void) found; /* silence unused var warning */
229 /* this ensure that nir_lower_samplers looks at the correct
230 * shader_program->UniformStorage[location]:
231 */
232 uniform->data.location = val;
233 } else if (strncmp(uniform->name, "gl_", 3) == 0) {
234 const gl_state_index *const stateTokens = (gl_state_index *)uniform->state_slots[0].tokens;
235 /* This state reference has already been setup by ir_to_mesa, but we'll
236 * get the same index back here.
237 */
238 loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
239 } else {
240 loc = st_nir_lookup_parameter_index(prog->Parameters, uniform->name);
241 }
242
243 uniform->data.driver_location = loc;
244
245 max = MAX2(max, loc + type_size(uniform->type));
246 }
247 *size = max;
248 }
249
250 extern "C" {
251
252 /* First half of converting glsl_to_nir.. this leaves things in a pre-
253 * nir_lower_io state, so that shader variants can more easily insert/
254 * replace variables, etc.
255 */
256 nir_shader *
257 st_glsl_to_nir(struct st_context *st, struct gl_program *prog,
258 struct gl_shader_program *shader_program,
259 gl_shader_stage stage)
260 {
261 struct pipe_screen *pscreen = st->pipe->screen;
262 enum pipe_shader_type ptarget = pipe_shader_type_from_mesa(stage);
263 const nir_shader_compiler_options *options;
264 nir_shader *nir;
265
266 assert(pscreen->get_compiler_options); /* drivers using NIR must implement this */
267
268 options = (const nir_shader_compiler_options *)
269 pscreen->get_compiler_options(pscreen, PIPE_SHADER_IR_NIR, ptarget);
270 assert(options);
271
272 if (prog->nir)
273 return prog->nir;
274
275 nir = glsl_to_nir(shader_program, stage, options);
276
277 /* Make a pass over the IR to add state references for any built-in
278 * uniforms that are used. This has to be done now (during linking).
279 * Code generation doesn't happen until the first time this shader is
280 * used for rendering. Waiting until then to generate the parameters is
281 * too late. At that point, the values for the built-in uniforms won't
282 * get sent to the shader.
283 */
284 nir_foreach_variable(var, &nir->uniforms) {
285 if (strncmp(var->name, "gl_", 3) == 0) {
286 const nir_state_slot *const slots = var->state_slots;
287 assert(var->state_slots != NULL);
288
289 for (unsigned int i = 0; i < var->num_state_slots; i++) {
290 _mesa_add_state_reference(prog->Parameters,
291 (gl_state_index *)slots[i].tokens);
292 }
293 }
294 }
295
296 /* Avoid reallocation of the program parameter list, because the uniform
297 * storage is only associated with the original parameter list.
298 * This should be enough for Bitmap and DrawPixels constants.
299 */
300 _mesa_reserve_parameter_storage(prog->Parameters, 8);
301
302 /* This has to be done last. Any operation the can cause
303 * prog->ParameterValues to get reallocated (e.g., anything that adds a
304 * program constant) has to happen before creating this linkage.
305 */
306 _mesa_associate_uniform_storage(st->ctx, shader_program, prog, true);
307
308 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
309 nir_shader_get_entrypoint(nir),
310 true, true);
311 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
312 NIR_PASS_V(nir, nir_split_var_copies);
313 NIR_PASS_V(nir, nir_lower_var_copies);
314
315 /* fragment shaders may need : */
316 if (stage == MESA_SHADER_FRAGMENT) {
317 static const gl_state_index wposTransformState[STATE_LENGTH] = {
318 STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
319 };
320 nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
321 struct pipe_screen *pscreen = st->pipe->screen;
322
323 memcpy(wpos_options.state_tokens, wposTransformState,
324 sizeof(wpos_options.state_tokens));
325 wpos_options.fs_coord_origin_upper_left =
326 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT);
327 wpos_options.fs_coord_origin_lower_left =
328 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
329 wpos_options.fs_coord_pixel_center_integer =
330 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
331 wpos_options.fs_coord_pixel_center_half_integer =
332 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER);
333
334 if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
335 nir_validate_shader(nir);
336 _mesa_add_state_reference(prog->Parameters, wposTransformState);
337 }
338 }
339
340 NIR_PASS_V(nir, nir_lower_system_values);
341
342 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
343 prog->info = nir->info;
344
345 st_set_prog_affected_state_flags(prog);
346
347 NIR_PASS_V(nir, st_nir_lower_builtin);
348 NIR_PASS_V(nir, nir_lower_atomics, shader_program);
349
350 if (st->ctx->_Shader->Flags & GLSL_DUMP) {
351 _mesa_log("\n");
352 _mesa_log("NIR IR for linked %s program %d:\n",
353 _mesa_shader_stage_to_string(stage),
354 shader_program->Name);
355 nir_print_shader(nir, _mesa_get_log_file());
356 _mesa_log("\n\n");
357 }
358
359 prog->nir = nir;
360
361 return nir;
362 }
363
364 /* TODO any better helper somewhere to sort a list? */
365
366 static void
367 insert_sorted(struct exec_list *var_list, nir_variable *new_var)
368 {
369 nir_foreach_variable(var, var_list) {
370 if (var->data.location > new_var->data.location) {
371 exec_node_insert_node_before(&var->node, &new_var->node);
372 return;
373 }
374 }
375 exec_list_push_tail(var_list, &new_var->node);
376 }
377
378 static void
379 sort_varyings(struct exec_list *var_list)
380 {
381 struct exec_list new_list;
382 exec_list_make_empty(&new_list);
383 nir_foreach_variable_safe(var, var_list) {
384 exec_node_remove(&var->node);
385 insert_sorted(&new_list, var);
386 }
387 exec_list_move_nodes_to(&new_list, var_list);
388 }
389
390 /* Second half of preparing nir from glsl, which happens after shader
391 * variant lowering.
392 */
393 void
394 st_finalize_nir(struct st_context *st, struct gl_program *prog,
395 struct gl_shader_program *shader_program, nir_shader *nir)
396 {
397 struct pipe_screen *screen = st->pipe->screen;
398
399 NIR_PASS_V(nir, nir_split_var_copies);
400 NIR_PASS_V(nir, nir_lower_var_copies);
401 NIR_PASS_V(nir, nir_lower_io_types);
402
403 if (nir->info.stage == MESA_SHADER_VERTEX) {
404 /* Needs special handling so drvloc matches the vbo state: */
405 st_nir_assign_vs_in_locations(prog, nir);
406 /* Re-lower global vars, to deal with any dead VS inputs. */
407 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
408
409 sort_varyings(&nir->outputs);
410 st_nir_assign_var_locations(&nir->outputs,
411 &nir->num_outputs);
412 st_nir_fixup_varying_slots(st, &nir->outputs);
413 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
414 sort_varyings(&nir->inputs);
415 st_nir_assign_var_locations(&nir->inputs,
416 &nir->num_inputs);
417 st_nir_fixup_varying_slots(st, &nir->inputs);
418 st_nir_assign_var_locations(&nir->outputs,
419 &nir->num_outputs);
420 } else if (nir->info.stage == MESA_SHADER_COMPUTE) {
421 /* TODO? */
422 } else {
423 unreachable("invalid shader type for tgsi bypass\n");
424 }
425
426 NIR_PASS_V(nir, nir_lower_atomics_to_ssbo,
427 st->ctx->Const.Program[nir->info.stage].MaxAtomicBuffers);
428
429 st_nir_assign_uniform_locations(prog, shader_program,
430 &nir->uniforms, &nir->num_uniforms);
431
432 if (screen->get_param(screen, PIPE_CAP_NIR_SAMPLERS_AS_DEREF))
433 NIR_PASS_V(nir, nir_lower_samplers_as_deref, shader_program);
434 else
435 NIR_PASS_V(nir, nir_lower_samplers, shader_program);
436 }
437
438 struct gl_program *
439 st_nir_get_mesa_program(struct gl_context *ctx,
440 struct gl_shader_program *shader_program,
441 struct gl_linked_shader *shader)
442 {
443 struct st_context *st = st_context(ctx);
444 struct gl_program *prog;
445
446 validate_ir_tree(shader->ir);
447
448 prog = shader->Program;
449
450 prog->Parameters = _mesa_new_parameter_list();
451
452 _mesa_copy_linked_program_data(shader_program, shader);
453 _mesa_generate_parameters_list_for_uniforms(ctx, shader_program, shader,
454 prog->Parameters);
455
456 if (ctx->_Shader->Flags & GLSL_DUMP) {
457 _mesa_log("\n");
458 _mesa_log("GLSL IR for linked %s program %d:\n",
459 _mesa_shader_stage_to_string(shader->Stage),
460 shader_program->Name);
461 _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
462 _mesa_log("\n\n");
463 }
464
465 prog->ExternalSamplersUsed = gl_external_samplers(prog);
466 _mesa_update_shader_textures_used(shader_program, prog);
467
468 struct st_vertex_program *stvp;
469 struct st_common_program *stp;
470 struct st_fragment_program *stfp;
471 struct st_compute_program *stcp;
472
473 nir_shader *nir = st_glsl_to_nir(st, prog, shader_program, shader->Stage);
474
475 switch (shader->Stage) {
476 case MESA_SHADER_VERTEX:
477 stvp = (struct st_vertex_program *)prog;
478 stvp->shader_program = shader_program;
479 stvp->tgsi.type = PIPE_SHADER_IR_NIR;
480 stvp->tgsi.ir.nir = nir;
481 break;
482 case MESA_SHADER_GEOMETRY:
483 case MESA_SHADER_TESS_CTRL:
484 case MESA_SHADER_TESS_EVAL:
485 stp = (struct st_common_program *)prog;
486 stp->shader_program = shader_program;
487 stp->tgsi.type = PIPE_SHADER_IR_NIR;
488 stp->tgsi.ir.nir = nir;
489 break;
490 case MESA_SHADER_FRAGMENT:
491 stfp = (struct st_fragment_program *)prog;
492 stfp->shader_program = shader_program;
493 stfp->tgsi.type = PIPE_SHADER_IR_NIR;
494 stfp->tgsi.ir.nir = nir;
495 break;
496 case MESA_SHADER_COMPUTE:
497 stcp = (struct st_compute_program *)prog;
498 stcp->shader_program = shader_program;
499 stcp->tgsi.ir_type = PIPE_SHADER_IR_NIR;
500 stcp->tgsi.prog = nir_shader_clone(NULL, nir);
501 break;
502 default:
503 assert(!"should not be reached");
504 return NULL;
505 }
506
507
508 return prog;
509 }
510
511 bool
512 st_link_nir(struct gl_context *ctx,
513 struct gl_shader_program *shader_program)
514 {
515 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
516 struct gl_linked_shader *shader = shader_program->_LinkedShaders[i];
517 if (shader == NULL)
518 continue;
519
520 struct gl_program *linked_prog =
521 st_nir_get_mesa_program(ctx, shader_program, shader);
522
523 if (linked_prog) {
524 if (!ctx->Driver.ProgramStringNotify(ctx,
525 _mesa_shader_stage_to_program(i),
526 linked_prog)) {
527 _mesa_reference_program(ctx, &shader->Program, NULL);
528 return false;
529 }
530 }
531 }
532
533 return true;
534 }
535
536 } /* extern "C" */