1 /*
2  * Copyright © 2010 Intel Corporation
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
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23 
24 
25 /**
26  * Building this file with MinGW g++ 7.3 or 7.4 with:
27  *   scons platform=windows toolchain=crossmingw machine=x86 build=profile
28  * triggers an internal compiler error.
29  * Overriding the optimization level to -O1 works around the issue.
30  * MinGW 5.3.1 does not seem to have the bug, neither does 8.3.  So for now
31  * we're simply testing for version 7.x here.
32  */
33 #if defined(__MINGW32__) && __GNUC__ == 7
34 #warning "disabling optimizations for this file to work around compiler bug in MinGW gcc 7.x"
35 #pragma GCC optimize("O1")
36 #endif
37 
38 
39 #include "ir.h"
40 #include "ir_builder.h"
41 #include "linker.h"
42 #include "glsl_parser_extras.h"
43 #include "glsl_symbol_table.h"
44 #include "main/mtypes.h"
45 #include "main/uniforms.h"
46 #include "program/prog_statevars.h"
47 #include "program/prog_instruction.h"
48 #include "builtin_functions.h"
49 
50 using namespace ir_builder;
51 
52 static const struct gl_builtin_uniform_element gl_NumSamples_elements[] = {
53    {NULL, {STATE_NUM_SAMPLES, 0, 0}, SWIZZLE_XXXX}
54 };
55 
56 static const struct gl_builtin_uniform_element gl_DepthRange_elements[] = {
57    {"near", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_XXXX},
58    {"far", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_YYYY},
59    {"diff", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_ZZZZ},
60 };
61 
62 static const struct gl_builtin_uniform_element gl_ClipPlane_elements[] = {
63    {NULL, {STATE_CLIPPLANE, 0, 0}, SWIZZLE_XYZW}
64 };
65 
66 static const struct gl_builtin_uniform_element gl_Point_elements[] = {
67    {"size", {STATE_POINT_SIZE}, SWIZZLE_XXXX},
68    {"sizeMin", {STATE_POINT_SIZE}, SWIZZLE_YYYY},
69    {"sizeMax", {STATE_POINT_SIZE}, SWIZZLE_ZZZZ},
70    {"fadeThresholdSize", {STATE_POINT_SIZE}, SWIZZLE_WWWW},
71    {"distanceConstantAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_XXXX},
72    {"distanceLinearAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_YYYY},
73    {"distanceQuadraticAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_ZZZZ},
74 };
75 
76 static const struct gl_builtin_uniform_element gl_FrontMaterial_elements[] = {
77    {"emission", {STATE_MATERIAL, 0, STATE_EMISSION}, SWIZZLE_XYZW},
78    {"ambient", {STATE_MATERIAL, 0, STATE_AMBIENT}, SWIZZLE_XYZW},
79    {"diffuse", {STATE_MATERIAL, 0, STATE_DIFFUSE}, SWIZZLE_XYZW},
80    {"specular", {STATE_MATERIAL, 0, STATE_SPECULAR}, SWIZZLE_XYZW},
81    {"shininess", {STATE_MATERIAL, 0, STATE_SHININESS}, SWIZZLE_XXXX},
82 };
83 
84 static const struct gl_builtin_uniform_element gl_BackMaterial_elements[] = {
85    {"emission", {STATE_MATERIAL, 1, STATE_EMISSION}, SWIZZLE_XYZW},
86    {"ambient", {STATE_MATERIAL, 1, STATE_AMBIENT}, SWIZZLE_XYZW},
87    {"diffuse", {STATE_MATERIAL, 1, STATE_DIFFUSE}, SWIZZLE_XYZW},
88    {"specular", {STATE_MATERIAL, 1, STATE_SPECULAR}, SWIZZLE_XYZW},
89    {"shininess", {STATE_MATERIAL, 1, STATE_SHININESS}, SWIZZLE_XXXX},
90 };
91 
92 static const struct gl_builtin_uniform_element gl_LightSource_elements[] = {
93    {"ambient", {STATE_LIGHT, 0, STATE_AMBIENT}, SWIZZLE_XYZW},
94    {"diffuse", {STATE_LIGHT, 0, STATE_DIFFUSE}, SWIZZLE_XYZW},
95    {"specular", {STATE_LIGHT, 0, STATE_SPECULAR}, SWIZZLE_XYZW},
96    {"position", {STATE_LIGHT, 0, STATE_POSITION}, SWIZZLE_XYZW},
97    {"halfVector", {STATE_LIGHT, 0, STATE_HALF_VECTOR}, SWIZZLE_XYZW},
98    {"spotDirection", {STATE_LIGHT, 0, STATE_SPOT_DIRECTION},
99     MAKE_SWIZZLE4(SWIZZLE_X,
100 		  SWIZZLE_Y,
101 		  SWIZZLE_Z,
102 		  SWIZZLE_Z)},
103    {"spotExponent", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_WWWW},
104    {"spotCutoff", {STATE_LIGHT, 0, STATE_SPOT_CUTOFF}, SWIZZLE_XXXX},
105    {"spotCosCutoff", {STATE_LIGHT, 0, STATE_SPOT_DIRECTION}, SWIZZLE_WWWW},
106    {"constantAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_XXXX},
107    {"linearAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_YYYY},
108    {"quadraticAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_ZZZZ},
109 };
110 
111 static const struct gl_builtin_uniform_element gl_LightModel_elements[] = {
112    {"ambient", {STATE_LIGHTMODEL_AMBIENT, 0}, SWIZZLE_XYZW},
113 };
114 
115 static const struct gl_builtin_uniform_element gl_FrontLightModelProduct_elements[] = {
116    {"sceneColor", {STATE_LIGHTMODEL_SCENECOLOR, 0}, SWIZZLE_XYZW},
117 };
118 
119 static const struct gl_builtin_uniform_element gl_BackLightModelProduct_elements[] = {
120    {"sceneColor", {STATE_LIGHTMODEL_SCENECOLOR, 1}, SWIZZLE_XYZW},
121 };
122 
123 static const struct gl_builtin_uniform_element gl_FrontLightProduct_elements[] = {
124    {"ambient", {STATE_LIGHTPROD, 0, 0, STATE_AMBIENT}, SWIZZLE_XYZW},
125    {"diffuse", {STATE_LIGHTPROD, 0, 0, STATE_DIFFUSE}, SWIZZLE_XYZW},
126    {"specular", {STATE_LIGHTPROD, 0, 0, STATE_SPECULAR}, SWIZZLE_XYZW},
127 };
128 
129 static const struct gl_builtin_uniform_element gl_BackLightProduct_elements[] = {
130    {"ambient", {STATE_LIGHTPROD, 0, 1, STATE_AMBIENT}, SWIZZLE_XYZW},
131    {"diffuse", {STATE_LIGHTPROD, 0, 1, STATE_DIFFUSE}, SWIZZLE_XYZW},
132    {"specular", {STATE_LIGHTPROD, 0, 1, STATE_SPECULAR}, SWIZZLE_XYZW},
133 };
134 
135 static const struct gl_builtin_uniform_element gl_TextureEnvColor_elements[] = {
136    {NULL, {STATE_TEXENV_COLOR, 0}, SWIZZLE_XYZW},
137 };
138 
139 static const struct gl_builtin_uniform_element gl_EyePlaneS_elements[] = {
140    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_S}, SWIZZLE_XYZW},
141 };
142 
143 static const struct gl_builtin_uniform_element gl_EyePlaneT_elements[] = {
144    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_T}, SWIZZLE_XYZW},
145 };
146 
147 static const struct gl_builtin_uniform_element gl_EyePlaneR_elements[] = {
148    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_R}, SWIZZLE_XYZW},
149 };
150 
151 static const struct gl_builtin_uniform_element gl_EyePlaneQ_elements[] = {
152    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_Q}, SWIZZLE_XYZW},
153 };
154 
155 static const struct gl_builtin_uniform_element gl_ObjectPlaneS_elements[] = {
156    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_S}, SWIZZLE_XYZW},
157 };
158 
159 static const struct gl_builtin_uniform_element gl_ObjectPlaneT_elements[] = {
160    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_T}, SWIZZLE_XYZW},
161 };
162 
163 static const struct gl_builtin_uniform_element gl_ObjectPlaneR_elements[] = {
164    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_R}, SWIZZLE_XYZW},
165 };
166 
167 static const struct gl_builtin_uniform_element gl_ObjectPlaneQ_elements[] = {
168    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_Q}, SWIZZLE_XYZW},
169 };
170 
171 static const struct gl_builtin_uniform_element gl_Fog_elements[] = {
172    {"color", {STATE_FOG_COLOR}, SWIZZLE_XYZW},
173    {"density", {STATE_FOG_PARAMS}, SWIZZLE_XXXX},
174    {"start", {STATE_FOG_PARAMS}, SWIZZLE_YYYY},
175    {"end", {STATE_FOG_PARAMS}, SWIZZLE_ZZZZ},
176    {"scale", {STATE_FOG_PARAMS}, SWIZZLE_WWWW},
177 };
178 
179 static const struct gl_builtin_uniform_element gl_NormalScale_elements[] = {
180    {NULL, {STATE_NORMAL_SCALE}, SWIZZLE_XXXX},
181 };
182 
183 static const struct gl_builtin_uniform_element gl_FogParamsOptimizedMESA_elements[] = {
184    {NULL, {STATE_INTERNAL, STATE_FOG_PARAMS_OPTIMIZED}, SWIZZLE_XYZW},
185 };
186 
187 static const struct gl_builtin_uniform_element gl_CurrentAttribVertMESA_elements[] = {
188    {NULL, {STATE_INTERNAL, STATE_CURRENT_ATTRIB, 0}, SWIZZLE_XYZW},
189 };
190 
191 static const struct gl_builtin_uniform_element gl_CurrentAttribFragMESA_elements[] = {
192    {NULL, {STATE_INTERNAL, STATE_CURRENT_ATTRIB_MAYBE_VP_CLAMPED, 0}, SWIZZLE_XYZW},
193 };
194 
195 #define MATRIX(name, statevar, modifier)				\
196    static const struct gl_builtin_uniform_element name ## _elements[] = { \
197       { NULL, { statevar, 0, 0, 0, modifier}, SWIZZLE_XYZW },		\
198       { NULL, { statevar, 0, 1, 1, modifier}, SWIZZLE_XYZW },		\
199       { NULL, { statevar, 0, 2, 2, modifier}, SWIZZLE_XYZW },		\
200       { NULL, { statevar, 0, 3, 3, modifier}, SWIZZLE_XYZW },		\
201    }
202 
203 MATRIX(gl_ModelViewMatrix,
204        STATE_MODELVIEW_MATRIX, STATE_MATRIX_TRANSPOSE);
205 MATRIX(gl_ModelViewMatrixInverse,
206        STATE_MODELVIEW_MATRIX, STATE_MATRIX_INVTRANS);
207 MATRIX(gl_ModelViewMatrixTranspose,
208        STATE_MODELVIEW_MATRIX, 0);
209 MATRIX(gl_ModelViewMatrixInverseTranspose,
210        STATE_MODELVIEW_MATRIX, STATE_MATRIX_INVERSE);
211 
212 MATRIX(gl_ProjectionMatrix,
213        STATE_PROJECTION_MATRIX, STATE_MATRIX_TRANSPOSE);
214 MATRIX(gl_ProjectionMatrixInverse,
215        STATE_PROJECTION_MATRIX, STATE_MATRIX_INVTRANS);
216 MATRIX(gl_ProjectionMatrixTranspose,
217        STATE_PROJECTION_MATRIX, 0);
218 MATRIX(gl_ProjectionMatrixInverseTranspose,
219        STATE_PROJECTION_MATRIX, STATE_MATRIX_INVERSE);
220 
221 MATRIX(gl_ModelViewProjectionMatrix,
222        STATE_MVP_MATRIX, STATE_MATRIX_TRANSPOSE);
223 MATRIX(gl_ModelViewProjectionMatrixInverse,
224        STATE_MVP_MATRIX, STATE_MATRIX_INVTRANS);
225 MATRIX(gl_ModelViewProjectionMatrixTranspose,
226        STATE_MVP_MATRIX, 0);
227 MATRIX(gl_ModelViewProjectionMatrixInverseTranspose,
228        STATE_MVP_MATRIX, STATE_MATRIX_INVERSE);
229 
230 MATRIX(gl_TextureMatrix,
231        STATE_TEXTURE_MATRIX, STATE_MATRIX_TRANSPOSE);
232 MATRIX(gl_TextureMatrixInverse,
233        STATE_TEXTURE_MATRIX, STATE_MATRIX_INVTRANS);
234 MATRIX(gl_TextureMatrixTranspose,
235        STATE_TEXTURE_MATRIX, 0);
236 MATRIX(gl_TextureMatrixInverseTranspose,
237        STATE_TEXTURE_MATRIX, STATE_MATRIX_INVERSE);
238 
239 static const struct gl_builtin_uniform_element gl_NormalMatrix_elements[] = {
240    { NULL, { STATE_MODELVIEW_MATRIX, 0, 0, 0, STATE_MATRIX_INVERSE},
241      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z) },
242    { NULL, { STATE_MODELVIEW_MATRIX, 0, 1, 1, STATE_MATRIX_INVERSE},
243      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z) },
244    { NULL, { STATE_MODELVIEW_MATRIX, 0, 2, 2, STATE_MATRIX_INVERSE},
245      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z) },
246 };
247 
248 #undef MATRIX
249 
250 #define STATEVAR(name) {#name, name ## _elements, ARRAY_SIZE(name ## _elements)}
251 
252 static const struct gl_builtin_uniform_desc _mesa_builtin_uniform_desc[] = {
253    STATEVAR(gl_NumSamples),
254    STATEVAR(gl_DepthRange),
255    STATEVAR(gl_ClipPlane),
256    STATEVAR(gl_Point),
257    STATEVAR(gl_FrontMaterial),
258    STATEVAR(gl_BackMaterial),
259    STATEVAR(gl_LightSource),
260    STATEVAR(gl_LightModel),
261    STATEVAR(gl_FrontLightModelProduct),
262    STATEVAR(gl_BackLightModelProduct),
263    STATEVAR(gl_FrontLightProduct),
264    STATEVAR(gl_BackLightProduct),
265    STATEVAR(gl_TextureEnvColor),
266    STATEVAR(gl_EyePlaneS),
267    STATEVAR(gl_EyePlaneT),
268    STATEVAR(gl_EyePlaneR),
269    STATEVAR(gl_EyePlaneQ),
270    STATEVAR(gl_ObjectPlaneS),
271    STATEVAR(gl_ObjectPlaneT),
272    STATEVAR(gl_ObjectPlaneR),
273    STATEVAR(gl_ObjectPlaneQ),
274    STATEVAR(gl_Fog),
275 
276    STATEVAR(gl_ModelViewMatrix),
277    STATEVAR(gl_ModelViewMatrixInverse),
278    STATEVAR(gl_ModelViewMatrixTranspose),
279    STATEVAR(gl_ModelViewMatrixInverseTranspose),
280 
281    STATEVAR(gl_ProjectionMatrix),
282    STATEVAR(gl_ProjectionMatrixInverse),
283    STATEVAR(gl_ProjectionMatrixTranspose),
284    STATEVAR(gl_ProjectionMatrixInverseTranspose),
285 
286    STATEVAR(gl_ModelViewProjectionMatrix),
287    STATEVAR(gl_ModelViewProjectionMatrixInverse),
288    STATEVAR(gl_ModelViewProjectionMatrixTranspose),
289    STATEVAR(gl_ModelViewProjectionMatrixInverseTranspose),
290 
291    STATEVAR(gl_TextureMatrix),
292    STATEVAR(gl_TextureMatrixInverse),
293    STATEVAR(gl_TextureMatrixTranspose),
294    STATEVAR(gl_TextureMatrixInverseTranspose),
295 
296    STATEVAR(gl_NormalMatrix),
297    STATEVAR(gl_NormalScale),
298 
299    STATEVAR(gl_FogParamsOptimizedMESA),
300    STATEVAR(gl_CurrentAttribVertMESA),
301    STATEVAR(gl_CurrentAttribFragMESA),
302 
303    {NULL, NULL, 0}
304 };
305 
306 
307 namespace {
308 
309 /**
310  * Data structure that accumulates fields for the gl_PerVertex interface
311  * block.
312  */
313 class per_vertex_accumulator
314 {
315 public:
316    per_vertex_accumulator();
317    void add_field(int slot, const glsl_type *type, int precision,
318                   const char *name);
319    const glsl_type *construct_interface_instance() const;
320 
321 private:
322    glsl_struct_field fields[11];
323    unsigned num_fields;
324 };
325 
326 
per_vertex_accumulator()327 per_vertex_accumulator::per_vertex_accumulator()
328    : fields(),
329      num_fields(0)
330 {
331 }
332 
333 
334 void
add_field(int slot,const glsl_type * type,int precision,const char * name)335 per_vertex_accumulator::add_field(int slot, const glsl_type *type,
336                                   int precision, const char *name)
337 {
338    assert(this->num_fields < ARRAY_SIZE(this->fields));
339    this->fields[this->num_fields].type = type;
340    this->fields[this->num_fields].name = name;
341    this->fields[this->num_fields].matrix_layout = GLSL_MATRIX_LAYOUT_INHERITED;
342    this->fields[this->num_fields].location = slot;
343    this->fields[this->num_fields].offset = -1;
344    this->fields[this->num_fields].interpolation = INTERP_MODE_NONE;
345    this->fields[this->num_fields].centroid = 0;
346    this->fields[this->num_fields].sample = 0;
347    this->fields[this->num_fields].patch = 0;
348    this->fields[this->num_fields].precision = precision;
349    this->fields[this->num_fields].memory_read_only = 0;
350    this->fields[this->num_fields].memory_write_only = 0;
351    this->fields[this->num_fields].memory_coherent = 0;
352    this->fields[this->num_fields].memory_volatile = 0;
353    this->fields[this->num_fields].memory_restrict = 0;
354    this->fields[this->num_fields].image_format = PIPE_FORMAT_NONE;
355    this->fields[this->num_fields].explicit_xfb_buffer = 0;
356    this->fields[this->num_fields].xfb_buffer = -1;
357    this->fields[this->num_fields].xfb_stride = -1;
358    this->num_fields++;
359 }
360 
361 
362 const glsl_type *
construct_interface_instance() const363 per_vertex_accumulator::construct_interface_instance() const
364 {
365    return glsl_type::get_interface_instance(this->fields, this->num_fields,
366                                             GLSL_INTERFACE_PACKING_STD140,
367                                             false,
368                                             "gl_PerVertex");
369 }
370 
371 
372 class builtin_variable_generator
373 {
374 public:
375    builtin_variable_generator(exec_list *instructions,
376                               struct _mesa_glsl_parse_state *state);
377    void generate_constants();
378    void generate_uniforms();
379    void generate_special_vars();
380    void generate_vs_special_vars();
381    void generate_tcs_special_vars();
382    void generate_tes_special_vars();
383    void generate_gs_special_vars();
384    void generate_fs_special_vars();
385    void generate_cs_special_vars();
386    void generate_varyings();
387 
388 private:
array(const glsl_type * base,unsigned elements)389    const glsl_type *array(const glsl_type *base, unsigned elements)
390    {
391       return glsl_type::get_array_instance(base, elements);
392    }
393 
type(const char * name)394    const glsl_type *type(const char *name)
395    {
396       return symtab->get_type(name);
397    }
398 
add_input(int slot,const glsl_type * type,int precision,const char * name)399    ir_variable *add_input(int slot, const glsl_type *type, int precision,
400                           const char *name)
401    {
402       return add_variable(name, type, precision, ir_var_shader_in, slot);
403    }
404 
add_input(int slot,const glsl_type * type,const char * name)405    ir_variable *add_input(int slot, const glsl_type *type, const char *name)
406    {
407       return add_input(slot, type, GLSL_PRECISION_NONE, name);
408    }
409 
add_output(int slot,const glsl_type * type,int precision,const char * name)410    ir_variable *add_output(int slot, const glsl_type *type, int precision,
411                            const char *name)
412    {
413       return add_variable(name, type, precision, ir_var_shader_out, slot);
414    }
415 
add_output(int slot,const glsl_type * type,const char * name)416    ir_variable *add_output(int slot, const glsl_type *type, const char *name)
417    {
418       return add_output(slot, type, GLSL_PRECISION_NONE, name);
419    }
420 
add_index_output(int slot,int index,const glsl_type * type,int precision,const char * name)421    ir_variable *add_index_output(int slot, int index, const glsl_type *type,
422                                  int precision, const char *name)
423    {
424       return add_index_variable(name, type, precision, ir_var_shader_out, slot,
425                                 index);
426    }
427 
add_system_value(int slot,const glsl_type * type,int precision,const char * name)428    ir_variable *add_system_value(int slot, const glsl_type *type, int precision,
429                                  const char *name)
430    {
431       return add_variable(name, type, precision, ir_var_system_value, slot);
432    }
add_system_value(int slot,const glsl_type * type,const char * name)433    ir_variable *add_system_value(int slot, const glsl_type *type,
434                                  const char *name)
435    {
436       return add_system_value(slot, type, GLSL_PRECISION_NONE, name);
437    }
438 
439    ir_variable *add_variable(const char *name, const glsl_type *type,
440                              int precision, enum ir_variable_mode mode,
441                              int slot);
442    ir_variable *add_index_variable(const char *name, const glsl_type *type,
443                                    int precision, enum ir_variable_mode mode,
444                                    int slot, int index);
445    ir_variable *add_uniform(const glsl_type *type, int precision,
446                             const char *name);
add_uniform(const glsl_type * type,const char * name)447    ir_variable *add_uniform(const glsl_type *type, const char *name)
448    {
449       return add_uniform(type, GLSL_PRECISION_NONE, name);
450    }
451    ir_variable *add_const(const char *name, int precision, int value);
add_const(const char * name,int value)452    ir_variable *add_const(const char *name, int value)
453    {
454       return add_const(name, GLSL_PRECISION_MEDIUM, value);
455    }
456    ir_variable *add_const_ivec3(const char *name, int x, int y, int z);
457    void add_varying(int slot, const glsl_type *type, int precision,
458                     const char *name);
add_varying(int slot,const glsl_type * type,const char * name)459    void add_varying(int slot, const glsl_type *type, const char *name)
460    {
461       add_varying(slot, type, GLSL_PRECISION_NONE, name);
462    }
463 
464    exec_list * const instructions;
465    struct _mesa_glsl_parse_state * const state;
466    glsl_symbol_table * const symtab;
467 
468    /**
469     * True if compatibility-profile-only variables should be included.  (In
470     * desktop GL, these are always included when the GLSL version is 1.30 and
471     * or below).
472     */
473    const bool compatibility;
474 
475    const glsl_type * const bool_t;
476    const glsl_type * const int_t;
477    const glsl_type * const uint_t;
478    const glsl_type * const uint64_t;
479    const glsl_type * const float_t;
480    const glsl_type * const vec2_t;
481    const glsl_type * const vec3_t;
482    const glsl_type * const vec4_t;
483    const glsl_type * const uvec3_t;
484    const glsl_type * const mat3_t;
485    const glsl_type * const mat4_t;
486 
487    per_vertex_accumulator per_vertex_in;
488    per_vertex_accumulator per_vertex_out;
489 };
490 
491 
builtin_variable_generator(exec_list * instructions,struct _mesa_glsl_parse_state * state)492 builtin_variable_generator::builtin_variable_generator(
493    exec_list *instructions, struct _mesa_glsl_parse_state *state)
494    : instructions(instructions), state(state), symtab(state->symbols),
495      compatibility(state->compat_shader || state->ARB_compatibility_enable),
496      bool_t(glsl_type::bool_type), int_t(glsl_type::int_type),
497      uint_t(glsl_type::uint_type),
498      uint64_t(glsl_type::uint64_t_type),
499      float_t(glsl_type::float_type), vec2_t(glsl_type::vec2_type),
500      vec3_t(glsl_type::vec3_type), vec4_t(glsl_type::vec4_type),
501      uvec3_t(glsl_type::uvec3_type),
502      mat3_t(glsl_type::mat3_type), mat4_t(glsl_type::mat4_type)
503 {
504 }
505 
506 ir_variable *
add_index_variable(const char * name,const glsl_type * type,int precision,enum ir_variable_mode mode,int slot,int index)507 builtin_variable_generator::add_index_variable(const char *name,
508                                                const glsl_type *type,
509                                                int precision,
510                                                enum ir_variable_mode mode,
511                                                int slot, int index)
512 {
513    ir_variable *var = new(symtab) ir_variable(type, name, mode);
514    var->data.how_declared = ir_var_declared_implicitly;
515 
516    switch (var->data.mode) {
517    case ir_var_auto:
518    case ir_var_shader_in:
519    case ir_var_uniform:
520    case ir_var_system_value:
521       var->data.read_only = true;
522       break;
523    case ir_var_shader_out:
524    case ir_var_shader_storage:
525       break;
526    default:
527       /* The only variables that are added using this function should be
528        * uniforms, shader storage, shader inputs, and shader outputs, constants
529        * (which use ir_var_auto), and system values.
530        */
531       assert(0);
532       break;
533    }
534 
535    var->data.location = slot;
536    var->data.explicit_location = (slot >= 0);
537    var->data.explicit_index = 1;
538    var->data.index = index;
539 
540    if (state->es_shader)
541       var->data.precision = precision;
542 
543    /* Once the variable is created an initialized, add it to the symbol table
544     * and add the declaration to the IR stream.
545     */
546    instructions->push_tail(var);
547 
548    symtab->add_variable(var);
549    return var;
550 }
551 
552 ir_variable *
add_variable(const char * name,const glsl_type * type,int precision,enum ir_variable_mode mode,int slot)553 builtin_variable_generator::add_variable(const char *name,
554                                          const glsl_type *type,
555                                          int precision,
556                                          enum ir_variable_mode mode, int slot)
557 {
558    ir_variable *var = new(symtab) ir_variable(type, name, mode);
559    var->data.how_declared = ir_var_declared_implicitly;
560 
561    switch (var->data.mode) {
562    case ir_var_auto:
563    case ir_var_shader_in:
564    case ir_var_uniform:
565    case ir_var_system_value:
566       var->data.read_only = true;
567       break;
568    case ir_var_shader_out:
569    case ir_var_shader_storage:
570       break;
571    default:
572       /* The only variables that are added using this function should be
573        * uniforms, shader storage, shader inputs, and shader outputs, constants
574        * (which use ir_var_auto), and system values.
575        */
576       assert(0);
577       break;
578    }
579 
580    var->data.location = slot;
581    var->data.explicit_location = (slot >= 0);
582    var->data.explicit_index = 0;
583 
584    if (state->es_shader)
585       var->data.precision = precision;
586 
587    /* Once the variable is created an initialized, add it to the symbol table
588     * and add the declaration to the IR stream.
589     */
590    instructions->push_tail(var);
591 
592    symtab->add_variable(var);
593    return var;
594 }
595 
596 extern "C" const struct gl_builtin_uniform_desc *
_mesa_glsl_get_builtin_uniform_desc(const char * name)597 _mesa_glsl_get_builtin_uniform_desc(const char *name)
598 {
599    for (unsigned i = 0; _mesa_builtin_uniform_desc[i].name != NULL; i++) {
600       if (strcmp(_mesa_builtin_uniform_desc[i].name, name) == 0) {
601          return &_mesa_builtin_uniform_desc[i];
602       }
603    }
604    return NULL;
605 }
606 
607 ir_variable *
add_uniform(const glsl_type * type,int precision,const char * name)608 builtin_variable_generator::add_uniform(const glsl_type *type,
609                                         int precision,
610                                         const char *name)
611 {
612    ir_variable *const uni =
613       add_variable(name, type, precision, ir_var_uniform, -1);
614 
615    const struct gl_builtin_uniform_desc* const statevar =
616       _mesa_glsl_get_builtin_uniform_desc(name);
617    assert(statevar != NULL);
618 
619    const unsigned array_count = type->is_array() ? type->length : 1;
620 
621    ir_state_slot *slots =
622       uni->allocate_state_slots(array_count * statevar->num_elements);
623 
624    for (unsigned a = 0; a < array_count; a++) {
625       for (unsigned j = 0; j < statevar->num_elements; j++) {
626 	 const struct gl_builtin_uniform_element *element =
627 	    &statevar->elements[j];
628 
629 	 memcpy(slots->tokens, element->tokens, sizeof(element->tokens));
630 	 if (type->is_array()) {
631 	    if (strcmp(name, "gl_CurrentAttribVertMESA") == 0 ||
632 		strcmp(name, "gl_CurrentAttribFragMESA") == 0) {
633 	       slots->tokens[2] = a;
634 	    } else {
635 	       slots->tokens[1] = a;
636 	    }
637 	 }
638 
639 	 slots->swizzle = element->swizzle;
640 	 slots++;
641       }
642    }
643 
644    return uni;
645 }
646 
647 
648 ir_variable *
add_const(const char * name,int precision,int value)649 builtin_variable_generator::add_const(const char *name, int precision,
650                                       int value)
651 {
652    ir_variable *const var = add_variable(name, glsl_type::int_type,
653                                          precision, ir_var_auto, -1);
654    var->constant_value = new(var) ir_constant(value);
655    var->constant_initializer = new(var) ir_constant(value);
656    var->data.has_initializer = true;
657    return var;
658 }
659 
660 
661 ir_variable *
add_const_ivec3(const char * name,int x,int y,int z)662 builtin_variable_generator::add_const_ivec3(const char *name, int x, int y,
663                                             int z)
664 {
665    ir_variable *const var = add_variable(name, glsl_type::ivec3_type,
666                                          GLSL_PRECISION_HIGH,
667                                          ir_var_auto, -1);
668    ir_constant_data data;
669    memset(&data, 0, sizeof(data));
670    data.i[0] = x;
671    data.i[1] = y;
672    data.i[2] = z;
673    var->constant_value = new(var) ir_constant(glsl_type::ivec3_type, &data);
674    var->constant_initializer =
675       new(var) ir_constant(glsl_type::ivec3_type, &data);
676    var->data.has_initializer = true;
677    return var;
678 }
679 
680 
681 void
generate_constants()682 builtin_variable_generator::generate_constants()
683 {
684    add_const("gl_MaxVertexAttribs", state->Const.MaxVertexAttribs);
685    add_const("gl_MaxVertexTextureImageUnits",
686              state->Const.MaxVertexTextureImageUnits);
687    add_const("gl_MaxCombinedTextureImageUnits",
688              state->Const.MaxCombinedTextureImageUnits);
689    add_const("gl_MaxTextureImageUnits", state->Const.MaxTextureImageUnits);
690    add_const("gl_MaxDrawBuffers", state->Const.MaxDrawBuffers);
691 
692    /* Max uniforms/varyings: GLSL ES counts these in units of vectors; desktop
693     * GL counts them in units of "components" or "floats" and also in units
694     * of vectors since GL 4.1
695     */
696    if (!state->es_shader) {
697       add_const("gl_MaxFragmentUniformComponents",
698                 state->Const.MaxFragmentUniformComponents);
699       add_const("gl_MaxVertexUniformComponents",
700                 state->Const.MaxVertexUniformComponents);
701    }
702 
703    if (state->is_version(410, 100)) {
704       add_const("gl_MaxVertexUniformVectors",
705                 state->Const.MaxVertexUniformComponents / 4);
706       add_const("gl_MaxFragmentUniformVectors",
707                 state->Const.MaxFragmentUniformComponents / 4);
708 
709       /* In GLSL ES 3.00, gl_MaxVaryingVectors was split out to separate
710        * vertex and fragment shader constants.
711        */
712       if (state->is_version(0, 300)) {
713          add_const("gl_MaxVertexOutputVectors",
714                    state->ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents / 4);
715          add_const("gl_MaxFragmentInputVectors",
716                    state->ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents / 4);
717       } else {
718          add_const("gl_MaxVaryingVectors",
719                    state->ctx->Const.MaxVarying);
720       }
721 
722       /* EXT_blend_func_extended brings a built in constant
723        * for determining number of dual source draw buffers
724        */
725       if (state->EXT_blend_func_extended_enable) {
726          add_const("gl_MaxDualSourceDrawBuffersEXT",
727                    state->Const.MaxDualSourceDrawBuffers);
728       }
729    } else {
730       /* Note: gl_MaxVaryingFloats was deprecated in GLSL 1.30+, but not
731        * removed
732        */
733       add_const("gl_MaxVaryingFloats", state->ctx->Const.MaxVarying * 4);
734    }
735 
736    /* Texel offsets were introduced in ARB_shading_language_420pack (which
737     * requires desktop GLSL version 130), and adopted into desktop GLSL
738     * version 4.20 and GLSL ES version 3.00.
739     */
740    if ((state->is_version(130, 0) &&
741         state->ARB_shading_language_420pack_enable) ||
742       state->is_version(420, 300)) {
743       add_const("gl_MinProgramTexelOffset",
744                 state->Const.MinProgramTexelOffset);
745       add_const("gl_MaxProgramTexelOffset",
746                 state->Const.MaxProgramTexelOffset);
747    }
748 
749    if (state->has_clip_distance()) {
750       add_const("gl_MaxClipDistances", state->Const.MaxClipPlanes);
751    }
752    if (state->is_version(130, 0)) {
753       add_const("gl_MaxVaryingComponents", state->ctx->Const.MaxVarying * 4);
754    }
755    if (state->has_cull_distance()) {
756       add_const("gl_MaxCullDistances", state->Const.MaxClipPlanes);
757       add_const("gl_MaxCombinedClipAndCullDistances",
758                 state->Const.MaxClipPlanes);
759    }
760 
761    if (state->has_geometry_shader()) {
762       add_const("gl_MaxVertexOutputComponents",
763                 state->Const.MaxVertexOutputComponents);
764       add_const("gl_MaxGeometryInputComponents",
765                 state->Const.MaxGeometryInputComponents);
766       add_const("gl_MaxGeometryOutputComponents",
767                 state->Const.MaxGeometryOutputComponents);
768       add_const("gl_MaxFragmentInputComponents",
769                 state->Const.MaxFragmentInputComponents);
770       add_const("gl_MaxGeometryTextureImageUnits",
771                 state->Const.MaxGeometryTextureImageUnits);
772       add_const("gl_MaxGeometryOutputVertices",
773                 state->Const.MaxGeometryOutputVertices);
774       add_const("gl_MaxGeometryTotalOutputComponents",
775                 state->Const.MaxGeometryTotalOutputComponents);
776       add_const("gl_MaxGeometryUniformComponents",
777                 state->Const.MaxGeometryUniformComponents);
778 
779       /* Note: the GLSL 1.50-4.40 specs require
780        * gl_MaxGeometryVaryingComponents to be present, and to be at least 64.
781        * But they do not define what it means (and there does not appear to be
782        * any corresponding constant in the GL specs).  However,
783        * ARB_geometry_shader4 defines MAX_GEOMETRY_VARYING_COMPONENTS_ARB to
784        * be the maximum number of components available for use as geometry
785        * outputs.  So we assume this is a synonym for
786        * gl_MaxGeometryOutputComponents.
787        */
788       add_const("gl_MaxGeometryVaryingComponents",
789                 state->Const.MaxGeometryOutputComponents);
790    }
791 
792    if (compatibility) {
793       /* Note: gl_MaxLights stopped being listed as an explicit constant in
794        * GLSL 1.30, however it continues to be referred to (as a minimum size
795        * for compatibility-mode uniforms) all the way up through GLSL 4.30, so
796        * this seems like it was probably an oversight.
797        */
798       add_const("gl_MaxLights", state->Const.MaxLights);
799 
800       add_const("gl_MaxClipPlanes", state->Const.MaxClipPlanes);
801 
802       /* Note: gl_MaxTextureUnits wasn't made compatibility-only until GLSL
803        * 1.50, however this seems like it was probably an oversight.
804        */
805       add_const("gl_MaxTextureUnits", state->Const.MaxTextureUnits);
806 
807       /* Note: gl_MaxTextureCoords was left out of GLSL 1.40, but it was
808        * re-introduced in GLSL 1.50, so this seems like it was probably an
809        * oversight.
810        */
811       add_const("gl_MaxTextureCoords", state->Const.MaxTextureCoords);
812    }
813 
814    if (state->has_atomic_counters()) {
815       add_const("gl_MaxVertexAtomicCounters",
816                 state->Const.MaxVertexAtomicCounters);
817       add_const("gl_MaxFragmentAtomicCounters",
818                 state->Const.MaxFragmentAtomicCounters);
819       add_const("gl_MaxCombinedAtomicCounters",
820                 state->Const.MaxCombinedAtomicCounters);
821       add_const("gl_MaxAtomicCounterBindings",
822                 state->Const.MaxAtomicBufferBindings);
823 
824       if (state->has_geometry_shader()) {
825          add_const("gl_MaxGeometryAtomicCounters",
826                    state->Const.MaxGeometryAtomicCounters);
827       }
828       if (state->is_version(110, 320)) {
829          add_const("gl_MaxTessControlAtomicCounters",
830                    state->Const.MaxTessControlAtomicCounters);
831          add_const("gl_MaxTessEvaluationAtomicCounters",
832                    state->Const.MaxTessEvaluationAtomicCounters);
833       }
834    }
835 
836    if (state->is_version(420, 310)) {
837       add_const("gl_MaxVertexAtomicCounterBuffers",
838                 state->Const.MaxVertexAtomicCounterBuffers);
839       add_const("gl_MaxFragmentAtomicCounterBuffers",
840                 state->Const.MaxFragmentAtomicCounterBuffers);
841       add_const("gl_MaxCombinedAtomicCounterBuffers",
842                 state->Const.MaxCombinedAtomicCounterBuffers);
843       add_const("gl_MaxAtomicCounterBufferSize",
844                 state->Const.MaxAtomicCounterBufferSize);
845 
846       if (state->has_geometry_shader()) {
847          add_const("gl_MaxGeometryAtomicCounterBuffers",
848                    state->Const.MaxGeometryAtomicCounterBuffers);
849       }
850       if (state->is_version(110, 320)) {
851          add_const("gl_MaxTessControlAtomicCounterBuffers",
852                    state->Const.MaxTessControlAtomicCounterBuffers);
853          add_const("gl_MaxTessEvaluationAtomicCounterBuffers",
854                    state->Const.MaxTessEvaluationAtomicCounterBuffers);
855       }
856    }
857 
858    if (state->is_version(430, 310) || state->ARB_compute_shader_enable) {
859       add_const("gl_MaxComputeAtomicCounterBuffers",
860                 state->Const.MaxComputeAtomicCounterBuffers);
861       add_const("gl_MaxComputeAtomicCounters",
862                 state->Const.MaxComputeAtomicCounters);
863       add_const("gl_MaxComputeImageUniforms",
864                 state->Const.MaxComputeImageUniforms);
865       add_const("gl_MaxComputeTextureImageUnits",
866                 state->Const.MaxComputeTextureImageUnits);
867       add_const("gl_MaxComputeUniformComponents",
868                 state->Const.MaxComputeUniformComponents);
869 
870       add_const_ivec3("gl_MaxComputeWorkGroupCount",
871                       state->Const.MaxComputeWorkGroupCount[0],
872                       state->Const.MaxComputeWorkGroupCount[1],
873                       state->Const.MaxComputeWorkGroupCount[2]);
874       add_const_ivec3("gl_MaxComputeWorkGroupSize",
875                       state->Const.MaxComputeWorkGroupSize[0],
876                       state->Const.MaxComputeWorkGroupSize[1],
877                       state->Const.MaxComputeWorkGroupSize[2]);
878 
879       /* From the GLSL 4.40 spec, section 7.1 (Built-In Language Variables):
880        *
881        *     The built-in constant gl_WorkGroupSize is a compute-shader
882        *     constant containing the local work-group size of the shader.  The
883        *     size of the work group in the X, Y, and Z dimensions is stored in
884        *     the x, y, and z components.  The constants values in
885        *     gl_WorkGroupSize will match those specified in the required
886        *     local_size_x, local_size_y, and local_size_z layout qualifiers
887        *     for the current shader.  This is a constant so that it can be
888        *     used to size arrays of memory that can be shared within the local
889        *     work group.  It is a compile-time error to use gl_WorkGroupSize
890        *     in a shader that does not declare a fixed local group size, or
891        *     before that shader has declared a fixed local group size, using
892        *     local_size_x, local_size_y, and local_size_z.
893        *
894        * To prevent the shader from trying to refer to gl_WorkGroupSize before
895        * the layout declaration, we don't define it here.  Intead we define it
896        * in ast_cs_input_layout::hir().
897        */
898    }
899 
900    if (state->has_enhanced_layouts()) {
901       add_const("gl_MaxTransformFeedbackBuffers",
902                 state->Const.MaxTransformFeedbackBuffers);
903       add_const("gl_MaxTransformFeedbackInterleavedComponents",
904                 state->Const.MaxTransformFeedbackInterleavedComponents);
905    }
906 
907    if (state->has_shader_image_load_store()) {
908       add_const("gl_MaxImageUnits",
909                 state->Const.MaxImageUnits);
910       add_const("gl_MaxVertexImageUniforms",
911                 state->Const.MaxVertexImageUniforms);
912       add_const("gl_MaxFragmentImageUniforms",
913                 state->Const.MaxFragmentImageUniforms);
914       add_const("gl_MaxCombinedImageUniforms",
915                 state->Const.MaxCombinedImageUniforms);
916 
917       if (state->has_geometry_shader()) {
918          add_const("gl_MaxGeometryImageUniforms",
919                    state->Const.MaxGeometryImageUniforms);
920       }
921 
922       if (!state->es_shader) {
923          add_const("gl_MaxCombinedImageUnitsAndFragmentOutputs",
924                    state->Const.MaxCombinedShaderOutputResources);
925          add_const("gl_MaxImageSamples",
926                    state->Const.MaxImageSamples);
927       }
928 
929       if (state->has_tessellation_shader()) {
930          add_const("gl_MaxTessControlImageUniforms",
931                    state->Const.MaxTessControlImageUniforms);
932          add_const("gl_MaxTessEvaluationImageUniforms",
933                    state->Const.MaxTessEvaluationImageUniforms);
934       }
935    }
936 
937    if (state->is_version(440, 310) ||
938        state->ARB_ES3_1_compatibility_enable) {
939       add_const("gl_MaxCombinedShaderOutputResources",
940                 state->Const.MaxCombinedShaderOutputResources);
941    }
942 
943    if (state->is_version(410, 0) ||
944        state->ARB_viewport_array_enable ||
945        state->OES_viewport_array_enable) {
946       add_const("gl_MaxViewports", GLSL_PRECISION_HIGH,
947                 state->Const.MaxViewports);
948    }
949 
950    if (state->has_tessellation_shader()) {
951       add_const("gl_MaxPatchVertices", state->Const.MaxPatchVertices);
952       add_const("gl_MaxTessGenLevel", state->Const.MaxTessGenLevel);
953       add_const("gl_MaxTessControlInputComponents", state->Const.MaxTessControlInputComponents);
954       add_const("gl_MaxTessControlOutputComponents", state->Const.MaxTessControlOutputComponents);
955       add_const("gl_MaxTessControlTextureImageUnits", state->Const.MaxTessControlTextureImageUnits);
956       add_const("gl_MaxTessEvaluationInputComponents", state->Const.MaxTessEvaluationInputComponents);
957       add_const("gl_MaxTessEvaluationOutputComponents", state->Const.MaxTessEvaluationOutputComponents);
958       add_const("gl_MaxTessEvaluationTextureImageUnits", state->Const.MaxTessEvaluationTextureImageUnits);
959       add_const("gl_MaxTessPatchComponents", state->Const.MaxTessPatchComponents);
960       add_const("gl_MaxTessControlTotalOutputComponents", state->Const.MaxTessControlTotalOutputComponents);
961       add_const("gl_MaxTessControlUniformComponents", state->Const.MaxTessControlUniformComponents);
962       add_const("gl_MaxTessEvaluationUniformComponents", state->Const.MaxTessEvaluationUniformComponents);
963    }
964 
965    if (state->is_version(450, 320) ||
966        state->OES_sample_variables_enable ||
967        state->ARB_ES3_1_compatibility_enable)
968       add_const("gl_MaxSamples", state->Const.MaxSamples);
969 }
970 
971 
972 /**
973  * Generate uniform variables (which exist in all types of shaders).
974  */
975 void
generate_uniforms()976 builtin_variable_generator::generate_uniforms()
977 {
978    if (state->is_version(400, 320) ||
979        state->ARB_sample_shading_enable ||
980        state->OES_sample_variables_enable)
981       add_uniform(int_t, GLSL_PRECISION_LOW, "gl_NumSamples");
982    add_uniform(type("gl_DepthRangeParameters"), "gl_DepthRange");
983    add_uniform(array(vec4_t, VERT_ATTRIB_MAX), "gl_CurrentAttribVertMESA");
984    add_uniform(array(vec4_t, VARYING_SLOT_MAX), "gl_CurrentAttribFragMESA");
985 
986    if (compatibility) {
987       add_uniform(mat4_t, "gl_ModelViewMatrix");
988       add_uniform(mat4_t, "gl_ProjectionMatrix");
989       add_uniform(mat4_t, "gl_ModelViewProjectionMatrix");
990       add_uniform(mat3_t, "gl_NormalMatrix");
991       add_uniform(mat4_t, "gl_ModelViewMatrixInverse");
992       add_uniform(mat4_t, "gl_ProjectionMatrixInverse");
993       add_uniform(mat4_t, "gl_ModelViewProjectionMatrixInverse");
994       add_uniform(mat4_t, "gl_ModelViewMatrixTranspose");
995       add_uniform(mat4_t, "gl_ProjectionMatrixTranspose");
996       add_uniform(mat4_t, "gl_ModelViewProjectionMatrixTranspose");
997       add_uniform(mat4_t, "gl_ModelViewMatrixInverseTranspose");
998       add_uniform(mat4_t, "gl_ProjectionMatrixInverseTranspose");
999       add_uniform(mat4_t, "gl_ModelViewProjectionMatrixInverseTranspose");
1000       add_uniform(float_t, "gl_NormalScale");
1001       add_uniform(type("gl_LightModelParameters"), "gl_LightModel");
1002       add_uniform(vec4_t, "gl_FogParamsOptimizedMESA");
1003 
1004       const glsl_type *const mat4_array_type =
1005 	 array(mat4_t, state->Const.MaxTextureCoords);
1006       add_uniform(mat4_array_type, "gl_TextureMatrix");
1007       add_uniform(mat4_array_type, "gl_TextureMatrixInverse");
1008       add_uniform(mat4_array_type, "gl_TextureMatrixTranspose");
1009       add_uniform(mat4_array_type, "gl_TextureMatrixInverseTranspose");
1010 
1011       add_uniform(array(vec4_t, state->Const.MaxClipPlanes), "gl_ClipPlane");
1012       add_uniform(type("gl_PointParameters"), "gl_Point");
1013 
1014       const glsl_type *const material_parameters_type =
1015 	 type("gl_MaterialParameters");
1016       add_uniform(material_parameters_type, "gl_FrontMaterial");
1017       add_uniform(material_parameters_type, "gl_BackMaterial");
1018 
1019       add_uniform(array(type("gl_LightSourceParameters"),
1020                         state->Const.MaxLights),
1021                   "gl_LightSource");
1022 
1023       const glsl_type *const light_model_products_type =
1024          type("gl_LightModelProducts");
1025       add_uniform(light_model_products_type, "gl_FrontLightModelProduct");
1026       add_uniform(light_model_products_type, "gl_BackLightModelProduct");
1027 
1028       const glsl_type *const light_products_type =
1029          array(type("gl_LightProducts"), state->Const.MaxLights);
1030       add_uniform(light_products_type, "gl_FrontLightProduct");
1031       add_uniform(light_products_type, "gl_BackLightProduct");
1032 
1033       add_uniform(array(vec4_t, state->Const.MaxTextureUnits),
1034                   "gl_TextureEnvColor");
1035 
1036       const glsl_type *const texcoords_vec4 =
1037 	 array(vec4_t, state->Const.MaxTextureCoords);
1038       add_uniform(texcoords_vec4, "gl_EyePlaneS");
1039       add_uniform(texcoords_vec4, "gl_EyePlaneT");
1040       add_uniform(texcoords_vec4, "gl_EyePlaneR");
1041       add_uniform(texcoords_vec4, "gl_EyePlaneQ");
1042       add_uniform(texcoords_vec4, "gl_ObjectPlaneS");
1043       add_uniform(texcoords_vec4, "gl_ObjectPlaneT");
1044       add_uniform(texcoords_vec4, "gl_ObjectPlaneR");
1045       add_uniform(texcoords_vec4, "gl_ObjectPlaneQ");
1046 
1047       add_uniform(type("gl_FogParameters"), "gl_Fog");
1048    }
1049 }
1050 
1051 
1052 /**
1053  * Generate special variables which exist in all shaders.
1054  */
1055 void
generate_special_vars()1056 builtin_variable_generator::generate_special_vars()
1057 {
1058    if (state->ARB_shader_ballot_enable) {
1059       add_system_value(SYSTEM_VALUE_SUBGROUP_SIZE, uint_t, "gl_SubGroupSizeARB");
1060       add_system_value(SYSTEM_VALUE_SUBGROUP_INVOCATION, uint_t, "gl_SubGroupInvocationARB");
1061       add_system_value(SYSTEM_VALUE_SUBGROUP_EQ_MASK, uint64_t, "gl_SubGroupEqMaskARB");
1062       add_system_value(SYSTEM_VALUE_SUBGROUP_GE_MASK, uint64_t, "gl_SubGroupGeMaskARB");
1063       add_system_value(SYSTEM_VALUE_SUBGROUP_GT_MASK, uint64_t, "gl_SubGroupGtMaskARB");
1064       add_system_value(SYSTEM_VALUE_SUBGROUP_LE_MASK, uint64_t, "gl_SubGroupLeMaskARB");
1065       add_system_value(SYSTEM_VALUE_SUBGROUP_LT_MASK, uint64_t, "gl_SubGroupLtMaskARB");
1066    }
1067 }
1068 
1069 
1070 /**
1071  * Generate variables which only exist in vertex shaders.
1072  */
1073 void
generate_vs_special_vars()1074 builtin_variable_generator::generate_vs_special_vars()
1075 {
1076    ir_variable *var;
1077 
1078    if (state->is_version(130, 300) || state->EXT_gpu_shader4_enable) {
1079       add_system_value(SYSTEM_VALUE_VERTEX_ID, int_t, GLSL_PRECISION_HIGH,
1080                        "gl_VertexID");
1081    }
1082    if (state->is_version(460, 0)) {
1083       add_system_value(SYSTEM_VALUE_BASE_VERTEX, int_t, "gl_BaseVertex");
1084       add_system_value(SYSTEM_VALUE_BASE_INSTANCE, int_t, "gl_BaseInstance");
1085       add_system_value(SYSTEM_VALUE_DRAW_ID, int_t, "gl_DrawID");
1086    }
1087    if (state->EXT_draw_instanced_enable && state->is_version(0, 100))
1088       add_system_value(SYSTEM_VALUE_INSTANCE_ID, int_t, GLSL_PRECISION_HIGH,
1089                        "gl_InstanceIDEXT");
1090 
1091    if (state->ARB_draw_instanced_enable)
1092       add_system_value(SYSTEM_VALUE_INSTANCE_ID, int_t, "gl_InstanceIDARB");
1093 
1094    if (state->ARB_draw_instanced_enable || state->is_version(140, 300) ||
1095        state->EXT_gpu_shader4_enable) {
1096       add_system_value(SYSTEM_VALUE_INSTANCE_ID, int_t, GLSL_PRECISION_HIGH,
1097                        "gl_InstanceID");
1098    }
1099    if (state->ARB_shader_draw_parameters_enable) {
1100       add_system_value(SYSTEM_VALUE_BASE_VERTEX, int_t, "gl_BaseVertexARB");
1101       add_system_value(SYSTEM_VALUE_BASE_INSTANCE, int_t, "gl_BaseInstanceARB");
1102       add_system_value(SYSTEM_VALUE_DRAW_ID, int_t, "gl_DrawIDARB");
1103    }
1104    if (state->AMD_vertex_shader_layer_enable ||
1105        state->ARB_shader_viewport_layer_array_enable ||
1106        state->NV_viewport_array2_enable) {
1107       var = add_output(VARYING_SLOT_LAYER, int_t, "gl_Layer");
1108       var->data.interpolation = INTERP_MODE_FLAT;
1109    }
1110    if (state->AMD_vertex_shader_viewport_index_enable ||
1111        state->ARB_shader_viewport_layer_array_enable ||
1112        state->NV_viewport_array2_enable) {
1113       var = add_output(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex");
1114       var->data.interpolation = INTERP_MODE_FLAT;
1115    }
1116    if (state->NV_viewport_array2_enable) {
1117       /* From the NV_viewport_array2 specification:
1118        *
1119        *    "The variable gl_ViewportMask[] is available as an output variable
1120        *    in the VTG languages. The array has ceil(v/32) elements where v is
1121        *    the maximum number of viewports supported by the implementation."
1122        *
1123        * Since no drivers expose more than 16 viewports, we can simply set the
1124        * array size to 1 rather than computing it and dealing with varying
1125        * slot complication.
1126        */
1127       var = add_output(VARYING_SLOT_VIEWPORT_MASK, array(int_t, 1),
1128                        "gl_ViewportMask");
1129       var->data.interpolation = INTERP_MODE_FLAT;
1130    }
1131    if (compatibility) {
1132       add_input(VERT_ATTRIB_POS, vec4_t, "gl_Vertex");
1133       add_input(VERT_ATTRIB_NORMAL, vec3_t, "gl_Normal");
1134       add_input(VERT_ATTRIB_COLOR0, vec4_t, "gl_Color");
1135       add_input(VERT_ATTRIB_COLOR1, vec4_t, "gl_SecondaryColor");
1136       add_input(VERT_ATTRIB_TEX0, vec4_t, "gl_MultiTexCoord0");
1137       add_input(VERT_ATTRIB_TEX1, vec4_t, "gl_MultiTexCoord1");
1138       add_input(VERT_ATTRIB_TEX2, vec4_t, "gl_MultiTexCoord2");
1139       add_input(VERT_ATTRIB_TEX3, vec4_t, "gl_MultiTexCoord3");
1140       add_input(VERT_ATTRIB_TEX4, vec4_t, "gl_MultiTexCoord4");
1141       add_input(VERT_ATTRIB_TEX5, vec4_t, "gl_MultiTexCoord5");
1142       add_input(VERT_ATTRIB_TEX6, vec4_t, "gl_MultiTexCoord6");
1143       add_input(VERT_ATTRIB_TEX7, vec4_t, "gl_MultiTexCoord7");
1144       add_input(VERT_ATTRIB_FOG, float_t, "gl_FogCoord");
1145    }
1146 }
1147 
1148 
1149 /**
1150  * Generate variables which only exist in tessellation control shaders.
1151  */
1152 void
generate_tcs_special_vars()1153 builtin_variable_generator::generate_tcs_special_vars()
1154 {
1155    add_system_value(SYSTEM_VALUE_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1156                     "gl_PrimitiveID");
1157    add_system_value(SYSTEM_VALUE_INVOCATION_ID, int_t, GLSL_PRECISION_HIGH,
1158                     "gl_InvocationID");
1159    add_system_value(SYSTEM_VALUE_VERTICES_IN, int_t, GLSL_PRECISION_HIGH,
1160                     "gl_PatchVerticesIn");
1161 
1162    add_output(VARYING_SLOT_TESS_LEVEL_OUTER, array(float_t, 4),
1163               GLSL_PRECISION_HIGH, "gl_TessLevelOuter")->data.patch = 1;
1164    add_output(VARYING_SLOT_TESS_LEVEL_INNER, array(float_t, 2),
1165               GLSL_PRECISION_HIGH, "gl_TessLevelInner")->data.patch = 1;
1166    /* XXX What to do if multiple are flipped on? */
1167    int bbox_slot = state->ctx->Const.NoPrimitiveBoundingBoxOutput ? -1 :
1168       VARYING_SLOT_BOUNDING_BOX0;
1169    if (state->EXT_primitive_bounding_box_enable)
1170       add_output(bbox_slot, array(vec4_t, 2), "gl_BoundingBoxEXT")
1171          ->data.patch = 1;
1172    if (state->OES_primitive_bounding_box_enable) {
1173       add_output(bbox_slot, array(vec4_t, 2), GLSL_PRECISION_HIGH,
1174                  "gl_BoundingBoxOES")->data.patch = 1;
1175    }
1176    if (state->is_version(0, 320) || state->ARB_ES3_2_compatibility_enable) {
1177       add_output(bbox_slot, array(vec4_t, 2), GLSL_PRECISION_HIGH,
1178                  "gl_BoundingBox")->data.patch = 1;
1179    }
1180 
1181    /* NOTE: These are completely pointless. Writing these will never go
1182     * anywhere. But the specs demands it. So we add them with a slot of -1,
1183     * which makes the data go nowhere.
1184     */
1185    if (state->NV_viewport_array2_enable) {
1186       add_output(-1, int_t, "gl_Layer");
1187       add_output(-1, int_t, "gl_ViewportIndex");
1188       add_output(-1, array(int_t, 1), "gl_ViewportMask");
1189    }
1190 
1191 }
1192 
1193 
1194 /**
1195  * Generate variables which only exist in tessellation evaluation shaders.
1196  */
1197 void
generate_tes_special_vars()1198 builtin_variable_generator::generate_tes_special_vars()
1199 {
1200    ir_variable *var;
1201 
1202    add_system_value(SYSTEM_VALUE_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1203                     "gl_PrimitiveID");
1204    add_system_value(SYSTEM_VALUE_VERTICES_IN, int_t, GLSL_PRECISION_HIGH,
1205                     "gl_PatchVerticesIn");
1206    add_system_value(SYSTEM_VALUE_TESS_COORD, vec3_t, GLSL_PRECISION_HIGH,
1207                     "gl_TessCoord");
1208    if (this->state->ctx->Const.GLSLTessLevelsAsInputs) {
1209       add_input(VARYING_SLOT_TESS_LEVEL_OUTER, array(float_t, 4),
1210                 GLSL_PRECISION_HIGH, "gl_TessLevelOuter")->data.patch = 1;
1211       add_input(VARYING_SLOT_TESS_LEVEL_INNER, array(float_t, 2),
1212                 GLSL_PRECISION_HIGH, "gl_TessLevelInner")->data.patch = 1;
1213    } else {
1214       add_system_value(SYSTEM_VALUE_TESS_LEVEL_OUTER, array(float_t, 4),
1215                        GLSL_PRECISION_HIGH, "gl_TessLevelOuter");
1216       add_system_value(SYSTEM_VALUE_TESS_LEVEL_INNER, array(float_t, 2),
1217                        GLSL_PRECISION_HIGH, "gl_TessLevelInner");
1218    }
1219    if (state->ARB_shader_viewport_layer_array_enable ||
1220        state->NV_viewport_array2_enable) {
1221       var = add_output(VARYING_SLOT_LAYER, int_t, "gl_Layer");
1222       var->data.interpolation = INTERP_MODE_FLAT;
1223       var = add_output(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex");
1224       var->data.interpolation = INTERP_MODE_FLAT;
1225    }
1226    if (state->NV_viewport_array2_enable) {
1227       var = add_output(VARYING_SLOT_VIEWPORT_MASK, array(int_t, 1),
1228                        "gl_ViewportMask");
1229       var->data.interpolation = INTERP_MODE_FLAT;
1230    }
1231 }
1232 
1233 
1234 /**
1235  * Generate variables which only exist in geometry shaders.
1236  */
1237 void
generate_gs_special_vars()1238 builtin_variable_generator::generate_gs_special_vars()
1239 {
1240    ir_variable *var;
1241 
1242    var = add_output(VARYING_SLOT_LAYER, int_t, GLSL_PRECISION_HIGH, "gl_Layer");
1243    var->data.interpolation = INTERP_MODE_FLAT;
1244    if (state->is_version(410, 0) || state->ARB_viewport_array_enable ||
1245        state->OES_viewport_array_enable) {
1246       var = add_output(VARYING_SLOT_VIEWPORT, int_t, GLSL_PRECISION_HIGH,
1247                        "gl_ViewportIndex");
1248       var->data.interpolation = INTERP_MODE_FLAT;
1249    }
1250    if (state->NV_viewport_array2_enable) {
1251       var = add_output(VARYING_SLOT_VIEWPORT_MASK, array(int_t, 1),
1252                        "gl_ViewportMask");
1253       var->data.interpolation = INTERP_MODE_FLAT;
1254    }
1255    if (state->is_version(400, 320) || state->ARB_gpu_shader5_enable ||
1256        state->OES_geometry_shader_enable || state->EXT_geometry_shader_enable) {
1257       add_system_value(SYSTEM_VALUE_INVOCATION_ID, int_t, GLSL_PRECISION_HIGH,
1258                        "gl_InvocationID");
1259    }
1260 
1261    /* Although gl_PrimitiveID appears in tessellation control and tessellation
1262     * evaluation shaders, it has a different function there than it has in
1263     * geometry shaders, so we treat it (and its counterpart gl_PrimitiveIDIn)
1264     * as special geometry shader variables.
1265     *
1266     * Note that although the general convention of suffixing geometry shader
1267     * input varyings with "In" was not adopted into GLSL 1.50, it is used in
1268     * the specific case of gl_PrimitiveIDIn.  So we don't need to treat
1269     * gl_PrimitiveIDIn as an {ARB,EXT}_geometry_shader4-only variable.
1270     */
1271    var = add_input(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1272                    "gl_PrimitiveIDIn");
1273    var->data.interpolation = INTERP_MODE_FLAT;
1274    var = add_output(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1275                     "gl_PrimitiveID");
1276    var->data.interpolation = INTERP_MODE_FLAT;
1277 }
1278 
1279 
1280 /**
1281  * Generate variables which only exist in fragment shaders.
1282  */
1283 void
generate_fs_special_vars()1284 builtin_variable_generator::generate_fs_special_vars()
1285 {
1286    ir_variable *var;
1287 
1288    int frag_coord_precision = (state->is_version(0, 300) ?
1289                                GLSL_PRECISION_HIGH :
1290                                GLSL_PRECISION_MEDIUM);
1291 
1292    if (this->state->ctx->Const.GLSLFragCoordIsSysVal) {
1293       add_system_value(SYSTEM_VALUE_FRAG_COORD, vec4_t, frag_coord_precision,
1294                        "gl_FragCoord");
1295    } else {
1296       add_input(VARYING_SLOT_POS, vec4_t, frag_coord_precision, "gl_FragCoord");
1297    }
1298 
1299    if (this->state->ctx->Const.GLSLFrontFacingIsSysVal) {
1300       var = add_system_value(SYSTEM_VALUE_FRONT_FACE, bool_t, "gl_FrontFacing");
1301       var->data.interpolation = INTERP_MODE_FLAT;
1302    } else {
1303       var = add_input(VARYING_SLOT_FACE, bool_t, "gl_FrontFacing");
1304       var->data.interpolation = INTERP_MODE_FLAT;
1305    }
1306 
1307    if (state->is_version(120, 100)) {
1308       if (this->state->ctx->Const.GLSLPointCoordIsSysVal)
1309          add_system_value(SYSTEM_VALUE_POINT_COORD, vec2_t,
1310                           GLSL_PRECISION_MEDIUM, "gl_PointCoord");
1311       else
1312          add_input(VARYING_SLOT_PNTC, vec2_t, GLSL_PRECISION_MEDIUM,
1313                    "gl_PointCoord");
1314    }
1315 
1316    if (state->has_geometry_shader() || state->EXT_gpu_shader4_enable) {
1317       var = add_input(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1318                       "gl_PrimitiveID");
1319       var->data.interpolation = INTERP_MODE_FLAT;
1320    }
1321 
1322    /* gl_FragColor and gl_FragData were deprecated starting in desktop GLSL
1323     * 1.30, and were relegated to the compatibility profile in GLSL 4.20.
1324     * They were removed from GLSL ES 3.00.
1325     */
1326    if (compatibility || !state->is_version(420, 300)) {
1327       add_output(FRAG_RESULT_COLOR, vec4_t, GLSL_PRECISION_MEDIUM,
1328                  "gl_FragColor");
1329       add_output(FRAG_RESULT_DATA0,
1330                  array(vec4_t, state->Const.MaxDrawBuffers),
1331                  GLSL_PRECISION_MEDIUM,
1332                  "gl_FragData");
1333    }
1334 
1335    if (state->has_framebuffer_fetch() && !state->is_version(130, 300)) {
1336       ir_variable *const var =
1337          add_output(FRAG_RESULT_DATA0,
1338                     array(vec4_t, state->Const.MaxDrawBuffers),
1339                     "gl_LastFragData");
1340       var->data.precision = GLSL_PRECISION_MEDIUM;
1341       var->data.read_only = 1;
1342       var->data.fb_fetch_output = 1;
1343       var->data.memory_coherent = 1;
1344    }
1345 
1346    if (state->es_shader && state->language_version == 100 && state->EXT_blend_func_extended_enable) {
1347       add_index_output(FRAG_RESULT_COLOR, 1, vec4_t,
1348                        GLSL_PRECISION_MEDIUM, "gl_SecondaryFragColorEXT");
1349       add_index_output(FRAG_RESULT_DATA0, 1,
1350                        array(vec4_t, state->Const.MaxDualSourceDrawBuffers),
1351                        GLSL_PRECISION_MEDIUM, "gl_SecondaryFragDataEXT");
1352    }
1353 
1354    /* gl_FragDepth has always been in desktop GLSL, but did not appear in GLSL
1355     * ES 1.00.
1356     */
1357    if (state->is_version(110, 300)) {
1358       add_output(FRAG_RESULT_DEPTH, float_t, GLSL_PRECISION_HIGH,
1359                  "gl_FragDepth");
1360    }
1361 
1362    if (state->EXT_frag_depth_enable)
1363       add_output(FRAG_RESULT_DEPTH, float_t, "gl_FragDepthEXT");
1364 
1365    if (state->ARB_shader_stencil_export_enable) {
1366       ir_variable *const var =
1367          add_output(FRAG_RESULT_STENCIL, int_t, "gl_FragStencilRefARB");
1368       if (state->ARB_shader_stencil_export_warn)
1369          var->enable_extension_warning("GL_ARB_shader_stencil_export");
1370    }
1371 
1372    if (state->AMD_shader_stencil_export_enable) {
1373       ir_variable *const var =
1374          add_output(FRAG_RESULT_STENCIL, int_t, "gl_FragStencilRefAMD");
1375       if (state->AMD_shader_stencil_export_warn)
1376          var->enable_extension_warning("GL_AMD_shader_stencil_export");
1377    }
1378 
1379    if (state->is_version(400, 320) ||
1380        state->ARB_sample_shading_enable ||
1381        state->OES_sample_variables_enable) {
1382       add_system_value(SYSTEM_VALUE_SAMPLE_ID, int_t, GLSL_PRECISION_LOW,
1383                        "gl_SampleID");
1384       add_system_value(SYSTEM_VALUE_SAMPLE_POS, vec2_t, GLSL_PRECISION_MEDIUM,
1385                        "gl_SamplePosition");
1386       /* From the ARB_sample_shading specification:
1387        *    "The number of elements in the array is ceil(<s>/32), where
1388        *    <s> is the maximum number of color samples supported by the
1389        *    implementation."
1390        * Since no drivers expose more than 32x MSAA, we can simply set
1391        * the array size to 1 rather than computing it.
1392        */
1393       add_output(FRAG_RESULT_SAMPLE_MASK, array(int_t, 1),
1394                  GLSL_PRECISION_HIGH, "gl_SampleMask");
1395    }
1396 
1397    if (state->is_version(400, 320) ||
1398        state->ARB_gpu_shader5_enable ||
1399        state->OES_sample_variables_enable) {
1400       add_system_value(SYSTEM_VALUE_SAMPLE_MASK_IN, array(int_t, 1),
1401                        GLSL_PRECISION_HIGH, "gl_SampleMaskIn");
1402    }
1403 
1404    if (state->is_version(430, 320) ||
1405        state->ARB_fragment_layer_viewport_enable ||
1406        state->OES_geometry_shader_enable ||
1407        state->EXT_geometry_shader_enable) {
1408       var = add_input(VARYING_SLOT_LAYER, int_t, GLSL_PRECISION_HIGH,
1409                       "gl_Layer");
1410       var->data.interpolation = INTERP_MODE_FLAT;
1411    }
1412 
1413    if (state->is_version(430, 0) ||
1414        state->ARB_fragment_layer_viewport_enable ||
1415        state->OES_viewport_array_enable) {
1416       var = add_input(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex");
1417       var->data.interpolation = INTERP_MODE_FLAT;
1418    }
1419 
1420    if (state->is_version(450, 310) || state->ARB_ES3_1_compatibility_enable)
1421       add_system_value(SYSTEM_VALUE_HELPER_INVOCATION, bool_t, "gl_HelperInvocation");
1422 }
1423 
1424 
1425 /**
1426  * Generate variables which only exist in compute shaders.
1427  */
1428 void
generate_cs_special_vars()1429 builtin_variable_generator::generate_cs_special_vars()
1430 {
1431    add_system_value(SYSTEM_VALUE_LOCAL_INVOCATION_ID, uvec3_t,
1432                     "gl_LocalInvocationID");
1433    add_system_value(SYSTEM_VALUE_WORK_GROUP_ID, uvec3_t, "gl_WorkGroupID");
1434    add_system_value(SYSTEM_VALUE_NUM_WORK_GROUPS, uvec3_t, "gl_NumWorkGroups");
1435 
1436    if (state->ARB_compute_variable_group_size_enable) {
1437       add_system_value(SYSTEM_VALUE_LOCAL_GROUP_SIZE,
1438                        uvec3_t, "gl_LocalGroupSizeARB");
1439    }
1440 
1441    add_system_value(SYSTEM_VALUE_GLOBAL_INVOCATION_ID,
1442                     uvec3_t, "gl_GlobalInvocationID");
1443    add_system_value(SYSTEM_VALUE_LOCAL_INVOCATION_INDEX,
1444                     uint_t, "gl_LocalInvocationIndex");
1445 }
1446 
1447 
1448 /**
1449  * Add a single "varying" variable.  The variable's type and direction (input
1450  * or output) are adjusted as appropriate for the type of shader being
1451  * compiled.
1452  */
1453 void
add_varying(int slot,const glsl_type * type,int precision,const char * name)1454 builtin_variable_generator::add_varying(int slot, const glsl_type *type,
1455                                         int precision, const char *name)
1456 {
1457    switch (state->stage) {
1458    case MESA_SHADER_TESS_CTRL:
1459    case MESA_SHADER_TESS_EVAL:
1460    case MESA_SHADER_GEOMETRY:
1461       this->per_vertex_in.add_field(slot, type, precision, name);
1462       /* FALLTHROUGH */
1463    case MESA_SHADER_VERTEX:
1464       this->per_vertex_out.add_field(slot, type, precision, name);
1465       break;
1466    case MESA_SHADER_FRAGMENT:
1467       add_input(slot, type, precision, name);
1468       break;
1469    case MESA_SHADER_COMPUTE:
1470       /* Compute shaders don't have varyings. */
1471       break;
1472    default:
1473       break;
1474    }
1475 }
1476 
1477 
1478 /**
1479  * Generate variables that are used to communicate data from one shader stage
1480  * to the next ("varyings").
1481  */
1482 void
generate_varyings()1483 builtin_variable_generator::generate_varyings()
1484 {
1485    struct gl_shader_compiler_options *options =
1486       &state->ctx->Const.ShaderCompilerOptions[state->stage];
1487 
1488    /* gl_Position and gl_PointSize are not visible from fragment shaders. */
1489    if (state->stage != MESA_SHADER_FRAGMENT) {
1490       add_varying(VARYING_SLOT_POS, vec4_t, GLSL_PRECISION_HIGH, "gl_Position");
1491       if (!state->es_shader ||
1492           state->stage == MESA_SHADER_VERTEX ||
1493           (state->stage == MESA_SHADER_GEOMETRY &&
1494            (state->OES_geometry_point_size_enable ||
1495             state->EXT_geometry_point_size_enable)) ||
1496           ((state->stage == MESA_SHADER_TESS_CTRL ||
1497             state->stage == MESA_SHADER_TESS_EVAL) &&
1498            (state->OES_tessellation_point_size_enable ||
1499             state->EXT_tessellation_point_size_enable))) {
1500          add_varying(VARYING_SLOT_PSIZ,
1501                      float_t,
1502                      state->is_version(0, 300) ?
1503                      GLSL_PRECISION_HIGH :
1504                      GLSL_PRECISION_MEDIUM,
1505                      "gl_PointSize");
1506       }
1507    }
1508 
1509    if (state->has_clip_distance()) {
1510        add_varying(VARYING_SLOT_CLIP_DIST0, array(float_t, 0),
1511                    GLSL_PRECISION_HIGH, "gl_ClipDistance");
1512    }
1513    if (state->has_cull_distance()) {
1514       add_varying(VARYING_SLOT_CULL_DIST0, array(float_t, 0),
1515                   GLSL_PRECISION_HIGH, "gl_CullDistance");
1516    }
1517 
1518    if (compatibility) {
1519       add_varying(VARYING_SLOT_TEX0, array(vec4_t, 0), "gl_TexCoord");
1520       add_varying(VARYING_SLOT_FOGC, float_t, "gl_FogFragCoord");
1521       if (state->stage == MESA_SHADER_FRAGMENT) {
1522          add_varying(VARYING_SLOT_COL0, vec4_t, "gl_Color");
1523          add_varying(VARYING_SLOT_COL1, vec4_t, "gl_SecondaryColor");
1524       } else {
1525          add_varying(VARYING_SLOT_CLIP_VERTEX, vec4_t, "gl_ClipVertex");
1526          add_varying(VARYING_SLOT_COL0, vec4_t, "gl_FrontColor");
1527          add_varying(VARYING_SLOT_BFC0, vec4_t, "gl_BackColor");
1528          add_varying(VARYING_SLOT_COL1, vec4_t, "gl_FrontSecondaryColor");
1529          add_varying(VARYING_SLOT_BFC1, vec4_t, "gl_BackSecondaryColor");
1530       }
1531    }
1532 
1533    /* Section 7.1 (Built-In Language Variables) of the GLSL 4.00 spec
1534     * says:
1535     *
1536     *    "In the tessellation control language, built-in variables are
1537     *    intrinsically declared as:
1538     *
1539     *        in gl_PerVertex {
1540     *            vec4 gl_Position;
1541     *            float gl_PointSize;
1542     *            float gl_ClipDistance[];
1543     *        } gl_in[gl_MaxPatchVertices];"
1544     */
1545    if (state->stage == MESA_SHADER_TESS_CTRL ||
1546        state->stage == MESA_SHADER_TESS_EVAL) {
1547       const glsl_type *per_vertex_in_type =
1548          this->per_vertex_in.construct_interface_instance();
1549       add_variable("gl_in", array(per_vertex_in_type, state->Const.MaxPatchVertices),
1550                    GLSL_PRECISION_NONE, ir_var_shader_in, -1);
1551    }
1552    if (state->stage == MESA_SHADER_GEOMETRY) {
1553       const glsl_type *per_vertex_in_type =
1554          this->per_vertex_in.construct_interface_instance();
1555       add_variable("gl_in", array(per_vertex_in_type, 0),
1556                    GLSL_PRECISION_NONE, ir_var_shader_in, -1);
1557    }
1558    if (state->stage == MESA_SHADER_TESS_CTRL) {
1559       const glsl_type *per_vertex_out_type =
1560          this->per_vertex_out.construct_interface_instance();
1561       add_variable("gl_out", array(per_vertex_out_type, 0),
1562                    GLSL_PRECISION_NONE, ir_var_shader_out, -1);
1563    }
1564    if (state->stage == MESA_SHADER_VERTEX ||
1565        state->stage == MESA_SHADER_TESS_EVAL ||
1566        state->stage == MESA_SHADER_GEOMETRY) {
1567       const glsl_type *per_vertex_out_type =
1568          this->per_vertex_out.construct_interface_instance();
1569       const glsl_struct_field *fields = per_vertex_out_type->fields.structure;
1570       for (unsigned i = 0; i < per_vertex_out_type->length; i++) {
1571          ir_variable *var =
1572             add_variable(fields[i].name, fields[i].type, fields[i].precision,
1573                          ir_var_shader_out, fields[i].location);
1574          var->data.interpolation = fields[i].interpolation;
1575          var->data.centroid = fields[i].centroid;
1576          var->data.sample = fields[i].sample;
1577          var->data.patch = fields[i].patch;
1578          var->init_interface_type(per_vertex_out_type);
1579 
1580          var->data.invariant = fields[i].location == VARYING_SLOT_POS &&
1581                                options->PositionAlwaysInvariant;
1582       }
1583    }
1584 }
1585 
1586 
1587 }; /* Anonymous namespace */
1588 
1589 
1590 void
_mesa_glsl_initialize_variables(exec_list * instructions,struct _mesa_glsl_parse_state * state)1591 _mesa_glsl_initialize_variables(exec_list *instructions,
1592 				struct _mesa_glsl_parse_state *state)
1593 {
1594    builtin_variable_generator gen(instructions, state);
1595 
1596    gen.generate_constants();
1597    gen.generate_uniforms();
1598    gen.generate_special_vars();
1599 
1600    gen.generate_varyings();
1601 
1602    switch (state->stage) {
1603    case MESA_SHADER_VERTEX:
1604       gen.generate_vs_special_vars();
1605       break;
1606    case MESA_SHADER_TESS_CTRL:
1607       gen.generate_tcs_special_vars();
1608       break;
1609    case MESA_SHADER_TESS_EVAL:
1610       gen.generate_tes_special_vars();
1611       break;
1612    case MESA_SHADER_GEOMETRY:
1613       gen.generate_gs_special_vars();
1614       break;
1615    case MESA_SHADER_FRAGMENT:
1616       gen.generate_fs_special_vars();
1617       break;
1618    case MESA_SHADER_COMPUTE:
1619       gen.generate_cs_special_vars();
1620       break;
1621    default:
1622       break;
1623    }
1624 }
1625