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