]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/generate.cpp
Some rearranging and comments
[libs/gl.git] / source / glsl / generate.cpp
1 #include <algorithm>
2 #include <msp/core/hash.h>
3 #include <msp/core/raii.h>
4 #include <msp/strings/lexicalcast.h>
5 #include <msp/strings/utils.h>
6 #include "builtin.h"
7 #include "generate.h"
8
9 using namespace std;
10
11 namespace Msp {
12 namespace GL {
13 namespace SL {
14
15 void DeclarationCombiner::apply(Stage &stage)
16 {
17         stage.content.visit(*this);
18         NodeRemover().apply(stage, nodes_to_remove);
19 }
20
21 void DeclarationCombiner::visit(Block &block)
22 {
23         if(current_block)
24                 return;
25
26         TraversingVisitor::visit(block);
27 }
28
29 void DeclarationCombiner::visit(VariableDeclaration &var)
30 {
31         VariableDeclaration *&ptr = variables[var.name];
32         if(ptr)
33         {
34                 ptr->type = var.type;
35                 if(var.init_expression)
36                         ptr->init_expression = var.init_expression;
37                 if(var.layout)
38                 {
39                         if(ptr->layout)
40                         {
41                                 for(vector<Layout::Qualifier>::iterator i=var.layout->qualifiers.begin(); i!=var.layout->qualifiers.end(); ++i)
42                                 {
43                                         bool found = false;
44                                         for(vector<Layout::Qualifier>::iterator j=ptr->layout->qualifiers.begin(); (!found && j!=ptr->layout->qualifiers.end()); ++j)
45                                                 if(j->name==i->name)
46                                                 {
47                                                         j->has_value = i->value;
48                                                         j->value = i->value;
49                                                         found = true;
50                                                 }
51
52                                         if(!found)
53                                                 ptr->layout->qualifiers.push_back(*i);
54                                 }
55                         }
56                         else
57                                 ptr->layout = var.layout;
58                 }
59                 nodes_to_remove.insert(&var);
60         }
61         else
62                 ptr = &var;
63 }
64
65
66 ConstantSpecializer::ConstantSpecializer():
67         values(0)
68 { }
69
70 void ConstantSpecializer::apply(Stage &stage, const map<string, int> *v)
71 {
72         values = v;
73         stage.content.visit(*this);
74 }
75
76 void ConstantSpecializer::visit(VariableDeclaration &var)
77 {
78         bool specializable = false;
79         if(var.layout)
80         {
81                 vector<Layout::Qualifier> &qualifiers = var.layout->qualifiers;
82                 for(vector<Layout::Qualifier>::iterator i=qualifiers.begin(); i!=qualifiers.end(); ++i)
83                         if(i->name=="constant_id")
84                         {
85                                 specializable = true;
86                                 if(values)
87                                         qualifiers.erase(i);
88                                 else if(i->value==-1)
89                                         i->value = hash32(var.name)&0x7FFFFFFF;
90                                 break;
91                         }
92
93                 if(qualifiers.empty())
94                         var.layout = 0;
95         }
96
97         if(specializable && values)
98         {
99                 map<string, int>::const_iterator i = values->find(var.name);
100                 if(i!=values->end())
101                 {
102                         RefPtr<Literal> literal = new Literal;
103                         if(var.type=="bool")
104                         {
105                                 literal->token = (i->second ? "true" : "false");
106                                 literal->value = static_cast<bool>(i->second);
107                         }
108                         else if(var.type=="int")
109                         {
110                                 literal->token = lexical_cast<string>(i->second);
111                                 literal->value = i->second;
112                         }
113                         var.init_expression = literal;
114                 }
115         }
116 }
117
118
119 void BlockHierarchyResolver::enter(Block &block)
120 {
121         r_any_resolved |= (current_block!=block.parent);
122         block.parent = current_block;
123 }
124
125
126 TypeResolver::TypeResolver():
127         stage(0),
128         iface_block(0),
129         r_any_resolved(false)
130 { }
131
132 bool TypeResolver::apply(Stage &s)
133 {
134         stage = &s;
135         s.types.clear();
136         r_any_resolved = false;
137         s.content.visit(*this);
138         return r_any_resolved;
139 }
140
141 TypeDeclaration *TypeResolver::get_or_create_array_type(TypeDeclaration &type)
142 {
143         map<TypeDeclaration *, TypeDeclaration *>::iterator i = array_types.find(&type);
144         if(i!=array_types.end())
145                 return i->second;
146
147         BasicTypeDeclaration *array = new BasicTypeDeclaration;
148         array->source = BUILTIN_SOURCE;
149         array->name = type.name+"[]";
150         array->kind = BasicTypeDeclaration::ARRAY;
151         array->base = type.name;
152         array->base_type = &type;
153         stage->content.body.insert(type_insert_point, array);
154         array_types[&type] = array;
155         return array;
156 }
157
158 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array)
159 {
160         TypeDeclaration *resolved = 0;
161         map<string, TypeDeclaration *>::iterator i = stage->types.find(name);
162         if(i!=stage->types.end())
163         {
164                 map<TypeDeclaration *, TypeDeclaration *>::iterator j = alias_map.find(i->second);
165                 resolved = (j!=alias_map.end() ? j->second : i->second);
166         }
167
168         if(resolved && array)
169                 resolved = get_or_create_array_type(*resolved);
170
171         r_any_resolved |= (resolved!=type);
172         type=resolved;
173 }
174
175 void TypeResolver::visit(Block &block)
176 {
177         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
178         {
179                 if(!block.parent)
180                         type_insert_point = i;
181                 (*i)->visit(*this);
182         }
183 }
184
185 void TypeResolver::visit(BasicTypeDeclaration &type)
186 {
187         resolve_type(type.base_type, type.base, false);
188
189         if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
190                 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
191                         if(basic_base->kind==BasicTypeDeclaration::VECTOR)
192                         {
193                                 type.kind = BasicTypeDeclaration::MATRIX;
194                                 /* A matrix's base type is its column vector type.  This will put
195                                 the column vector's size, i.e. the matrix's row count, in the high
196                                 half of the size. */
197                                 type.size |= basic_base->size<<16;
198                         }
199
200         if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
201                 alias_map[&type] = type.base_type;
202         else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
203                 array_types[type.base_type] = &type;
204
205         stage->types.insert(make_pair(type.name, &type));
206 }
207
208 void TypeResolver::visit(ImageTypeDeclaration &type)
209 {
210         resolve_type(type.base_type, type.base, false);
211         stage->types.insert(make_pair(type.name, &type));
212 }
213
214 void TypeResolver::visit(StructDeclaration &strct)
215 {
216         stage->types.insert(make_pair(strct.name, &strct));
217         TraversingVisitor::visit(strct);
218 }
219
220 void TypeResolver::visit(VariableDeclaration &var)
221 {
222         resolve_type(var.type_declaration, var.type, var.array);
223         if(iface_block && var.interface==iface_block->interface)
224                 var.interface.clear();
225 }
226
227 void TypeResolver::visit(InterfaceBlock &iface)
228 {
229         if(iface.members)
230         {
231                 SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
232                 iface.members->visit(*this);
233
234                 StructDeclaration *strct = new StructDeclaration;
235                 strct->source = INTERNAL_SOURCE;
236                 strct->name = format("_%s_%s", iface.interface, iface.name);
237                 strct->members.body.splice(strct->members.body.begin(), iface.members->body);
238                 stage->content.body.insert(type_insert_point, strct);
239                 stage->types.insert(make_pair(strct->name, strct));
240
241                 iface.members = 0;
242                 strct->interface_block = &iface;
243                 iface.struct_declaration = strct;
244         }
245
246         TypeDeclaration *type = iface.struct_declaration;
247         if(type && iface.array)
248                 type = get_or_create_array_type(*type);
249         r_any_resolved = (type!=iface.type_declaration);
250         iface.type_declaration = type;
251 }
252
253 void TypeResolver::visit(FunctionDeclaration &func)
254 {
255         resolve_type(func.return_type_declaration, func.return_type, false);
256         TraversingVisitor::visit(func);
257 }
258
259
260 VariableResolver::VariableResolver():
261         stage(0),
262         r_any_resolved(false),
263         record_target(false),
264         r_self_referencing(false)
265 { }
266
267 bool VariableResolver::apply(Stage &s)
268 {
269         stage = &s;
270         s.interface_blocks.clear();
271         r_any_resolved = false;
272         s.content.visit(*this);
273         return r_any_resolved;
274 }
275
276 void VariableResolver::enter(Block &block)
277 {
278         block.variables.clear();
279 }
280
281 void VariableResolver::visit(RefPtr<Expression> &expr)
282 {
283         r_replacement_expr = 0;
284         expr->visit(*this);
285         if(r_replacement_expr)
286         {
287                 expr = r_replacement_expr;
288                 /* Don't record assignment target when doing a replacement, because chain
289                 information won't be correct. */
290                 r_assignment_target.declaration = 0;
291                 r_any_resolved = true;
292         }
293         r_replacement_expr = 0;
294 }
295
296 void VariableResolver::check_assignment_target(Statement *declaration)
297 {
298         if(record_target)
299         {
300                 if(r_assignment_target.declaration)
301                 {
302                         /* More than one reference found in assignment target.  Unable to
303                         determine what the primary target is. */
304                         record_target = false;
305                         r_assignment_target.declaration = 0;
306                 }
307                 else
308                         r_assignment_target.declaration = declaration;
309         }
310         // TODO This check is overly broad and may prevent some optimizations.
311         else if(declaration && declaration==r_assignment_target.declaration)
312                 r_self_referencing = true;
313 }
314
315 void VariableResolver::visit(VariableReference &var)
316 {
317         VariableDeclaration *declaration = 0;
318
319         /* Look for variable declarations in the block hierarchy first.  Interface
320         blocks are always defined in the top level so we can't accidentally skip
321         one. */
322         for(Block *block=current_block; (!declaration && block); block=block->parent)
323         {
324                 map<string, VariableDeclaration *>::iterator i = block->variables.find(var.name);
325                 if(i!=block->variables.end())
326                         declaration = i->second;
327         }
328
329         if(!declaration)
330         {
331                 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
332                 map<string, InterfaceBlock *>::const_iterator i = blocks.find("_"+var.name);
333                 if(i!=blocks.end())
334                 {
335                         /* The name refers to an interface block with an instance name rather
336                         than a variable.  Prepare a new syntax tree node accordingly. */
337                         InterfaceBlockReference *iface_ref = new InterfaceBlockReference;
338                         iface_ref->source = var.source;
339                         iface_ref->line = var.line;
340                         iface_ref->name = var.name;
341                         iface_ref->declaration = i->second;
342                         r_replacement_expr = iface_ref;
343                 }
344                 else
345                 {
346                         // Look for the variable in anonymous interface blocks.
347                         for(i=blocks.begin(); (!declaration && i!=blocks.end()); ++i)
348                                 if(i->second->instance_name.empty() && i->second->struct_declaration)
349                                 {
350                                         const map<string, VariableDeclaration *> &iface_vars = i->second->struct_declaration->members.variables;
351                                         map<string, VariableDeclaration *>::const_iterator j = iface_vars.find(var.name);
352                                         if(j!=iface_vars.end())
353                                                 declaration = j->second;
354                                 }
355                 }
356         }
357
358         r_any_resolved |= (declaration!=var.declaration);
359         var.declaration = declaration;
360
361         check_assignment_target(var.declaration);
362 }
363
364 void VariableResolver::visit(InterfaceBlockReference &iface)
365 {
366         map<string, InterfaceBlock *>::iterator i = stage->interface_blocks.find("_"+iface.name);
367         InterfaceBlock *declaration = (i!=stage->interface_blocks.end() ? i->second : 0);
368         r_any_resolved |= (declaration!=iface.declaration);
369         iface.declaration = declaration;
370
371         check_assignment_target(iface.declaration);
372 }
373
374 void VariableResolver::add_to_chain(Assignment::Target::ChainType type, unsigned index)
375 {
376         if(r_assignment_target.chain_len<7)
377                 r_assignment_target.chain[r_assignment_target.chain_len] = type | min<unsigned>(index, 0x3F);
378         ++r_assignment_target.chain_len;
379 }
380
381 void VariableResolver::visit(MemberAccess &memacc)
382 {
383         TraversingVisitor::visit(memacc);
384
385         VariableDeclaration *declaration = 0;
386         if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
387         {
388                 map<string, VariableDeclaration *>::iterator i = strct->members.variables.find(memacc.member);
389                 if(i!=strct->members.variables.end())
390                 {
391                         declaration = i->second;
392
393                         if(record_target)
394                         {
395                                 unsigned index = 0;
396                                 for(NodeList<Statement>::const_iterator j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
397                                         ++index;
398
399                                 add_to_chain(Assignment::Target::MEMBER, index);
400                         }
401                 }
402         }
403         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
404         {
405                 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
406                 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
407                 if(scalar_swizzle || vector_swizzle)
408                 {
409                         static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
410
411                         bool ok = true;
412                         UInt8 components[4] = { };
413                         for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
414                                 ok = ((components[i] = (find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
415
416                         if(ok)
417                         {
418                                 Swizzle *swizzle = new Swizzle;
419                                 swizzle->source = memacc.source;
420                                 swizzle->line = memacc.line;
421                                 swizzle->oper = memacc.oper;
422                                 swizzle->left = memacc.left;
423                                 swizzle->component_group = memacc.member;
424                                 swizzle->count = memacc.member.size();
425                                 copy(components, components+memacc.member.size(), swizzle->components);
426                                 r_replacement_expr = swizzle;
427                         }
428                 }
429         }
430
431         r_any_resolved |= (declaration!=memacc.declaration);
432         memacc.declaration = declaration;
433 }
434
435 void VariableResolver::visit(Swizzle &swizzle)
436 {
437         TraversingVisitor::visit(swizzle);
438
439         if(record_target)
440         {
441                 unsigned mask = 0;
442                 for(unsigned i=0; i<swizzle.count; ++i)
443                         mask |= 1<<swizzle.components[i];
444                 add_to_chain(Assignment::Target::SWIZZLE, mask);
445         }
446 }
447
448 void VariableResolver::visit(BinaryExpression &binary)
449 {
450         if(binary.oper->token[0]=='[')
451         {
452                 {
453                         /* The subscript expression is not a part of the primary assignment
454                         target. */
455                         SetFlag set(record_target, false);
456                         visit(binary.right);
457                 }
458                 visit(binary.left);
459
460                 if(record_target)
461                 {
462                         unsigned index = 0x3F;
463                         if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
464                                 if(literal_subscript->value.check_type<int>())
465                                         index = literal_subscript->value.value<int>();
466                         add_to_chain(Assignment::Target::ARRAY, index);
467                 }
468         }
469         else
470                 TraversingVisitor::visit(binary);
471 }
472
473 void VariableResolver::visit(Assignment &assign)
474 {
475         {
476                 SetFlag set(record_target);
477                 r_assignment_target = Assignment::Target();
478                 visit(assign.left);
479                 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
480                 assign.target = r_assignment_target;
481         }
482
483         r_self_referencing = false;
484         visit(assign.right);
485         assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
486 }
487
488 void VariableResolver::visit(VariableDeclaration &var)
489 {
490         TraversingVisitor::visit(var);
491         current_block->variables.insert(make_pair(var.name, &var));
492 }
493
494 void VariableResolver::visit(InterfaceBlock &iface)
495 {
496         /* Block names can be reused in different interfaces.  Prefix the name with
497         the first character of the interface to avoid conflicts. */
498         stage->interface_blocks.insert(make_pair(iface.interface+iface.name, &iface));
499         if(!iface.instance_name.empty())
500                 stage->interface_blocks.insert(make_pair("_"+iface.instance_name, &iface));
501
502         TraversingVisitor::visit(iface);
503 }
504
505
506 ExpressionResolver::ExpressionResolver():
507         stage(0),
508         r_any_resolved(false)
509 { }
510
511 bool ExpressionResolver::apply(Stage &s)
512 {
513         stage = &s;
514         r_any_resolved = false;
515         s.content.visit(*this);
516         return r_any_resolved;
517 }
518
519 bool ExpressionResolver::is_scalar(BasicTypeDeclaration &type)
520 {
521         return (type.kind==BasicTypeDeclaration::INT || type.kind==BasicTypeDeclaration::FLOAT);
522 }
523
524 bool ExpressionResolver::is_vector_or_matrix(BasicTypeDeclaration &type)
525 {
526         return (type.kind==BasicTypeDeclaration::VECTOR || type.kind==BasicTypeDeclaration::MATRIX);
527 }
528
529 BasicTypeDeclaration *ExpressionResolver::get_element_type(BasicTypeDeclaration &type)
530 {
531         if(is_vector_or_matrix(type) || type.kind==BasicTypeDeclaration::ARRAY)
532         {
533                 BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type);
534                 return (basic_base ? get_element_type(*basic_base) : 0);
535         }
536         else
537                 return &type;
538 }
539
540 bool ExpressionResolver::can_convert(BasicTypeDeclaration &from, BasicTypeDeclaration &to)
541 {
542         if(from.kind==BasicTypeDeclaration::INT && to.kind==BasicTypeDeclaration::FLOAT)
543                 return from.size<=to.size;
544         else if(from.kind!=to.kind)
545                 return false;
546         else if((from.kind==BasicTypeDeclaration::VECTOR || from.kind==BasicTypeDeclaration::MATRIX) && from.size==to.size)
547         {
548                 BasicTypeDeclaration *from_base = dynamic_cast<BasicTypeDeclaration *>(from.base_type);
549                 BasicTypeDeclaration *to_base = dynamic_cast<BasicTypeDeclaration *>(to.base_type);
550                 return (from_base && to_base && can_convert(*from_base, *to_base));
551         }
552         else
553                 return false;
554 }
555
556 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
557 {
558         if(&left==&right)
559                 return SAME_TYPE;
560         else if(can_convert(left, right))
561                 return LEFT_CONVERTIBLE;
562         else if(can_convert(right, left))
563                 return RIGHT_CONVERTIBLE;
564         else
565                 return NOT_COMPATIBLE;
566 }
567
568 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size)
569 {
570         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
571                 if((*i)->kind==kind && (*i)->size==size)
572                         return *i;
573         return 0;
574 }
575
576 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
577 {
578         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
579                 if(get_element_type(**i)==&elem_type && (*i)->kind==kind && (*i)->size==size)
580                         return *i;
581         return 0;
582 }
583
584 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
585 {
586         RefPtr<FunctionCall> call = new FunctionCall;
587         call->name = type.name;
588         call->constructor = true;
589         call->arguments.push_back(0);
590         call->arguments.back() = expr;
591         call->type = &type;
592         expr = call;
593 }
594
595 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
596 {
597         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
598         {
599                 BasicTypeDeclaration *to_type = &elem_type;
600                 if(is_vector_or_matrix(*expr_basic))
601                         to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
602                 if(to_type)
603                 {
604                         convert_to(expr, *to_type);
605                         return true;
606                 }
607         }
608
609         return false;
610 }
611
612 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
613 {
614         r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
615         expr.type = type;
616         expr.lvalue = lvalue;
617 }
618
619 void ExpressionResolver::visit(Literal &literal)
620 {
621         if(literal.value.check_type<bool>())
622                 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
623         else if(literal.value.check_type<int>())
624                 resolve(literal, find_type(BasicTypeDeclaration::INT, 32), false);
625         else if(literal.value.check_type<float>())
626                 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
627 }
628
629 void ExpressionResolver::visit(ParenthesizedExpression &parexpr)
630 {
631         TraversingVisitor::visit(parexpr);
632         resolve(parexpr, parexpr.expression->type, parexpr.expression->lvalue);
633 }
634
635 void ExpressionResolver::visit(VariableReference &var)
636 {
637         if(var.declaration)
638                 resolve(var, var.declaration->type_declaration, true);
639 }
640
641 void ExpressionResolver::visit(InterfaceBlockReference &iface)
642 {
643         if(iface.declaration)
644                 resolve(iface, iface.declaration->type_declaration, true);
645 }
646
647 void ExpressionResolver::visit(MemberAccess &memacc)
648 {
649         TraversingVisitor::visit(memacc);
650
651         if(memacc.declaration)
652                 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
653 }
654
655 void ExpressionResolver::visit(Swizzle &swizzle)
656 {
657         TraversingVisitor::visit(swizzle);
658
659         if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
660         {
661                 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
662                 if(swizzle.count==1)
663                         resolve(swizzle, left_elem, swizzle.left->lvalue);
664                 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
665                         resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
666         }
667 }
668
669 void ExpressionResolver::visit(UnaryExpression &unary)
670 {
671         TraversingVisitor::visit(unary);
672
673         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
674         if(!basic)
675                 return;
676
677         char oper = unary.oper->token[0];
678         if(oper=='!')
679         {
680                 if(basic->kind!=BasicTypeDeclaration::BOOL)
681                         return;
682         }
683         else if(oper=='~')
684         {
685                 if(basic->kind!=BasicTypeDeclaration::INT)
686                         return;
687         }
688         else if(oper=='+' || oper=='-')
689         {
690                 BasicTypeDeclaration *elem = get_element_type(*basic);
691                 if(!elem || !is_scalar(*elem))
692                         return;
693         }
694         resolve(unary, basic, unary.expression->lvalue);
695 }
696
697 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
698 {
699         /* Binary operators are only defined for basic types (not for image or
700         structure types). */
701         BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
702         BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
703         if(!basic_left || !basic_right)
704                 return;
705
706         char oper = binary.oper->token[0];
707         if(oper=='[')
708         {
709                 /* Subscripting operates on vectors, matrices and arrays, and the right
710                 operand must be an integer. */
711                 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
712                         return;
713
714                 resolve(binary, basic_left->base_type, binary.left->lvalue);
715                 return;
716         }
717         else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
718                 // No other binary operator can be used with arrays.
719                 return;
720
721         BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
722         BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
723         if(!elem_left || !elem_right)
724                 return;
725
726         Compatibility compat = get_compatibility(*basic_left, *basic_right);
727         Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
728         if(elem_compat==NOT_COMPATIBLE)
729                 return;
730         if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
731                 return;
732
733         TypeDeclaration *type = 0;
734         char oper2 = binary.oper->token[1];
735         if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
736         {
737                 /* Relational operators compare two scalar integer or floating-point
738                 values. */
739                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
740                         return;
741
742                 type = find_type(BasicTypeDeclaration::BOOL, 1);
743         }
744         else if((oper=='=' || oper=='!') && oper2=='=')
745         {
746                 // Equality comparison can be done on any compatible types.
747                 if(compat==NOT_COMPATIBLE)
748                         return;
749
750                 type = find_type(BasicTypeDeclaration::BOOL, 1);
751         }
752         else if(oper2=='&' || oper2=='|' || oper2=='^')
753         {
754                 // Logical operators can only be applied to booleans.
755                 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
756                         return;
757
758                 type = basic_left;
759         }
760         else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
761         {
762                 // Bitwise operators and modulo can only be applied to integers.
763                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
764                         return;
765
766                 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
767         }
768         else if((oper=='<' || oper=='>') && oper2==oper)
769         {
770                 // Shifts apply to integer scalars and vectors, with some restrictions.
771                 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
772                         return;
773                 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
774                 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
775                 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
776                         return;
777
778                 type = basic_left;
779                 // Don't perform conversion even if the operands are of different sizes.
780                 compat = SAME_TYPE;
781         }
782         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
783         {
784                 // Arithmetic operators require scalar elements.
785                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
786                         return;
787
788                 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
789                         (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
790                 {
791                         /* Multiplication has special rules when at least one operand is a
792                         matrix and the other is a vector or a matrix. */
793                         unsigned left_columns = basic_left->size&0xFFFF;
794                         unsigned right_rows = basic_right->size;
795                         if(basic_right->kind==BasicTypeDeclaration::MATRIX)
796                                 right_rows >>= 16;
797                         if(left_columns!=right_rows)
798                                 return;
799
800                         BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
801
802                         if(basic_left->kind==BasicTypeDeclaration::VECTOR)
803                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
804                         else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
805                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
806                         else
807                                 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
808                 }
809                 else if(compat==NOT_COMPATIBLE)
810                 {
811                         // Arithmetic between scalars and matrices or vectors is supported.
812                         if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
813                                 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
814                         else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
815                                 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
816                         else
817                                 return;
818                 }
819                 else if(compat==LEFT_CONVERTIBLE)
820                         type = basic_right;
821                 else
822                         type = basic_left;
823         }
824         else
825                 return;
826
827         if(assign && type!=basic_left)
828                 return;
829
830         bool converted = true;
831         if(compat==LEFT_CONVERTIBLE)
832                 convert_to(binary.left, *basic_right);
833         else if(compat==RIGHT_CONVERTIBLE)
834                 convert_to(binary.right, *basic_left);
835         else if(elem_compat==LEFT_CONVERTIBLE)
836                 converted = convert_to_element(binary.left, *elem_right);
837         else if(elem_compat==RIGHT_CONVERTIBLE)
838                 converted = convert_to_element(binary.right, *elem_left);
839
840         if(!converted)
841                 type = 0;
842
843         resolve(binary, type, assign);
844 }
845
846 void ExpressionResolver::visit(BinaryExpression &binary)
847 {
848         TraversingVisitor::visit(binary);
849         visit(binary, false);
850 }
851
852 void ExpressionResolver::visit(Assignment &assign)
853 {
854         TraversingVisitor::visit(assign);
855
856         if(assign.oper->token[0]!='=')
857                 return visit(assign, true);
858         else if(assign.left->type!=assign.right->type)
859         {
860                 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
861                 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
862                 if(!basic_left || !basic_right)
863                         return;
864
865                 Compatibility compat = get_compatibility(*basic_left, *basic_right);
866                 if(compat==RIGHT_CONVERTIBLE)
867                         convert_to(assign.right, *basic_left);
868                 else if(compat!=SAME_TYPE)
869                         return;
870         }
871
872         resolve(assign, assign.left->type, true);
873 }
874
875 void ExpressionResolver::visit(FunctionCall &call)
876 {
877         TraversingVisitor::visit(call);
878
879         TypeDeclaration *type = 0;
880         if(call.declaration)
881                 type = call.declaration->return_type_declaration;
882         else if(call.constructor)
883         {
884                 map<string, TypeDeclaration *>::const_iterator i=stage->types.find(call.name);
885                 type = (i!=stage->types.end() ? i->second : 0);
886         }
887         resolve(call, type, false);
888 }
889
890 void ExpressionResolver::visit(BasicTypeDeclaration &type)
891 {
892         basic_types.push_back(&type);
893 }
894
895 void ExpressionResolver::visit(VariableDeclaration &var)
896 {
897         TraversingVisitor::visit(var);
898         if(!var.init_expression)
899                 return;
900
901         BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
902         BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
903         if(!var_basic || !init_basic)
904                 return;
905
906         Compatibility compat = get_compatibility(*var_basic, *init_basic);
907         if(compat==RIGHT_CONVERTIBLE)
908                 convert_to(var.init_expression, *var_basic);
909 }
910
911
912 bool FunctionResolver::apply(Stage &s)
913 {
914         stage = &s;
915         s.functions.clear();
916         r_any_resolved = false;
917         s.content.visit(*this);
918         return r_any_resolved;
919 }
920
921 void FunctionResolver::visit(FunctionCall &call)
922 {
923         string arg_types;
924         bool has_signature = true;
925         for(NodeArray<Expression>::const_iterator i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
926         {
927                 if((*i)->type)
928                         append(arg_types, ",", (*i)->type->name);
929                 else
930                         has_signature = false;
931         }
932
933         FunctionDeclaration *declaration = 0;
934         if(has_signature)
935         {
936                 map<string, FunctionDeclaration *>::iterator i = stage->functions.find(format("%s(%s)", call.name, arg_types));
937                 declaration = (i!=stage->functions.end() ? i->second : 0);
938         }
939         r_any_resolved |= (declaration!=call.declaration);
940         call.declaration = declaration;
941
942         TraversingVisitor::visit(call);
943 }
944
945 void FunctionResolver::visit(FunctionDeclaration &func)
946 {
947         if(func.signature.empty())
948         {
949                 string param_types;
950                 for(NodeArray<VariableDeclaration>::const_iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
951                 {
952                         if((*i)->type_declaration)
953                                 append(param_types, ",", (*i)->type_declaration->name);
954                         else
955                                 return;
956                 }
957                 func.signature = format("(%s)", param_types);
958                 r_any_resolved = true;
959         }
960
961         string key = func.name+func.signature;
962         FunctionDeclaration *&stage_decl = stage->functions[key];
963         vector<FunctionDeclaration *> &decls = declarations[key];
964         if(func.definition==&func)
965         {
966                 stage_decl = &func;
967
968                 // Set all previous declarations to use this definition.
969                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
970                 {
971                         r_any_resolved |= (func.definition!=(*i)->definition);
972                         (*i)->definition = func.definition;
973                         (*i)->body.body.clear();
974                 }
975         }
976         else
977         {
978                 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
979                 r_any_resolved |= (definition!=func.definition);
980                 func.definition = definition;
981
982                 if(!stage_decl)
983                         stage_decl = &func;
984         }
985         decls.push_back(&func);
986
987         TraversingVisitor::visit(func);
988 }
989
990
991 InterfaceGenerator::InterfaceGenerator():
992         stage(0),
993         function_scope(false),
994         copy_block(false),
995         iface_target_block(0)
996 { }
997
998 string InterfaceGenerator::get_out_prefix(Stage::Type type)
999 {
1000         if(type==Stage::VERTEX)
1001                 return "_vs_out_";
1002         else if(type==Stage::GEOMETRY)
1003                 return "_gs_out_";
1004         else
1005                 return string();
1006 }
1007
1008 void InterfaceGenerator::apply(Stage &s)
1009 {
1010         stage = &s;
1011         iface_target_block = &stage->content;
1012         if(stage->previous)
1013                 in_prefix = get_out_prefix(stage->previous->type);
1014         out_prefix = get_out_prefix(stage->type);
1015         s.content.visit(*this);
1016         NodeRemover().apply(s, nodes_to_remove);
1017 }
1018
1019 void InterfaceGenerator::visit(Block &block)
1020 {
1021         SetForScope<Block *> set_block(current_block, &block);
1022         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
1023         {
1024                 assignment_insert_point = i;
1025                 if(&block==&stage->content)
1026                         iface_insert_point = i;
1027
1028                 (*i)->visit(*this);
1029         }
1030 }
1031
1032 string InterfaceGenerator::change_prefix(const string &name, const string &prefix) const
1033 {
1034         unsigned offset = (name.compare(0, in_prefix.size(), in_prefix) ? 0 : in_prefix.size());
1035         return prefix+name.substr(offset);
1036 }
1037
1038 VariableDeclaration *InterfaceGenerator::generate_interface(VariableDeclaration &var, const string &iface, const string &name)
1039 {
1040         if(stage->content.variables.count(name))
1041                 return 0;
1042
1043         VariableDeclaration* iface_var = new VariableDeclaration;
1044         iface_var->sampling = var.sampling;
1045         iface_var->interface = iface;
1046         iface_var->type = var.type;
1047         iface_var->name = name;
1048         /* Geometry shader inputs are always arrays.  But if we're bringing in an
1049         entire block, the array is on the block and not individual variables. */
1050         if(stage->type==Stage::GEOMETRY && !copy_block)
1051                 iface_var->array = ((var.array && var.interface!="in") || iface=="in");
1052         else
1053                 iface_var->array = var.array;
1054         if(iface_var->array)
1055                 iface_var->array_size = var.array_size;
1056         if(iface=="in")
1057         {
1058                 iface_var->layout = var.layout;
1059                 iface_var->linked_declaration = &var;
1060                 var.linked_declaration = iface_var;
1061         }
1062
1063         iface_target_block->body.insert(iface_insert_point, iface_var);
1064         iface_target_block->variables.insert(make_pair(name, iface_var));
1065
1066         return iface_var;
1067 }
1068
1069 InterfaceBlock *InterfaceGenerator::generate_interface(InterfaceBlock &out_block)
1070 {
1071         if(stage->interface_blocks.count("in"+out_block.name))
1072                 return 0;
1073
1074         InterfaceBlock *in_block = new InterfaceBlock;
1075         in_block->interface = "in";
1076         in_block->name = out_block.name;
1077         in_block->members = new Block;
1078         in_block->instance_name = out_block.instance_name;
1079         if(stage->type==Stage::GEOMETRY)
1080                 in_block->array = true;
1081         else
1082                 in_block->array = out_block.array;
1083         in_block->linked_block = &out_block;
1084         out_block.linked_block = in_block;
1085
1086         {
1087                 SetFlag set_copy(copy_block, true);
1088                 SetForScope<Block *> set_target(iface_target_block, in_block->members.get());
1089                 SetForScope<NodeList<Statement>::iterator> set_ins_pt(iface_insert_point, in_block->members->body.end());
1090                 if(out_block.struct_declaration)
1091                         out_block.struct_declaration->members.visit(*this);
1092                 else if(out_block.members)
1093                         out_block.members->visit(*this);
1094         }
1095
1096         iface_target_block->body.insert(iface_insert_point, in_block);
1097         stage->interface_blocks.insert(make_pair("in"+in_block->name, in_block));
1098         if(!in_block->instance_name.empty())
1099                 stage->interface_blocks.insert(make_pair("_"+in_block->instance_name, in_block));
1100
1101         SetFlag set_scope(function_scope, false);
1102         SetForScope<Block *> set_block(current_block, &stage->content);
1103         in_block->visit(*this);
1104
1105         return in_block;
1106 }
1107
1108 ExpressionStatement &InterfaceGenerator::insert_assignment(const string &left, Expression *right)
1109 {
1110         Assignment *assign = new Assignment;
1111         VariableReference *ref = new VariableReference;
1112         ref->name = left;
1113         assign->left = ref;
1114         assign->oper = &Operator::get_operator("=", Operator::BINARY);
1115         assign->right = right;
1116
1117         ExpressionStatement *stmt = new ExpressionStatement;
1118         stmt->expression = assign;
1119         current_block->body.insert(assignment_insert_point, stmt);
1120         stmt->visit(*this);
1121
1122         return *stmt;
1123 }
1124
1125 void InterfaceGenerator::visit(VariableReference &var)
1126 {
1127         if(var.declaration || !stage->previous)
1128                 return;
1129         /* Don't pull a variable from previous stage if we just generated an output
1130         interface in this stage */
1131         if(stage->content.variables.count(var.name))
1132                 return;
1133
1134         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1135         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
1136         if(i==prev_vars.end() || i->second->interface!="out")
1137                 i = prev_vars.find(in_prefix+var.name);
1138         if(i!=prev_vars.end() && i->second->interface=="out")
1139         {
1140                 generate_interface(*i->second, "in", i->second->name);
1141                 var.name = i->second->name;
1142                 return;
1143         }
1144
1145         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
1146         map<string, InterfaceBlock *>::const_iterator j = prev_blocks.find("_"+var.name);
1147         if(j!=prev_blocks.end() && j->second->interface=="out")
1148         {
1149                 generate_interface(*j->second);
1150                 /* Let VariableResolver convert the variable reference into an interface
1151                 block reference. */
1152                 return;
1153         }
1154
1155         for(j=prev_blocks.begin(); j!=prev_blocks.end(); ++j)
1156                 if(j->second->instance_name.empty() && j->second->struct_declaration)
1157                 {
1158                         const map<string, VariableDeclaration *> &iface_vars = j->second->struct_declaration->members.variables;
1159                         i = iface_vars.find(var.name);
1160                         if(i!=iface_vars.end())
1161                         {
1162                                 generate_interface(*j->second);
1163                                 return;
1164                         }
1165                 }
1166 }
1167
1168 void InterfaceGenerator::visit(VariableDeclaration &var)
1169 {
1170         if(copy_block)
1171                 generate_interface(var, "in", var.name);
1172         else if(var.interface=="out")
1173         {
1174                 /* For output variables in function scope, generate a global interface
1175                 and replace the local declaration with an assignment. */
1176                 VariableDeclaration *out_var = 0;
1177                 if(function_scope && (out_var=generate_interface(var, "out", var.name)))
1178                 {
1179                         out_var->source = var.source;
1180                         out_var->line = var.line;
1181                         nodes_to_remove.insert(&var);
1182                         if(var.init_expression)
1183                         {
1184                                 ExpressionStatement &stmt = insert_assignment(var.name, var.init_expression->clone());
1185                                 stmt.source = var.source;
1186                                 stmt.line = var.line;
1187                                 return;
1188                         }
1189                 }
1190         }
1191         else if(var.interface=="in")
1192         {
1193                 /* Try to link input variables in global scope with output variables from
1194                 previous stage. */
1195                 if(current_block==&stage->content && !var.linked_declaration && stage->previous)
1196                 {
1197                         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1198                         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
1199                         if(i!=prev_vars.end() && i->second->interface=="out")
1200                         {
1201                                 var.linked_declaration = i->second;
1202                                 i->second->linked_declaration = &var;
1203                         }
1204                 }
1205         }
1206
1207         TraversingVisitor::visit(var);
1208 }
1209
1210 void InterfaceGenerator::visit(InterfaceBlock &iface)
1211 {
1212         if(iface.interface=="in")
1213         {
1214                 /* Try to link input blocks with output blocks sharing the same block
1215                 name from previous stage. */
1216                 if(!iface.linked_block && stage->previous)
1217                 {
1218                         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
1219                         map<string, InterfaceBlock *>::const_iterator i = prev_blocks.find("out"+iface.name);
1220                         if(i!=prev_blocks.end())
1221                         {
1222                                 iface.linked_block = i->second;
1223                                 i->second->linked_block = &iface;
1224                         }
1225                 }
1226         }
1227
1228         TraversingVisitor::visit(iface);
1229 }
1230
1231 void InterfaceGenerator::visit(FunctionDeclaration &func)
1232 {
1233         SetFlag set_scope(function_scope, true);
1234         // Skip parameters because they're not useful here
1235         func.body.visit(*this);
1236 }
1237
1238 void InterfaceGenerator::visit(Passthrough &pass)
1239 {
1240         vector<VariableDeclaration *> pass_vars;
1241
1242         // Pass through all input variables of this stage.
1243         for(map<string, VariableDeclaration *>::const_iterator i=stage->content.variables.begin(); i!=stage->content.variables.end(); ++i)
1244                 if(i->second->interface=="in")
1245                         pass_vars.push_back(i->second);
1246
1247         if(stage->previous)
1248         {
1249                 const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1250                 for(map<string, VariableDeclaration *>::const_iterator i=prev_vars.begin(); i!=prev_vars.end(); ++i)
1251                 {
1252                         if(i->second->interface!="out")
1253                                 continue;
1254
1255                         /* Pass through output variables from the previous stage, but only
1256                         those which are not already linked to an input here. */
1257                         if(!i->second->linked_declaration && generate_interface(*i->second, "in", i->second->name))
1258                                 pass_vars.push_back(i->second);
1259                 }
1260         }
1261
1262         if(stage->type==Stage::GEOMETRY)
1263         {
1264                 /* Special case for geometry shader: copy gl_Position from input to
1265                 output. */
1266                 InterfaceBlockReference *ref = new InterfaceBlockReference;
1267                 ref->name = "gl_in";
1268
1269                 BinaryExpression *subscript = new BinaryExpression;
1270                 subscript->left = ref;
1271                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1272                 subscript->right = pass.subscript;
1273
1274                 MemberAccess *memacc = new MemberAccess;
1275                 memacc->left = subscript;
1276                 memacc->member = "gl_Position";
1277
1278                 insert_assignment("gl_Position", memacc);
1279         }
1280
1281         for(vector<VariableDeclaration *>::const_iterator i=pass_vars.begin(); i!=pass_vars.end(); ++i)
1282         {
1283                 string out_name = change_prefix((*i)->name, out_prefix);
1284                 generate_interface(**i, "out", out_name);
1285
1286                 VariableReference *ref = new VariableReference;
1287                 ref->name = (*i)->name;
1288                 if(pass.subscript)
1289                 {
1290                         BinaryExpression *subscript = new BinaryExpression;
1291                         subscript->left = ref;
1292                         subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1293                         subscript->right = pass.subscript;
1294                         insert_assignment(out_name, subscript);
1295                 }
1296                 else
1297                         insert_assignment(out_name, ref);
1298         }
1299
1300         nodes_to_remove.insert(&pass);
1301 }
1302
1303 } // namespace SL
1304 } // namespace GL
1305 } // namespace Msp