]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/generate.cpp
Give declaration nodes to all GLSL types.
[libs/gl.git] / source / glsl / generate.cpp
1 #include <msp/core/hash.h>
2 #include <msp/core/raii.h>
3 #include <msp/strings/lexicalcast.h>
4 #include "builtin.h"
5 #include "generate.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GL {
11 namespace SL {
12
13 void DeclarationCombiner::apply(Stage &stage)
14 {
15         stage.content.visit(*this);
16         NodeRemover().apply(stage, nodes_to_remove);
17 }
18
19 void DeclarationCombiner::visit(Block &block)
20 {
21         if(current_block)
22                 return;
23
24         TraversingVisitor::visit(block);
25 }
26
27 void DeclarationCombiner::visit(VariableDeclaration &var)
28 {
29         VariableDeclaration *&ptr = variables[var.name];
30         if(ptr)
31         {
32                 ptr->type = var.type;
33                 if(var.init_expression)
34                         ptr->init_expression = var.init_expression;
35                 if(var.layout)
36                 {
37                         if(ptr->layout)
38                         {
39                                 for(vector<Layout::Qualifier>::iterator i=var.layout->qualifiers.begin(); i!=var.layout->qualifiers.end(); ++i)
40                                 {
41                                         bool found = false;
42                                         for(vector<Layout::Qualifier>::iterator j=ptr->layout->qualifiers.begin(); (!found && j!=ptr->layout->qualifiers.end()); ++j)
43                                                 if(j->name==i->name)
44                                                 {
45                                                         j->has_value = i->value;
46                                                         j->value = i->value;
47                                                         found = true;
48                                                 }
49
50                                         if(!found)
51                                                 ptr->layout->qualifiers.push_back(*i);
52                                 }
53                         }
54                         else
55                                 ptr->layout = var.layout;
56                 }
57                 nodes_to_remove.insert(&var);
58         }
59         else
60                 ptr = &var;
61 }
62
63
64 ConstantSpecializer::ConstantSpecializer():
65         values(0)
66 { }
67
68 void ConstantSpecializer::apply(Stage &stage, const map<string, int> *v)
69 {
70         values = v;
71         stage.content.visit(*this);
72 }
73
74 void ConstantSpecializer::visit(VariableDeclaration &var)
75 {
76         bool specializable = false;
77         if(var.layout)
78         {
79                 vector<Layout::Qualifier> &qualifiers = var.layout->qualifiers;
80                 for(vector<Layout::Qualifier>::iterator i=qualifiers.begin(); i!=qualifiers.end(); ++i)
81                         if(i->name=="constant_id")
82                         {
83                                 specializable = true;
84                                 if(values)
85                                         qualifiers.erase(i);
86                                 else if(i->value==-1)
87                                         i->value = hash32(var.name)&0x7FFFFFFF;
88                                 break;
89                         }
90
91                 if(qualifiers.empty())
92                         var.layout = 0;
93         }
94
95         if(specializable && values)
96         {
97                 map<string, int>::const_iterator i = values->find(var.name);
98                 if(i!=values->end())
99                 {
100                         RefPtr<Literal> literal = new Literal;
101                         if(var.type=="bool")
102                                 literal->token = (i->second ? "true" : "false");
103                         else if(var.type=="int")
104                                 literal->token = lexical_cast<string>(i->second);
105                         var.init_expression = literal;
106                 }
107         }
108 }
109
110
111 void BlockHierarchyResolver::enter(Block &block)
112 {
113         block.parent = current_block;
114 }
115
116
117 TypeResolver::TypeResolver():
118         stage(0)
119 { }
120
121 void TypeResolver::apply(Stage &s)
122 {
123         stage = &s;
124         s.types.clear();
125         s.content.visit(*this);
126 }
127
128 void TypeResolver::visit(BasicTypeDeclaration &type)
129 {
130         map<string, TypeDeclaration *>::iterator i = stage->types.find(type.base);
131         type.base_type = (i!=stage->types.end() ? i->second : 0);
132
133         if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
134                 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
135                         if(basic_base->kind==BasicTypeDeclaration::VECTOR)
136                         {
137                                 type.kind = BasicTypeDeclaration::MATRIX;
138                                 type.size |= basic_base->size<<16;
139                         }
140
141         stage->types.insert(make_pair(type.name, &type));
142 }
143
144 void TypeResolver::visit(ImageTypeDeclaration &type)
145 {
146         map<string, TypeDeclaration *>::iterator i = stage->types.find(type.base);
147         type.base_type = (i!=stage->types.end() ? i->second : 0);
148
149         stage->types.insert(make_pair(type.name, &type));
150 }
151
152 void TypeResolver::visit(StructDeclaration &strct)
153 {
154         stage->types.insert(make_pair(strct.name, &strct));
155         TraversingVisitor::visit(strct);
156 }
157
158 void TypeResolver::visit(VariableDeclaration &var)
159 {
160         map<string, TypeDeclaration *>::iterator i = stage->types.find(var.type);
161         if(i!=stage->types.end())
162                 var.type_declaration = i->second;
163 }
164
165
166 VariableResolver::VariableResolver():
167         stage(0),
168         r_members(0),
169         record_target(false),
170         r_self_referencing(false),
171         r_assignment_target(0)
172 { }
173
174 void VariableResolver::apply(Stage &s)
175 {
176         stage = &s;
177         s.interface_blocks.clear();
178         s.content.visit(*this);
179 }
180
181 void VariableResolver::enter(Block &block)
182 {
183         block.variables.clear();
184 }
185
186 void VariableResolver::visit(VariableReference &var)
187 {
188         var.declaration = 0;
189         r_members = 0;
190         /* Look for variable declarations in the block hierarchy first.  Interface
191         blocks are always defined in the top level so we can't accidentally skip
192         one. */
193         for(Block *block=current_block; (!var.declaration && block); block=block->parent)
194         {
195                 map<string, VariableDeclaration *>::iterator i = block->variables.find(var.name);
196                 if(i!=block->variables.end())
197                         var.declaration = i->second;
198         }
199
200         if(var.declaration)
201         {
202                 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(var.declaration->type_declaration))
203                         r_members = &strct->members.variables;
204         }
205         else
206         {
207                 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
208                 map<string, InterfaceBlock *>::const_iterator i = blocks.find("_"+var.name);
209                 if(i!=blocks.end())
210                 {
211                         /* The name refers to an interface block with an instance name rather
212                         than a variable.  Prepare a new syntax tree node accordingly. */
213                         r_iface_ref = new InterfaceBlockReference;
214                         r_iface_ref->name = var.name;
215                         r_iface_ref->declaration = i->second;
216                         r_members = &i->second->members.variables;
217                 }
218                 else
219                 {
220                         // Look for the variable in anonymous interface blocks.
221                         for(i=blocks.begin(); (!var.declaration && i!=blocks.end()); ++i)
222                                 if(i->second->instance_name.empty())
223                                 {
224                                         map<string, VariableDeclaration *>::iterator j = i->second->members.variables.find(var.name);
225                                         if(j!=i->second->members.variables.end())
226                                                 var.declaration = j->second;
227                                 }
228                 }
229         }
230
231         if(record_target)
232         {
233                 if(r_assignment_target)
234                 {
235                         /* More than one variable reference found in assignment target.
236                         Unable to determine what the primary target is. */
237                         record_target = false;
238                         r_assignment_target = 0;
239                 }
240                 else
241                         r_assignment_target = var.declaration;
242         }
243         else if(var.declaration && var.declaration==r_assignment_target)
244                 r_self_referencing = true;
245 }
246
247 void VariableResolver::visit(InterfaceBlockReference &iface)
248 {
249         iface.declaration = 0;
250         for(Block *block=current_block; block; block=block->parent)
251         {
252                 map<string, InterfaceBlock *>::iterator i = stage->interface_blocks.find("_"+iface.name);
253                 if(i!=stage->interface_blocks.end())
254                 {
255                         iface.declaration = i->second;
256                         r_members = &i->second->members.variables;
257                         break;
258                 }
259         }
260 }
261
262 void VariableResolver::visit(MemberAccess &memacc)
263 {
264         r_members = 0;
265         r_iface_ref = 0;
266         memacc.left->visit(*this);
267
268         if(r_iface_ref)
269                 memacc.left = r_iface_ref;
270         r_iface_ref = 0;
271
272         memacc.declaration = 0;
273         if(r_members)
274         {
275                 map<string, VariableDeclaration *>::iterator i = r_members->find(memacc.member);
276                 if(i!=r_members->end())
277                 {
278                         memacc.declaration = i->second;
279                         if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second->type_declaration))
280                                 r_members = &strct->members.variables;
281                 }
282                 else
283                         r_members = 0;
284         }
285 }
286
287 void VariableResolver::visit(UnaryExpression &unary)
288 {
289         TraversingVisitor::visit(unary);
290         r_members = 0;
291         r_iface_ref = 0;
292 }
293
294 void VariableResolver::visit(BinaryExpression &binary)
295 {
296         if(binary.oper->token[0]=='[')
297         {
298                 {
299                         /* The subscript expression is not a part of the primary assignment
300                         target. */
301                         SetFlag set(record_target, false);
302                         binary.right->visit(*this);
303                 }
304                 r_members = 0;
305                 r_iface_ref = 0;
306                 binary.left->visit(*this);
307                 if(r_iface_ref)
308                         binary.left = r_iface_ref;
309         }
310         else
311         {
312                 TraversingVisitor::visit(binary);
313                 r_members = 0;
314         }
315
316         r_iface_ref = 0;
317 }
318
319 void VariableResolver::visit(Assignment &assign)
320 {
321         {
322                 SetFlag set(record_target);
323                 r_assignment_target = 0;
324                 assign.left->visit(*this);
325                 assign.target_declaration = r_assignment_target;
326         }
327
328         r_self_referencing = false;
329         assign.right->visit(*this);
330         assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
331
332         r_members = 0;
333         r_iface_ref = 0;
334 }
335
336 void VariableResolver::visit(FunctionCall &call)
337 {
338         TraversingVisitor::visit(call);
339         r_members = 0;
340         r_iface_ref = 0;
341 }
342
343 void VariableResolver::visit(VariableDeclaration &var)
344 {
345         if(!block_interface.empty() && var.interface.empty())
346                 var.interface = block_interface;
347
348         TraversingVisitor::visit(var);
349         current_block->variables.insert(make_pair(var.name, &var));
350 }
351
352 void VariableResolver::visit(InterfaceBlock &iface)
353 {
354         /* Block names can be reused in different interfaces.  Prefix the name with
355         the first character of the interface to avoid conflicts. */
356         stage->interface_blocks.insert(make_pair(iface.interface+iface.name, &iface));
357         if(!iface.instance_name.empty())
358                 stage->interface_blocks.insert(make_pair("_"+iface.instance_name, &iface));
359
360         SetForScope<string> set_iface(block_interface, iface.interface);
361         TraversingVisitor::visit(iface);
362 }
363
364
365 void FunctionResolver::apply(Stage &s)
366 {
367         stage = &s;
368         s.functions.clear();
369         s.content.visit(*this);
370 }
371
372 void FunctionResolver::visit(FunctionCall &call)
373 {
374         map<string, FunctionDeclaration *>::iterator i = stage->functions.find(call.name);
375         if(i!=stage->functions.end())
376                 call.declaration = i->second;
377
378         TraversingVisitor::visit(call);
379 }
380
381 void FunctionResolver::visit(FunctionDeclaration &func)
382 {
383         FunctionDeclaration *&stage_decl = stage->functions[func.name];
384         vector<FunctionDeclaration *> &decls = declarations[func.name];
385         if(func.definition==&func)
386         {
387                 stage_decl = &func;
388
389                 // Set all previous declarations to use this definition.
390                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
391                 {
392                         (*i)->definition = func.definition;
393                         (*i)->body.body.clear();
394                 }
395         }
396         else
397         {
398                 func.definition = 0;
399                 if(!stage_decl)
400                         stage_decl = &func;
401                 else
402                         func.definition = stage_decl->definition;
403         }
404         decls.push_back(&func);
405
406         TraversingVisitor::visit(func);
407 }
408
409
410 InterfaceGenerator::InterfaceGenerator():
411         stage(0),
412         function_scope(false),
413         iface_block(0),
414         copy_block(false),
415         iface_target_block(0)
416 { }
417
418 string InterfaceGenerator::get_out_prefix(Stage::Type type)
419 {
420         if(type==Stage::VERTEX)
421                 return "_vs_out_";
422         else if(type==Stage::GEOMETRY)
423                 return "_gs_out_";
424         else
425                 return string();
426 }
427
428 void InterfaceGenerator::apply(Stage &s)
429 {
430         stage = &s;
431         iface_target_block = &stage->content;
432         if(stage->previous)
433                 in_prefix = get_out_prefix(stage->previous->type);
434         out_prefix = get_out_prefix(stage->type);
435         s.content.visit(*this);
436         NodeRemover().apply(s, nodes_to_remove);
437 }
438
439 void InterfaceGenerator::visit(Block &block)
440 {
441         SetForScope<Block *> set_block(current_block, &block);
442         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
443         {
444                 assignment_insert_point = i;
445                 if(&block==&stage->content)
446                         iface_insert_point = i;
447
448                 (*i)->visit(*this);
449         }
450 }
451
452 string InterfaceGenerator::change_prefix(const string &name, const string &prefix) const
453 {
454         unsigned offset = (name.compare(0, in_prefix.size(), in_prefix) ? 0 : in_prefix.size());
455         return prefix+name.substr(offset);
456 }
457
458 VariableDeclaration *InterfaceGenerator::generate_interface(VariableDeclaration &var, const string &iface, const string &name)
459 {
460         if(stage->content.variables.count(name))
461                 return 0;
462
463         VariableDeclaration* iface_var = new VariableDeclaration;
464         iface_var->sampling = var.sampling;
465         iface_var->interface = iface;
466         iface_var->type = var.type;
467         iface_var->name = name;
468         /* Geometry shader inputs are always arrays.  But if we're bringing in an
469         entire block, the array is on the block and not individual variables. */
470         if(stage->type==Stage::GEOMETRY && !copy_block)
471                 iface_var->array = ((var.array && var.interface!="in") || iface=="in");
472         else
473                 iface_var->array = var.array;
474         if(iface_var->array)
475                 iface_var->array_size = var.array_size;
476         if(iface=="in")
477         {
478                 iface_var->layout = var.layout;
479                 iface_var->linked_declaration = &var;
480                 var.linked_declaration = iface_var;
481         }
482
483         iface_target_block->body.insert(iface_insert_point, iface_var);
484         iface_target_block->variables.insert(make_pair(name, iface_var));
485
486         return iface_var;
487 }
488
489 InterfaceBlock *InterfaceGenerator::generate_interface(InterfaceBlock &out_block)
490 {
491         if(stage->interface_blocks.count("in"+out_block.name))
492                 return 0;
493
494         InterfaceBlock *in_block = new InterfaceBlock;
495         in_block->interface = "in";
496         in_block->name = out_block.name;
497         in_block->instance_name = out_block.instance_name;
498         if(stage->type==Stage::GEOMETRY)
499                 in_block->array = true;
500         else
501                 in_block->array = out_block.array;
502         in_block->linked_block = &out_block;
503         out_block.linked_block = in_block;
504
505         {
506                 SetFlag set_copy(copy_block, true);
507                 SetForScope<Block *> set_target(iface_target_block, &in_block->members);
508                 SetForScope<NodeList<Statement>::iterator> set_ins_pt(iface_insert_point, in_block->members.body.end());
509                 out_block.members.visit(*this);
510         }
511
512         iface_target_block->body.insert(iface_insert_point, in_block);
513         stage->interface_blocks.insert(make_pair("in"+in_block->name, in_block));
514         if(!in_block->instance_name.empty())
515                 stage->interface_blocks.insert(make_pair("_"+in_block->instance_name, in_block));
516
517         SetFlag set_scope(function_scope, false);
518         SetForScope<Block *> set_block(current_block, &stage->content);
519         in_block->visit(*this);
520
521         return in_block;
522 }
523
524 ExpressionStatement &InterfaceGenerator::insert_assignment(const string &left, Expression *right)
525 {
526         Assignment *assign = new Assignment;
527         VariableReference *ref = new VariableReference;
528         ref->name = left;
529         assign->left = ref;
530         assign->oper = &Operator::get_operator("=", Operator::BINARY);
531         assign->right = right;
532
533         ExpressionStatement *stmt = new ExpressionStatement;
534         stmt->expression = assign;
535         current_block->body.insert(assignment_insert_point, stmt);
536         stmt->visit(*this);
537
538         return *stmt;
539 }
540
541 void InterfaceGenerator::visit(VariableReference &var)
542 {
543         if(var.declaration || !stage->previous)
544                 return;
545         /* Don't pull a variable from previous stage if we just generated an output
546         interface in this stage */
547         if(stage->content.variables.count(var.name))
548                 return;
549
550         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
551         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
552         if(i==prev_vars.end() || i->second->interface!="out")
553                 i = prev_vars.find(in_prefix+var.name);
554         if(i!=prev_vars.end() && i->second->interface=="out")
555         {
556                 generate_interface(*i->second, "in", i->second->name);
557                 var.name = i->second->name;
558                 return;
559         }
560
561         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
562         map<string, InterfaceBlock *>::const_iterator j = prev_blocks.find("_"+var.name);
563         if(j!=prev_blocks.end() && j->second->interface=="out")
564         {
565                 generate_interface(*j->second);
566                 /* Let VariableResolver convert the variable reference into an interface
567                 block reference. */
568                 return;
569         }
570
571         for(j=prev_blocks.begin(); j!=prev_blocks.end(); ++j)
572                 if(j->second->instance_name.empty())
573                 {
574                         i = j->second->members.variables.find(var.name);
575                         if(i!=j->second->members.variables.end())
576                         {
577                                 generate_interface(*j->second);
578                                 return;
579                         }
580                 }
581 }
582
583 void InterfaceGenerator::visit(VariableDeclaration &var)
584 {
585         if(copy_block)
586         {
587                 generate_interface(var, "in", var.name);
588                 return;
589         }
590
591         if(iface_block)
592         {
593                 if(iface_block->linked_block)
594                 {
595                         // Link all variables to their counterparts in the linked block.
596                         const map<string, VariableDeclaration *> &linked_vars = iface_block->linked_block->members.variables;
597                         map<string, VariableDeclaration *>::const_iterator i = linked_vars.find(var.name);
598                         if(i!=linked_vars.end())
599                         {
600                                 var.linked_declaration = i->second;
601                                 var.linked_declaration->linked_declaration = &var;
602                         }
603                 }
604                 return;
605         }
606
607         if(var.interface=="out")
608         {
609                 /* For output variables in function scope, generate a global interface
610                 and replace the local declaration with an assignment. */
611                 VariableDeclaration *out_var = 0;
612                 if(function_scope && (out_var=generate_interface(var, "out", var.name)))
613                 {
614                         out_var->source = var.source;
615                         out_var->line = var.line;
616                         nodes_to_remove.insert(&var);
617                         if(var.init_expression)
618                         {
619                                 ExpressionStatement &stmt = insert_assignment(var.name, var.init_expression->clone());
620                                 stmt.source = var.source;
621                                 stmt.line = var.line;
622                                 return;
623                         }
624                 }
625         }
626         else if(var.interface=="in")
627         {
628                 /* Try to link input variables in global scope with output variables from
629                 previous stage. */
630                 if(current_block==&stage->content && !var.linked_declaration && stage->previous)
631                 {
632                         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
633                         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
634                         if(i!=prev_vars.end() && i->second->interface=="out")
635                         {
636                                 var.linked_declaration = i->second;
637                                 i->second->linked_declaration = &var;
638                         }
639                 }
640         }
641
642         TraversingVisitor::visit(var);
643 }
644
645 void InterfaceGenerator::visit(InterfaceBlock &iface)
646 {
647         if(iface.interface=="in")
648         {
649                 /* Try to link input blocks with output blocks sharing the same block
650                 name from previous stage. */
651                 if(!iface.linked_block && stage->previous)
652                 {
653                         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
654                         map<string, InterfaceBlock *>::const_iterator i = prev_blocks.find("out"+iface.name);
655                         if(i!=prev_blocks.end())
656                         {
657                                 iface.linked_block = i->second;
658                                 i->second->linked_block = &iface;
659                         }
660                 }
661         }
662
663         SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
664         TraversingVisitor::visit(iface);
665 }
666
667 void InterfaceGenerator::visit(FunctionDeclaration &func)
668 {
669         SetFlag set_scope(function_scope, true);
670         // Skip parameters because they're not useful here
671         func.body.visit(*this);
672 }
673
674 void InterfaceGenerator::visit(Passthrough &pass)
675 {
676         vector<VariableDeclaration *> pass_vars;
677
678         // Pass through all input variables of this stage.
679         for(map<string, VariableDeclaration *>::const_iterator i=stage->content.variables.begin(); i!=stage->content.variables.end(); ++i)
680                 if(i->second->interface=="in")
681                         pass_vars.push_back(i->second);
682
683         if(stage->previous)
684         {
685                 const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
686                 for(map<string, VariableDeclaration *>::const_iterator i=prev_vars.begin(); i!=prev_vars.end(); ++i)
687                 {
688                         if(i->second->interface!="out")
689                                 continue;
690
691                         /* Pass through output variables from the previous stage, but only
692                         those which are not already linked to an input here. */
693                         if(!i->second->linked_declaration && generate_interface(*i->second, "in", i->second->name))
694                                 pass_vars.push_back(i->second);
695                 }
696         }
697
698         if(stage->type==Stage::GEOMETRY)
699         {
700                 /* Special case for geometry shader: copy gl_Position from input to
701                 output. */
702                 InterfaceBlockReference *ref = new InterfaceBlockReference;
703                 ref->name = "gl_in";
704
705                 BinaryExpression *subscript = new BinaryExpression;
706                 subscript->left = ref;
707                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
708                 subscript->right = pass.subscript;
709
710                 MemberAccess *memacc = new MemberAccess;
711                 memacc->left = subscript;
712                 memacc->member = "gl_Position";
713
714                 insert_assignment("gl_Position", memacc);
715         }
716
717         for(vector<VariableDeclaration *>::const_iterator i=pass_vars.begin(); i!=pass_vars.end(); ++i)
718         {
719                 string out_name = change_prefix((*i)->name, out_prefix);
720                 generate_interface(**i, "out", out_name);
721
722                 VariableReference *ref = new VariableReference;
723                 ref->name = (*i)->name;
724                 if(pass.subscript)
725                 {
726                         BinaryExpression *subscript = new BinaryExpression;
727                         subscript->left = ref;
728                         subscript->oper = &Operator::get_operator("[", Operator::BINARY);
729                         subscript->right = pass.subscript;
730                         insert_assignment(out_name, subscript);
731                 }
732                 else
733                         insert_assignment(out_name, ref);
734         }
735
736         nodes_to_remove.insert(&pass);
737 }
738
739 } // namespace SL
740 } // namespace GL
741 } // namespace Msp