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 map<TypeDeclaration *, TypeDeclaration *>::iterator 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 map<string, TypeDeclaration *>::iterator i = stage->types.find(name);
56 if(i!=stage->types.end())
58 map<TypeDeclaration *, TypeDeclaration *>::iterator 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(NodeList<Statement>::iterator 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(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;
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 map<string, VariableDeclaration *>::iterator 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 map<string, InterfaceBlock *>::const_iterator 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 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;
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 map<string, VariableDeclaration *>::iterator i = strct->members.variables.find(memacc.member);
294 if(i!=strct->members.variables.end())
296 declaration = i->second;
298 for(NodeList<Statement>::const_iterator 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 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);
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(vector<Layout::Qualifier>::const_iterator i=from_layout.qualifiers.begin(); i!=from_layout.qualifiers.end(); ++i)
396 for(vector<Layout::Qualifier>::iterator j=to_layout.qualifiers.begin(); (!found && j!=to_layout.qualifiers.end()); ++j)
399 j->has_value = i->value;
405 to_layout.qualifiers.push_back(*i);
409 void VariableResolver::visit(VariableDeclaration &var)
411 TraversingVisitor::visit(var);
412 VariableDeclaration *&ptr = current_block->variables[var.name];
415 else if(!current_block->parent && ptr->interface==var.interface && ptr->type==var.type)
417 if(ptr->source==BUILTIN_SOURCE)
418 redeclared_builtins.push_back(&var);
420 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, var.source, var.line,
421 format("Redeclaring non-builtin variable '%s' is deprecated", var.name)));
423 if(var.init_expression)
424 ptr->init_expression = var.init_expression;
428 merge_layouts(*ptr->layout, *var.layout);
430 ptr->layout = var.layout;
432 nodes_to_remove.insert(&var);
434 r_any_resolved = true;
438 void VariableResolver::visit(InterfaceBlock &iface)
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));
446 TraversingVisitor::visit(iface);
450 ExpressionResolver::ExpressionResolver():
452 r_any_resolved(false)
455 bool ExpressionResolver::apply(Stage &s)
458 r_any_resolved = false;
459 s.content.visit(*this);
460 return r_any_resolved;
463 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
467 else if(can_convert(left, right))
468 return LEFT_CONVERTIBLE;
469 else if(can_convert(right, left))
470 return RIGHT_CONVERTIBLE;
472 return NOT_COMPATIBLE;
475 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
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)
483 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
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)
491 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
493 RefPtr<FunctionCall> call = new FunctionCall;
494 call->name = type.name;
495 call->constructor = true;
496 call->arguments.push_back_nocopy(expr);
501 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
503 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
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);
510 convert_to(expr, *to_type);
518 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
520 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
521 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
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;
531 swizzle->type = expr_elem;
533 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
542 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
544 r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
546 expr.lvalue = lvalue;
549 void ExpressionResolver::visit(Block &block)
551 SetForScope<Block *> set_block(current_block, &block);
552 for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
559 void ExpressionResolver::visit(Literal &literal)
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);
571 void ExpressionResolver::visit(VariableReference &var)
574 resolve(var, var.declaration->type_declaration, true);
577 void ExpressionResolver::visit(InterfaceBlockReference &iface)
579 if(iface.declaration)
580 resolve(iface, iface.declaration->type_declaration, true);
583 void ExpressionResolver::visit(MemberAccess &memacc)
585 TraversingVisitor::visit(memacc);
587 if(memacc.declaration)
588 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
591 void ExpressionResolver::visit(Swizzle &swizzle)
593 TraversingVisitor::visit(swizzle);
595 if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
597 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
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);
605 void ExpressionResolver::visit(UnaryExpression &unary)
607 TraversingVisitor::visit(unary);
609 BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
613 char oper = unary.oper->token[0];
616 if(basic->kind!=BasicTypeDeclaration::BOOL)
621 if(basic->kind!=BasicTypeDeclaration::INT)
624 else if(oper=='+' || oper=='-')
626 BasicTypeDeclaration *elem = get_element_type(*basic);
627 if(!elem || !is_scalar(*elem))
630 resolve(unary, basic, unary.expression->lvalue);
633 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
635 /* Binary operators are only defined for basic types (not for image or
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)
642 char oper = binary.oper->token[0];
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)
650 resolve(binary, basic_left->base_type, binary.left->lvalue);
653 else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
654 // No other binary operator can be used with arrays.
657 BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
658 BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
659 if(!elem_left || !elem_right)
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)
666 if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
669 TypeDeclaration *type = 0;
670 char oper2 = binary.oper->token[1];
671 if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
673 /* Relational operators compare two scalar integer or floating-point
675 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
678 type = find_type(BasicTypeDeclaration::BOOL, 1);
680 else if((oper=='=' || oper=='!') && oper2=='=')
682 // Equality comparison can be done on any compatible types.
683 if(compat==NOT_COMPATIBLE)
686 type = find_type(BasicTypeDeclaration::BOOL, 1);
688 else if(oper2=='&' || oper2=='|' || oper2=='^')
690 // Logical operators can only be applied to booleans.
691 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
696 else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
698 // Bitwise operators and modulo can only be applied to integers.
699 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
702 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
704 else if((oper=='<' || oper=='>') && oper2==oper)
706 // Shifts apply to integer scalars and vectors, with some restrictions.
707 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
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))
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)
718 BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
722 convert_to(binary.right, *vec_right);
726 // Don't perform conversion even if the operands are of different sizes.
729 else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
731 // Arithmetic operators require scalar elements.
732 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
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))
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)
744 if(left_columns!=right_rows)
747 BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
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);
754 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
756 else if(compat==NOT_COMPATIBLE)
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);
766 else if(compat==LEFT_CONVERTIBLE)
774 if(assign && type!=basic_left)
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);
790 resolve(binary, type, assign);
793 void ExpressionResolver::visit(BinaryExpression &binary)
795 TraversingVisitor::visit(binary);
796 visit(binary, false);
799 void ExpressionResolver::visit(Assignment &assign)
801 TraversingVisitor::visit(assign);
803 if(assign.oper->token[0]!='=')
804 return visit(assign, true);
805 else if(assign.left->type!=assign.right->type)
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)
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)
819 resolve(assign, assign.left->type, true);
822 void ExpressionResolver::visit(TernaryExpression &ternary)
824 TraversingVisitor::visit(ternary);
826 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
827 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
830 TypeDeclaration *type = 0;
831 if(ternary.true_expr->type==ternary.false_expr->type)
832 type = ternary.true_expr->type;
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)
840 Compatibility compat = get_compatibility(*basic_true, *basic_false);
841 if(compat==NOT_COMPATIBLE)
844 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
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);
852 resolve(ternary, type, false);
855 void ExpressionResolver::visit_constructor(FunctionCall &call)
857 if(call.arguments.empty())
860 map<string, TypeDeclaration *>::const_iterator i = stage->types.find(call.name);
861 if(i==stage->types.end())
863 else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
865 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
867 BasicTypeDeclaration *elem = get_element_type(*basic);
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)
878 if(!(info.type=dynamic_cast<BasicTypeDeclaration *>((*j)->type)))
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)
886 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
891 arg_component_total += info.component_count;
892 args.push_back(info);
895 bool convert_args = false;
896 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
898 if(arg_component_total>1)
899 truncate_vector(call.arguments.front(), 1);
901 /* Single-element type constructors never need to convert their
902 arguments because the constructor *is* the conversion. */
904 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
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)
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)
915 if(arg_component_total==1)
917 else if(arg_component_total>basic->size)
918 truncate_vector(call.arguments.front(), basic->size);
920 else if(arg_component_total==basic->size)
925 else if(basic->kind==BasicTypeDeclaration::MATRIX)
927 unsigned column_count = basic->size&0xFFFF;
928 unsigned row_count = basic->size>>16;
929 if(call.arguments.size()==1)
931 /* A matrix can be constructed from a single element or another
932 matrix of sufficient size. */
933 if(arg_component_total==1)
935 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
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)
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);
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)
955 RefPtr<VariableReference> ref = new VariableReference;
956 ref->name = temporary->name;
958 RefPtr<Literal> index = new Literal;
959 index->token = lexical_cast<string>(j);
960 index->value = static_cast<int>(j);
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;
968 columns.push_back(subscript);
969 if(arg_rows>row_count)
970 truncate_vector(columns.back(), row_count);
973 call.arguments.resize(column_count);
974 copy(columns.begin(), columns.end(), call.arguments.begin());
976 /* Let VariableResolver process the new nodes and finish
977 resolving the constructor on the next pass. */
978 r_any_resolved = true;
984 else if(arg_component_total==column_count*row_count && !has_matrices)
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);
991 vector<RefPtr<Expression> > column_args;
992 column_args.reserve(row_count);
993 unsigned column_component_count = 0;
995 for(unsigned j=0; j<call.arguments.size(); ++j)
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]);
1003 column_args.push_back(call.arguments[j]);
1004 column_component_count += info.component_count;
1005 if(column_component_count==row_count)
1007 /* The column has filled up. Create a vector constructor
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);
1018 column_args.clear();
1019 column_component_count = 0;
1021 else if(column_component_count>row_count)
1022 // Argument alignment mismatch.
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))
1039 BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1041 convert_to_element(*j, *elem);
1045 else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1047 if(call.arguments.size()!=strct->members.body.size())
1051 for(NodeList<Statement>::const_iterator j=strct->members.body.begin(); j!=strct->members.body.end(); ++j, ++k)
1053 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(j->get()))
1055 if(!call.arguments[k]->type || call.arguments[k]->type!=var->type_declaration)
1063 resolve(call, i->second, false);
1066 void ExpressionResolver::visit(FunctionCall &call)
1068 TraversingVisitor::visit(call);
1070 if(call.declaration)
1071 resolve(call, call.declaration->return_type_declaration, false);
1072 else if(call.constructor)
1073 visit_constructor(call);
1076 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1078 basic_types.push_back(&type);
1081 void ExpressionResolver::visit(VariableDeclaration &var)
1083 TraversingVisitor::visit(var);
1084 if(!var.init_expression)
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)
1092 Compatibility compat = get_compatibility(*var_basic, *init_basic);
1093 if(compat==RIGHT_CONVERTIBLE)
1094 convert_to(var.init_expression, *var_basic);
1098 bool FunctionResolver::apply(Stage &s)
1101 s.functions.clear();
1102 r_any_resolved = false;
1103 s.content.visit(*this);
1104 return r_any_resolved;
1107 bool FunctionResolver::can_convert_arguments(const FunctionCall &call, const FunctionDeclaration &decl)
1109 if(decl.parameters.size()!=call.arguments.size())
1112 for(unsigned j=0; j<call.arguments.size(); ++j)
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)
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))
1130 void FunctionResolver::visit(FunctionCall &call)
1132 FunctionDeclaration *declaration = 0;
1133 if(stage->types.count(call.name))
1134 call.constructor = true;
1138 bool has_signature = true;
1139 for(NodeArray<Expression>::const_iterator i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1142 append(arg_types, ",", (*i)->type->name);
1144 has_signature = false;
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);
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))
1163 declaration = i->second;
1169 r_any_resolved |= (declaration!=call.declaration);
1170 call.declaration = declaration;
1172 TraversingVisitor::visit(call);
1175 void FunctionResolver::visit(FunctionDeclaration &func)
1177 if(func.signature.empty())
1180 for(NodeArray<VariableDeclaration>::const_iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
1182 if((*i)->type_declaration)
1183 append(param_types, ",", (*i)->type_declaration->name);
1187 func.signature = format("(%s)", param_types);
1188 r_any_resolved = true;
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)
1196 if(stage_decl && stage_decl->definition)
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)));
1207 // Set all previous declarations to use this definition.
1208 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
1210 r_any_resolved |= (func.definition!=(*i)->definition);
1211 (*i)->definition = func.definition;
1212 (*i)->body.body.clear();
1217 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1218 r_any_resolved |= (definition!=func.definition);
1219 func.definition = definition;
1224 decls.push_back(&func);
1226 TraversingVisitor::visit(func);