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