program: Remove variable used only in assert().
[mesa.git] / src / mesa / program / prog_optimize.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2009 VMware, Inc. All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * VMWARE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
20 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24
25
26 #include "main/glheader.h"
27 #include "main/context.h"
28 #include "main/macros.h"
29 #include "program.h"
30 #include "prog_instruction.h"
31 #include "prog_optimize.h"
32 #include "prog_print.h"
33
34
35 #define MAX_LOOP_NESTING 50
36 /* MAX_PROGRAM_TEMPS is a low number (256), and we want to be able to
37 * register allocate many temporary values into that small number of
38 * temps. So allow large temporary indices coming into the register
39 * allocator.
40 */
41 #define REG_ALLOCATE_MAX_PROGRAM_TEMPS ((1 << INST_INDEX_BITS) - 1)
42
43 static GLboolean dbg = GL_FALSE;
44
45 #define NO_MASK 0xf
46
47 /**
48 * Returns the mask of channels (bitmask of WRITEMASK_X,Y,Z,W) which
49 * are read from the given src in this instruction, We also provide
50 * one optional masks which may mask other components in the dst
51 * register
52 */
53 static GLuint
54 get_src_arg_mask(const struct prog_instruction *inst,
55 GLuint arg, GLuint dst_mask)
56 {
57 GLuint read_mask, channel_mask;
58 GLuint comp;
59
60 assert(arg < _mesa_num_inst_src_regs(inst->Opcode));
61
62 /* Form the dst register, find the written channels */
63 switch (inst->Opcode) {
64 case OPCODE_MOV:
65 case OPCODE_MIN:
66 case OPCODE_MAX:
67 case OPCODE_ABS:
68 case OPCODE_ADD:
69 case OPCODE_MAD:
70 case OPCODE_MUL:
71 case OPCODE_SUB:
72 case OPCODE_CMP:
73 case OPCODE_FLR:
74 case OPCODE_FRC:
75 case OPCODE_LRP:
76 case OPCODE_SEQ:
77 case OPCODE_SGE:
78 case OPCODE_SGT:
79 case OPCODE_SLE:
80 case OPCODE_SLT:
81 case OPCODE_SNE:
82 case OPCODE_SSG:
83 channel_mask = inst->DstReg.WriteMask & dst_mask;
84 break;
85 case OPCODE_RCP:
86 case OPCODE_SIN:
87 case OPCODE_COS:
88 case OPCODE_RSQ:
89 case OPCODE_POW:
90 case OPCODE_EX2:
91 case OPCODE_LOG:
92 channel_mask = WRITEMASK_X;
93 break;
94 case OPCODE_DP2:
95 channel_mask = WRITEMASK_XY;
96 break;
97 case OPCODE_DP3:
98 case OPCODE_XPD:
99 channel_mask = WRITEMASK_XYZ;
100 break;
101 default:
102 channel_mask = WRITEMASK_XYZW;
103 break;
104 }
105
106 /* Now, given the src swizzle and the written channels, find which
107 * components are actually read
108 */
109 read_mask = 0x0;
110 for (comp = 0; comp < 4; ++comp) {
111 const GLuint coord = GET_SWZ(inst->SrcReg[arg].Swizzle, comp);
112 if (channel_mask & (1 << comp) && coord <= SWIZZLE_W)
113 read_mask |= 1 << coord;
114 }
115
116 return read_mask;
117 }
118
119
120 /**
121 * For a MOV instruction, compute a write mask when src register also has
122 * a mask
123 */
124 static GLuint
125 get_dst_mask_for_mov(const struct prog_instruction *mov, GLuint src_mask)
126 {
127 const GLuint mask = mov->DstReg.WriteMask;
128 GLuint comp;
129 GLuint updated_mask = 0x0;
130
131 assert(mov->Opcode == OPCODE_MOV);
132
133 for (comp = 0; comp < 4; ++comp) {
134 GLuint src_comp;
135 if ((mask & (1 << comp)) == 0)
136 continue;
137 src_comp = GET_SWZ(mov->SrcReg[0].Swizzle, comp);
138 if ((src_mask & (1 << src_comp)) == 0)
139 continue;
140 updated_mask |= 1 << comp;
141 }
142
143 return updated_mask;
144 }
145
146
147 /**
148 * Ensure that the swizzle is regular. That is, all of the swizzle
149 * terms are SWIZZLE_X,Y,Z,W and not SWIZZLE_ZERO or SWIZZLE_ONE.
150 */
151 static GLboolean
152 is_swizzle_regular(GLuint swz)
153 {
154 return GET_SWZ(swz,0) <= SWIZZLE_W &&
155 GET_SWZ(swz,1) <= SWIZZLE_W &&
156 GET_SWZ(swz,2) <= SWIZZLE_W &&
157 GET_SWZ(swz,3) <= SWIZZLE_W;
158 }
159
160
161 /**
162 * In 'prog' remove instruction[i] if removeFlags[i] == TRUE.
163 * \return number of instructions removed
164 */
165 static GLuint
166 remove_instructions(struct gl_program *prog, const GLboolean *removeFlags)
167 {
168 GLint i, removeEnd = 0, removeCount = 0;
169 GLuint totalRemoved = 0;
170
171 /* go backward */
172 for (i = prog->NumInstructions - 1; i >= 0; i--) {
173 if (removeFlags[i]) {
174 totalRemoved++;
175 if (removeCount == 0) {
176 /* begin a run of instructions to remove */
177 removeEnd = i;
178 removeCount = 1;
179 }
180 else {
181 /* extend the run of instructions to remove */
182 removeCount++;
183 }
184 }
185 else {
186 /* don't remove this instruction, but check if the preceeding
187 * instructions are to be removed.
188 */
189 if (removeCount > 0) {
190 GLint removeStart = removeEnd - removeCount + 1;
191 _mesa_delete_instructions(prog, removeStart, removeCount);
192 removeStart = removeCount = 0; /* reset removal info */
193 }
194 }
195 }
196 /* Finish removing if the first instruction was to be removed. */
197 if (removeCount > 0) {
198 GLint removeStart = removeEnd - removeCount + 1;
199 _mesa_delete_instructions(prog, removeStart, removeCount);
200 }
201 return totalRemoved;
202 }
203
204
205 /**
206 * Remap register indexes according to map.
207 * \param prog the program to search/replace
208 * \param file the type of register file to search/replace
209 * \param map maps old register indexes to new indexes
210 */
211 static void
212 replace_regs(struct gl_program *prog, gl_register_file file, const GLint map[])
213 {
214 GLuint i;
215
216 for (i = 0; i < prog->NumInstructions; i++) {
217 struct prog_instruction *inst = prog->Instructions + i;
218 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
219 GLuint j;
220 for (j = 0; j < numSrc; j++) {
221 if (inst->SrcReg[j].File == file) {
222 GLuint index = inst->SrcReg[j].Index;
223 assert(map[index] >= 0);
224 inst->SrcReg[j].Index = map[index];
225 }
226 }
227 if (inst->DstReg.File == file) {
228 const GLuint index = inst->DstReg.Index;
229 assert(map[index] >= 0);
230 inst->DstReg.Index = map[index];
231 }
232 }
233 }
234
235
236 /**
237 * Remove dead instructions from the given program.
238 * This is very primitive for now. Basically look for temp registers
239 * that are written to but never read. Remove any instructions that
240 * write to such registers. Be careful with condition code setters.
241 */
242 static GLboolean
243 _mesa_remove_dead_code_global(struct gl_program *prog)
244 {
245 GLboolean tempRead[REG_ALLOCATE_MAX_PROGRAM_TEMPS][4];
246 GLboolean *removeInst; /* per-instruction removal flag */
247 GLuint i, rem = 0, comp;
248
249 memset(tempRead, 0, sizeof(tempRead));
250
251 if (dbg) {
252 printf("Optimize: Begin dead code removal\n");
253 /*_mesa_print_program(prog);*/
254 }
255
256 removeInst =
257 calloc(prog->NumInstructions, sizeof(GLboolean));
258
259 /* Determine which temps are read and written */
260 for (i = 0; i < prog->NumInstructions; i++) {
261 const struct prog_instruction *inst = prog->Instructions + i;
262 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
263 GLuint j;
264
265 /* check src regs */
266 for (j = 0; j < numSrc; j++) {
267 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
268 const GLuint index = inst->SrcReg[j].Index;
269 GLuint read_mask;
270 assert(index < REG_ALLOCATE_MAX_PROGRAM_TEMPS);
271 read_mask = get_src_arg_mask(inst, j, NO_MASK);
272
273 if (inst->SrcReg[j].RelAddr) {
274 if (dbg)
275 printf("abort remove dead code (indirect temp)\n");
276 goto done;
277 }
278
279 for (comp = 0; comp < 4; comp++) {
280 const GLuint swz = GET_SWZ(inst->SrcReg[j].Swizzle, comp);
281 if (swz <= SWIZZLE_W) {
282 if ((read_mask & (1 << swz)) == 0)
283 continue;
284 tempRead[index][swz] = GL_TRUE;
285 }
286 }
287 }
288 }
289
290 /* check dst reg */
291 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
292 assert(inst->DstReg.Index < REG_ALLOCATE_MAX_PROGRAM_TEMPS);
293
294 if (inst->DstReg.RelAddr) {
295 if (dbg)
296 printf("abort remove dead code (indirect temp)\n");
297 goto done;
298 }
299 }
300 }
301
302 /* find instructions that write to dead registers, flag for removal */
303 for (i = 0; i < prog->NumInstructions; i++) {
304 struct prog_instruction *inst = prog->Instructions + i;
305 const GLuint numDst = _mesa_num_inst_dst_regs(inst->Opcode);
306
307 if (numDst != 0 && inst->DstReg.File == PROGRAM_TEMPORARY) {
308 GLint chan, index = inst->DstReg.Index;
309
310 for (chan = 0; chan < 4; chan++) {
311 if (!tempRead[index][chan] &&
312 inst->DstReg.WriteMask & (1 << chan)) {
313 if (dbg) {
314 printf("Remove writemask on %u.%c\n", i,
315 chan == 3 ? 'w' : 'x' + chan);
316 }
317 inst->DstReg.WriteMask &= ~(1 << chan);
318 rem++;
319 }
320 }
321
322 if (inst->DstReg.WriteMask == 0) {
323 /* If we cleared all writes, the instruction can be removed. */
324 if (dbg)
325 printf("Remove instruction %u: \n", i);
326 removeInst[i] = GL_TRUE;
327 }
328 }
329 }
330
331 /* now remove the instructions which aren't needed */
332 rem = remove_instructions(prog, removeInst);
333
334 if (dbg) {
335 printf("Optimize: End dead code removal.\n");
336 printf(" %u channel writes removed\n", rem);
337 printf(" %u instructions removed\n", rem);
338 /*_mesa_print_program(prog);*/
339 }
340
341 done:
342 free(removeInst);
343 return rem != 0;
344 }
345
346
347 enum inst_use
348 {
349 READ,
350 WRITE,
351 FLOW,
352 END
353 };
354
355
356 /**
357 * Scan forward in program from 'start' for the next occurances of TEMP[index].
358 * We look if an instruction reads the component given by the masks and if they
359 * are overwritten.
360 * Return READ, WRITE, FLOW or END to indicate the next usage or an indicator
361 * that we can't look further.
362 */
363 static enum inst_use
364 find_next_use(const struct gl_program *prog,
365 GLuint start,
366 GLuint index,
367 GLuint mask)
368 {
369 GLuint i;
370
371 for (i = start; i < prog->NumInstructions; i++) {
372 const struct prog_instruction *inst = prog->Instructions + i;
373 switch (inst->Opcode) {
374 case OPCODE_BGNLOOP:
375 case OPCODE_BGNSUB:
376 case OPCODE_CAL:
377 case OPCODE_CONT:
378 case OPCODE_IF:
379 case OPCODE_ELSE:
380 case OPCODE_ENDIF:
381 case OPCODE_ENDLOOP:
382 case OPCODE_ENDSUB:
383 case OPCODE_RET:
384 return FLOW;
385 case OPCODE_END:
386 return END;
387 default:
388 {
389 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
390 GLuint j;
391 for (j = 0; j < numSrc; j++) {
392 if (inst->SrcReg[j].RelAddr ||
393 (inst->SrcReg[j].File == PROGRAM_TEMPORARY &&
394 inst->SrcReg[j].Index == (GLint)index &&
395 (get_src_arg_mask(inst,j,NO_MASK) & mask)))
396 return READ;
397 }
398 if (_mesa_num_inst_dst_regs(inst->Opcode) == 1 &&
399 inst->DstReg.File == PROGRAM_TEMPORARY &&
400 inst->DstReg.Index == index) {
401 mask &= ~inst->DstReg.WriteMask;
402 if (mask == 0)
403 return WRITE;
404 }
405 }
406 }
407 }
408 return END;
409 }
410
411
412 /**
413 * Is the given instruction opcode a flow-control opcode?
414 * XXX maybe move this into prog_instruction.[ch]
415 */
416 static GLboolean
417 _mesa_is_flow_control_opcode(enum prog_opcode opcode)
418 {
419 switch (opcode) {
420 case OPCODE_BGNLOOP:
421 case OPCODE_BGNSUB:
422 case OPCODE_CAL:
423 case OPCODE_CONT:
424 case OPCODE_IF:
425 case OPCODE_ELSE:
426 case OPCODE_END:
427 case OPCODE_ENDIF:
428 case OPCODE_ENDLOOP:
429 case OPCODE_ENDSUB:
430 case OPCODE_RET:
431 return GL_TRUE;
432 default:
433 return GL_FALSE;
434 }
435 }
436
437
438 /**
439 * Test if the given instruction is a simple MOV (no conditional updating,
440 * not relative addressing, no negation/abs, etc).
441 */
442 static GLboolean
443 can_downward_mov_be_modifed(const struct prog_instruction *mov)
444 {
445 return
446 mov->Opcode == OPCODE_MOV &&
447 mov->SrcReg[0].RelAddr == 0 &&
448 mov->SrcReg[0].Negate == 0 &&
449 mov->DstReg.RelAddr == 0;
450 }
451
452
453 static GLboolean
454 can_upward_mov_be_modifed(const struct prog_instruction *mov)
455 {
456 return
457 can_downward_mov_be_modifed(mov) &&
458 mov->DstReg.File == PROGRAM_TEMPORARY &&
459 !mov->Saturate;
460 }
461
462
463 /**
464 * Try to remove use of extraneous MOV instructions, to free them up for dead
465 * code removal.
466 */
467 static void
468 _mesa_remove_extra_move_use(struct gl_program *prog)
469 {
470 GLuint i, j;
471
472 if (dbg) {
473 printf("Optimize: Begin remove extra move use\n");
474 _mesa_print_program(prog);
475 }
476
477 /*
478 * Look for sequences such as this:
479 * MOV tmpX, arg0;
480 * ...
481 * FOO tmpY, tmpX, arg1;
482 * and convert into:
483 * MOV tmpX, arg0;
484 * ...
485 * FOO tmpY, arg0, arg1;
486 */
487
488 for (i = 0; i + 1 < prog->NumInstructions; i++) {
489 const struct prog_instruction *mov = prog->Instructions + i;
490 GLuint dst_mask, src_mask;
491 if (can_upward_mov_be_modifed(mov) == GL_FALSE)
492 continue;
493
494 /* Scanning the code, we maintain the components which are still active in
495 * these two masks
496 */
497 dst_mask = mov->DstReg.WriteMask;
498 src_mask = get_src_arg_mask(mov, 0, NO_MASK);
499
500 /* Walk through remaining instructions until the or src reg gets
501 * rewritten or we get into some flow-control, eliminating the use of
502 * this MOV.
503 */
504 for (j = i + 1; j < prog->NumInstructions; j++) {
505 struct prog_instruction *inst2 = prog->Instructions + j;
506 GLuint arg;
507
508 if (_mesa_is_flow_control_opcode(inst2->Opcode))
509 break;
510
511 /* First rewrite this instruction's args if appropriate. */
512 for (arg = 0; arg < _mesa_num_inst_src_regs(inst2->Opcode); arg++) {
513 GLuint comp, read_mask;
514
515 if (inst2->SrcReg[arg].File != mov->DstReg.File ||
516 inst2->SrcReg[arg].Index != mov->DstReg.Index ||
517 inst2->SrcReg[arg].RelAddr)
518 continue;
519 read_mask = get_src_arg_mask(inst2, arg, NO_MASK);
520
521 /* Adjust the swizzles of inst2 to point at MOV's source if ALL the
522 * components read still come from the mov instructions
523 */
524 if (is_swizzle_regular(inst2->SrcReg[arg].Swizzle) &&
525 (read_mask & dst_mask) == read_mask) {
526 for (comp = 0; comp < 4; comp++) {
527 const GLuint inst2_swz =
528 GET_SWZ(inst2->SrcReg[arg].Swizzle, comp);
529 const GLuint s = GET_SWZ(mov->SrcReg[0].Swizzle, inst2_swz);
530 inst2->SrcReg[arg].Swizzle &= ~(7 << (3 * comp));
531 inst2->SrcReg[arg].Swizzle |= s << (3 * comp);
532 inst2->SrcReg[arg].Negate ^= (((mov->SrcReg[0].Negate >>
533 inst2_swz) & 0x1) << comp);
534 }
535 inst2->SrcReg[arg].File = mov->SrcReg[0].File;
536 inst2->SrcReg[arg].Index = mov->SrcReg[0].Index;
537 }
538 }
539
540 /* The source of MOV is written. This potentially deactivates some
541 * components from the src and dst of the MOV instruction
542 */
543 if (inst2->DstReg.File == mov->DstReg.File &&
544 (inst2->DstReg.RelAddr ||
545 inst2->DstReg.Index == mov->DstReg.Index)) {
546 dst_mask &= ~inst2->DstReg.WriteMask;
547 src_mask = get_src_arg_mask(mov, 0, dst_mask);
548 }
549
550 /* Idem when the destination of mov is written */
551 if (inst2->DstReg.File == mov->SrcReg[0].File &&
552 (inst2->DstReg.RelAddr ||
553 inst2->DstReg.Index == mov->SrcReg[0].Index)) {
554 src_mask &= ~inst2->DstReg.WriteMask;
555 dst_mask &= get_dst_mask_for_mov(mov, src_mask);
556 }
557 if (dst_mask == 0)
558 break;
559 }
560 }
561
562 if (dbg) {
563 printf("Optimize: End remove extra move use.\n");
564 /*_mesa_print_program(prog);*/
565 }
566 }
567
568
569 /**
570 * Complements dead_code_global. Try to remove code in block of code by
571 * carefully monitoring the swizzles. Both functions should be merged into one
572 * with a proper control flow graph
573 */
574 static GLboolean
575 _mesa_remove_dead_code_local(struct gl_program *prog)
576 {
577 GLboolean *removeInst;
578 GLuint i, arg, rem = 0;
579
580 removeInst =
581 calloc(prog->NumInstructions, sizeof(GLboolean));
582
583 for (i = 0; i < prog->NumInstructions; i++) {
584 const struct prog_instruction *inst = prog->Instructions + i;
585 const GLuint index = inst->DstReg.Index;
586 const GLuint mask = inst->DstReg.WriteMask;
587 enum inst_use use;
588
589 /* We must deactivate the pass as soon as some indirection is used */
590 if (inst->DstReg.RelAddr)
591 goto done;
592 for (arg = 0; arg < _mesa_num_inst_src_regs(inst->Opcode); arg++)
593 if (inst->SrcReg[arg].RelAddr)
594 goto done;
595
596 if (_mesa_is_flow_control_opcode(inst->Opcode) ||
597 _mesa_num_inst_dst_regs(inst->Opcode) == 0 ||
598 inst->DstReg.File != PROGRAM_TEMPORARY ||
599 inst->DstReg.RelAddr)
600 continue;
601
602 use = find_next_use(prog, i+1, index, mask);
603 if (use == WRITE || use == END)
604 removeInst[i] = GL_TRUE;
605 }
606
607 rem = remove_instructions(prog, removeInst);
608
609 done:
610 free(removeInst);
611 return rem != 0;
612 }
613
614
615 /**
616 * Try to inject the destination of mov as the destination of inst and recompute
617 * the swizzles operators for the sources of inst if required. Return GL_TRUE
618 * of the substitution was possible, GL_FALSE otherwise
619 */
620 static GLboolean
621 _mesa_merge_mov_into_inst(struct prog_instruction *inst,
622 const struct prog_instruction *mov)
623 {
624 /* Indirection table which associates destination and source components for
625 * the mov instruction
626 */
627 const GLuint mask = get_src_arg_mask(mov, 0, NO_MASK);
628
629 /* Some components are not written by inst. We cannot remove the mov */
630 if (mask != (inst->DstReg.WriteMask & mask))
631 return GL_FALSE;
632
633 inst->Saturate |= mov->Saturate;
634
635 /* Depending on the instruction, we may need to recompute the swizzles.
636 * Also, some other instructions (like TEX) are not linear. We will only
637 * consider completely active sources and destinations
638 */
639 switch (inst->Opcode) {
640
641 /* Carstesian instructions: we compute the swizzle */
642 case OPCODE_MOV:
643 case OPCODE_MIN:
644 case OPCODE_MAX:
645 case OPCODE_ABS:
646 case OPCODE_ADD:
647 case OPCODE_MAD:
648 case OPCODE_MUL:
649 case OPCODE_SUB:
650 {
651 GLuint dst_to_src_comp[4] = {0,0,0,0};
652 GLuint dst_comp, arg;
653 for (dst_comp = 0; dst_comp < 4; ++dst_comp) {
654 if (mov->DstReg.WriteMask & (1 << dst_comp)) {
655 const GLuint src_comp = GET_SWZ(mov->SrcReg[0].Swizzle, dst_comp);
656 assert(src_comp < 4);
657 dst_to_src_comp[dst_comp] = src_comp;
658 }
659 }
660
661 /* Patch each source of the instruction */
662 for (arg = 0; arg < _mesa_num_inst_src_regs(inst->Opcode); arg++) {
663 const GLuint arg_swz = inst->SrcReg[arg].Swizzle;
664 inst->SrcReg[arg].Swizzle = 0;
665
666 /* Reset each active component of the swizzle */
667 for (dst_comp = 0; dst_comp < 4; ++dst_comp) {
668 GLuint src_comp, arg_comp;
669 if ((mov->DstReg.WriteMask & (1 << dst_comp)) == 0)
670 continue;
671 src_comp = dst_to_src_comp[dst_comp];
672 assert(src_comp < 4);
673 arg_comp = GET_SWZ(arg_swz, src_comp);
674 assert(arg_comp < 4);
675 inst->SrcReg[arg].Swizzle |= arg_comp << (3*dst_comp);
676 }
677 }
678 inst->DstReg = mov->DstReg;
679 return GL_TRUE;
680 }
681
682 /* Dot products and scalar instructions: we only change the destination */
683 case OPCODE_RCP:
684 case OPCODE_SIN:
685 case OPCODE_COS:
686 case OPCODE_RSQ:
687 case OPCODE_POW:
688 case OPCODE_EX2:
689 case OPCODE_LOG:
690 case OPCODE_DP2:
691 case OPCODE_DP3:
692 case OPCODE_DP4:
693 inst->DstReg = mov->DstReg;
694 return GL_TRUE;
695
696 /* All other instructions require fully active components with no swizzle */
697 default:
698 if (mov->SrcReg[0].Swizzle != SWIZZLE_XYZW ||
699 inst->DstReg.WriteMask != WRITEMASK_XYZW)
700 return GL_FALSE;
701 inst->DstReg = mov->DstReg;
702 return GL_TRUE;
703 }
704 }
705
706
707 /**
708 * Try to remove extraneous MOV instructions from the given program.
709 */
710 static GLboolean
711 _mesa_remove_extra_moves(struct gl_program *prog)
712 {
713 GLboolean *removeInst; /* per-instruction removal flag */
714 GLuint i, rem = 0, nesting = 0;
715
716 if (dbg) {
717 printf("Optimize: Begin remove extra moves\n");
718 _mesa_print_program(prog);
719 }
720
721 removeInst =
722 calloc(prog->NumInstructions, sizeof(GLboolean));
723
724 /*
725 * Look for sequences such as this:
726 * FOO tmpX, arg0, arg1;
727 * MOV tmpY, tmpX;
728 * and convert into:
729 * FOO tmpY, arg0, arg1;
730 */
731
732 for (i = 0; i < prog->NumInstructions; i++) {
733 const struct prog_instruction *mov = prog->Instructions + i;
734
735 switch (mov->Opcode) {
736 case OPCODE_BGNLOOP:
737 case OPCODE_BGNSUB:
738 case OPCODE_IF:
739 nesting++;
740 break;
741 case OPCODE_ENDLOOP:
742 case OPCODE_ENDSUB:
743 case OPCODE_ENDIF:
744 nesting--;
745 break;
746 case OPCODE_MOV:
747 if (i > 0 &&
748 can_downward_mov_be_modifed(mov) &&
749 mov->SrcReg[0].File == PROGRAM_TEMPORARY &&
750 nesting == 0)
751 {
752
753 /* see if this MOV can be removed */
754 const GLuint id = mov->SrcReg[0].Index;
755 struct prog_instruction *prevInst;
756 GLuint prevI;
757
758 /* get pointer to previous instruction */
759 prevI = i - 1;
760 while (prevI > 0 && removeInst[prevI])
761 prevI--;
762 prevInst = prog->Instructions + prevI;
763
764 if (prevInst->DstReg.File == PROGRAM_TEMPORARY &&
765 prevInst->DstReg.Index == id &&
766 prevInst->DstReg.RelAddr == 0) {
767
768 const GLuint dst_mask = prevInst->DstReg.WriteMask;
769 enum inst_use next_use = find_next_use(prog, i+1, id, dst_mask);
770
771 if (next_use == WRITE || next_use == END) {
772 /* OK, we can safely remove this MOV instruction.
773 * Transform:
774 * prevI: FOO tempIndex, x, y;
775 * i: MOV z, tempIndex;
776 * Into:
777 * prevI: FOO z, x, y;
778 */
779 if (_mesa_merge_mov_into_inst(prevInst, mov)) {
780 removeInst[i] = GL_TRUE;
781 if (dbg) {
782 printf("Remove MOV at %u\n", i);
783 printf("new prev inst %u: ", prevI);
784 _mesa_print_instruction(prevInst);
785 }
786 }
787 }
788 }
789 }
790 break;
791 default:
792 ; /* nothing */
793 }
794 }
795
796 /* now remove the instructions which aren't needed */
797 rem = remove_instructions(prog, removeInst);
798
799 free(removeInst);
800
801 if (dbg) {
802 printf("Optimize: End remove extra moves. %u instructions removed\n", rem);
803 /*_mesa_print_program(prog);*/
804 }
805
806 return rem != 0;
807 }
808
809
810 /** A live register interval */
811 struct interval
812 {
813 GLuint Reg; /** The temporary register index */
814 GLuint Start, End; /** Start/end instruction numbers */
815 };
816
817
818 /** A list of register intervals */
819 struct interval_list
820 {
821 GLuint Num;
822 struct interval Intervals[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
823 };
824
825
826 static void
827 append_interval(struct interval_list *list, const struct interval *inv)
828 {
829 list->Intervals[list->Num++] = *inv;
830 }
831
832
833 /** Insert interval inv into list, sorted by interval end */
834 static void
835 insert_interval_by_end(struct interval_list *list, const struct interval *inv)
836 {
837 /* XXX we could do a binary search insertion here since list is sorted */
838 GLint i = list->Num - 1;
839 while (i >= 0 && list->Intervals[i].End > inv->End) {
840 list->Intervals[i + 1] = list->Intervals[i];
841 i--;
842 }
843 list->Intervals[i + 1] = *inv;
844 list->Num++;
845
846 #ifdef DEBUG
847 {
848 GLuint i;
849 for (i = 0; i + 1 < list->Num; i++) {
850 assert(list->Intervals[i].End <= list->Intervals[i + 1].End);
851 }
852 }
853 #endif
854 }
855
856
857 /** Remove the given interval from the interval list */
858 static void
859 remove_interval(struct interval_list *list, const struct interval *inv)
860 {
861 /* XXX we could binary search since list is sorted */
862 GLuint k;
863 for (k = 0; k < list->Num; k++) {
864 if (list->Intervals[k].Reg == inv->Reg) {
865 /* found, remove it */
866 assert(list->Intervals[k].Start == inv->Start);
867 assert(list->Intervals[k].End == inv->End);
868 while (k < list->Num - 1) {
869 list->Intervals[k] = list->Intervals[k + 1];
870 k++;
871 }
872 list->Num--;
873 return;
874 }
875 }
876 }
877
878
879 /** called by qsort() */
880 static int
881 compare_start(const void *a, const void *b)
882 {
883 const struct interval *ia = (const struct interval *) a;
884 const struct interval *ib = (const struct interval *) b;
885 if (ia->Start < ib->Start)
886 return -1;
887 else if (ia->Start > ib->Start)
888 return +1;
889 else
890 return 0;
891 }
892
893
894 /** sort the interval list according to interval starts */
895 static void
896 sort_interval_list_by_start(struct interval_list *list)
897 {
898 qsort(list->Intervals, list->Num, sizeof(struct interval), compare_start);
899 #ifdef DEBUG
900 {
901 GLuint i;
902 for (i = 0; i + 1 < list->Num; i++) {
903 assert(list->Intervals[i].Start <= list->Intervals[i + 1].Start);
904 }
905 }
906 #endif
907 }
908
909 struct loop_info
910 {
911 GLuint Start, End; /**< Start, end instructions of loop */
912 };
913
914 /**
915 * Update the intermediate interval info for register 'index' and
916 * instruction 'ic'.
917 */
918 static void
919 update_interval(GLint intBegin[], GLint intEnd[],
920 struct loop_info *loopStack, GLuint loopStackDepth,
921 GLuint index, GLuint ic)
922 {
923 unsigned i;
924 GLuint begin = ic;
925 GLuint end = ic;
926
927 /* If the register is used in a loop, extend its lifetime through the end
928 * of the outermost loop that doesn't contain its definition.
929 */
930 for (i = 0; i < loopStackDepth; i++) {
931 if (intBegin[index] < loopStack[i].Start) {
932 end = loopStack[i].End;
933 break;
934 }
935 }
936
937 /* Variables that are live at the end of a loop will also be live at the
938 * beginning, so an instruction inside of a loop should have its live
939 * interval begin at the start of the outermost loop.
940 */
941 if (loopStackDepth > 0 && ic > loopStack[0].Start && ic < loopStack[0].End) {
942 begin = loopStack[0].Start;
943 }
944
945 assert(index < REG_ALLOCATE_MAX_PROGRAM_TEMPS);
946 if (intBegin[index] == -1) {
947 assert(intEnd[index] == -1);
948 intBegin[index] = begin;
949 intEnd[index] = end;
950 }
951 else {
952 intEnd[index] = end;
953 }
954 }
955
956
957 /**
958 * Find first/last instruction that references each temporary register.
959 */
960 GLboolean
961 _mesa_find_temp_intervals(const struct prog_instruction *instructions,
962 GLuint numInstructions,
963 GLint intBegin[REG_ALLOCATE_MAX_PROGRAM_TEMPS],
964 GLint intEnd[REG_ALLOCATE_MAX_PROGRAM_TEMPS])
965 {
966 struct loop_info loopStack[MAX_LOOP_NESTING];
967 GLuint loopStackDepth = 0;
968 GLuint i;
969
970 for (i = 0; i < REG_ALLOCATE_MAX_PROGRAM_TEMPS; i++){
971 intBegin[i] = intEnd[i] = -1;
972 }
973
974 /* Scan instructions looking for temporary registers */
975 for (i = 0; i < numInstructions; i++) {
976 const struct prog_instruction *inst = instructions + i;
977 if (inst->Opcode == OPCODE_BGNLOOP) {
978 loopStack[loopStackDepth].Start = i;
979 loopStack[loopStackDepth].End = inst->BranchTarget;
980 loopStackDepth++;
981 }
982 else if (inst->Opcode == OPCODE_ENDLOOP) {
983 loopStackDepth--;
984 }
985 else if (inst->Opcode == OPCODE_CAL) {
986 return GL_FALSE;
987 }
988 else {
989 const GLuint numSrc = 3;/*_mesa_num_inst_src_regs(inst->Opcode);*/
990 GLuint j;
991 for (j = 0; j < numSrc; j++) {
992 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
993 const GLuint index = inst->SrcReg[j].Index;
994 if (inst->SrcReg[j].RelAddr)
995 return GL_FALSE;
996 update_interval(intBegin, intEnd, loopStack, loopStackDepth,
997 index, i);
998 }
999 }
1000 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
1001 const GLuint index = inst->DstReg.Index;
1002 if (inst->DstReg.RelAddr)
1003 return GL_FALSE;
1004 update_interval(intBegin, intEnd, loopStack, loopStackDepth,
1005 index, i);
1006 }
1007 }
1008 }
1009
1010 return GL_TRUE;
1011 }
1012
1013
1014 /**
1015 * Find the live intervals for each temporary register in the program.
1016 * For register R, the interval [A,B] indicates that R is referenced
1017 * from instruction A through instruction B.
1018 * Special consideration is needed for loops and subroutines.
1019 * \return GL_TRUE if success, GL_FALSE if we cannot proceed for some reason
1020 */
1021 static GLboolean
1022 find_live_intervals(struct gl_program *prog,
1023 struct interval_list *liveIntervals)
1024 {
1025 GLint intBegin[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1026 GLint intEnd[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1027 GLuint i;
1028
1029 /*
1030 * Note: we'll return GL_FALSE below if we find relative indexing
1031 * into the TEMP register file. We can't handle that yet.
1032 * We also give up on subroutines for now.
1033 */
1034
1035 if (dbg) {
1036 printf("Optimize: Begin find intervals\n");
1037 }
1038
1039 /* build intermediate arrays */
1040 if (!_mesa_find_temp_intervals(prog->Instructions, prog->NumInstructions,
1041 intBegin, intEnd))
1042 return GL_FALSE;
1043
1044 /* Build live intervals list from intermediate arrays */
1045 liveIntervals->Num = 0;
1046 for (i = 0; i < REG_ALLOCATE_MAX_PROGRAM_TEMPS; i++) {
1047 if (intBegin[i] >= 0) {
1048 struct interval inv;
1049 inv.Reg = i;
1050 inv.Start = intBegin[i];
1051 inv.End = intEnd[i];
1052 append_interval(liveIntervals, &inv);
1053 }
1054 }
1055
1056 /* Sort the list according to interval starts */
1057 sort_interval_list_by_start(liveIntervals);
1058
1059 if (dbg) {
1060 /* print interval info */
1061 for (i = 0; i < liveIntervals->Num; i++) {
1062 const struct interval *inv = liveIntervals->Intervals + i;
1063 printf("Reg[%d] live [%d, %d]:",
1064 inv->Reg, inv->Start, inv->End);
1065 if (1) {
1066 GLuint j;
1067 for (j = 0; j < inv->Start; j++)
1068 printf(" ");
1069 for (j = inv->Start; j <= inv->End; j++)
1070 printf("x");
1071 }
1072 printf("\n");
1073 }
1074 }
1075
1076 return GL_TRUE;
1077 }
1078
1079
1080 /** Scan the array of used register flags to find free entry */
1081 static GLint
1082 alloc_register(GLboolean usedRegs[REG_ALLOCATE_MAX_PROGRAM_TEMPS])
1083 {
1084 GLuint k;
1085 for (k = 0; k < REG_ALLOCATE_MAX_PROGRAM_TEMPS; k++) {
1086 if (!usedRegs[k]) {
1087 usedRegs[k] = GL_TRUE;
1088 return k;
1089 }
1090 }
1091 return -1;
1092 }
1093
1094
1095 /**
1096 * This function implements "Linear Scan Register Allocation" to reduce
1097 * the number of temporary registers used by the program.
1098 *
1099 * We compute the "live interval" for all temporary registers then
1100 * examine the overlap of the intervals to allocate new registers.
1101 * Basically, if two intervals do not overlap, they can use the same register.
1102 */
1103 static void
1104 _mesa_reallocate_registers(struct gl_program *prog)
1105 {
1106 struct interval_list liveIntervals;
1107 GLint registerMap[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1108 GLboolean usedRegs[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1109 GLuint i;
1110 GLint maxTemp = -1;
1111
1112 if (dbg) {
1113 printf("Optimize: Begin live-interval register reallocation\n");
1114 _mesa_print_program(prog);
1115 }
1116
1117 for (i = 0; i < REG_ALLOCATE_MAX_PROGRAM_TEMPS; i++){
1118 registerMap[i] = -1;
1119 usedRegs[i] = GL_FALSE;
1120 }
1121
1122 if (!find_live_intervals(prog, &liveIntervals)) {
1123 if (dbg)
1124 printf("Aborting register reallocation\n");
1125 return;
1126 }
1127
1128 {
1129 struct interval_list activeIntervals;
1130 activeIntervals.Num = 0;
1131
1132 /* loop over live intervals, allocating a new register for each */
1133 for (i = 0; i < liveIntervals.Num; i++) {
1134 const struct interval *live = liveIntervals.Intervals + i;
1135
1136 if (dbg)
1137 printf("Consider register %u\n", live->Reg);
1138
1139 /* Expire old intervals. Intervals which have ended with respect
1140 * to the live interval can have their remapped registers freed.
1141 */
1142 {
1143 GLint j;
1144 for (j = 0; j < (GLint) activeIntervals.Num; j++) {
1145 const struct interval *inv = activeIntervals.Intervals + j;
1146 if (inv->End >= live->Start) {
1147 /* Stop now. Since the activeInterval list is sorted
1148 * we know we don't have to go further.
1149 */
1150 break;
1151 }
1152 else {
1153 /* Interval 'inv' has expired */
1154 const GLint regNew = registerMap[inv->Reg];
1155 assert(regNew >= 0);
1156
1157 if (dbg)
1158 printf(" expire interval for reg %u\n", inv->Reg);
1159
1160 /* remove interval j from active list */
1161 remove_interval(&activeIntervals, inv);
1162 j--; /* counter-act j++ in for-loop above */
1163
1164 /* return register regNew to the free pool */
1165 if (dbg)
1166 printf(" free reg %d\n", regNew);
1167 assert(usedRegs[regNew] == GL_TRUE);
1168 usedRegs[regNew] = GL_FALSE;
1169 }
1170 }
1171 }
1172
1173 /* find a free register for this live interval */
1174 {
1175 const GLint k = alloc_register(usedRegs);
1176 if (k < 0) {
1177 /* out of registers, give up */
1178 return;
1179 }
1180 registerMap[live->Reg] = k;
1181 maxTemp = MAX2(maxTemp, k);
1182 if (dbg)
1183 printf(" remap register %u -> %d\n", live->Reg, k);
1184 }
1185
1186 /* Insert this live interval into the active list which is sorted
1187 * by increasing end points.
1188 */
1189 insert_interval_by_end(&activeIntervals, live);
1190 }
1191 }
1192
1193 if (maxTemp + 1 < (GLint) liveIntervals.Num) {
1194 /* OK, we've reduced the number of registers needed.
1195 * Scan the program and replace all the old temporary register
1196 * indexes with the new indexes.
1197 */
1198 replace_regs(prog, PROGRAM_TEMPORARY, registerMap);
1199
1200 prog->NumTemporaries = maxTemp + 1;
1201 }
1202
1203 if (dbg) {
1204 printf("Optimize: End live-interval register reallocation\n");
1205 printf("Num temp regs before: %u after: %u\n",
1206 liveIntervals.Num, maxTemp + 1);
1207 _mesa_print_program(prog);
1208 }
1209 }
1210
1211
1212 #if 0
1213 static void
1214 print_it(struct gl_context *ctx, struct gl_program *program, const char *txt) {
1215 fprintf(stderr, "%s (%u inst):\n", txt, program->NumInstructions);
1216 _mesa_print_program(program);
1217 _mesa_print_program_parameters(ctx, program);
1218 fprintf(stderr, "\n\n");
1219 }
1220 #endif
1221
1222 /**
1223 * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
1224 * instruction is the first instruction to write to register T0. The are
1225 * several lowering passes done in GLSL IR (e.g. branches and
1226 * relative addressing) that create a large number of conditional assignments
1227 * that ir_to_mesa converts to CMP instructions like the one mentioned above.
1228 *
1229 * Here is why this conversion is safe:
1230 * CMP T0, T1 T2 T0 can be expanded to:
1231 * if (T1 < 0.0)
1232 * MOV T0, T2;
1233 * else
1234 * MOV T0, T0;
1235 *
1236 * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
1237 * as the original program. If (T1 < 0.0) evaluates to false, executing
1238 * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
1239 * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
1240 * because any instruction that was going to read from T0 after this was going
1241 * to read a garbage value anyway.
1242 */
1243 static void
1244 _mesa_simplify_cmp(struct gl_program * program)
1245 {
1246 GLuint tempWrites[REG_ALLOCATE_MAX_PROGRAM_TEMPS];
1247 GLuint outputWrites[MAX_PROGRAM_OUTPUTS];
1248 GLuint i;
1249
1250 if (dbg) {
1251 printf("Optimize: Begin reads without writes\n");
1252 _mesa_print_program(program);
1253 }
1254
1255 for (i = 0; i < REG_ALLOCATE_MAX_PROGRAM_TEMPS; i++) {
1256 tempWrites[i] = 0;
1257 }
1258
1259 for (i = 0; i < MAX_PROGRAM_OUTPUTS; i++) {
1260 outputWrites[i] = 0;
1261 }
1262
1263 for (i = 0; i < program->NumInstructions; i++) {
1264 struct prog_instruction *inst = program->Instructions + i;
1265 GLuint prevWriteMask;
1266
1267 /* Give up if we encounter relative addressing or flow control. */
1268 if (_mesa_is_flow_control_opcode(inst->Opcode) || inst->DstReg.RelAddr) {
1269 return;
1270 }
1271
1272 if (inst->DstReg.File == PROGRAM_OUTPUT) {
1273 assert(inst->DstReg.Index < MAX_PROGRAM_OUTPUTS);
1274 prevWriteMask = outputWrites[inst->DstReg.Index];
1275 outputWrites[inst->DstReg.Index] |= inst->DstReg.WriteMask;
1276 } else if (inst->DstReg.File == PROGRAM_TEMPORARY) {
1277 assert(inst->DstReg.Index < REG_ALLOCATE_MAX_PROGRAM_TEMPS);
1278 prevWriteMask = tempWrites[inst->DstReg.Index];
1279 tempWrites[inst->DstReg.Index] |= inst->DstReg.WriteMask;
1280 } else {
1281 /* No other register type can be a destination register. */
1282 continue;
1283 }
1284
1285 /* For a CMP to be considered a conditional write, the destination
1286 * register and source register two must be the same. */
1287 if (inst->Opcode == OPCODE_CMP
1288 && !(inst->DstReg.WriteMask & prevWriteMask)
1289 && inst->SrcReg[2].File == inst->DstReg.File
1290 && inst->SrcReg[2].Index == inst->DstReg.Index
1291 && inst->DstReg.WriteMask == get_src_arg_mask(inst, 2, NO_MASK)) {
1292
1293 inst->Opcode = OPCODE_MOV;
1294 inst->SrcReg[0] = inst->SrcReg[1];
1295
1296 /* Unused operands are expected to have the file set to
1297 * PROGRAM_UNDEFINED. This is how _mesa_init_instructions initializes
1298 * all of the sources.
1299 */
1300 inst->SrcReg[1].File = PROGRAM_UNDEFINED;
1301 inst->SrcReg[1].Swizzle = SWIZZLE_NOOP;
1302 inst->SrcReg[2].File = PROGRAM_UNDEFINED;
1303 inst->SrcReg[2].Swizzle = SWIZZLE_NOOP;
1304 }
1305 }
1306 if (dbg) {
1307 printf("Optimize: End reads without writes\n");
1308 _mesa_print_program(program);
1309 }
1310 }
1311
1312 /**
1313 * Apply optimizations to the given program to eliminate unnecessary
1314 * instructions, temp regs, etc.
1315 */
1316 void
1317 _mesa_optimize_program(struct gl_context *ctx, struct gl_program *program)
1318 {
1319 GLboolean any_change;
1320
1321 _mesa_simplify_cmp(program);
1322 /* Stop when no modifications were output */
1323 do {
1324 any_change = GL_FALSE;
1325 _mesa_remove_extra_move_use(program);
1326 if (_mesa_remove_dead_code_global(program))
1327 any_change = GL_TRUE;
1328 if (_mesa_remove_extra_moves(program))
1329 any_change = GL_TRUE;
1330 if (_mesa_remove_dead_code_local(program))
1331 any_change = GL_TRUE;
1332
1333 any_change = _mesa_constant_fold(program) || any_change;
1334 _mesa_reallocate_registers(program);
1335 } while (any_change);
1336 }
1337