]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/optimize.cpp
Use accurate assignment targets in ExpressionInliner
[libs/gl.git] / source / glsl / optimize.cpp
1 #include <msp/core/raii.h>
2 #include <msp/strings/format.h>
3 #include "optimize.h"
4
5 using namespace std;
6
7 namespace Msp {
8 namespace GL {
9 namespace SL {
10
11 InlineableFunctionLocator::InlineableFunctionLocator():
12         current_function(0),
13         return_count(0)
14 { }
15
16 void InlineableFunctionLocator::visit(FunctionCall &call)
17 {
18         FunctionDeclaration *def = call.declaration;
19         if(def)
20                 def = def->definition;
21
22         if(def)
23         {
24                 unsigned &count = refcounts[def];
25                 ++count;
26                 /* Don't inline functions which are called more than once or are called
27                 recursively. */
28                 if(count>1 || def==current_function)
29                         inlineable.erase(def);
30         }
31
32         TraversingVisitor::visit(call);
33 }
34
35 void InlineableFunctionLocator::visit(FunctionDeclaration &func)
36 {
37         unsigned &count = refcounts[func.definition];
38         if(count<=1 && func.parameters.empty())
39                 inlineable.insert(func.definition);
40
41         SetForScope<FunctionDeclaration *> set(current_function, &func);
42         return_count = 0;
43         TraversingVisitor::visit(func);
44 }
45
46 void InlineableFunctionLocator::visit(Conditional &cond)
47 {
48         TraversingVisitor::visit(cond);
49         inlineable.erase(current_function);
50 }
51
52 void InlineableFunctionLocator::visit(Iteration &iter)
53 {
54         TraversingVisitor::visit(iter);
55         inlineable.erase(current_function);
56 }
57
58 void InlineableFunctionLocator::visit(Return &ret)
59 {
60         TraversingVisitor::visit(ret);
61         if(return_count)
62                 inlineable.erase(current_function);
63         ++return_count;
64 }
65
66
67 InlineContentInjector::InlineContentInjector():
68         source_func(0),
69         remap_names(false),
70         deps_only(false)
71 { }
72
73 const string &InlineContentInjector::apply(Stage &stage, FunctionDeclaration &target_func, Block &tgt_blk, const NodeList<Statement>::iterator &ins_pt, FunctionDeclaration &src)
74 {
75         target_block = &tgt_blk;
76         source_func = &src;
77         for(NodeList<Statement>::iterator i=src.body.body.begin(); i!=src.body.body.end(); ++i)
78         {
79                 r_inlined_statement = 0;
80                 (*i)->visit(*this);
81                 if(!r_inlined_statement)
82                         r_inlined_statement = (*i)->clone();
83
84                 SetFlag set_remap(remap_names);
85                 r_inlined_statement->visit(*this);
86                 tgt_blk.body.insert(ins_pt, r_inlined_statement);
87         }
88
89         NodeReorderer().apply(stage, target_func, dependencies);
90
91         return r_result_name;
92 }
93
94 string InlineContentInjector::create_unused_name(const string &base, bool always_prefix)
95 {
96         string result = base;
97         if(always_prefix || target_block->variables.count(result))
98                 result = format("_%s_%s", source_func->name, base);
99         unsigned initial_size = result.size();
100         for(unsigned i=1; target_block->variables.count(result); ++i)
101         {
102                 result.erase(initial_size);
103                 result += format("_%d", i);
104         }
105         return result;
106 }
107
108 void InlineContentInjector::visit(VariableReference &var)
109 {
110         if(remap_names)
111         {
112                 map<string, VariableDeclaration *>::const_iterator i = variable_map.find(var.name);
113                 if(i!=variable_map.end())
114                         var.name = i->second->name;
115         }
116         else if(var.declaration)
117         {
118                 SetFlag set_deps(deps_only);
119                 dependencies.insert(var.declaration);
120                 var.declaration->visit(*this);
121         }
122 }
123
124 void InlineContentInjector::visit(InterfaceBlockReference &iface)
125 {
126         if(!remap_names && iface.declaration)
127         {
128                 SetFlag set_deps(deps_only);
129                 dependencies.insert(iface.declaration);
130                 iface.declaration->visit(*this);
131         }
132 }
133
134 void InlineContentInjector::visit(FunctionCall &call)
135 {
136         if(!remap_names && call.declaration)
137                 dependencies.insert(call.declaration);
138         TraversingVisitor::visit(call);
139 }
140
141 void InlineContentInjector::visit(VariableDeclaration &var)
142 {
143         TraversingVisitor::visit(var);
144
145         if(var.type_declaration)
146         {
147                 SetFlag set_deps(deps_only);
148                 dependencies.insert(var.type_declaration);
149                 var.type_declaration->visit(*this);
150         }
151
152         if(!remap_names && !deps_only)
153         {
154                 RefPtr<VariableDeclaration> inlined_var = var.clone();
155                 inlined_var->name = create_unused_name(var.name, false);
156                 r_inlined_statement = inlined_var;
157
158                 variable_map[var.name] = inlined_var.get();
159         }
160 }
161
162 void InlineContentInjector::visit(Return &ret)
163 {
164         TraversingVisitor::visit(ret);
165
166         if(ret.expression)
167         {
168                 /* Create a new variable to hold the return value of the inlined
169                 function. */
170                 r_result_name = create_unused_name("return", true);
171                 RefPtr<VariableDeclaration> var = new VariableDeclaration;
172                 var->source = ret.source;
173                 var->line = ret.line;
174                 var->type = source_func->return_type;
175                 var->name = r_result_name;
176                 var->init_expression = ret.expression->clone();
177                 r_inlined_statement = var;
178         }
179 }
180
181
182 FunctionInliner::FunctionInliner():
183         current_function(0),
184         r_any_inlined(false)
185 { }
186
187 bool FunctionInliner::apply(Stage &s)
188 {
189         stage = &s;
190         inlineable = InlineableFunctionLocator().apply(s);
191         r_any_inlined = false;
192         s.content.visit(*this);
193         return r_any_inlined;
194 }
195
196 void FunctionInliner::visit_and_inline(RefPtr<Expression> &ptr)
197 {
198         r_inline_result = 0;
199         ptr->visit(*this);
200         if(r_inline_result)
201         {
202                 ptr = r_inline_result;
203                 r_any_inlined = true;
204         }
205         r_inline_result = 0;
206 }
207
208 void FunctionInliner::visit(Block &block)
209 {
210         SetForScope<Block *> set_block(current_block, &block);
211         SetForScope<NodeList<Statement>::iterator> save_insert_point(insert_point, block.body.begin());
212         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
213         {
214                 insert_point = i;
215                 (*i)->visit(*this);
216         }
217 }
218
219 void FunctionInliner::visit(UnaryExpression &unary)
220 {
221         visit_and_inline(unary.expression);
222 }
223
224 void FunctionInliner::visit(BinaryExpression &binary)
225 {
226         visit_and_inline(binary.left);
227         visit_and_inline(binary.right);
228 }
229
230 void FunctionInliner::visit(MemberAccess &memacc)
231 {
232         visit_and_inline(memacc.left);
233 }
234
235 void FunctionInliner::visit(Swizzle &swizzle)
236 {
237         visit_and_inline(swizzle.left);
238 }
239
240 void FunctionInliner::visit(FunctionCall &call)
241 {
242         for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
243                 visit_and_inline(*i);
244
245         FunctionDeclaration *def = call.declaration;
246         if(def)
247                 def = def->definition;
248
249         if(def && inlineable.count(def))
250         {
251                 string result_name = InlineContentInjector().apply(*stage, *current_function, *current_block, insert_point, *def);
252
253                 // This will later get removed by UnusedVariableRemover.
254                 if(result_name.empty())
255                         result_name = "msp_unused_from_inline";
256
257                 RefPtr<VariableReference> ref = new VariableReference;
258                 ref->name = result_name;
259                 r_inline_result = ref;
260
261                 /* Inlined variables need to be resolved before this function can be
262                 inlined further. */
263                 inlineable.erase(current_function);
264         }
265 }
266
267 void FunctionInliner::visit(ExpressionStatement &expr)
268 {
269         visit_and_inline(expr.expression);
270 }
271
272 void FunctionInliner::visit(VariableDeclaration &var)
273 {
274         if(var.init_expression)
275                 visit_and_inline(var.init_expression);
276 }
277
278 void FunctionInliner::visit(FunctionDeclaration &func)
279 {
280         SetForScope<FunctionDeclaration *> set_func(current_function, &func);
281         TraversingVisitor::visit(func);
282 }
283
284 void FunctionInliner::visit(Conditional &cond)
285 {
286         visit_and_inline(cond.condition);
287         cond.body.visit(*this);
288 }
289
290 void FunctionInliner::visit(Iteration &iter)
291 {
292         /* Visit the initialization statement before entering the loop body so the
293         inlined statements get inserted outside. */
294         if(iter.init_statement)
295                 iter.init_statement->visit(*this);
296
297         SetForScope<Block *> set_block(current_block, &iter.body);
298         /* Skip the condition and loop expression parts because they're not properly
299         inside the body block.  Inlining anything into them will require a more
300         comprehensive transformation. */
301         iter.body.visit(*this);
302 }
303
304 void FunctionInliner::visit(Return &ret)
305 {
306         if(ret.expression)
307                 visit_and_inline(ret.expression);
308 }
309
310
311 ExpressionInliner::ExpressionInfo::ExpressionInfo():
312         expression(0),
313         assign_scope(0),
314         inline_point(0),
315         inner_oper(0),
316         outer_oper(0),
317         inline_on_rhs(false),
318         trivial(false),
319         available(true)
320 { }
321
322
323 ExpressionInliner::ExpressionInliner():
324         r_ref_info(0),
325         r_any_inlined(false),
326         r_trivial(false),
327         mutating(false),
328         iteration_init(false),
329         iteration_body(0),
330         r_oper(0)
331 { }
332
333 bool ExpressionInliner::apply(Stage &s)
334 {
335         s.content.visit(*this);
336         return r_any_inlined;
337 }
338
339 void ExpressionInliner::visit_and_record(RefPtr<Expression> &ptr, const Operator *outer_oper, bool on_rhs)
340 {
341         r_ref_info = 0;
342         ptr->visit(*this);
343         if(r_ref_info && r_ref_info->expression && r_ref_info->available)
344         {
345                 if(iteration_body && !r_ref_info->trivial)
346                 {
347                         /* Don't inline non-trivial expressions which were assigned outside
348                         an iteration statement.  The iteration may run multiple times, which
349                         would cause the expression to also be evaluated multiple times. */
350                         Block *i = r_ref_info->assign_scope;
351                         for(; (i && i!=iteration_body); i=i->parent) ;
352                         if(!i)
353                                 return;
354                 }
355
356                 r_ref_info->outer_oper = outer_oper;
357                 if(r_ref_info->trivial)
358                         inline_expression(*r_ref_info->expression, ptr, outer_oper, r_ref_info->inner_oper, on_rhs);
359                 else
360                 {
361                         /* Record the inline point for a non-trivial expression but don't
362                         inline it yet.  It might turn out it shouldn't be inlined after all. */
363                         r_ref_info->inline_point = &ptr;
364                         r_ref_info->inline_on_rhs = on_rhs;
365                 }
366         }
367         r_ref_info = 0;
368 }
369
370 void ExpressionInliner::inline_expression(Expression &expr, RefPtr<Expression> &ptr, const Operator *outer_oper, const Operator *inner_oper, bool on_rhs)
371 {
372         unsigned outer_precedence = (outer_oper ? outer_oper->precedence : 20);
373         unsigned inner_precedence = (inner_oper ? inner_oper->precedence : 0);
374
375         bool needs_parentheses = (inner_precedence>=outer_precedence);
376         if(inner_oper && inner_oper==outer_oper)
377                 // Omit parentheses if the operator's natural grouping works out.
378                 needs_parentheses = (inner_oper->assoc!=Operator::ASSOCIATIVE && on_rhs!=(inner_oper->assoc==Operator::RIGHT_TO_LEFT));
379
380         if(needs_parentheses)
381         {
382                 RefPtr<ParenthesizedExpression> parexpr = new ParenthesizedExpression;
383                 parexpr->expression = expr.clone();
384                 ptr = parexpr;
385         }
386         else
387                 ptr = expr.clone();
388
389         r_any_inlined = true;
390 }
391
392 void ExpressionInliner::visit(Block &block)
393 {
394         TraversingVisitor::visit(block);
395
396         for(map<string, VariableDeclaration *>::iterator i=block.variables.begin(); i!=block.variables.end(); ++i)
397         {
398                 map<Assignment::Target, ExpressionInfo>::iterator j = expressions.lower_bound(i->second);
399                 for(; (j!=expressions.end() && j->first.declaration==i->second); )
400                 {
401                         if(j->second.expression && j->second.inline_point)
402                                 inline_expression(*j->second.expression, *j->second.inline_point, j->second.outer_oper, j->second.inner_oper, j->second.inline_on_rhs);
403
404                         expressions.erase(j++);
405                 }
406         }
407
408         /* Expressions assigned in this block may depend on local variables of the
409         block.  If this is a conditionally executed block, the assignments might not
410         always happen.  Mark the expressions as not available to any outer blocks. */
411         for(map<Assignment::Target, ExpressionInfo>::iterator i=expressions.begin(); i!=expressions.end(); ++i)
412                 if(i->second.assign_scope==&block)
413                         i->second.available = false;
414 }
415
416 void ExpressionInliner::visit(VariableReference &var)
417 {
418         if(var.declaration)
419         {
420                 map<Assignment::Target, ExpressionInfo>::iterator i = expressions.find(var.declaration);
421                 if(i!=expressions.end())
422                 {
423                         /* If a non-trivial expression is referenced multiple times, don't
424                         inline it. */
425                         if(i->second.inline_point && !i->second.trivial)
426                                 i->second.expression = 0;
427                         /* Mutating expressions are analogous to self-referencing assignments
428                         and prevent inlining. */
429                         if(mutating)
430                                 i->second.expression = 0;
431                         r_ref_info = &i->second;
432                 }
433         }
434 }
435
436 void ExpressionInliner::visit(MemberAccess &memacc)
437 {
438         visit_and_record(memacc.left, memacc.oper, false);
439         r_oper = memacc.oper;
440         r_trivial = false;
441 }
442
443 void ExpressionInliner::visit(Swizzle &swizzle)
444 {
445         visit_and_record(swizzle.left, swizzle.oper, false);
446         r_oper = swizzle.oper;
447         r_trivial = false;
448 }
449
450 void ExpressionInliner::visit(UnaryExpression &unary)
451 {
452         SetFlag set_target(mutating, mutating || unary.oper->token[1]=='+' || unary.oper->token[1]=='-');
453         visit_and_record(unary.expression, unary.oper, false);
454         r_oper = unary.oper;
455         r_trivial = false;
456 }
457
458 void ExpressionInliner::visit(BinaryExpression &binary)
459 {
460         visit_and_record(binary.left, binary.oper, false);
461         {
462                 SetFlag clear_target(mutating, false);
463                 visit_and_record(binary.right, binary.oper, true);
464         }
465         r_oper = binary.oper;
466         r_trivial = false;
467 }
468
469 void ExpressionInliner::visit(Assignment &assign)
470 {
471         {
472                 SetFlag set_target(mutating);
473                 visit_and_record(assign.left, assign.oper, false);
474         }
475         r_oper = 0;
476         visit_and_record(assign.right, assign.oper, true);
477
478         map<Assignment::Target, ExpressionInfo>::iterator i = expressions.find(assign.target);
479         if(i!=expressions.end())
480         {
481                 /* Self-referencing assignments can't be inlined without additional
482                 work.  Just clear any previous expression. */
483                 i->second.expression = (assign.self_referencing ? 0 : assign.right.get());
484                 i->second.assign_scope = current_block;
485                 i->second.inline_point = 0;
486                 i->second.inner_oper = r_oper;
487                 i->second.available = true;
488         }
489
490         r_oper = assign.oper;
491         r_trivial = false;
492 }
493
494 void ExpressionInliner::visit(FunctionCall &call)
495 {
496         for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
497                 visit_and_record(*i, 0, false);
498         r_oper = 0;
499         r_trivial = false;
500 }
501
502 void ExpressionInliner::visit(VariableDeclaration &var)
503 {
504         r_oper = 0;
505         r_trivial = true;
506         if(var.init_expression)
507                 visit_and_record(var.init_expression, 0, false);
508
509         bool constant = var.constant;
510         if(constant && var.layout)
511         {
512                 for(vector<Layout::Qualifier>::const_iterator i=var.layout->qualifiers.begin(); (constant && i!=var.layout->qualifiers.end()); ++i)
513                         constant = (i->name!="constant_id");
514         }
515
516         /* Only inline global variables if they're constant and have trivial
517         initializers.  Non-constant variables could change in ways which are hard to
518         analyze and non-trivial expressions could be expensive to inline.  */
519         if((current_block->parent || (constant && r_trivial)) && var.interface.empty())
520         {
521                 ExpressionInfo &info = expressions[&var];
522                 /* Assume variables declared in an iteration initialization statement
523                 will have their values change throughout the iteration. */
524                 info.expression = (iteration_init ? 0 : var.init_expression.get());
525                 info.assign_scope = current_block;
526                 info.inner_oper = r_oper;
527                 info.trivial = r_trivial;
528         }
529 }
530
531 void ExpressionInliner::visit(Conditional &cond)
532 {
533         visit_and_record(cond.condition, 0, false);
534         cond.body.visit(*this);
535 }
536
537 void ExpressionInliner::visit(Iteration &iter)
538 {
539         SetForScope<Block *> set_block(current_block, &iter.body);
540         if(iter.init_statement)
541         {
542                 SetFlag set_init(iteration_init);
543                 iter.init_statement->visit(*this);
544         }
545
546         SetForScope<Block *> set_body(iteration_body, &iter.body);
547         if(iter.condition)
548                 iter.condition->visit(*this);
549         iter.body.visit(*this);
550         if(iter.loop_expression)
551                 iter.loop_expression->visit(*this);
552 }
553
554 void ExpressionInliner::visit(Return &ret)
555 {
556         if(ret.expression)
557                 visit_and_record(ret.expression, 0, false);
558 }
559
560
561 void ConstantConditionEliminator::apply(Stage &stage)
562 {
563         stage.content.visit(*this);
564         NodeRemover().apply(stage, nodes_to_remove);
565 }
566
567 void ConstantConditionEliminator::visit(Block &block)
568 {
569         SetForScope<Block *> set_block(current_block, &block);
570         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
571         {
572                 insert_point = i;
573                 (*i)->visit(*this);
574         }
575 }
576
577 void ConstantConditionEliminator::visit(Conditional &cond)
578 {
579         ExpressionEvaluator eval;
580         cond.condition->visit(eval);
581         if(eval.is_result_valid())
582         {
583                 Block &block = (eval.get_result() ? cond.body : cond.else_body);
584                 current_block->body.splice(insert_point, block.body);
585                 nodes_to_remove.insert(&cond);
586                 return;
587         }
588
589         TraversingVisitor::visit(cond);
590 }
591
592 void ConstantConditionEliminator::visit(Iteration &iter)
593 {
594         if(iter.condition)
595         {
596                 /* If the loop condition is always false on the first iteration, the
597                 entire loop can be removed */
598                 ExpressionEvaluator::ValueMap values;
599                 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(iter.init_statement.get()))
600                         values[var] = var->init_expression.get();
601                 ExpressionEvaluator eval(values);
602                 iter.condition->visit(eval);
603                 if(eval.is_result_valid() && !eval.get_result())
604                 {
605                         nodes_to_remove.insert(&iter);
606                         return;
607                 }
608         }
609
610         TraversingVisitor::visit(iter);
611 }
612
613
614 UnusedVariableRemover::VariableInfo::VariableInfo():
615         local(false),
616         output(false),
617         conditionally_assigned(false),
618         referenced(false),
619         interface_block(0)
620 { }
621
622
623 bool UnusedTypeRemover::apply(Stage &stage)
624 {
625         stage.content.visit(*this);
626         NodeRemover().apply(stage, unused_nodes);
627         return !unused_nodes.empty();
628 }
629
630 void UnusedTypeRemover::visit(Literal &literal)
631 {
632         unused_nodes.erase(literal.type);
633 }
634
635 void UnusedTypeRemover::visit(UnaryExpression &unary)
636 {
637         unused_nodes.erase(unary.type);
638         TraversingVisitor::visit(unary);
639 }
640
641 void UnusedTypeRemover::visit(BinaryExpression &binary)
642 {
643         unused_nodes.erase(binary.type);
644         TraversingVisitor::visit(binary);
645 }
646
647 void UnusedTypeRemover::visit(FunctionCall &call)
648 {
649         unused_nodes.erase(call.type);
650         TraversingVisitor::visit(call);
651 }
652
653 void UnusedTypeRemover::visit(BasicTypeDeclaration &type)
654 {
655         if(type.base_type)
656                 unused_nodes.erase(type.base_type);
657         unused_nodes.insert(&type);
658 }
659
660 void UnusedTypeRemover::visit(ImageTypeDeclaration &type)
661 {
662         if(type.base_type)
663                 unused_nodes.erase(type.base_type);
664         unused_nodes.insert(&type);
665 }
666
667 void UnusedTypeRemover::visit(StructDeclaration &strct)
668 {
669         unused_nodes.insert(&strct);
670         TraversingVisitor::visit(strct);
671 }
672
673 void UnusedTypeRemover::visit(VariableDeclaration &var)
674 {
675         unused_nodes.erase(var.type_declaration);
676 }
677
678 void UnusedTypeRemover::visit(InterfaceBlock &iface)
679 {
680         unused_nodes.erase(iface.type_declaration);
681 }
682
683 void UnusedTypeRemover::visit(FunctionDeclaration &func)
684 {
685         unused_nodes.erase(func.return_type_declaration);
686         TraversingVisitor::visit(func);
687 }
688
689
690 UnusedVariableRemover::UnusedVariableRemover():
691         stage(0),
692         interface_block(0),
693         r_assignment(0),
694         assignment_target(false),
695         r_side_effects(false)
696 { }
697
698 bool UnusedVariableRemover::apply(Stage &s)
699 {
700         stage = &s;
701         variables.push_back(BlockVariableMap());
702         s.content.visit(*this);
703
704         BlockVariableMap &global_variables = variables.back();
705         set<InterfaceBlock *> used_interface_blocks;
706         Statement *prev_decl = 0;
707         bool output;
708         for(BlockVariableMap::iterator i=global_variables.begin(); i!=global_variables.end(); ++i)
709         {
710                 if(i->first.declaration!=prev_decl)
711                 {
712                         prev_decl = i->first.declaration;
713                         output = i->second.output;
714                 }
715                 if(output)
716                 {
717                         if(!i->second.assignments.empty() && i->second.interface_block)
718                                 used_interface_blocks.insert(i->second.interface_block);
719                         continue;
720                 }
721
722                 // Mark other unreferenced global variables as unused.
723                 if(!i->second.referenced)
724                 {
725                         if(!i->second.interface_block && !i->first.chain_len)
726                                 unused_nodes.insert(i->first.declaration);
727                         clear_assignments(i->second, true);
728                 }
729                 else if(i->second.interface_block)
730                         used_interface_blocks.insert(i->second.interface_block);
731         }
732         variables.pop_back();
733
734         for(map<string, InterfaceBlock *>::const_iterator i=s.interface_blocks.begin(); i!=s.interface_blocks.end(); ++i)
735                 if(i->second->instance_name.empty() && !used_interface_blocks.count(i->second))
736                         unused_nodes.insert(i->second);
737
738         NodeRemover().apply(s, unused_nodes);
739
740         return !unused_nodes.empty();
741 }
742
743 void UnusedVariableRemover::reference_used(Statement &declaration)
744 {
745         BlockVariableMap &block_vars = variables.back();
746         /* Previous assignments of all subfields of this variable are used by
747         this reference. */
748         for(BlockVariableMap::iterator i=block_vars.lower_bound(&declaration); (i!=block_vars.end() && i->first.declaration==&declaration); ++i)
749         {
750                 clear_assignments(i->second, false);
751                 i->second.referenced = true;
752         }
753
754         // Always record a reference to the primary declaration, even if it didn't exist before
755         block_vars[&declaration].referenced = true;
756 }
757
758 void UnusedVariableRemover::visit(VariableReference &var)
759 {
760         if(var.declaration && !assignment_target)
761                 reference_used(*var.declaration);
762 }
763
764 void UnusedVariableRemover::visit(InterfaceBlockReference &iface)
765 {
766         if(iface.declaration && !assignment_target)
767                 reference_used(*iface.declaration);
768 }
769
770 void UnusedVariableRemover::visit(UnaryExpression &unary)
771 {
772         TraversingVisitor::visit(unary);
773         if(unary.oper->token[1]=='+' || unary.oper->token[1]=='-')
774                 r_side_effects = true;
775 }
776
777 void UnusedVariableRemover::visit(BinaryExpression &binary)
778 {
779         if(binary.oper->token[0]=='[')
780         {
781                 binary.left->visit(*this);
782                 SetFlag set(assignment_target, false);
783                 binary.right->visit(*this);
784         }
785         else
786                 TraversingVisitor::visit(binary);
787 }
788
789 void UnusedVariableRemover::visit(Assignment &assign)
790 {
791         {
792                 SetFlag set(assignment_target, !assign.self_referencing);
793                 assign.left->visit(*this);
794         }
795         assign.right->visit(*this);
796         r_assignment = &assign;
797         r_side_effects = true;
798 }
799
800 void UnusedVariableRemover::visit(FunctionCall &call)
801 {
802         TraversingVisitor::visit(call);
803         /* Treat function calls as having side effects so expression statements
804         consisting of nothing but a function call won't be optimized away. */
805         r_side_effects = true;
806 }
807
808 void UnusedVariableRemover::record_assignment(const Assignment::Target &target, Node &node, bool chained)
809 {
810         BlockVariableMap &block_vars = variables.back();
811         for(BlockVariableMap::iterator i=block_vars.lower_bound(target); (i!=block_vars.end() && i->first.declaration==target.declaration); ++i)
812         {
813                 bool subfield = (i->first.chain_len>=target.chain_len);
814                 for(unsigned j=0; (subfield && j<target.chain_len); ++j)
815                         subfield = (i->first.chain[j]==target.chain[j]);
816                 if(!subfield)
817                         break;
818
819                 /* An assignment to the target causes any previous unreferenced
820                 assignments to the same target or its subfields to be unused. */
821                 if(!chained)
822                         clear_assignments(i->second, true);
823         }
824
825         VariableInfo &var_info = variables.back()[target];
826         var_info.assignments.push_back(&node);
827         var_info.conditionally_assigned = false;
828 }
829
830 void UnusedVariableRemover::clear_assignments(VariableInfo &var_info, bool mark_unused)
831 {
832         if(mark_unused)
833         {
834                 for(vector<Node *>::iterator i=var_info.assignments.begin(); i!=var_info.assignments.end(); ++i)
835                         unused_nodes.insert(*i);
836         }
837         var_info.assignments.clear();
838 }
839
840 void UnusedVariableRemover::visit(ExpressionStatement &expr)
841 {
842         r_assignment = 0;
843         r_side_effects = false;
844         TraversingVisitor::visit(expr);
845         if(r_assignment && r_assignment->target.declaration)
846                 record_assignment(r_assignment->target, expr, r_assignment->self_referencing);
847         if(!r_side_effects)
848                 unused_nodes.insert(&expr);
849 }
850
851 void UnusedVariableRemover::visit(VariableDeclaration &var)
852 {
853         VariableInfo &var_info = variables.back()[&var];
854         var_info.local = true;
855         var_info.interface_block = interface_block;
856
857         /* Mark variables as output if they're used by the next stage or the
858         graphics API. */
859         if(interface_block)
860                 var_info.output = (interface_block->interface=="out" && (interface_block->linked_block || !interface_block->name.compare(0, 3, "gl_")));
861         else
862                 var_info.output = (var.interface=="out" && (stage->type==Stage::FRAGMENT || var.linked_declaration || !var.name.compare(0, 3, "gl_")));
863
864         if(var.init_expression)
865                 record_assignment(&var, *var.init_expression, false);
866         TraversingVisitor::visit(var);
867 }
868
869 void UnusedVariableRemover::visit(InterfaceBlock &iface)
870 {
871         if(iface.instance_name.empty())
872         {
873                 SetForScope<InterfaceBlock *> set_block(interface_block, &iface);
874                 iface.struct_declaration->members.visit(*this);
875         }
876         else
877         {
878                 VariableInfo &var_info = variables.back()[&iface];
879                 var_info.local = true;
880                 var_info.output = (iface.interface=="out" && (iface.linked_block || !iface.name.compare(0, 3, "gl_")));
881         }
882 }
883
884 void UnusedVariableRemover::visit(FunctionDeclaration &func)
885 {
886         variables.push_back(BlockVariableMap());
887
888         for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
889                 (*i)->visit(*this);
890         func.body.visit(*this);
891
892         BlockVariableMap &block_variables = variables.back();
893
894         /* Mark global variables as conditionally assigned so assignments in other
895         functions won't be removed. */
896         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
897                 if(!i->second.local)
898                         i->second.conditionally_assigned = true;
899
900         /* Always treat function parameters as referenced.  Removing unused
901         parameters is not currently supported. */
902         for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
903                 block_variables[i->get()].referenced = true;
904
905         merge_down_variables();
906 }
907
908 void UnusedVariableRemover::merge_down_variables()
909 {
910         BlockVariableMap &parent_variables = variables[variables.size()-2];
911         BlockVariableMap &block_variables = variables.back();
912         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
913         {
914                 if(i->second.local)
915                 {
916                         if(!i->second.referenced && !i->first.chain_len)
917                                 unused_nodes.insert(i->first.declaration);
918                         /* Any unreferenced assignments when a variable runs out of scope
919                         become unused. */
920                         clear_assignments(i->second, true);
921                         continue;
922                 }
923
924                 BlockVariableMap::iterator j = parent_variables.find(i->first);
925                 if(j==parent_variables.end())
926                         parent_variables.insert(*i);
927                 else
928                 {
929                         // Merge a non-local variable's state into the parent scope.
930                         if(i->second.referenced || !i->second.conditionally_assigned)
931                                 clear_assignments(j->second, !i->second.referenced);
932                         j->second.conditionally_assigned = i->second.conditionally_assigned;
933                         j->second.referenced |= i->second.referenced;
934                         j->second.assignments.insert(j->second.assignments.end(), i->second.assignments.begin(), i->second.assignments.end());
935                 }
936         }
937         variables.pop_back();
938 }
939
940 void UnusedVariableRemover::visit(Conditional &cond)
941 {
942         cond.condition->visit(*this);
943         variables.push_back(BlockVariableMap());
944         cond.body.visit(*this);
945
946         BlockVariableMap if_variables;
947         swap(variables.back(), if_variables);
948         cond.else_body.visit(*this);
949
950         // Combine variables from both branches.
951         BlockVariableMap &else_variables = variables.back();
952         for(BlockVariableMap::iterator i=else_variables.begin(); i!=else_variables.end(); ++i)
953         {
954                 BlockVariableMap::iterator j = if_variables.find(i->first);
955                 if(j!=if_variables.end())
956                 {
957                         // The variable was found in both branches.
958                         i->second.assignments.insert(i->second.assignments.end(), j->second.assignments.begin(), j->second.assignments.end());
959                         i->second.conditionally_assigned |= j->second.conditionally_assigned;
960                         if_variables.erase(j);
961                 }
962                 else
963                         // Mark variables found in only one branch as conditionally assigned.
964                         i->second.conditionally_assigned = true;
965         }
966
967         /* Move variables which were only used in the if block into the combined
968         block. */
969         for(BlockVariableMap::iterator i=if_variables.begin(); i!=if_variables.end(); ++i)
970         {
971                 i->second.conditionally_assigned = true;
972                 else_variables.insert(*i);
973         }
974
975         merge_down_variables();
976 }
977
978 void UnusedVariableRemover::visit(Iteration &iter)
979 {
980         variables.push_back(BlockVariableMap());
981         TraversingVisitor::visit(iter);
982         merge_down_variables();
983 }
984
985
986 bool UnusedFunctionRemover::apply(Stage &stage)
987 {
988         stage.content.visit(*this);
989         NodeRemover().apply(stage, unused_nodes);
990         return !unused_nodes.empty();
991 }
992
993 void UnusedFunctionRemover::visit(FunctionCall &call)
994 {
995         TraversingVisitor::visit(call);
996
997         unused_nodes.erase(call.declaration);
998         if(call.declaration && call.declaration->definition!=call.declaration)
999                 used_definitions.insert(call.declaration->definition);
1000 }
1001
1002 void UnusedFunctionRemover::visit(FunctionDeclaration &func)
1003 {
1004         TraversingVisitor::visit(func);
1005
1006         if((func.name!="main" || func.body.body.empty()) && !used_definitions.count(&func))
1007                 unused_nodes.insert(&func);
1008 }
1009
1010 } // namespace SL
1011 } // namespace GL
1012 } // namespace Msp