2 * Mesa 3-D graphics library
4 * Copyright (C) 2009 VMware, Inc. All Rights Reserved.
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:
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
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.
26 #include "main/glheader.h"
27 #include "main/context.h"
28 #include "main/macros.h"
30 #include "prog_instruction.h"
31 #include "prog_optimize.h"
32 #include "prog_print.h"
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
41 #define REG_ALLOCATE_MAX_PROGRAM_TEMPS ((1 << INST_INDEX_BITS) - 1)
43 static GLboolean dbg
= GL_FALSE
;
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
54 get_src_arg_mask(const struct prog_instruction
*inst
,
55 GLuint arg
, GLuint dst_mask
)
57 GLuint read_mask
, channel_mask
;
60 assert(arg
< _mesa_num_inst_src_regs(inst
->Opcode
));
62 /* Form the dst register, find the written channels */
63 if (inst
->CondUpdate
) {
64 channel_mask
= WRITEMASK_XYZW
;
67 switch (inst
->Opcode
) {
87 channel_mask
= inst
->DstReg
.WriteMask
& dst_mask
;
96 channel_mask
= WRITEMASK_X
;
99 channel_mask
= WRITEMASK_XY
;
103 channel_mask
= WRITEMASK_XYZ
;
106 channel_mask
= WRITEMASK_XYZW
;
111 /* Now, given the src swizzle and the written channels, find which
112 * components are actually read
115 for (comp
= 0; comp
< 4; ++comp
) {
116 const GLuint coord
= GET_SWZ(inst
->SrcReg
[arg
].Swizzle
, comp
);
117 if (channel_mask
& (1 << comp
) && coord
<= SWIZZLE_W
)
118 read_mask
|= 1 << coord
;
126 * For a MOV instruction, compute a write mask when src register also has
130 get_dst_mask_for_mov(const struct prog_instruction
*mov
, GLuint src_mask
)
132 const GLuint mask
= mov
->DstReg
.WriteMask
;
134 GLuint updated_mask
= 0x0;
136 assert(mov
->Opcode
== OPCODE_MOV
);
138 for (comp
= 0; comp
< 4; ++comp
) {
140 if ((mask
& (1 << comp
)) == 0)
142 src_comp
= GET_SWZ(mov
->SrcReg
[0].Swizzle
, comp
);
143 if ((src_mask
& (1 << src_comp
)) == 0)
145 updated_mask
|= 1 << comp
;
153 * Ensure that the swizzle is regular. That is, all of the swizzle
154 * terms are SWIZZLE_X,Y,Z,W and not SWIZZLE_ZERO or SWIZZLE_ONE.
157 is_swizzle_regular(GLuint swz
)
159 return GET_SWZ(swz
,0) <= SWIZZLE_W
&&
160 GET_SWZ(swz
,1) <= SWIZZLE_W
&&
161 GET_SWZ(swz
,2) <= SWIZZLE_W
&&
162 GET_SWZ(swz
,3) <= SWIZZLE_W
;
167 * In 'prog' remove instruction[i] if removeFlags[i] == TRUE.
168 * \return number of instructions removed
171 remove_instructions(struct gl_program
*prog
, const GLboolean
*removeFlags
)
173 GLint i
, removeEnd
= 0, removeCount
= 0;
174 GLuint totalRemoved
= 0;
177 for (i
= prog
->NumInstructions
- 1; i
>= 0; i
--) {
178 if (removeFlags
[i
]) {
180 if (removeCount
== 0) {
181 /* begin a run of instructions to remove */
186 /* extend the run of instructions to remove */
191 /* don't remove this instruction, but check if the preceeding
192 * instructions are to be removed.
194 if (removeCount
> 0) {
195 GLint removeStart
= removeEnd
- removeCount
+ 1;
196 _mesa_delete_instructions(prog
, removeStart
, removeCount
);
197 removeStart
= removeCount
= 0; /* reset removal info */
201 /* Finish removing if the first instruction was to be removed. */
202 if (removeCount
> 0) {
203 GLint removeStart
= removeEnd
- removeCount
+ 1;
204 _mesa_delete_instructions(prog
, removeStart
, removeCount
);
211 * Remap register indexes according to map.
212 * \param prog the program to search/replace
213 * \param file the type of register file to search/replace
214 * \param map maps old register indexes to new indexes
217 replace_regs(struct gl_program
*prog
, gl_register_file file
, const GLint map
[])
221 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
222 struct prog_instruction
*inst
= prog
->Instructions
+ i
;
223 const GLuint numSrc
= _mesa_num_inst_src_regs(inst
->Opcode
);
225 for (j
= 0; j
< numSrc
; j
++) {
226 if (inst
->SrcReg
[j
].File
== file
) {
227 GLuint index
= inst
->SrcReg
[j
].Index
;
228 assert(map
[index
] >= 0);
229 inst
->SrcReg
[j
].Index
= map
[index
];
232 if (inst
->DstReg
.File
== file
) {
233 const GLuint index
= inst
->DstReg
.Index
;
234 assert(map
[index
] >= 0);
235 inst
->DstReg
.Index
= map
[index
];
242 * Remove dead instructions from the given program.
243 * This is very primitive for now. Basically look for temp registers
244 * that are written to but never read. Remove any instructions that
245 * write to such registers. Be careful with condition code setters.
248 _mesa_remove_dead_code_global(struct gl_program
*prog
)
250 GLboolean tempRead
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
][4];
251 GLboolean
*removeInst
; /* per-instruction removal flag */
252 GLuint i
, rem
= 0, comp
;
254 memset(tempRead
, 0, sizeof(tempRead
));
257 printf("Optimize: Begin dead code removal\n");
258 /*_mesa_print_program(prog);*/
262 calloc(prog
->NumInstructions
, sizeof(GLboolean
));
264 /* Determine which temps are read and written */
265 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
266 const struct prog_instruction
*inst
= prog
->Instructions
+ i
;
267 const GLuint numSrc
= _mesa_num_inst_src_regs(inst
->Opcode
);
271 for (j
= 0; j
< numSrc
; j
++) {
272 if (inst
->SrcReg
[j
].File
== PROGRAM_TEMPORARY
) {
273 const GLuint index
= inst
->SrcReg
[j
].Index
;
275 assert(index
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
);
276 read_mask
= get_src_arg_mask(inst
, j
, NO_MASK
);
278 if (inst
->SrcReg
[j
].RelAddr
) {
280 printf("abort remove dead code (indirect temp)\n");
284 for (comp
= 0; comp
< 4; comp
++) {
285 const GLuint swz
= GET_SWZ(inst
->SrcReg
[j
].Swizzle
, comp
);
286 if (swz
<= SWIZZLE_W
) {
287 if ((read_mask
& (1 << swz
)) == 0)
289 tempRead
[index
][swz
] = GL_TRUE
;
296 if (inst
->DstReg
.File
== PROGRAM_TEMPORARY
) {
297 const GLuint index
= inst
->DstReg
.Index
;
298 assert(index
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
);
300 if (inst
->DstReg
.RelAddr
) {
302 printf("abort remove dead code (indirect temp)\n");
306 if (inst
->CondUpdate
) {
307 /* If we're writing to this register and setting condition
308 * codes we cannot remove the instruction. Prevent removal
309 * by setting the 'read' flag.
311 tempRead
[index
][0] = GL_TRUE
;
312 tempRead
[index
][1] = GL_TRUE
;
313 tempRead
[index
][2] = GL_TRUE
;
314 tempRead
[index
][3] = GL_TRUE
;
319 /* find instructions that write to dead registers, flag for removal */
320 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
321 struct prog_instruction
*inst
= prog
->Instructions
+ i
;
322 const GLuint numDst
= _mesa_num_inst_dst_regs(inst
->Opcode
);
324 if (numDst
!= 0 && inst
->DstReg
.File
== PROGRAM_TEMPORARY
) {
325 GLint chan
, index
= inst
->DstReg
.Index
;
327 for (chan
= 0; chan
< 4; chan
++) {
328 if (!tempRead
[index
][chan
] &&
329 inst
->DstReg
.WriteMask
& (1 << chan
)) {
331 printf("Remove writemask on %u.%c\n", i
,
332 chan
== 3 ? 'w' : 'x' + chan
);
334 inst
->DstReg
.WriteMask
&= ~(1 << chan
);
339 if (inst
->DstReg
.WriteMask
== 0) {
340 /* If we cleared all writes, the instruction can be removed. */
342 printf("Remove instruction %u: \n", i
);
343 removeInst
[i
] = GL_TRUE
;
348 /* now remove the instructions which aren't needed */
349 rem
= remove_instructions(prog
, removeInst
);
352 printf("Optimize: End dead code removal.\n");
353 printf(" %u channel writes removed\n", rem
);
354 printf(" %u instructions removed\n", rem
);
355 /*_mesa_print_program(prog);*/
374 * Scan forward in program from 'start' for the next occurances of TEMP[index].
375 * We look if an instruction reads the component given by the masks and if they
377 * Return READ, WRITE, FLOW or END to indicate the next usage or an indicator
378 * that we can't look further.
381 find_next_use(const struct gl_program
*prog
,
388 for (i
= start
; i
< prog
->NumInstructions
; i
++) {
389 const struct prog_instruction
*inst
= prog
->Instructions
+ i
;
390 switch (inst
->Opcode
) {
406 const GLuint numSrc
= _mesa_num_inst_src_regs(inst
->Opcode
);
408 for (j
= 0; j
< numSrc
; j
++) {
409 if (inst
->SrcReg
[j
].RelAddr
||
410 (inst
->SrcReg
[j
].File
== PROGRAM_TEMPORARY
&&
411 inst
->SrcReg
[j
].Index
== (GLint
)index
&&
412 (get_src_arg_mask(inst
,j
,NO_MASK
) & mask
)))
415 if (_mesa_num_inst_dst_regs(inst
->Opcode
) == 1 &&
416 inst
->DstReg
.File
== PROGRAM_TEMPORARY
&&
417 inst
->DstReg
.Index
== index
) {
418 mask
&= ~inst
->DstReg
.WriteMask
;
430 * Is the given instruction opcode a flow-control opcode?
431 * XXX maybe move this into prog_instruction.[ch]
434 _mesa_is_flow_control_opcode(enum prog_opcode opcode
)
456 * Test if the given instruction is a simple MOV (no conditional updating,
457 * not relative addressing, no negation/abs, etc).
460 can_downward_mov_be_modifed(const struct prog_instruction
*mov
)
463 mov
->Opcode
== OPCODE_MOV
&&
464 mov
->CondUpdate
== GL_FALSE
&&
465 mov
->SrcReg
[0].RelAddr
== 0 &&
466 mov
->SrcReg
[0].Negate
== 0 &&
467 mov
->SrcReg
[0].Abs
== 0 &&
468 mov
->DstReg
.RelAddr
== 0 &&
469 mov
->DstReg
.CondMask
== COND_TR
;
474 can_upward_mov_be_modifed(const struct prog_instruction
*mov
)
477 can_downward_mov_be_modifed(mov
) &&
478 mov
->DstReg
.File
== PROGRAM_TEMPORARY
&&
484 * Try to remove use of extraneous MOV instructions, to free them up for dead
488 _mesa_remove_extra_move_use(struct gl_program
*prog
)
493 printf("Optimize: Begin remove extra move use\n");
494 _mesa_print_program(prog
);
498 * Look for sequences such as this:
501 * FOO tmpY, tmpX, arg1;
505 * FOO tmpY, arg0, arg1;
508 for (i
= 0; i
+ 1 < prog
->NumInstructions
; i
++) {
509 const struct prog_instruction
*mov
= prog
->Instructions
+ i
;
510 GLuint dst_mask
, src_mask
;
511 if (can_upward_mov_be_modifed(mov
) == GL_FALSE
)
514 /* Scanning the code, we maintain the components which are still active in
517 dst_mask
= mov
->DstReg
.WriteMask
;
518 src_mask
= get_src_arg_mask(mov
, 0, NO_MASK
);
520 /* Walk through remaining instructions until the or src reg gets
521 * rewritten or we get into some flow-control, eliminating the use of
524 for (j
= i
+ 1; j
< prog
->NumInstructions
; j
++) {
525 struct prog_instruction
*inst2
= prog
->Instructions
+ j
;
528 if (_mesa_is_flow_control_opcode(inst2
->Opcode
))
531 /* First rewrite this instruction's args if appropriate. */
532 for (arg
= 0; arg
< _mesa_num_inst_src_regs(inst2
->Opcode
); arg
++) {
533 GLuint comp
, read_mask
;
535 if (inst2
->SrcReg
[arg
].File
!= mov
->DstReg
.File
||
536 inst2
->SrcReg
[arg
].Index
!= mov
->DstReg
.Index
||
537 inst2
->SrcReg
[arg
].RelAddr
||
538 inst2
->SrcReg
[arg
].Abs
)
540 read_mask
= get_src_arg_mask(inst2
, arg
, NO_MASK
);
542 /* Adjust the swizzles of inst2 to point at MOV's source if ALL the
543 * components read still come from the mov instructions
545 if (is_swizzle_regular(inst2
->SrcReg
[arg
].Swizzle
) &&
546 (read_mask
& dst_mask
) == read_mask
) {
547 for (comp
= 0; comp
< 4; comp
++) {
548 const GLuint inst2_swz
=
549 GET_SWZ(inst2
->SrcReg
[arg
].Swizzle
, comp
);
550 const GLuint s
= GET_SWZ(mov
->SrcReg
[0].Swizzle
, inst2_swz
);
551 inst2
->SrcReg
[arg
].Swizzle
&= ~(7 << (3 * comp
));
552 inst2
->SrcReg
[arg
].Swizzle
|= s
<< (3 * comp
);
553 inst2
->SrcReg
[arg
].Negate
^= (((mov
->SrcReg
[0].Negate
>>
554 inst2_swz
) & 0x1) << comp
);
556 inst2
->SrcReg
[arg
].File
= mov
->SrcReg
[0].File
;
557 inst2
->SrcReg
[arg
].Index
= mov
->SrcReg
[0].Index
;
561 /* The source of MOV is written. This potentially deactivates some
562 * components from the src and dst of the MOV instruction
564 if (inst2
->DstReg
.File
== mov
->DstReg
.File
&&
565 (inst2
->DstReg
.RelAddr
||
566 inst2
->DstReg
.Index
== mov
->DstReg
.Index
)) {
567 dst_mask
&= ~inst2
->DstReg
.WriteMask
;
568 src_mask
= get_src_arg_mask(mov
, 0, dst_mask
);
571 /* Idem when the destination of mov is written */
572 if (inst2
->DstReg
.File
== mov
->SrcReg
[0].File
&&
573 (inst2
->DstReg
.RelAddr
||
574 inst2
->DstReg
.Index
== mov
->SrcReg
[0].Index
)) {
575 src_mask
&= ~inst2
->DstReg
.WriteMask
;
576 dst_mask
&= get_dst_mask_for_mov(mov
, src_mask
);
584 printf("Optimize: End remove extra move use.\n");
585 /*_mesa_print_program(prog);*/
591 * Complements dead_code_global. Try to remove code in block of code by
592 * carefully monitoring the swizzles. Both functions should be merged into one
593 * with a proper control flow graph
596 _mesa_remove_dead_code_local(struct gl_program
*prog
)
598 GLboolean
*removeInst
;
599 GLuint i
, arg
, rem
= 0;
602 calloc(prog
->NumInstructions
, sizeof(GLboolean
));
604 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
605 const struct prog_instruction
*inst
= prog
->Instructions
+ i
;
606 const GLuint index
= inst
->DstReg
.Index
;
607 const GLuint mask
= inst
->DstReg
.WriteMask
;
610 /* We must deactivate the pass as soon as some indirection is used */
611 if (inst
->DstReg
.RelAddr
)
613 for (arg
= 0; arg
< _mesa_num_inst_src_regs(inst
->Opcode
); arg
++)
614 if (inst
->SrcReg
[arg
].RelAddr
)
617 if (_mesa_is_flow_control_opcode(inst
->Opcode
) ||
618 _mesa_num_inst_dst_regs(inst
->Opcode
) == 0 ||
619 inst
->DstReg
.File
!= PROGRAM_TEMPORARY
||
620 inst
->DstReg
.RelAddr
)
623 use
= find_next_use(prog
, i
+1, index
, mask
);
624 if (use
== WRITE
|| use
== END
)
625 removeInst
[i
] = GL_TRUE
;
628 rem
= remove_instructions(prog
, removeInst
);
637 * Try to inject the destination of mov as the destination of inst and recompute
638 * the swizzles operators for the sources of inst if required. Return GL_TRUE
639 * of the substitution was possible, GL_FALSE otherwise
642 _mesa_merge_mov_into_inst(struct prog_instruction
*inst
,
643 const struct prog_instruction
*mov
)
645 /* Indirection table which associates destination and source components for
646 * the mov instruction
648 const GLuint mask
= get_src_arg_mask(mov
, 0, NO_MASK
);
650 /* Some components are not written by inst. We cannot remove the mov */
651 if (mask
!= (inst
->DstReg
.WriteMask
& mask
))
654 inst
->Saturate
|= mov
->Saturate
;
656 /* Depending on the instruction, we may need to recompute the swizzles.
657 * Also, some other instructions (like TEX) are not linear. We will only
658 * consider completely active sources and destinations
660 switch (inst
->Opcode
) {
662 /* Carstesian instructions: we compute the swizzle */
672 GLuint dst_to_src_comp
[4] = {0,0,0,0};
673 GLuint dst_comp
, arg
;
674 for (dst_comp
= 0; dst_comp
< 4; ++dst_comp
) {
675 if (mov
->DstReg
.WriteMask
& (1 << dst_comp
)) {
676 const GLuint src_comp
= GET_SWZ(mov
->SrcReg
[0].Swizzle
, dst_comp
);
677 assert(src_comp
< 4);
678 dst_to_src_comp
[dst_comp
] = src_comp
;
682 /* Patch each source of the instruction */
683 for (arg
= 0; arg
< _mesa_num_inst_src_regs(inst
->Opcode
); arg
++) {
684 const GLuint arg_swz
= inst
->SrcReg
[arg
].Swizzle
;
685 inst
->SrcReg
[arg
].Swizzle
= 0;
687 /* Reset each active component of the swizzle */
688 for (dst_comp
= 0; dst_comp
< 4; ++dst_comp
) {
689 GLuint src_comp
, arg_comp
;
690 if ((mov
->DstReg
.WriteMask
& (1 << dst_comp
)) == 0)
692 src_comp
= dst_to_src_comp
[dst_comp
];
693 assert(src_comp
< 4);
694 arg_comp
= GET_SWZ(arg_swz
, src_comp
);
695 assert(arg_comp
< 4);
696 inst
->SrcReg
[arg
].Swizzle
|= arg_comp
<< (3*dst_comp
);
699 inst
->DstReg
= mov
->DstReg
;
703 /* Dot products and scalar instructions: we only change the destination */
714 inst
->DstReg
= mov
->DstReg
;
717 /* All other instructions require fully active components with no swizzle */
719 if (mov
->SrcReg
[0].Swizzle
!= SWIZZLE_XYZW
||
720 inst
->DstReg
.WriteMask
!= WRITEMASK_XYZW
)
722 inst
->DstReg
= mov
->DstReg
;
729 * Try to remove extraneous MOV instructions from the given program.
732 _mesa_remove_extra_moves(struct gl_program
*prog
)
734 GLboolean
*removeInst
; /* per-instruction removal flag */
735 GLuint i
, rem
= 0, nesting
= 0;
738 printf("Optimize: Begin remove extra moves\n");
739 _mesa_print_program(prog
);
743 calloc(prog
->NumInstructions
, sizeof(GLboolean
));
746 * Look for sequences such as this:
747 * FOO tmpX, arg0, arg1;
750 * FOO tmpY, arg0, arg1;
753 for (i
= 0; i
< prog
->NumInstructions
; i
++) {
754 const struct prog_instruction
*mov
= prog
->Instructions
+ i
;
756 switch (mov
->Opcode
) {
769 can_downward_mov_be_modifed(mov
) &&
770 mov
->SrcReg
[0].File
== PROGRAM_TEMPORARY
&&
774 /* see if this MOV can be removed */
775 const GLuint id
= mov
->SrcReg
[0].Index
;
776 struct prog_instruction
*prevInst
;
779 /* get pointer to previous instruction */
781 while (prevI
> 0 && removeInst
[prevI
])
783 prevInst
= prog
->Instructions
+ prevI
;
785 if (prevInst
->DstReg
.File
== PROGRAM_TEMPORARY
&&
786 prevInst
->DstReg
.Index
== id
&&
787 prevInst
->DstReg
.RelAddr
== 0 &&
788 prevInst
->DstReg
.CondMask
== COND_TR
) {
790 const GLuint dst_mask
= prevInst
->DstReg
.WriteMask
;
791 enum inst_use next_use
= find_next_use(prog
, i
+1, id
, dst_mask
);
793 if (next_use
== WRITE
|| next_use
== END
) {
794 /* OK, we can safely remove this MOV instruction.
796 * prevI: FOO tempIndex, x, y;
797 * i: MOV z, tempIndex;
799 * prevI: FOO z, x, y;
801 if (_mesa_merge_mov_into_inst(prevInst
, mov
)) {
802 removeInst
[i
] = GL_TRUE
;
804 printf("Remove MOV at %u\n", i
);
805 printf("new prev inst %u: ", prevI
);
806 _mesa_print_instruction(prevInst
);
818 /* now remove the instructions which aren't needed */
819 rem
= remove_instructions(prog
, removeInst
);
824 printf("Optimize: End remove extra moves. %u instructions removed\n", rem
);
825 /*_mesa_print_program(prog);*/
832 /** A live register interval */
835 GLuint Reg
; /** The temporary register index */
836 GLuint Start
, End
; /** Start/end instruction numbers */
840 /** A list of register intervals */
844 struct interval Intervals
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
849 append_interval(struct interval_list
*list
, const struct interval
*inv
)
851 list
->Intervals
[list
->Num
++] = *inv
;
855 /** Insert interval inv into list, sorted by interval end */
857 insert_interval_by_end(struct interval_list
*list
, const struct interval
*inv
)
859 /* XXX we could do a binary search insertion here since list is sorted */
860 GLint i
= list
->Num
- 1;
861 while (i
>= 0 && list
->Intervals
[i
].End
> inv
->End
) {
862 list
->Intervals
[i
+ 1] = list
->Intervals
[i
];
865 list
->Intervals
[i
+ 1] = *inv
;
871 for (i
= 0; i
+ 1 < list
->Num
; i
++) {
872 assert(list
->Intervals
[i
].End
<= list
->Intervals
[i
+ 1].End
);
879 /** Remove the given interval from the interval list */
881 remove_interval(struct interval_list
*list
, const struct interval
*inv
)
883 /* XXX we could binary search since list is sorted */
885 for (k
= 0; k
< list
->Num
; k
++) {
886 if (list
->Intervals
[k
].Reg
== inv
->Reg
) {
887 /* found, remove it */
888 assert(list
->Intervals
[k
].Start
== inv
->Start
);
889 assert(list
->Intervals
[k
].End
== inv
->End
);
890 while (k
< list
->Num
- 1) {
891 list
->Intervals
[k
] = list
->Intervals
[k
+ 1];
901 /** called by qsort() */
903 compare_start(const void *a
, const void *b
)
905 const struct interval
*ia
= (const struct interval
*) a
;
906 const struct interval
*ib
= (const struct interval
*) b
;
907 if (ia
->Start
< ib
->Start
)
909 else if (ia
->Start
> ib
->Start
)
916 /** sort the interval list according to interval starts */
918 sort_interval_list_by_start(struct interval_list
*list
)
920 qsort(list
->Intervals
, list
->Num
, sizeof(struct interval
), compare_start
);
924 for (i
= 0; i
+ 1 < list
->Num
; i
++) {
925 assert(list
->Intervals
[i
].Start
<= list
->Intervals
[i
+ 1].Start
);
933 GLuint Start
, End
; /**< Start, end instructions of loop */
937 * Update the intermediate interval info for register 'index' and
941 update_interval(GLint intBegin
[], GLint intEnd
[],
942 struct loop_info
*loopStack
, GLuint loopStackDepth
,
943 GLuint index
, GLuint ic
)
949 /* If the register is used in a loop, extend its lifetime through the end
950 * of the outermost loop that doesn't contain its definition.
952 for (i
= 0; i
< loopStackDepth
; i
++) {
953 if (intBegin
[index
] < loopStack
[i
].Start
) {
954 end
= loopStack
[i
].End
;
959 /* Variables that are live at the end of a loop will also be live at the
960 * beginning, so an instruction inside of a loop should have its live
961 * interval begin at the start of the outermost loop.
963 if (loopStackDepth
> 0 && ic
> loopStack
[0].Start
&& ic
< loopStack
[0].End
) {
964 begin
= loopStack
[0].Start
;
967 assert(index
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
);
968 if (intBegin
[index
] == -1) {
969 assert(intEnd
[index
] == -1);
970 intBegin
[index
] = begin
;
980 * Find first/last instruction that references each temporary register.
983 _mesa_find_temp_intervals(const struct prog_instruction
*instructions
,
984 GLuint numInstructions
,
985 GLint intBegin
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
],
986 GLint intEnd
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
])
988 struct loop_info loopStack
[MAX_LOOP_NESTING
];
989 GLuint loopStackDepth
= 0;
992 for (i
= 0; i
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; i
++){
993 intBegin
[i
] = intEnd
[i
] = -1;
996 /* Scan instructions looking for temporary registers */
997 for (i
= 0; i
< numInstructions
; i
++) {
998 const struct prog_instruction
*inst
= instructions
+ i
;
999 if (inst
->Opcode
== OPCODE_BGNLOOP
) {
1000 loopStack
[loopStackDepth
].Start
= i
;
1001 loopStack
[loopStackDepth
].End
= inst
->BranchTarget
;
1004 else if (inst
->Opcode
== OPCODE_ENDLOOP
) {
1007 else if (inst
->Opcode
== OPCODE_CAL
) {
1011 const GLuint numSrc
= 3;/*_mesa_num_inst_src_regs(inst->Opcode);*/
1013 for (j
= 0; j
< numSrc
; j
++) {
1014 if (inst
->SrcReg
[j
].File
== PROGRAM_TEMPORARY
) {
1015 const GLuint index
= inst
->SrcReg
[j
].Index
;
1016 if (inst
->SrcReg
[j
].RelAddr
)
1018 update_interval(intBegin
, intEnd
, loopStack
, loopStackDepth
,
1022 if (inst
->DstReg
.File
== PROGRAM_TEMPORARY
) {
1023 const GLuint index
= inst
->DstReg
.Index
;
1024 if (inst
->DstReg
.RelAddr
)
1026 update_interval(intBegin
, intEnd
, loopStack
, loopStackDepth
,
1037 * Find the live intervals for each temporary register in the program.
1038 * For register R, the interval [A,B] indicates that R is referenced
1039 * from instruction A through instruction B.
1040 * Special consideration is needed for loops and subroutines.
1041 * \return GL_TRUE if success, GL_FALSE if we cannot proceed for some reason
1044 find_live_intervals(struct gl_program
*prog
,
1045 struct interval_list
*liveIntervals
)
1047 GLint intBegin
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1048 GLint intEnd
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1052 * Note: we'll return GL_FALSE below if we find relative indexing
1053 * into the TEMP register file. We can't handle that yet.
1054 * We also give up on subroutines for now.
1058 printf("Optimize: Begin find intervals\n");
1061 /* build intermediate arrays */
1062 if (!_mesa_find_temp_intervals(prog
->Instructions
, prog
->NumInstructions
,
1066 /* Build live intervals list from intermediate arrays */
1067 liveIntervals
->Num
= 0;
1068 for (i
= 0; i
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; i
++) {
1069 if (intBegin
[i
] >= 0) {
1070 struct interval inv
;
1072 inv
.Start
= intBegin
[i
];
1073 inv
.End
= intEnd
[i
];
1074 append_interval(liveIntervals
, &inv
);
1078 /* Sort the list according to interval starts */
1079 sort_interval_list_by_start(liveIntervals
);
1082 /* print interval info */
1083 for (i
= 0; i
< liveIntervals
->Num
; i
++) {
1084 const struct interval
*inv
= liveIntervals
->Intervals
+ i
;
1085 printf("Reg[%d] live [%d, %d]:",
1086 inv
->Reg
, inv
->Start
, inv
->End
);
1089 for (j
= 0; j
< inv
->Start
; j
++)
1091 for (j
= inv
->Start
; j
<= inv
->End
; j
++)
1102 /** Scan the array of used register flags to find free entry */
1104 alloc_register(GLboolean usedRegs
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
])
1107 for (k
= 0; k
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; k
++) {
1109 usedRegs
[k
] = GL_TRUE
;
1118 * This function implements "Linear Scan Register Allocation" to reduce
1119 * the number of temporary registers used by the program.
1121 * We compute the "live interval" for all temporary registers then
1122 * examine the overlap of the intervals to allocate new registers.
1123 * Basically, if two intervals do not overlap, they can use the same register.
1126 _mesa_reallocate_registers(struct gl_program
*prog
)
1128 struct interval_list liveIntervals
;
1129 GLint registerMap
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1130 GLboolean usedRegs
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1135 printf("Optimize: Begin live-interval register reallocation\n");
1136 _mesa_print_program(prog
);
1139 for (i
= 0; i
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; i
++){
1140 registerMap
[i
] = -1;
1141 usedRegs
[i
] = GL_FALSE
;
1144 if (!find_live_intervals(prog
, &liveIntervals
)) {
1146 printf("Aborting register reallocation\n");
1151 struct interval_list activeIntervals
;
1152 activeIntervals
.Num
= 0;
1154 /* loop over live intervals, allocating a new register for each */
1155 for (i
= 0; i
< liveIntervals
.Num
; i
++) {
1156 const struct interval
*live
= liveIntervals
.Intervals
+ i
;
1159 printf("Consider register %u\n", live
->Reg
);
1161 /* Expire old intervals. Intervals which have ended with respect
1162 * to the live interval can have their remapped registers freed.
1166 for (j
= 0; j
< (GLint
) activeIntervals
.Num
; j
++) {
1167 const struct interval
*inv
= activeIntervals
.Intervals
+ j
;
1168 if (inv
->End
>= live
->Start
) {
1169 /* Stop now. Since the activeInterval list is sorted
1170 * we know we don't have to go further.
1175 /* Interval 'inv' has expired */
1176 const GLint regNew
= registerMap
[inv
->Reg
];
1177 assert(regNew
>= 0);
1180 printf(" expire interval for reg %u\n", inv
->Reg
);
1182 /* remove interval j from active list */
1183 remove_interval(&activeIntervals
, inv
);
1184 j
--; /* counter-act j++ in for-loop above */
1186 /* return register regNew to the free pool */
1188 printf(" free reg %d\n", regNew
);
1189 assert(usedRegs
[regNew
] == GL_TRUE
);
1190 usedRegs
[regNew
] = GL_FALSE
;
1195 /* find a free register for this live interval */
1197 const GLint k
= alloc_register(usedRegs
);
1199 /* out of registers, give up */
1202 registerMap
[live
->Reg
] = k
;
1203 maxTemp
= MAX2(maxTemp
, k
);
1205 printf(" remap register %u -> %d\n", live
->Reg
, k
);
1208 /* Insert this live interval into the active list which is sorted
1209 * by increasing end points.
1211 insert_interval_by_end(&activeIntervals
, live
);
1215 if (maxTemp
+ 1 < (GLint
) liveIntervals
.Num
) {
1216 /* OK, we've reduced the number of registers needed.
1217 * Scan the program and replace all the old temporary register
1218 * indexes with the new indexes.
1220 replace_regs(prog
, PROGRAM_TEMPORARY
, registerMap
);
1222 prog
->NumTemporaries
= maxTemp
+ 1;
1226 printf("Optimize: End live-interval register reallocation\n");
1227 printf("Num temp regs before: %u after: %u\n",
1228 liveIntervals
.Num
, maxTemp
+ 1);
1229 _mesa_print_program(prog
);
1236 print_it(struct gl_context
*ctx
, struct gl_program
*program
, const char *txt
) {
1237 fprintf(stderr
, "%s (%u inst):\n", txt
, program
->NumInstructions
);
1238 _mesa_print_program(program
);
1239 _mesa_print_program_parameters(ctx
, program
);
1240 fprintf(stderr
, "\n\n");
1245 * This pass replaces CMP T0, T1 T2 T0 with MOV T0, T2 when the CMP
1246 * instruction is the first instruction to write to register T0. The are
1247 * several lowering passes done in GLSL IR (e.g. branches and
1248 * relative addressing) that create a large number of conditional assignments
1249 * that ir_to_mesa converts to CMP instructions like the one mentioned above.
1251 * Here is why this conversion is safe:
1252 * CMP T0, T1 T2 T0 can be expanded to:
1258 * If (T1 < 0.0) evaluates to true then our replacement MOV T0, T2 is the same
1259 * as the original program. If (T1 < 0.0) evaluates to false, executing
1260 * MOV T0, T0 will store a garbage value in T0 since T0 is uninitialized.
1261 * Therefore, it doesn't matter that we are replacing MOV T0, T0 with MOV T0, T2
1262 * because any instruction that was going to read from T0 after this was going
1263 * to read a garbage value anyway.
1266 _mesa_simplify_cmp(struct gl_program
* program
)
1268 GLuint tempWrites
[REG_ALLOCATE_MAX_PROGRAM_TEMPS
];
1269 GLuint outputWrites
[MAX_PROGRAM_OUTPUTS
];
1273 printf("Optimize: Begin reads without writes\n");
1274 _mesa_print_program(program
);
1277 for (i
= 0; i
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
; i
++) {
1281 for (i
= 0; i
< MAX_PROGRAM_OUTPUTS
; i
++) {
1282 outputWrites
[i
] = 0;
1285 for (i
= 0; i
< program
->NumInstructions
; i
++) {
1286 struct prog_instruction
*inst
= program
->Instructions
+ i
;
1287 GLuint prevWriteMask
;
1289 /* Give up if we encounter relative addressing or flow control. */
1290 if (_mesa_is_flow_control_opcode(inst
->Opcode
) || inst
->DstReg
.RelAddr
) {
1294 if (inst
->DstReg
.File
== PROGRAM_OUTPUT
) {
1295 assert(inst
->DstReg
.Index
< MAX_PROGRAM_OUTPUTS
);
1296 prevWriteMask
= outputWrites
[inst
->DstReg
.Index
];
1297 outputWrites
[inst
->DstReg
.Index
] |= inst
->DstReg
.WriteMask
;
1298 } else if (inst
->DstReg
.File
== PROGRAM_TEMPORARY
) {
1299 assert(inst
->DstReg
.Index
< REG_ALLOCATE_MAX_PROGRAM_TEMPS
);
1300 prevWriteMask
= tempWrites
[inst
->DstReg
.Index
];
1301 tempWrites
[inst
->DstReg
.Index
] |= inst
->DstReg
.WriteMask
;
1303 /* No other register type can be a destination register. */
1307 /* For a CMP to be considered a conditional write, the destination
1308 * register and source register two must be the same. */
1309 if (inst
->Opcode
== OPCODE_CMP
1310 && !(inst
->DstReg
.WriteMask
& prevWriteMask
)
1311 && inst
->SrcReg
[2].File
== inst
->DstReg
.File
1312 && inst
->SrcReg
[2].Index
== inst
->DstReg
.Index
1313 && inst
->DstReg
.WriteMask
== get_src_arg_mask(inst
, 2, NO_MASK
)) {
1315 inst
->Opcode
= OPCODE_MOV
;
1316 inst
->SrcReg
[0] = inst
->SrcReg
[1];
1318 /* Unused operands are expected to have the file set to
1319 * PROGRAM_UNDEFINED. This is how _mesa_init_instructions initializes
1320 * all of the sources.
1322 inst
->SrcReg
[1].File
= PROGRAM_UNDEFINED
;
1323 inst
->SrcReg
[1].Swizzle
= SWIZZLE_NOOP
;
1324 inst
->SrcReg
[2].File
= PROGRAM_UNDEFINED
;
1325 inst
->SrcReg
[2].Swizzle
= SWIZZLE_NOOP
;
1329 printf("Optimize: End reads without writes\n");
1330 _mesa_print_program(program
);
1335 * Apply optimizations to the given program to eliminate unnecessary
1336 * instructions, temp regs, etc.
1339 _mesa_optimize_program(struct gl_context
*ctx
, struct gl_program
*program
)
1341 GLboolean any_change
;
1343 _mesa_simplify_cmp(program
);
1344 /* Stop when no modifications were output */
1346 any_change
= GL_FALSE
;
1347 _mesa_remove_extra_move_use(program
);
1348 if (_mesa_remove_dead_code_global(program
))
1349 any_change
= GL_TRUE
;
1350 if (_mesa_remove_extra_moves(program
))
1351 any_change
= GL_TRUE
;
1352 if (_mesa_remove_dead_code_local(program
))
1353 any_change
= GL_TRUE
;
1355 any_change
= _mesa_constant_fold(program
) || any_change
;
1356 _mesa_reallocate_registers(program
);
1357 } while (any_change
);