1/*
2 * Mesa 3-D graphics library
3 *
4 * Copyright © 2013 Gregory Hainaut <gregory.hainaut@gmail.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 * IN THE SOFTWARE.
24 */
25
26/**
27 * \file pipelineobj.c
28 * \author Hainaut Gregory <gregory.hainaut@gmail.com>
29 *
30 * Implementation of pipeline object related API functions. Based on
31 * GL_ARB_separate_shader_objects extension.
32 */
33
34#include <stdbool.h>
35#include "main/glheader.h"
36#include "main/context.h"
37#include "main/draw_validate.h"
38#include "main/enums.h"
39#include "main/hash.h"
40#include "main/mtypes.h"
41#include "main/pipelineobj.h"
42#include "main/shaderapi.h"
43#include "main/shaderobj.h"
44#include "main/state.h"
45#include "main/transformfeedback.h"
46#include "main/uniforms.h"
47#include "compiler/glsl/glsl_parser_extras.h"
48#include "compiler/glsl/ir_uniform.h"
49#include "program/program.h"
50#include "program/prog_parameter.h"
51#include "util/ralloc.h"
52#include "util/bitscan.h"
53
54/**
55 * Delete a pipeline object.
56 */
57void
58_mesa_delete_pipeline_object(struct gl_context *ctx,
59                             struct gl_pipeline_object *obj)
60{
61   unsigned i;
62
63   for (i = 0; i < MESA_SHADER_STAGES; i++) {
64      _mesa_reference_program(ctx, &obj->CurrentProgram[i], NULL);
65      _mesa_reference_shader_program(ctx, &obj->ReferencedPrograms[i], NULL);
66   }
67
68   _mesa_reference_shader_program(ctx, &obj->ActiveProgram, NULL);
69   free(obj->Label);
70   ralloc_free(obj);
71}
72
73/**
74 * Allocate and initialize a new pipeline object.
75 */
76static struct gl_pipeline_object *
77_mesa_new_pipeline_object(struct gl_context *ctx, GLuint name)
78{
79   struct gl_pipeline_object *obj = rzalloc(NULL, struct gl_pipeline_object);
80   if (obj) {
81      obj->Name = name;
82      obj->RefCount = 1;
83      obj->Flags = _mesa_get_shader_flags();
84      obj->InfoLog = NULL;
85   }
86
87   return obj;
88}
89
90/**
91 * Initialize pipeline object state for given context.
92 */
93void
94_mesa_init_pipeline(struct gl_context *ctx)
95{
96   ctx->Pipeline.Objects = _mesa_NewHashTable();
97
98   ctx->Pipeline.Current = NULL;
99
100   /* Install a default Pipeline */
101   ctx->Pipeline.Default = _mesa_new_pipeline_object(ctx, 0);
102   _mesa_reference_pipeline_object(ctx, &ctx->_Shader, ctx->Pipeline.Default);
103}
104
105
106/**
107 * Callback for deleting a pipeline object.  Called by _mesa_HashDeleteAll().
108 */
109static void
110delete_pipelineobj_cb(void *data, void *userData)
111{
112   struct gl_pipeline_object *obj = (struct gl_pipeline_object *) data;
113   struct gl_context *ctx = (struct gl_context *) userData;
114   _mesa_delete_pipeline_object(ctx, obj);
115}
116
117
118/**
119 * Free pipeline state for given context.
120 */
121void
122_mesa_free_pipeline_data(struct gl_context *ctx)
123{
124   _mesa_reference_pipeline_object(ctx, &ctx->_Shader, NULL);
125
126   _mesa_HashDeleteAll(ctx->Pipeline.Objects, delete_pipelineobj_cb, ctx);
127   _mesa_DeleteHashTable(ctx->Pipeline.Objects);
128
129   _mesa_delete_pipeline_object(ctx, ctx->Pipeline.Default);
130}
131
132/**
133 * Look up the pipeline object for the given ID.
134 *
135 * \returns
136 * Either a pointer to the pipeline object with the specified ID or \c NULL for
137 * a non-existent ID.  The spec defines ID 0 as being technically
138 * non-existent.
139 */
140struct gl_pipeline_object *
141_mesa_lookup_pipeline_object(struct gl_context *ctx, GLuint id)
142{
143   if (id == 0)
144      return NULL;
145   else
146      return (struct gl_pipeline_object *)
147         _mesa_HashLookupLocked(ctx->Pipeline.Objects, id);
148}
149
150/**
151 * Add the given pipeline object to the pipeline object pool.
152 */
153static void
154save_pipeline_object(struct gl_context *ctx, struct gl_pipeline_object *obj)
155{
156   if (obj->Name > 0) {
157      _mesa_HashInsertLocked(ctx->Pipeline.Objects, obj->Name, obj, true);
158   }
159}
160
161/**
162 * Remove the given pipeline object from the pipeline object pool.
163 * Do not deallocate the pipeline object though.
164 */
165static void
166remove_pipeline_object(struct gl_context *ctx, struct gl_pipeline_object *obj)
167{
168   if (obj->Name > 0) {
169      _mesa_HashRemoveLocked(ctx->Pipeline.Objects, obj->Name);
170   }
171}
172
173/**
174 * Set ptr to obj w/ reference counting.
175 * Note: this should only be called from the _mesa_reference_pipeline_object()
176 * inline function.
177 */
178void
179_mesa_reference_pipeline_object_(struct gl_context *ctx,
180                                 struct gl_pipeline_object **ptr,
181                                 struct gl_pipeline_object *obj)
182{
183   assert(*ptr != obj);
184
185   if (*ptr) {
186      /* Unreference the old pipeline object */
187      struct gl_pipeline_object *oldObj = *ptr;
188
189      assert(oldObj->RefCount > 0);
190      oldObj->RefCount--;
191
192      if (oldObj->RefCount == 0) {
193         _mesa_delete_pipeline_object(ctx, oldObj);
194      }
195
196      *ptr = NULL;
197   }
198   assert(!*ptr);
199
200   if (obj) {
201      /* reference new pipeline object */
202      assert(obj->RefCount > 0);
203
204      obj->RefCount++;
205      *ptr = obj;
206   }
207}
208
209static void
210use_program_stage(struct gl_context *ctx, GLenum type,
211                  struct gl_shader_program *shProg,
212                  struct gl_pipeline_object *pipe) {
213   gl_shader_stage stage = _mesa_shader_enum_to_shader_stage(type);
214   struct gl_program *prog = NULL;
215   if (shProg && shProg->_LinkedShaders[stage])
216      prog = shProg->_LinkedShaders[stage]->Program;
217
218   _mesa_use_program(ctx, stage, shProg, prog, pipe);
219}
220
221static void
222use_program_stages(struct gl_context *ctx, struct gl_shader_program *shProg,
223                   GLbitfield stages, struct gl_pipeline_object *pipe) {
224
225   /* Enable individual stages from the program as requested by the
226    * application.  If there is no shader for a requested stage in the
227    * program, _mesa_use_shader_program will enable fixed-function processing
228    * as dictated by the spec.
229    *
230    * Section 2.11.4 (Program Pipeline Objects) of the OpenGL 4.1 spec
231    * says:
232    *
233    *     "If UseProgramStages is called with program set to zero or with a
234    *     program object that contains no executable code for the given
235    *     stages, it is as if the pipeline object has no programmable stage
236    *     configured for the indicated shader stages."
237    */
238   if ((stages & GL_VERTEX_SHADER_BIT) != 0)
239      use_program_stage(ctx, GL_VERTEX_SHADER, shProg, pipe);
240
241   if ((stages & GL_FRAGMENT_SHADER_BIT) != 0)
242      use_program_stage(ctx, GL_FRAGMENT_SHADER, shProg, pipe);
243
244   if ((stages & GL_GEOMETRY_SHADER_BIT) != 0)
245      use_program_stage(ctx, GL_GEOMETRY_SHADER, shProg, pipe);
246
247   if ((stages & GL_TESS_CONTROL_SHADER_BIT) != 0)
248      use_program_stage(ctx, GL_TESS_CONTROL_SHADER, shProg, pipe);
249
250   if ((stages & GL_TESS_EVALUATION_SHADER_BIT) != 0)
251      use_program_stage(ctx, GL_TESS_EVALUATION_SHADER, shProg, pipe);
252
253   if ((stages & GL_COMPUTE_SHADER_BIT) != 0)
254      use_program_stage(ctx, GL_COMPUTE_SHADER, shProg, pipe);
255
256   pipe->Validated = pipe->UserValidated = false;
257
258   if (pipe == ctx->_Shader)
259      _mesa_update_valid_to_render_state(ctx);
260}
261
262void GLAPIENTRY
263_mesa_UseProgramStages_no_error(GLuint pipeline, GLbitfield stages,
264                                GLuint prog)
265{
266   GET_CURRENT_CONTEXT(ctx);
267
268   struct gl_pipeline_object *pipe =
269      _mesa_lookup_pipeline_object(ctx, pipeline);
270   struct gl_shader_program *shProg = NULL;
271
272   if (prog)
273      shProg = _mesa_lookup_shader_program(ctx, prog);
274
275   /* Object is created by any Pipeline call but glGenProgramPipelines,
276    * glIsProgramPipeline and GetProgramPipelineInfoLog
277    */
278   pipe->EverBound = GL_TRUE;
279
280   use_program_stages(ctx, shProg, stages, pipe);
281}
282
283/**
284 * Bound program to severals stages of the pipeline
285 */
286void GLAPIENTRY
287_mesa_UseProgramStages(GLuint pipeline, GLbitfield stages, GLuint program)
288{
289   GET_CURRENT_CONTEXT(ctx);
290
291   struct gl_pipeline_object *pipe = _mesa_lookup_pipeline_object(ctx, pipeline);
292   struct gl_shader_program *shProg = NULL;
293   GLbitfield any_valid_stages;
294
295   if (MESA_VERBOSE & VERBOSE_API)
296      _mesa_debug(ctx, "glUseProgramStages(%u, 0x%x, %u)\n",
297                  pipeline, stages, program);
298
299   if (!pipe) {
300      _mesa_error(ctx, GL_INVALID_OPERATION, "glUseProgramStages(pipeline)");
301      return;
302   }
303
304   /* Object is created by any Pipeline call but glGenProgramPipelines,
305    * glIsProgramPipeline and GetProgramPipelineInfoLog
306    */
307   pipe->EverBound = GL_TRUE;
308
309   /* Section 2.11.4 (Program Pipeline Objects) of the OpenGL 4.1 spec says:
310    *
311    *     "If stages is not the special value ALL_SHADER_BITS, and has a bit
312    *     set that is not recognized, the error INVALID_VALUE is generated."
313    */
314   any_valid_stages = GL_VERTEX_SHADER_BIT | GL_FRAGMENT_SHADER_BIT;
315   if (_mesa_has_geometry_shaders(ctx))
316      any_valid_stages |= GL_GEOMETRY_SHADER_BIT;
317   if (_mesa_has_tessellation(ctx))
318      any_valid_stages |= GL_TESS_CONTROL_SHADER_BIT |
319                          GL_TESS_EVALUATION_SHADER_BIT;
320   if (_mesa_has_compute_shaders(ctx))
321      any_valid_stages |= GL_COMPUTE_SHADER_BIT;
322
323   if (stages != GL_ALL_SHADER_BITS && (stages & ~any_valid_stages) != 0) {
324      _mesa_error(ctx, GL_INVALID_VALUE, "glUseProgramStages(Stages)");
325      return;
326   }
327
328   /* Section 2.17.2 (Transform Feedback Primitive Capture) of the OpenGL 4.1
329    * spec says:
330    *
331    *     "The error INVALID_OPERATION is generated:
332    *
333    *      ...
334    *
335    *         - by UseProgramStages if the program pipeline object it refers
336    *           to is current and the current transform feedback object is
337    *           active and not paused;
338    */
339   if (ctx->_Shader == pipe) {
340      if (_mesa_is_xfb_active_and_unpaused(ctx)) {
341         _mesa_error(ctx, GL_INVALID_OPERATION,
342               "glUseProgramStages(transform feedback active)");
343         return;
344      }
345   }
346
347   if (program) {
348      shProg = _mesa_lookup_shader_program_err(ctx, program,
349                                               "glUseProgramStages");
350      if (shProg == NULL)
351         return;
352
353      /* Section 2.11.4 (Program Pipeline Objects) of the OpenGL 4.1 spec
354       * says:
355       *
356       *     "If the program object named by program was linked without the
357       *     PROGRAM_SEPARABLE parameter set, or was not linked successfully,
358       *     the error INVALID_OPERATION is generated and the corresponding
359       *     shader stages in the pipeline program pipeline object are not
360       *     modified."
361       */
362      if (!shProg->data->LinkStatus) {
363         _mesa_error(ctx, GL_INVALID_OPERATION,
364                     "glUseProgramStages(program not linked)");
365         return;
366      }
367
368      if (!shProg->SeparateShader) {
369         _mesa_error(ctx, GL_INVALID_OPERATION,
370                     "glUseProgramStages(program wasn't linked with the "
371                     "PROGRAM_SEPARABLE flag)");
372         return;
373      }
374   }
375
376   use_program_stages(ctx, shProg, stages, pipe);
377}
378
379static ALWAYS_INLINE void
380active_shader_program(struct gl_context *ctx, GLuint pipeline, GLuint program,
381                      bool no_error)
382{
383   struct gl_shader_program *shProg = NULL;
384   struct gl_pipeline_object *pipe = _mesa_lookup_pipeline_object(ctx, pipeline);
385
386   if (program) {
387      if (no_error) {
388         shProg = _mesa_lookup_shader_program(ctx, program);
389      } else {
390         shProg = _mesa_lookup_shader_program_err(ctx, program,
391                                                  "glActiveShaderProgram(program)");
392         if (shProg == NULL)
393            return;
394      }
395   }
396
397   if (!no_error && !pipe) {
398      _mesa_error(ctx, GL_INVALID_OPERATION, "glActiveShaderProgram(pipeline)");
399      return;
400   }
401
402   /* Object is created by any Pipeline call but glGenProgramPipelines,
403    * glIsProgramPipeline and GetProgramPipelineInfoLog
404    */
405   pipe->EverBound = GL_TRUE;
406
407   if (!no_error && shProg != NULL && !shProg->data->LinkStatus) {
408      _mesa_error(ctx, GL_INVALID_OPERATION,
409            "glActiveShaderProgram(program %u not linked)", shProg->Name);
410      return;
411   }
412
413   _mesa_reference_shader_program(ctx, &pipe->ActiveProgram, shProg);
414   if (pipe == ctx->_Shader)
415      _mesa_update_valid_to_render_state(ctx);
416}
417
418void GLAPIENTRY
419_mesa_ActiveShaderProgram_no_error(GLuint pipeline, GLuint program)
420{
421   GET_CURRENT_CONTEXT(ctx);
422   active_shader_program(ctx, pipeline, program, true);
423}
424
425/**
426 * Use the named shader program for subsequent glUniform calls (if pipeline
427 * bound)
428 */
429void GLAPIENTRY
430_mesa_ActiveShaderProgram(GLuint pipeline, GLuint program)
431{
432   GET_CURRENT_CONTEXT(ctx);
433
434   if (MESA_VERBOSE & VERBOSE_API)
435      _mesa_debug(ctx, "glActiveShaderProgram(%u, %u)\n", pipeline, program);
436
437   active_shader_program(ctx, pipeline, program, false);
438}
439
440static ALWAYS_INLINE void
441bind_program_pipeline(struct gl_context *ctx, GLuint pipeline, bool no_error)
442{
443   struct gl_pipeline_object *newObj = NULL;
444
445   if (MESA_VERBOSE & VERBOSE_API)
446      _mesa_debug(ctx, "glBindProgramPipeline(%u)\n", pipeline);
447
448   /* Rebinding the same pipeline object: no change.
449    */
450   if (ctx->_Shader->Name == pipeline)
451      return;
452
453   /* Section 2.17.2 (Transform Feedback Primitive Capture) of the OpenGL 4.1
454    * spec says:
455    *
456    *     "The error INVALID_OPERATION is generated:
457    *
458    *      ...
459    *
460    *         - by BindProgramPipeline if the current transform feedback
461    *           object is active and not paused;
462    */
463   if (!no_error && _mesa_is_xfb_active_and_unpaused(ctx)) {
464      _mesa_error(ctx, GL_INVALID_OPERATION,
465            "glBindProgramPipeline(transform feedback active)");
466      return;
467   }
468
469   /* Get pointer to new pipeline object (newObj)
470    */
471   if (pipeline) {
472      /* non-default pipeline object */
473      newObj = _mesa_lookup_pipeline_object(ctx, pipeline);
474      if (!no_error && !newObj) {
475         _mesa_error(ctx, GL_INVALID_OPERATION,
476                     "glBindProgramPipeline(non-gen name)");
477         return;
478      }
479
480      /* Object is created by any Pipeline call but glGenProgramPipelines,
481       * glIsProgramPipeline and GetProgramPipelineInfoLog
482       */
483      newObj->EverBound = GL_TRUE;
484   }
485
486   _mesa_bind_pipeline(ctx, newObj);
487}
488
489void GLAPIENTRY
490_mesa_BindProgramPipeline_no_error(GLuint pipeline)
491{
492   GET_CURRENT_CONTEXT(ctx);
493   bind_program_pipeline(ctx, pipeline, true);
494}
495
496/**
497 * Make program of the pipeline current
498 */
499void GLAPIENTRY
500_mesa_BindProgramPipeline(GLuint pipeline)
501{
502   GET_CURRENT_CONTEXT(ctx);
503   bind_program_pipeline(ctx, pipeline, false);
504}
505
506void
507_mesa_bind_pipeline(struct gl_context *ctx,
508                    struct gl_pipeline_object *pipe)
509{
510   int i;
511   /* First bind the Pipeline to pipeline binding point */
512   _mesa_reference_pipeline_object(ctx, &ctx->Pipeline.Current, pipe);
513
514   /* Section 2.11.3 (Program Objects) of the OpenGL 4.1 spec says:
515    *
516    *     "If there is a current program object established by UseProgram,
517    *     that program is considered current for all stages. Otherwise, if
518    *     there is a bound program pipeline object (see section 2.11.4), the
519    *     program bound to the appropriate stage of the pipeline object is
520    *     considered current."
521    */
522   if (&ctx->Shader != ctx->_Shader) {
523      FLUSH_VERTICES(ctx, _NEW_PROGRAM | _NEW_PROGRAM_CONSTANTS, 0);
524
525      if (pipe != NULL) {
526         /* Bound the pipeline to the current program and
527          * restore the pipeline state
528          */
529         _mesa_reference_pipeline_object(ctx, &ctx->_Shader, pipe);
530      } else {
531         /* Unbind the pipeline */
532         _mesa_reference_pipeline_object(ctx, &ctx->_Shader,
533                                         ctx->Pipeline.Default);
534      }
535
536      for (i = 0; i < MESA_SHADER_STAGES; i++) {
537         struct gl_program *prog = ctx->_Shader->CurrentProgram[i];
538         if (prog) {
539            _mesa_program_init_subroutine_defaults(ctx, prog);
540         }
541      }
542
543      _mesa_update_vertex_processing_mode(ctx);
544      _mesa_update_allow_draw_out_of_order(ctx);
545      _mesa_update_valid_to_render_state(ctx);
546   }
547}
548
549/**
550 * Delete a set of pipeline objects.
551 *
552 * \param n      Number of pipeline objects to delete.
553 * \param ids    pipeline of \c n pipeline object IDs.
554 */
555void GLAPIENTRY
556_mesa_DeleteProgramPipelines(GLsizei n, const GLuint *pipelines)
557{
558   GET_CURRENT_CONTEXT(ctx);
559   GLsizei i;
560
561   if (MESA_VERBOSE & VERBOSE_API)
562      _mesa_debug(ctx, "glDeleteProgramPipelines(%d, %p)\n", n, pipelines);
563
564   if (n < 0) {
565      _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteProgramPipelines(n<0)");
566      return;
567   }
568
569   for (i = 0; i < n; i++) {
570      struct gl_pipeline_object *obj =
571         _mesa_lookup_pipeline_object(ctx, pipelines[i]);
572
573      if (obj) {
574         assert(obj->Name == pipelines[i]);
575
576         /* If the pipeline object is currently bound, the spec says "If an
577          * object that is currently bound is deleted, the binding for that
578          * object reverts to zero and no program pipeline object becomes
579          * current."
580          */
581         if (obj == ctx->Pipeline.Current) {
582            _mesa_BindProgramPipeline(0);
583         }
584
585         /* The ID is immediately freed for re-use */
586         remove_pipeline_object(ctx, obj);
587
588         /* Unreference the pipeline object.
589          * If refcount hits zero, the object will be deleted.
590          */
591         _mesa_reference_pipeline_object(ctx, &obj, NULL);
592      }
593   }
594}
595
596/**
597 * Generate a set of unique pipeline object IDs and store them in \c pipelines.
598 * \param n       Number of IDs to generate.
599 * \param pipelines  pipeline of \c n locations to store the IDs.
600 */
601static void
602create_program_pipelines(struct gl_context *ctx, GLsizei n, GLuint *pipelines,
603                         bool dsa)
604{
605   const char *func = dsa ? "glCreateProgramPipelines" : "glGenProgramPipelines";
606   GLint i;
607
608   if (!pipelines)
609      return;
610
611   _mesa_HashFindFreeKeys(ctx->Pipeline.Objects, pipelines, n);
612
613   for (i = 0; i < n; i++) {
614      struct gl_pipeline_object *obj;
615
616      obj = _mesa_new_pipeline_object(ctx, pipelines[i]);
617      if (!obj) {
618         _mesa_error(ctx, GL_OUT_OF_MEMORY, "%s", func);
619         return;
620      }
621
622      if (dsa) {
623         /* make dsa-allocated objects behave like program objects */
624         obj->EverBound = GL_TRUE;
625      }
626
627      save_pipeline_object(ctx, obj);
628   }
629}
630
631static void
632create_program_pipelines_err(struct gl_context *ctx, GLsizei n,
633                             GLuint *pipelines, bool dsa)
634{
635   const char *func = dsa ? "glCreateProgramPipelines" : "glGenProgramPipelines";
636
637   if (n < 0) {
638      _mesa_error(ctx, GL_INVALID_VALUE, "%s (n < 0)", func);
639      return;
640   }
641
642   create_program_pipelines(ctx, n, pipelines, dsa);
643}
644
645void GLAPIENTRY
646_mesa_GenProgramPipelines_no_error(GLsizei n, GLuint *pipelines)
647{
648   GET_CURRENT_CONTEXT(ctx);
649   create_program_pipelines(ctx, n, pipelines, false);
650}
651
652void GLAPIENTRY
653_mesa_GenProgramPipelines(GLsizei n, GLuint *pipelines)
654{
655   GET_CURRENT_CONTEXT(ctx);
656
657   if (MESA_VERBOSE & VERBOSE_API)
658      _mesa_debug(ctx, "glGenProgramPipelines(%d, %p)\n", n, pipelines);
659
660   create_program_pipelines_err(ctx, n, pipelines, false);
661}
662
663void GLAPIENTRY
664_mesa_CreateProgramPipelines_no_error(GLsizei n, GLuint *pipelines)
665{
666   GET_CURRENT_CONTEXT(ctx);
667   create_program_pipelines(ctx, n, pipelines, true);
668}
669
670void GLAPIENTRY
671_mesa_CreateProgramPipelines(GLsizei n, GLuint *pipelines)
672{
673   GET_CURRENT_CONTEXT(ctx);
674
675   if (MESA_VERBOSE & VERBOSE_API)
676      _mesa_debug(ctx, "glCreateProgramPipelines(%d, %p)\n", n, pipelines);
677
678   create_program_pipelines_err(ctx, n, pipelines, true);
679}
680
681/**
682 * Determine if ID is the name of an pipeline object.
683 *
684 * \param id  ID of the potential pipeline object.
685 * \return  \c GL_TRUE if \c id is the name of a pipeline object,
686 *          \c GL_FALSE otherwise.
687 */
688GLboolean GLAPIENTRY
689_mesa_IsProgramPipeline(GLuint pipeline)
690{
691   GET_CURRENT_CONTEXT(ctx);
692
693   if (MESA_VERBOSE & VERBOSE_API)
694      _mesa_debug(ctx, "glIsProgramPipeline(%u)\n", pipeline);
695
696   struct gl_pipeline_object *obj = _mesa_lookup_pipeline_object(ctx, pipeline);
697   if (obj == NULL)
698      return GL_FALSE;
699
700   return obj->EverBound;
701}
702
703/**
704 * glGetProgramPipelineiv() - get pipeline shader state.
705 */
706void GLAPIENTRY
707_mesa_GetProgramPipelineiv(GLuint pipeline, GLenum pname, GLint *params)
708{
709   GET_CURRENT_CONTEXT(ctx);
710   struct gl_pipeline_object *pipe = _mesa_lookup_pipeline_object(ctx, pipeline);
711
712   if (MESA_VERBOSE & VERBOSE_API)
713      _mesa_debug(ctx, "glGetProgramPipelineiv(%u, %d, %p)\n",
714                  pipeline, pname, params);
715
716   /* Are geometry shaders available in this context?
717    */
718   const bool has_gs = _mesa_has_geometry_shaders(ctx);
719   const bool has_tess = _mesa_has_tessellation(ctx);
720
721   if (!pipe) {
722      _mesa_error(ctx, GL_INVALID_OPERATION,
723                  "glGetProgramPipelineiv(pipeline)");
724      return;
725   }
726
727   /* Object is created by any Pipeline call but glGenProgramPipelines,
728    * glIsProgramPipeline and GetProgramPipelineInfoLog
729    */
730   pipe->EverBound = GL_TRUE;
731
732   switch (pname) {
733   case GL_ACTIVE_PROGRAM:
734      *params = pipe->ActiveProgram ? pipe->ActiveProgram->Name : 0;
735      return;
736   case GL_INFO_LOG_LENGTH:
737      *params = (pipe->InfoLog && pipe->InfoLog[0] != '\0') ?
738         strlen(pipe->InfoLog) + 1 : 0;
739      return;
740   case GL_VALIDATE_STATUS:
741      *params = pipe->UserValidated;
742      return;
743   case GL_VERTEX_SHADER:
744      *params = pipe->CurrentProgram[MESA_SHADER_VERTEX]
745         ? pipe->CurrentProgram[MESA_SHADER_VERTEX]->Id : 0;
746      return;
747   case GL_TESS_EVALUATION_SHADER:
748      if (!has_tess)
749         break;
750      *params = pipe->CurrentProgram[MESA_SHADER_TESS_EVAL]
751         ? pipe->CurrentProgram[MESA_SHADER_TESS_EVAL]->Id : 0;
752      return;
753   case GL_TESS_CONTROL_SHADER:
754      if (!has_tess)
755         break;
756      *params = pipe->CurrentProgram[MESA_SHADER_TESS_CTRL]
757         ? pipe->CurrentProgram[MESA_SHADER_TESS_CTRL]->Id : 0;
758      return;
759   case GL_GEOMETRY_SHADER:
760      if (!has_gs)
761         break;
762      *params = pipe->CurrentProgram[MESA_SHADER_GEOMETRY]
763         ? pipe->CurrentProgram[MESA_SHADER_GEOMETRY]->Id : 0;
764      return;
765   case GL_FRAGMENT_SHADER:
766      *params = pipe->CurrentProgram[MESA_SHADER_FRAGMENT]
767         ? pipe->CurrentProgram[MESA_SHADER_FRAGMENT]->Id : 0;
768      return;
769   case GL_COMPUTE_SHADER:
770      if (!_mesa_has_compute_shaders(ctx))
771         break;
772      *params = pipe->CurrentProgram[MESA_SHADER_COMPUTE]
773         ? pipe->CurrentProgram[MESA_SHADER_COMPUTE]->Id : 0;
774      return;
775   default:
776      break;
777   }
778
779   _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramPipelineiv(pname=%s)",
780               _mesa_enum_to_string(pname));
781}
782
783/**
784 * Determines whether every stage in a linked program is active in the
785 * specified pipeline.
786 */
787static bool
788program_stages_all_active(struct gl_pipeline_object *pipe,
789                          const struct gl_program *prog)
790{
791   bool status = true;
792
793   if (!prog)
794      return true;
795
796   unsigned mask = prog->sh.data->linked_stages;
797   while (mask) {
798      const int i = u_bit_scan(&mask);
799      if (pipe->CurrentProgram[i]) {
800         if (prog->Id != pipe->CurrentProgram[i]->Id) {
801            status = false;
802         }
803      } else {
804         status = false;
805      }
806   }
807
808   if (!status) {
809      pipe->InfoLog = ralloc_asprintf(pipe,
810                                      "Program %d is not active for all "
811                                      "shaders that was linked",
812                                      prog->Id);
813   }
814
815   return status;
816}
817
818static bool
819program_stages_interleaved_illegally(const struct gl_pipeline_object *pipe)
820{
821   unsigned prev_linked_stages = 0;
822
823   /* Look for programs bound to stages: A -> B -> A, with any intervening
824    * sequence of unrelated programs or empty stages.
825    */
826   for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
827      struct gl_program *cur = pipe->CurrentProgram[i];
828
829      /* Empty stages anywhere in the pipe are OK.  Also we can be confident
830       * that if the linked_stages mask matches we are looking at the same
831       * linked program because a previous validation call to
832       * program_stages_all_active() will have already failed if two different
833       * programs with the sames stages linked are not active for all linked
834       * stages.
835       */
836      if (!cur || cur->sh.data->linked_stages == prev_linked_stages)
837         continue;
838
839      if (prev_linked_stages) {
840         /* We've seen an A -> B transition; look at the rest of the pipe
841          * to see if we ever see A again.
842          */
843         if (prev_linked_stages >> (i + 1))
844            return true;
845      }
846
847      prev_linked_stages = cur->sh.data->linked_stages;
848   }
849
850   return false;
851}
852
853extern GLboolean
854_mesa_validate_program_pipeline(struct gl_context* ctx,
855                                struct gl_pipeline_object *pipe)
856{
857   unsigned i;
858   bool program_empty = true;
859
860   pipe->Validated = GL_FALSE;
861
862   /* Release and reset the info log.
863    */
864   if (pipe->InfoLog != NULL)
865      ralloc_free(pipe->InfoLog);
866
867   pipe->InfoLog = NULL;
868
869   /* Section 2.11.11 (Shader Execution), subheading "Validation," of the
870    * OpenGL 4.1 spec says:
871    *
872    *     "[INVALID_OPERATION] is generated by any command that transfers
873    *     vertices to the GL if:
874    *
875    *         - A program object is active for at least one, but not all of
876    *           the shader stages that were present when the program was
877    *           linked."
878    *
879    * For each possible program stage, verify that the program bound to that
880    * stage has all of its stages active.  In other words, if the program
881    * bound to the vertex stage also has a fragment shader, the fragment
882    * shader must also be bound to the fragment stage.
883    */
884   for (i = 0; i < MESA_SHADER_STAGES; i++) {
885      if (!program_stages_all_active(pipe, pipe->CurrentProgram[i])) {
886         return GL_FALSE;
887      }
888   }
889
890   /* Section 2.11.11 (Shader Execution), subheading "Validation," of the
891    * OpenGL 4.1 spec says:
892    *
893    *     "[INVALID_OPERATION] is generated by any command that transfers
894    *     vertices to the GL if:
895    *
896    *         ...
897    *
898    *         - One program object is active for at least two shader stages
899    *           and a second program is active for a shader stage between two
900    *           stages for which the first program was active."
901    */
902   if (program_stages_interleaved_illegally(pipe)) {
903      pipe->InfoLog =
904         ralloc_strdup(pipe,
905                       "Program is active for multiple shader stages with an "
906                       "intervening stage provided by another program");
907      return GL_FALSE;
908   }
909
910   /* Section 2.11.11 (Shader Execution), subheading "Validation," of the
911    * OpenGL 4.1 spec says:
912    *
913    *     "[INVALID_OPERATION] is generated by any command that transfers
914    *     vertices to the GL if:
915    *
916    *         ...
917    *
918    *         - There is an active program for tessellation control,
919    *           tessellation evaluation, or geometry stages with corresponding
920    *           executable shader, but there is no active program with
921    *           executable vertex shader."
922    */
923   if (!pipe->CurrentProgram[MESA_SHADER_VERTEX]
924       && (pipe->CurrentProgram[MESA_SHADER_GEOMETRY] ||
925           pipe->CurrentProgram[MESA_SHADER_TESS_CTRL] ||
926           pipe->CurrentProgram[MESA_SHADER_TESS_EVAL])) {
927      pipe->InfoLog = ralloc_strdup(pipe, "Program lacks a vertex shader");
928      return GL_FALSE;
929   }
930
931   /* Section 2.11.11 (Shader Execution), subheading "Validation," of the
932    * OpenGL 4.1 spec says:
933    *
934    *     "[INVALID_OPERATION] is generated by any command that transfers
935    *     vertices to the GL if:
936    *
937    *         ...
938    *
939    *         - There is no current program object specified by UseProgram,
940    *           there is a current program pipeline object, and the current
941    *           program for any shader stage has been relinked since being
942    *           applied to the pipeline object via UseProgramStages with the
943    *           PROGRAM_SEPARABLE parameter set to FALSE.
944    */
945   for (i = 0; i < MESA_SHADER_STAGES; i++) {
946      if (pipe->CurrentProgram[i] &&
947          !pipe->CurrentProgram[i]->info.separate_shader) {
948         pipe->InfoLog = ralloc_asprintf(pipe,
949                                         "Program %d was relinked without "
950                                         "PROGRAM_SEPARABLE state",
951                                         pipe->CurrentProgram[i]->Id);
952         return GL_FALSE;
953      }
954   }
955
956   /* Section 11.1.3.11 (Validation) of the OpenGL 4.5 spec says:
957    *
958    *    "An INVALID_OPERATION error is generated by any command that trans-
959    *    fers vertices to the GL or launches compute work if the current set
960    *    of active program objects cannot be executed, for reasons including:
961    *
962    *       ...
963    *
964    *       - There is no current program object specified by UseProgram,
965    *         there is a current program pipeline object, and that object is
966    *         empty (no executable code is installed for any stage).
967    */
968   for (i = 0; i < MESA_SHADER_STAGES; i++) {
969      if (pipe->CurrentProgram[i]) {
970         program_empty = false;
971         break;
972      }
973   }
974
975   if (program_empty) {
976      return GL_FALSE;
977   }
978
979   /* Section 2.11.11 (Shader Execution), subheading "Validation," of the
980    * OpenGL 4.1 spec says:
981    *
982    *     "[INVALID_OPERATION] is generated by any command that transfers
983    *     vertices to the GL if:
984    *
985    *         ...
986    *
987    *         - Any two active samplers in the current program object are of
988    *           different types, but refer to the same texture image unit.
989    *
990    *         - The number of active samplers in the program exceeds the
991    *           maximum number of texture image units allowed."
992    */
993   if (!_mesa_sampler_uniforms_pipeline_are_valid(pipe))
994      return GL_FALSE;
995
996   /* Validate inputs against outputs, this cannot be done during linking
997    * since programs have been linked separately from each other.
998    *
999    * Section 11.1.3.11 (Validation) of the OpenGL 4.5 Core Profile spec says:
1000    *
1001    *     "Separable program objects may have validation failures that cannot be
1002    *     detected without the complete program pipeline. Mismatched interfaces,
1003    *     improper usage of program objects together, and the same
1004    *     state-dependent failures can result in validation errors for such
1005    *     program objects."
1006    *
1007    * OpenGL ES 3.1 specification has the same text.
1008    *
1009    * Section 11.1.3.11 (Validation) of the OpenGL ES spec also says:
1010    *
1011    *    An INVALID_OPERATION error is generated by any command that transfers
1012    *    vertices to the GL or launches compute work if the current set of
1013    *    active program objects cannot be executed, for reasons including:
1014    *
1015    *    * The current program pipeline object contains a shader interface
1016    *      that doesn't have an exact match (see section 7.4.1)
1017    *
1018    * Based on this, only perform the most-strict checking on ES or when the
1019    * application has created a debug context.
1020    */
1021   if ((_mesa_is_gles(ctx) || (ctx->Const.ContextFlags & GL_CONTEXT_FLAG_DEBUG_BIT)) &&
1022       !_mesa_validate_pipeline_io(pipe)) {
1023      if (_mesa_is_gles(ctx))
1024         return GL_FALSE;
1025
1026      static GLuint msg_id = 0;
1027
1028      _mesa_gl_debugf(ctx, &msg_id,
1029                      MESA_DEBUG_SOURCE_API,
1030                      MESA_DEBUG_TYPE_PORTABILITY,
1031                      MESA_DEBUG_SEVERITY_MEDIUM,
1032                      "glValidateProgramPipeline: pipeline %u does not meet "
1033                      "strict OpenGL ES 3.1 requirements and may not be "
1034                      "portable across desktop hardware\n",
1035                      pipe->Name);
1036   }
1037
1038   pipe->Validated = GL_TRUE;
1039   return GL_TRUE;
1040}
1041
1042/**
1043 * Check compatibility of pipeline's program
1044 */
1045void GLAPIENTRY
1046_mesa_ValidateProgramPipeline(GLuint pipeline)
1047{
1048   GET_CURRENT_CONTEXT(ctx);
1049
1050   if (MESA_VERBOSE & VERBOSE_API)
1051      _mesa_debug(ctx, "glValidateProgramPipeline(%u)\n", pipeline);
1052
1053   struct gl_pipeline_object *pipe = _mesa_lookup_pipeline_object(ctx, pipeline);
1054
1055   if (!pipe) {
1056      _mesa_error(ctx, GL_INVALID_OPERATION,
1057                  "glValidateProgramPipeline(pipeline)");
1058      return;
1059   }
1060
1061   _mesa_validate_program_pipeline(ctx, pipe);
1062   pipe->UserValidated = pipe->Validated;
1063}
1064
1065void GLAPIENTRY
1066_mesa_GetProgramPipelineInfoLog(GLuint pipeline, GLsizei bufSize,
1067                                GLsizei *length, GLchar *infoLog)
1068{
1069   GET_CURRENT_CONTEXT(ctx);
1070
1071   if (MESA_VERBOSE & VERBOSE_API)
1072      _mesa_debug(ctx, "glGetProgramPipelineInfoLog(%u, %d, %p, %p)\n",
1073                  pipeline, bufSize, length, infoLog);
1074
1075   struct gl_pipeline_object *pipe = _mesa_lookup_pipeline_object(ctx, pipeline);
1076
1077   if (!pipe) {
1078      _mesa_error(ctx, GL_INVALID_VALUE,
1079                  "glGetProgramPipelineInfoLog(pipeline)");
1080      return;
1081   }
1082
1083   if (bufSize < 0) {
1084      _mesa_error(ctx, GL_INVALID_VALUE,
1085                  "glGetProgramPipelineInfoLog(bufSize)");
1086      return;
1087   }
1088
1089   _mesa_copy_string(infoLog, bufSize, length, pipe->InfoLog);
1090}
1091