]> git.tdb.fi Git - libs/gl.git/blob - source/programcompiler.cpp
Visit the rest of an iteration statement in NodeRemover
[libs/gl.git] / source / programcompiler.cpp
1 #include <msp/core/raii.h>
2 #include <msp/gl/extensions/ext_gpu_shader4.h>
3 #include <msp/strings/format.h>
4 #include <msp/strings/utils.h>
5 #include "error.h"
6 #include "program.h"
7 #include "programcompiler.h"
8 #include "resources.h"
9 #include "shader.h"
10
11 #undef interface
12
13 using namespace std;
14
15 namespace {
16
17 const char builtins_src[] =
18         "#pragma MSP stage(vertex)\n"
19         "out gl_PerVertex {\n"
20         "  vec4 gl_Position;\n"
21         "  float gl_ClipDistance[];\n"
22         "};\n"
23         "#pragma MSP stage(geometry)\n"
24         "in gl_PerVertex {\n"
25         "  vec4 gl_Position;\n"
26         "  float gl_ClipDistance[];\n"
27         "} gl_in[];\n"
28         "out gl_PerVertex {\n"
29         "  vec4 gl_Position;\n"
30         "  float gl_ClipDistance[];\n"
31         "};\n";
32
33 }
34
35 namespace Msp {
36 namespace GL {
37
38 using namespace ProgramSyntax;
39
40 ProgramCompiler::ProgramCompiler():
41         resources(0),
42         module(0)
43 { }
44
45 ProgramCompiler::~ProgramCompiler()
46 {
47         delete module;
48 }
49
50 void ProgramCompiler::compile(const string &source, const string &src_name)
51 {
52         resources = 0;
53         delete module;
54         module = new Module();
55         ProgramParser parser;
56         imported_names.insert(src_name);
57         append_module(parser.parse(source, src_name));
58         process();
59 }
60
61 void ProgramCompiler::compile(IO::Base &io, Resources *res, const string &src_name)
62 {
63         resources = res;
64         delete module;
65         module = new Module();
66         ProgramParser parser;
67         imported_names.insert(src_name);
68         append_module(parser.parse(io, src_name));
69         process();
70 }
71
72 void ProgramCompiler::compile(IO::Base &io, const string &src_name)
73 {
74         compile(io, 0, src_name);
75 }
76
77 void ProgramCompiler::add_shaders(Program &program)
78 {
79         if(!module)
80                 throw invalid_operation("ProgramCompiler::add_shaders");
81
82         for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); ++i)
83         {
84                 if(i->type==VERTEX)
85                 {
86                         program.attach_shader_owned(new VertexShader(apply<Formatter>(*i)));
87                         for(map<string, unsigned>::iterator j=i->locations.begin(); j!=i->locations.end(); ++j)
88                                 program.bind_attribute(j->second, j->first);
89                 }
90                 else if(i->type==GEOMETRY)
91                         program.attach_shader_owned(new GeometryShader(apply<Formatter>(*i)));
92                 else if(i->type==FRAGMENT)
93                 {
94                         program.attach_shader_owned(new FragmentShader(apply<Formatter>(*i)));
95                         if(EXT_gpu_shader4)
96                         {
97                                 for(map<string, unsigned>::iterator j=i->locations.begin(); j!=i->locations.end(); ++j)
98                                         program.bind_fragment_data(j->second, j->first);
99                         }
100                 }
101         }
102 }
103
104 Module *ProgramCompiler::create_builtins_module()
105 {
106         ProgramParser parser;
107         Module *module = new Module(parser.parse(builtins_src, "<builtin>"));
108         for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); ++i)
109         {
110                 VariableResolver resolver;
111                 i->content.visit(resolver);
112                 for(map<string, VariableDeclaration *>::iterator j=i->content.variables.begin(); j!=i->content.variables.end(); ++j)
113                         j->second->linked_declaration = j->second;
114         }
115         return module;
116 }
117
118 Module &ProgramCompiler::get_builtins_module()
119 {
120         static RefPtr<Module> builtins_module = create_builtins_module();
121         return *builtins_module;
122 }
123
124 Stage *ProgramCompiler::get_builtins(StageType type)
125 {
126         Module &module = get_builtins_module();
127         for(list<Stage>::iterator i=module.stages.begin(); i!=module.stages.end(); ++i)
128                 if(i->type==type)
129                         return &*i;
130         return 0;
131 }
132
133 void ProgramCompiler::append_module(ProgramSyntax::Module &mod)
134 {
135         vector<Import *> imports = apply<NodeGatherer<Import> >(mod.shared);
136         for(vector<Import *>::iterator i=imports.begin(); i!=imports.end(); ++i)
137                 import((*i)->module);
138         apply<NodeRemover>(mod.shared, set<Node *>(imports.begin(), imports.end()));
139
140         append_stage(mod.shared);
141         for(list<Stage>::iterator i=mod.stages.begin(); i!=mod.stages.end(); ++i)
142                 append_stage(*i);
143 }
144
145 void ProgramCompiler::append_stage(Stage &stage)
146 {
147         Stage *target = 0;
148         if(stage.type==SHARED)
149                 target = &module->shared;
150         else
151         {
152                 list<Stage>::iterator i;
153                 for(i=module->stages.begin(); (i!=module->stages.end() && i->type<stage.type); ++i) ;
154                 if(i==module->stages.end() || i->type>stage.type)
155                 {
156                         list<Stage>::iterator j = module->stages.insert(i, stage.type);
157                         if(i!=module->stages.end())
158                                 i->previous = &*j;
159                         i = j;
160                         if(i!=module->stages.begin())
161                                 i->previous = &*--j;
162                 }
163
164                 target = &*i;
165         }
166
167         for(NodeList<Node>::iterator i=stage.content.body.begin(); i!=stage.content.body.end(); ++i)
168                 target->content.body.push_back(*i);
169         apply<DeclarationCombiner>(*target);
170 }
171
172 void ProgramCompiler::process()
173 {
174         for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); ++i)
175                 generate(*i);
176         for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); )
177         {
178                 if(optimize(*i))
179                         i = module->stages.begin();
180                 else
181                         ++i;
182         }
183         for(list<Stage>::iterator i=module->stages.begin(); i!=module->stages.end(); ++i)
184                 finalize(*i);
185 }
186
187 void ProgramCompiler::import(const string &name)
188 {
189         string fn = name+".glsl";
190         if(imported_names.count(fn))
191                 return;
192         imported_names.insert(fn);
193
194         RefPtr<IO::Seekable> io = (resources ? resources->open_raw(fn) : Resources::get_builtins().open(fn));
195         if(!io)
196                 throw runtime_error(format("module %s not found", name));
197         ProgramParser import_parser;
198         append_module(import_parser.parse(*io, fn));
199 }
200
201 void ProgramCompiler::generate(Stage &stage)
202 {
203         inject_block(stage.content, module->shared.content);
204
205         apply<DeclarationReorderer>(stage);
206         apply<FunctionResolver>(stage);
207         apply<VariableResolver>(stage);
208         apply<InterfaceGenerator>(stage);
209         apply<VariableResolver>(stage);
210         apply<DeclarationReorderer>(stage);
211         apply<FunctionResolver>(stage);
212         apply<LegacyConverter>(stage);
213 }
214
215 bool ProgramCompiler::optimize(Stage &stage)
216 {
217         apply<ConstantConditionEliminator>(stage);
218
219         set<FunctionDeclaration *> inlineable = apply<InlineableFunctionLocator>(stage);
220         apply<FunctionInliner>(stage, inlineable);
221
222         set<Node *> unused = apply<UnusedVariableLocator>(stage);
223         set<Node *> unused2 = apply<UnusedFunctionLocator>(stage);
224         unused.insert(unused2.begin(), unused2.end());
225         apply<NodeRemover>(stage, unused);
226
227         return !unused.empty();
228 }
229
230 void ProgramCompiler::finalize(Stage &stage)
231 {
232         if(get_gl_api()==OPENGL_ES2)
233                 apply<DefaultPrecisionGenerator>(stage);
234         else
235                 apply<PrecisionRemover>(stage);
236 }
237
238 void ProgramCompiler::inject_block(Block &target, const Block &source)
239 {
240         list<RefPtr<Node> >::iterator insert_point = target.body.begin();
241         for(list<RefPtr<Node> >::const_iterator i=source.body.begin(); i!=source.body.end(); ++i)
242                 target.body.insert(insert_point, (*i)->clone());
243 }
244
245 template<typename T>
246 typename T::ResultType ProgramCompiler::apply(Stage &stage)
247 {
248         T visitor;
249         visitor.apply(stage);
250         return visitor.get_result();
251 }
252
253 template<typename T, typename A>
254 typename T::ResultType ProgramCompiler::apply(Stage &stage, const A &arg)
255 {
256         T visitor(arg);
257         visitor.apply(stage);
258         return visitor.get_result();
259 }
260
261
262 ProgramCompiler::Visitor::Visitor():
263         stage(0)
264 { }
265
266 void ProgramCompiler::Visitor::apply(Stage &s)
267 {
268         SetForScope<Stage *> set(stage, &s);
269         stage->content.visit(*this);
270 }
271
272
273 ProgramCompiler::BlockModifier::BlockModifier():
274         remove_node(false)
275 { }
276
277 void ProgramCompiler::BlockModifier::flatten_block(Block &block)
278 {
279         insert_nodes.insert(insert_nodes.end(), block.body.begin(), block.body.end());
280         remove_node = true;
281 }
282
283 void ProgramCompiler::BlockModifier::apply_and_increment(Block &block, list<RefPtr<Node> >::iterator &i)
284 {
285         block.body.insert(i, insert_nodes.begin(), insert_nodes.end());
286         insert_nodes.clear();
287
288         if(remove_node)
289                 block.body.erase(i++);
290         else
291                 ++i;
292         remove_node = false;
293 }
294
295 void ProgramCompiler::BlockModifier::visit(Block &block)
296 {
297         for(list<RefPtr<Node> >::iterator i=block.body.begin(); i!=block.body.end(); )
298         {
299                 (*i)->visit(*this);
300                 apply_and_increment(block, i);
301         }
302 }
303
304
305 ProgramCompiler::Formatter::Formatter():
306         indent(0),
307         parameter_list(false),
308         else_if(0)
309 { }
310
311 void ProgramCompiler::Formatter::apply(ProgramSyntax::Stage &s)
312 {
313         GLApi api = get_gl_api();
314         const Version &ver = s.required_version;
315
316         if(ver)
317         {
318                 formatted += format("#version %d%02d", ver.major, ver.minor);
319                 if(api==OPENGL_ES2 && ver>=Version(3, 0))
320                         formatted += " es";
321                 formatted += '\n';
322         }
323
324         Visitor::apply(s);
325 }
326
327 void ProgramCompiler::Formatter::visit(Literal &literal)
328 {
329         formatted += literal.token;
330 }
331
332 void ProgramCompiler::Formatter::visit(ParenthesizedExpression &parexpr)
333 {
334         formatted += '(';
335         parexpr.expression->visit(*this);
336         formatted += ')';
337 }
338
339 void ProgramCompiler::Formatter::visit(VariableReference &var)
340 {
341         formatted += var.name;
342 }
343
344 void ProgramCompiler::Formatter::visit(MemberAccess &memacc)
345 {
346         memacc.left->visit(*this);
347         formatted += format(".%s", memacc.member);
348 }
349
350 void ProgramCompiler::Formatter::visit(UnaryExpression &unary)
351 {
352         if(unary.prefix)
353                 formatted += unary.oper;
354         unary.expression->visit(*this);
355         if(!unary.prefix)
356                 formatted += unary.oper;
357 }
358
359 void ProgramCompiler::Formatter::visit(BinaryExpression &binary)
360 {
361         binary.left->visit(*this);
362         formatted += binary.oper;
363         binary.right->visit(*this);
364         formatted += binary.after;
365 }
366
367 void ProgramCompiler::Formatter::visit(Assignment &assign)
368 {
369         assign.left->visit(*this);
370         formatted += format(" %s ", assign.oper);
371         assign.right->visit(*this);
372 }
373
374 void ProgramCompiler::Formatter::visit(FunctionCall &call)
375 {
376         formatted += format("%s(", call.name);
377         for(vector<RefPtr<Expression> >::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
378         {
379                 if(i!=call.arguments.begin())
380                         formatted += ", ";
381                 (*i)->visit(*this);
382         }
383         formatted += ')';
384 }
385
386 void ProgramCompiler::Formatter::visit(ExpressionStatement &expr)
387 {
388         expr.expression->visit(*this);
389         formatted += ';';
390 }
391
392 void ProgramCompiler::Formatter::visit(Block &block)
393 {
394         if(else_if)
395                 --else_if;
396
397         unsigned brace_indent = indent;
398         bool use_braces = (block.use_braces || (indent && block.body.size()!=1));
399         if(use_braces)
400                 formatted += format("%s{\n", string(brace_indent*2, ' '));
401
402         SetForScope<unsigned> set(indent, indent+(indent>0 || use_braces));
403         string spaces(indent*2, ' ');
404         for(list<RefPtr<Node> >::iterator i=block.body.begin(); i!=block.body.end(); ++i)
405         {
406                 if(i!=block.body.begin())
407                         formatted += '\n';
408                 formatted += spaces;
409                 (*i)->visit(*this);
410                 else_if = 0;
411         }
412
413         if(use_braces)
414                 formatted += format("\n%s}", string(brace_indent*2, ' '));
415 }
416
417 void ProgramCompiler::Formatter::visit(Import &import)
418 {
419         formatted += format("import %s;", import.module);
420 }
421
422 void ProgramCompiler::Formatter::visit(Precision &prec)
423 {
424         formatted += format("precision %s %s;", prec.precision, prec.type);
425 }
426
427 void ProgramCompiler::Formatter::visit(Layout &layout)
428 {
429         formatted += "layout(";
430         for(vector<Layout::Qualifier>::const_iterator i=layout.qualifiers.begin(); i!=layout.qualifiers.end(); ++i)
431         {
432                 if(i!=layout.qualifiers.begin())
433                         formatted += ", ";
434                 formatted += i->identifier;
435                 if(!i->value.empty())
436                         formatted += format("=%s", i->value);
437         }
438         formatted += ')';
439 }
440
441 void ProgramCompiler::Formatter::visit(InterfaceLayout &layout)
442 {
443         layout.layout.visit(*this);
444         formatted += format(" %s;", layout.interface);
445 }
446
447 void ProgramCompiler::Formatter::visit(StructDeclaration &strct)
448 {
449         formatted += format("struct %s\n", strct.name);
450         strct.members.visit(*this);
451         formatted += ';';
452 }
453
454 void ProgramCompiler::Formatter::visit(VariableDeclaration &var)
455 {
456         if(var.layout)
457         {
458                 var.layout->visit(*this);
459                 formatted += ' ';
460         }
461         if(var.constant)
462                 formatted += "const ";
463         if(!var.interpolation.empty())
464                 formatted += format("%s ", var.interpolation);
465         if(!var.sampling.empty())
466                 formatted += format("%s ", var.sampling);
467         if(!var.interface.empty() && var.interface!=block_interface)
468         {
469                 string interface = var.interface;
470                 if(stage->required_version<Version(1, 30))
471                 {
472                         if(stage->type==VERTEX && var.interface=="in")
473                                 interface = "attribute";
474                         else if((stage->type==VERTEX && var.interface=="out") || (stage->type==FRAGMENT && var.interface=="in"))
475                                 interface = "varying";
476                 }
477                 formatted += format("%s ", interface);
478         }
479         if(!var.precision.empty())
480                 formatted += format("%s ", var.precision);
481         formatted += format("%s %s", var.type, var.name);
482         if(var.array)
483         {
484                 formatted += '[';
485                 if(var.array_size)
486                         var.array_size->visit(*this);
487                 formatted += ']';
488         }
489         if(var.init_expression)
490         {
491                 formatted += " = ";
492                 var.init_expression->visit(*this);
493         }
494         if(!parameter_list)
495                 formatted += ';';
496 }
497
498 void ProgramCompiler::Formatter::visit(InterfaceBlock &iface)
499 {
500         SetForScope<string> set(block_interface, iface.interface);
501         formatted += format("%s %s\n", iface.interface, iface.name);
502         iface.members.visit(*this);
503         formatted += ';';
504 }
505
506 void ProgramCompiler::Formatter::visit(FunctionDeclaration &func)
507 {
508         formatted += format("%s %s(", func.return_type, func.name);
509         for(vector<RefPtr<VariableDeclaration> >::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
510         {
511                 if(i!=func.parameters.begin())
512                         formatted += ", ";
513                 SetFlag set(parameter_list);
514                 (*i)->visit(*this);
515         }
516         formatted += ')';
517         if(func.definition==&func)
518         {
519                 formatted += '\n';
520                 func.body.visit(*this);
521         }
522         else
523                 formatted += ';';
524 }
525
526 void ProgramCompiler::Formatter::visit(Conditional &cond)
527 {
528         if(else_if)
529                 formatted.replace(formatted.rfind('\n'), string::npos, 1, ' ');
530
531         indent -= else_if;
532
533         formatted += "if(";
534         cond.condition->visit(*this);
535         formatted += ")\n";
536
537         cond.body.visit(*this);
538         if(!cond.else_body.body.empty())
539         {
540                 formatted += format("\n%selse\n", string(indent*2, ' '));
541                 SetForScope<unsigned> set(else_if, 2);
542                 cond.else_body.visit(*this);
543         }
544 }
545
546 void ProgramCompiler::Formatter::visit(Iteration &iter)
547 {
548         if(!iter.init_statement && iter.condition && !iter.loop_expression)
549         {
550                 formatted += "while(";
551                 iter.condition->visit(*this);
552                 formatted += ')';
553         }
554         else
555         {
556                 formatted += "for(";
557                 if(iter.init_statement)
558                         iter.init_statement->visit(*this);
559                 else
560                         formatted += ';';
561                 if(iter.condition)
562                 {
563                         formatted += ' ';
564                         iter.condition->visit(*this);
565                 }
566                 formatted += ';';
567                 if(iter.loop_expression)
568                 {
569                         formatted += ' ';
570                         iter.loop_expression->visit(*this);
571                 }
572                 formatted += ')';
573         }
574
575         if(iter.body.body.empty())
576                 formatted += " { }";
577         else
578         {
579                 formatted += '\n';
580                 iter.body.visit(*this);
581         }
582 }
583
584 void ProgramCompiler::Formatter::visit(Return &ret)
585 {
586         formatted += "return";
587         if(ret.expression)
588         {
589                 formatted += ' ';
590                 ret.expression->visit(*this);
591         }
592         formatted += ';';
593 }
594
595 void ProgramCompiler::Formatter::visit(Jump &jump)
596 {
597         formatted += jump.keyword;
598         formatted += ';';
599 }
600
601
602 ProgramCompiler::DeclarationCombiner::DeclarationCombiner():
603         toplevel(true)
604 { }
605
606 void ProgramCompiler::DeclarationCombiner::visit(Block &block)
607 {
608         if(!toplevel)
609                 return;
610
611         SetForScope<bool> set(toplevel, false);
612         BlockModifier::visit(block);
613 }
614
615 void ProgramCompiler::DeclarationCombiner::visit(FunctionDeclaration &func)
616 {
617         vector<FunctionDeclaration *> &decls = functions[func.name];
618         if(func.definition)
619         {
620                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
621                 {
622                         (*i)->definition = func.definition;
623                         (*i)->body.body.clear();
624                 }
625         }
626         decls.push_back(&func);
627 }
628
629 void ProgramCompiler::DeclarationCombiner::visit(VariableDeclaration &var)
630 {
631         VariableDeclaration *&ptr = variables[var.name];
632         if(ptr)
633         {
634                 ptr->type = var.type;
635                 if(var.init_expression)
636                         ptr->init_expression = var.init_expression;
637                 remove_node = true;
638         }
639         else
640                 ptr = &var;
641 }
642
643
644 ProgramCompiler::VariableResolver::VariableResolver():
645         anonymous(false),
646         record_target(false),
647         assignment_target(0),
648         self_referencing(false)
649 { }
650
651 void ProgramCompiler::VariableResolver::apply(Stage &s)
652 {
653         SetForScope<Stage *> set(stage, &s);
654         Stage *builtins = get_builtins(stage->type);
655         if(builtins)
656                 blocks.push_back(&builtins->content);
657         stage->content.visit(*this);
658         if(builtins)
659                 blocks.pop_back();
660 }
661
662 void ProgramCompiler::VariableResolver::visit(Block &block)
663 {
664         blocks.push_back(&block);
665         block.variables.clear();
666         TraversingVisitor::visit(block);
667         blocks.pop_back();
668 }
669
670 void ProgramCompiler::VariableResolver::visit(VariableReference &var)
671 {
672         var.declaration = 0;
673         type = 0;
674         for(vector<Block *>::iterator i=blocks.end(); i!=blocks.begin(); )
675         {
676                 --i;
677                 map<string, VariableDeclaration *>::iterator j = (*i)->variables.find(var.name);
678                 if(j!=(*i)->variables.end())
679                 {
680                         var.declaration = j->second;
681                         type = j->second->type_declaration;
682                         break;
683                 }
684         }
685
686         if(record_target)
687         {
688                 if(assignment_target)
689                 {
690                         record_target = false;
691                         assignment_target = 0;
692                 }
693                 else
694                         assignment_target = var.declaration;
695         }
696         else if(var.declaration && var.declaration==assignment_target)
697                 self_referencing = true;
698 }
699
700 void ProgramCompiler::VariableResolver::visit(MemberAccess &memacc)
701 {
702         type = 0;
703         TraversingVisitor::visit(memacc);
704         memacc.declaration = 0;
705         if(type)
706         {
707                 map<string, VariableDeclaration *>::iterator i = type->members.variables.find(memacc.member);
708                 if(i!=type->members.variables.end())
709                 {
710                         memacc.declaration = i->second;
711                         type = i->second->type_declaration;
712                 }
713                 else
714                         type = 0;
715         }
716 }
717
718 void ProgramCompiler::VariableResolver::visit(BinaryExpression &binary)
719 {
720         if(binary.oper=="[")
721         {
722                 {
723                         SetForScope<bool> set(record_target, false);
724                         binary.right->visit(*this);
725                 }
726                 type = 0;
727                 binary.left->visit(*this);
728         }
729         else
730         {
731                 TraversingVisitor::visit(binary);
732                 type = 0;
733         }
734 }
735
736 void ProgramCompiler::VariableResolver::visit(Assignment &assign)
737 {
738         {
739                 SetFlag set(record_target);
740                 assignment_target = 0;
741                 assign.left->visit(*this);
742         }
743
744         self_referencing = false;
745         assign.right->visit(*this);
746
747         assign.self_referencing = (self_referencing || assign.oper!="=");
748         assign.target_declaration = assignment_target;
749 }
750
751 void ProgramCompiler::VariableResolver::visit(StructDeclaration &strct)
752 {
753         TraversingVisitor::visit(strct);
754         blocks.back()->types[strct.name] = &strct;
755 }
756
757 void ProgramCompiler::VariableResolver::visit(VariableDeclaration &var)
758 {
759         for(vector<Block *>::iterator i=blocks.end(); i!=blocks.begin(); )
760         {
761                 --i;
762                 map<string, StructDeclaration *>::iterator j = (*i)->types.find(var.type);
763                 if(j!=(*i)->types.end())
764                         var.type_declaration = j->second;
765         }
766
767         if(!block_interface.empty() && var.interface.empty())
768                 var.interface = block_interface;
769
770         TraversingVisitor::visit(var);
771         blocks.back()->variables[var.name] = &var;
772         if(anonymous && blocks.size()>1)
773                 blocks[blocks.size()-2]->variables[var.name] = &var;
774 }
775
776 void ProgramCompiler::VariableResolver::visit(InterfaceBlock &iface)
777 {
778         SetFlag set(anonymous);
779         SetForScope<string> set2(block_interface, iface.interface);
780         TraversingVisitor::visit(iface);
781 }
782
783
784 void ProgramCompiler::FunctionResolver::visit(FunctionCall &call)
785 {
786         map<string, vector<FunctionDeclaration *> >::iterator i = functions.find(call.name);
787         if(i!=functions.end())
788                 call.declaration = i->second.back();
789
790         TraversingVisitor::visit(call);
791 }
792
793 void ProgramCompiler::FunctionResolver::visit(FunctionDeclaration &func)
794 {
795         vector<FunctionDeclaration *> &decls = functions[func.name];
796         if(func.definition)
797         {
798                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
799                         (*i)->definition = func.definition;
800                 decls.clear();
801                 decls.push_back(&func);
802         }
803         else if(!decls.empty() && decls.back()->definition)
804                 func.definition = decls.back()->definition;
805         else
806                 decls.push_back(&func);
807
808         TraversingVisitor::visit(func);
809 }
810
811
812 ProgramCompiler::InterfaceGenerator::InterfaceGenerator():
813         scope_level(0)
814 { }
815
816 string ProgramCompiler::InterfaceGenerator::get_out_prefix(StageType type)
817 {
818         if(type==VERTEX)
819                 return "_vs_out_";
820         else if(type==GEOMETRY)
821                 return "_gs_out_";
822         else
823                 return string();
824 }
825
826 void ProgramCompiler::InterfaceGenerator::apply(Stage &s)
827 {
828         SetForScope<Stage *> set(stage, &s);
829         if(stage->previous)
830                 in_prefix = get_out_prefix(stage->previous->type);
831         out_prefix = get_out_prefix(stage->type);
832         stage->content.visit(*this);
833 }
834
835 void ProgramCompiler::InterfaceGenerator::visit(Block &block)
836 {
837         SetForScope<unsigned> set(scope_level, scope_level+1);
838         for(list<RefPtr<Node> >::iterator i=block.body.begin(); i!=block.body.end(); )
839         {
840                 (*i)->visit(*this);
841
842                 if(scope_level==1)
843                 {
844                         for(map<string, RefPtr<VariableDeclaration> >::iterator j=iface_declarations.begin(); j!=iface_declarations.end(); ++j)
845                         {
846                                 list<RefPtr<Node> >::iterator k = block.body.insert(i, j->second);
847                                 (*k)->visit(*this);
848                         }
849                         iface_declarations.clear();
850                 }
851
852                 apply_and_increment(block, i);
853         }
854 }
855
856 string ProgramCompiler::InterfaceGenerator::change_prefix(const string &name, const string &prefix) const
857 {
858         unsigned offset = (name.compare(0, in_prefix.size(), in_prefix) ? 0 : in_prefix.size());
859         return prefix+name.substr(offset);
860 }
861
862 bool ProgramCompiler::InterfaceGenerator::generate_interface(VariableDeclaration &var, const string &iface, const string &name)
863 {
864         const map<string, VariableDeclaration *> &stage_vars = (iface=="in" ? stage->in_variables : stage->out_variables);
865         if(stage_vars.count(name) || iface_declarations.count(name))
866                 return false;
867
868         VariableDeclaration* iface_var = new VariableDeclaration;
869         iface_var->sampling = var.sampling;
870         iface_var->interface = iface;
871         iface_var->type = var.type;
872         iface_var->type_declaration = var.type_declaration;
873         iface_var->name = name;
874         if(stage->type==GEOMETRY)
875                 iface_var->array = ((var.array && var.interface!="in") || iface=="in");
876         else
877                 iface_var->array = var.array;
878         if(iface_var->array)
879                 iface_var->array_size = var.array_size;
880         if(iface=="in")
881                 iface_var->linked_declaration = &var;
882         iface_declarations[name] = iface_var;
883
884         return true;
885 }
886
887 void ProgramCompiler::InterfaceGenerator::insert_assignment(const string &left, ProgramSyntax::Expression *right)
888 {
889         Assignment *assign = new Assignment;
890         VariableReference *ref = new VariableReference;
891         ref->name = left;
892         assign->left = ref;
893         assign->oper = "=";
894         assign->right = right;
895
896         ExpressionStatement *stmt = new ExpressionStatement;
897         stmt->expression = assign;
898         stmt->visit(*this);
899         insert_nodes.push_back(stmt);
900 }
901
902 void ProgramCompiler::InterfaceGenerator::visit(VariableReference &var)
903 {
904         if(var.declaration || !stage->previous)
905                 return;
906         if(iface_declarations.count(var.name))
907                 return;
908
909         const map<string, VariableDeclaration *> &prev_out = stage->previous->out_variables;
910         map<string, VariableDeclaration *>::const_iterator i = prev_out.find(var.name);
911         if(i==prev_out.end())
912                 i = prev_out.find(in_prefix+var.name);
913         if(i!=prev_out.end())
914         {
915                 generate_interface(*i->second, "in", i->second->name);
916                 var.name = i->second->name;
917         }
918 }
919
920 void ProgramCompiler::InterfaceGenerator::visit(VariableDeclaration &var)
921 {
922         if(var.interface=="out")
923         {
924                 if(scope_level==1)
925                         stage->out_variables[var.name] = &var;
926                 else if(generate_interface(var, "out", change_prefix(var.name, string())))
927                 {
928                         remove_node = true;
929                         if(var.init_expression)
930                         {
931                                 insert_assignment(var.name, var.init_expression->clone());
932                                 return;
933                         }
934                 }
935         }
936         else if(var.interface=="in")
937         {
938                 stage->in_variables[var.name] = &var;
939                 if(var.linked_declaration)
940                         var.linked_declaration->linked_declaration = &var;
941                 else if(stage->previous)
942                 {
943                         const map<string, VariableDeclaration *> &prev_out = stage->previous->out_variables;
944                         map<string, VariableDeclaration *>::const_iterator i = prev_out.find(var.name);
945                         if(i!=prev_out.end())
946                         {
947                                 var.linked_declaration = i->second;
948                                 i->second->linked_declaration = &var;
949                         }
950                 }
951         }
952
953         TraversingVisitor::visit(var);
954 }
955
956 void ProgramCompiler::InterfaceGenerator::visit(Passthrough &pass)
957 {
958         vector<VariableDeclaration *> pass_vars;
959
960         for(map<string, VariableDeclaration *>::const_iterator i=stage->in_variables.begin(); i!=stage->in_variables.end(); ++i)
961                 pass_vars.push_back(i->second);
962         for(map<string, RefPtr<VariableDeclaration> >::const_iterator i=iface_declarations.begin(); i!=iface_declarations.end(); ++i)
963                 if(i->second->interface=="in")
964                         pass_vars.push_back(i->second.get());
965
966         if(stage->previous)
967         {
968                 const map<string, VariableDeclaration *> &prev_out = stage->previous->out_variables;
969                 for(map<string, VariableDeclaration *>::const_iterator i=prev_out.begin(); i!=prev_out.end(); ++i)
970                 {
971                         bool linked = false;
972                         for(vector<VariableDeclaration *>::const_iterator j=pass_vars.begin(); (!linked && j!=pass_vars.end()); ++j)
973                                 linked = ((*j)->linked_declaration==i->second);
974
975                         if(!linked && generate_interface(*i->second, "in", i->second->name))
976                                 pass_vars.push_back(i->second);
977                 }
978         }
979
980         if(stage->type==GEOMETRY)
981         {
982                 VariableReference *ref = new VariableReference;
983                 ref->name = "gl_in";
984
985                 BinaryExpression *subscript = new BinaryExpression;
986                 subscript->left = ref;
987                 subscript->oper = "[";
988                 subscript->right = pass.subscript;
989                 subscript->after = "]";
990
991                 MemberAccess *memacc = new MemberAccess;
992                 memacc->left = subscript;
993                 memacc->member = "gl_Position";
994
995                 insert_assignment("gl_Position", memacc);
996         }
997
998         for(vector<VariableDeclaration *>::const_iterator i=pass_vars.begin(); i!=pass_vars.end(); ++i)
999         {
1000                 string out_name = change_prefix((*i)->name, out_prefix);
1001                 generate_interface(**i, "out", out_name);
1002
1003                 VariableReference *ref = new VariableReference;
1004                 ref->name = (*i)->name;
1005                 if(pass.subscript)
1006                 {
1007                         BinaryExpression *subscript = new BinaryExpression;
1008                         subscript->left = ref;
1009                         subscript->oper = "[";
1010                         subscript->right = pass.subscript;
1011                         subscript->after = "]";
1012                         insert_assignment(out_name, subscript);
1013                 }
1014                 else
1015                         insert_assignment(out_name, ref);
1016         }
1017
1018         remove_node = true;
1019 }
1020
1021
1022 ProgramCompiler::DeclarationReorderer::DeclarationReorderer():
1023         scope_level(0),
1024         kind(NO_DECLARATION)
1025 { }
1026
1027 void ProgramCompiler::DeclarationReorderer::visit(FunctionCall &call)
1028 {
1029         FunctionDeclaration *def = call.declaration;
1030         if(def)
1031                 def = def->definition;
1032         if(def && !ordered_funcs.count(def))
1033                 needed_funcs.insert(def);
1034 }
1035
1036 void ProgramCompiler::DeclarationReorderer::visit(Block &block)
1037 {
1038         SetForScope<unsigned> set(scope_level, scope_level+1);
1039         if(scope_level>1)
1040                 return Visitor::visit(block);
1041
1042         list<RefPtr<Node> >::iterator struct_insert_point = block.body.end();
1043         list<RefPtr<Node> >::iterator variable_insert_point = block.body.end();
1044         list<RefPtr<Node> >::iterator function_insert_point = block.body.end();
1045         unsigned unordered_func_count = 0;
1046         bool ordered_any_funcs = false;
1047
1048         for(list<RefPtr<Node> >::iterator i=block.body.begin(); i!=block.body.end(); )
1049         {
1050                 kind = NO_DECLARATION;
1051                 (*i)->visit(*this);
1052
1053                 bool moved = false;
1054                 if(kind==STRUCT && struct_insert_point!=block.body.end())
1055                 {
1056                         block.body.insert(struct_insert_point, *i);
1057                         moved = true;
1058                 }
1059                 else if(kind>STRUCT && struct_insert_point==block.body.end())
1060                         struct_insert_point = i;
1061
1062                 if(kind==VARIABLE && variable_insert_point!=block.body.end())
1063                 {
1064                         block.body.insert(variable_insert_point, *i);
1065                         moved = true;
1066                 }
1067                 else if(kind>VARIABLE && variable_insert_point==block.body.end())
1068                         variable_insert_point = i;
1069
1070                 if(kind==FUNCTION)
1071                 {
1072                         if(function_insert_point==block.body.end())
1073                                 function_insert_point = i;
1074
1075                         if(needed_funcs.empty())
1076                         {
1077                                 ordered_funcs.insert(i->get());
1078                                 if(i!=function_insert_point)
1079                                 {
1080                                         block.body.insert(function_insert_point, *i);
1081                                         moved = true;
1082                                 }
1083                                 else
1084                                         ++function_insert_point;
1085                                 ordered_any_funcs = true;
1086                         }
1087                         else
1088                                 ++unordered_func_count;
1089                 }
1090
1091                 if(moved)
1092                 {
1093                         if(function_insert_point==i)
1094                                 ++function_insert_point;
1095                         block.body.erase(i++);
1096                 }
1097                 else
1098                         ++i;
1099
1100                 if(i==block.body.end() && unordered_func_count)
1101                 {
1102                         if(!ordered_any_funcs)
1103                                 // A subset of the remaining functions forms a recursive loop
1104                                 /* TODO pick a function and move it up, adding any necessary
1105                                 declarations */
1106                                 break;
1107
1108                         i = function_insert_point;
1109                         unordered_func_count = 0;
1110                 }
1111         }
1112 }
1113
1114 void ProgramCompiler::DeclarationReorderer::visit(ProgramSyntax::VariableDeclaration &var)
1115 {
1116         Visitor::visit(var);
1117         kind = VARIABLE;
1118 }
1119
1120 void ProgramCompiler::DeclarationReorderer::visit(FunctionDeclaration &func)
1121 {
1122         needed_funcs.clear();
1123         func.body.visit(*this);
1124         needed_funcs.erase(&func);
1125         kind = FUNCTION;
1126 }
1127
1128
1129 ProgramCompiler::InlineableFunctionLocator::InlineableFunctionLocator():
1130         in_function(0)
1131 { }
1132
1133 void ProgramCompiler::InlineableFunctionLocator::visit(FunctionCall &call)
1134 {
1135         FunctionDeclaration *def = call.declaration;
1136         if(def && def->definition!=def)
1137                 def = def->definition;
1138
1139         if(def)
1140         {
1141                 unsigned &count = refcounts[def];
1142                 ++count;
1143                 if(count>1 || def==in_function)
1144                         inlineable.erase(def);
1145         }
1146
1147         TraversingVisitor::visit(call);
1148 }
1149
1150 void ProgramCompiler::InlineableFunctionLocator::visit(FunctionDeclaration &func)
1151 {
1152         unsigned &count = refcounts[func.definition];
1153         if(!count && func.parameters.empty())
1154                 inlineable.insert(func.definition);
1155
1156         SetForScope<FunctionDeclaration *> set(in_function, &func);
1157         TraversingVisitor::visit(func);
1158 }
1159
1160
1161 ProgramCompiler::FunctionInliner::FunctionInliner():
1162         extract_result(0)
1163 { }
1164
1165 ProgramCompiler::FunctionInliner::FunctionInliner(const set<FunctionDeclaration *> &in):
1166         inlineable(in),
1167         extract_result(0)
1168 { }
1169
1170 void ProgramCompiler::FunctionInliner::visit_and_inline(RefPtr<Expression> &ptr)
1171 {
1172         inline_result = 0;
1173         ptr->visit(*this);
1174         if(inline_result)
1175                 ptr = inline_result;
1176 }
1177
1178 void ProgramCompiler::FunctionInliner::visit(Block &block)
1179 {
1180         if(extract_result)
1181                 --extract_result;
1182
1183         for(list<RefPtr<Node> >::iterator i=block.body.begin(); i!=block.body.end(); ++i)
1184         {
1185                 (*i)->visit(*this);
1186                 if(extract_result)
1187                         --extract_result;
1188         }
1189 }
1190
1191 void ProgramCompiler::FunctionInliner::visit(UnaryExpression &unary)
1192 {
1193         visit_and_inline(unary.expression);
1194         inline_result = 0;
1195 }
1196
1197 void ProgramCompiler::FunctionInliner::visit(BinaryExpression &binary)
1198 {
1199         visit_and_inline(binary.left);
1200         visit_and_inline(binary.right);
1201         inline_result = 0;
1202 }
1203
1204 void ProgramCompiler::FunctionInliner::visit(MemberAccess &memacc)
1205 {
1206         visit_and_inline(memacc.left);
1207         inline_result = 0;
1208 }
1209
1210 void ProgramCompiler::FunctionInliner::visit(FunctionCall &call)
1211 {
1212         for(vector<RefPtr<Expression> >::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
1213                 visit_and_inline(*i);
1214
1215         FunctionDeclaration *def = call.declaration;
1216         if(def && def->definition!=def)
1217                 def = def->definition;
1218
1219         if(def && inlineable.count(def))
1220         {
1221                 extract_result = 2;
1222                 def->visit(*this);
1223         }
1224         else
1225                 inline_result = 0;
1226 }
1227
1228 void ProgramCompiler::FunctionInliner::visit(VariableDeclaration &var)
1229 {
1230         if(var.init_expression)
1231                 visit_and_inline(var.init_expression);
1232         inline_result = 0;
1233 }
1234
1235 void ProgramCompiler::FunctionInliner::visit(Return &ret)
1236 {
1237         TraversingVisitor::visit(ret);
1238
1239         if(extract_result)
1240                 inline_result = ret.expression->clone();
1241 }
1242
1243
1244 ProgramCompiler::ExpressionEvaluator::ExpressionEvaluator():
1245         variable_values(0),
1246         result(0.0f),
1247         result_valid(false)
1248 { }
1249
1250 ProgramCompiler::ExpressionEvaluator::ExpressionEvaluator(const ValueMap &v):
1251         variable_values(&v),
1252         result(0.0f),
1253         result_valid(false)
1254 { }
1255
1256 void ProgramCompiler::ExpressionEvaluator::visit(Literal &literal)
1257 {
1258         if(literal.token=="true")
1259                 result = 1.0f;
1260         else if(literal.token=="false")
1261                 result = 0.0f;
1262         else
1263                 result = lexical_cast<float>(literal.token);
1264         result_valid = true;
1265 }
1266
1267 void ProgramCompiler::ExpressionEvaluator::visit(ParenthesizedExpression &parexp)
1268 {
1269         parexp.expression->visit(*this);
1270 }
1271
1272 void ProgramCompiler::ExpressionEvaluator::visit(VariableReference &var)
1273 {
1274         if(!var.declaration)
1275                 return;
1276
1277         if(variable_values)
1278         {
1279                 ValueMap::const_iterator i = variable_values->find(var.declaration);
1280                 if(i!=variable_values->end())
1281                         i->second->visit(*this);
1282         }
1283         else if(var.declaration->init_expression)
1284                 var.declaration->init_expression->visit(*this);
1285 }
1286
1287 void ProgramCompiler::ExpressionEvaluator::visit(UnaryExpression &unary)
1288 {
1289         result_valid = false;
1290         unary.expression->visit(*this);
1291         if(!result_valid)
1292                 return;
1293
1294         if(unary.oper=="!")
1295                 result = !result;
1296         else
1297                 result_valid = false;
1298 }
1299
1300 void ProgramCompiler::ExpressionEvaluator::visit(BinaryExpression &binary)
1301 {
1302         result_valid = false;
1303         binary.left->visit(*this);
1304         if(!result_valid)
1305                 return;
1306
1307         float left_result = result;
1308         result_valid = false;
1309         binary.right->visit(*this);
1310         if(!result_valid)
1311                 return;
1312
1313         if(binary.oper=="<")
1314                 result = (left_result<result);
1315         else if(binary.oper=="<=")
1316                 result = (left_result<=result);
1317         else if(binary.oper==">")
1318                 result = (left_result>result);
1319         else if(binary.oper==">=")
1320                 result = (left_result>=result);
1321         else if(binary.oper=="==")
1322                 result = (left_result==result);
1323         else if(binary.oper=="!=")
1324                 result = (left_result!=result);
1325         else if(binary.oper=="&&")
1326                 result = (left_result && result);
1327         else if(binary.oper=="||")
1328                 result = (left_result || result);
1329         else
1330                 result_valid = false;
1331 }
1332
1333
1334 ProgramCompiler::ConstantConditionEliminator::ConstantConditionEliminator():
1335         scope_level(0),
1336         record_only(false)
1337 { }
1338
1339 void ProgramCompiler::ConstantConditionEliminator::visit(Block &block)
1340 {
1341         SetForScope<unsigned> set(scope_level, scope_level+1);
1342         BlockModifier::visit(block);
1343
1344         for(map<string, VariableDeclaration *>::const_iterator i=block.variables.begin(); i!=block.variables.end(); ++i)
1345                 variable_values.erase(i->second);
1346 }
1347
1348 void ProgramCompiler::ConstantConditionEliminator::visit(UnaryExpression &unary)
1349 {
1350         if(VariableReference *var = dynamic_cast<VariableReference *>(unary.expression.get()))
1351                 if(unary.oper=="++" || unary.oper=="--")
1352                         variable_values.erase(var->declaration);
1353 }
1354
1355 void ProgramCompiler::ConstantConditionEliminator::visit(Assignment &assign)
1356 {
1357         variable_values.erase(assign.target_declaration);
1358 }
1359
1360 void ProgramCompiler::ConstantConditionEliminator::visit(VariableDeclaration &var)
1361 {
1362         if(var.constant || scope_level>1)
1363                 variable_values[&var] = var.init_expression.get();
1364 }
1365
1366 void ProgramCompiler::ConstantConditionEliminator::visit(Conditional &cond)
1367 {
1368         if(!record_only)
1369         {
1370                 ExpressionEvaluator eval(variable_values);
1371                 cond.condition->visit(eval);
1372                 if(eval.result_valid)
1373                 {
1374                         flatten_block(eval.result ? cond.body : cond.else_body);
1375                         return;
1376                 }
1377         }
1378
1379         TraversingVisitor::visit(cond);
1380 }
1381
1382 void ProgramCompiler::ConstantConditionEliminator::visit(Iteration &iter)
1383 {
1384         if(!record_only)
1385         {
1386                 if(iter.condition)
1387                 {
1388                         /* If the loop condition is always false on the first iteration, the
1389                         entire loop can be removed */
1390                         if(iter.init_statement)
1391                                 iter.init_statement->visit(*this);
1392                         ExpressionEvaluator eval(variable_values);
1393                         iter.condition->visit(eval);
1394                         if(eval.result_valid && !eval.result)
1395                         {
1396                                 remove_node = true;
1397                                 return;
1398                         }
1399                 }
1400
1401                 /* Record all assignments that occur inside the loop body so those
1402                 variables won't be considered as constant */
1403                 SetFlag set_record(record_only);
1404                 TraversingVisitor::visit(iter);
1405         }
1406
1407         TraversingVisitor::visit(iter);
1408
1409         if(VariableDeclaration *init_decl = dynamic_cast<VariableDeclaration *>(iter.init_statement.get()))
1410                 variable_values.erase(init_decl);
1411 }
1412
1413
1414 ProgramCompiler::UnusedVariableLocator::UnusedVariableLocator():
1415         aggregate(0),
1416         assignment(0),
1417         assignment_target(false),
1418         global_scope(true)
1419 { }
1420
1421 void ProgramCompiler::UnusedVariableLocator::apply(Stage &s)
1422 {
1423         variables.push_back(BlockVariableMap());
1424         Visitor::apply(s);
1425         BlockVariableMap &global_variables = variables.back();
1426         for(BlockVariableMap::iterator i=global_variables.begin(); i!=global_variables.end(); ++i)
1427         {
1428                 if(i->first->interface=="out" && (s.type==FRAGMENT || i->first->linked_declaration || !i->first->name.compare(0, 3, "gl_")))
1429                         continue;
1430                 if(!i->second.referenced)
1431                 {
1432                         unused_nodes.insert(i->first);
1433                         clear_assignments(i->second, true);
1434                 }
1435         }
1436         variables.pop_back();
1437 }
1438
1439 void ProgramCompiler::UnusedVariableLocator::visit(VariableReference &var)
1440 {
1441         map<VariableDeclaration *, Node *>::iterator i = aggregates.find(var.declaration);
1442         if(i!=aggregates.end())
1443                 unused_nodes.erase(i->second);
1444
1445         if(var.declaration && !assignment_target)
1446         {
1447                 VariableInfo &var_info = variables.back()[var.declaration];
1448                 var_info.assignments.clear();
1449                 var_info.referenced = true;
1450         }
1451 }
1452
1453 void ProgramCompiler::UnusedVariableLocator::visit(MemberAccess &memacc)
1454 {
1455         TraversingVisitor::visit(memacc);
1456         unused_nodes.erase(memacc.declaration);
1457 }
1458
1459 void ProgramCompiler::UnusedVariableLocator::visit(BinaryExpression &binary)
1460 {
1461         if(binary.oper=="[")
1462         {
1463                 binary.left->visit(*this);
1464                 SetForScope<bool> set(assignment_target, false);
1465                 binary.right->visit(*this);
1466         }
1467         else
1468                 TraversingVisitor::visit(binary);
1469 }
1470
1471 void ProgramCompiler::UnusedVariableLocator::visit(Assignment &assign)
1472 {
1473         {
1474                 SetForScope<bool> set(assignment_target, !assign.self_referencing);
1475                 assign.left->visit(*this);
1476         }
1477         assign.right->visit(*this);
1478         assignment = &assign;
1479 }
1480
1481 void ProgramCompiler::UnusedVariableLocator::record_assignment(VariableDeclaration &var, Node &node, bool self_ref)
1482 {
1483         VariableInfo &var_info = variables.back()[&var];
1484         if(!self_ref)
1485                 clear_assignments(var_info, true);
1486         var_info.assignments.push_back(&node);
1487         var_info.conditionally_assigned = false;
1488 }
1489
1490 void ProgramCompiler::UnusedVariableLocator::clear_assignments(VariableInfo &var_info, bool mark_unused)
1491 {
1492         if(mark_unused)
1493         {
1494                 for(vector<Node *>::iterator i=var_info.assignments.begin(); i!=var_info.assignments.end(); ++i)
1495                         unused_nodes.insert(*i);
1496         }
1497         var_info.assignments.clear();
1498 }
1499
1500 void ProgramCompiler::UnusedVariableLocator::visit(ExpressionStatement &expr)
1501 {
1502         assignment = 0;
1503         TraversingVisitor::visit(expr);
1504         if(assignment && assignment->target_declaration)
1505                 record_assignment(*assignment->target_declaration, expr, assignment->self_referencing);
1506 }
1507
1508 void ProgramCompiler::UnusedVariableLocator::visit(StructDeclaration &strct)
1509 {
1510         SetForScope<Node *> set(aggregate, &strct);
1511         unused_nodes.insert(&strct);
1512         TraversingVisitor::visit(strct);
1513 }
1514
1515 void ProgramCompiler::UnusedVariableLocator::visit(VariableDeclaration &var)
1516 {
1517         if(aggregate)
1518                 aggregates[&var] = aggregate;
1519         else
1520         {
1521                 variables.back()[&var].local = true;
1522                 if(var.init_expression)
1523                         record_assignment(var, *var.init_expression, false);
1524         }
1525         unused_nodes.erase(var.type_declaration);
1526         TraversingVisitor::visit(var);
1527 }
1528
1529 void ProgramCompiler::UnusedVariableLocator::visit(InterfaceBlock &iface)
1530 {
1531         SetForScope<Node *> set(aggregate, &iface);
1532         unused_nodes.insert(&iface);
1533         TraversingVisitor::visit(iface);
1534 }
1535
1536 void ProgramCompiler::UnusedVariableLocator::visit(FunctionDeclaration &func)
1537 {
1538         variables.push_back(BlockVariableMap());
1539
1540         {
1541                 SetForScope<bool> set(global_scope, false);
1542                 for(vector<RefPtr<VariableDeclaration> >::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
1543                         (*i)->visit(*this);
1544                 func.body.visit(*this);
1545         }
1546
1547         BlockVariableMap &block_variables = variables.back();
1548         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
1549                 i->second.conditionally_assigned = true;
1550         for(vector<RefPtr<VariableDeclaration> >::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
1551                 block_variables[i->get()].referenced = true;
1552         merge_down_variables();
1553 }
1554
1555 void ProgramCompiler::UnusedVariableLocator::merge_down_variables()
1556 {
1557         BlockVariableMap &parent_variables = variables[variables.size()-2];
1558         BlockVariableMap &block_variables = variables.back();
1559         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
1560         {
1561                 if(i->second.local)
1562                 {
1563                         if(!i->second.referenced)
1564                                 unused_nodes.insert(i->first);
1565                         clear_assignments(i->second, true);
1566                         continue;
1567                 }
1568
1569                 BlockVariableMap::iterator j = parent_variables.find(i->first);
1570                 if(j==parent_variables.end())
1571                         parent_variables.insert(*i);
1572                 else
1573                 {
1574                         if(i->second.referenced || !i->second.conditionally_assigned)
1575                                 clear_assignments(j->second, !i->second.referenced);
1576                         j->second.conditionally_assigned = i->second.conditionally_assigned;
1577                         j->second.referenced |= i->second.referenced;
1578                         j->second.assignments.insert(j->second.assignments.end(), i->second.assignments.begin(), i->second.assignments.end());
1579                 }
1580         }
1581         variables.pop_back();
1582 }
1583
1584 void ProgramCompiler::UnusedVariableLocator::visit(Conditional &cond)
1585 {
1586         cond.condition->visit(*this);
1587         variables.push_back(BlockVariableMap());
1588         cond.body.visit(*this);
1589
1590         BlockVariableMap if_variables;
1591         swap(variables.back(), if_variables);
1592         cond.else_body.visit(*this);
1593
1594         BlockVariableMap &else_variables = variables.back();
1595         for(BlockVariableMap::iterator i=else_variables.begin(); i!=else_variables.end(); ++i)
1596         {
1597                 BlockVariableMap::iterator j = if_variables.find(i->first);
1598                 if(j!=if_variables.end())
1599                 {
1600                         i->second.assignments.insert(i->second.assignments.end(), j->second.assignments.begin(), j->second.assignments.end());
1601                         i->second.conditionally_assigned |= j->second.conditionally_assigned;
1602                         if_variables.erase(j);
1603                 }
1604                 else
1605                         i->second.conditionally_assigned = true;
1606         }
1607
1608         for(BlockVariableMap::iterator i=if_variables.begin(); i!=if_variables.end(); ++i)
1609         {
1610                 i->second.conditionally_assigned = true;
1611                 else_variables.insert(*i);
1612         }
1613
1614         merge_down_variables();
1615 }
1616
1617 void ProgramCompiler::UnusedVariableLocator::visit(Iteration &iter)
1618 {
1619         variables.push_back(BlockVariableMap());
1620         TraversingVisitor::visit(iter);
1621
1622         BlockVariableMap &block_variables = variables.back();
1623         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
1624                 if(!i->second.local && i->second.referenced)
1625                         i->second.assignments.clear();
1626
1627         merge_down_variables();
1628 }
1629
1630
1631 ProgramCompiler::UnusedVariableLocator::VariableInfo::VariableInfo():
1632         local(false),
1633         conditionally_assigned(false),
1634         referenced(false)
1635 { }
1636
1637
1638 void ProgramCompiler::UnusedFunctionLocator::visit(FunctionCall &call)
1639 {
1640         TraversingVisitor::visit(call);
1641
1642         unused_nodes.erase(call.declaration);
1643         if(call.declaration && call.declaration->definition!=call.declaration)
1644                 used_definitions.insert(call.declaration->definition);
1645 }
1646
1647 void ProgramCompiler::UnusedFunctionLocator::visit(FunctionDeclaration &func)
1648 {
1649         TraversingVisitor::visit(func);
1650
1651         if((func.name!="main" || func.body.body.empty()) && !used_definitions.count(&func))
1652                 unused_nodes.insert(&func);
1653 }
1654
1655
1656 ProgramCompiler::NodeRemover::NodeRemover(const set<Node *> &r):
1657         to_remove(r)
1658 { }
1659
1660 void ProgramCompiler::NodeRemover::visit(Block &block)
1661 {
1662         for(list<RefPtr<Node> >::iterator i=block.body.begin(); i!=block.body.end(); )
1663         {
1664                 (*i)->visit(*this);
1665                 if(to_remove.count(i->get()))
1666                         block.body.erase(i++);
1667                 else
1668                         ++i;
1669         }
1670 }
1671
1672 void ProgramCompiler::NodeRemover::visit(VariableDeclaration &var)
1673 {
1674         if(to_remove.count(&var))
1675         {
1676                 stage->in_variables.erase(var.name);
1677                 stage->out_variables.erase(var.name);
1678                 stage->locations.erase(var.name);
1679                 if(var.linked_declaration)
1680                         var.linked_declaration->linked_declaration = 0;
1681         }
1682         else if(var.init_expression && to_remove.count(var.init_expression.get()))
1683                 var.init_expression = 0;
1684 }
1685
1686 void ProgramCompiler::NodeRemover::visit(Iteration &iter)
1687 {
1688         if(to_remove.count(iter.init_statement.get()))
1689                 iter.init_statement = 0;
1690         TraversingVisitor::visit(iter);
1691 }
1692
1693
1694 void ProgramCompiler::PrecisionRemover::visit(Precision &)
1695 {
1696         remove_node = true;
1697 }
1698
1699 void ProgramCompiler::PrecisionRemover::visit(VariableDeclaration &var)
1700 {
1701         var.precision.clear();
1702 }
1703
1704
1705 ProgramCompiler::DefaultPrecisionGenerator::DefaultPrecisionGenerator():
1706         toplevel(true)
1707 { }
1708
1709 void ProgramCompiler::DefaultPrecisionGenerator::visit(Block &block)
1710 {
1711         if(toplevel)
1712         {
1713                 SetForScope<bool> set(toplevel, false);
1714                 BlockModifier::visit(block);
1715         }
1716         else
1717                 Visitor::visit(block);
1718 }
1719
1720 void ProgramCompiler::DefaultPrecisionGenerator::visit(Precision &prec)
1721 {
1722         have_default.insert(prec.type);
1723 }
1724
1725 void ProgramCompiler::DefaultPrecisionGenerator::visit(VariableDeclaration &var)
1726 {
1727         if(var.type_declaration)
1728                 return;
1729
1730         string type = var.type;
1731         if(!type.compare(0, 3, "vec") || !type.compare(0, 3, "mat"))
1732                 type = "float";
1733         else if(!type.compare(0, 3, "ivec") || type=="uint")
1734                 type = "int";
1735
1736         if(!have_default.count(type))
1737         {
1738                 Precision *prec = new Precision;
1739                 if(!type.compare(0, 7, "sampler"))
1740                         prec->precision = "lowp";
1741                 else if(stage->type==FRAGMENT)
1742                         prec->precision = "mediump";
1743                 else
1744                         prec->precision = "highp";
1745                 prec->type = type;
1746                 insert_nodes.push_back(prec);
1747
1748                 have_default.insert(type);
1749         }
1750 }
1751
1752
1753 ProgramCompiler::LegacyConverter::LegacyConverter():
1754         target_api(get_gl_api()),
1755         target_version(get_glsl_version()),
1756         frag_out(0)
1757 { }
1758
1759 ProgramCompiler::LegacyConverter::LegacyConverter(const Version &v):
1760         target_api(get_gl_api()),
1761         target_version(v),
1762         frag_out(0)
1763 { }
1764
1765 bool ProgramCompiler::LegacyConverter::check_version(const Version &feature_version) const
1766 {
1767         if(target_version<feature_version)
1768                 return false;
1769         else if(stage->required_version<feature_version)
1770                 stage->required_version = feature_version;
1771
1772         return true;
1773 }
1774
1775 bool ProgramCompiler::LegacyConverter::supports_unified_interface_syntax() const
1776 {
1777         if(target_api==OPENGL_ES2)
1778                 return check_version(Version(3, 0));
1779         else
1780                 return check_version(Version(1, 30));
1781 }
1782
1783 void ProgramCompiler::LegacyConverter::visit(VariableReference &var)
1784 {
1785         if(var.declaration==frag_out && !supports_unified_interface_syntax())
1786         {
1787                 var.name = "gl_FragColor";
1788                 var.declaration = 0;
1789                 type = "vec4";
1790         }
1791         else if(var.declaration)
1792                 type = var.declaration->type;
1793         else
1794                 type = string();
1795 }
1796
1797 void ProgramCompiler::LegacyConverter::visit(Assignment &assign)
1798 {
1799         TraversingVisitor::visit(assign);
1800         if(assign.target_declaration==frag_out && !supports_unified_interface_syntax())
1801                 assign.target_declaration = 0;
1802 }
1803
1804 bool ProgramCompiler::LegacyConverter::supports_unified_sampling_functions() const
1805 {
1806         if(target_api==OPENGL_ES2)
1807                 return check_version(Version(3, 0));
1808         else
1809                 return check_version(Version(1, 30));
1810 }
1811
1812 void ProgramCompiler::LegacyConverter::visit(FunctionCall &call)
1813 {
1814         if(call.name=="texture" && !call.declaration && !supports_unified_sampling_functions())
1815         {
1816                 vector<RefPtr<Expression> >::iterator i = call.arguments.begin();
1817                 if(i!=call.arguments.end())
1818                 {
1819                         (*i)->visit(*this);
1820                         if(type=="sampler1D")
1821                                 call.name = "texture1D";
1822                         else if(type=="sampler2D")
1823                                 call.name = "texture2D";
1824                         else if(type=="sampler3D")
1825                                 call.name = "texture3D";
1826                         else if(type=="sampler1DShadow")
1827                                 call.name = "shadow1D";
1828                         else if(type=="sampler2DShadow")
1829                                 call.name = "shadow2D";
1830
1831                         for(; i!=call.arguments.end(); ++i)
1832                                 (*i)->visit(*this);
1833                 }
1834         }
1835         else
1836                 TraversingVisitor::visit(call);
1837 }
1838
1839 bool ProgramCompiler::LegacyConverter::supports_interface_layouts() const
1840 {
1841         if(target_api==OPENGL_ES2)
1842                 return check_version(Version(3, 0));
1843         else
1844                 return check_version(Version(3, 30));
1845 }
1846
1847 bool ProgramCompiler::LegacyConverter::supports_centroid_sampling() const
1848 {
1849         if(target_api==OPENGL_ES2)
1850                 return check_version(Version(3, 0));
1851         else
1852                 return check_version(Version(1, 20));
1853 }
1854
1855 bool ProgramCompiler::LegacyConverter::supports_sample_sampling() const
1856 {
1857         if(target_api==OPENGL_ES2)
1858                 return check_version(Version(3, 20));
1859         else
1860                 return check_version(Version(4, 0));
1861 }
1862
1863 void ProgramCompiler::LegacyConverter::visit(VariableDeclaration &var)
1864 {
1865         if(var.layout && !supports_interface_layouts())
1866         {
1867                 vector<Layout::Qualifier>::iterator i;
1868                 for(i=var.layout->qualifiers.begin(); (i!=var.layout->qualifiers.end() && i->identifier!="location"); ++i) ;
1869                 if(i!=var.layout->qualifiers.end())
1870                 {
1871                         unsigned location = lexical_cast<unsigned>(i->value);
1872                         if(stage->type==VERTEX && var.interface=="in")
1873                         {
1874                                 stage->locations[var.name] = location;
1875                                 var.layout->qualifiers.erase(i);
1876                         }
1877                         else if(stage->type==FRAGMENT && var.interface=="out")
1878                         {
1879                                 if(location!=0)
1880                                         static Require _req(EXT_gpu_shader4);
1881                                 stage->locations[var.name] = location;
1882                                 var.layout->qualifiers.erase(i);
1883                         }
1884
1885                         if(var.layout->qualifiers.empty())
1886                                 var.layout = 0;
1887                 }
1888         }
1889
1890         if(var.sampling=="centroid")
1891         {
1892                 if(!supports_centroid_sampling())
1893                         var.sampling = string();
1894         }
1895         else if(var.sampling=="sample")
1896         {
1897                 if(!supports_sample_sampling())
1898                         var.sampling = string();
1899         }
1900
1901         if((var.interface=="in" || var.interface=="out") && !supports_unified_interface_syntax())
1902         {
1903                 if(stage->type==FRAGMENT && var.interface=="out")
1904                 {
1905                         frag_out = &var;
1906                         remove_node = true;
1907                 }
1908         }
1909
1910         TraversingVisitor::visit(var);
1911 }
1912
1913 bool ProgramCompiler::LegacyConverter::supports_interface_blocks(const string &iface) const
1914 {
1915         if(target_api==OPENGL_ES2)
1916         {
1917                 if(iface=="uniform")
1918                         return check_version(Version(3, 0));
1919                 else
1920                         return check_version(Version(3, 20));
1921         }
1922         else
1923                 return check_version(Version(1, 50));
1924 }
1925
1926 void ProgramCompiler::LegacyConverter::visit(InterfaceBlock &iface)
1927 {
1928         if(!supports_interface_blocks(iface.interface))
1929                 flatten_block(iface.members);
1930 }
1931
1932 } // namespace GL
1933 } // namespace Msp