brw_fs.cpp revision 454dc83f66643e66ea7ee9117368211f0cfe84d7
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 DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24/** @file brw_fs.cpp
25 *
26 * This file drives the GLSL IR -> LIR translation, contains the
27 * optimizations on the LIR, and drives the generation of native code
28 * from the LIR.
29 */
30
31extern "C" {
32
33#include <sys/types.h>
34
35#include "main/macros.h"
36#include "main/shaderobj.h"
37#include "main/uniforms.h"
38#include "main/fbobject.h"
39#include "program/prog_parameter.h"
40#include "program/prog_print.h"
41#include "program/register_allocate.h"
42#include "program/sampler.h"
43#include "program/hash_table.h"
44#include "brw_context.h"
45#include "brw_eu.h"
46#include "brw_wm.h"
47}
48#include "brw_shader.h"
49#include "brw_fs.h"
50#include "glsl/glsl_types.h"
51#include "glsl/ir_print_visitor.h"
52
53void
54fs_inst::init()
55{
56   memset(this, 0, sizeof(*this));
57   this->opcode = BRW_OPCODE_NOP;
58   this->conditional_mod = BRW_CONDITIONAL_NONE;
59
60   this->dst = reg_undef;
61   this->src[0] = reg_undef;
62   this->src[1] = reg_undef;
63   this->src[2] = reg_undef;
64}
65
66fs_inst::fs_inst()
67{
68   init();
69}
70
71fs_inst::fs_inst(enum opcode opcode)
72{
73   init();
74   this->opcode = opcode;
75}
76
77fs_inst::fs_inst(enum opcode opcode, fs_reg dst)
78{
79   init();
80   this->opcode = opcode;
81   this->dst = dst;
82
83   if (dst.file == GRF)
84      assert(dst.reg_offset >= 0);
85}
86
87fs_inst::fs_inst(enum opcode opcode, fs_reg dst, fs_reg src0)
88{
89   init();
90   this->opcode = opcode;
91   this->dst = dst;
92   this->src[0] = src0;
93
94   if (dst.file == GRF)
95      assert(dst.reg_offset >= 0);
96   if (src[0].file == GRF)
97      assert(src[0].reg_offset >= 0);
98}
99
100fs_inst::fs_inst(enum opcode opcode, fs_reg dst, fs_reg src0, fs_reg src1)
101{
102   init();
103   this->opcode = opcode;
104   this->dst = dst;
105   this->src[0] = src0;
106   this->src[1] = src1;
107
108   if (dst.file == GRF)
109      assert(dst.reg_offset >= 0);
110   if (src[0].file == GRF)
111      assert(src[0].reg_offset >= 0);
112   if (src[1].file == GRF)
113      assert(src[1].reg_offset >= 0);
114}
115
116fs_inst::fs_inst(enum opcode opcode, fs_reg dst,
117		 fs_reg src0, fs_reg src1, fs_reg src2)
118{
119   init();
120   this->opcode = opcode;
121   this->dst = dst;
122   this->src[0] = src0;
123   this->src[1] = src1;
124   this->src[2] = src2;
125
126   if (dst.file == GRF)
127      assert(dst.reg_offset >= 0);
128   if (src[0].file == GRF)
129      assert(src[0].reg_offset >= 0);
130   if (src[1].file == GRF)
131      assert(src[1].reg_offset >= 0);
132   if (src[2].file == GRF)
133      assert(src[2].reg_offset >= 0);
134}
135
136bool
137fs_inst::equals(fs_inst *inst)
138{
139   return (opcode == inst->opcode &&
140           dst.equals(inst->dst) &&
141           src[0].equals(inst->src[0]) &&
142           src[1].equals(inst->src[1]) &&
143           src[2].equals(inst->src[2]) &&
144           saturate == inst->saturate &&
145           predicated == inst->predicated &&
146           conditional_mod == inst->conditional_mod &&
147           mlen == inst->mlen &&
148           base_mrf == inst->base_mrf &&
149           sampler == inst->sampler &&
150           target == inst->target &&
151           eot == inst->eot &&
152           header_present == inst->header_present &&
153           shadow_compare == inst->shadow_compare &&
154           offset == inst->offset);
155}
156
157int
158fs_inst::regs_written()
159{
160   if (is_tex())
161      return 4;
162
163   /* The SINCOS and INT_DIV_QUOTIENT_AND_REMAINDER math functions return 2,
164    * but we don't currently use them...nor do we have an opcode for them.
165    */
166
167   return 1;
168}
169
170bool
171fs_inst::overwrites_reg(const fs_reg &reg)
172{
173   return (reg.file == dst.file &&
174           reg.reg == dst.reg &&
175           reg.reg_offset >= dst.reg_offset  &&
176           reg.reg_offset < dst.reg_offset + regs_written());
177}
178
179bool
180fs_inst::is_tex()
181{
182   return (opcode == SHADER_OPCODE_TEX ||
183           opcode == FS_OPCODE_TXB ||
184           opcode == SHADER_OPCODE_TXD ||
185           opcode == SHADER_OPCODE_TXF ||
186           opcode == SHADER_OPCODE_TXL ||
187           opcode == SHADER_OPCODE_TXS);
188}
189
190bool
191fs_inst::is_math()
192{
193   return (opcode == SHADER_OPCODE_RCP ||
194           opcode == SHADER_OPCODE_RSQ ||
195           opcode == SHADER_OPCODE_SQRT ||
196           opcode == SHADER_OPCODE_EXP2 ||
197           opcode == SHADER_OPCODE_LOG2 ||
198           opcode == SHADER_OPCODE_SIN ||
199           opcode == SHADER_OPCODE_COS ||
200           opcode == SHADER_OPCODE_INT_QUOTIENT ||
201           opcode == SHADER_OPCODE_INT_REMAINDER ||
202           opcode == SHADER_OPCODE_POW);
203}
204
205void
206fs_reg::init()
207{
208   memset(this, 0, sizeof(*this));
209   this->smear = -1;
210}
211
212/** Generic unset register constructor. */
213fs_reg::fs_reg()
214{
215   init();
216   this->file = BAD_FILE;
217}
218
219/** Immediate value constructor. */
220fs_reg::fs_reg(float f)
221{
222   init();
223   this->file = IMM;
224   this->type = BRW_REGISTER_TYPE_F;
225   this->imm.f = f;
226}
227
228/** Immediate value constructor. */
229fs_reg::fs_reg(int32_t i)
230{
231   init();
232   this->file = IMM;
233   this->type = BRW_REGISTER_TYPE_D;
234   this->imm.i = i;
235}
236
237/** Immediate value constructor. */
238fs_reg::fs_reg(uint32_t u)
239{
240   init();
241   this->file = IMM;
242   this->type = BRW_REGISTER_TYPE_UD;
243   this->imm.u = u;
244}
245
246/** Fixed brw_reg Immediate value constructor. */
247fs_reg::fs_reg(struct brw_reg fixed_hw_reg)
248{
249   init();
250   this->file = FIXED_HW_REG;
251   this->fixed_hw_reg = fixed_hw_reg;
252   this->type = fixed_hw_reg.type;
253}
254
255bool
256fs_reg::equals(const fs_reg &r) const
257{
258   return (file == r.file &&
259           reg == r.reg &&
260           reg_offset == r.reg_offset &&
261           type == r.type &&
262           negate == r.negate &&
263           abs == r.abs &&
264           memcmp(&fixed_hw_reg, &r.fixed_hw_reg,
265                  sizeof(fixed_hw_reg)) == 0 &&
266           smear == r.smear &&
267           imm.u == r.imm.u);
268}
269
270int
271fs_visitor::type_size(const struct glsl_type *type)
272{
273   unsigned int size, i;
274
275   switch (type->base_type) {
276   case GLSL_TYPE_UINT:
277   case GLSL_TYPE_INT:
278   case GLSL_TYPE_FLOAT:
279   case GLSL_TYPE_BOOL:
280      return type->components();
281   case GLSL_TYPE_ARRAY:
282      return type_size(type->fields.array) * type->length;
283   case GLSL_TYPE_STRUCT:
284      size = 0;
285      for (i = 0; i < type->length; i++) {
286	 size += type_size(type->fields.structure[i].type);
287      }
288      return size;
289   case GLSL_TYPE_SAMPLER:
290      /* Samplers take up no register space, since they're baked in at
291       * link time.
292       */
293      return 0;
294   default:
295      assert(!"not reached");
296      return 0;
297   }
298}
299
300void
301fs_visitor::fail(const char *format, ...)
302{
303   va_list va;
304   char *msg;
305
306   if (failed)
307      return;
308
309   failed = true;
310
311   va_start(va, format);
312   msg = ralloc_vasprintf(mem_ctx, format, va);
313   va_end(va);
314   msg = ralloc_asprintf(mem_ctx, "FS compile failed: %s\n", msg);
315
316   this->fail_msg = msg;
317
318   if (INTEL_DEBUG & DEBUG_WM) {
319      fprintf(stderr, "%s",  msg);
320   }
321}
322
323fs_inst *
324fs_visitor::emit(enum opcode opcode)
325{
326   return emit(fs_inst(opcode));
327}
328
329fs_inst *
330fs_visitor::emit(enum opcode opcode, fs_reg dst)
331{
332   return emit(fs_inst(opcode, dst));
333}
334
335fs_inst *
336fs_visitor::emit(enum opcode opcode, fs_reg dst, fs_reg src0)
337{
338   return emit(fs_inst(opcode, dst, src0));
339}
340
341fs_inst *
342fs_visitor::emit(enum opcode opcode, fs_reg dst, fs_reg src0, fs_reg src1)
343{
344   return emit(fs_inst(opcode, dst, src0, src1));
345}
346
347fs_inst *
348fs_visitor::emit(enum opcode opcode, fs_reg dst,
349                 fs_reg src0, fs_reg src1, fs_reg src2)
350{
351   return emit(fs_inst(opcode, dst, src0, src1, src2));
352}
353
354void
355fs_visitor::push_force_uncompressed()
356{
357   force_uncompressed_stack++;
358}
359
360void
361fs_visitor::pop_force_uncompressed()
362{
363   force_uncompressed_stack--;
364   assert(force_uncompressed_stack >= 0);
365}
366
367void
368fs_visitor::push_force_sechalf()
369{
370   force_sechalf_stack++;
371}
372
373void
374fs_visitor::pop_force_sechalf()
375{
376   force_sechalf_stack--;
377   assert(force_sechalf_stack >= 0);
378}
379
380/**
381 * Returns how many MRFs an FS opcode will write over.
382 *
383 * Note that this is not the 0 or 1 implied writes in an actual gen
384 * instruction -- the FS opcodes often generate MOVs in addition.
385 */
386int
387fs_visitor::implied_mrf_writes(fs_inst *inst)
388{
389   if (inst->mlen == 0)
390      return 0;
391
392   switch (inst->opcode) {
393   case SHADER_OPCODE_RCP:
394   case SHADER_OPCODE_RSQ:
395   case SHADER_OPCODE_SQRT:
396   case SHADER_OPCODE_EXP2:
397   case SHADER_OPCODE_LOG2:
398   case SHADER_OPCODE_SIN:
399   case SHADER_OPCODE_COS:
400      return 1 * c->dispatch_width / 8;
401   case SHADER_OPCODE_POW:
402   case SHADER_OPCODE_INT_QUOTIENT:
403   case SHADER_OPCODE_INT_REMAINDER:
404      return 2 * c->dispatch_width / 8;
405   case SHADER_OPCODE_TEX:
406   case FS_OPCODE_TXB:
407   case SHADER_OPCODE_TXD:
408   case SHADER_OPCODE_TXF:
409   case SHADER_OPCODE_TXL:
410   case SHADER_OPCODE_TXS:
411      return 1;
412   case FS_OPCODE_FB_WRITE:
413      return 2;
414   case FS_OPCODE_PULL_CONSTANT_LOAD:
415   case FS_OPCODE_UNSPILL:
416      return 1;
417   case FS_OPCODE_SPILL:
418      return 2;
419   default:
420      assert(!"not reached");
421      return inst->mlen;
422   }
423}
424
425int
426fs_visitor::virtual_grf_alloc(int size)
427{
428   if (virtual_grf_array_size <= virtual_grf_count) {
429      if (virtual_grf_array_size == 0)
430	 virtual_grf_array_size = 16;
431      else
432	 virtual_grf_array_size *= 2;
433      virtual_grf_sizes = reralloc(mem_ctx, virtual_grf_sizes, int,
434				   virtual_grf_array_size);
435   }
436   virtual_grf_sizes[virtual_grf_count] = size;
437   return virtual_grf_count++;
438}
439
440/** Fixed HW reg constructor. */
441fs_reg::fs_reg(enum register_file file, int reg)
442{
443   init();
444   this->file = file;
445   this->reg = reg;
446   this->type = BRW_REGISTER_TYPE_F;
447}
448
449/** Fixed HW reg constructor. */
450fs_reg::fs_reg(enum register_file file, int reg, uint32_t type)
451{
452   init();
453   this->file = file;
454   this->reg = reg;
455   this->type = type;
456}
457
458/** Automatic reg constructor. */
459fs_reg::fs_reg(class fs_visitor *v, const struct glsl_type *type)
460{
461   init();
462
463   this->file = GRF;
464   this->reg = v->virtual_grf_alloc(v->type_size(type));
465   this->reg_offset = 0;
466   this->type = brw_type_for_base_type(type);
467}
468
469fs_reg *
470fs_visitor::variable_storage(ir_variable *var)
471{
472   return (fs_reg *)hash_table_find(this->variable_ht, var);
473}
474
475void
476import_uniforms_callback(const void *key,
477			 void *data,
478			 void *closure)
479{
480   struct hash_table *dst_ht = (struct hash_table *)closure;
481   const fs_reg *reg = (const fs_reg *)data;
482
483   if (reg->file != UNIFORM)
484      return;
485
486   hash_table_insert(dst_ht, data, key);
487}
488
489/* For 16-wide, we need to follow from the uniform setup of 8-wide dispatch.
490 * This brings in those uniform definitions
491 */
492void
493fs_visitor::import_uniforms(fs_visitor *v)
494{
495   hash_table_call_foreach(v->variable_ht,
496			   import_uniforms_callback,
497			   variable_ht);
498   this->params_remap = v->params_remap;
499}
500
501/* Our support for uniforms is piggy-backed on the struct
502 * gl_fragment_program, because that's where the values actually
503 * get stored, rather than in some global gl_shader_program uniform
504 * store.
505 */
506int
507fs_visitor::setup_uniform_values(int loc, const glsl_type *type)
508{
509   unsigned int offset = 0;
510
511   if (type->is_matrix()) {
512      const glsl_type *column = glsl_type::get_instance(GLSL_TYPE_FLOAT,
513							type->vector_elements,
514							1);
515
516      for (unsigned int i = 0; i < type->matrix_columns; i++) {
517	 offset += setup_uniform_values(loc + offset, column);
518      }
519
520      return offset;
521   }
522
523   switch (type->base_type) {
524   case GLSL_TYPE_FLOAT:
525   case GLSL_TYPE_UINT:
526   case GLSL_TYPE_INT:
527   case GLSL_TYPE_BOOL:
528      for (unsigned int i = 0; i < type->vector_elements; i++) {
529	 unsigned int param = c->prog_data.nr_params++;
530
531	 assert(param < ARRAY_SIZE(c->prog_data.param));
532
533	 this->param_index[param] = loc;
534	 this->param_offset[param] = i;
535      }
536      return 1;
537
538   case GLSL_TYPE_STRUCT:
539      for (unsigned int i = 0; i < type->length; i++) {
540	 offset += setup_uniform_values(loc + offset,
541					type->fields.structure[i].type);
542      }
543      return offset;
544
545   case GLSL_TYPE_ARRAY:
546      for (unsigned int i = 0; i < type->length; i++) {
547	 offset += setup_uniform_values(loc + offset, type->fields.array);
548      }
549      return offset;
550
551   case GLSL_TYPE_SAMPLER:
552      /* The sampler takes up a slot, but we don't use any values from it. */
553      return 1;
554
555   default:
556      assert(!"not reached");
557      return 0;
558   }
559}
560
561
562/* Our support for builtin uniforms is even scarier than non-builtin.
563 * It sits on top of the PROG_STATE_VAR parameters that are
564 * automatically updated from GL context state.
565 */
566void
567fs_visitor::setup_builtin_uniform_values(ir_variable *ir)
568{
569   const ir_state_slot *const slots = ir->state_slots;
570   assert(ir->state_slots != NULL);
571
572   for (unsigned int i = 0; i < ir->num_state_slots; i++) {
573      /* This state reference has already been setup by ir_to_mesa, but we'll
574       * get the same index back here.
575       */
576      int index = _mesa_add_state_reference(this->fp->Base.Parameters,
577					    (gl_state_index *)slots[i].tokens);
578
579      /* Add each of the unique swizzles of the element as a parameter.
580       * This'll end up matching the expected layout of the
581       * array/matrix/structure we're trying to fill in.
582       */
583      int last_swiz = -1;
584      for (unsigned int j = 0; j < 4; j++) {
585	 int swiz = GET_SWZ(slots[i].swizzle, j);
586	 if (swiz == last_swiz)
587	    break;
588	 last_swiz = swiz;
589
590	 this->param_index[c->prog_data.nr_params] = index;
591	 this->param_offset[c->prog_data.nr_params] = swiz;
592	 c->prog_data.nr_params++;
593      }
594   }
595}
596
597fs_reg *
598fs_visitor::emit_fragcoord_interpolation(ir_variable *ir)
599{
600   fs_reg *reg = new(this->mem_ctx) fs_reg(this, ir->type);
601   fs_reg wpos = *reg;
602   bool flip = !ir->origin_upper_left ^ c->key.render_to_fbo;
603
604   /* gl_FragCoord.x */
605   if (ir->pixel_center_integer) {
606      emit(BRW_OPCODE_MOV, wpos, this->pixel_x);
607   } else {
608      emit(BRW_OPCODE_ADD, wpos, this->pixel_x, fs_reg(0.5f));
609   }
610   wpos.reg_offset++;
611
612   /* gl_FragCoord.y */
613   if (!flip && ir->pixel_center_integer) {
614      emit(BRW_OPCODE_MOV, wpos, this->pixel_y);
615   } else {
616      fs_reg pixel_y = this->pixel_y;
617      float offset = (ir->pixel_center_integer ? 0.0 : 0.5);
618
619      if (flip) {
620	 pixel_y.negate = true;
621	 offset += c->key.drawable_height - 1.0;
622      }
623
624      emit(BRW_OPCODE_ADD, wpos, pixel_y, fs_reg(offset));
625   }
626   wpos.reg_offset++;
627
628   /* gl_FragCoord.z */
629   if (intel->gen >= 6) {
630      emit(BRW_OPCODE_MOV, wpos,
631	   fs_reg(brw_vec8_grf(c->source_depth_reg, 0)));
632   } else {
633      emit(FS_OPCODE_LINTERP, wpos,
634           this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
635           this->delta_y[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC],
636           interp_reg(FRAG_ATTRIB_WPOS, 2));
637   }
638   wpos.reg_offset++;
639
640   /* gl_FragCoord.w: Already set up in emit_interpolation */
641   emit(BRW_OPCODE_MOV, wpos, this->wpos_w);
642
643   return reg;
644}
645
646fs_inst *
647fs_visitor::emit_linterp(const fs_reg &attr, const fs_reg &interp,
648                         glsl_interp_qualifier interpolation_mode,
649                         bool is_centroid)
650{
651   brw_wm_barycentric_interp_mode barycoord_mode;
652   if (is_centroid) {
653      if (interpolation_mode == INTERP_QUALIFIER_SMOOTH)
654         barycoord_mode = BRW_WM_PERSPECTIVE_CENTROID_BARYCENTRIC;
655      else
656         barycoord_mode = BRW_WM_NONPERSPECTIVE_CENTROID_BARYCENTRIC;
657   } else {
658      if (interpolation_mode == INTERP_QUALIFIER_SMOOTH)
659         barycoord_mode = BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC;
660      else
661         barycoord_mode = BRW_WM_NONPERSPECTIVE_PIXEL_BARYCENTRIC;
662   }
663   return emit(FS_OPCODE_LINTERP, attr,
664               this->delta_x[barycoord_mode],
665               this->delta_y[barycoord_mode], interp);
666}
667
668fs_reg *
669fs_visitor::emit_general_interpolation(ir_variable *ir)
670{
671   fs_reg *reg = new(this->mem_ctx) fs_reg(this, ir->type);
672   reg->type = brw_type_for_base_type(ir->type->get_scalar_type());
673   fs_reg attr = *reg;
674
675   unsigned int array_elements;
676   const glsl_type *type;
677
678   if (ir->type->is_array()) {
679      array_elements = ir->type->length;
680      if (array_elements == 0) {
681	 fail("dereferenced array '%s' has length 0\n", ir->name);
682      }
683      type = ir->type->fields.array;
684   } else {
685      array_elements = 1;
686      type = ir->type;
687   }
688
689   glsl_interp_qualifier interpolation_mode =
690      ir->determine_interpolation_mode(c->key.flat_shade);
691
692   int location = ir->location;
693   for (unsigned int i = 0; i < array_elements; i++) {
694      for (unsigned int j = 0; j < type->matrix_columns; j++) {
695	 if (urb_setup[location] == -1) {
696	    /* If there's no incoming setup data for this slot, don't
697	     * emit interpolation for it.
698	     */
699	    attr.reg_offset += type->vector_elements;
700	    location++;
701	    continue;
702	 }
703
704	 if (interpolation_mode == INTERP_QUALIFIER_FLAT) {
705	    /* Constant interpolation (flat shading) case. The SF has
706	     * handed us defined values in only the constant offset
707	     * field of the setup reg.
708	     */
709	    for (unsigned int k = 0; k < type->vector_elements; k++) {
710	       struct brw_reg interp = interp_reg(location, k);
711	       interp = suboffset(interp, 3);
712               interp.type = reg->type;
713	       emit(FS_OPCODE_CINTERP, attr, fs_reg(interp));
714	       attr.reg_offset++;
715	    }
716	 } else {
717	    /* Smooth/noperspective interpolation case. */
718	    for (unsigned int k = 0; k < type->vector_elements; k++) {
719	       /* FINISHME: At some point we probably want to push
720		* this farther by giving similar treatment to the
721		* other potentially constant components of the
722		* attribute, as well as making brw_vs_constval.c
723		* handle varyings other than gl_TexCoord.
724		*/
725	       if (location >= FRAG_ATTRIB_TEX0 &&
726		   location <= FRAG_ATTRIB_TEX7 &&
727		   k == 3 && !(c->key.proj_attrib_mask & (1 << location))) {
728		  emit(BRW_OPCODE_MOV, attr, fs_reg(1.0f));
729	       } else {
730		  struct brw_reg interp = interp_reg(location, k);
731                  emit_linterp(attr, fs_reg(interp), interpolation_mode,
732                               ir->centroid);
733                  if (brw->needs_unlit_centroid_workaround && ir->centroid) {
734                     /* Get the pixel/sample mask into f0 so that we know
735                      * which pixels are lit.  Then, for each channel that is
736                      * unlit, replace the centroid data with non-centroid
737                      * data.
738                      */
739                     emit(FS_OPCODE_MOV_DISPATCH_TO_FLAGS, attr);
740                     fs_inst *inst = emit_linterp(attr, fs_reg(interp),
741                                                  interpolation_mode, false);
742                     inst->predicated = true;
743                     inst->predicate_inverse = true;
744                  }
745		  if (intel->gen < 6) {
746		     emit(BRW_OPCODE_MUL, attr, attr, this->pixel_w);
747		  }
748	       }
749	       attr.reg_offset++;
750	    }
751
752	 }
753	 location++;
754      }
755   }
756
757   return reg;
758}
759
760fs_reg *
761fs_visitor::emit_frontfacing_interpolation(ir_variable *ir)
762{
763   fs_reg *reg = new(this->mem_ctx) fs_reg(this, ir->type);
764
765   /* The frontfacing comes in as a bit in the thread payload. */
766   if (intel->gen >= 6) {
767      emit(BRW_OPCODE_ASR, *reg,
768	   fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_D)),
769	   fs_reg(15));
770      emit(BRW_OPCODE_NOT, *reg, *reg);
771      emit(BRW_OPCODE_AND, *reg, *reg, fs_reg(1));
772   } else {
773      struct brw_reg r1_6ud = retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_UD);
774      /* bit 31 is "primitive is back face", so checking < (1 << 31) gives
775       * us front face
776       */
777      fs_inst *inst = emit(BRW_OPCODE_CMP, *reg,
778			   fs_reg(r1_6ud),
779			   fs_reg(1u << 31));
780      inst->conditional_mod = BRW_CONDITIONAL_L;
781      emit(BRW_OPCODE_AND, *reg, *reg, fs_reg(1u));
782   }
783
784   return reg;
785}
786
787fs_inst *
788fs_visitor::emit_math(enum opcode opcode, fs_reg dst, fs_reg src)
789{
790   switch (opcode) {
791   case SHADER_OPCODE_RCP:
792   case SHADER_OPCODE_RSQ:
793   case SHADER_OPCODE_SQRT:
794   case SHADER_OPCODE_EXP2:
795   case SHADER_OPCODE_LOG2:
796   case SHADER_OPCODE_SIN:
797   case SHADER_OPCODE_COS:
798      break;
799   default:
800      assert(!"not reached: bad math opcode");
801      return NULL;
802   }
803
804   /* Can't do hstride == 0 args to gen6 math, so expand it out.  We
805    * might be able to do better by doing execsize = 1 math and then
806    * expanding that result out, but we would need to be careful with
807    * masking.
808    *
809    * Gen 6 hardware ignores source modifiers (negate and abs) on math
810    * instructions, so we also move to a temp to set those up.
811    */
812   if (intel->gen == 6 && (src.file == UNIFORM ||
813			   src.abs ||
814			   src.negate)) {
815      fs_reg expanded = fs_reg(this, glsl_type::float_type);
816      emit(BRW_OPCODE_MOV, expanded, src);
817      src = expanded;
818   }
819
820   fs_inst *inst = emit(opcode, dst, src);
821
822   if (intel->gen < 6) {
823      inst->base_mrf = 2;
824      inst->mlen = c->dispatch_width / 8;
825   }
826
827   return inst;
828}
829
830fs_inst *
831fs_visitor::emit_math(enum opcode opcode, fs_reg dst, fs_reg src0, fs_reg src1)
832{
833   int base_mrf = 2;
834   fs_inst *inst;
835
836   switch (opcode) {
837   case SHADER_OPCODE_POW:
838   case SHADER_OPCODE_INT_QUOTIENT:
839   case SHADER_OPCODE_INT_REMAINDER:
840      break;
841   default:
842      assert(!"not reached: unsupported binary math opcode.");
843      return NULL;
844   }
845
846   if (intel->gen >= 7) {
847      inst = emit(opcode, dst, src0, src1);
848   } else if (intel->gen == 6) {
849      /* Can't do hstride == 0 args to gen6 math, so expand it out.
850       *
851       * The hardware ignores source modifiers (negate and abs) on math
852       * instructions, so we also move to a temp to set those up.
853       */
854      if (src0.file == UNIFORM || src0.abs || src0.negate) {
855	 fs_reg expanded = fs_reg(this, glsl_type::float_type);
856	 expanded.type = src0.type;
857	 emit(BRW_OPCODE_MOV, expanded, src0);
858	 src0 = expanded;
859      }
860
861      if (src1.file == UNIFORM || src1.abs || src1.negate) {
862	 fs_reg expanded = fs_reg(this, glsl_type::float_type);
863	 expanded.type = src1.type;
864	 emit(BRW_OPCODE_MOV, expanded, src1);
865	 src1 = expanded;
866      }
867
868      inst = emit(opcode, dst, src0, src1);
869   } else {
870      /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
871       * "Message Payload":
872       *
873       * "Operand0[7].  For the INT DIV functions, this operand is the
874       *  denominator."
875       *  ...
876       * "Operand1[7].  For the INT DIV functions, this operand is the
877       *  numerator."
878       */
879      bool is_int_div = opcode != SHADER_OPCODE_POW;
880      fs_reg &op0 = is_int_div ? src1 : src0;
881      fs_reg &op1 = is_int_div ? src0 : src1;
882
883      emit(BRW_OPCODE_MOV, fs_reg(MRF, base_mrf + 1, op1.type), op1);
884      inst = emit(opcode, dst, op0, reg_null_f);
885
886      inst->base_mrf = base_mrf;
887      inst->mlen = 2 * c->dispatch_width / 8;
888   }
889   return inst;
890}
891
892/**
893 * To be called after the last _mesa_add_state_reference() call, to
894 * set up prog_data.param[] for assign_curb_setup() and
895 * setup_pull_constants().
896 */
897void
898fs_visitor::setup_paramvalues_refs()
899{
900   if (c->dispatch_width != 8)
901      return;
902
903   /* Set up the pointers to ParamValues now that that array is finalized. */
904   for (unsigned int i = 0; i < c->prog_data.nr_params; i++) {
905      c->prog_data.param[i] =
906	 (const float *)fp->Base.Parameters->ParameterValues[this->param_index[i]] +
907	 this->param_offset[i];
908   }
909}
910
911void
912fs_visitor::assign_curb_setup()
913{
914   c->prog_data.curb_read_length = ALIGN(c->prog_data.nr_params, 8) / 8;
915   if (c->dispatch_width == 8) {
916      c->prog_data.first_curbe_grf = c->nr_payload_regs;
917   } else {
918      c->prog_data.first_curbe_grf_16 = c->nr_payload_regs;
919   }
920
921   /* Map the offsets in the UNIFORM file to fixed HW regs. */
922   foreach_list(node, &this->instructions) {
923      fs_inst *inst = (fs_inst *)node;
924
925      for (unsigned int i = 0; i < 3; i++) {
926	 if (inst->src[i].file == UNIFORM) {
927	    int constant_nr = inst->src[i].reg + inst->src[i].reg_offset;
928	    struct brw_reg brw_reg = brw_vec1_grf(c->nr_payload_regs +
929						  constant_nr / 8,
930						  constant_nr % 8);
931
932	    inst->src[i].file = FIXED_HW_REG;
933	    inst->src[i].fixed_hw_reg = retype(brw_reg, inst->src[i].type);
934	 }
935      }
936   }
937}
938
939void
940fs_visitor::calculate_urb_setup()
941{
942   for (unsigned int i = 0; i < FRAG_ATTRIB_MAX; i++) {
943      urb_setup[i] = -1;
944   }
945
946   int urb_next = 0;
947   /* Figure out where each of the incoming setup attributes lands. */
948   if (intel->gen >= 6) {
949      for (unsigned int i = 0; i < FRAG_ATTRIB_MAX; i++) {
950	 if (fp->Base.InputsRead & BITFIELD64_BIT(i)) {
951	    urb_setup[i] = urb_next++;
952	 }
953      }
954   } else {
955      /* FINISHME: The sf doesn't map VS->FS inputs for us very well. */
956      for (unsigned int i = 0; i < VERT_RESULT_MAX; i++) {
957	 if (c->key.vp_outputs_written & BITFIELD64_BIT(i)) {
958	    int fp_index = _mesa_vert_result_to_frag_attrib((gl_vert_result) i);
959
960	    if (fp_index >= 0)
961	       urb_setup[fp_index] = urb_next++;
962	 }
963      }
964
965      /*
966       * It's a FS only attribute, and we did interpolation for this attribute
967       * in SF thread. So, count it here, too.
968       *
969       * See compile_sf_prog() for more info.
970       */
971      if (brw->fragment_program->Base.InputsRead & BITFIELD64_BIT(FRAG_ATTRIB_PNTC))
972         urb_setup[FRAG_ATTRIB_PNTC] = urb_next++;
973   }
974
975   /* Each attribute is 4 setup channels, each of which is half a reg. */
976   c->prog_data.urb_read_length = urb_next * 2;
977}
978
979void
980fs_visitor::assign_urb_setup()
981{
982   int urb_start = c->nr_payload_regs + c->prog_data.curb_read_length;
983
984   /* Offset all the urb_setup[] index by the actual position of the
985    * setup regs, now that the location of the constants has been chosen.
986    */
987   foreach_list(node, &this->instructions) {
988      fs_inst *inst = (fs_inst *)node;
989
990      if (inst->opcode == FS_OPCODE_LINTERP) {
991	 assert(inst->src[2].file == FIXED_HW_REG);
992	 inst->src[2].fixed_hw_reg.nr += urb_start;
993      }
994
995      if (inst->opcode == FS_OPCODE_CINTERP) {
996	 assert(inst->src[0].file == FIXED_HW_REG);
997	 inst->src[0].fixed_hw_reg.nr += urb_start;
998      }
999   }
1000
1001   this->first_non_payload_grf = urb_start + c->prog_data.urb_read_length;
1002}
1003
1004/**
1005 * Split large virtual GRFs into separate components if we can.
1006 *
1007 * This is mostly duplicated with what brw_fs_vector_splitting does,
1008 * but that's really conservative because it's afraid of doing
1009 * splitting that doesn't result in real progress after the rest of
1010 * the optimization phases, which would cause infinite looping in
1011 * optimization.  We can do it once here, safely.  This also has the
1012 * opportunity to split interpolated values, or maybe even uniforms,
1013 * which we don't have at the IR level.
1014 *
1015 * We want to split, because virtual GRFs are what we register
1016 * allocate and spill (due to contiguousness requirements for some
1017 * instructions), and they're what we naturally generate in the
1018 * codegen process, but most virtual GRFs don't actually need to be
1019 * contiguous sets of GRFs.  If we split, we'll end up with reduced
1020 * live intervals and better dead code elimination and coalescing.
1021 */
1022void
1023fs_visitor::split_virtual_grfs()
1024{
1025   int num_vars = this->virtual_grf_count;
1026   bool split_grf[num_vars];
1027   int new_virtual_grf[num_vars];
1028
1029   /* Try to split anything > 0 sized. */
1030   for (int i = 0; i < num_vars; i++) {
1031      if (this->virtual_grf_sizes[i] != 1)
1032	 split_grf[i] = true;
1033      else
1034	 split_grf[i] = false;
1035   }
1036
1037   if (brw->has_pln &&
1038       this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC].file == GRF) {
1039      /* PLN opcodes rely on the delta_xy being contiguous.  We only have to
1040       * check this for BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC, because prior to
1041       * Gen6, that was the only supported interpolation mode, and since Gen6,
1042       * delta_x and delta_y are in fixed hardware registers.
1043       */
1044      split_grf[this->delta_x[BRW_WM_PERSPECTIVE_PIXEL_BARYCENTRIC].reg] =
1045         false;
1046   }
1047
1048   foreach_list(node, &this->instructions) {
1049      fs_inst *inst = (fs_inst *)node;
1050
1051      /* If there's a SEND message that requires contiguous destination
1052       * registers, no splitting is allowed.
1053       */
1054      if (inst->regs_written() > 1) {
1055	 split_grf[inst->dst.reg] = false;
1056      }
1057   }
1058
1059   /* Allocate new space for split regs.  Note that the virtual
1060    * numbers will be contiguous.
1061    */
1062   for (int i = 0; i < num_vars; i++) {
1063      if (split_grf[i]) {
1064	 new_virtual_grf[i] = virtual_grf_alloc(1);
1065	 for (int j = 2; j < this->virtual_grf_sizes[i]; j++) {
1066	    int reg = virtual_grf_alloc(1);
1067	    assert(reg == new_virtual_grf[i] + j - 1);
1068	    (void) reg;
1069	 }
1070	 this->virtual_grf_sizes[i] = 1;
1071      }
1072   }
1073
1074   foreach_list(node, &this->instructions) {
1075      fs_inst *inst = (fs_inst *)node;
1076
1077      if (inst->dst.file == GRF &&
1078	  split_grf[inst->dst.reg] &&
1079	  inst->dst.reg_offset != 0) {
1080	 inst->dst.reg = (new_virtual_grf[inst->dst.reg] +
1081			  inst->dst.reg_offset - 1);
1082	 inst->dst.reg_offset = 0;
1083      }
1084      for (int i = 0; i < 3; i++) {
1085	 if (inst->src[i].file == GRF &&
1086	     split_grf[inst->src[i].reg] &&
1087	     inst->src[i].reg_offset != 0) {
1088	    inst->src[i].reg = (new_virtual_grf[inst->src[i].reg] +
1089				inst->src[i].reg_offset - 1);
1090	    inst->src[i].reg_offset = 0;
1091	 }
1092      }
1093   }
1094   this->live_intervals_valid = false;
1095}
1096
1097bool
1098fs_visitor::remove_dead_constants()
1099{
1100   if (c->dispatch_width == 8) {
1101      this->params_remap = ralloc_array(mem_ctx, int, c->prog_data.nr_params);
1102
1103      for (unsigned int i = 0; i < c->prog_data.nr_params; i++)
1104	 this->params_remap[i] = -1;
1105
1106      /* Find which params are still in use. */
1107      foreach_list(node, &this->instructions) {
1108	 fs_inst *inst = (fs_inst *)node;
1109
1110	 for (int i = 0; i < 3; i++) {
1111	    int constant_nr = inst->src[i].reg + inst->src[i].reg_offset;
1112
1113	    if (inst->src[i].file != UNIFORM)
1114	       continue;
1115
1116	    assert(constant_nr < (int)c->prog_data.nr_params);
1117
1118	    /* For now, set this to non-negative.  We'll give it the
1119	     * actual new number in a moment, in order to keep the
1120	     * register numbers nicely ordered.
1121	     */
1122	    this->params_remap[constant_nr] = 0;
1123	 }
1124      }
1125
1126      /* Figure out what the new numbers for the params will be.  At some
1127       * point when we're doing uniform array access, we're going to want
1128       * to keep the distinction between .reg and .reg_offset, but for
1129       * now we don't care.
1130       */
1131      unsigned int new_nr_params = 0;
1132      for (unsigned int i = 0; i < c->prog_data.nr_params; i++) {
1133	 if (this->params_remap[i] != -1) {
1134	    this->params_remap[i] = new_nr_params++;
1135	 }
1136      }
1137
1138      /* Update the list of params to be uploaded to match our new numbering. */
1139      for (unsigned int i = 0; i < c->prog_data.nr_params; i++) {
1140	 int remapped = this->params_remap[i];
1141
1142	 if (remapped == -1)
1143	    continue;
1144
1145	 /* We've already done setup_paramvalues_refs() so no need to worry
1146	  * about param_index and param_offset.
1147	  */
1148	 c->prog_data.param[remapped] = c->prog_data.param[i];
1149      }
1150
1151      c->prog_data.nr_params = new_nr_params;
1152   } else {
1153      /* This should have been generated in the 8-wide pass already. */
1154      assert(this->params_remap);
1155   }
1156
1157   /* Now do the renumbering of the shader to remove unused params. */
1158   foreach_list(node, &this->instructions) {
1159      fs_inst *inst = (fs_inst *)node;
1160
1161      for (int i = 0; i < 3; i++) {
1162	 int constant_nr = inst->src[i].reg + inst->src[i].reg_offset;
1163
1164	 if (inst->src[i].file != UNIFORM)
1165	    continue;
1166
1167	 assert(this->params_remap[constant_nr] != -1);
1168	 inst->src[i].reg = this->params_remap[constant_nr];
1169	 inst->src[i].reg_offset = 0;
1170      }
1171   }
1172
1173   return true;
1174}
1175
1176/**
1177 * Choose accesses from the UNIFORM file to demote to using the pull
1178 * constant buffer.
1179 *
1180 * We allow a fragment shader to have more than the specified minimum
1181 * maximum number of fragment shader uniform components (64).  If
1182 * there are too many of these, they'd fill up all of register space.
1183 * So, this will push some of them out to the pull constant buffer and
1184 * update the program to load them.
1185 */
1186void
1187fs_visitor::setup_pull_constants()
1188{
1189   /* Only allow 16 registers (128 uniform components) as push constants. */
1190   unsigned int max_uniform_components = 16 * 8;
1191   if (c->prog_data.nr_params <= max_uniform_components)
1192      return;
1193
1194   if (c->dispatch_width == 16) {
1195      fail("Pull constants not supported in 16-wide\n");
1196      return;
1197   }
1198
1199   /* Just demote the end of the list.  We could probably do better
1200    * here, demoting things that are rarely used in the program first.
1201    */
1202   int pull_uniform_base = max_uniform_components;
1203   int pull_uniform_count = c->prog_data.nr_params - pull_uniform_base;
1204
1205   foreach_list(node, &this->instructions) {
1206      fs_inst *inst = (fs_inst *)node;
1207
1208      for (int i = 0; i < 3; i++) {
1209	 if (inst->src[i].file != UNIFORM)
1210	    continue;
1211
1212	 int uniform_nr = inst->src[i].reg + inst->src[i].reg_offset;
1213	 if (uniform_nr < pull_uniform_base)
1214	    continue;
1215
1216	 fs_reg dst = fs_reg(this, glsl_type::float_type);
1217	 fs_reg index = fs_reg((unsigned)SURF_INDEX_FRAG_CONST_BUFFER);
1218	 fs_reg offset = fs_reg((unsigned)(((uniform_nr -
1219					     pull_uniform_base) * 4) & ~15));
1220	 fs_inst *pull = new(mem_ctx) fs_inst(FS_OPCODE_PULL_CONSTANT_LOAD,
1221					      dst, index, offset);
1222	 pull->ir = inst->ir;
1223	 pull->annotation = inst->annotation;
1224	 pull->base_mrf = 14;
1225	 pull->mlen = 1;
1226
1227	 inst->insert_before(pull);
1228
1229	 inst->src[i].file = GRF;
1230	 inst->src[i].reg = dst.reg;
1231	 inst->src[i].reg_offset = 0;
1232	 inst->src[i].smear = (uniform_nr - pull_uniform_base) & 3;
1233      }
1234   }
1235
1236   for (int i = 0; i < pull_uniform_count; i++) {
1237      c->prog_data.pull_param[i] = c->prog_data.param[pull_uniform_base + i];
1238   }
1239   c->prog_data.nr_params -= pull_uniform_count;
1240   c->prog_data.nr_pull_params = pull_uniform_count;
1241}
1242
1243/**
1244 * Attempts to move immediate constants into the immediate
1245 * constant slot of following instructions.
1246 *
1247 * Immediate constants are a bit tricky -- they have to be in the last
1248 * operand slot, you can't do abs/negate on them,
1249 */
1250
1251bool
1252fs_visitor::propagate_constants()
1253{
1254   bool progress = false;
1255
1256   calculate_live_intervals();
1257
1258   foreach_list(node, &this->instructions) {
1259      fs_inst *inst = (fs_inst *)node;
1260
1261      if (inst->opcode != BRW_OPCODE_MOV ||
1262	  inst->predicated ||
1263	  inst->dst.file != GRF || inst->src[0].file != IMM ||
1264	  inst->dst.type != inst->src[0].type ||
1265	  (c->dispatch_width == 16 &&
1266	   (inst->force_uncompressed || inst->force_sechalf)))
1267	 continue;
1268
1269      /* Don't bother with cases where we should have had the
1270       * operation on the constant folded in GLSL already.
1271       */
1272      if (inst->saturate)
1273	 continue;
1274
1275      /* Found a move of a constant to a GRF.  Find anything else using the GRF
1276       * before it's written, and replace it with the constant if we can.
1277       */
1278      for (fs_inst *scan_inst = (fs_inst *)inst->next;
1279	   !scan_inst->is_tail_sentinel();
1280	   scan_inst = (fs_inst *)scan_inst->next) {
1281	 if (scan_inst->opcode == BRW_OPCODE_DO ||
1282	     scan_inst->opcode == BRW_OPCODE_WHILE ||
1283	     scan_inst->opcode == BRW_OPCODE_ELSE ||
1284	     scan_inst->opcode == BRW_OPCODE_ENDIF) {
1285	    break;
1286	 }
1287
1288	 for (int i = 2; i >= 0; i--) {
1289	    if (scan_inst->src[i].file != GRF ||
1290		scan_inst->src[i].reg != inst->dst.reg ||
1291		scan_inst->src[i].reg_offset != inst->dst.reg_offset)
1292	       continue;
1293
1294	    /* Don't bother with cases where we should have had the
1295	     * operation on the constant folded in GLSL already.
1296	     */
1297	    if (scan_inst->src[i].negate || scan_inst->src[i].abs)
1298	       continue;
1299
1300	    switch (scan_inst->opcode) {
1301	    case BRW_OPCODE_MOV:
1302	       scan_inst->src[i] = inst->src[0];
1303	       progress = true;
1304	       break;
1305
1306	    case BRW_OPCODE_MUL:
1307	    case BRW_OPCODE_ADD:
1308	       if (i == 1) {
1309		  scan_inst->src[i] = inst->src[0];
1310		  progress = true;
1311	       } else if (i == 0 && scan_inst->src[1].file != IMM) {
1312		  /* Fit this constant in by commuting the operands.
1313		   * Exception: we can't do this for 32-bit integer MUL
1314		   * because it's asymmetric.
1315		   */
1316		  if (scan_inst->opcode == BRW_OPCODE_MUL &&
1317		      (scan_inst->src[1].type == BRW_REGISTER_TYPE_D ||
1318		       scan_inst->src[1].type == BRW_REGISTER_TYPE_UD))
1319		     break;
1320		  scan_inst->src[0] = scan_inst->src[1];
1321		  scan_inst->src[1] = inst->src[0];
1322		  progress = true;
1323	       }
1324	       break;
1325
1326	    case BRW_OPCODE_CMP:
1327	    case BRW_OPCODE_IF:
1328	       if (i == 1) {
1329		  scan_inst->src[i] = inst->src[0];
1330		  progress = true;
1331	       } else if (i == 0 && scan_inst->src[1].file != IMM) {
1332		  uint32_t new_cmod;
1333
1334		  new_cmod = brw_swap_cmod(scan_inst->conditional_mod);
1335		  if (new_cmod != ~0u) {
1336		     /* Fit this constant in by swapping the operands and
1337		      * flipping the test
1338		      */
1339		     scan_inst->src[0] = scan_inst->src[1];
1340		     scan_inst->src[1] = inst->src[0];
1341		     scan_inst->conditional_mod = new_cmod;
1342		     progress = true;
1343		  }
1344	       }
1345	       break;
1346
1347	    case BRW_OPCODE_SEL:
1348	       if (i == 1) {
1349		  scan_inst->src[i] = inst->src[0];
1350		  progress = true;
1351	       } else if (i == 0 && scan_inst->src[1].file != IMM) {
1352		  scan_inst->src[0] = scan_inst->src[1];
1353		  scan_inst->src[1] = inst->src[0];
1354
1355		  /* If this was predicated, flipping operands means
1356		   * we also need to flip the predicate.
1357		   */
1358		  if (scan_inst->conditional_mod == BRW_CONDITIONAL_NONE) {
1359		     scan_inst->predicate_inverse =
1360			!scan_inst->predicate_inverse;
1361		  }
1362		  progress = true;
1363	       }
1364	       break;
1365
1366	    case SHADER_OPCODE_RCP:
1367	       /* The hardware doesn't do math on immediate values
1368		* (because why are you doing that, seriously?), but
1369		* the correct answer is to just constant fold it
1370		* anyway.
1371		*/
1372	       assert(i == 0);
1373	       if (inst->src[0].imm.f != 0.0f) {
1374		  scan_inst->opcode = BRW_OPCODE_MOV;
1375		  scan_inst->src[0] = inst->src[0];
1376		  scan_inst->src[0].imm.f = 1.0f / scan_inst->src[0].imm.f;
1377		  progress = true;
1378	       }
1379	       break;
1380
1381	    default:
1382	       break;
1383	    }
1384	 }
1385
1386	 if (scan_inst->dst.file == GRF &&
1387             scan_inst->overwrites_reg(inst->dst)) {
1388	    break;
1389	 }
1390      }
1391   }
1392
1393   if (progress)
1394       this->live_intervals_valid = false;
1395
1396   return progress;
1397}
1398
1399
1400/**
1401 * Attempts to move immediate constants into the immediate
1402 * constant slot of following instructions.
1403 *
1404 * Immediate constants are a bit tricky -- they have to be in the last
1405 * operand slot, you can't do abs/negate on them,
1406 */
1407
1408bool
1409fs_visitor::opt_algebraic()
1410{
1411   bool progress = false;
1412
1413   calculate_live_intervals();
1414
1415   foreach_list(node, &this->instructions) {
1416      fs_inst *inst = (fs_inst *)node;
1417
1418      switch (inst->opcode) {
1419      case BRW_OPCODE_MUL:
1420	 if (inst->src[1].file != IMM)
1421	    continue;
1422
1423	 /* a * 1.0 = a */
1424	 if (inst->src[1].type == BRW_REGISTER_TYPE_F &&
1425	     inst->src[1].imm.f == 1.0) {
1426	    inst->opcode = BRW_OPCODE_MOV;
1427	    inst->src[1] = reg_undef;
1428	    progress = true;
1429	    break;
1430	 }
1431
1432	 break;
1433      default:
1434	 break;
1435      }
1436   }
1437
1438   return progress;
1439}
1440
1441/**
1442 * Must be called after calculate_live_intervales() to remove unused
1443 * writes to registers -- register allocation will fail otherwise
1444 * because something deffed but not used won't be considered to
1445 * interfere with other regs.
1446 */
1447bool
1448fs_visitor::dead_code_eliminate()
1449{
1450   bool progress = false;
1451   int pc = 0;
1452
1453   calculate_live_intervals();
1454
1455   foreach_list_safe(node, &this->instructions) {
1456      fs_inst *inst = (fs_inst *)node;
1457
1458      if (inst->dst.file == GRF && this->virtual_grf_use[inst->dst.reg] <= pc) {
1459	 inst->remove();
1460	 progress = true;
1461      }
1462
1463      pc++;
1464   }
1465
1466   if (progress)
1467      live_intervals_valid = false;
1468
1469   return progress;
1470}
1471
1472/**
1473 * Implements a second type of register coalescing: This one checks if
1474 * the two regs involved in a raw move don't interfere, in which case
1475 * they can both by stored in the same place and the MOV removed.
1476 */
1477bool
1478fs_visitor::register_coalesce_2()
1479{
1480   bool progress = false;
1481
1482   calculate_live_intervals();
1483
1484   foreach_list_safe(node, &this->instructions) {
1485      fs_inst *inst = (fs_inst *)node;
1486
1487      if (inst->opcode != BRW_OPCODE_MOV ||
1488	  inst->predicated ||
1489	  inst->saturate ||
1490	  inst->src[0].file != GRF ||
1491	  inst->src[0].negate ||
1492	  inst->src[0].abs ||
1493	  inst->src[0].smear != -1 ||
1494	  inst->dst.file != GRF ||
1495	  inst->dst.type != inst->src[0].type ||
1496	  virtual_grf_sizes[inst->src[0].reg] != 1 ||
1497	  virtual_grf_interferes(inst->dst.reg, inst->src[0].reg)) {
1498	 continue;
1499      }
1500
1501      int reg_from = inst->src[0].reg;
1502      assert(inst->src[0].reg_offset == 0);
1503      int reg_to = inst->dst.reg;
1504      int reg_to_offset = inst->dst.reg_offset;
1505
1506      foreach_list_safe(node, &this->instructions) {
1507	 fs_inst *scan_inst = (fs_inst *)node;
1508
1509	 if (scan_inst->dst.file == GRF &&
1510	     scan_inst->dst.reg == reg_from) {
1511	    scan_inst->dst.reg = reg_to;
1512	    scan_inst->dst.reg_offset = reg_to_offset;
1513	 }
1514	 for (int i = 0; i < 3; i++) {
1515	    if (scan_inst->src[i].file == GRF &&
1516		scan_inst->src[i].reg == reg_from) {
1517	       scan_inst->src[i].reg = reg_to;
1518	       scan_inst->src[i].reg_offset = reg_to_offset;
1519	    }
1520	 }
1521      }
1522
1523      inst->remove();
1524      live_intervals_valid = false;
1525      progress = true;
1526      continue;
1527   }
1528
1529   return progress;
1530}
1531
1532bool
1533fs_visitor::register_coalesce()
1534{
1535   bool progress = false;
1536   int if_depth = 0;
1537   int loop_depth = 0;
1538
1539   foreach_list_safe(node, &this->instructions) {
1540      fs_inst *inst = (fs_inst *)node;
1541
1542      /* Make sure that we dominate the instructions we're going to
1543       * scan for interfering with our coalescing, or we won't have
1544       * scanned enough to see if anything interferes with our
1545       * coalescing.  We don't dominate the following instructions if
1546       * we're in a loop or an if block.
1547       */
1548      switch (inst->opcode) {
1549      case BRW_OPCODE_DO:
1550	 loop_depth++;
1551	 break;
1552      case BRW_OPCODE_WHILE:
1553	 loop_depth--;
1554	 break;
1555      case BRW_OPCODE_IF:
1556	 if_depth++;
1557	 break;
1558      case BRW_OPCODE_ENDIF:
1559	 if_depth--;
1560	 break;
1561      default:
1562	 break;
1563      }
1564      if (loop_depth || if_depth)
1565	 continue;
1566
1567      if (inst->opcode != BRW_OPCODE_MOV ||
1568	  inst->predicated ||
1569	  inst->saturate ||
1570	  inst->dst.file != GRF || (inst->src[0].file != GRF &&
1571				    inst->src[0].file != UNIFORM)||
1572	  inst->dst.type != inst->src[0].type)
1573	 continue;
1574
1575      bool has_source_modifiers = inst->src[0].abs || inst->src[0].negate;
1576
1577      /* Found a move of a GRF to a GRF.  Let's see if we can coalesce
1578       * them: check for no writes to either one until the exit of the
1579       * program.
1580       */
1581      bool interfered = false;
1582
1583      for (fs_inst *scan_inst = (fs_inst *)inst->next;
1584	   !scan_inst->is_tail_sentinel();
1585	   scan_inst = (fs_inst *)scan_inst->next) {
1586	 if (scan_inst->dst.file == GRF) {
1587	    if (scan_inst->overwrites_reg(inst->dst) ||
1588                scan_inst->overwrites_reg(inst->src[0])) {
1589	       interfered = true;
1590	       break;
1591	    }
1592	 }
1593
1594	 /* The gen6 MATH instruction can't handle source modifiers or
1595	  * unusual register regions, so avoid coalescing those for
1596	  * now.  We should do something more specific.
1597	  */
1598	 if (intel->gen >= 6 &&
1599	     scan_inst->is_math() &&
1600	     (has_source_modifiers || inst->src[0].file == UNIFORM)) {
1601	    interfered = true;
1602	    break;
1603	 }
1604
1605	 /* The accumulator result appears to get used for the
1606	  * conditional modifier generation.  When negating a UD
1607	  * value, there is a 33rd bit generated for the sign in the
1608	  * accumulator value, so now you can't check, for example,
1609	  * equality with a 32-bit value.  See piglit fs-op-neg-uint.
1610	  */
1611	 if (scan_inst->conditional_mod &&
1612	     inst->src[0].negate &&
1613	     inst->src[0].type == BRW_REGISTER_TYPE_UD) {
1614	    interfered = true;
1615	    break;
1616	 }
1617      }
1618      if (interfered) {
1619	 continue;
1620      }
1621
1622      /* Rewrite the later usage to point at the source of the move to
1623       * be removed.
1624       */
1625      for (fs_inst *scan_inst = inst;
1626	   !scan_inst->is_tail_sentinel();
1627	   scan_inst = (fs_inst *)scan_inst->next) {
1628	 for (int i = 0; i < 3; i++) {
1629	    if (scan_inst->src[i].file == GRF &&
1630		scan_inst->src[i].reg == inst->dst.reg &&
1631		scan_inst->src[i].reg_offset == inst->dst.reg_offset) {
1632	       fs_reg new_src = inst->src[0];
1633               if (scan_inst->src[i].abs) {
1634                  new_src.negate = 0;
1635                  new_src.abs = 1;
1636               }
1637	       new_src.negate ^= scan_inst->src[i].negate;
1638	       scan_inst->src[i] = new_src;
1639	    }
1640	 }
1641      }
1642
1643      inst->remove();
1644      progress = true;
1645   }
1646
1647   if (progress)
1648      live_intervals_valid = false;
1649
1650   return progress;
1651}
1652
1653
1654bool
1655fs_visitor::compute_to_mrf()
1656{
1657   bool progress = false;
1658   int next_ip = 0;
1659
1660   calculate_live_intervals();
1661
1662   foreach_list_safe(node, &this->instructions) {
1663      fs_inst *inst = (fs_inst *)node;
1664
1665      int ip = next_ip;
1666      next_ip++;
1667
1668      if (inst->opcode != BRW_OPCODE_MOV ||
1669	  inst->predicated ||
1670	  inst->dst.file != MRF || inst->src[0].file != GRF ||
1671	  inst->dst.type != inst->src[0].type ||
1672	  inst->src[0].abs || inst->src[0].negate || inst->src[0].smear != -1)
1673	 continue;
1674
1675      /* Work out which hardware MRF registers are written by this
1676       * instruction.
1677       */
1678      int mrf_low = inst->dst.reg & ~BRW_MRF_COMPR4;
1679      int mrf_high;
1680      if (inst->dst.reg & BRW_MRF_COMPR4) {
1681	 mrf_high = mrf_low + 4;
1682      } else if (c->dispatch_width == 16 &&
1683		 (!inst->force_uncompressed && !inst->force_sechalf)) {
1684	 mrf_high = mrf_low + 1;
1685      } else {
1686	 mrf_high = mrf_low;
1687      }
1688
1689      /* Can't compute-to-MRF this GRF if someone else was going to
1690       * read it later.
1691       */
1692      if (this->virtual_grf_use[inst->src[0].reg] > ip)
1693	 continue;
1694
1695      /* Found a move of a GRF to a MRF.  Let's see if we can go
1696       * rewrite the thing that made this GRF to write into the MRF.
1697       */
1698      fs_inst *scan_inst;
1699      for (scan_inst = (fs_inst *)inst->prev;
1700	   scan_inst->prev != NULL;
1701	   scan_inst = (fs_inst *)scan_inst->prev) {
1702	 if (scan_inst->dst.file == GRF &&
1703	     scan_inst->dst.reg == inst->src[0].reg) {
1704	    /* Found the last thing to write our reg we want to turn
1705	     * into a compute-to-MRF.
1706	     */
1707
1708            /* SENDs can only write to GRFs, so no compute-to-MRF. */
1709	    if (scan_inst->mlen) {
1710	       break;
1711	    }
1712
1713	    /* If it's predicated, it (probably) didn't populate all
1714	     * the channels.  We might be able to rewrite everything
1715	     * that writes that reg, but it would require smarter
1716	     * tracking to delay the rewriting until complete success.
1717	     */
1718	    if (scan_inst->predicated)
1719	       break;
1720
1721	    /* If it's half of register setup and not the same half as
1722	     * our MOV we're trying to remove, bail for now.
1723	     */
1724	    if (scan_inst->force_uncompressed != inst->force_uncompressed ||
1725		scan_inst->force_sechalf != inst->force_sechalf) {
1726	       break;
1727	    }
1728
1729	    /* SEND instructions can't have MRF as a destination. */
1730	    if (scan_inst->mlen)
1731	       break;
1732
1733	    if (intel->gen >= 6) {
1734	       /* gen6 math instructions must have the destination be
1735		* GRF, so no compute-to-MRF for them.
1736		*/
1737	       if (scan_inst->is_math()) {
1738		  break;
1739	       }
1740	    }
1741
1742	    if (scan_inst->dst.reg_offset == inst->src[0].reg_offset) {
1743	       /* Found the creator of our MRF's source value. */
1744	       scan_inst->dst.file = MRF;
1745	       scan_inst->dst.reg = inst->dst.reg;
1746	       scan_inst->saturate |= inst->saturate;
1747	       inst->remove();
1748	       progress = true;
1749	    }
1750	    break;
1751	 }
1752
1753	 /* We don't handle flow control here.  Most computation of
1754	  * values that end up in MRFs are shortly before the MRF
1755	  * write anyway.
1756	  */
1757	 if (scan_inst->opcode == BRW_OPCODE_DO ||
1758	     scan_inst->opcode == BRW_OPCODE_WHILE ||
1759	     scan_inst->opcode == BRW_OPCODE_ELSE ||
1760	     scan_inst->opcode == BRW_OPCODE_ENDIF) {
1761	    break;
1762	 }
1763
1764	 /* You can't read from an MRF, so if someone else reads our
1765	  * MRF's source GRF that we wanted to rewrite, that stops us.
1766	  */
1767	 bool interfered = false;
1768	 for (int i = 0; i < 3; i++) {
1769	    if (scan_inst->src[i].file == GRF &&
1770		scan_inst->src[i].reg == inst->src[0].reg &&
1771		scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
1772	       interfered = true;
1773	    }
1774	 }
1775	 if (interfered)
1776	    break;
1777
1778	 if (scan_inst->dst.file == MRF) {
1779	    /* If somebody else writes our MRF here, we can't
1780	     * compute-to-MRF before that.
1781	     */
1782	    int scan_mrf_low = scan_inst->dst.reg & ~BRW_MRF_COMPR4;
1783	    int scan_mrf_high;
1784
1785	    if (scan_inst->dst.reg & BRW_MRF_COMPR4) {
1786	       scan_mrf_high = scan_mrf_low + 4;
1787	    } else if (c->dispatch_width == 16 &&
1788		       (!scan_inst->force_uncompressed &&
1789			!scan_inst->force_sechalf)) {
1790	       scan_mrf_high = scan_mrf_low + 1;
1791	    } else {
1792	       scan_mrf_high = scan_mrf_low;
1793	    }
1794
1795	    if (mrf_low == scan_mrf_low ||
1796		mrf_low == scan_mrf_high ||
1797		mrf_high == scan_mrf_low ||
1798		mrf_high == scan_mrf_high) {
1799	       break;
1800	    }
1801	 }
1802
1803	 if (scan_inst->mlen > 0) {
1804	    /* Found a SEND instruction, which means that there are
1805	     * live values in MRFs from base_mrf to base_mrf +
1806	     * scan_inst->mlen - 1.  Don't go pushing our MRF write up
1807	     * above it.
1808	     */
1809	    if (mrf_low >= scan_inst->base_mrf &&
1810		mrf_low < scan_inst->base_mrf + scan_inst->mlen) {
1811	       break;
1812	    }
1813	    if (mrf_high >= scan_inst->base_mrf &&
1814		mrf_high < scan_inst->base_mrf + scan_inst->mlen) {
1815	       break;
1816	    }
1817	 }
1818      }
1819   }
1820
1821   if (progress)
1822      live_intervals_valid = false;
1823
1824   return progress;
1825}
1826
1827/**
1828 * Walks through basic blocks, looking for repeated MRF writes and
1829 * removing the later ones.
1830 */
1831bool
1832fs_visitor::remove_duplicate_mrf_writes()
1833{
1834   fs_inst *last_mrf_move[16];
1835   bool progress = false;
1836
1837   /* Need to update the MRF tracking for compressed instructions. */
1838   if (c->dispatch_width == 16)
1839      return false;
1840
1841   memset(last_mrf_move, 0, sizeof(last_mrf_move));
1842
1843   foreach_list_safe(node, &this->instructions) {
1844      fs_inst *inst = (fs_inst *)node;
1845
1846      switch (inst->opcode) {
1847      case BRW_OPCODE_DO:
1848      case BRW_OPCODE_WHILE:
1849      case BRW_OPCODE_IF:
1850      case BRW_OPCODE_ELSE:
1851      case BRW_OPCODE_ENDIF:
1852	 memset(last_mrf_move, 0, sizeof(last_mrf_move));
1853	 continue;
1854      default:
1855	 break;
1856      }
1857
1858      if (inst->opcode == BRW_OPCODE_MOV &&
1859	  inst->dst.file == MRF) {
1860	 fs_inst *prev_inst = last_mrf_move[inst->dst.reg];
1861	 if (prev_inst && inst->equals(prev_inst)) {
1862	    inst->remove();
1863	    progress = true;
1864	    continue;
1865	 }
1866      }
1867
1868      /* Clear out the last-write records for MRFs that were overwritten. */
1869      if (inst->dst.file == MRF) {
1870	 last_mrf_move[inst->dst.reg] = NULL;
1871      }
1872
1873      if (inst->mlen > 0) {
1874	 /* Found a SEND instruction, which will include two or fewer
1875	  * implied MRF writes.  We could do better here.
1876	  */
1877	 for (int i = 0; i < implied_mrf_writes(inst); i++) {
1878	    last_mrf_move[inst->base_mrf + i] = NULL;
1879	 }
1880      }
1881
1882      /* Clear out any MRF move records whose sources got overwritten. */
1883      if (inst->dst.file == GRF) {
1884	 for (unsigned int i = 0; i < Elements(last_mrf_move); i++) {
1885	    if (last_mrf_move[i] &&
1886		last_mrf_move[i]->src[0].reg == inst->dst.reg) {
1887	       last_mrf_move[i] = NULL;
1888	    }
1889	 }
1890      }
1891
1892      if (inst->opcode == BRW_OPCODE_MOV &&
1893	  inst->dst.file == MRF &&
1894	  inst->src[0].file == GRF &&
1895	  !inst->predicated) {
1896	 last_mrf_move[inst->dst.reg] = inst;
1897      }
1898   }
1899
1900   if (progress)
1901      live_intervals_valid = false;
1902
1903   return progress;
1904}
1905
1906/**
1907 * Possibly returns an instruction that set up @param reg.
1908 *
1909 * Sometimes we want to take the result of some expression/variable
1910 * dereference tree and rewrite the instruction generating the result
1911 * of the tree.  When processing the tree, we know that the
1912 * instructions generated are all writing temporaries that are dead
1913 * outside of this tree.  So, if we have some instructions that write
1914 * a temporary, we're free to point that temp write somewhere else.
1915 *
1916 * Note that this doesn't guarantee that the instruction generated
1917 * only reg -- it might be the size=4 destination of a texture instruction.
1918 */
1919fs_inst *
1920fs_visitor::get_instruction_generating_reg(fs_inst *start,
1921					   fs_inst *end,
1922					   fs_reg reg)
1923{
1924   if (end == start ||
1925       end->predicated ||
1926       end->force_uncompressed ||
1927       end->force_sechalf ||
1928       !reg.equals(end->dst)) {
1929      return NULL;
1930   } else {
1931      return end;
1932   }
1933}
1934
1935bool
1936fs_visitor::run()
1937{
1938   uint32_t prog_offset_16 = 0;
1939   uint32_t orig_nr_params = c->prog_data.nr_params;
1940
1941   brw_wm_payload_setup(brw, c);
1942
1943   if (c->dispatch_width == 16) {
1944      /* align to 64 byte boundary. */
1945      while ((c->func.nr_insn * sizeof(struct brw_instruction)) % 64) {
1946	 brw_NOP(p);
1947      }
1948
1949      /* Save off the start of this 16-wide program in case we succeed. */
1950      prog_offset_16 = c->func.nr_insn * sizeof(struct brw_instruction);
1951
1952      brw_set_compression_control(p, BRW_COMPRESSION_COMPRESSED);
1953   }
1954
1955   if (0) {
1956      emit_dummy_fs();
1957   } else {
1958      calculate_urb_setup();
1959      if (intel->gen < 6)
1960	 emit_interpolation_setup_gen4();
1961      else
1962	 emit_interpolation_setup_gen6();
1963
1964      /* Generate FS IR for main().  (the visitor only descends into
1965       * functions called "main").
1966       */
1967      foreach_list(node, &*shader->ir) {
1968	 ir_instruction *ir = (ir_instruction *)node;
1969	 base_ir = ir;
1970	 this->result = reg_undef;
1971	 ir->accept(this);
1972      }
1973      if (failed)
1974	 return false;
1975
1976      emit_fb_writes();
1977
1978      split_virtual_grfs();
1979
1980      setup_paramvalues_refs();
1981      setup_pull_constants();
1982
1983      bool progress;
1984      do {
1985	 progress = false;
1986
1987	 progress = remove_duplicate_mrf_writes() || progress;
1988
1989	 progress = propagate_constants() || progress;
1990	 progress = opt_algebraic() || progress;
1991	 progress = opt_cse() || progress;
1992	 progress = opt_copy_propagate() || progress;
1993	 progress = register_coalesce() || progress;
1994	 progress = register_coalesce_2() || progress;
1995	 progress = compute_to_mrf() || progress;
1996	 progress = dead_code_eliminate() || progress;
1997      } while (progress);
1998
1999      remove_dead_constants();
2000
2001      schedule_instructions();
2002
2003      assign_curb_setup();
2004      assign_urb_setup();
2005
2006      if (0) {
2007	 /* Debug of register spilling: Go spill everything. */
2008	 for (int i = 0; i < virtual_grf_count; i++) {
2009	    spill_reg(i);
2010	 }
2011      }
2012
2013      if (0)
2014	 assign_regs_trivial();
2015      else {
2016	 while (!assign_regs()) {
2017	    if (failed)
2018	       break;
2019	 }
2020      }
2021   }
2022   assert(force_uncompressed_stack == 0);
2023   assert(force_sechalf_stack == 0);
2024
2025   if (failed)
2026      return false;
2027
2028   generate_code();
2029
2030   if (c->dispatch_width == 8) {
2031      c->prog_data.reg_blocks = brw_register_blocks(grf_used);
2032   } else {
2033      c->prog_data.reg_blocks_16 = brw_register_blocks(grf_used);
2034      c->prog_data.prog_offset_16 = prog_offset_16;
2035
2036      /* Make sure we didn't try to sneak in an extra uniform */
2037      assert(orig_nr_params == c->prog_data.nr_params);
2038      (void) orig_nr_params;
2039   }
2040
2041   return !failed;
2042}
2043
2044bool
2045brw_wm_fs_emit(struct brw_context *brw, struct brw_wm_compile *c,
2046	       struct gl_shader_program *prog)
2047{
2048   struct intel_context *intel = &brw->intel;
2049
2050   if (!prog)
2051      return false;
2052
2053   struct brw_shader *shader =
2054     (brw_shader *) prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2055   if (!shader)
2056      return false;
2057
2058   if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
2059      printf("GLSL IR for native fragment shader %d:\n", prog->Name);
2060      _mesa_print_ir(shader->ir, NULL);
2061      printf("\n\n");
2062   }
2063
2064   /* Now the main event: Visit the shader IR and generate our FS IR for it.
2065    */
2066   c->dispatch_width = 8;
2067
2068   fs_visitor v(c, prog, shader);
2069   if (!v.run()) {
2070      prog->LinkStatus = false;
2071      ralloc_strcat(&prog->InfoLog, v.fail_msg);
2072
2073      _mesa_problem(NULL, "Failed to compile fragment shader: %s\n",
2074		    v.fail_msg);
2075
2076      return false;
2077   }
2078
2079   if (intel->gen >= 5 && c->prog_data.nr_pull_params == 0) {
2080      c->dispatch_width = 16;
2081      fs_visitor v2(c, prog, shader);
2082      v2.import_uniforms(&v);
2083      v2.run();
2084   }
2085
2086   c->prog_data.dispatch_width = 8;
2087
2088   return true;
2089}
2090
2091bool
2092brw_fs_precompile(struct gl_context *ctx, struct gl_shader_program *prog)
2093{
2094   struct brw_context *brw = brw_context(ctx);
2095   struct brw_wm_prog_key key;
2096
2097   if (!prog->_LinkedShaders[MESA_SHADER_FRAGMENT])
2098      return true;
2099
2100   struct gl_fragment_program *fp = (struct gl_fragment_program *)
2101      prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->Program;
2102   struct brw_fragment_program *bfp = brw_fragment_program(fp);
2103   bool program_uses_dfdy = fp->UsesDFdy;
2104
2105   memset(&key, 0, sizeof(key));
2106
2107   if (fp->UsesKill)
2108      key.iz_lookup |= IZ_PS_KILL_ALPHATEST_BIT;
2109
2110   if (fp->Base.OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_DEPTH))
2111      key.iz_lookup |= IZ_PS_COMPUTES_DEPTH_BIT;
2112
2113   /* Just assume depth testing. */
2114   key.iz_lookup |= IZ_DEPTH_TEST_ENABLE_BIT;
2115   key.iz_lookup |= IZ_DEPTH_WRITE_ENABLE_BIT;
2116
2117   key.vp_outputs_written |= BITFIELD64_BIT(FRAG_ATTRIB_WPOS);
2118   for (int i = 0; i < FRAG_ATTRIB_MAX; i++) {
2119      if (!(fp->Base.InputsRead & BITFIELD64_BIT(i)))
2120	 continue;
2121
2122      key.proj_attrib_mask |= 1 << i;
2123
2124      int vp_index = _mesa_vert_result_to_frag_attrib((gl_vert_result) i);
2125
2126      if (vp_index >= 0)
2127	 key.vp_outputs_written |= BITFIELD64_BIT(vp_index);
2128   }
2129
2130   key.clamp_fragment_color = true;
2131
2132   for (int i = 0; i < BRW_MAX_TEX_UNIT; i++) {
2133      /* FINISHME: depth compares might use (0,0,0,W) for example */
2134      key.tex.swizzles[i] = SWIZZLE_XYZW;
2135   }
2136
2137   if (fp->Base.InputsRead & FRAG_BIT_WPOS) {
2138      key.drawable_height = ctx->DrawBuffer->Height;
2139   }
2140
2141   if ((fp->Base.InputsRead & FRAG_BIT_WPOS) || program_uses_dfdy) {
2142      key.render_to_fbo = _mesa_is_user_fbo(ctx->DrawBuffer);
2143   }
2144
2145   key.nr_color_regions = 1;
2146
2147   key.program_string_id = bfp->id;
2148
2149   uint32_t old_prog_offset = brw->wm.prog_offset;
2150   struct brw_wm_prog_data *old_prog_data = brw->wm.prog_data;
2151
2152   bool success = do_wm_prog(brw, prog, bfp, &key);
2153
2154   brw->wm.prog_offset = old_prog_offset;
2155   brw->wm.prog_data = old_prog_data;
2156
2157   return success;
2158}
2159