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 = 0;
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->ARB_draw_instanced_enable)
1088       add_system_value(SYSTEM_VALUE_INSTANCE_ID, int_t, "gl_InstanceIDARB");
1089    if (state->ARB_draw_instanced_enable || state->is_version(140, 300) ||
1090        state->EXT_gpu_shader4_enable) {
1091       add_system_value(SYSTEM_VALUE_INSTANCE_ID, int_t, GLSL_PRECISION_HIGH,
1092                        "gl_InstanceID");
1093    }
1094    if (state->ARB_shader_draw_parameters_enable) {
1095       add_system_value(SYSTEM_VALUE_BASE_VERTEX, int_t, "gl_BaseVertexARB");
1096       add_system_value(SYSTEM_VALUE_BASE_INSTANCE, int_t, "gl_BaseInstanceARB");
1097       add_system_value(SYSTEM_VALUE_DRAW_ID, int_t, "gl_DrawIDARB");
1098    }
1099    if (state->AMD_vertex_shader_layer_enable ||
1100        state->ARB_shader_viewport_layer_array_enable) {
1101       var = add_output(VARYING_SLOT_LAYER, int_t, "gl_Layer");
1102       var->data.interpolation = INTERP_MODE_FLAT;
1103    }
1104    if (state->AMD_vertex_shader_viewport_index_enable ||
1105        state->ARB_shader_viewport_layer_array_enable) {
1106       var = add_output(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex");
1107       var->data.interpolation = INTERP_MODE_FLAT;
1108    }
1109    if (compatibility) {
1110       add_input(VERT_ATTRIB_POS, vec4_t, "gl_Vertex");
1111       add_input(VERT_ATTRIB_NORMAL, vec3_t, "gl_Normal");
1112       add_input(VERT_ATTRIB_COLOR0, vec4_t, "gl_Color");
1113       add_input(VERT_ATTRIB_COLOR1, vec4_t, "gl_SecondaryColor");
1114       add_input(VERT_ATTRIB_TEX0, vec4_t, "gl_MultiTexCoord0");
1115       add_input(VERT_ATTRIB_TEX1, vec4_t, "gl_MultiTexCoord1");
1116       add_input(VERT_ATTRIB_TEX2, vec4_t, "gl_MultiTexCoord2");
1117       add_input(VERT_ATTRIB_TEX3, vec4_t, "gl_MultiTexCoord3");
1118       add_input(VERT_ATTRIB_TEX4, vec4_t, "gl_MultiTexCoord4");
1119       add_input(VERT_ATTRIB_TEX5, vec4_t, "gl_MultiTexCoord5");
1120       add_input(VERT_ATTRIB_TEX6, vec4_t, "gl_MultiTexCoord6");
1121       add_input(VERT_ATTRIB_TEX7, vec4_t, "gl_MultiTexCoord7");
1122       add_input(VERT_ATTRIB_FOG, float_t, "gl_FogCoord");
1123    }
1124 }
1125 
1126 
1127 /**
1128  * Generate variables which only exist in tessellation control shaders.
1129  */
1130 void
generate_tcs_special_vars()1131 builtin_variable_generator::generate_tcs_special_vars()
1132 {
1133    add_system_value(SYSTEM_VALUE_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1134                     "gl_PrimitiveID");
1135    add_system_value(SYSTEM_VALUE_INVOCATION_ID, int_t, GLSL_PRECISION_HIGH,
1136                     "gl_InvocationID");
1137    add_system_value(SYSTEM_VALUE_VERTICES_IN, int_t, GLSL_PRECISION_HIGH,
1138                     "gl_PatchVerticesIn");
1139 
1140    add_output(VARYING_SLOT_TESS_LEVEL_OUTER, array(float_t, 4),
1141               GLSL_PRECISION_HIGH, "gl_TessLevelOuter")->data.patch = 1;
1142    add_output(VARYING_SLOT_TESS_LEVEL_INNER, array(float_t, 2),
1143               GLSL_PRECISION_HIGH, "gl_TessLevelInner")->data.patch = 1;
1144    /* XXX What to do if multiple are flipped on? */
1145    int bbox_slot = state->ctx->Const.NoPrimitiveBoundingBoxOutput ? -1 :
1146       VARYING_SLOT_BOUNDING_BOX0;
1147    if (state->EXT_primitive_bounding_box_enable)
1148       add_output(bbox_slot, array(vec4_t, 2), "gl_BoundingBoxEXT")
1149          ->data.patch = 1;
1150    if (state->OES_primitive_bounding_box_enable) {
1151       add_output(bbox_slot, array(vec4_t, 2), GLSL_PRECISION_HIGH,
1152                  "gl_BoundingBoxOES")->data.patch = 1;
1153    }
1154    if (state->is_version(0, 320) || state->ARB_ES3_2_compatibility_enable) {
1155       add_output(bbox_slot, array(vec4_t, 2), GLSL_PRECISION_HIGH,
1156                  "gl_BoundingBox")->data.patch = 1;
1157    }
1158 }
1159 
1160 
1161 /**
1162  * Generate variables which only exist in tessellation evaluation shaders.
1163  */
1164 void
generate_tes_special_vars()1165 builtin_variable_generator::generate_tes_special_vars()
1166 {
1167    ir_variable *var;
1168 
1169    add_system_value(SYSTEM_VALUE_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1170                     "gl_PrimitiveID");
1171    add_system_value(SYSTEM_VALUE_VERTICES_IN, int_t, GLSL_PRECISION_HIGH,
1172                     "gl_PatchVerticesIn");
1173    add_system_value(SYSTEM_VALUE_TESS_COORD, vec3_t, GLSL_PRECISION_HIGH,
1174                     "gl_TessCoord");
1175    if (this->state->ctx->Const.GLSLTessLevelsAsInputs) {
1176       add_input(VARYING_SLOT_TESS_LEVEL_OUTER, array(float_t, 4),
1177                 GLSL_PRECISION_HIGH, "gl_TessLevelOuter")->data.patch = 1;
1178       add_input(VARYING_SLOT_TESS_LEVEL_INNER, array(float_t, 2),
1179                 GLSL_PRECISION_HIGH, "gl_TessLevelInner")->data.patch = 1;
1180    } else {
1181       add_system_value(SYSTEM_VALUE_TESS_LEVEL_OUTER, array(float_t, 4),
1182                        GLSL_PRECISION_HIGH, "gl_TessLevelOuter");
1183       add_system_value(SYSTEM_VALUE_TESS_LEVEL_INNER, array(float_t, 2),
1184                        GLSL_PRECISION_HIGH, "gl_TessLevelInner");
1185    }
1186    if (state->ARB_shader_viewport_layer_array_enable) {
1187       var = add_output(VARYING_SLOT_LAYER, int_t, "gl_Layer");
1188       var->data.interpolation = INTERP_MODE_FLAT;
1189       var = add_output(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex");
1190       var->data.interpolation = INTERP_MODE_FLAT;
1191    }
1192 }
1193 
1194 
1195 /**
1196  * Generate variables which only exist in geometry shaders.
1197  */
1198 void
generate_gs_special_vars()1199 builtin_variable_generator::generate_gs_special_vars()
1200 {
1201    ir_variable *var;
1202 
1203    var = add_output(VARYING_SLOT_LAYER, int_t, GLSL_PRECISION_HIGH, "gl_Layer");
1204    var->data.interpolation = INTERP_MODE_FLAT;
1205    if (state->is_version(410, 0) || state->ARB_viewport_array_enable ||
1206        state->OES_viewport_array_enable) {
1207       var = add_output(VARYING_SLOT_VIEWPORT, int_t, GLSL_PRECISION_HIGH,
1208                        "gl_ViewportIndex");
1209       var->data.interpolation = INTERP_MODE_FLAT;
1210    }
1211    if (state->is_version(400, 320) || state->ARB_gpu_shader5_enable ||
1212        state->OES_geometry_shader_enable || state->EXT_geometry_shader_enable) {
1213       add_system_value(SYSTEM_VALUE_INVOCATION_ID, int_t, GLSL_PRECISION_HIGH,
1214                        "gl_InvocationID");
1215    }
1216 
1217    /* Although gl_PrimitiveID appears in tessellation control and tessellation
1218     * evaluation shaders, it has a different function there than it has in
1219     * geometry shaders, so we treat it (and its counterpart gl_PrimitiveIDIn)
1220     * as special geometry shader variables.
1221     *
1222     * Note that although the general convention of suffixing geometry shader
1223     * input varyings with "In" was not adopted into GLSL 1.50, it is used in
1224     * the specific case of gl_PrimitiveIDIn.  So we don't need to treat
1225     * gl_PrimitiveIDIn as an {ARB,EXT}_geometry_shader4-only variable.
1226     */
1227    var = add_input(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1228                    "gl_PrimitiveIDIn");
1229    var->data.interpolation = INTERP_MODE_FLAT;
1230    var = add_output(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1231                     "gl_PrimitiveID");
1232    var->data.interpolation = INTERP_MODE_FLAT;
1233 }
1234 
1235 
1236 /**
1237  * Generate variables which only exist in fragment shaders.
1238  */
1239 void
generate_fs_special_vars()1240 builtin_variable_generator::generate_fs_special_vars()
1241 {
1242    ir_variable *var;
1243 
1244    int frag_coord_precision = (state->is_version(0, 300) ?
1245                                GLSL_PRECISION_HIGH :
1246                                GLSL_PRECISION_MEDIUM);
1247 
1248    if (this->state->ctx->Const.GLSLFragCoordIsSysVal) {
1249       add_system_value(SYSTEM_VALUE_FRAG_COORD, vec4_t, frag_coord_precision,
1250                        "gl_FragCoord");
1251    } else {
1252       add_input(VARYING_SLOT_POS, vec4_t, frag_coord_precision, "gl_FragCoord");
1253    }
1254 
1255    if (this->state->ctx->Const.GLSLFrontFacingIsSysVal) {
1256       var = add_system_value(SYSTEM_VALUE_FRONT_FACE, bool_t, "gl_FrontFacing");
1257       var->data.interpolation = INTERP_MODE_FLAT;
1258    } else {
1259       var = add_input(VARYING_SLOT_FACE, bool_t, "gl_FrontFacing");
1260       var->data.interpolation = INTERP_MODE_FLAT;
1261    }
1262 
1263    if (state->is_version(120, 100)) {
1264       if (this->state->ctx->Const.GLSLPointCoordIsSysVal)
1265          add_system_value(SYSTEM_VALUE_POINT_COORD, vec2_t,
1266                           GLSL_PRECISION_MEDIUM, "gl_PointCoord");
1267       else
1268          add_input(VARYING_SLOT_PNTC, vec2_t, GLSL_PRECISION_MEDIUM,
1269                    "gl_PointCoord");
1270    }
1271 
1272    if (state->has_geometry_shader() || state->EXT_gpu_shader4_enable) {
1273       var = add_input(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1274                       "gl_PrimitiveID");
1275       var->data.interpolation = INTERP_MODE_FLAT;
1276    }
1277 
1278    /* gl_FragColor and gl_FragData were deprecated starting in desktop GLSL
1279     * 1.30, and were relegated to the compatibility profile in GLSL 4.20.
1280     * They were removed from GLSL ES 3.00.
1281     */
1282    if (compatibility || !state->is_version(420, 300)) {
1283       add_output(FRAG_RESULT_COLOR, vec4_t, GLSL_PRECISION_MEDIUM,
1284                  "gl_FragColor");
1285       add_output(FRAG_RESULT_DATA0,
1286                  array(vec4_t, state->Const.MaxDrawBuffers),
1287                  GLSL_PRECISION_MEDIUM,
1288                  "gl_FragData");
1289    }
1290 
1291    if (state->has_framebuffer_fetch() && !state->is_version(130, 300)) {
1292       ir_variable *const var =
1293          add_output(FRAG_RESULT_DATA0,
1294                     array(vec4_t, state->Const.MaxDrawBuffers),
1295                     "gl_LastFragData");
1296       var->data.precision = GLSL_PRECISION_MEDIUM;
1297       var->data.read_only = 1;
1298       var->data.fb_fetch_output = 1;
1299       var->data.memory_coherent = 1;
1300    }
1301 
1302    if (state->es_shader && state->language_version == 100 && state->EXT_blend_func_extended_enable) {
1303       add_index_output(FRAG_RESULT_COLOR, 1, vec4_t,
1304                        GLSL_PRECISION_MEDIUM, "gl_SecondaryFragColorEXT");
1305       add_index_output(FRAG_RESULT_DATA0, 1,
1306                        array(vec4_t, state->Const.MaxDualSourceDrawBuffers),
1307                        GLSL_PRECISION_MEDIUM, "gl_SecondaryFragDataEXT");
1308    }
1309 
1310    /* gl_FragDepth has always been in desktop GLSL, but did not appear in GLSL
1311     * ES 1.00.
1312     */
1313    if (state->is_version(110, 300)) {
1314       add_output(FRAG_RESULT_DEPTH, float_t, GLSL_PRECISION_HIGH,
1315                  "gl_FragDepth");
1316    }
1317 
1318    if (state->EXT_frag_depth_enable)
1319       add_output(FRAG_RESULT_DEPTH, float_t, "gl_FragDepthEXT");
1320 
1321    if (state->ARB_shader_stencil_export_enable) {
1322       ir_variable *const var =
1323          add_output(FRAG_RESULT_STENCIL, int_t, "gl_FragStencilRefARB");
1324       if (state->ARB_shader_stencil_export_warn)
1325          var->enable_extension_warning("GL_ARB_shader_stencil_export");
1326    }
1327 
1328    if (state->AMD_shader_stencil_export_enable) {
1329       ir_variable *const var =
1330          add_output(FRAG_RESULT_STENCIL, int_t, "gl_FragStencilRefAMD");
1331       if (state->AMD_shader_stencil_export_warn)
1332          var->enable_extension_warning("GL_AMD_shader_stencil_export");
1333    }
1334 
1335    if (state->is_version(400, 320) ||
1336        state->ARB_sample_shading_enable ||
1337        state->OES_sample_variables_enable) {
1338       add_system_value(SYSTEM_VALUE_SAMPLE_ID, int_t, GLSL_PRECISION_LOW,
1339                        "gl_SampleID");
1340       add_system_value(SYSTEM_VALUE_SAMPLE_POS, vec2_t, GLSL_PRECISION_MEDIUM,
1341                        "gl_SamplePosition");
1342       /* From the ARB_sample_shading specification:
1343        *    "The number of elements in the array is ceil(<s>/32), where
1344        *    <s> is the maximum number of color samples supported by the
1345        *    implementation."
1346        * Since no drivers expose more than 32x MSAA, we can simply set
1347        * the array size to 1 rather than computing it.
1348        */
1349       add_output(FRAG_RESULT_SAMPLE_MASK, array(int_t, 1),
1350                  GLSL_PRECISION_HIGH, "gl_SampleMask");
1351    }
1352 
1353    if (state->is_version(400, 320) ||
1354        state->ARB_gpu_shader5_enable ||
1355        state->OES_sample_variables_enable) {
1356       add_system_value(SYSTEM_VALUE_SAMPLE_MASK_IN, array(int_t, 1),
1357                        GLSL_PRECISION_HIGH, "gl_SampleMaskIn");
1358    }
1359 
1360    if (state->is_version(430, 320) ||
1361        state->ARB_fragment_layer_viewport_enable ||
1362        state->OES_geometry_shader_enable ||
1363        state->EXT_geometry_shader_enable) {
1364       var = add_input(VARYING_SLOT_LAYER, int_t, GLSL_PRECISION_HIGH,
1365                       "gl_Layer");
1366       var->data.interpolation = INTERP_MODE_FLAT;
1367    }
1368 
1369    if (state->is_version(430, 0) ||
1370        state->ARB_fragment_layer_viewport_enable ||
1371        state->OES_viewport_array_enable) {
1372       var = add_input(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex");
1373       var->data.interpolation = INTERP_MODE_FLAT;
1374    }
1375 
1376    if (state->is_version(450, 310) || state->ARB_ES3_1_compatibility_enable)
1377       add_system_value(SYSTEM_VALUE_HELPER_INVOCATION, bool_t, "gl_HelperInvocation");
1378 }
1379 
1380 
1381 /**
1382  * Generate variables which only exist in compute shaders.
1383  */
1384 void
generate_cs_special_vars()1385 builtin_variable_generator::generate_cs_special_vars()
1386 {
1387    add_system_value(SYSTEM_VALUE_LOCAL_INVOCATION_ID, uvec3_t,
1388                     "gl_LocalInvocationID");
1389    add_system_value(SYSTEM_VALUE_WORK_GROUP_ID, uvec3_t, "gl_WorkGroupID");
1390    add_system_value(SYSTEM_VALUE_NUM_WORK_GROUPS, uvec3_t, "gl_NumWorkGroups");
1391 
1392    if (state->ARB_compute_variable_group_size_enable) {
1393       add_system_value(SYSTEM_VALUE_LOCAL_GROUP_SIZE,
1394                        uvec3_t, "gl_LocalGroupSizeARB");
1395    }
1396 
1397    add_system_value(SYSTEM_VALUE_GLOBAL_INVOCATION_ID,
1398                     uvec3_t, "gl_GlobalInvocationID");
1399    add_system_value(SYSTEM_VALUE_LOCAL_INVOCATION_INDEX,
1400                     uint_t, "gl_LocalInvocationIndex");
1401 }
1402 
1403 
1404 /**
1405  * Add a single "varying" variable.  The variable's type and direction (input
1406  * or output) are adjusted as appropriate for the type of shader being
1407  * compiled.
1408  */
1409 void
add_varying(int slot,const glsl_type * type,int precision,const char * name)1410 builtin_variable_generator::add_varying(int slot, const glsl_type *type,
1411                                         int precision, const char *name)
1412 {
1413    switch (state->stage) {
1414    case MESA_SHADER_TESS_CTRL:
1415    case MESA_SHADER_TESS_EVAL:
1416    case MESA_SHADER_GEOMETRY:
1417       this->per_vertex_in.add_field(slot, type, precision, name);
1418       /* FALLTHROUGH */
1419    case MESA_SHADER_VERTEX:
1420       this->per_vertex_out.add_field(slot, type, precision, name);
1421       break;
1422    case MESA_SHADER_FRAGMENT:
1423       add_input(slot, type, precision, name);
1424       break;
1425    case MESA_SHADER_COMPUTE:
1426       /* Compute shaders don't have varyings. */
1427       break;
1428    default:
1429       break;
1430    }
1431 }
1432 
1433 
1434 /**
1435  * Generate variables that are used to communicate data from one shader stage
1436  * to the next ("varyings").
1437  */
1438 void
generate_varyings()1439 builtin_variable_generator::generate_varyings()
1440 {
1441    struct gl_shader_compiler_options *options =
1442       &state->ctx->Const.ShaderCompilerOptions[state->stage];
1443 
1444    /* gl_Position and gl_PointSize are not visible from fragment shaders. */
1445    if (state->stage != MESA_SHADER_FRAGMENT) {
1446       add_varying(VARYING_SLOT_POS, vec4_t, GLSL_PRECISION_HIGH, "gl_Position");
1447       if (!state->es_shader ||
1448           state->stage == MESA_SHADER_VERTEX ||
1449           (state->stage == MESA_SHADER_GEOMETRY &&
1450            (state->OES_geometry_point_size_enable ||
1451             state->EXT_geometry_point_size_enable)) ||
1452           ((state->stage == MESA_SHADER_TESS_CTRL ||
1453             state->stage == MESA_SHADER_TESS_EVAL) &&
1454            (state->OES_tessellation_point_size_enable ||
1455             state->EXT_tessellation_point_size_enable))) {
1456          add_varying(VARYING_SLOT_PSIZ,
1457                      float_t,
1458                      state->is_version(0, 300) ?
1459                      GLSL_PRECISION_HIGH :
1460                      GLSL_PRECISION_MEDIUM,
1461                      "gl_PointSize");
1462       }
1463    }
1464 
1465    if (state->has_clip_distance()) {
1466        add_varying(VARYING_SLOT_CLIP_DIST0, array(float_t, 0),
1467                    GLSL_PRECISION_HIGH, "gl_ClipDistance");
1468    }
1469    if (state->has_cull_distance()) {
1470       add_varying(VARYING_SLOT_CULL_DIST0, array(float_t, 0),
1471                   GLSL_PRECISION_HIGH, "gl_CullDistance");
1472    }
1473 
1474    if (compatibility) {
1475       add_varying(VARYING_SLOT_TEX0, array(vec4_t, 0), "gl_TexCoord");
1476       add_varying(VARYING_SLOT_FOGC, float_t, "gl_FogFragCoord");
1477       if (state->stage == MESA_SHADER_FRAGMENT) {
1478          add_varying(VARYING_SLOT_COL0, vec4_t, "gl_Color");
1479          add_varying(VARYING_SLOT_COL1, vec4_t, "gl_SecondaryColor");
1480       } else {
1481          add_varying(VARYING_SLOT_CLIP_VERTEX, vec4_t, "gl_ClipVertex");
1482          add_varying(VARYING_SLOT_COL0, vec4_t, "gl_FrontColor");
1483          add_varying(VARYING_SLOT_BFC0, vec4_t, "gl_BackColor");
1484          add_varying(VARYING_SLOT_COL1, vec4_t, "gl_FrontSecondaryColor");
1485          add_varying(VARYING_SLOT_BFC1, vec4_t, "gl_BackSecondaryColor");
1486       }
1487    }
1488 
1489    /* Section 7.1 (Built-In Language Variables) of the GLSL 4.00 spec
1490     * says:
1491     *
1492     *    "In the tessellation control language, built-in variables are
1493     *    intrinsically declared as:
1494     *
1495     *        in gl_PerVertex {
1496     *            vec4 gl_Position;
1497     *            float gl_PointSize;
1498     *            float gl_ClipDistance[];
1499     *        } gl_in[gl_MaxPatchVertices];"
1500     */
1501    if (state->stage == MESA_SHADER_TESS_CTRL ||
1502        state->stage == MESA_SHADER_TESS_EVAL) {
1503       const glsl_type *per_vertex_in_type =
1504          this->per_vertex_in.construct_interface_instance();
1505       add_variable("gl_in", array(per_vertex_in_type, state->Const.MaxPatchVertices),
1506                    GLSL_PRECISION_NONE, ir_var_shader_in, -1);
1507    }
1508    if (state->stage == MESA_SHADER_GEOMETRY) {
1509       const glsl_type *per_vertex_in_type =
1510          this->per_vertex_in.construct_interface_instance();
1511       add_variable("gl_in", array(per_vertex_in_type, 0),
1512                    GLSL_PRECISION_NONE, ir_var_shader_in, -1);
1513    }
1514    if (state->stage == MESA_SHADER_TESS_CTRL) {
1515       const glsl_type *per_vertex_out_type =
1516          this->per_vertex_out.construct_interface_instance();
1517       add_variable("gl_out", array(per_vertex_out_type, 0),
1518                    GLSL_PRECISION_NONE, ir_var_shader_out, -1);
1519    }
1520    if (state->stage == MESA_SHADER_VERTEX ||
1521        state->stage == MESA_SHADER_TESS_EVAL ||
1522        state->stage == MESA_SHADER_GEOMETRY) {
1523       const glsl_type *per_vertex_out_type =
1524          this->per_vertex_out.construct_interface_instance();
1525       const glsl_struct_field *fields = per_vertex_out_type->fields.structure;
1526       for (unsigned i = 0; i < per_vertex_out_type->length; i++) {
1527          ir_variable *var =
1528             add_variable(fields[i].name, fields[i].type, fields[i].precision,
1529                          ir_var_shader_out, fields[i].location);
1530          var->data.interpolation = fields[i].interpolation;
1531          var->data.centroid = fields[i].centroid;
1532          var->data.sample = fields[i].sample;
1533          var->data.patch = fields[i].patch;
1534          var->init_interface_type(per_vertex_out_type);
1535 
1536          var->data.invariant = fields[i].location == VARYING_SLOT_POS &&
1537                                options->PositionAlwaysInvariant;
1538       }
1539    }
1540 }
1541 
1542 
1543 }; /* Anonymous namespace */
1544 
1545 
1546 void
_mesa_glsl_initialize_variables(exec_list * instructions,struct _mesa_glsl_parse_state * state)1547 _mesa_glsl_initialize_variables(exec_list *instructions,
1548 				struct _mesa_glsl_parse_state *state)
1549 {
1550    builtin_variable_generator gen(instructions, state);
1551 
1552    gen.generate_constants();
1553    gen.generate_uniforms();
1554    gen.generate_special_vars();
1555 
1556    gen.generate_varyings();
1557 
1558    switch (state->stage) {
1559    case MESA_SHADER_VERTEX:
1560       gen.generate_vs_special_vars();
1561       break;
1562    case MESA_SHADER_TESS_CTRL:
1563       gen.generate_tcs_special_vars();
1564       break;
1565    case MESA_SHADER_TESS_EVAL:
1566       gen.generate_tes_special_vars();
1567       break;
1568    case MESA_SHADER_GEOMETRY:
1569       gen.generate_gs_special_vars();
1570       break;
1571    case MESA_SHADER_FRAGMENT:
1572       gen.generate_fs_special_vars();
1573       break;
1574    case MESA_SHADER_COMPUTE:
1575       gen.generate_cs_special_vars();
1576       break;
1577    default:
1578       break;
1579    }
1580 }
1581