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
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24/**
25 * \file opt_tree_grafting.cpp
26 *
27 * Takes assignments to variables that are dereferenced only once and
28 * pastes the RHS expression into where the variable is dereferenced.
29 *
30 * In the process of various operations like function inlining and
31 * tertiary op handling, we'll end up with our expression trees having
32 * been chopped up into a series of assignments of short expressions
33 * to temps.  Other passes like ir_algebraic.cpp would prefer to see
34 * the deepest expression trees they can to try to optimize them.
35 *
36 * This is a lot like copy propagaton.  In comparison, copy
37 * propagation only acts on plain copies, not arbitrary expressions on
38 * the RHS.  Generally, we wouldn't want to go pasting some
39 * complicated expression everywhere it got used, though, so we don't
40 * handle expressions in that pass.
41 *
42 * The hard part is making sure we don't move an expression across
43 * some other assignments that would change the value of the
44 * expression.  So we split this into two passes: First, find the
45 * variables in our scope which are written to once and read once, and
46 * then go through basic blocks seeing if we find an opportunity to
47 * move those expressions safely.
48 */
49
50#include "ir.h"
51#include "ir_visitor.h"
52#include "ir_variable_refcount.h"
53#include "ir_basic_block.h"
54#include "ir_optimization.h"
55#include "glsl_types.h"
56
57namespace {
58
59static bool debug = false;
60
61class ir_tree_grafting_visitor : public ir_hierarchical_visitor {
62public:
63   ir_tree_grafting_visitor(ir_assignment *graft_assign,
64			    ir_variable *graft_var)
65   {
66      this->progress = false;
67      this->graft_assign = graft_assign;
68      this->graft_var = graft_var;
69   }
70
71   virtual ir_visitor_status visit_leave(class ir_assignment *);
72   virtual ir_visitor_status visit_enter(class ir_call *);
73   virtual ir_visitor_status visit_enter(class ir_expression *);
74   virtual ir_visitor_status visit_enter(class ir_function *);
75   virtual ir_visitor_status visit_enter(class ir_function_signature *);
76   virtual ir_visitor_status visit_enter(class ir_if *);
77   virtual ir_visitor_status visit_enter(class ir_loop *);
78   virtual ir_visitor_status visit_enter(class ir_swizzle *);
79   virtual ir_visitor_status visit_enter(class ir_texture *);
80
81   ir_visitor_status check_graft(ir_instruction *ir, ir_variable *var);
82
83   bool do_graft(ir_rvalue **rvalue);
84
85   bool progress;
86   ir_variable *graft_var;
87   ir_assignment *graft_assign;
88};
89
90struct find_deref_info {
91   ir_variable *var;
92   bool found;
93};
94
95void
96dereferences_variable_callback(ir_instruction *ir, void *data)
97{
98   struct find_deref_info *info = (struct find_deref_info *)data;
99   ir_dereference_variable *deref = ir->as_dereference_variable();
100
101   if (deref && deref->var == info->var)
102      info->found = true;
103}
104
105static bool
106dereferences_variable(ir_instruction *ir, ir_variable *var)
107{
108   struct find_deref_info info;
109
110   info.var = var;
111   info.found = false;
112
113   visit_tree(ir, dereferences_variable_callback, &info);
114
115   return info.found;
116}
117
118bool
119ir_tree_grafting_visitor::do_graft(ir_rvalue **rvalue)
120{
121   if (!*rvalue)
122      return false;
123
124   ir_dereference_variable *deref = (*rvalue)->as_dereference_variable();
125
126   if (!deref || deref->var != this->graft_var)
127      return false;
128
129   if (debug) {
130      printf("GRAFTING:\n");
131      this->graft_assign->print();
132      printf("\n");
133      printf("TO:\n");
134      (*rvalue)->print();
135      printf("\n");
136   }
137
138   this->graft_assign->remove();
139   *rvalue = this->graft_assign->rhs;
140
141   this->progress = true;
142   return true;
143}
144
145ir_visitor_status
146ir_tree_grafting_visitor::visit_enter(ir_loop *ir)
147{
148   (void)ir;
149   /* Do not traverse into the body of the loop since that is a
150    * different basic block.
151    */
152   return visit_stop;
153}
154
155/**
156 * Check if we can continue grafting after writing to a variable.  If the
157 * expression we're trying to graft references the variable, we must stop.
158 *
159 * \param ir   An instruction that writes to a variable.
160 * \param var  The variable being updated.
161 */
162ir_visitor_status
163ir_tree_grafting_visitor::check_graft(ir_instruction *ir, ir_variable *var)
164{
165   if (dereferences_variable(this->graft_assign->rhs, var)) {
166      if (debug) {
167	 printf("graft killed by: ");
168	 ir->print();
169	 printf("\n");
170      }
171      return visit_stop;
172   }
173
174   return visit_continue;
175}
176
177ir_visitor_status
178ir_tree_grafting_visitor::visit_leave(ir_assignment *ir)
179{
180   if (do_graft(&ir->rhs) ||
181       do_graft(&ir->condition))
182      return visit_stop;
183
184   /* If this assignment updates a variable used in the assignment
185    * we're trying to graft, then we're done.
186    */
187   return check_graft(ir, ir->lhs->variable_referenced());
188}
189
190ir_visitor_status
191ir_tree_grafting_visitor::visit_enter(ir_function *ir)
192{
193   (void) ir;
194   return visit_continue_with_parent;
195}
196
197ir_visitor_status
198ir_tree_grafting_visitor::visit_enter(ir_function_signature *ir)
199{
200   (void)ir;
201   return visit_continue_with_parent;
202}
203
204ir_visitor_status
205ir_tree_grafting_visitor::visit_enter(ir_call *ir)
206{
207   exec_list_iterator sig_iter = ir->callee->parameters.iterator();
208   /* Reminder: iterating ir_call iterates its parameters. */
209   foreach_iter(exec_list_iterator, iter, *ir) {
210      ir_variable *sig_param = (ir_variable *)sig_iter.get();
211      ir_rvalue *ir = (ir_rvalue *)iter.get();
212      ir_rvalue *new_ir = ir;
213
214      if (sig_param->mode != ir_var_in && sig_param->mode != ir_var_const_in) {
215	 if (check_graft(ir, sig_param) == visit_stop)
216	    return visit_stop;
217	 continue;
218      }
219
220      if (do_graft(&new_ir)) {
221	 ir->replace_with(new_ir);
222	 return visit_stop;
223      }
224      sig_iter.next();
225   }
226
227   if (ir->return_deref && check_graft(ir, ir->return_deref->var) == visit_stop)
228      return visit_stop;
229
230   return visit_continue;
231}
232
233ir_visitor_status
234ir_tree_grafting_visitor::visit_enter(ir_expression *ir)
235{
236   for (unsigned int i = 0; i < ir->get_num_operands(); i++) {
237      if (do_graft(&ir->operands[i]))
238	 return visit_stop;
239   }
240
241   return visit_continue;
242}
243
244ir_visitor_status
245ir_tree_grafting_visitor::visit_enter(ir_if *ir)
246{
247   if (do_graft(&ir->condition))
248      return visit_stop;
249
250   /* Do not traverse into the body of the if-statement since that is a
251    * different basic block.
252    */
253   return visit_continue_with_parent;
254}
255
256ir_visitor_status
257ir_tree_grafting_visitor::visit_enter(ir_swizzle *ir)
258{
259   if (do_graft(&ir->val))
260      return visit_stop;
261
262   return visit_continue;
263}
264
265ir_visitor_status
266ir_tree_grafting_visitor::visit_enter(ir_texture *ir)
267{
268   if (do_graft(&ir->coordinate) ||
269       do_graft(&ir->projector) ||
270       do_graft(&ir->offset) ||
271       do_graft(&ir->shadow_comparitor))
272	 return visit_stop;
273
274   switch (ir->op) {
275   case ir_tex:
276      break;
277   case ir_txb:
278      if (do_graft(&ir->lod_info.bias))
279	 return visit_stop;
280      break;
281   case ir_txf:
282   case ir_txl:
283   case ir_txs:
284      if (do_graft(&ir->lod_info.lod))
285	 return visit_stop;
286      break;
287   case ir_txd:
288      if (do_graft(&ir->lod_info.grad.dPdx) ||
289	  do_graft(&ir->lod_info.grad.dPdy))
290	 return visit_stop;
291      break;
292   }
293
294   return visit_continue;
295}
296
297struct tree_grafting_info {
298   ir_variable_refcount_visitor *refs;
299   bool progress;
300};
301
302static bool
303try_tree_grafting(ir_assignment *start,
304		  ir_variable *lhs_var,
305		  ir_instruction *bb_last)
306{
307   ir_tree_grafting_visitor v(start, lhs_var);
308
309   if (debug) {
310      printf("trying to graft: ");
311      lhs_var->print();
312      printf("\n");
313   }
314
315   for (ir_instruction *ir = (ir_instruction *)start->next;
316	ir != bb_last->next;
317	ir = (ir_instruction *)ir->next) {
318
319      if (debug) {
320	 printf("- ");
321	 ir->print();
322	 printf("\n");
323      }
324
325      ir_visitor_status s = ir->accept(&v);
326      if (s == visit_stop)
327	 return v.progress;
328   }
329
330   return false;
331}
332
333static void
334tree_grafting_basic_block(ir_instruction *bb_first,
335			  ir_instruction *bb_last,
336			  void *data)
337{
338   struct tree_grafting_info *info = (struct tree_grafting_info *)data;
339   ir_instruction *ir, *next;
340
341   for (ir = bb_first, next = (ir_instruction *)ir->next;
342	ir != bb_last->next;
343	ir = next, next = (ir_instruction *)ir->next) {
344      ir_assignment *assign = ir->as_assignment();
345
346      if (!assign)
347	 continue;
348
349      ir_variable *lhs_var = assign->whole_variable_written();
350      if (!lhs_var)
351	 continue;
352
353      if (lhs_var->mode == ir_var_out ||
354	  lhs_var->mode == ir_var_inout)
355	 continue;
356
357      ir_variable_refcount_entry *entry = info->refs->get_variable_entry(lhs_var);
358
359      if (!entry->declaration ||
360	  entry->assigned_count != 1 ||
361	  entry->referenced_count != 2)
362	 continue;
363
364      assert(assign == entry->assign);
365
366      /* Found a possibly graftable assignment.  Now, walk through the
367       * rest of the BB seeing if the deref is here, and if nothing interfered with
368       * pasting its expression's values in between.
369       */
370      info->progress |= try_tree_grafting(assign, lhs_var, bb_last);
371   }
372}
373
374} /* unnamed namespace */
375
376/**
377 * Does a copy propagation pass on the code present in the instruction stream.
378 */
379bool
380do_tree_grafting(exec_list *instructions)
381{
382   ir_variable_refcount_visitor refs;
383   struct tree_grafting_info info;
384
385   info.progress = false;
386   info.refs = &refs;
387
388   visit_list_elements(info.refs, instructions);
389
390   call_for_basic_blocks(instructions, tree_grafting_basic_block, &info);
391
392   return info.progress;
393}
394