]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/generate.cpp
Apply replacement to variable declaration components in VariableResolver
[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         if(var.layout)
402                 var.layout->visit(*this);
403         if(var.array_size)
404                 visit_and_replace(var.array_size);
405         if(var.init_expression)
406                 visit_and_replace(var.init_expression);
407         current_block->variables.insert(make_pair(var.name, &var));
408 }
409
410 void VariableResolver::visit(InterfaceBlock &iface)
411 {
412         /* Block names can be reused in different interfaces.  Prefix the name with
413         the first character of the interface to avoid conflicts. */
414         stage->interface_blocks.insert(make_pair(iface.interface+iface.name, &iface));
415         if(!iface.instance_name.empty())
416                 stage->interface_blocks.insert(make_pair("_"+iface.instance_name, &iface));
417
418         SetForScope<string> set_iface(block_interface, iface.interface);
419         TraversingVisitor::visit(iface);
420 }
421
422
423 ExpressionResolver::ExpressionResolver():
424         stage(0),
425         r_any_resolved(false)
426 { }
427
428 bool ExpressionResolver::apply(Stage &s)
429 {
430         stage = &s;
431         r_any_resolved = false;
432         s.content.visit(*this);
433         return r_any_resolved;
434 }
435
436 bool ExpressionResolver::is_scalar(BasicTypeDeclaration &type)
437 {
438         return (type.kind==BasicTypeDeclaration::INT || type.kind==BasicTypeDeclaration::FLOAT);
439 }
440
441 bool ExpressionResolver::is_vector_or_matrix(BasicTypeDeclaration &type)
442 {
443         return (type.kind==BasicTypeDeclaration::VECTOR || type.kind==BasicTypeDeclaration::MATRIX);
444 }
445
446 BasicTypeDeclaration *ExpressionResolver::get_element_type(BasicTypeDeclaration &type)
447 {
448         if(is_vector_or_matrix(type) || type.kind==BasicTypeDeclaration::ARRAY)
449         {
450                 BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type);
451                 return (basic_base ? get_element_type(*basic_base) : 0);
452         }
453         else
454                 return &type;
455 }
456
457 bool ExpressionResolver::can_convert(BasicTypeDeclaration &from, BasicTypeDeclaration &to)
458 {
459         if(from.kind==BasicTypeDeclaration::INT && to.kind==BasicTypeDeclaration::FLOAT)
460                 return from.size<=to.size;
461         else if(from.kind!=to.kind)
462                 return false;
463         else if((from.kind==BasicTypeDeclaration::VECTOR || from.kind==BasicTypeDeclaration::MATRIX) && from.size==to.size)
464         {
465                 BasicTypeDeclaration *from_base = dynamic_cast<BasicTypeDeclaration *>(from.base_type);
466                 BasicTypeDeclaration *to_base = dynamic_cast<BasicTypeDeclaration *>(to.base_type);
467                 return (from_base && to_base && can_convert(*from_base, *to_base));
468         }
469         else
470                 return false;
471 }
472
473 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
474 {
475         if(&left==&right)
476                 return SAME_TYPE;
477         else if(can_convert(left, right))
478                 return LEFT_CONVERTIBLE;
479         else if(can_convert(right, left))
480                 return RIGHT_CONVERTIBLE;
481         else
482                 return NOT_COMPATIBLE;
483 }
484
485 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size)
486 {
487         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
488                 if((*i)->kind==kind && (*i)->size==size)
489                         return *i;
490         return 0;
491 }
492
493 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
494 {
495         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
496                 if(get_element_type(**i)==&elem_type && (*i)->kind==kind && (*i)->size==size)
497                         return *i;
498         return 0;
499 }
500
501 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
502 {
503         RefPtr<FunctionCall> call = new FunctionCall;
504         call->name = type.name;
505         call->constructor = true;
506         call->arguments.push_back(0);
507         call->arguments.back() = expr;
508         call->type = &type;
509         expr = call;
510 }
511
512 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
513 {
514         if(BasicTypeDeclaration *expr_type = dynamic_cast<BasicTypeDeclaration *>(expr->type))
515         {
516                 BasicTypeDeclaration *to_type = &elem_type;
517                 if(is_vector_or_matrix(*expr_type))
518                         to_type = find_type(elem_type, expr_type->kind, expr_type->size);
519                 if(to_type)
520                 {
521                         convert_to(expr, *to_type);
522                         return true;
523                 }
524         }
525
526         return false;
527 }
528
529 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
530 {
531         r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
532         expr.type = type;
533         expr.lvalue = lvalue;
534 }
535
536 void ExpressionResolver::visit(Literal &literal)
537 {
538         if(literal.value.check_type<bool>())
539                 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
540         else if(literal.value.check_type<int>())
541                 resolve(literal, find_type(BasicTypeDeclaration::INT, 32), false);
542         else if(literal.value.check_type<float>())
543                 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
544 }
545
546 void ExpressionResolver::visit(ParenthesizedExpression &parexpr)
547 {
548         TraversingVisitor::visit(parexpr);
549         resolve(parexpr, parexpr.expression->type, parexpr.expression->lvalue);
550 }
551
552 void ExpressionResolver::visit(VariableReference &var)
553 {
554         if(var.declaration)
555                 resolve(var, var.declaration->type_declaration, true);
556 }
557
558 void ExpressionResolver::visit(InterfaceBlockReference &iface)
559 {
560         resolve(iface, 0, true);
561 }
562
563 void ExpressionResolver::visit(MemberAccess &memacc)
564 {
565         TraversingVisitor::visit(memacc);
566
567         if(memacc.declaration)
568                 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
569 }
570
571 void ExpressionResolver::visit(UnaryExpression &unary)
572 {
573         TraversingVisitor::visit(unary);
574
575         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
576         if(!basic)
577                 return;
578
579         char oper = unary.oper->token[0];
580         if(oper=='!')
581         {
582                 if(basic->kind!=BasicTypeDeclaration::BOOL)
583                         return;
584         }
585         else if(oper=='~')
586         {
587                 if(basic->kind!=BasicTypeDeclaration::INT)
588                         return;
589         }
590         else if(oper=='+' || oper=='-')
591         {
592                 BasicTypeDeclaration *elem = get_element_type(*basic);
593                 if(!elem || !is_scalar(*elem))
594                         return;
595         }
596         resolve(unary, basic, unary.expression->lvalue);
597 }
598
599 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
600 {
601         /* Binary operators are only defined for basic types (not for image or
602         structure types). */
603         BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
604         BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
605         if(!basic_left || !basic_right)
606                 return;
607
608         char oper = binary.oper->token[0];
609         if(oper=='[')
610         {
611                 /* Subscripting operates on vectors, matrices and arrays, and the right
612                 operand must be an integer. */
613                 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
614                         return;
615
616                 resolve(binary, basic_left->base_type, binary.left->lvalue);
617                 return;
618         }
619         else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
620                 // No other binary operator can be used with arrays.
621                 return;
622
623         BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
624         BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
625         if(!elem_left || !elem_right)
626                 return;
627
628         Compatibility compat = get_compatibility(*basic_left, *basic_right);
629         Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
630         if(elem_compat==NOT_COMPATIBLE)
631                 return;
632         if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
633                 return;
634
635         TypeDeclaration *type = 0;
636         char oper2 = binary.oper->token[1];
637         if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
638         {
639                 /* Relational operators compare two scalar integer or floating-point
640                 values. */
641                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
642                         return;
643
644                 type = find_type(BasicTypeDeclaration::BOOL, 1);
645         }
646         else if((oper=='=' || oper=='!') && oper2=='=')
647         {
648                 // Equality comparison can be done on any compatible types.
649                 if(compat==NOT_COMPATIBLE)
650                         return;
651
652                 type = find_type(BasicTypeDeclaration::BOOL, 1);
653         }
654         else if(oper2=='&' || oper2=='|' || oper2=='^')
655         {
656                 // Logical operators can only be applied to booleans.
657                 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
658                         return;
659
660                 type = basic_left;
661         }
662         else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
663         {
664                 // Bitwise operators and modulo can only be applied to integers.
665                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
666                         return;
667
668                 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
669         }
670         else if((oper=='<' || oper=='>') && oper2==oper)
671         {
672                 // Shifts apply to integer scalars and vectors, with some restrictions.
673                 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
674                         return;
675                 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
676                 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
677                 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
678                         return;
679
680                 type = basic_left;
681                 // Don't perform conversion even if the operands are of different sizes.
682                 compat = SAME_TYPE;
683         }
684         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
685         {
686                 // Arithmetic operators require scalar elements.
687                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
688                         return;
689
690                 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
691                         (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
692                 {
693                         /* Multiplication has special rules when at least one operand is a
694                         matrix and the other is a vector or a matrix. */
695                         unsigned left_columns = basic_left->size&0xFFFF;
696                         unsigned right_rows = basic_right->size;
697                         if(basic_right->kind==BasicTypeDeclaration::MATRIX)
698                                 right_rows >>= 16;
699                         if(left_columns!=right_rows)
700                                 return;
701
702                         BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
703
704                         if(basic_left->kind==BasicTypeDeclaration::VECTOR)
705                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
706                         else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
707                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
708                         else
709                                 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
710                 }
711                 else if(compat==NOT_COMPATIBLE)
712                 {
713                         // Arithmetic between scalars and matrices or vectors is supported.
714                         if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
715                                 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
716                         else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
717                                 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
718                         else
719                                 return;
720                 }
721                 else if(compat==LEFT_CONVERTIBLE)
722                         type = basic_right;
723                 else
724                         type = basic_left;
725         }
726         else
727                 return;
728
729         if(assign && type!=basic_left)
730                 return;
731
732         bool converted = true;
733         if(compat==LEFT_CONVERTIBLE)
734                 convert_to(binary.left, *basic_right);
735         else if(compat==RIGHT_CONVERTIBLE)
736                 convert_to(binary.right, *basic_left);
737         else if(elem_compat==LEFT_CONVERTIBLE)
738                 converted = convert_to_element(binary.left, *elem_right);
739         else if(elem_compat==RIGHT_CONVERTIBLE)
740                 converted = convert_to_element(binary.right, *elem_left);
741
742         if(!converted)
743                 type = 0;
744
745         resolve(binary, type, assign);
746 }
747
748 void ExpressionResolver::visit(BinaryExpression &binary)
749 {
750         TraversingVisitor::visit(binary);
751         visit(binary, false);
752 }
753
754 void ExpressionResolver::visit(Assignment &assign)
755 {
756         TraversingVisitor::visit(assign);
757
758         if(assign.oper->token[0]!='=')
759                 return visit(assign, true);
760         else if(assign.left->type!=assign.right->type)
761         {
762                 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
763                 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
764                 if(!basic_left || !basic_right)
765                         return;
766
767                 Compatibility compat = get_compatibility(*basic_left, *basic_right);
768                 if(compat==RIGHT_CONVERTIBLE)
769                         convert_to(assign.right, *basic_left);
770                 else if(compat!=SAME_TYPE)
771                         return;
772         }
773
774         resolve(assign, assign.left->type, true);
775 }
776
777 void ExpressionResolver::visit(FunctionCall &call)
778 {
779         TraversingVisitor::visit(call);
780
781         TypeDeclaration *type = 0;
782         if(call.declaration)
783                 type = call.declaration->return_type_declaration;
784         else if(call.constructor)
785         {
786                 map<string, TypeDeclaration *>::const_iterator i=stage->types.find(call.name);
787                 type = (i!=stage->types.end() ? i->second : 0);
788         }
789         resolve(call, type, false);
790 }
791
792 void ExpressionResolver::visit(BasicTypeDeclaration &type)
793 {
794         basic_types.push_back(&type);
795 }
796
797 void ExpressionResolver::visit(VariableDeclaration &var)
798 {
799         TraversingVisitor::visit(var);
800         if(!var.init_expression)
801                 return;
802
803         BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
804         BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
805         if(!var_basic || !init_basic)
806                 return;
807
808         Compatibility compat = get_compatibility(*var_basic, *init_basic);
809         if(compat==RIGHT_CONVERTIBLE)
810                 convert_to(var.init_expression, *var_basic);
811 }
812
813
814 bool FunctionResolver::apply(Stage &s)
815 {
816         stage = &s;
817         s.functions.clear();
818         r_any_resolved = false;
819         s.content.visit(*this);
820         return r_any_resolved;
821 }
822
823 void FunctionResolver::visit(FunctionCall &call)
824 {
825         map<string, FunctionDeclaration *>::iterator i = stage->functions.find(call.name);
826         if(i!=stage->functions.end())
827                 call.declaration = i->second;
828
829         TraversingVisitor::visit(call);
830 }
831
832 void FunctionResolver::visit(FunctionDeclaration &func)
833 {
834         FunctionDeclaration *&stage_decl = stage->functions[func.name];
835         vector<FunctionDeclaration *> &decls = declarations[func.name];
836         if(func.definition==&func)
837         {
838                 stage_decl = &func;
839
840                 // Set all previous declarations to use this definition.
841                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
842                 {
843                         (*i)->definition = func.definition;
844                         (*i)->body.body.clear();
845                 }
846         }
847         else
848         {
849                 func.definition = 0;
850                 if(!stage_decl)
851                         stage_decl = &func;
852                 else
853                         func.definition = stage_decl->definition;
854         }
855         decls.push_back(&func);
856
857         TraversingVisitor::visit(func);
858 }
859
860
861 InterfaceGenerator::InterfaceGenerator():
862         stage(0),
863         function_scope(false),
864         iface_block(0),
865         copy_block(false),
866         iface_target_block(0)
867 { }
868
869 string InterfaceGenerator::get_out_prefix(Stage::Type type)
870 {
871         if(type==Stage::VERTEX)
872                 return "_vs_out_";
873         else if(type==Stage::GEOMETRY)
874                 return "_gs_out_";
875         else
876                 return string();
877 }
878
879 void InterfaceGenerator::apply(Stage &s)
880 {
881         stage = &s;
882         iface_target_block = &stage->content;
883         if(stage->previous)
884                 in_prefix = get_out_prefix(stage->previous->type);
885         out_prefix = get_out_prefix(stage->type);
886         s.content.visit(*this);
887         NodeRemover().apply(s, nodes_to_remove);
888 }
889
890 void InterfaceGenerator::visit(Block &block)
891 {
892         SetForScope<Block *> set_block(current_block, &block);
893         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
894         {
895                 assignment_insert_point = i;
896                 if(&block==&stage->content)
897                         iface_insert_point = i;
898
899                 (*i)->visit(*this);
900         }
901 }
902
903 string InterfaceGenerator::change_prefix(const string &name, const string &prefix) const
904 {
905         unsigned offset = (name.compare(0, in_prefix.size(), in_prefix) ? 0 : in_prefix.size());
906         return prefix+name.substr(offset);
907 }
908
909 VariableDeclaration *InterfaceGenerator::generate_interface(VariableDeclaration &var, const string &iface, const string &name)
910 {
911         if(stage->content.variables.count(name))
912                 return 0;
913
914         VariableDeclaration* iface_var = new VariableDeclaration;
915         iface_var->sampling = var.sampling;
916         iface_var->interface = iface;
917         iface_var->type = var.type;
918         iface_var->name = name;
919         /* Geometry shader inputs are always arrays.  But if we're bringing in an
920         entire block, the array is on the block and not individual variables. */
921         if(stage->type==Stage::GEOMETRY && !copy_block)
922                 iface_var->array = ((var.array && var.interface!="in") || iface=="in");
923         else
924                 iface_var->array = var.array;
925         if(iface_var->array)
926                 iface_var->array_size = var.array_size;
927         if(iface=="in")
928         {
929                 iface_var->layout = var.layout;
930                 iface_var->linked_declaration = &var;
931                 var.linked_declaration = iface_var;
932         }
933
934         iface_target_block->body.insert(iface_insert_point, iface_var);
935         iface_target_block->variables.insert(make_pair(name, iface_var));
936
937         return iface_var;
938 }
939
940 InterfaceBlock *InterfaceGenerator::generate_interface(InterfaceBlock &out_block)
941 {
942         if(stage->interface_blocks.count("in"+out_block.name))
943                 return 0;
944
945         InterfaceBlock *in_block = new InterfaceBlock;
946         in_block->interface = "in";
947         in_block->name = out_block.name;
948         in_block->instance_name = out_block.instance_name;
949         if(stage->type==Stage::GEOMETRY)
950                 in_block->array = true;
951         else
952                 in_block->array = out_block.array;
953         in_block->linked_block = &out_block;
954         out_block.linked_block = in_block;
955
956         {
957                 SetFlag set_copy(copy_block, true);
958                 SetForScope<Block *> set_target(iface_target_block, &in_block->members);
959                 SetForScope<NodeList<Statement>::iterator> set_ins_pt(iface_insert_point, in_block->members.body.end());
960                 out_block.members.visit(*this);
961         }
962
963         iface_target_block->body.insert(iface_insert_point, in_block);
964         stage->interface_blocks.insert(make_pair("in"+in_block->name, in_block));
965         if(!in_block->instance_name.empty())
966                 stage->interface_blocks.insert(make_pair("_"+in_block->instance_name, in_block));
967
968         SetFlag set_scope(function_scope, false);
969         SetForScope<Block *> set_block(current_block, &stage->content);
970         in_block->visit(*this);
971
972         return in_block;
973 }
974
975 ExpressionStatement &InterfaceGenerator::insert_assignment(const string &left, Expression *right)
976 {
977         Assignment *assign = new Assignment;
978         VariableReference *ref = new VariableReference;
979         ref->name = left;
980         assign->left = ref;
981         assign->oper = &Operator::get_operator("=", Operator::BINARY);
982         assign->right = right;
983
984         ExpressionStatement *stmt = new ExpressionStatement;
985         stmt->expression = assign;
986         current_block->body.insert(assignment_insert_point, stmt);
987         stmt->visit(*this);
988
989         return *stmt;
990 }
991
992 void InterfaceGenerator::visit(VariableReference &var)
993 {
994         if(var.declaration || !stage->previous)
995                 return;
996         /* Don't pull a variable from previous stage if we just generated an output
997         interface in this stage */
998         if(stage->content.variables.count(var.name))
999                 return;
1000
1001         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1002         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
1003         if(i==prev_vars.end() || i->second->interface!="out")
1004                 i = prev_vars.find(in_prefix+var.name);
1005         if(i!=prev_vars.end() && i->second->interface=="out")
1006         {
1007                 generate_interface(*i->second, "in", i->second->name);
1008                 var.name = i->second->name;
1009                 return;
1010         }
1011
1012         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
1013         map<string, InterfaceBlock *>::const_iterator j = prev_blocks.find("_"+var.name);
1014         if(j!=prev_blocks.end() && j->second->interface=="out")
1015         {
1016                 generate_interface(*j->second);
1017                 /* Let VariableResolver convert the variable reference into an interface
1018                 block reference. */
1019                 return;
1020         }
1021
1022         for(j=prev_blocks.begin(); j!=prev_blocks.end(); ++j)
1023                 if(j->second->instance_name.empty())
1024                 {
1025                         i = j->second->members.variables.find(var.name);
1026                         if(i!=j->second->members.variables.end())
1027                         {
1028                                 generate_interface(*j->second);
1029                                 return;
1030                         }
1031                 }
1032 }
1033
1034 void InterfaceGenerator::visit(VariableDeclaration &var)
1035 {
1036         if(copy_block)
1037         {
1038                 generate_interface(var, "in", var.name);
1039                 return;
1040         }
1041
1042         if(iface_block)
1043         {
1044                 if(iface_block->linked_block)
1045                 {
1046                         // Link all variables to their counterparts in the linked block.
1047                         const map<string, VariableDeclaration *> &linked_vars = iface_block->linked_block->members.variables;
1048                         map<string, VariableDeclaration *>::const_iterator i = linked_vars.find(var.name);
1049                         if(i!=linked_vars.end())
1050                         {
1051                                 var.linked_declaration = i->second;
1052                                 var.linked_declaration->linked_declaration = &var;
1053                         }
1054                 }
1055                 return;
1056         }
1057
1058         if(var.interface=="out")
1059         {
1060                 /* For output variables in function scope, generate a global interface
1061                 and replace the local declaration with an assignment. */
1062                 VariableDeclaration *out_var = 0;
1063                 if(function_scope && (out_var=generate_interface(var, "out", var.name)))
1064                 {
1065                         out_var->source = var.source;
1066                         out_var->line = var.line;
1067                         nodes_to_remove.insert(&var);
1068                         if(var.init_expression)
1069                         {
1070                                 ExpressionStatement &stmt = insert_assignment(var.name, var.init_expression->clone());
1071                                 stmt.source = var.source;
1072                                 stmt.line = var.line;
1073                                 return;
1074                         }
1075                 }
1076         }
1077         else if(var.interface=="in")
1078         {
1079                 /* Try to link input variables in global scope with output variables from
1080                 previous stage. */
1081                 if(current_block==&stage->content && !var.linked_declaration && stage->previous)
1082                 {
1083                         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1084                         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
1085                         if(i!=prev_vars.end() && i->second->interface=="out")
1086                         {
1087                                 var.linked_declaration = i->second;
1088                                 i->second->linked_declaration = &var;
1089                         }
1090                 }
1091         }
1092
1093         TraversingVisitor::visit(var);
1094 }
1095
1096 void InterfaceGenerator::visit(InterfaceBlock &iface)
1097 {
1098         if(iface.interface=="in")
1099         {
1100                 /* Try to link input blocks with output blocks sharing the same block
1101                 name from previous stage. */
1102                 if(!iface.linked_block && stage->previous)
1103                 {
1104                         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
1105                         map<string, InterfaceBlock *>::const_iterator i = prev_blocks.find("out"+iface.name);
1106                         if(i!=prev_blocks.end())
1107                         {
1108                                 iface.linked_block = i->second;
1109                                 i->second->linked_block = &iface;
1110                         }
1111                 }
1112         }
1113
1114         SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
1115         TraversingVisitor::visit(iface);
1116 }
1117
1118 void InterfaceGenerator::visit(FunctionDeclaration &func)
1119 {
1120         SetFlag set_scope(function_scope, true);
1121         // Skip parameters because they're not useful here
1122         func.body.visit(*this);
1123 }
1124
1125 void InterfaceGenerator::visit(Passthrough &pass)
1126 {
1127         vector<VariableDeclaration *> pass_vars;
1128
1129         // Pass through all input variables of this stage.
1130         for(map<string, VariableDeclaration *>::const_iterator i=stage->content.variables.begin(); i!=stage->content.variables.end(); ++i)
1131                 if(i->second->interface=="in")
1132                         pass_vars.push_back(i->second);
1133
1134         if(stage->previous)
1135         {
1136                 const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1137                 for(map<string, VariableDeclaration *>::const_iterator i=prev_vars.begin(); i!=prev_vars.end(); ++i)
1138                 {
1139                         if(i->second->interface!="out")
1140                                 continue;
1141
1142                         /* Pass through output variables from the previous stage, but only
1143                         those which are not already linked to an input here. */
1144                         if(!i->second->linked_declaration && generate_interface(*i->second, "in", i->second->name))
1145                                 pass_vars.push_back(i->second);
1146                 }
1147         }
1148
1149         if(stage->type==Stage::GEOMETRY)
1150         {
1151                 /* Special case for geometry shader: copy gl_Position from input to
1152                 output. */
1153                 InterfaceBlockReference *ref = new InterfaceBlockReference;
1154                 ref->name = "gl_in";
1155
1156                 BinaryExpression *subscript = new BinaryExpression;
1157                 subscript->left = ref;
1158                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1159                 subscript->right = pass.subscript;
1160
1161                 MemberAccess *memacc = new MemberAccess;
1162                 memacc->left = subscript;
1163                 memacc->member = "gl_Position";
1164
1165                 insert_assignment("gl_Position", memacc);
1166         }
1167
1168         for(vector<VariableDeclaration *>::const_iterator i=pass_vars.begin(); i!=pass_vars.end(); ++i)
1169         {
1170                 string out_name = change_prefix((*i)->name, out_prefix);
1171                 generate_interface(**i, "out", out_name);
1172
1173                 VariableReference *ref = new VariableReference;
1174                 ref->name = (*i)->name;
1175                 if(pass.subscript)
1176                 {
1177                         BinaryExpression *subscript = new BinaryExpression;
1178                         subscript->left = ref;
1179                         subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1180                         subscript->right = pass.subscript;
1181                         insert_assignment(out_name, subscript);
1182                 }
1183                 else
1184                         insert_assignment(out_name, ref);
1185         }
1186
1187         nodes_to_remove.insert(&pass);
1188 }
1189
1190 } // namespace SL
1191 } // namespace GL
1192 } // namespace Msp