1/*
2 * Copyright (C) 2021 Collabora, Ltd.
3 * Copyright (C) 2019 Ryan Houdek <Sonicadvance1@gmail.com>
4 * Copyright (C) 2014 Rob Clark <robclark@freedesktop.org>
5 * Copyright © 2015 Red Hat
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the next
15 * paragraph) shall be included in all copies or substantial portions of the
16 * Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * SOFTWARE.
25 */
26
27#include <getopt.h>
28#include <string.h>
29#include "disassemble.h"
30#include "compiler.h"
31
32#include "main/mtypes.h"
33#include "compiler/glsl/standalone.h"
34#include "compiler/glsl/glsl_to_nir.h"
35#include "compiler/glsl/gl_nir.h"
36#include "compiler/nir_types.h"
37#include "util/u_dynarray.h"
38#include "bifrost_compile.h"
39
40unsigned gpu_id = 0x7212;
41int verbose = 0;
42
43static gl_shader_stage
44filename_to_stage(const char *stage)
45{
46        const char *ext = strrchr(stage, '.');
47
48        if (ext == NULL) {
49                fprintf(stderr, "No extension found in %s\n", stage);
50                exit(1);
51        }
52
53        if (!strcmp(ext, ".cs") || !strcmp(ext, ".comp"))
54                return MESA_SHADER_COMPUTE;
55        else if (!strcmp(ext, ".vs") || !strcmp(ext, ".vert"))
56                return MESA_SHADER_VERTEX;
57        else if (!strcmp(ext, ".fs") || !strcmp(ext, ".frag"))
58                return MESA_SHADER_FRAGMENT;
59        else {
60                fprintf(stderr, "Invalid extension %s\n", ext);
61                exit(1);
62        }
63
64        unreachable("Should've returned or bailed");
65}
66
67static int
68st_packed_uniforms_type_size(const struct glsl_type *type, bool bindless)
69{
70   return glsl_count_dword_slots(type, bindless);
71}
72
73static int
74glsl_type_size(const struct glsl_type *type, bool bindless)
75{
76   return glsl_count_attribute_slots(type, false);
77}
78
79static void
80insert_sorted(struct exec_list *var_list, nir_variable *new_var)
81{
82   nir_foreach_variable_in_list (var, var_list) {
83      if (var->data.location > new_var->data.location) {
84         exec_node_insert_node_before(&var->node, &new_var->node);
85         return;
86      }
87   }
88   exec_list_push_tail(var_list, &new_var->node);
89}
90
91static void
92sort_varyings(nir_shader *nir, nir_variable_mode mode)
93{
94   struct exec_list new_list;
95   exec_list_make_empty(&new_list);
96   nir_foreach_variable_with_modes_safe (var, nir, mode) {
97      exec_node_remove(&var->node);
98      insert_sorted(&new_list, var);
99   }
100   exec_list_append(&nir->variables, &new_list);
101}
102
103static void
104fixup_varying_slots(nir_shader *nir, nir_variable_mode mode)
105{
106   nir_foreach_variable_with_modes (var, nir, mode) {
107      if (var->data.location >= VARYING_SLOT_VAR0) {
108         var->data.location += 9;
109      } else if ((var->data.location >= VARYING_SLOT_TEX0) &&
110                 (var->data.location <= VARYING_SLOT_TEX7)) {
111         var->data.location += VARYING_SLOT_VAR0 - VARYING_SLOT_TEX0;
112      }
113   }
114}
115
116static void
117compile_shader(int stages, char **files)
118{
119        struct gl_shader_program *prog;
120        nir_shader *nir[MESA_SHADER_COMPUTE + 1];
121        unsigned shader_types[MESA_SHADER_COMPUTE + 1];
122
123        if (stages > MESA_SHADER_COMPUTE) {
124                fprintf(stderr, "Too many stages");
125                exit(1);
126        }
127
128        for (unsigned i = 0; i < stages; ++i)
129                shader_types[i] = filename_to_stage(files[i]);
130
131        struct standalone_options options = {
132                .glsl_version = 300, /* ES - needed for precision */
133                .do_link = true,
134                .lower_precision = true
135        };
136
137        static struct gl_context local_ctx;
138
139        prog = standalone_compile_shader(&options, stages, files, &local_ctx);
140
141        for (unsigned i = 0; i < stages; ++i) {
142                gl_shader_stage stage = shader_types[i];
143                prog->_LinkedShaders[stage]->Program->info.stage = stage;
144        }
145
146        struct util_dynarray binary;
147
148        util_dynarray_init(&binary, NULL);
149
150        for (unsigned i = 0; i < stages; ++i) {
151                nir[i] = glsl_to_nir(&local_ctx, prog, shader_types[i], &bifrost_nir_options);
152
153                if (shader_types[i] == MESA_SHADER_VERTEX) {
154                        nir_assign_var_locations(nir[i], nir_var_shader_in, &nir[i]->num_inputs,
155                                        glsl_type_size);
156                        sort_varyings(nir[i], nir_var_shader_out);
157                        nir_assign_var_locations(nir[i], nir_var_shader_out, &nir[i]->num_outputs,
158                                        glsl_type_size);
159                        fixup_varying_slots(nir[i], nir_var_shader_out);
160                } else if (shader_types[i] == MESA_SHADER_FRAGMENT) {
161                      sort_varyings(nir[i], nir_var_shader_in);
162                      nir_assign_var_locations(nir[i], nir_var_shader_in, &nir[i]->num_inputs,
163                                      glsl_type_size);
164                      fixup_varying_slots(nir[i], nir_var_shader_in);
165                      nir_assign_var_locations(nir[i], nir_var_shader_out, &nir[i]->num_outputs,
166                                      glsl_type_size);
167                }
168
169                nir_assign_var_locations(nir[i], nir_var_uniform, &nir[i]->num_uniforms,
170                                glsl_type_size);
171
172                NIR_PASS_V(nir[i], nir_lower_global_vars_to_local);
173                NIR_PASS_V(nir[i], nir_lower_io_to_temporaries, nir_shader_get_entrypoint(nir[i]), true, i == 0);
174                NIR_PASS_V(nir[i], nir_opt_copy_prop_vars);
175                NIR_PASS_V(nir[i], nir_opt_combine_stores, nir_var_all);
176
177                NIR_PASS_V(nir[i], nir_lower_system_values);
178                NIR_PASS_V(nir[i], gl_nir_lower_samplers, prog);
179                NIR_PASS_V(nir[i], nir_split_var_copies);
180                NIR_PASS_V(nir[i], nir_lower_var_copies);
181
182                NIR_PASS_V(nir[i], nir_lower_io, nir_var_uniform,
183                                st_packed_uniforms_type_size,
184                                (nir_lower_io_options)0);
185                NIR_PASS_V(nir[i], nir_lower_uniforms_to_ubo, true, false);
186
187                /* before buffers and vars_to_ssa */
188                NIR_PASS_V(nir[i], gl_nir_lower_images, true);
189
190                NIR_PASS_V(nir[i], gl_nir_lower_buffers, prog);
191                NIR_PASS_V(nir[i], nir_opt_constant_folding);
192
193                struct panfrost_compile_inputs inputs = {
194                        .gpu_id = gpu_id,
195                };
196                struct pan_shader_info info = { 0 };
197
198                util_dynarray_clear(&binary);
199                bifrost_compile_shader_nir(nir[i], &inputs, &binary, &info);
200
201                char *fn = NULL;
202                asprintf(&fn, "shader_%u.bin", i);
203                assert(fn != NULL);
204                FILE *fp = fopen(fn, "wb");
205                fwrite(binary.data, 1, binary.size, fp);
206                fclose(fp);
207                free(fn);
208        }
209
210        util_dynarray_fini(&binary);
211}
212
213#define BI_FOURCC(ch0, ch1, ch2, ch3) ( \
214  (uint32_t)(ch0)        | (uint32_t)(ch1) << 8 | \
215  (uint32_t)(ch2) << 16  | (uint32_t)(ch3) << 24)
216
217static void
218disassemble(const char *filename)
219{
220        FILE *fp = fopen(filename, "rb");
221        assert(fp);
222
223        fseek(fp, 0, SEEK_END);
224        unsigned filesize = ftell(fp);
225        rewind(fp);
226
227        uint32_t *code = malloc(filesize);
228        unsigned res = fread(code, 1, filesize, fp);
229        if (res != filesize) {
230                printf("Couldn't read full file\n");
231        }
232
233        fclose(fp);
234
235        if (filesize && code[0] == BI_FOURCC('M', 'B', 'S', '2')) {
236                for (int i = 0; i < filesize / 4; ++i) {
237                        if (code[i] != BI_FOURCC('O', 'B', 'J', 'C'))
238                                continue;
239
240                        unsigned size = code[i + 1];
241                        unsigned offset = i + 2;
242
243                        disassemble_bifrost(stdout, (uint8_t*)(code + offset), size, verbose);
244                }
245        } else {
246                disassemble_bifrost(stdout, (uint8_t*)code, filesize, verbose);
247        }
248
249        free(code);
250}
251
252int
253main(int argc, char **argv)
254{
255        int c;
256
257        if (argc < 2) {
258                printf("Pass a command\n");
259                exit(1);
260        }
261
262        static struct option longopts[] = {
263                { "id", optional_argument, NULL, 'i' },
264                { "gpu", optional_argument, NULL, 'g' },
265                { "verbose", no_argument, &verbose, 'v' },
266                { NULL, 0, NULL, 0 }
267        };
268
269        static struct {
270                const char *name;
271                unsigned major, minor;
272        } gpus[] = {
273                { "G71",   6, 0 },
274                { "G72",   6, 2 },
275                { "G51",   7, 0 },
276                { "G76",   7, 1 },
277                { "G52",   7, 2 },
278                { "G31",   7, 3 },
279                { "G77",   9, 0 },
280                { "G57",   9, 1 },
281                { "G78",   9, 2 },
282                { "G57",   9, 3 },
283                { "G68",   9, 4 },
284                { "G78AE", 9, 5 },
285        };
286
287        while ((c = getopt_long(argc, argv, "v:", longopts, NULL)) != -1) {
288
289                switch (c) {
290                case 'i':
291                        gpu_id = atoi(optarg);
292
293                        if (!gpu_id) {
294                                fprintf(stderr, "Expected GPU ID, got %s\n", optarg);
295                                return 1;
296                        }
297
298                        break;
299                case 'g':
300                        gpu_id = 0;
301
302                        /* Compatibility with the Arm compiler */
303                        if (strncmp(optarg, "Mali-", 5) == 0) optarg += 5;
304
305                        for (unsigned i = 0; i < ARRAY_SIZE(gpus); ++i) {
306                                if (strcmp(gpus[i].name, optarg)) continue;
307
308                                unsigned major = gpus[i].major;
309                                unsigned minor = gpus[i].minor;
310
311                                gpu_id = (major << 12) | (minor << 8);
312                                break;
313                        }
314
315                        if (!gpu_id) {
316                                fprintf(stderr, "Unknown GPU %s\n", optarg);
317                                return 1;
318                        }
319
320                        break;
321                default:
322                        break;
323                }
324        }
325
326        if (strcmp(argv[optind], "compile") == 0)
327                compile_shader(argc - optind - 1, &argv[optind + 1]);
328        else if (strcmp(argv[optind], "disasm") == 0)
329                disassemble(argv[optind + 1]);
330        else {
331                fprintf(stderr, "Unknown command. Valid: compile/disasm\n");
332                return 1;
333        }
334
335        return 0;
336}
337