1 #include <msp/core/algorithm.h>
2 #include <msp/core/raii.h>
3 #include <msp/strings/utils.h>
13 void BlockHierarchyResolver::enter(Block &block)
15 r_any_resolved |= (current_block!=block.parent);
16 block.parent = current_block;
20 bool TypeResolver::apply(Stage &s)
24 r_any_resolved = false;
25 s.content.visit(*this);
26 return r_any_resolved;
29 TypeDeclaration *TypeResolver::get_or_create_array_type(TypeDeclaration &type)
31 auto i = array_types.find(&type);
32 if(i!=array_types.end())
35 BasicTypeDeclaration *array = new BasicTypeDeclaration;
36 array->source = INTERNAL_SOURCE;
37 array->name = type.name+"[]";
38 array->kind = BasicTypeDeclaration::ARRAY;
39 array->base = type.name;
40 array->base_type = &type;
41 stage->content.body.insert(type_insert_point, array);
42 array_types[&type] = array;
46 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array)
48 TypeDeclaration *resolved = 0;
49 auto i = stage->types.find(name);
50 if(i!=stage->types.end())
52 auto j = alias_map.find(i->second);
53 resolved = (j!=alias_map.end() ? j->second : i->second);
57 resolved = get_or_create_array_type(*resolved);
59 r_any_resolved |= (resolved!=type);
63 void TypeResolver::visit(Block &block)
65 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
68 type_insert_point = i;
73 void TypeResolver::visit(BasicTypeDeclaration &type)
75 resolve_type(type.base_type, type.base, false);
77 if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
78 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
79 if(basic_base->kind==BasicTypeDeclaration::VECTOR)
81 type.kind = BasicTypeDeclaration::MATRIX;
82 /* A matrix's base type is its column vector type. This will put
83 the column vector's size, i.e. the matrix's row count, in the high
85 type.size |= basic_base->size<<16;
88 if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
89 alias_map[&type] = type.base_type;
90 else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
91 array_types[type.base_type] = &type;
93 stage->types.insert(make_pair(type.name, &type));
96 void TypeResolver::visit(ImageTypeDeclaration &type)
98 resolve_type(type.base_type, type.base, false);
99 stage->types.insert(make_pair(type.name, &type));
102 void TypeResolver::visit(StructDeclaration &strct)
104 stage->types.insert(make_pair(strct.name, &strct));
105 TraversingVisitor::visit(strct);
108 void TypeResolver::visit(VariableDeclaration &var)
110 resolve_type(var.type_declaration, var.type, var.array);
111 if(iface_block && var.interface==iface_block->interface)
112 var.interface.clear();
115 void TypeResolver::visit(InterfaceBlock &iface)
119 SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
120 iface.members->visit(*this);
122 StructDeclaration *strct = new StructDeclaration;
123 strct->source = INTERNAL_SOURCE;
124 strct->name = format("_%s_%s", iface.interface, iface.block_name);
125 strct->members.body.splice(strct->members.body.begin(), iface.members->body);
126 stage->content.body.insert(type_insert_point, strct);
127 stage->types.insert(make_pair(strct->name, strct));
130 strct->interface_block = &iface;
131 iface.struct_declaration = strct;
134 TypeDeclaration *type = iface.struct_declaration;
135 if(type && iface.array)
136 type = get_or_create_array_type(*type);
137 r_any_resolved = (type!=iface.type_declaration);
138 iface.type_declaration = type;
141 void TypeResolver::visit(FunctionDeclaration &func)
143 resolve_type(func.return_type_declaration, func.return_type, false);
144 TraversingVisitor::visit(func);
148 bool VariableResolver::apply(Stage &s)
151 s.interface_blocks.clear();
152 r_any_resolved = false;
153 s.content.visit(*this);
154 for(Statement *b: redeclared_builtins)
155 b->source = GENERATED_SOURCE;
156 NodeRemover().apply(s, nodes_to_remove);
157 return r_any_resolved;
160 void VariableResolver::enter(Block &block)
162 block.variables.clear();
165 void VariableResolver::visit(RefPtr<Expression> &expr)
167 r_replacement_expr = 0;
169 if(r_replacement_expr)
171 expr = r_replacement_expr;
172 /* Don't record assignment target when doing a replacement, because chain
173 information won't be correct. */
174 r_assignment_target.declaration = 0;
175 r_any_resolved = true;
177 r_replacement_expr = 0;
180 void VariableResolver::check_assignment_target(Statement *declaration)
184 if(r_assignment_target.declaration)
186 /* More than one reference found in assignment target. Unable to
187 determine what the primary target is. */
188 record_target = false;
189 r_assignment_target.declaration = 0;
192 r_assignment_target.declaration = declaration;
194 // TODO This check is overly broad and may prevent some optimizations.
195 else if(declaration && declaration==r_assignment_target.declaration)
196 r_self_referencing = true;
199 void VariableResolver::visit(VariableReference &var)
201 VariableDeclaration *declaration = 0;
203 /* Look for variable declarations in the block hierarchy first. Interface
204 blocks are always defined in the top level so we can't accidentally skip
206 for(Block *block=current_block; (!declaration && block); block=block->parent)
208 auto i = block->variables.find(var.name);
209 if(i!=block->variables.end())
210 declaration = i->second;
215 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
216 auto i = blocks.find(var.name);
219 // Look for the variable in anonymous interface blocks.
220 for(i=blocks.begin(); i!=blocks.end(); ++i)
221 if(i->second->instance_name.empty() && i->second->struct_declaration)
222 if(i->second->struct_declaration->members.variables.count(var.name))
228 /* The name refers to either an interface block with an instance name
229 or a variable declared inside an anonymous interface block. Prepare
230 new syntax tree nodes accordingly. */
231 InterfaceBlockReference *iface_ref = new InterfaceBlockReference;
232 iface_ref->source = var.source;
233 iface_ref->line = var.line;
234 iface_ref->declaration = i->second;
236 if(i->second->instance_name.empty())
238 iface_ref->name = format("%s %s", i->second->interface, i->second->block_name);
240 MemberAccess *memacc = new MemberAccess;
241 memacc->source = var.source;
242 memacc->line = var.line;
243 memacc->left = iface_ref;
244 memacc->member = var.name;
246 r_replacement_expr = memacc;
250 iface_ref->name = var.name;
251 r_replacement_expr = iface_ref;
256 r_any_resolved |= (declaration!=var.declaration);
257 var.declaration = declaration;
259 check_assignment_target(var.declaration);
262 void VariableResolver::visit(InterfaceBlockReference &iface)
264 auto i = stage->interface_blocks.find(iface.name);
265 InterfaceBlock *declaration = (i!=stage->interface_blocks.end() ? i->second : 0);
266 r_any_resolved |= (declaration!=iface.declaration);
267 iface.declaration = declaration;
269 check_assignment_target(iface.declaration);
272 void VariableResolver::visit(MemberAccess &memacc)
274 TraversingVisitor::visit(memacc);
276 VariableDeclaration *declaration = 0;
278 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
280 auto i = strct->members.variables.find(memacc.member);
281 if(i!=strct->members.variables.end())
283 declaration = i->second;
285 for(auto j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
289 add_to_chain(r_assignment_target, Assignment::Target::MEMBER, index);
292 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
294 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
295 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
296 if(scalar_swizzle || vector_swizzle)
298 static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
301 uint8_t components[4] = { };
302 for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
303 ok = ((components[i] = (std::find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
307 Swizzle *swizzle = new Swizzle;
308 swizzle->source = memacc.source;
309 swizzle->line = memacc.line;
310 swizzle->oper = memacc.oper;
311 swizzle->left = memacc.left;
312 swizzle->component_group = memacc.member;
313 swizzle->count = memacc.member.size();
314 copy(components, components+memacc.member.size(), swizzle->components);
315 r_replacement_expr = swizzle;
320 r_any_resolved |= (declaration!=memacc.declaration || index!=memacc.index);
321 memacc.declaration = declaration;
322 memacc.index = index;
325 void VariableResolver::visit(Swizzle &swizzle)
327 TraversingVisitor::visit(swizzle);
332 for(unsigned i=0; i<swizzle.count; ++i)
333 mask |= 1<<swizzle.components[i];
334 add_to_chain(r_assignment_target, Assignment::Target::SWIZZLE, mask);
338 void VariableResolver::visit(BinaryExpression &binary)
340 if(binary.oper->token[0]=='[')
343 /* The subscript expression is not a part of the primary assignment
345 SetFlag set(record_target, false);
352 unsigned index = 0x3F;
353 if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
354 if(literal_subscript->value.check_type<int>())
355 index = literal_subscript->value.value<int>();
356 add_to_chain(r_assignment_target, Assignment::Target::ARRAY, index);
360 TraversingVisitor::visit(binary);
363 void VariableResolver::visit(Assignment &assign)
366 SetFlag set(record_target);
367 r_assignment_target = Assignment::Target();
369 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
370 assign.target = r_assignment_target;
373 r_self_referencing = false;
375 assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
378 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
380 for(const Layout::Qualifier &q: from_layout.qualifiers)
382 auto i = find_member(to_layout.qualifiers, q.name, &Layout::Qualifier::name);
383 if(i!=to_layout.qualifiers.end())
385 i->has_value = q.value;
389 to_layout.qualifiers.push_back(q);
393 void VariableResolver::visit(VariableDeclaration &var)
395 TraversingVisitor::visit(var);
397 auto i = current_block->variables.find(var.name);
398 VariableDeclaration *existing = 0;
399 InterfaceBlock *block = 0;
400 if(i!=current_block->variables.end())
401 existing = i->second;
402 else if(!current_block->parent)
404 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
405 for(auto j=blocks.begin(); j!=blocks.end(); ++j)
406 if(j->second->instance_name.empty() && j->second->struct_declaration)
408 map<string, VariableDeclaration *> &block_vars = j->second->struct_declaration->members.variables;
409 i = block_vars.find(var.name);
410 if(i!=block_vars.end())
412 existing = i->second;
420 current_block->variables.insert(make_pair(var.name, &var));
421 else if(!current_block->parent && (block ? block->interface : existing->interface)==var.interface && existing->type==var.type && existing->array==var.array)
423 if(existing->source==BUILTIN_SOURCE)
428 merge_layouts(*existing->layout, *var.layout);
430 existing->layout = var.layout;
433 existing->array_size = var.array_size;
435 redeclared_builtins.push_back(existing);
438 redeclared_builtins.push_back(block);
439 for(const auto &kvp: block->struct_declaration->members.variables)
440 redeclared_builtins.push_back(kvp.second);
443 nodes_to_remove.insert(&var);
444 r_any_resolved = true;
446 else if(existing->array && !existing->array_size && !var.layout && !var.init_expression)
448 existing->array_size = var.array_size;
449 nodes_to_remove.insert(&var);
450 r_any_resolved = true;
455 void VariableResolver::visit(InterfaceBlock &iface)
457 /* Block names can be reused in different interfaces. Prefix the name with
458 the first character of the interface to avoid conflicts. */
459 stage->interface_blocks.insert(make_pair(format("%s %s", iface.interface, iface.block_name), &iface));
460 if(!iface.instance_name.empty())
461 stage->interface_blocks.insert(make_pair(iface.instance_name, &iface));
463 TraversingVisitor::visit(iface);
467 bool ExpressionResolver::apply(Stage &s)
470 r_any_resolved = false;
471 s.content.visit(*this);
472 return r_any_resolved;
475 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
479 else if(can_convert(left, right))
480 return LEFT_CONVERTIBLE;
481 else if(can_convert(right, left))
482 return RIGHT_CONVERTIBLE;
484 return NOT_COMPATIBLE;
487 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
489 auto i = find_if(basic_types,
490 [kind, size, sign](const BasicTypeDeclaration *t){ return t->kind==kind && t->size==size && t->sign==sign; });
491 return (i!=basic_types.end() ? *i : 0);
494 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
496 auto i = find_if(basic_types,
497 [&elem_type, kind, size](BasicTypeDeclaration *t){ return get_element_type(*t)==&elem_type && t->kind==kind && t->size==size; });
498 return (i!=basic_types.end() ? *i : 0);
501 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
503 RefPtr<FunctionCall> call = new FunctionCall;
504 call->name = type.name;
505 call->constructor = true;
506 call->arguments.push_back_nocopy(expr);
511 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
513 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
515 BasicTypeDeclaration *to_type = &elem_type;
516 if(is_vector_or_matrix(*expr_basic))
517 to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
520 convert_to(expr, *to_type);
528 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
530 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
531 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
533 RefPtr<Swizzle> swizzle = new Swizzle;
534 swizzle->left = expr;
535 swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
536 swizzle->component_group = string("xyzw", size);
537 swizzle->count = size;
538 for(unsigned i=0; i<size; ++i)
539 swizzle->components[i] = i;
541 swizzle->type = expr_elem;
543 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
552 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
554 r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
556 expr.lvalue = lvalue;
559 void ExpressionResolver::visit(Block &block)
561 SetForScope<Block *> set_block(current_block, &block);
562 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
569 void ExpressionResolver::visit(Literal &literal)
571 if(literal.value.check_type<bool>())
572 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
573 else if(literal.value.check_type<int>())
574 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, true), false);
575 else if(literal.value.check_type<unsigned>())
576 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, false), false);
577 else if(literal.value.check_type<float>())
578 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
581 void ExpressionResolver::visit(VariableReference &var)
584 resolve(var, var.declaration->type_declaration, true);
587 void ExpressionResolver::visit(InterfaceBlockReference &iface)
589 if(iface.declaration)
590 resolve(iface, iface.declaration->type_declaration, true);
593 void ExpressionResolver::visit(MemberAccess &memacc)
595 TraversingVisitor::visit(memacc);
597 if(memacc.declaration)
598 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
601 void ExpressionResolver::visit(Swizzle &swizzle)
603 TraversingVisitor::visit(swizzle);
605 if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
607 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
609 resolve(swizzle, left_elem, swizzle.left->lvalue);
610 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
611 resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
615 void ExpressionResolver::visit(UnaryExpression &unary)
617 TraversingVisitor::visit(unary);
619 BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
623 char oper = unary.oper->token[0];
626 if(basic->kind!=BasicTypeDeclaration::BOOL)
631 if(basic->kind!=BasicTypeDeclaration::INT)
634 else if(oper=='+' || oper=='-')
636 BasicTypeDeclaration *elem = get_element_type(*basic);
637 if(!elem || !is_scalar(*elem))
640 resolve(unary, basic, unary.expression->lvalue);
643 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
645 /* Binary operators are only defined for basic types (not for image or
647 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
648 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
649 if(!basic_left || !basic_right)
652 char oper = binary.oper->token[0];
655 /* Subscripting operates on vectors, matrices and arrays, and the right
656 operand must be an integer. */
657 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
660 resolve(binary, basic_left->base_type, binary.left->lvalue);
663 else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
664 // No other binary operator can be used with arrays.
667 BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
668 BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
669 if(!elem_left || !elem_right)
672 Compatibility compat = get_compatibility(*basic_left, *basic_right);
673 Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
674 if(elem_compat==NOT_COMPATIBLE)
676 if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
679 TypeDeclaration *type = 0;
680 char oper2 = binary.oper->token[1];
681 if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
683 /* Relational operators compare two scalar integer or floating-point
685 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
688 type = find_type(BasicTypeDeclaration::BOOL, 1);
690 else if((oper=='=' || oper=='!') && oper2=='=')
692 // Equality comparison can be done on any compatible types.
693 if(compat==NOT_COMPATIBLE)
696 type = find_type(BasicTypeDeclaration::BOOL, 1);
698 else if(oper2=='&' || oper2=='|' || oper2=='^')
700 // Logical operators can only be applied to booleans.
701 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
706 else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
708 // Bitwise operators and modulo can only be applied to integers.
709 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
712 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
714 else if((oper=='<' || oper=='>') && oper2==oper)
716 // Shifts apply to integer scalars and vectors, with some restrictions.
717 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
719 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
720 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
721 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
724 /* If the left operand is a vector and right is scalar, convert the right
725 operand to a vector too. */
726 if(left_size>1 && right_size==1)
728 BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
732 convert_to(binary.right, *vec_right);
736 // Don't perform conversion even if the operands are of different sizes.
739 else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
741 // Arithmetic operators require scalar elements.
742 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
745 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
746 (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
748 /* Multiplication has special rules when at least one operand is a
749 matrix and the other is a vector or a matrix. */
750 unsigned left_columns = basic_left->size&0xFFFF;
751 unsigned right_rows = basic_right->size;
752 if(basic_right->kind==BasicTypeDeclaration::MATRIX)
754 if(left_columns!=right_rows)
757 BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
759 if(basic_left->kind==BasicTypeDeclaration::VECTOR)
760 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
761 else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
762 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
764 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
766 else if(compat==NOT_COMPATIBLE)
768 // Arithmetic between scalars and matrices or vectors is supported.
769 if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
770 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
771 else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
772 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
776 else if(compat==LEFT_CONVERTIBLE)
784 if(assign && type!=basic_left)
787 bool converted = true;
788 if(compat==LEFT_CONVERTIBLE)
789 convert_to(binary.left, *basic_right);
790 else if(compat==RIGHT_CONVERTIBLE)
791 convert_to(binary.right, *basic_left);
792 else if(elem_compat==LEFT_CONVERTIBLE)
793 converted = convert_to_element(binary.left, *elem_right);
794 else if(elem_compat==RIGHT_CONVERTIBLE)
795 converted = convert_to_element(binary.right, *elem_left);
800 resolve(binary, type, assign);
803 void ExpressionResolver::visit(BinaryExpression &binary)
805 TraversingVisitor::visit(binary);
806 visit(binary, false);
809 void ExpressionResolver::visit(Assignment &assign)
811 TraversingVisitor::visit(assign);
813 if(assign.oper->token[0]!='=')
814 return visit(assign, true);
815 else if(assign.left->type!=assign.right->type)
817 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
818 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
819 if(!basic_left || !basic_right)
822 Compatibility compat = get_compatibility(*basic_left, *basic_right);
823 if(compat==RIGHT_CONVERTIBLE)
824 convert_to(assign.right, *basic_left);
825 else if(compat!=SAME_TYPE)
829 resolve(assign, assign.left->type, true);
832 void ExpressionResolver::visit(TernaryExpression &ternary)
834 TraversingVisitor::visit(ternary);
836 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
837 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
840 TypeDeclaration *type = 0;
841 if(ternary.true_expr->type==ternary.false_expr->type)
842 type = ternary.true_expr->type;
845 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
846 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
847 if(!basic_true || !basic_false)
850 Compatibility compat = get_compatibility(*basic_true, *basic_false);
851 if(compat==NOT_COMPATIBLE)
854 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
856 if(compat==LEFT_CONVERTIBLE)
857 convert_to(ternary.true_expr, *basic_false);
858 else if(compat==RIGHT_CONVERTIBLE)
859 convert_to(ternary.false_expr, *basic_true);
862 resolve(ternary, type, false);
865 void ExpressionResolver::visit_constructor(FunctionCall &call)
867 if(call.arguments.empty())
870 auto i = stage->types.find(call.name);
871 if(i==stage->types.end())
873 else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
875 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
877 BasicTypeDeclaration *elem = get_element_type(*basic);
881 vector<ArgumentInfo> args;
882 args.reserve(call.arguments.size());
883 unsigned arg_component_total = 0;
884 bool has_matrices = false;
885 for(const RefPtr<Expression> &a: call.arguments)
888 if(!(info.type=dynamic_cast<BasicTypeDeclaration *>(a->type)))
890 if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
891 info.component_count = 1;
892 else if(info.type->kind==BasicTypeDeclaration::VECTOR)
893 info.component_count = info.type->size;
894 else if(info.type->kind==BasicTypeDeclaration::MATRIX)
896 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
901 arg_component_total += info.component_count;
902 args.push_back(info);
905 bool convert_args = false;
906 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
908 if(arg_component_total>1)
909 truncate_vector(call.arguments.front(), 1);
911 /* Single-element type constructors never need to convert their
912 arguments because the constructor *is* the conversion. */
914 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
916 /* Vector constructors need either a single scalar argument or
917 enough components to fill out the vector. */
918 if(arg_component_total!=1 && arg_component_total<basic->size)
921 /* A vector of same size can be converted directly. For other
922 combinations the individual arguments need to be converted. */
923 if(call.arguments.size()==1)
925 if(arg_component_total==1)
927 else if(arg_component_total>basic->size)
928 truncate_vector(call.arguments.front(), basic->size);
930 else if(arg_component_total==basic->size)
935 else if(basic->kind==BasicTypeDeclaration::MATRIX)
937 unsigned column_count = basic->size&0xFFFF;
938 unsigned row_count = basic->size>>16;
939 if(call.arguments.size()==1)
941 /* A matrix can be constructed from a single element or another
942 matrix of sufficient size. */
943 if(arg_component_total==1)
945 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
947 unsigned arg_columns = args.front().type->size&0xFFFF;
948 unsigned arg_rows = args.front().type->size>>16;
949 if(arg_columns<column_count || arg_rows<row_count)
952 /* Always generate a temporary here and let the optimization
953 stage inline it if that's reasonable. */
954 RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
955 temporary->type = args.front().type->name;
956 temporary->name = get_unused_variable_name(*current_block, "_temp");
957 temporary->init_expression = call.arguments.front();
958 current_block->body.insert(insert_point, temporary);
960 // Create expressions to build each column.
961 vector<RefPtr<Expression> > columns;
962 columns.reserve(column_count);
963 for(unsigned j=0; j<column_count; ++j)
965 RefPtr<VariableReference> ref = new VariableReference;
966 ref->name = temporary->name;
968 RefPtr<Literal> index = new Literal;
969 index->token = lexical_cast<string>(j);
970 index->value = static_cast<int>(j);
972 RefPtr<BinaryExpression> subscript = new BinaryExpression;
973 subscript->left = ref;
974 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
975 subscript->right = index;
976 subscript->type = args.front().type->base_type;
978 columns.push_back(subscript);
979 if(arg_rows>row_count)
980 truncate_vector(columns.back(), row_count);
983 call.arguments.resize(column_count);
984 copy(columns.begin(), columns.end(), call.arguments.begin());
986 /* Let VariableResolver process the new nodes and finish
987 resolving the constructor on the next pass. */
988 r_any_resolved = true;
994 else if(arg_component_total==column_count*row_count && !has_matrices)
996 /* Construct a matrix from individual components in column-major
997 order. Arguments must align at column boundaries. */
998 vector<RefPtr<Expression> > columns;
999 columns.reserve(column_count);
1001 vector<RefPtr<Expression> > column_args;
1002 column_args.reserve(row_count);
1003 unsigned column_component_count = 0;
1005 for(unsigned j=0; j<call.arguments.size(); ++j)
1007 const ArgumentInfo &info = args[j];
1008 if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
1009 // A vector filling the entire column can be used as is.
1010 columns.push_back(call.arguments[j]);
1013 column_args.push_back(call.arguments[j]);
1014 column_component_count += info.component_count;
1015 if(column_component_count==row_count)
1017 /* The column has filled up. Create a vector constructor
1019 RefPtr<FunctionCall> column_call = new FunctionCall;
1020 column_call->name = basic->base_type->name;
1021 column_call->constructor = true;
1022 column_call->arguments.resize(column_args.size());
1023 copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1024 column_call->type = basic->base_type;
1025 visit_constructor(*column_call);
1026 columns.push_back(column_call);
1028 column_args.clear();
1029 column_component_count = 0;
1031 else if(column_component_count>row_count)
1032 // Argument alignment mismatch.
1045 // The argument list may have changed so can't rely on args.
1046 for(RefPtr<Expression> &a: call.arguments)
1047 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1049 BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1051 convert_to_element(a, *elem);
1055 else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1057 if(call.arguments.size()!=strct->members.body.size())
1060 auto j = call.arguments.begin();
1061 for(const RefPtr<Statement> &s: strct->members.body)
1063 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(s.get()))
1065 if(!(*j)->type || (*j)->type!=var->type_declaration)
1074 resolve(call, i->second, false);
1077 void ExpressionResolver::visit(FunctionCall &call)
1079 TraversingVisitor::visit(call);
1081 if(call.declaration)
1082 resolve(call, call.declaration->return_type_declaration, false);
1083 else if(call.constructor)
1084 visit_constructor(call);
1087 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1089 basic_types.push_back(&type);
1092 void ExpressionResolver::visit(VariableDeclaration &var)
1094 TraversingVisitor::visit(var);
1095 if(!var.init_expression)
1098 BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1099 BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1100 if(!var_basic || !init_basic)
1103 Compatibility compat = get_compatibility(*var_basic, *init_basic);
1104 if(compat==RIGHT_CONVERTIBLE)
1105 convert_to(var.init_expression, *var_basic);
1109 bool FunctionResolver::apply(Stage &s)
1112 s.functions.clear();
1113 r_any_resolved = false;
1114 s.content.visit(*this);
1115 return r_any_resolved;
1118 bool FunctionResolver::can_convert_arguments(const FunctionCall &call, const FunctionDeclaration &decl)
1120 if(decl.parameters.size()!=call.arguments.size())
1123 for(unsigned j=0; j<call.arguments.size(); ++j)
1125 const TypeDeclaration *arg_type = call.arguments[j]->type;
1126 const TypeDeclaration *param_type = decl.parameters[j]->type_declaration;
1127 if(arg_type==param_type)
1130 const BasicTypeDeclaration *arg_basic = dynamic_cast<const BasicTypeDeclaration *>(arg_type);
1131 const BasicTypeDeclaration *param_basic = dynamic_cast<const BasicTypeDeclaration *>(param_type);
1132 if(arg_basic && param_basic && can_convert(*arg_basic, *param_basic))
1141 void FunctionResolver::visit(FunctionCall &call)
1143 FunctionDeclaration *declaration = 0;
1144 if(stage->types.count(call.name))
1145 call.constructor = true;
1149 bool has_signature = true;
1150 for(auto i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1153 append(arg_types, ",", (*i)->type->name);
1155 has_signature = false;
1160 auto i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1161 declaration = (i!=stage->functions.end() ? i->second : 0);
1165 for(i=stage->functions.lower_bound(call.name+"("); (i!=stage->functions.end() && i->second->name==call.name); ++i)
1166 if(can_convert_arguments(call, *i->second))
1174 declaration = i->second;
1180 r_any_resolved |= (declaration!=call.declaration);
1181 call.declaration = declaration;
1183 TraversingVisitor::visit(call);
1186 void FunctionResolver::visit(FunctionDeclaration &func)
1188 if(func.signature.empty())
1191 for(const RefPtr<VariableDeclaration> &p: func.parameters)
1193 if(p->type_declaration)
1194 append(param_types, ",", p->type_declaration->name);
1198 func.signature = format("(%s)", param_types);
1199 r_any_resolved = true;
1202 string key = func.name+func.signature;
1203 FunctionDeclaration *&stage_decl = stage->functions[key];
1204 vector<FunctionDeclaration *> &decls = declarations[key];
1205 if(func.definition==&func)
1207 if(stage_decl && stage_decl->definition)
1210 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1211 format("Overriding function '%s' without the override keyword is deprecated", key)));
1212 if(!stage_decl->definition->virtua)
1213 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1214 format("Overriding function '%s' not declared as virtual is deprecated", key)));
1218 // Set all previous declarations to use this definition.
1219 for(FunctionDeclaration *f: decls)
1221 r_any_resolved |= (func.definition!=f->definition);
1222 f->definition = func.definition;
1223 f->body.body.clear();
1228 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1229 r_any_resolved |= (definition!=func.definition);
1230 func.definition = definition;
1235 decls.push_back(&func);
1237 TraversingVisitor::visit(func);