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 TypeResolver::TypeResolver():
26 bool TypeResolver::apply(Stage &s)
30 r_any_resolved = false;
31 s.content.visit(*this);
32 return r_any_resolved;
35 TypeDeclaration *TypeResolver::get_or_create_array_type(TypeDeclaration &type)
37 auto i = array_types.find(&type);
38 if(i!=array_types.end())
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;
52 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array)
54 TypeDeclaration *resolved = 0;
55 auto i = stage->types.find(name);
56 if(i!=stage->types.end())
58 auto j = alias_map.find(i->second);
59 resolved = (j!=alias_map.end() ? j->second : i->second);
63 resolved = get_or_create_array_type(*resolved);
65 r_any_resolved |= (resolved!=type);
69 void TypeResolver::visit(Block &block)
71 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
74 type_insert_point = i;
79 void TypeResolver::visit(BasicTypeDeclaration &type)
81 resolve_type(type.base_type, type.base, false);
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)
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
91 type.size |= basic_base->size<<16;
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;
99 stage->types.insert(make_pair(type.name, &type));
102 void TypeResolver::visit(ImageTypeDeclaration &type)
104 resolve_type(type.base_type, type.base, false);
105 stage->types.insert(make_pair(type.name, &type));
108 void TypeResolver::visit(StructDeclaration &strct)
110 stage->types.insert(make_pair(strct.name, &strct));
111 TraversingVisitor::visit(strct);
114 void TypeResolver::visit(VariableDeclaration &var)
116 resolve_type(var.type_declaration, var.type, var.array);
117 if(iface_block && var.interface==iface_block->interface)
118 var.interface.clear();
121 void TypeResolver::visit(InterfaceBlock &iface)
125 SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
126 iface.members->visit(*this);
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));
136 strct->interface_block = &iface;
137 iface.struct_declaration = strct;
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;
147 void TypeResolver::visit(FunctionDeclaration &func)
149 resolve_type(func.return_type_declaration, func.return_type, false);
150 TraversingVisitor::visit(func);
154 VariableResolver::VariableResolver():
156 r_any_resolved(false),
157 record_target(false),
158 r_self_referencing(false)
161 bool VariableResolver::apply(Stage &s)
164 s.interface_blocks.clear();
165 r_any_resolved = false;
166 s.content.visit(*this);
167 for(VariableDeclaration *v: redeclared_builtins)
168 v->source = GENERATED_SOURCE;
169 NodeRemover().apply(s, nodes_to_remove);
170 return r_any_resolved;
173 void VariableResolver::enter(Block &block)
175 block.variables.clear();
178 void VariableResolver::visit(RefPtr<Expression> &expr)
180 r_replacement_expr = 0;
182 if(r_replacement_expr)
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;
190 r_replacement_expr = 0;
193 void VariableResolver::check_assignment_target(Statement *declaration)
197 if(r_assignment_target.declaration)
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;
205 r_assignment_target.declaration = declaration;
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;
212 void VariableResolver::visit(VariableReference &var)
214 VariableDeclaration *declaration = 0;
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
219 for(Block *block=current_block; (!declaration && block); block=block->parent)
221 auto i = block->variables.find(var.name);
222 if(i!=block->variables.end())
223 declaration = i->second;
228 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
229 auto i = blocks.find(var.name);
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))
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;
249 if(i->second->instance_name.empty())
251 iface_ref->name = format("%s %s", i->second->interface, i->second->block_name);
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;
259 r_replacement_expr = memacc;
263 iface_ref->name = var.name;
264 r_replacement_expr = iface_ref;
269 r_any_resolved |= (declaration!=var.declaration);
270 var.declaration = declaration;
272 check_assignment_target(var.declaration);
275 void VariableResolver::visit(InterfaceBlockReference &iface)
277 auto 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;
282 check_assignment_target(iface.declaration);
285 void VariableResolver::visit(MemberAccess &memacc)
287 TraversingVisitor::visit(memacc);
289 VariableDeclaration *declaration = 0;
291 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
293 auto i = strct->members.variables.find(memacc.member);
294 if(i!=strct->members.variables.end())
296 declaration = i->second;
298 for(auto j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
302 add_to_chain(r_assignment_target, Assignment::Target::MEMBER, index);
305 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
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)
311 static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
314 uint8_t components[4] = { };
315 for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
316 ok = ((components[i] = (std::find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
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;
333 r_any_resolved |= (declaration!=memacc.declaration || index!=memacc.index);
334 memacc.declaration = declaration;
335 memacc.index = index;
338 void VariableResolver::visit(Swizzle &swizzle)
340 TraversingVisitor::visit(swizzle);
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);
351 void VariableResolver::visit(BinaryExpression &binary)
353 if(binary.oper->token[0]=='[')
356 /* The subscript expression is not a part of the primary assignment
358 SetFlag set(record_target, false);
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);
373 TraversingVisitor::visit(binary);
376 void VariableResolver::visit(Assignment &assign)
379 SetFlag set(record_target);
380 r_assignment_target = Assignment::Target();
382 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
383 assign.target = r_assignment_target;
386 r_self_referencing = false;
388 assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
391 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
393 for(const Layout::Qualifier &q: from_layout.qualifiers)
395 auto i = find_member(to_layout.qualifiers, q.name, &Layout::Qualifier::name);
396 if(i!=to_layout.qualifiers.end())
398 i->has_value = q.value;
402 to_layout.qualifiers.push_back(q);
406 void VariableResolver::visit(VariableDeclaration &var)
408 TraversingVisitor::visit(var);
409 VariableDeclaration *&ptr = current_block->variables[var.name];
412 else if(!current_block->parent && ptr->interface==var.interface && ptr->type==var.type)
414 if(ptr->source==BUILTIN_SOURCE)
415 redeclared_builtins.push_back(&var);
417 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, var.source, var.line,
418 format("Redeclaring non-builtin variable '%s' is deprecated", var.name)));
420 if(var.init_expression)
421 ptr->init_expression = var.init_expression;
425 merge_layouts(*ptr->layout, *var.layout);
427 ptr->layout = var.layout;
429 nodes_to_remove.insert(&var);
431 r_any_resolved = true;
435 void VariableResolver::visit(InterfaceBlock &iface)
437 /* Block names can be reused in different interfaces. Prefix the name with
438 the first character of the interface to avoid conflicts. */
439 stage->interface_blocks.insert(make_pair(format("%s %s", iface.interface, iface.block_name), &iface));
440 if(!iface.instance_name.empty())
441 stage->interface_blocks.insert(make_pair(iface.instance_name, &iface));
443 TraversingVisitor::visit(iface);
447 ExpressionResolver::ExpressionResolver():
449 r_any_resolved(false)
452 bool ExpressionResolver::apply(Stage &s)
455 r_any_resolved = false;
456 s.content.visit(*this);
457 return r_any_resolved;
460 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
464 else if(can_convert(left, right))
465 return LEFT_CONVERTIBLE;
466 else if(can_convert(right, left))
467 return RIGHT_CONVERTIBLE;
469 return NOT_COMPATIBLE;
472 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
474 auto i = find_if(basic_types,
475 [kind, size, sign](const BasicTypeDeclaration *t){ return t->kind==kind && t->size==size && t->sign==sign; });
476 return (i!=basic_types.end() ? *i : 0);
479 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
481 auto i = find_if(basic_types,
482 [&elem_type, kind, size](BasicTypeDeclaration *t){ return get_element_type(*t)==&elem_type && t->kind==kind && t->size==size; });
483 return (i!=basic_types.end() ? *i : 0);
486 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
488 RefPtr<FunctionCall> call = new FunctionCall;
489 call->name = type.name;
490 call->constructor = true;
491 call->arguments.push_back_nocopy(expr);
496 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
498 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
500 BasicTypeDeclaration *to_type = &elem_type;
501 if(is_vector_or_matrix(*expr_basic))
502 to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
505 convert_to(expr, *to_type);
513 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
515 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
516 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
518 RefPtr<Swizzle> swizzle = new Swizzle;
519 swizzle->left = expr;
520 swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
521 swizzle->component_group = string("xyzw", size);
522 swizzle->count = size;
523 for(unsigned i=0; i<size; ++i)
524 swizzle->components[i] = i;
526 swizzle->type = expr_elem;
528 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
537 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
539 r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
541 expr.lvalue = lvalue;
544 void ExpressionResolver::visit(Block &block)
546 SetForScope<Block *> set_block(current_block, &block);
547 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
554 void ExpressionResolver::visit(Literal &literal)
556 if(literal.value.check_type<bool>())
557 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
558 else if(literal.value.check_type<int>())
559 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, true), false);
560 else if(literal.value.check_type<unsigned>())
561 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, false), false);
562 else if(literal.value.check_type<float>())
563 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
566 void ExpressionResolver::visit(VariableReference &var)
569 resolve(var, var.declaration->type_declaration, true);
572 void ExpressionResolver::visit(InterfaceBlockReference &iface)
574 if(iface.declaration)
575 resolve(iface, iface.declaration->type_declaration, true);
578 void ExpressionResolver::visit(MemberAccess &memacc)
580 TraversingVisitor::visit(memacc);
582 if(memacc.declaration)
583 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
586 void ExpressionResolver::visit(Swizzle &swizzle)
588 TraversingVisitor::visit(swizzle);
590 if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
592 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
594 resolve(swizzle, left_elem, swizzle.left->lvalue);
595 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
596 resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
600 void ExpressionResolver::visit(UnaryExpression &unary)
602 TraversingVisitor::visit(unary);
604 BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
608 char oper = unary.oper->token[0];
611 if(basic->kind!=BasicTypeDeclaration::BOOL)
616 if(basic->kind!=BasicTypeDeclaration::INT)
619 else if(oper=='+' || oper=='-')
621 BasicTypeDeclaration *elem = get_element_type(*basic);
622 if(!elem || !is_scalar(*elem))
625 resolve(unary, basic, unary.expression->lvalue);
628 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
630 /* Binary operators are only defined for basic types (not for image or
632 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
633 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
634 if(!basic_left || !basic_right)
637 char oper = binary.oper->token[0];
640 /* Subscripting operates on vectors, matrices and arrays, and the right
641 operand must be an integer. */
642 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
645 resolve(binary, basic_left->base_type, binary.left->lvalue);
648 else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
649 // No other binary operator can be used with arrays.
652 BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
653 BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
654 if(!elem_left || !elem_right)
657 Compatibility compat = get_compatibility(*basic_left, *basic_right);
658 Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
659 if(elem_compat==NOT_COMPATIBLE)
661 if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
664 TypeDeclaration *type = 0;
665 char oper2 = binary.oper->token[1];
666 if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
668 /* Relational operators compare two scalar integer or floating-point
670 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
673 type = find_type(BasicTypeDeclaration::BOOL, 1);
675 else if((oper=='=' || oper=='!') && oper2=='=')
677 // Equality comparison can be done on any compatible types.
678 if(compat==NOT_COMPATIBLE)
681 type = find_type(BasicTypeDeclaration::BOOL, 1);
683 else if(oper2=='&' || oper2=='|' || oper2=='^')
685 // Logical operators can only be applied to booleans.
686 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
691 else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
693 // Bitwise operators and modulo can only be applied to integers.
694 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
697 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
699 else if((oper=='<' || oper=='>') && oper2==oper)
701 // Shifts apply to integer scalars and vectors, with some restrictions.
702 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
704 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
705 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
706 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
709 /* If the left operand is a vector and right is scalar, convert the right
710 operand to a vector too. */
711 if(left_size>1 && right_size==1)
713 BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
717 convert_to(binary.right, *vec_right);
721 // Don't perform conversion even if the operands are of different sizes.
724 else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
726 // Arithmetic operators require scalar elements.
727 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
730 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
731 (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
733 /* Multiplication has special rules when at least one operand is a
734 matrix and the other is a vector or a matrix. */
735 unsigned left_columns = basic_left->size&0xFFFF;
736 unsigned right_rows = basic_right->size;
737 if(basic_right->kind==BasicTypeDeclaration::MATRIX)
739 if(left_columns!=right_rows)
742 BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
744 if(basic_left->kind==BasicTypeDeclaration::VECTOR)
745 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
746 else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
747 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
749 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
751 else if(compat==NOT_COMPATIBLE)
753 // Arithmetic between scalars and matrices or vectors is supported.
754 if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
755 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
756 else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
757 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
761 else if(compat==LEFT_CONVERTIBLE)
769 if(assign && type!=basic_left)
772 bool converted = true;
773 if(compat==LEFT_CONVERTIBLE)
774 convert_to(binary.left, *basic_right);
775 else if(compat==RIGHT_CONVERTIBLE)
776 convert_to(binary.right, *basic_left);
777 else if(elem_compat==LEFT_CONVERTIBLE)
778 converted = convert_to_element(binary.left, *elem_right);
779 else if(elem_compat==RIGHT_CONVERTIBLE)
780 converted = convert_to_element(binary.right, *elem_left);
785 resolve(binary, type, assign);
788 void ExpressionResolver::visit(BinaryExpression &binary)
790 TraversingVisitor::visit(binary);
791 visit(binary, false);
794 void ExpressionResolver::visit(Assignment &assign)
796 TraversingVisitor::visit(assign);
798 if(assign.oper->token[0]!='=')
799 return visit(assign, true);
800 else if(assign.left->type!=assign.right->type)
802 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
803 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
804 if(!basic_left || !basic_right)
807 Compatibility compat = get_compatibility(*basic_left, *basic_right);
808 if(compat==RIGHT_CONVERTIBLE)
809 convert_to(assign.right, *basic_left);
810 else if(compat!=SAME_TYPE)
814 resolve(assign, assign.left->type, true);
817 void ExpressionResolver::visit(TernaryExpression &ternary)
819 TraversingVisitor::visit(ternary);
821 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
822 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
825 TypeDeclaration *type = 0;
826 if(ternary.true_expr->type==ternary.false_expr->type)
827 type = ternary.true_expr->type;
830 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
831 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
832 if(!basic_true || !basic_false)
835 Compatibility compat = get_compatibility(*basic_true, *basic_false);
836 if(compat==NOT_COMPATIBLE)
839 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
841 if(compat==LEFT_CONVERTIBLE)
842 convert_to(ternary.true_expr, *basic_false);
843 else if(compat==RIGHT_CONVERTIBLE)
844 convert_to(ternary.false_expr, *basic_true);
847 resolve(ternary, type, false);
850 void ExpressionResolver::visit_constructor(FunctionCall &call)
852 if(call.arguments.empty())
855 auto i = stage->types.find(call.name);
856 if(i==stage->types.end())
858 else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
860 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
862 BasicTypeDeclaration *elem = get_element_type(*basic);
866 vector<ArgumentInfo> args;
867 args.reserve(call.arguments.size());
868 unsigned arg_component_total = 0;
869 bool has_matrices = false;
870 for(const RefPtr<Expression> &a: call.arguments)
873 if(!(info.type=dynamic_cast<BasicTypeDeclaration *>(a->type)))
875 if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
876 info.component_count = 1;
877 else if(info.type->kind==BasicTypeDeclaration::VECTOR)
878 info.component_count = info.type->size;
879 else if(info.type->kind==BasicTypeDeclaration::MATRIX)
881 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
886 arg_component_total += info.component_count;
887 args.push_back(info);
890 bool convert_args = false;
891 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
893 if(arg_component_total>1)
894 truncate_vector(call.arguments.front(), 1);
896 /* Single-element type constructors never need to convert their
897 arguments because the constructor *is* the conversion. */
899 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
901 /* Vector constructors need either a single scalar argument or
902 enough components to fill out the vector. */
903 if(arg_component_total!=1 && arg_component_total<basic->size)
906 /* A vector of same size can be converted directly. For other
907 combinations the individual arguments need to be converted. */
908 if(call.arguments.size()==1)
910 if(arg_component_total==1)
912 else if(arg_component_total>basic->size)
913 truncate_vector(call.arguments.front(), basic->size);
915 else if(arg_component_total==basic->size)
920 else if(basic->kind==BasicTypeDeclaration::MATRIX)
922 unsigned column_count = basic->size&0xFFFF;
923 unsigned row_count = basic->size>>16;
924 if(call.arguments.size()==1)
926 /* A matrix can be constructed from a single element or another
927 matrix of sufficient size. */
928 if(arg_component_total==1)
930 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
932 unsigned arg_columns = args.front().type->size&0xFFFF;
933 unsigned arg_rows = args.front().type->size>>16;
934 if(arg_columns<column_count || arg_rows<row_count)
937 /* Always generate a temporary here and let the optimization
938 stage inline it if that's reasonable. */
939 RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
940 temporary->type = args.front().type->name;
941 temporary->name = get_unused_variable_name(*current_block, "_temp");
942 temporary->init_expression = call.arguments.front();
943 current_block->body.insert(insert_point, temporary);
945 // Create expressions to build each column.
946 vector<RefPtr<Expression> > columns;
947 columns.reserve(column_count);
948 for(unsigned j=0; j<column_count; ++j)
950 RefPtr<VariableReference> ref = new VariableReference;
951 ref->name = temporary->name;
953 RefPtr<Literal> index = new Literal;
954 index->token = lexical_cast<string>(j);
955 index->value = static_cast<int>(j);
957 RefPtr<BinaryExpression> subscript = new BinaryExpression;
958 subscript->left = ref;
959 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
960 subscript->right = index;
961 subscript->type = args.front().type->base_type;
963 columns.push_back(subscript);
964 if(arg_rows>row_count)
965 truncate_vector(columns.back(), row_count);
968 call.arguments.resize(column_count);
969 copy(columns.begin(), columns.end(), call.arguments.begin());
971 /* Let VariableResolver process the new nodes and finish
972 resolving the constructor on the next pass. */
973 r_any_resolved = true;
979 else if(arg_component_total==column_count*row_count && !has_matrices)
981 /* Construct a matrix from individual components in column-major
982 order. Arguments must align at column boundaries. */
983 vector<RefPtr<Expression> > columns;
984 columns.reserve(column_count);
986 vector<RefPtr<Expression> > column_args;
987 column_args.reserve(row_count);
988 unsigned column_component_count = 0;
990 for(unsigned j=0; j<call.arguments.size(); ++j)
992 const ArgumentInfo &info = args[j];
993 if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
994 // A vector filling the entire column can be used as is.
995 columns.push_back(call.arguments[j]);
998 column_args.push_back(call.arguments[j]);
999 column_component_count += info.component_count;
1000 if(column_component_count==row_count)
1002 /* The column has filled up. Create a vector constructor
1004 RefPtr<FunctionCall> column_call = new FunctionCall;
1005 column_call->name = basic->base_type->name;
1006 column_call->constructor = true;
1007 column_call->arguments.resize(column_args.size());
1008 copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1009 column_call->type = basic->base_type;
1010 visit_constructor(*column_call);
1011 columns.push_back(column_call);
1013 column_args.clear();
1014 column_component_count = 0;
1016 else if(column_component_count>row_count)
1017 // Argument alignment mismatch.
1030 // The argument list may have changed so can't rely on args.
1031 for(RefPtr<Expression> &a: call.arguments)
1032 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1034 BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1036 convert_to_element(a, *elem);
1040 else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1042 if(call.arguments.size()!=strct->members.body.size())
1045 auto j = call.arguments.begin();
1046 for(const RefPtr<Statement> &s: strct->members.body)
1048 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(s.get()))
1050 if(!(*j)->type || (*j)->type!=var->type_declaration)
1059 resolve(call, i->second, false);
1062 void ExpressionResolver::visit(FunctionCall &call)
1064 TraversingVisitor::visit(call);
1066 if(call.declaration)
1067 resolve(call, call.declaration->return_type_declaration, false);
1068 else if(call.constructor)
1069 visit_constructor(call);
1072 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1074 basic_types.push_back(&type);
1077 void ExpressionResolver::visit(VariableDeclaration &var)
1079 TraversingVisitor::visit(var);
1080 if(!var.init_expression)
1083 BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1084 BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1085 if(!var_basic || !init_basic)
1088 Compatibility compat = get_compatibility(*var_basic, *init_basic);
1089 if(compat==RIGHT_CONVERTIBLE)
1090 convert_to(var.init_expression, *var_basic);
1094 bool FunctionResolver::apply(Stage &s)
1097 s.functions.clear();
1098 r_any_resolved = false;
1099 s.content.visit(*this);
1100 return r_any_resolved;
1103 bool FunctionResolver::can_convert_arguments(const FunctionCall &call, const FunctionDeclaration &decl)
1105 if(decl.parameters.size()!=call.arguments.size())
1108 for(unsigned j=0; j<call.arguments.size(); ++j)
1110 const TypeDeclaration *arg_type = call.arguments[j]->type;
1111 const TypeDeclaration *param_type = decl.parameters[j]->type_declaration;
1112 if(arg_type==param_type)
1115 const BasicTypeDeclaration *arg_basic = dynamic_cast<const BasicTypeDeclaration *>(arg_type);
1116 const BasicTypeDeclaration *param_basic = dynamic_cast<const BasicTypeDeclaration *>(param_type);
1117 if(arg_basic && param_basic && can_convert(*arg_basic, *param_basic))
1126 void FunctionResolver::visit(FunctionCall &call)
1128 FunctionDeclaration *declaration = 0;
1129 if(stage->types.count(call.name))
1130 call.constructor = true;
1134 bool has_signature = true;
1135 for(auto i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1138 append(arg_types, ",", (*i)->type->name);
1140 has_signature = false;
1145 auto i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1146 declaration = (i!=stage->functions.end() ? i->second : 0);
1150 for(i=stage->functions.lower_bound(call.name+"("); (i!=stage->functions.end() && i->second->name==call.name); ++i)
1151 if(can_convert_arguments(call, *i->second))
1159 declaration = i->second;
1165 r_any_resolved |= (declaration!=call.declaration);
1166 call.declaration = declaration;
1168 TraversingVisitor::visit(call);
1171 void FunctionResolver::visit(FunctionDeclaration &func)
1173 if(func.signature.empty())
1176 for(const RefPtr<VariableDeclaration> &p: func.parameters)
1178 if(p->type_declaration)
1179 append(param_types, ",", p->type_declaration->name);
1183 func.signature = format("(%s)", param_types);
1184 r_any_resolved = true;
1187 string key = func.name+func.signature;
1188 FunctionDeclaration *&stage_decl = stage->functions[key];
1189 vector<FunctionDeclaration *> &decls = declarations[key];
1190 if(func.definition==&func)
1192 if(stage_decl && stage_decl->definition)
1195 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1196 format("Overriding function '%s' without the override keyword is deprecated", key)));
1197 if(!stage_decl->definition->virtua)
1198 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1199 format("Overriding function '%s' not declared as virtual is deprecated", key)));
1203 // Set all previous declarations to use this definition.
1204 for(FunctionDeclaration *f: decls)
1206 r_any_resolved |= (func.definition!=f->definition);
1207 f->definition = func.definition;
1208 f->body.body.clear();
1213 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1214 r_any_resolved |= (definition!=func.definition);
1215 func.definition = definition;
1220 decls.push_back(&func);
1222 TraversingVisitor::visit(func);