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