mesa/st: compute support for glsl_to_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 #include "util/string_to_uint_map.h"
39
40 #include "st_context.h"
41 #include "st_program.h"
42 #include "st_glsl_types.h"
43
44 #include "compiler/nir/nir.h"
45 #include "compiler/glsl_types.h"
46 #include "compiler/glsl/glsl_to_nir.h"
47 #include "compiler/glsl/ir.h"
48
49
50 /* Depending on PIPE_CAP_TGSI_TEXCOORD (st->needs_texcoord_semantic) we
51 * may need to fix up varying slots so the glsl->nir path is aligned
52 * with the anything->tgsi->nir path.
53 */
54 static void
55 st_nir_fixup_varying_slots(struct st_context *st, struct exec_list *var_list)
56 {
57 if (st->needs_texcoord_semantic)
58 return;
59
60 nir_foreach_variable(var, var_list) {
61 if (var->data.location >= VARYING_SLOT_VAR0) {
62 var->data.location += 9;
63 } else if ((var->data.location >= VARYING_SLOT_TEX0) &&
64 (var->data.location <= VARYING_SLOT_TEX7)) {
65 var->data.location += VARYING_SLOT_VAR0 - VARYING_SLOT_TEX0;
66 }
67 }
68 }
69
70 /* input location assignment for VS inputs must be handled specially, so
71 * that it is aligned w/ st's vbo state.
72 * (This isn't the case with, for ex, FS inputs, which only need to agree
73 * on varying-slot w/ the VS outputs)
74 */
75 static void
76 st_nir_assign_vs_in_locations(struct gl_program *prog, nir_shader *nir)
77 {
78 unsigned attr, num_inputs = 0;
79 unsigned input_to_index[VERT_ATTRIB_MAX] = {0};
80
81 /* TODO de-duplicate w/ similar code in st_translate_vertex_program()? */
82 for (attr = 0; attr < VERT_ATTRIB_MAX; attr++) {
83 if ((prog->info.inputs_read & BITFIELD64_BIT(attr)) != 0) {
84 input_to_index[attr] = num_inputs;
85 num_inputs++;
86 if ((prog->info.double_inputs_read & BITFIELD64_BIT(attr)) != 0) {
87 /* add placeholder for second part of a double attribute */
88 num_inputs++;
89 }
90 } else {
91 input_to_index[attr] = ~0;
92 }
93 }
94
95 nir->num_inputs = 0;
96 nir_foreach_variable_safe(var, &nir->inputs) {
97 attr = var->data.location;
98 assert(attr < ARRAY_SIZE(input_to_index));
99
100 if (input_to_index[attr] != ~0u) {
101 var->data.driver_location = input_to_index[attr];
102 nir->num_inputs++;
103 } else {
104 /* Move unused input variables to the globals list (with no
105 * initialization), to avoid confusing drivers looking through the
106 * inputs array and expecting to find inputs with a driver_location
107 * set.
108 */
109 exec_node_remove(&var->node);
110 var->data.mode = nir_var_global;
111 exec_list_push_tail(&nir->globals, &var->node);
112 }
113 }
114 }
115
116 static int
117 st_nir_lookup_parameter_index(const struct gl_program_parameter_list *params,
118 const char *name)
119 {
120 int loc = _mesa_lookup_parameter_index(params, name);
121
122 /* is there a better way to do this? If we have something like:
123 *
124 * struct S {
125 * float f;
126 * vec4 v;
127 * };
128 * uniform S color;
129 *
130 * Then what we get in prog->Parameters looks like:
131 *
132 * 0: Name=color.f, Type=6, DataType=1406, Size=1
133 * 1: Name=color.v, Type=6, DataType=8b52, Size=4
134 *
135 * So the name doesn't match up and _mesa_lookup_parameter_index()
136 * fails. In this case just find the first matching "color.*"..
137 *
138 * Note for arrays you could end up w/ color[n].f, for example.
139 *
140 * glsl_to_tgsi works slightly differently in this regard. It is
141 * emitting something more low level, so it just translates the
142 * params list 1:1 to CONST[] regs. Going from GLSL IR to TGSI,
143 * it just calculates the additional offset of struct field members
144 * in glsl_to_tgsi_visitor::visit(ir_dereference_record *ir) or
145 * glsl_to_tgsi_visitor::visit(ir_dereference_array *ir). It never
146 * needs to work backwards to get base var loc from the param-list
147 * which already has them separated out.
148 */
149 if (loc < 0) {
150 int namelen = strlen(name);
151 for (unsigned i = 0; i < params->NumParameters; i++) {
152 struct gl_program_parameter *p = &params->Parameters[i];
153 if ((strncmp(p->Name, name, namelen) == 0) &&
154 ((p->Name[namelen] == '.') || (p->Name[namelen] == '['))) {
155 loc = i;
156 break;
157 }
158 }
159 }
160
161 return loc;
162 }
163
164 static void
165 st_nir_assign_uniform_locations(struct gl_program *prog,
166 struct gl_shader_program *shader_program,
167 struct exec_list *uniform_list, unsigned *size)
168 {
169 int max = 0;
170 int shaderidx = 0;
171
172 nir_foreach_variable(uniform, uniform_list) {
173 int loc;
174
175 /*
176 * UBO's have their own address spaces, so don't count them towards the
177 * number of global uniforms
178 */
179 if ((uniform->data.mode == nir_var_uniform || uniform->data.mode == nir_var_shader_storage) &&
180 uniform->interface_type != NULL)
181 continue;
182
183 if (uniform->type->is_sampler()) {
184 unsigned val = 0;
185 bool found = shader_program->UniformHash->get(val, uniform->name);
186 loc = shaderidx++;
187 assert(found);
188 (void) found; /* silence unused var warning */
189 /* this ensure that nir_lower_samplers looks at the correct
190 * shader_program->UniformStorage[location]:
191 */
192 uniform->data.location = val;
193 } else if (strncmp(uniform->name, "gl_", 3) == 0) {
194 const gl_state_index *const stateTokens = (gl_state_index *)uniform->state_slots[0].tokens;
195 /* This state reference has already been setup by ir_to_mesa, but we'll
196 * get the same index back here.
197 */
198 loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
199 } else {
200 loc = st_nir_lookup_parameter_index(prog->Parameters, uniform->name);
201 }
202
203 uniform->data.driver_location = loc;
204
205 max = MAX2(max, loc + st_glsl_type_size(uniform->type));
206 }
207 *size = max;
208 }
209
210 extern "C" {
211
212 /* First half of converting glsl_to_nir.. this leaves things in a pre-
213 * nir_lower_io state, so that shader variants can more easily insert/
214 * replace variables, etc.
215 */
216 nir_shader *
217 st_glsl_to_nir(struct st_context *st, struct gl_program *prog,
218 struct gl_shader_program *shader_program,
219 gl_shader_stage stage)
220 {
221 struct pipe_screen *pscreen = st->pipe->screen;
222 enum pipe_shader_type ptarget = st_shader_stage_to_ptarget(stage);
223 const nir_shader_compiler_options *options;
224 nir_shader *nir;
225
226 assert(pscreen->get_compiler_options); /* drivers using NIR must implement this */
227
228 options = (const nir_shader_compiler_options *)
229 pscreen->get_compiler_options(pscreen, PIPE_SHADER_IR_NIR, ptarget);
230 assert(options);
231
232 if (prog->nir)
233 return prog->nir;
234
235 nir = glsl_to_nir(shader_program, stage, options);
236 prog->nir = nir;
237
238 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
239 nir_shader_get_entrypoint(nir),
240 true, true);
241 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
242 NIR_PASS_V(nir, nir_split_var_copies);
243 NIR_PASS_V(nir, nir_lower_var_copies);
244 NIR_PASS_V(nir, st_nir_lower_builtin);
245 NIR_PASS_V(nir, nir_lower_atomics, shader_program);
246
247 /* fragment shaders may need : */
248 if (stage == MESA_SHADER_FRAGMENT) {
249 static const gl_state_index wposTransformState[STATE_LENGTH] = {
250 STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
251 };
252 nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
253 struct pipe_screen *pscreen = st->pipe->screen;
254
255 memcpy(wpos_options.state_tokens, wposTransformState,
256 sizeof(wpos_options.state_tokens));
257 wpos_options.fs_coord_origin_upper_left =
258 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT);
259 wpos_options.fs_coord_origin_lower_left =
260 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
261 wpos_options.fs_coord_pixel_center_integer =
262 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
263 wpos_options.fs_coord_pixel_center_half_integer =
264 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER);
265
266 if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
267 nir_validate_shader(nir);
268 _mesa_add_state_reference(prog->Parameters, wposTransformState);
269 }
270 }
271
272 if (st->ctx->_Shader->Flags & GLSL_DUMP) {
273 _mesa_log("\n");
274 _mesa_log("NIR IR for linked %s program %d:\n",
275 _mesa_shader_stage_to_string(stage),
276 shader_program->Name);
277 nir_print_shader(nir, _mesa_get_log_file());
278 _mesa_log("\n\n");
279 }
280
281 return nir;
282 }
283
284 /* TODO any better helper somewhere to sort a list? */
285
286 static void
287 insert_sorted(struct exec_list *var_list, nir_variable *new_var)
288 {
289 nir_foreach_variable(var, var_list) {
290 if (var->data.location > new_var->data.location) {
291 exec_node_insert_node_before(&var->node, &new_var->node);
292 return;
293 }
294 }
295 exec_list_push_tail(var_list, &new_var->node);
296 }
297
298 static void
299 sort_varyings(struct exec_list *var_list)
300 {
301 struct exec_list new_list;
302 exec_list_make_empty(&new_list);
303 nir_foreach_variable_safe(var, var_list) {
304 exec_node_remove(&var->node);
305 insert_sorted(&new_list, var);
306 }
307 exec_list_move_nodes_to(&new_list, var_list);
308 }
309
310 /* Second half of preparing nir from glsl, which happens after shader
311 * variant lowering.
312 */
313 void
314 st_finalize_nir(struct st_context *st, struct gl_program *prog, nir_shader *nir)
315 {
316 NIR_PASS_V(nir, nir_split_var_copies);
317 NIR_PASS_V(nir, nir_lower_var_copies);
318 NIR_PASS_V(nir, nir_lower_io_types);
319
320 if (nir->stage == MESA_SHADER_VERTEX) {
321 /* Needs special handling so drvloc matches the vbo state: */
322 st_nir_assign_vs_in_locations(prog, nir);
323 /* Re-lower global vars, to deal with any dead VS inputs. */
324 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
325
326 sort_varyings(&nir->outputs);
327 nir_assign_var_locations(&nir->outputs,
328 &nir->num_outputs,
329 st_glsl_type_size);
330 st_nir_fixup_varying_slots(st, &nir->outputs);
331 } else if (nir->stage == MESA_SHADER_FRAGMENT) {
332 sort_varyings(&nir->inputs);
333 nir_assign_var_locations(&nir->inputs,
334 &nir->num_inputs,
335 st_glsl_type_size);
336 st_nir_fixup_varying_slots(st, &nir->inputs);
337 nir_assign_var_locations(&nir->outputs,
338 &nir->num_outputs,
339 st_glsl_type_size);
340 } else if (nir->stage == MESA_SHADER_COMPUTE) {
341 /* TODO? */
342 } else {
343 unreachable("invalid shader type for tgsi bypass\n");
344 }
345
346 struct gl_shader_program *shader_program;
347 switch (nir->stage) {
348 case MESA_SHADER_VERTEX:
349 shader_program = ((struct st_vertex_program *)prog)->shader_program;
350 break;
351 case MESA_SHADER_FRAGMENT:
352 shader_program = ((struct st_fragment_program *)prog)->shader_program;
353 break;
354 case MESA_SHADER_COMPUTE:
355 shader_program = ((struct st_compute_program *)prog)->shader_program;
356 break;
357 default:
358 assert(!"should not be reached");
359 return;
360 }
361
362 NIR_PASS_V(nir, nir_lower_atomics_to_ssbo,
363 st->ctx->Const.Program[nir->stage].MaxAtomicBuffers);
364
365 st_nir_assign_uniform_locations(prog, shader_program,
366 &nir->uniforms, &nir->num_uniforms);
367
368 NIR_PASS_V(nir, nir_lower_system_values);
369 NIR_PASS_V(nir, nir_lower_io, nir_var_all, st_glsl_type_size,
370 (nir_lower_io_options)0);
371 NIR_PASS_V(nir, nir_lower_samplers, shader_program);
372 }
373
374 struct gl_program *
375 st_nir_get_mesa_program(struct gl_context *ctx,
376 struct gl_shader_program *shader_program,
377 struct gl_linked_shader *shader)
378 {
379 struct gl_program *prog;
380
381 validate_ir_tree(shader->ir);
382
383 prog = shader->Program;
384
385 prog->Parameters = _mesa_new_parameter_list();
386
387 do_set_program_inouts(shader->ir, prog, shader->Stage);
388
389 _mesa_copy_linked_program_data(shader_program, shader);
390 _mesa_generate_parameters_list_for_uniforms(shader_program, shader,
391 prog->Parameters);
392
393 /* Make a pass over the IR to add state references for any built-in
394 * uniforms that are used. This has to be done now (during linking).
395 * Code generation doesn't happen until the first time this shader is
396 * used for rendering. Waiting until then to generate the parameters is
397 * too late. At that point, the values for the built-in uniforms won't
398 * get sent to the shader.
399 */
400 foreach_in_list(ir_instruction, node, shader->ir) {
401 ir_variable *var = node->as_variable();
402
403 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
404 (strncmp(var->name, "gl_", 3) != 0))
405 continue;
406
407 const ir_state_slot *const slots = var->get_state_slots();
408 assert(slots != NULL);
409
410 for (unsigned int i = 0; i < var->get_num_state_slots(); i++) {
411 _mesa_add_state_reference(prog->Parameters,
412 (gl_state_index *) slots[i].tokens);
413 }
414 }
415
416 if (ctx->_Shader->Flags & GLSL_DUMP) {
417 _mesa_log("\n");
418 _mesa_log("GLSL IR for linked %s program %d:\n",
419 _mesa_shader_stage_to_string(shader->Stage),
420 shader_program->Name);
421 _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
422 _mesa_log("\n\n");
423 }
424
425 prog->ShadowSamplers = shader->shadow_samplers;
426 prog->ExternalSamplersUsed = gl_external_samplers(prog);
427 _mesa_update_shader_textures_used(shader_program, prog);
428
429 /* Avoid reallocation of the program parameter list, because the uniform
430 * storage is only associated with the original parameter list.
431 * This should be enough for Bitmap and DrawPixels constants.
432 */
433 _mesa_reserve_parameter_storage(prog->Parameters, 8);
434
435 /* This has to be done last. Any operation the can cause
436 * prog->ParameterValues to get reallocated (e.g., anything that adds a
437 * program constant) has to happen before creating this linkage.
438 */
439 _mesa_associate_uniform_storage(ctx, shader_program, prog->Parameters,
440 true);
441
442 struct st_vertex_program *stvp;
443 struct st_fragment_program *stfp;
444 struct st_compute_program *stcp;
445
446 switch (shader->Stage) {
447 case MESA_SHADER_VERTEX:
448 stvp = (struct st_vertex_program *)prog;
449 stvp->shader_program = shader_program;
450 break;
451 case MESA_SHADER_FRAGMENT:
452 stfp = (struct st_fragment_program *)prog;
453 stfp->shader_program = shader_program;
454 break;
455 case MESA_SHADER_COMPUTE:
456 stcp = (struct st_compute_program *)prog;
457 stcp->shader_program = shader_program;
458 break;
459 default:
460 assert(!"should not be reached");
461 return NULL;
462 }
463
464 return prog;
465 }
466
467 } /* extern "C" */