]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/optimize.cpp
215466b2a8390425ea7d440dec710c14d5bb17c0
[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<VariableDeclaration *, ExpressionInfo>::iterator i=expressions.begin(); i!=expressions.end(); )
397         {
398                 map<string, VariableDeclaration *>::iterator j = block.variables.find(i->first->name);
399                 if(j!=block.variables.end() && j->second==i->first)
400                 {
401                         if(i->second.expression && i->second.inline_point)
402                                 inline_expression(*i->second.expression, *i->second.inline_point, i->second.outer_oper, i->second.inner_oper, i->second.inline_on_rhs);
403
404                         expressions.erase(i++);
405                 }
406                 else
407                 {
408                         /* The expression was assigned in this block and may depend on local
409                         variables of the block.  If this is a conditionally executed block,
410                         the assignment might not always happen.  Mark the expression as not
411                         available to any outer blocks. */
412                         if(i->second.assign_scope==&block)
413                                 i->second.available = false;
414
415                         ++i;
416                 }
417         }
418 }
419
420 void ExpressionInliner::visit(VariableReference &var)
421 {
422         if(var.declaration)
423         {
424                 map<VariableDeclaration *, ExpressionInfo>::iterator i = expressions.find(var.declaration);
425                 if(i!=expressions.end())
426                 {
427                         /* If a non-trivial expression is referenced multiple times, don't
428                         inline it. */
429                         if(i->second.inline_point && !i->second.trivial)
430                                 i->second.expression = 0;
431                         /* Mutating expressions are analogous to self-referencing assignments
432                         and prevent inlining. */
433                         if(mutating)
434                                 i->second.expression = 0;
435                         r_ref_info = &i->second;
436                 }
437         }
438 }
439
440 void ExpressionInliner::visit(MemberAccess &memacc)
441 {
442         visit_and_record(memacc.left, memacc.oper, false);
443         r_oper = memacc.oper;
444         r_trivial = false;
445 }
446
447 void ExpressionInliner::visit(Swizzle &swizzle)
448 {
449         visit_and_record(swizzle.left, swizzle.oper, false);
450         r_oper = swizzle.oper;
451         r_trivial = false;
452 }
453
454 void ExpressionInliner::visit(UnaryExpression &unary)
455 {
456         SetFlag set_target(mutating, mutating || unary.oper->token[1]=='+' || unary.oper->token[1]=='-');
457         visit_and_record(unary.expression, unary.oper, false);
458         r_oper = unary.oper;
459         r_trivial = false;
460 }
461
462 void ExpressionInliner::visit(BinaryExpression &binary)
463 {
464         visit_and_record(binary.left, binary.oper, false);
465         {
466                 SetFlag clear_target(mutating, false);
467                 visit_and_record(binary.right, binary.oper, true);
468         }
469         r_oper = binary.oper;
470         r_trivial = false;
471 }
472
473 void ExpressionInliner::visit(Assignment &assign)
474 {
475         {
476                 SetFlag set_target(mutating);
477                 visit_and_record(assign.left, assign.oper, false);
478         }
479         r_oper = 0;
480         visit_and_record(assign.right, assign.oper, true);
481
482         if(VariableDeclaration *target_var = dynamic_cast<VariableDeclaration *>(assign.target.declaration))
483         {
484                 map<VariableDeclaration *, ExpressionInfo>::iterator i = expressions.find(target_var);
485                 if(i!=expressions.end())
486                 {
487                         /* Self-referencing assignments can't be inlined without additional
488                         work.  Just clear any previous expression. */
489                         i->second.expression = (assign.self_referencing ? 0 : assign.right.get());
490                         i->second.assign_scope = current_block;
491                         i->second.inline_point = 0;
492                         i->second.inner_oper = r_oper;
493                         i->second.available = true;
494                 }
495         }
496
497         r_oper = assign.oper;
498         r_trivial = false;
499 }
500
501 void ExpressionInliner::visit(FunctionCall &call)
502 {
503         for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
504                 visit_and_record(*i, 0, false);
505         r_oper = 0;
506         r_trivial = false;
507 }
508
509 void ExpressionInliner::visit(VariableDeclaration &var)
510 {
511         r_oper = 0;
512         r_trivial = true;
513         if(var.init_expression)
514                 visit_and_record(var.init_expression, 0, false);
515
516         bool constant = var.constant;
517         if(constant && var.layout)
518         {
519                 for(vector<Layout::Qualifier>::const_iterator i=var.layout->qualifiers.begin(); (constant && i!=var.layout->qualifiers.end()); ++i)
520                         constant = (i->name!="constant_id");
521         }
522
523         /* Only inline global variables if they're constant and have trivial
524         initializers.  Non-constant variables could change in ways which are hard to
525         analyze and non-trivial expressions could be expensive to inline.  */
526         if((current_block->parent || (constant && r_trivial)) && var.interface.empty())
527         {
528                 ExpressionInfo &info = expressions[&var];
529                 /* Assume variables declared in an iteration initialization statement
530                 will have their values change throughout the iteration. */
531                 info.expression = (iteration_init ? 0 : var.init_expression.get());
532                 info.assign_scope = current_block;
533                 info.inner_oper = r_oper;
534                 info.trivial = r_trivial;
535         }
536 }
537
538 void ExpressionInliner::visit(Conditional &cond)
539 {
540         visit_and_record(cond.condition, 0, false);
541         cond.body.visit(*this);
542 }
543
544 void ExpressionInliner::visit(Iteration &iter)
545 {
546         SetForScope<Block *> set_block(current_block, &iter.body);
547         if(iter.init_statement)
548         {
549                 SetFlag set_init(iteration_init);
550                 iter.init_statement->visit(*this);
551         }
552
553         SetForScope<Block *> set_body(iteration_body, &iter.body);
554         if(iter.condition)
555                 iter.condition->visit(*this);
556         iter.body.visit(*this);
557         if(iter.loop_expression)
558                 iter.loop_expression->visit(*this);
559 }
560
561 void ExpressionInliner::visit(Return &ret)
562 {
563         if(ret.expression)
564                 visit_and_record(ret.expression, 0, false);
565 }
566
567
568 void ConstantConditionEliminator::apply(Stage &stage)
569 {
570         stage.content.visit(*this);
571         NodeRemover().apply(stage, nodes_to_remove);
572 }
573
574 void ConstantConditionEliminator::visit(Block &block)
575 {
576         SetForScope<Block *> set_block(current_block, &block);
577         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
578         {
579                 insert_point = i;
580                 (*i)->visit(*this);
581         }
582 }
583
584 void ConstantConditionEliminator::visit(Conditional &cond)
585 {
586         ExpressionEvaluator eval;
587         cond.condition->visit(eval);
588         if(eval.is_result_valid())
589         {
590                 Block &block = (eval.get_result() ? cond.body : cond.else_body);
591                 current_block->body.splice(insert_point, block.body);
592                 nodes_to_remove.insert(&cond);
593                 return;
594         }
595
596         TraversingVisitor::visit(cond);
597 }
598
599 void ConstantConditionEliminator::visit(Iteration &iter)
600 {
601         if(iter.condition)
602         {
603                 /* If the loop condition is always false on the first iteration, the
604                 entire loop can be removed */
605                 ExpressionEvaluator::ValueMap values;
606                 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(iter.init_statement.get()))
607                         values[var] = var->init_expression.get();
608                 ExpressionEvaluator eval(values);
609                 iter.condition->visit(eval);
610                 if(eval.is_result_valid() && !eval.get_result())
611                 {
612                         nodes_to_remove.insert(&iter);
613                         return;
614                 }
615         }
616
617         TraversingVisitor::visit(iter);
618 }
619
620
621 UnusedVariableRemover::VariableInfo::VariableInfo():
622         local(false),
623         output(false),
624         conditionally_assigned(false),
625         referenced(false),
626         interface_block(0)
627 { }
628
629
630 bool UnusedTypeRemover::apply(Stage &stage)
631 {
632         stage.content.visit(*this);
633         NodeRemover().apply(stage, unused_nodes);
634         return !unused_nodes.empty();
635 }
636
637 void UnusedTypeRemover::visit(Literal &literal)
638 {
639         unused_nodes.erase(literal.type);
640 }
641
642 void UnusedTypeRemover::visit(UnaryExpression &unary)
643 {
644         unused_nodes.erase(unary.type);
645         TraversingVisitor::visit(unary);
646 }
647
648 void UnusedTypeRemover::visit(BinaryExpression &binary)
649 {
650         unused_nodes.erase(binary.type);
651         TraversingVisitor::visit(binary);
652 }
653
654 void UnusedTypeRemover::visit(FunctionCall &call)
655 {
656         unused_nodes.erase(call.type);
657         TraversingVisitor::visit(call);
658 }
659
660 void UnusedTypeRemover::visit(BasicTypeDeclaration &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(ImageTypeDeclaration &type)
668 {
669         if(type.base_type)
670                 unused_nodes.erase(type.base_type);
671         unused_nodes.insert(&type);
672 }
673
674 void UnusedTypeRemover::visit(StructDeclaration &strct)
675 {
676         unused_nodes.insert(&strct);
677         TraversingVisitor::visit(strct);
678 }
679
680 void UnusedTypeRemover::visit(VariableDeclaration &var)
681 {
682         unused_nodes.erase(var.type_declaration);
683 }
684
685 void UnusedTypeRemover::visit(InterfaceBlock &iface)
686 {
687         unused_nodes.erase(iface.type_declaration);
688 }
689
690 void UnusedTypeRemover::visit(FunctionDeclaration &func)
691 {
692         unused_nodes.erase(func.return_type_declaration);
693         TraversingVisitor::visit(func);
694 }
695
696
697 UnusedVariableRemover::UnusedVariableRemover():
698         stage(0),
699         interface_block(0),
700         r_assignment(0),
701         assignment_target(false),
702         r_side_effects(false)
703 { }
704
705 bool UnusedVariableRemover::apply(Stage &s)
706 {
707         stage = &s;
708         variables.push_back(BlockVariableMap());
709         s.content.visit(*this);
710
711         BlockVariableMap &global_variables = variables.back();
712         set<InterfaceBlock *> used_interface_blocks;
713         Statement *prev_decl = 0;
714         bool output;
715         for(BlockVariableMap::iterator i=global_variables.begin(); i!=global_variables.end(); ++i)
716         {
717                 if(i->first.declaration!=prev_decl)
718                 {
719                         prev_decl = i->first.declaration;
720                         output = i->second.output;
721                 }
722                 if(output)
723                 {
724                         if(!i->second.assignments.empty() && i->second.interface_block)
725                                 used_interface_blocks.insert(i->second.interface_block);
726                         continue;
727                 }
728
729                 // Mark other unreferenced global variables as unused.
730                 if(!i->second.referenced)
731                 {
732                         if(!i->second.interface_block && !i->first.chain_len)
733                                 unused_nodes.insert(i->first.declaration);
734                         clear_assignments(i->second, true);
735                 }
736                 else if(i->second.interface_block)
737                         used_interface_blocks.insert(i->second.interface_block);
738         }
739         variables.pop_back();
740
741         for(map<string, InterfaceBlock *>::const_iterator i=s.interface_blocks.begin(); i!=s.interface_blocks.end(); ++i)
742                 if(i->second->instance_name.empty() && !used_interface_blocks.count(i->second))
743                         unused_nodes.insert(i->second);
744
745         NodeRemover().apply(s, unused_nodes);
746
747         return !unused_nodes.empty();
748 }
749
750 void UnusedVariableRemover::reference_used(Statement &declaration)
751 {
752         BlockVariableMap &block_vars = variables.back();
753         /* Previous assignments of all subfields of this variable are used by
754         this reference. */
755         for(BlockVariableMap::iterator i=block_vars.lower_bound(&declaration); (i!=block_vars.end() && i->first.declaration==&declaration); ++i)
756         {
757                 clear_assignments(i->second, false);
758                 i->second.referenced = true;
759         }
760
761         // Always record a reference to the primary declaration, even if it didn't exist before
762         block_vars[&declaration].referenced = true;
763 }
764
765 void UnusedVariableRemover::visit(VariableReference &var)
766 {
767         if(var.declaration && !assignment_target)
768                 reference_used(*var.declaration);
769 }
770
771 void UnusedVariableRemover::visit(InterfaceBlockReference &iface)
772 {
773         if(iface.declaration && !assignment_target)
774                 reference_used(*iface.declaration);
775 }
776
777 void UnusedVariableRemover::visit(UnaryExpression &unary)
778 {
779         TraversingVisitor::visit(unary);
780         if(unary.oper->token[1]=='+' || unary.oper->token[1]=='-')
781                 r_side_effects = true;
782 }
783
784 void UnusedVariableRemover::visit(BinaryExpression &binary)
785 {
786         if(binary.oper->token[0]=='[')
787         {
788                 binary.left->visit(*this);
789                 SetFlag set(assignment_target, false);
790                 binary.right->visit(*this);
791         }
792         else
793                 TraversingVisitor::visit(binary);
794 }
795
796 void UnusedVariableRemover::visit(Assignment &assign)
797 {
798         {
799                 SetFlag set(assignment_target, !assign.self_referencing);
800                 assign.left->visit(*this);
801         }
802         assign.right->visit(*this);
803         r_assignment = &assign;
804         r_side_effects = true;
805 }
806
807 void UnusedVariableRemover::visit(FunctionCall &call)
808 {
809         TraversingVisitor::visit(call);
810         /* Treat function calls as having side effects so expression statements
811         consisting of nothing but a function call won't be optimized away. */
812         r_side_effects = true;
813 }
814
815 void UnusedVariableRemover::record_assignment(const Assignment::Target &target, Node &node, bool chained)
816 {
817         BlockVariableMap &block_vars = variables.back();
818         for(BlockVariableMap::iterator i=block_vars.lower_bound(target); (i!=block_vars.end() && i->first.declaration==target.declaration); ++i)
819         {
820                 bool subfield = (i->first.chain_len>=target.chain_len);
821                 for(unsigned j=0; (subfield && j<target.chain_len); ++j)
822                         subfield = (i->first.chain[j]==target.chain[j]);
823                 if(!subfield)
824                         break;
825
826                 /* An assignment to the target causes any previous unreferenced
827                 assignments to the same target or its subfields to be unused. */
828                 if(!chained)
829                         clear_assignments(i->second, true);
830         }
831
832         VariableInfo &var_info = variables.back()[target];
833         var_info.assignments.push_back(&node);
834         var_info.conditionally_assigned = false;
835 }
836
837 void UnusedVariableRemover::clear_assignments(VariableInfo &var_info, bool mark_unused)
838 {
839         if(mark_unused)
840         {
841                 for(vector<Node *>::iterator i=var_info.assignments.begin(); i!=var_info.assignments.end(); ++i)
842                         unused_nodes.insert(*i);
843         }
844         var_info.assignments.clear();
845 }
846
847 void UnusedVariableRemover::visit(ExpressionStatement &expr)
848 {
849         r_assignment = 0;
850         r_side_effects = false;
851         TraversingVisitor::visit(expr);
852         if(r_assignment && r_assignment->target.declaration)
853                 record_assignment(r_assignment->target, expr, r_assignment->self_referencing);
854         if(!r_side_effects)
855                 unused_nodes.insert(&expr);
856 }
857
858 void UnusedVariableRemover::visit(VariableDeclaration &var)
859 {
860         VariableInfo &var_info = variables.back()[&var];
861         var_info.local = true;
862         var_info.interface_block = interface_block;
863
864         /* Mark variables as output if they're used by the next stage or the
865         graphics API. */
866         if(interface_block)
867                 var_info.output = (interface_block->interface=="out" && (interface_block->linked_block || !interface_block->name.compare(0, 3, "gl_")));
868         else
869                 var_info.output = (var.interface=="out" && (stage->type==Stage::FRAGMENT || var.linked_declaration || !var.name.compare(0, 3, "gl_")));
870
871         if(var.init_expression)
872                 record_assignment(&var, *var.init_expression, false);
873         TraversingVisitor::visit(var);
874 }
875
876 void UnusedVariableRemover::visit(InterfaceBlock &iface)
877 {
878         if(iface.instance_name.empty())
879         {
880                 SetForScope<InterfaceBlock *> set_block(interface_block, &iface);
881                 iface.struct_declaration->members.visit(*this);
882         }
883         else
884         {
885                 VariableInfo &var_info = variables.back()[&iface];
886                 var_info.local = true;
887                 var_info.output = (iface.interface=="out" && (iface.linked_block || !iface.name.compare(0, 3, "gl_")));
888         }
889 }
890
891 void UnusedVariableRemover::visit(FunctionDeclaration &func)
892 {
893         variables.push_back(BlockVariableMap());
894
895         for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
896                 (*i)->visit(*this);
897         func.body.visit(*this);
898
899         BlockVariableMap &block_variables = variables.back();
900
901         /* Mark global variables as conditionally assigned so assignments in other
902         functions won't be removed. */
903         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
904                 if(!i->second.local)
905                         i->second.conditionally_assigned = true;
906
907         /* Always treat function parameters as referenced.  Removing unused
908         parameters is not currently supported. */
909         for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
910                 block_variables[i->get()].referenced = true;
911
912         merge_down_variables();
913 }
914
915 void UnusedVariableRemover::merge_down_variables()
916 {
917         BlockVariableMap &parent_variables = variables[variables.size()-2];
918         BlockVariableMap &block_variables = variables.back();
919         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
920         {
921                 if(i->second.local)
922                 {
923                         if(!i->second.referenced && !i->first.chain_len)
924                                 unused_nodes.insert(i->first.declaration);
925                         /* Any unreferenced assignments when a variable runs out of scope
926                         become unused. */
927                         clear_assignments(i->second, true);
928                         continue;
929                 }
930
931                 BlockVariableMap::iterator j = parent_variables.find(i->first);
932                 if(j==parent_variables.end())
933                         parent_variables.insert(*i);
934                 else
935                 {
936                         // Merge a non-local variable's state into the parent scope.
937                         if(i->second.referenced || !i->second.conditionally_assigned)
938                                 clear_assignments(j->second, !i->second.referenced);
939                         j->second.conditionally_assigned = i->second.conditionally_assigned;
940                         j->second.referenced |= i->second.referenced;
941                         j->second.assignments.insert(j->second.assignments.end(), i->second.assignments.begin(), i->second.assignments.end());
942                 }
943         }
944         variables.pop_back();
945 }
946
947 void UnusedVariableRemover::visit(Conditional &cond)
948 {
949         cond.condition->visit(*this);
950         variables.push_back(BlockVariableMap());
951         cond.body.visit(*this);
952
953         BlockVariableMap if_variables;
954         swap(variables.back(), if_variables);
955         cond.else_body.visit(*this);
956
957         // Combine variables from both branches.
958         BlockVariableMap &else_variables = variables.back();
959         for(BlockVariableMap::iterator i=else_variables.begin(); i!=else_variables.end(); ++i)
960         {
961                 BlockVariableMap::iterator j = if_variables.find(i->first);
962                 if(j!=if_variables.end())
963                 {
964                         // The variable was found in both branches.
965                         i->second.assignments.insert(i->second.assignments.end(), j->second.assignments.begin(), j->second.assignments.end());
966                         i->second.conditionally_assigned |= j->second.conditionally_assigned;
967                         if_variables.erase(j);
968                 }
969                 else
970                         // Mark variables found in only one branch as conditionally assigned.
971                         i->second.conditionally_assigned = true;
972         }
973
974         /* Move variables which were only used in the if block into the combined
975         block. */
976         for(BlockVariableMap::iterator i=if_variables.begin(); i!=if_variables.end(); ++i)
977         {
978                 i->second.conditionally_assigned = true;
979                 else_variables.insert(*i);
980         }
981
982         merge_down_variables();
983 }
984
985 void UnusedVariableRemover::visit(Iteration &iter)
986 {
987         variables.push_back(BlockVariableMap());
988         TraversingVisitor::visit(iter);
989         merge_down_variables();
990 }
991
992
993 bool UnusedFunctionRemover::apply(Stage &stage)
994 {
995         stage.content.visit(*this);
996         NodeRemover().apply(stage, unused_nodes);
997         return !unused_nodes.empty();
998 }
999
1000 void UnusedFunctionRemover::visit(FunctionCall &call)
1001 {
1002         TraversingVisitor::visit(call);
1003
1004         unused_nodes.erase(call.declaration);
1005         if(call.declaration && call.declaration->definition!=call.declaration)
1006                 used_definitions.insert(call.declaration->definition);
1007 }
1008
1009 void UnusedFunctionRemover::visit(FunctionDeclaration &func)
1010 {
1011         TraversingVisitor::visit(func);
1012
1013         if((func.name!="main" || func.body.body.empty()) && !used_definitions.count(&func))
1014                 unused_nodes.insert(&func);
1015 }
1016
1017 } // namespace SL
1018 } // namespace GL
1019 } // namespace Msp