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