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 * Authors:
24 *    Eric Anholt <eric@anholt.net>
25 *
26 */
27
28#include "brw_eu.h"
29#include "brw_fs.h"
30#include "brw_cfg.h"
31#include "util/set.h"
32#include "util/register_allocate.h"
33
34using namespace brw;
35
36static void
37assign_reg(unsigned *reg_hw_locations, fs_reg *reg)
38{
39   if (reg->file == VGRF) {
40      reg->nr = reg_hw_locations[reg->nr] + reg->offset / REG_SIZE;
41      reg->offset %= REG_SIZE;
42   }
43}
44
45void
46fs_visitor::assign_regs_trivial()
47{
48   unsigned hw_reg_mapping[this->alloc.count + 1];
49   unsigned i;
50   int reg_width = dispatch_width / 8;
51
52   /* Note that compressed instructions require alignment to 2 registers. */
53   hw_reg_mapping[0] = ALIGN(this->first_non_payload_grf, reg_width);
54   for (i = 1; i <= this->alloc.count; i++) {
55      hw_reg_mapping[i] = (hw_reg_mapping[i - 1] +
56			   this->alloc.sizes[i - 1]);
57   }
58   this->grf_used = hw_reg_mapping[this->alloc.count];
59
60   foreach_block_and_inst(block, fs_inst, inst, cfg) {
61      assign_reg(hw_reg_mapping, &inst->dst);
62      for (i = 0; i < inst->sources; i++) {
63         assign_reg(hw_reg_mapping, &inst->src[i]);
64      }
65   }
66
67   if (this->grf_used >= max_grf) {
68      fail("Ran out of regs on trivial allocator (%d/%d)\n",
69	   this->grf_used, max_grf);
70   } else {
71      this->alloc.count = this->grf_used;
72   }
73
74}
75
76/**
77 * Size of a register from the aligned_bary_class register class.
78 */
79static unsigned
80aligned_bary_size(unsigned dispatch_width)
81{
82   return (dispatch_width == 8 ? 2 : 4);
83}
84
85static void
86brw_alloc_reg_set(struct brw_compiler *compiler, int dispatch_width)
87{
88   const struct intel_device_info *devinfo = compiler->devinfo;
89   int base_reg_count = BRW_MAX_GRF;
90   const int index = util_logbase2(dispatch_width / 8);
91
92   if (dispatch_width > 8 && devinfo->ver >= 7) {
93      /* For IVB+, we don't need the PLN hacks or the even-reg alignment in
94       * SIMD16.  Therefore, we can use the exact same register sets for
95       * SIMD16 as we do for SIMD8 and we don't need to recalculate them.
96       */
97      compiler->fs_reg_sets[index] = compiler->fs_reg_sets[0];
98      return;
99   }
100
101   /* The registers used to make up almost all values handled in the compiler
102    * are a scalar value occupying a single register (or 2 registers in the
103    * case of SIMD16, which is handled by dividing base_reg_count by 2 and
104    * multiplying allocated register numbers by 2).  Things that were
105    * aggregates of scalar values at the GLSL level were split to scalar
106    * values by split_virtual_grfs().
107    *
108    * However, texture SEND messages return a series of contiguous registers
109    * to write into.  We currently always ask for 4 registers, but we may
110    * convert that to use less some day.
111    *
112    * Additionally, on gfx5 we need aligned pairs of registers for the PLN
113    * instruction, and on gfx4 we need 8 contiguous regs for workaround simd16
114    * texturing.
115    */
116   const int class_count = MAX_VGRF_SIZE;
117   int class_sizes[MAX_VGRF_SIZE];
118   for (unsigned i = 0; i < MAX_VGRF_SIZE; i++)
119      class_sizes[i] = i + 1;
120
121   struct ra_regs *regs = ra_alloc_reg_set(compiler, BRW_MAX_GRF, false);
122   if (devinfo->ver >= 6)
123      ra_set_allocate_round_robin(regs);
124   struct ra_class **classes = ralloc_array(compiler, struct ra_class *, class_count);
125   struct ra_class *aligned_bary_class = NULL;
126
127   /* Now, make the register classes for each size of contiguous register
128    * allocation we might need to make.
129    */
130   for (int i = 0; i < class_count; i++) {
131      classes[i] = ra_alloc_contig_reg_class(regs, class_sizes[i]);
132
133      if (devinfo->ver <= 5 && dispatch_width >= 16) {
134         /* From the G45 PRM:
135          *
136          * In order to reduce the hardware complexity, the following
137          * rules and restrictions apply to the compressed instruction:
138          * ...
139          * * Operand Alignment Rule: With the exceptions listed below, a
140          *   source/destination operand in general should be aligned to
141          *   even 256-bit physical register with a region size equal to
142          *   two 256-bit physical register
143          */
144         for (int reg = 0; reg <= base_reg_count - class_sizes[i]; reg += 2)
145            ra_class_add_reg(classes[i], reg);
146      } else {
147         for (int reg = 0; reg <= base_reg_count - class_sizes[i]; reg++)
148            ra_class_add_reg(classes[i], reg);
149      }
150   }
151
152   /* Add a special class for aligned barycentrics, which we'll put the
153    * first source of LINTERP on so that we can do PLN on Gen <= 6.
154    */
155   if (devinfo->has_pln && (devinfo->ver == 6 ||
156                            (dispatch_width == 8 && devinfo->ver <= 5))) {
157      int contig_len = aligned_bary_size(dispatch_width);
158      aligned_bary_class = ra_alloc_contig_reg_class(regs, contig_len);
159
160      for (int i = 0; i <= base_reg_count - contig_len; i += 2)
161         ra_class_add_reg(aligned_bary_class, i);
162   }
163
164   ra_set_finalize(regs, NULL);
165
166   compiler->fs_reg_sets[index].regs = regs;
167   for (unsigned i = 0; i < ARRAY_SIZE(compiler->fs_reg_sets[index].classes); i++)
168      compiler->fs_reg_sets[index].classes[i] = NULL;
169   for (int i = 0; i < class_count; i++)
170      compiler->fs_reg_sets[index].classes[class_sizes[i] - 1] = classes[i];
171   compiler->fs_reg_sets[index].aligned_bary_class = aligned_bary_class;
172}
173
174void
175brw_fs_alloc_reg_sets(struct brw_compiler *compiler)
176{
177   brw_alloc_reg_set(compiler, 8);
178   brw_alloc_reg_set(compiler, 16);
179   brw_alloc_reg_set(compiler, 32);
180}
181
182static int
183count_to_loop_end(const bblock_t *block)
184{
185   if (block->end()->opcode == BRW_OPCODE_WHILE)
186      return block->end_ip;
187
188   int depth = 1;
189   /* Skip the first block, since we don't want to count the do the calling
190    * function found.
191    */
192   for (block = block->next();
193        depth > 0;
194        block = block->next()) {
195      if (block->start()->opcode == BRW_OPCODE_DO)
196         depth++;
197      if (block->end()->opcode == BRW_OPCODE_WHILE) {
198         depth--;
199         if (depth == 0)
200            return block->end_ip;
201      }
202   }
203   unreachable("not reached");
204}
205
206void fs_visitor::calculate_payload_ranges(int payload_node_count,
207                                          int *payload_last_use_ip) const
208{
209   int loop_depth = 0;
210   int loop_end_ip = 0;
211
212   for (int i = 0; i < payload_node_count; i++)
213      payload_last_use_ip[i] = -1;
214
215   int ip = 0;
216   foreach_block_and_inst(block, fs_inst, inst, cfg) {
217      switch (inst->opcode) {
218      case BRW_OPCODE_DO:
219         loop_depth++;
220
221         /* Since payload regs are deffed only at the start of the shader
222          * execution, any uses of the payload within a loop mean the live
223          * interval extends to the end of the outermost loop.  Find the ip of
224          * the end now.
225          */
226         if (loop_depth == 1)
227            loop_end_ip = count_to_loop_end(block);
228         break;
229      case BRW_OPCODE_WHILE:
230         loop_depth--;
231         break;
232      default:
233         break;
234      }
235
236      int use_ip;
237      if (loop_depth > 0)
238         use_ip = loop_end_ip;
239      else
240         use_ip = ip;
241
242      /* Note that UNIFORM args have been turned into FIXED_GRF by
243       * assign_curbe_setup(), and interpolation uses fixed hardware regs from
244       * the start (see interp_reg()).
245       */
246      for (int i = 0; i < inst->sources; i++) {
247         if (inst->src[i].file == FIXED_GRF) {
248            int node_nr = inst->src[i].nr;
249            if (node_nr >= payload_node_count)
250               continue;
251
252            for (unsigned j = 0; j < regs_read(inst, i); j++) {
253               payload_last_use_ip[node_nr + j] = use_ip;
254               assert(node_nr + j < unsigned(payload_node_count));
255            }
256         }
257      }
258
259      if (inst->dst.file == FIXED_GRF) {
260         int node_nr = inst->dst.nr;
261         if (node_nr < payload_node_count) {
262            for (unsigned j = 0; j < regs_written(inst); j++) {
263               payload_last_use_ip[node_nr + j] = use_ip;
264               assert(node_nr + j < unsigned(payload_node_count));
265            }
266         }
267      }
268
269      /* Special case instructions which have extra implied registers used. */
270      switch (inst->opcode) {
271      case CS_OPCODE_CS_TERMINATE:
272         payload_last_use_ip[0] = use_ip;
273         break;
274
275      default:
276         if (inst->eot) {
277            /* We could omit this for the !inst->header_present case, except
278             * that the simulator apparently incorrectly reads from g0/g1
279             * instead of sideband.  It also really freaks out driver
280             * developers to see g0 used in unusual places, so just always
281             * reserve it.
282             */
283            payload_last_use_ip[0] = use_ip;
284            payload_last_use_ip[1] = use_ip;
285         }
286         break;
287      }
288
289      ip++;
290   }
291}
292
293class fs_reg_alloc {
294public:
295   fs_reg_alloc(fs_visitor *fs):
296      fs(fs), devinfo(fs->devinfo), compiler(fs->compiler),
297      live(fs->live_analysis.require()), g(NULL),
298      have_spill_costs(false)
299   {
300      mem_ctx = ralloc_context(NULL);
301
302      /* Stash the number of instructions so we can sanity check that our
303       * counts still match liveness.
304       */
305      live_instr_count = fs->cfg->last_block()->end_ip + 1;
306
307      spill_insts = _mesa_pointer_set_create(mem_ctx);
308
309      /* Most of this allocation was written for a reg_width of 1
310       * (dispatch_width == 8).  In extending to SIMD16, the code was
311       * left in place and it was converted to have the hardware
312       * registers it's allocating be contiguous physical pairs of regs
313       * for reg_width == 2.
314       */
315      int reg_width = fs->dispatch_width / 8;
316      rsi = util_logbase2(reg_width);
317      payload_node_count = ALIGN(fs->first_non_payload_grf, reg_width);
318
319      /* Get payload IP information */
320      payload_last_use_ip = ralloc_array(mem_ctx, int, payload_node_count);
321
322      node_count = 0;
323      first_payload_node = 0;
324      first_mrf_hack_node = 0;
325      scratch_header_node = 0;
326      grf127_send_hack_node = 0;
327      first_vgrf_node = 0;
328      last_vgrf_node = 0;
329      first_spill_node = 0;
330
331      spill_vgrf_ip = NULL;
332      spill_vgrf_ip_alloc = 0;
333      spill_node_count = 0;
334   }
335
336   ~fs_reg_alloc()
337   {
338      ralloc_free(mem_ctx);
339   }
340
341   bool assign_regs(bool allow_spilling, bool spill_all);
342
343private:
344   void setup_live_interference(unsigned node,
345                                int node_start_ip, int node_end_ip);
346   void setup_inst_interference(const fs_inst *inst);
347
348   void build_interference_graph(bool allow_spilling);
349   void discard_interference_graph();
350
351   void emit_unspill(const fs_builder &bld, fs_reg dst,
352                     uint32_t spill_offset, unsigned count);
353   void emit_spill(const fs_builder &bld, fs_reg src,
354                   uint32_t spill_offset, unsigned count);
355
356   void set_spill_costs();
357   int choose_spill_reg();
358   fs_reg alloc_scratch_header();
359   fs_reg alloc_spill_reg(unsigned size, int ip);
360   void spill_reg(unsigned spill_reg);
361
362   void *mem_ctx;
363   fs_visitor *fs;
364   const intel_device_info *devinfo;
365   const brw_compiler *compiler;
366   const fs_live_variables &live;
367   int live_instr_count;
368
369   set *spill_insts;
370
371   /* Which compiler->fs_reg_sets[] to use */
372   int rsi;
373
374   ra_graph *g;
375   bool have_spill_costs;
376
377   int payload_node_count;
378   int *payload_last_use_ip;
379
380   int node_count;
381   int first_payload_node;
382   int first_mrf_hack_node;
383   int scratch_header_node;
384   int grf127_send_hack_node;
385   int first_vgrf_node;
386   int last_vgrf_node;
387   int first_spill_node;
388
389   int *spill_vgrf_ip;
390   int spill_vgrf_ip_alloc;
391   int spill_node_count;
392
393   fs_reg scratch_header;
394};
395
396/**
397 * Sets the mrf_used array to indicate which MRFs are used by the shader IR
398 *
399 * This is used in assign_regs() to decide which of the GRFs that we use as
400 * MRFs on gfx7 get normally register allocated, and in register spilling to
401 * see if we can actually use MRFs to do spills without overwriting normal MRF
402 * contents.
403 */
404static void
405get_used_mrfs(const fs_visitor *v, bool *mrf_used)
406{
407   int reg_width = v->dispatch_width / 8;
408
409   memset(mrf_used, 0, BRW_MAX_MRF(v->devinfo->ver) * sizeof(bool));
410
411   foreach_block_and_inst(block, fs_inst, inst, v->cfg) {
412      if (inst->dst.file == MRF) {
413         int reg = inst->dst.nr & ~BRW_MRF_COMPR4;
414         mrf_used[reg] = true;
415         if (reg_width == 2) {
416            if (inst->dst.nr & BRW_MRF_COMPR4) {
417               mrf_used[reg + 4] = true;
418            } else {
419               mrf_used[reg + 1] = true;
420            }
421         }
422      }
423
424      if (inst->mlen > 0) {
425	 for (unsigned i = 0; i < inst->implied_mrf_writes(); i++) {
426            mrf_used[inst->base_mrf + i] = true;
427         }
428      }
429   }
430}
431
432namespace {
433   /**
434    * Maximum spill block size we expect to encounter in 32B units.
435    *
436    * This is somewhat arbitrary and doesn't necessarily limit the maximum
437    * variable size that can be spilled -- A higher value will allow a
438    * variable of a given size to be spilled more efficiently with a smaller
439    * number of scratch messages, but will increase the likelihood of a
440    * collision between the MRFs reserved for spilling and other MRFs used by
441    * the program (and possibly increase GRF register pressure on platforms
442    * without hardware MRFs), what could cause register allocation to fail.
443    *
444    * For the moment reserve just enough space so a register of 32 bit
445    * component type and natural region width can be spilled without splitting
446    * into multiple (force_writemask_all) scratch messages.
447    */
448   unsigned
449   spill_max_size(const backend_shader *s)
450   {
451      /* FINISHME - On Gfx7+ it should be possible to avoid this limit
452       *            altogether by spilling directly from the temporary GRF
453       *            allocated to hold the result of the instruction (and the
454       *            scratch write header).
455       */
456      /* FINISHME - The shader's dispatch width probably belongs in
457       *            backend_shader (or some nonexistent fs_shader class?)
458       *            rather than in the visitor class.
459       */
460      return static_cast<const fs_visitor *>(s)->dispatch_width / 8;
461   }
462
463   /**
464    * First MRF register available for spilling.
465    */
466   unsigned
467   spill_base_mrf(const backend_shader *s)
468   {
469      /* We don't use the MRF hack on Gfx9+ */
470      assert(s->devinfo->ver < 9);
471      return BRW_MAX_MRF(s->devinfo->ver) - spill_max_size(s) - 1;
472   }
473}
474
475void
476fs_reg_alloc::setup_live_interference(unsigned node,
477                                      int node_start_ip, int node_end_ip)
478{
479   /* Mark any virtual grf that is live between the start of the program and
480    * the last use of a payload node interfering with that payload node.
481    */
482   for (int i = 0; i < payload_node_count; i++) {
483      if (payload_last_use_ip[i] == -1)
484         continue;
485
486      /* Note that we use a <= comparison, unlike vgrfs_interfere(),
487       * in order to not have to worry about the uniform issue described in
488       * calculate_live_intervals().
489       */
490      if (node_start_ip <= payload_last_use_ip[i])
491         ra_add_node_interference(g, node, first_payload_node + i);
492   }
493
494   /* If we have the MRF hack enabled, mark this node as interfering with all
495    * MRF registers.
496    */
497   if (first_mrf_hack_node >= 0) {
498      for (int i = spill_base_mrf(fs); i < BRW_MAX_MRF(devinfo->ver); i++)
499         ra_add_node_interference(g, node, first_mrf_hack_node + i);
500   }
501
502   /* Everything interferes with the scratch header */
503   if (scratch_header_node >= 0)
504      ra_add_node_interference(g, node, scratch_header_node);
505
506   /* Add interference with every vgrf whose live range intersects this
507    * node's.  We only need to look at nodes below this one as the reflexivity
508    * of interference will take care of the rest.
509    */
510   for (unsigned n2 = first_vgrf_node;
511        n2 <= (unsigned)last_vgrf_node && n2 < node; n2++) {
512      unsigned vgrf = n2 - first_vgrf_node;
513      if (!(node_end_ip <= live.vgrf_start[vgrf] ||
514            live.vgrf_end[vgrf] <= node_start_ip))
515         ra_add_node_interference(g, node, n2);
516   }
517}
518
519void
520fs_reg_alloc::setup_inst_interference(const fs_inst *inst)
521{
522   /* Certain instructions can't safely use the same register for their
523    * sources and destination.  Add interference.
524    */
525   if (inst->dst.file == VGRF && inst->has_source_and_destination_hazard()) {
526      for (unsigned i = 0; i < inst->sources; i++) {
527         if (inst->src[i].file == VGRF) {
528            ra_add_node_interference(g, first_vgrf_node + inst->dst.nr,
529                                        first_vgrf_node + inst->src[i].nr);
530         }
531      }
532   }
533
534   /* In 16-wide instructions we have an issue where a compressed
535    * instruction is actually two instructions executed simultaneously.
536    * It's actually ok to have the source and destination registers be
537    * the same.  In this case, each instruction over-writes its own
538    * source and there's no problem.  The real problem here is if the
539    * source and destination registers are off by one.  Then you can end
540    * up in a scenario where the first instruction over-writes the
541    * source of the second instruction.  Since the compiler doesn't know
542    * about this level of granularity, we simply make the source and
543    * destination interfere.
544    */
545   if (inst->exec_size >= 16 && inst->dst.file == VGRF) {
546      for (int i = 0; i < inst->sources; ++i) {
547         if (inst->src[i].file == VGRF) {
548            ra_add_node_interference(g, first_vgrf_node + inst->dst.nr,
549                                        first_vgrf_node + inst->src[i].nr);
550         }
551      }
552   }
553
554   if (grf127_send_hack_node >= 0) {
555      /* At Intel Broadwell PRM, vol 07, section "Instruction Set Reference",
556       * subsection "EUISA Instructions", Send Message (page 990):
557       *
558       * "r127 must not be used for return address when there is a src and
559       * dest overlap in send instruction."
560       *
561       * We are avoiding using grf127 as part of the destination of send
562       * messages adding a node interference to the grf127_send_hack_node.
563       * This node has a fixed asignment to grf127.
564       *
565       * We don't apply it to SIMD16 instructions because previous code avoids
566       * any register overlap between sources and destination.
567       */
568      if (inst->exec_size < 16 && inst->is_send_from_grf() &&
569          inst->dst.file == VGRF)
570         ra_add_node_interference(g, first_vgrf_node + inst->dst.nr,
571                                     grf127_send_hack_node);
572
573      /* Spilling instruction are genereated as SEND messages from MRF but as
574       * Gfx7+ supports sending from GRF the driver will maps assingn these
575       * MRF registers to a GRF. Implementations reuses the dest of the send
576       * message as source. So as we will have an overlap for sure, we create
577       * an interference between destination and grf127.
578       */
579      if ((inst->opcode == SHADER_OPCODE_GFX7_SCRATCH_READ ||
580           inst->opcode == SHADER_OPCODE_GFX4_SCRATCH_READ) &&
581          inst->dst.file == VGRF)
582         ra_add_node_interference(g, first_vgrf_node + inst->dst.nr,
583                                     grf127_send_hack_node);
584   }
585
586   /* From the Skylake PRM Vol. 2a docs for sends:
587    *
588    *    "It is required that the second block of GRFs does not overlap with
589    *    the first block."
590    *
591    * Normally, this is taken care of by fixup_sends_duplicate_payload() but
592    * in the case where one of the registers is an undefined value, the
593    * register allocator may decide that they don't interfere even though
594    * they're used as sources in the same instruction.  We also need to add
595    * interference here.
596    */
597   if (devinfo->ver >= 9) {
598      if (inst->opcode == SHADER_OPCODE_SEND && inst->ex_mlen > 0 &&
599          inst->src[2].file == VGRF && inst->src[3].file == VGRF &&
600          inst->src[2].nr != inst->src[3].nr)
601         ra_add_node_interference(g, first_vgrf_node + inst->src[2].nr,
602                                     first_vgrf_node + inst->src[3].nr);
603   }
604
605   /* When we do send-from-GRF for FB writes, we need to ensure that the last
606    * write instruction sends from a high register.  This is because the
607    * vertex fetcher wants to start filling the low payload registers while
608    * the pixel data port is still working on writing out the memory.  If we
609    * don't do this, we get rendering artifacts.
610    *
611    * We could just do "something high".  Instead, we just pick the highest
612    * register that works.
613    */
614   if (inst->eot) {
615      const int vgrf = inst->opcode == SHADER_OPCODE_SEND ?
616                       inst->src[2].nr : inst->src[0].nr;
617      int size = fs->alloc.sizes[vgrf];
618      int reg = BRW_MAX_GRF - size;
619
620      if (first_mrf_hack_node >= 0) {
621         /* If something happened to spill, we want to push the EOT send
622          * register early enough in the register file that we don't
623          * conflict with any used MRF hack registers.
624          */
625         reg -= BRW_MAX_MRF(devinfo->ver) - spill_base_mrf(fs);
626      } else if (grf127_send_hack_node >= 0) {
627         /* Avoid r127 which might be unusable if the node was previously
628          * written by a SIMD8 SEND message with source/destination overlap.
629          */
630         reg--;
631      }
632
633      ra_set_node_reg(g, first_vgrf_node + vgrf, reg);
634   }
635}
636
637void
638fs_reg_alloc::build_interference_graph(bool allow_spilling)
639{
640   /* Compute the RA node layout */
641   node_count = 0;
642   first_payload_node = node_count;
643   node_count += payload_node_count;
644   if (devinfo->ver >= 7 && devinfo->ver < 9 && allow_spilling) {
645      first_mrf_hack_node = node_count;
646      node_count += BRW_MAX_GRF - GFX7_MRF_HACK_START;
647   } else {
648      first_mrf_hack_node = -1;
649   }
650   if (devinfo->ver >= 8) {
651      grf127_send_hack_node = node_count;
652      node_count ++;
653   } else {
654      grf127_send_hack_node = -1;
655   }
656   first_vgrf_node = node_count;
657   node_count += fs->alloc.count;
658   last_vgrf_node = node_count - 1;
659   if (devinfo->ver >= 9 && allow_spilling) {
660      scratch_header_node = node_count++;
661   } else {
662      scratch_header_node = -1;
663   }
664   first_spill_node = node_count;
665
666   fs->calculate_payload_ranges(payload_node_count,
667                                payload_last_use_ip);
668
669   assert(g == NULL);
670   g = ra_alloc_interference_graph(compiler->fs_reg_sets[rsi].regs, node_count);
671   ralloc_steal(mem_ctx, g);
672
673   /* Set up the payload nodes */
674   for (int i = 0; i < payload_node_count; i++)
675      ra_set_node_reg(g, first_payload_node + i, i);
676
677   if (first_mrf_hack_node >= 0) {
678      /* Mark each MRF reg node as being allocated to its physical
679       * register.
680       *
681       * The alternative would be to have per-physical-register classes,
682       * which would just be silly.
683       */
684      for (int i = 0; i < BRW_MAX_MRF(devinfo->ver); i++) {
685         ra_set_node_reg(g, first_mrf_hack_node + i,
686                            GFX7_MRF_HACK_START + i);
687      }
688   }
689
690   if (grf127_send_hack_node >= 0)
691      ra_set_node_reg(g, grf127_send_hack_node, 127);
692
693   /* Specify the classes of each virtual register. */
694   for (unsigned i = 0; i < fs->alloc.count; i++) {
695      unsigned size = fs->alloc.sizes[i];
696
697      assert(size <= ARRAY_SIZE(compiler->fs_reg_sets[rsi].classes) &&
698             "Register allocation relies on split_virtual_grfs()");
699
700      ra_set_node_class(g, first_vgrf_node + i,
701                        compiler->fs_reg_sets[rsi].classes[size - 1]);
702   }
703
704   /* Special case: on pre-Gfx7 hardware that supports PLN, the second operand
705    * of a PLN instruction needs to be an even-numbered register, so we have a
706    * special register class aligned_bary_class to handle this case.
707    */
708   if (compiler->fs_reg_sets[rsi].aligned_bary_class) {
709      foreach_block_and_inst(block, fs_inst, inst, fs->cfg) {
710         if (inst->opcode == FS_OPCODE_LINTERP && inst->src[0].file == VGRF &&
711             fs->alloc.sizes[inst->src[0].nr] ==
712               aligned_bary_size(fs->dispatch_width)) {
713            ra_set_node_class(g, first_vgrf_node + inst->src[0].nr,
714                              compiler->fs_reg_sets[rsi].aligned_bary_class);
715         }
716      }
717   }
718
719   /* Add interference based on the live range of the register */
720   for (unsigned i = 0; i < fs->alloc.count; i++) {
721      setup_live_interference(first_vgrf_node + i,
722                              live.vgrf_start[i],
723                              live.vgrf_end[i]);
724   }
725
726   /* Add interference based on the instructions in which a register is used.
727    */
728   foreach_block_and_inst(block, fs_inst, inst, fs->cfg)
729      setup_inst_interference(inst);
730}
731
732void
733fs_reg_alloc::discard_interference_graph()
734{
735   ralloc_free(g);
736   g = NULL;
737   have_spill_costs = false;
738}
739
740void
741fs_reg_alloc::emit_unspill(const fs_builder &bld, fs_reg dst,
742                           uint32_t spill_offset, unsigned count)
743{
744   const intel_device_info *devinfo = bld.shader->devinfo;
745   const unsigned reg_size = dst.component_size(bld.dispatch_width()) /
746                             REG_SIZE;
747   assert(count % reg_size == 0);
748
749   for (unsigned i = 0; i < count / reg_size; i++) {
750      fs_inst *unspill_inst;
751      if (devinfo->ver >= 9) {
752         fs_reg header = this->scratch_header;
753         fs_builder ubld = bld.exec_all().group(1, 0);
754         assert(spill_offset % 16 == 0);
755         unspill_inst = ubld.MOV(component(header, 2),
756                                 brw_imm_ud(spill_offset / 16));
757         _mesa_set_add(spill_insts, unspill_inst);
758
759         unsigned bti;
760         fs_reg ex_desc;
761         if (devinfo->verx10 >= 125) {
762            bti = GFX9_BTI_BINDLESS;
763            ex_desc = component(this->scratch_header, 0);
764         } else {
765            bti = GFX8_BTI_STATELESS_NON_COHERENT;
766            ex_desc = brw_imm_ud(0);
767         }
768
769         fs_reg srcs[] = { brw_imm_ud(0), ex_desc, header };
770         unspill_inst = bld.emit(SHADER_OPCODE_SEND, dst,
771                                 srcs, ARRAY_SIZE(srcs));
772         unspill_inst->mlen = 1;
773         unspill_inst->header_size = 1;
774         unspill_inst->size_written = reg_size * REG_SIZE;
775         unspill_inst->send_has_side_effects = false;
776         unspill_inst->send_is_volatile = true;
777         unspill_inst->sfid = GFX7_SFID_DATAPORT_DATA_CACHE;
778         unspill_inst->desc =
779            brw_dp_desc(devinfo, bti,
780                        BRW_DATAPORT_READ_MESSAGE_OWORD_BLOCK_READ,
781                        BRW_DATAPORT_OWORD_BLOCK_DWORDS(reg_size * 8));
782      } else if (devinfo->ver >= 7 && spill_offset < (1 << 12) * REG_SIZE) {
783         /* The Gfx7 descriptor-based offset is 12 bits of HWORD units.
784          * Because the Gfx7-style scratch block read is hardwired to BTI 255,
785          * on Gfx9+ it would cause the DC to do an IA-coherent read, what
786          * largely outweighs the slight advantage from not having to provide
787          * the address as part of the message header, so we're better off
788          * using plain old oword block reads.
789          */
790         unspill_inst = bld.emit(SHADER_OPCODE_GFX7_SCRATCH_READ, dst);
791         unspill_inst->offset = spill_offset;
792      } else {
793         unspill_inst = bld.emit(SHADER_OPCODE_GFX4_SCRATCH_READ, dst);
794         unspill_inst->offset = spill_offset;
795         unspill_inst->base_mrf = spill_base_mrf(bld.shader);
796         unspill_inst->mlen = 1; /* header contains offset */
797      }
798      _mesa_set_add(spill_insts, unspill_inst);
799
800      dst.offset += reg_size * REG_SIZE;
801      spill_offset += reg_size * REG_SIZE;
802   }
803}
804
805void
806fs_reg_alloc::emit_spill(const fs_builder &bld, fs_reg src,
807                         uint32_t spill_offset, unsigned count)
808{
809   const intel_device_info *devinfo = bld.shader->devinfo;
810   const unsigned reg_size = src.component_size(bld.dispatch_width()) /
811                             REG_SIZE;
812   assert(count % reg_size == 0);
813
814   for (unsigned i = 0; i < count / reg_size; i++) {
815      fs_inst *spill_inst;
816      if (devinfo->ver >= 9) {
817         fs_reg header = this->scratch_header;
818         fs_builder ubld = bld.exec_all().group(1, 0);
819         assert(spill_offset % 16 == 0);
820         spill_inst = ubld.MOV(component(header, 2),
821                               brw_imm_ud(spill_offset / 16));
822         _mesa_set_add(spill_insts, spill_inst);
823
824         unsigned bti;
825         fs_reg ex_desc;
826         if (devinfo->verx10 >= 125) {
827            bti = GFX9_BTI_BINDLESS;
828            ex_desc = component(this->scratch_header, 0);
829         } else {
830            bti = GFX8_BTI_STATELESS_NON_COHERENT;
831            ex_desc = brw_imm_ud(0);
832         }
833
834         fs_reg srcs[] = { brw_imm_ud(0), ex_desc, header, src };
835         spill_inst = bld.emit(SHADER_OPCODE_SEND, bld.null_reg_f(),
836                               srcs, ARRAY_SIZE(srcs));
837         spill_inst->mlen = 1;
838         spill_inst->ex_mlen = reg_size;
839         spill_inst->size_written = 0;
840         spill_inst->header_size = 1;
841         spill_inst->send_has_side_effects = true;
842         spill_inst->send_is_volatile = false;
843         spill_inst->sfid = GFX7_SFID_DATAPORT_DATA_CACHE;
844         spill_inst->desc =
845            brw_dp_desc(devinfo, bti,
846                        GFX6_DATAPORT_WRITE_MESSAGE_OWORD_BLOCK_WRITE,
847                        BRW_DATAPORT_OWORD_BLOCK_DWORDS(reg_size * 8));
848      } else {
849         spill_inst = bld.emit(SHADER_OPCODE_GFX4_SCRATCH_WRITE,
850                               bld.null_reg_f(), src);
851         spill_inst->offset = spill_offset;
852         spill_inst->mlen = 1 + reg_size; /* header, value */
853         spill_inst->base_mrf = spill_base_mrf(bld.shader);
854      }
855      _mesa_set_add(spill_insts, spill_inst);
856
857      src.offset += reg_size * REG_SIZE;
858      spill_offset += reg_size * REG_SIZE;
859   }
860}
861
862void
863fs_reg_alloc::set_spill_costs()
864{
865   float block_scale = 1.0;
866   float spill_costs[fs->alloc.count];
867   bool no_spill[fs->alloc.count];
868
869   for (unsigned i = 0; i < fs->alloc.count; i++) {
870      spill_costs[i] = 0.0;
871      no_spill[i] = false;
872   }
873
874   /* Calculate costs for spilling nodes.  Call it a cost of 1 per
875    * spill/unspill we'll have to do, and guess that the insides of
876    * loops run 10 times.
877    */
878   foreach_block_and_inst(block, fs_inst, inst, fs->cfg) {
879      for (unsigned int i = 0; i < inst->sources; i++) {
880	 if (inst->src[i].file == VGRF)
881            spill_costs[inst->src[i].nr] += regs_read(inst, i) * block_scale;
882      }
883
884      if (inst->dst.file == VGRF)
885         spill_costs[inst->dst.nr] += regs_written(inst) * block_scale;
886
887      /* Don't spill anything we generated while spilling */
888      if (_mesa_set_search(spill_insts, inst)) {
889         for (unsigned int i = 0; i < inst->sources; i++) {
890	    if (inst->src[i].file == VGRF)
891               no_spill[inst->src[i].nr] = true;
892         }
893	 if (inst->dst.file == VGRF)
894            no_spill[inst->dst.nr] = true;
895      }
896
897      switch (inst->opcode) {
898
899      case BRW_OPCODE_DO:
900	 block_scale *= 10;
901	 break;
902
903      case BRW_OPCODE_WHILE:
904	 block_scale /= 10;
905	 break;
906
907      case BRW_OPCODE_IF:
908      case BRW_OPCODE_IFF:
909         block_scale *= 0.5;
910         break;
911
912      case BRW_OPCODE_ENDIF:
913         block_scale /= 0.5;
914         break;
915
916      default:
917	 break;
918      }
919   }
920
921   for (unsigned i = 0; i < fs->alloc.count; i++) {
922      /* Do the no_spill check first.  Registers that are used as spill
923       * temporaries may have been allocated after we calculated liveness so
924       * we shouldn't look their liveness up.  Fortunately, they're always
925       * used in SCRATCH_READ/WRITE instructions so they'll always be flagged
926       * no_spill.
927       */
928      if (no_spill[i])
929         continue;
930
931      int live_length = live.vgrf_end[i] - live.vgrf_start[i];
932      if (live_length <= 0)
933         continue;
934
935      /* Divide the cost (in number of spills/fills) by the log of the length
936       * of the live range of the register.  This will encourage spill logic
937       * to spill long-living things before spilling short-lived things where
938       * spilling is less likely to actually do us any good.  We use the log
939       * of the length because it will fall off very quickly and not cause us
940       * to spill medium length registers with more uses.
941       */
942      float adjusted_cost = spill_costs[i] / logf(live_length);
943      ra_set_node_spill_cost(g, first_vgrf_node + i, adjusted_cost);
944   }
945
946   have_spill_costs = true;
947}
948
949int
950fs_reg_alloc::choose_spill_reg()
951{
952   if (!have_spill_costs)
953      set_spill_costs();
954
955   int node = ra_get_best_spill_node(g);
956   if (node < 0)
957      return -1;
958
959   assert(node >= first_vgrf_node);
960   return node - first_vgrf_node;
961}
962
963fs_reg
964fs_reg_alloc::alloc_scratch_header()
965{
966   int vgrf = fs->alloc.allocate(1);
967   assert(first_vgrf_node + vgrf == scratch_header_node);
968   ra_set_node_class(g, scratch_header_node,
969                        compiler->fs_reg_sets[rsi].classes[0]);
970
971   setup_live_interference(scratch_header_node, 0, INT_MAX);
972
973   return fs_reg(VGRF, vgrf, BRW_REGISTER_TYPE_UD);
974}
975
976fs_reg
977fs_reg_alloc::alloc_spill_reg(unsigned size, int ip)
978{
979   int vgrf = fs->alloc.allocate(size);
980   int n = ra_add_node(g, compiler->fs_reg_sets[rsi].classes[size - 1]);
981   assert(n == first_vgrf_node + vgrf);
982   assert(n == first_spill_node + spill_node_count);
983
984   setup_live_interference(n, ip - 1, ip + 1);
985
986   /* Add interference between this spill node and any other spill nodes for
987    * the same instruction.
988    */
989   for (int s = 0; s < spill_node_count; s++) {
990      if (spill_vgrf_ip[s] == ip)
991         ra_add_node_interference(g, n, first_spill_node + s);
992   }
993
994   /* Add this spill node to the list for next time */
995   if (spill_node_count >= spill_vgrf_ip_alloc) {
996      if (spill_vgrf_ip_alloc == 0)
997         spill_vgrf_ip_alloc = 16;
998      else
999         spill_vgrf_ip_alloc *= 2;
1000      spill_vgrf_ip = reralloc(mem_ctx, spill_vgrf_ip, int,
1001                               spill_vgrf_ip_alloc);
1002   }
1003   spill_vgrf_ip[spill_node_count++] = ip;
1004
1005   return fs_reg(VGRF, vgrf);
1006}
1007
1008void
1009fs_reg_alloc::spill_reg(unsigned spill_reg)
1010{
1011   int size = fs->alloc.sizes[spill_reg];
1012   unsigned int spill_offset = fs->last_scratch;
1013   assert(ALIGN(spill_offset, 16) == spill_offset); /* oword read/write req. */
1014
1015   /* Spills may use MRFs 13-15 in the SIMD16 case.  Our texturing is done
1016    * using up to 11 MRFs starting from either m1 or m2, and fb writes can use
1017    * up to m13 (gfx6+ simd16: 2 header + 8 color + 2 src0alpha + 2 omask) or
1018    * m15 (gfx4-5 simd16: 2 header + 8 color + 1 aads + 2 src depth + 2 dst
1019    * depth), starting from m1.  In summary: We may not be able to spill in
1020    * SIMD16 mode, because we'd stomp the FB writes.
1021    */
1022   if (!fs->spilled_any_registers) {
1023      if (devinfo->ver >= 9) {
1024         this->scratch_header = alloc_scratch_header();
1025         fs_builder ubld = fs->bld.exec_all().group(8, 0).at(
1026            fs->cfg->first_block(), fs->cfg->first_block()->start());
1027
1028         fs_inst *inst;
1029         if (devinfo->verx10 >= 125) {
1030            inst = ubld.MOV(this->scratch_header, brw_imm_ud(0));
1031            _mesa_set_add(spill_insts, inst);
1032            inst = ubld.group(1, 0).AND(component(this->scratch_header, 0),
1033                                        retype(brw_vec1_grf(0, 5),
1034                                               BRW_REGISTER_TYPE_UD),
1035                                        brw_imm_ud(INTEL_MASK(31, 10)));
1036            _mesa_set_add(spill_insts, inst);
1037         } else {
1038            inst = ubld.emit(SHADER_OPCODE_SCRATCH_HEADER,
1039                             this->scratch_header);
1040            _mesa_set_add(spill_insts, inst);
1041         }
1042      } else {
1043         bool mrf_used[BRW_MAX_MRF(devinfo->ver)];
1044         get_used_mrfs(fs, mrf_used);
1045
1046         for (int i = spill_base_mrf(fs); i < BRW_MAX_MRF(devinfo->ver); i++) {
1047            if (mrf_used[i]) {
1048               fs->fail("Register spilling not supported with m%d used", i);
1049             return;
1050            }
1051         }
1052      }
1053
1054      fs->spilled_any_registers = true;
1055   }
1056
1057   fs->last_scratch += size * REG_SIZE;
1058
1059   /* We're about to replace all uses of this register.  It no longer
1060    * conflicts with anything so we can get rid of its interference.
1061    */
1062   ra_set_node_spill_cost(g, first_vgrf_node + spill_reg, 0);
1063   ra_reset_node_interference(g, first_vgrf_node + spill_reg);
1064
1065   /* Generate spill/unspill instructions for the objects being
1066    * spilled.  Right now, we spill or unspill the whole thing to a
1067    * virtual grf of the same size.  For most instructions, though, we
1068    * could just spill/unspill the GRF being accessed.
1069    */
1070   int ip = 0;
1071   foreach_block_and_inst (block, fs_inst, inst, fs->cfg) {
1072      const fs_builder ibld = fs_builder(fs, block, inst);
1073      exec_node *before = inst->prev;
1074      exec_node *after = inst->next;
1075
1076      for (unsigned int i = 0; i < inst->sources; i++) {
1077	 if (inst->src[i].file == VGRF &&
1078             inst->src[i].nr == spill_reg) {
1079            int count = regs_read(inst, i);
1080            int subset_spill_offset = spill_offset +
1081               ROUND_DOWN_TO(inst->src[i].offset, REG_SIZE);
1082            fs_reg unspill_dst = alloc_spill_reg(count, ip);
1083
1084            inst->src[i].nr = unspill_dst.nr;
1085            inst->src[i].offset %= REG_SIZE;
1086
1087            /* We read the largest power-of-two divisor of the register count
1088             * (because only POT scratch read blocks are allowed by the
1089             * hardware) up to the maximum supported block size.
1090             */
1091            const unsigned width =
1092               MIN2(32, 1u << (ffs(MAX2(1, count) * 8) - 1));
1093
1094            /* Set exec_all() on unspill messages under the (rather
1095             * pessimistic) assumption that there is no one-to-one
1096             * correspondence between channels of the spilled variable in
1097             * scratch space and the scratch read message, which operates on
1098             * 32 bit channels.  It shouldn't hurt in any case because the
1099             * unspill destination is a block-local temporary.
1100             */
1101            emit_unspill(ibld.exec_all().group(width, 0), unspill_dst,
1102                         subset_spill_offset, count);
1103	 }
1104      }
1105
1106      if (inst->dst.file == VGRF &&
1107          inst->dst.nr == spill_reg &&
1108          inst->opcode != SHADER_OPCODE_UNDEF) {
1109         int subset_spill_offset = spill_offset +
1110            ROUND_DOWN_TO(inst->dst.offset, REG_SIZE);
1111         fs_reg spill_src = alloc_spill_reg(regs_written(inst), ip);
1112
1113         inst->dst.nr = spill_src.nr;
1114         inst->dst.offset %= REG_SIZE;
1115
1116         /* If we're immediately spilling the register, we should not use
1117          * destination dependency hints.  Doing so will cause the GPU do
1118          * try to read and write the register at the same time and may
1119          * hang the GPU.
1120          */
1121         inst->no_dd_clear = false;
1122         inst->no_dd_check = false;
1123
1124         /* Calculate the execution width of the scratch messages (which work
1125          * in terms of 32 bit components so we have a fixed number of eight
1126          * channels per spilled register).  We attempt to write one
1127          * exec_size-wide component of the variable at a time without
1128          * exceeding the maximum number of (fake) MRF registers reserved for
1129          * spills.
1130          */
1131         const unsigned width = 8 * MIN2(
1132            DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE),
1133            spill_max_size(fs));
1134
1135         /* Spills should only write data initialized by the instruction for
1136          * whichever channels are enabled in the excution mask.  If that's
1137          * not possible we'll have to emit a matching unspill before the
1138          * instruction and set force_writemask_all on the spill.
1139          */
1140         const bool per_channel =
1141            inst->dst.is_contiguous() && type_sz(inst->dst.type) == 4 &&
1142            inst->exec_size == width;
1143
1144         /* Builder used to emit the scratch messages. */
1145         const fs_builder ubld = ibld.exec_all(!per_channel).group(width, 0);
1146
1147	 /* If our write is going to affect just part of the
1148          * regs_written(inst), then we need to unspill the destination since
1149          * we write back out all of the regs_written().  If the original
1150          * instruction had force_writemask_all set and is not a partial
1151          * write, there should be no need for the unspill since the
1152          * instruction will be overwriting the whole destination in any case.
1153	  */
1154         if (inst->is_partial_write() ||
1155             (!inst->force_writemask_all && !per_channel))
1156            emit_unspill(ubld, spill_src, subset_spill_offset,
1157                         regs_written(inst));
1158
1159         emit_spill(ubld.at(block, inst->next), spill_src,
1160                    subset_spill_offset, regs_written(inst));
1161      }
1162
1163      for (fs_inst *inst = (fs_inst *)before->next;
1164           inst != after; inst = (fs_inst *)inst->next)
1165         setup_inst_interference(inst);
1166
1167      /* We don't advance the ip for scratch read/write instructions
1168       * because we consider them to have the same ip as instruction we're
1169       * spilling around for the purposes of interference.  Also, we're
1170       * inserting spill instructions without re-running liveness analysis
1171       * and we don't want to mess up our IPs.
1172       */
1173      if (!_mesa_set_search(spill_insts, inst))
1174         ip++;
1175   }
1176
1177   assert(ip == live_instr_count);
1178}
1179
1180bool
1181fs_reg_alloc::assign_regs(bool allow_spilling, bool spill_all)
1182{
1183   build_interference_graph(fs->spilled_any_registers || spill_all);
1184
1185   bool spilled = false;
1186   while (1) {
1187      /* Debug of register spilling: Go spill everything. */
1188      if (unlikely(spill_all)) {
1189         int reg = choose_spill_reg();
1190         if (reg != -1) {
1191            spill_reg(reg);
1192            continue;
1193         }
1194      }
1195
1196      if (ra_allocate(g))
1197         break;
1198
1199      if (!allow_spilling)
1200         return false;
1201
1202      /* Failed to allocate registers.  Spill a reg, and the caller will
1203       * loop back into here to try again.
1204       */
1205      int reg = choose_spill_reg();
1206      if (reg == -1)
1207         return false;
1208
1209      /* If we're going to spill but we've never spilled before, we need to
1210       * re-build the interference graph with MRFs enabled to allow spilling.
1211       */
1212      if (!fs->spilled_any_registers) {
1213         discard_interference_graph();
1214         build_interference_graph(true);
1215      }
1216
1217      spilled = true;
1218
1219      spill_reg(reg);
1220   }
1221
1222   if (spilled)
1223      fs->invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
1224
1225   /* Get the chosen virtual registers for each node, and map virtual
1226    * regs in the register classes back down to real hardware reg
1227    * numbers.
1228    */
1229   unsigned hw_reg_mapping[fs->alloc.count];
1230   fs->grf_used = fs->first_non_payload_grf;
1231   for (unsigned i = 0; i < fs->alloc.count; i++) {
1232      int reg = ra_get_node_reg(g, first_vgrf_node + i);
1233
1234      hw_reg_mapping[i] = reg;
1235      fs->grf_used = MAX2(fs->grf_used,
1236			  hw_reg_mapping[i] + fs->alloc.sizes[i]);
1237   }
1238
1239   foreach_block_and_inst(block, fs_inst, inst, fs->cfg) {
1240      assign_reg(hw_reg_mapping, &inst->dst);
1241      for (int i = 0; i < inst->sources; i++) {
1242         assign_reg(hw_reg_mapping, &inst->src[i]);
1243      }
1244   }
1245
1246   fs->alloc.count = fs->grf_used;
1247
1248   return true;
1249}
1250
1251bool
1252fs_visitor::assign_regs(bool allow_spilling, bool spill_all)
1253{
1254   fs_reg_alloc alloc(this);
1255   bool success = alloc.assign_regs(allow_spilling, spill_all);
1256   if (!success && allow_spilling) {
1257      fail("no register to spill:\n");
1258      dump_instructions(NULL);
1259   }
1260   return success;
1261}
1262