• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 Advanced Micro Devices, Inc.
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  * on the rights to use, copy, modify, merge, publish, distribute, sub
8  * license, and/or sell copies of the Software, and to permit persons to whom
9  * the 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 NON-INFRINGEMENT. IN NO EVENT SHALL
18  * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21  * USE OR OTHER DEALINGS IN THE SOFTWARE.
22  */
23 
24 #include "glspirv.h"
25 #include "errors.h"
26 #include "shaderobj.h"
27 #include "mtypes.h"
28 
29 #include "compiler/nir/nir.h"
30 #include "compiler/spirv/nir_spirv.h"
31 
32 #include "program/program.h"
33 
34 #include "util/u_atomic.h"
35 #include "api_exec_decl.h"
36 
37 void
_mesa_spirv_module_reference(struct gl_spirv_module ** dest,struct gl_spirv_module * src)38 _mesa_spirv_module_reference(struct gl_spirv_module **dest,
39                              struct gl_spirv_module *src)
40 {
41    struct gl_spirv_module *old = *dest;
42 
43    if (old && p_atomic_dec_zero(&old->RefCount))
44       free(old);
45 
46    *dest = src;
47 
48    if (src)
49       p_atomic_inc(&src->RefCount);
50 }
51 
52 void
_mesa_shader_spirv_data_reference(struct gl_shader_spirv_data ** dest,struct gl_shader_spirv_data * src)53 _mesa_shader_spirv_data_reference(struct gl_shader_spirv_data **dest,
54                                   struct gl_shader_spirv_data *src)
55 {
56    struct gl_shader_spirv_data *old = *dest;
57 
58    if (old && p_atomic_dec_zero(&old->RefCount)) {
59       _mesa_spirv_module_reference(&(*dest)->SpirVModule, NULL);
60       ralloc_free(old);
61    }
62 
63    *dest = src;
64 
65    if (src)
66       p_atomic_inc(&src->RefCount);
67 }
68 
69 void
_mesa_spirv_shader_binary(struct gl_context * ctx,unsigned n,struct gl_shader ** shaders,const void * binary,size_t length)70 _mesa_spirv_shader_binary(struct gl_context *ctx,
71                           unsigned n, struct gl_shader **shaders,
72                           const void* binary, size_t length)
73 {
74    struct gl_spirv_module *module;
75    struct gl_shader_spirv_data *spirv_data;
76 
77    /* From OpenGL 4.6 Core spec, "7.2 Shader Binaries" :
78     *
79     * "An INVALID_VALUE error is generated if the data pointed to by binary
80     *  does not match the specified binaryformat."
81     *
82     * However, the ARB_gl_spirv spec, under issue #16 says:
83     *
84     * "ShaderBinary is expected to form an association between the SPIR-V
85     *  module and likely would not parse the module as would be required to
86     *  detect unsupported capabilities or other validation failures."
87     *
88     * Which specifies little to no validation requirements. Nevertheless, the
89     * two small checks below seem reasonable.
90     */
91    if (!binary || (length % 4) != 0) {
92       _mesa_error(ctx, GL_INVALID_VALUE, "glShaderBinary");
93       return;
94    }
95 
96    module = malloc(sizeof(*module) + length);
97    if (!module) {
98       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderBinary");
99       return;
100    }
101 
102    p_atomic_set(&module->RefCount, 0);
103    module->Length = length;
104    memcpy(&module->Binary[0], binary, length);
105 
106    for (int i = 0; i < n; ++i) {
107       struct gl_shader *sh = shaders[i];
108 
109       spirv_data = rzalloc(NULL, struct gl_shader_spirv_data);
110       _mesa_shader_spirv_data_reference(&sh->spirv_data, spirv_data);
111       _mesa_spirv_module_reference(&spirv_data->SpirVModule, module);
112 
113       sh->CompileStatus = COMPILE_FAILURE;
114 
115       free((void *)sh->Source);
116       sh->Source = NULL;
117       free((void *)sh->FallbackSource);
118       sh->FallbackSource = NULL;
119 
120       ralloc_free(sh->ir);
121       sh->ir = NULL;
122       ralloc_free(sh->symbols);
123       sh->symbols = NULL;
124    }
125 }
126 
127 /**
128  * This is the equivalent to compiler/glsl/linker.cpp::link_shaders()
129  * but for SPIR-V programs.
130  *
131  * This method just creates the gl_linked_shader structs with a reference to
132  * the SPIR-V data collected during previous steps.
133  *
134  * The real linking happens later in the driver-specifc call LinkShader().
135  * This is so backends can implement different linking strategies for
136  * SPIR-V programs.
137  */
138 void
_mesa_spirv_link_shaders(struct gl_context * ctx,struct gl_shader_program * prog)139 _mesa_spirv_link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
140 {
141    prog->data->LinkStatus = LINKING_SUCCESS;
142    prog->data->Validated = false;
143 
144    for (unsigned i = 0; i < prog->NumShaders; i++) {
145       struct gl_shader *shader = prog->Shaders[i];
146       gl_shader_stage shader_type = shader->Stage;
147 
148       /* We only support one shader per stage. The gl_spirv spec doesn't seem
149        * to prevent this, but the way the API is designed, requiring all shaders
150        * to be specialized with an entry point, makes supporting this quite
151        * undefined.
152        *
153        * TODO: Turn this into a proper error once the spec bug
154        * <https://gitlab.khronos.org/opengl/API/issues/58> is resolved.
155        */
156       if (prog->_LinkedShaders[shader_type]) {
157          ralloc_strcat(&prog->data->InfoLog,
158                        "\nError trying to link more than one SPIR-V shader "
159                        "per stage.\n");
160          prog->data->LinkStatus = LINKING_FAILURE;
161          return;
162       }
163 
164       assert(shader->spirv_data);
165 
166       struct gl_linked_shader *linked = rzalloc(NULL, struct gl_linked_shader);
167       linked->Stage = shader_type;
168 
169       /* Create program and attach it to the linked shader */
170       struct gl_program *gl_prog =
171          ctx->Driver.NewProgram(ctx, shader_type, prog->Name, false);
172       if (!gl_prog) {
173          prog->data->LinkStatus = LINKING_FAILURE;
174          _mesa_delete_linked_shader(ctx, linked);
175          return;
176       }
177 
178       _mesa_reference_shader_program_data(&gl_prog->sh.data,
179                                           prog->data);
180 
181       /* Don't use _mesa_reference_program() just take ownership */
182       linked->Program = gl_prog;
183 
184       /* Reference the SPIR-V data from shader to the linked shader */
185       _mesa_shader_spirv_data_reference(&linked->spirv_data,
186                                         shader->spirv_data);
187 
188       prog->_LinkedShaders[shader_type] = linked;
189       prog->data->linked_stages |= 1 << shader_type;
190    }
191 
192    int last_vert_stage =
193       util_last_bit(prog->data->linked_stages &
194                     ((1 << (MESA_SHADER_GEOMETRY + 1)) - 1));
195 
196    if (last_vert_stage)
197       prog->last_vert_prog = prog->_LinkedShaders[last_vert_stage - 1]->Program;
198 
199    /* Some shaders have to be linked with some other shaders present. */
200    if (!prog->SeparateShader) {
201       static const struct {
202          gl_shader_stage a, b;
203       } stage_pairs[] = {
204          { MESA_SHADER_GEOMETRY, MESA_SHADER_VERTEX },
205          { MESA_SHADER_TESS_EVAL, MESA_SHADER_VERTEX },
206          { MESA_SHADER_TESS_CTRL, MESA_SHADER_VERTEX },
207          { MESA_SHADER_TESS_CTRL, MESA_SHADER_TESS_EVAL },
208       };
209 
210       for (unsigned i = 0; i < ARRAY_SIZE(stage_pairs); i++) {
211          gl_shader_stage a = stage_pairs[i].a;
212          gl_shader_stage b = stage_pairs[i].b;
213          if ((prog->data->linked_stages & ((1 << a) | (1 << b))) == (1 << a)) {
214             ralloc_asprintf_append(&prog->data->InfoLog,
215                                    "%s shader must be linked with %s shader\n",
216                                    _mesa_shader_stage_to_string(a),
217                                    _mesa_shader_stage_to_string(b));
218             prog->data->LinkStatus = LINKING_FAILURE;
219             return;
220          }
221       }
222    }
223 
224    /* Compute shaders have additional restrictions. */
225    if ((prog->data->linked_stages & (1 << MESA_SHADER_COMPUTE)) &&
226        (prog->data->linked_stages & ~(1 << MESA_SHADER_COMPUTE))) {
227       ralloc_asprintf_append(&prog->data->InfoLog,
228                              "Compute shaders may not be linked with any other "
229                              "type of shader\n");
230       prog->data->LinkStatus = LINKING_FAILURE;
231       return;
232    }
233 }
234 
235 nir_shader *
_mesa_spirv_to_nir(struct gl_context * ctx,const struct gl_shader_program * prog,gl_shader_stage stage,const nir_shader_compiler_options * options)236 _mesa_spirv_to_nir(struct gl_context *ctx,
237                    const struct gl_shader_program *prog,
238                    gl_shader_stage stage,
239                    const nir_shader_compiler_options *options)
240 {
241    struct gl_linked_shader *linked_shader = prog->_LinkedShaders[stage];
242    assert (linked_shader);
243 
244    struct gl_shader_spirv_data *spirv_data = linked_shader->spirv_data;
245    assert(spirv_data);
246 
247    struct gl_spirv_module *spirv_module = spirv_data->SpirVModule;
248    assert (spirv_module != NULL);
249 
250    const char *entry_point_name = spirv_data->SpirVEntryPoint;
251    assert(entry_point_name);
252 
253    struct nir_spirv_specialization *spec_entries =
254       calloc(sizeof(*spec_entries),
255              spirv_data->NumSpecializationConstants);
256 
257    for (unsigned i = 0; i < spirv_data->NumSpecializationConstants; ++i) {
258       spec_entries[i].id = spirv_data->SpecializationConstantsIndex[i];
259       spec_entries[i].value.u32 = spirv_data->SpecializationConstantsValue[i];
260       spec_entries[i].defined_on_module = false;
261    }
262 
263    const struct spirv_to_nir_options spirv_options = {
264       .environment = NIR_SPIRV_OPENGL,
265       .subgroup_size = SUBGROUP_SIZE_UNIFORM,
266       .caps = ctx->Const.SpirVCapabilities,
267       .ubo_addr_format = nir_address_format_32bit_index_offset,
268       .ssbo_addr_format = nir_address_format_32bit_index_offset,
269 
270       /* TODO: Consider changing this to an address format that has the NULL
271        * pointer equals to 0.  That might be a better format to play nice
272        * with certain code / code generators.
273        */
274       .shared_addr_format = nir_address_format_32bit_offset,
275 
276    };
277 
278    nir_shader *nir =
279       spirv_to_nir((const uint32_t *) &spirv_module->Binary[0],
280                    spirv_module->Length / 4,
281                    spec_entries, spirv_data->NumSpecializationConstants,
282                    stage, entry_point_name,
283                    &spirv_options,
284                    options);
285    free(spec_entries);
286 
287    assert(nir);
288    assert(nir->info.stage == stage);
289 
290    nir->options = options;
291 
292    nir->info.name =
293       ralloc_asprintf(nir, "SPIRV:%s:%d",
294                       _mesa_shader_stage_to_abbrev(nir->info.stage),
295                       prog->Name);
296    nir_validate_shader(nir, "after spirv_to_nir");
297 
298    nir->info.separate_shader = linked_shader->Program->info.separate_shader;
299 
300    /* Convert some sysvals to input varyings. */
301    const struct nir_lower_sysvals_to_varyings_options sysvals_to_varyings = {
302       .frag_coord = !ctx->Const.GLSLFragCoordIsSysVal,
303       .point_coord = !ctx->Const.GLSLPointCoordIsSysVal,
304       .front_face = !ctx->Const.GLSLFrontFacingIsSysVal,
305    };
306    NIR_PASS(_, nir, nir_lower_sysvals_to_varyings, &sysvals_to_varyings);
307 
308    /* We have to lower away local constant initializers right before we
309     * inline functions.  That way they get properly initialized at the top
310     * of the function and not at the top of its caller.
311     */
312    NIR_PASS(_, nir, nir_lower_variable_initializers, nir_var_function_temp);
313    NIR_PASS(_, nir, nir_lower_returns);
314    NIR_PASS(_, nir, nir_inline_functions);
315    NIR_PASS(_, nir, nir_copy_prop);
316    NIR_PASS(_, nir, nir_opt_deref);
317 
318    /* Pick off the single entrypoint that we want */
319    nir_remove_non_entrypoints(nir);
320 
321    /* Now that we've deleted all but the main function, we can go ahead and
322     * lower the rest of the constant initializers.  We do this here so that
323     * nir_remove_dead_variables and split_per_member_structs below see the
324     * corresponding stores.
325     */
326    NIR_PASS(_, nir, nir_lower_variable_initializers, ~0);
327 
328    /* Split member structs.  We do this before lower_io_to_temporaries so that
329     * it doesn't lower system values to temporaries by accident.
330     */
331    NIR_PASS(_, nir, nir_split_var_copies);
332    NIR_PASS(_, nir, nir_split_per_member_structs);
333 
334    if (nir->info.stage == MESA_SHADER_VERTEX)
335       nir_remap_dual_slot_attributes(nir, &linked_shader->Program->DualSlotInputs);
336 
337    NIR_PASS(_, nir, nir_lower_frexp);
338 
339    return nir;
340 }
341 
342 void GLAPIENTRY
_mesa_SpecializeShaderARB(GLuint shader,const GLchar * pEntryPoint,GLuint numSpecializationConstants,const GLuint * pConstantIndex,const GLuint * pConstantValue)343 _mesa_SpecializeShaderARB(GLuint shader,
344                           const GLchar *pEntryPoint,
345                           GLuint numSpecializationConstants,
346                           const GLuint *pConstantIndex,
347                           const GLuint *pConstantValue)
348 {
349    GET_CURRENT_CONTEXT(ctx);
350    struct gl_shader *sh;
351    struct nir_spirv_specialization *spec_entries = NULL;
352 
353    if (!ctx->Extensions.ARB_gl_spirv) {
354       _mesa_error(ctx, GL_INVALID_OPERATION, "glSpecializeShaderARB");
355       return;
356    }
357 
358    sh = _mesa_lookup_shader_err(ctx, shader, "glSpecializeShaderARB");
359    if (!sh)
360       return;
361 
362    if (!sh->spirv_data) {
363       _mesa_error(ctx, GL_INVALID_OPERATION,
364                   "glSpecializeShaderARB(not SPIR-V)");
365       return;
366    }
367 
368    if (sh->CompileStatus) {
369       _mesa_error(ctx, GL_INVALID_OPERATION,
370                   "glSpecializeShaderARB(already specialized)");
371       return;
372    }
373 
374    struct gl_shader_spirv_data *spirv_data = sh->spirv_data;
375 
376    /* From the GL_ARB_gl_spirv spec:
377     *
378     *    "The OpenGL API expects the SPIR-V module to have already been
379     *     validated, and can return an error if it discovers anything invalid
380     *     in the module. An invalid SPIR-V module is allowed to result in
381     *     undefined behavior."
382     *
383     * However, the following errors still need to be detected (from the same
384     * spec):
385     *
386     *    "INVALID_VALUE is generated if <pEntryPoint> does not name a valid
387     *     entry point for <shader>.
388     *
389     *     INVALID_VALUE is generated if any element of <pConstantIndex>
390     *     refers to a specialization constant that does not exist in the
391     *     shader module contained in <shader>."
392     *
393     * We cannot flag those errors a-priori because detecting them requires
394     * parsing the module. However, flagging them during specialization is okay,
395     * since it makes no difference in terms of application-visible state.
396     */
397    spec_entries = calloc(sizeof(*spec_entries), numSpecializationConstants);
398 
399    for (unsigned i = 0; i < numSpecializationConstants; ++i) {
400       spec_entries[i].id = pConstantIndex[i];
401       spec_entries[i].value.u32 = pConstantValue[i];
402       spec_entries[i].defined_on_module = false;
403    }
404 
405    enum spirv_verify_result r = spirv_verify_gl_specialization_constants(
406       (uint32_t *)&spirv_data->SpirVModule->Binary[0],
407       spirv_data->SpirVModule->Length / 4,
408       spec_entries, numSpecializationConstants,
409       sh->Stage, pEntryPoint);
410 
411    switch (r) {
412    case SPIRV_VERIFY_OK:
413       break;
414    case SPIRV_VERIFY_PARSER_ERROR:
415       _mesa_error(ctx, GL_INVALID_VALUE,
416                   "glSpecializeShaderARB(failed to parse entry point \"%s\""
417                   " for shader)", pEntryPoint);
418       goto end;
419    case SPIRV_VERIFY_ENTRY_POINT_NOT_FOUND:
420       _mesa_error(ctx, GL_INVALID_VALUE,
421                   "glSpecializeShaderARB(could not find entry point \"%s\""
422                   " for shader)", pEntryPoint);
423       goto end;
424    case SPIRV_VERIFY_UNKNOWN_SPEC_INDEX:
425       for (unsigned i = 0; i < numSpecializationConstants; ++i) {
426          if (spec_entries[i].defined_on_module == false) {
427             _mesa_error(ctx, GL_INVALID_VALUE,
428                         "glSpecializeShaderARB(constant \"%i\" does not exist "
429                         "in shader)", spec_entries[i].id);
430             break;
431          }
432       }
433       goto end;
434    }
435 
436    spirv_data->SpirVEntryPoint = ralloc_strdup(spirv_data, pEntryPoint);
437 
438    /* Note that we didn't make a real compilation of the module (spirv_to_nir),
439     * but just checked some error conditions. Real "compilation" will be done
440     * later, upon linking.
441     */
442    sh->CompileStatus = COMPILE_SUCCESS;
443 
444    spirv_data->NumSpecializationConstants = numSpecializationConstants;
445    spirv_data->SpecializationConstantsIndex =
446       rzalloc_array_size(spirv_data, sizeof(GLuint),
447                          numSpecializationConstants);
448    spirv_data->SpecializationConstantsValue =
449       rzalloc_array_size(spirv_data, sizeof(GLuint),
450                          numSpecializationConstants);
451    for (unsigned i = 0; i < numSpecializationConstants; ++i) {
452       spirv_data->SpecializationConstantsIndex[i] = pConstantIndex[i];
453       spirv_data->SpecializationConstantsValue[i] = pConstantValue[i];
454    }
455 
456  end:
457    free(spec_entries);
458 }
459