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 bool extended_alignment = iface_block;
32 auto key = make_pair(&type, extended_alignment);
33 auto i = array_types.find(key);
34 if(i!=array_types.end())
37 BasicTypeDeclaration *array = new BasicTypeDeclaration;
38 array->source = INTERNAL_SOURCE;
39 array->name = type.name+"[]";
40 array->kind = BasicTypeDeclaration::ARRAY;
41 array->extended_alignment = extended_alignment;
42 array->base = type.name;
43 array->base_type = &type;
44 stage->content.body.insert(type_insert_point, array);
45 array_types[key] = array;
49 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array)
51 TypeDeclaration *resolved = 0;
52 auto i = stage->types.find(name);
53 if(i!=stage->types.end())
55 auto j = alias_map.find(i->second);
56 resolved = (j!=alias_map.end() ? j->second : i->second);
60 resolved = get_or_create_array_type(*resolved);
62 r_any_resolved |= (resolved!=type);
66 void TypeResolver::visit(Block &block)
68 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
71 type_insert_point = i;
76 void TypeResolver::visit(BasicTypeDeclaration &type)
78 resolve_type(type.base_type, type.base, false);
80 if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
81 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
82 if(basic_base->kind==BasicTypeDeclaration::VECTOR)
84 type.kind = BasicTypeDeclaration::MATRIX;
85 /* A matrix's base type is its column vector type. This will put
86 the column vector's size, i.e. the matrix's row count, in the high
88 type.size |= basic_base->size<<16;
91 if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
92 alias_map[&type] = type.base_type;
93 else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
94 array_types[make_pair(type.base_type, type.extended_alignment)] = &type;
96 stage->types.insert(make_pair(type.name, &type));
99 void TypeResolver::visit(ImageTypeDeclaration &type)
101 resolve_type(type.base_type, type.base, false);
102 stage->types.insert(make_pair(type.name, &type));
105 void TypeResolver::visit(StructDeclaration &strct)
107 stage->types.insert(make_pair(strct.name, &strct));
108 if(strct.block_name.empty())
110 SetForScope<VariableDeclaration *> set_iface(iface_block, strct.block_declaration);
111 TraversingVisitor::visit(strct);
114 block_member_type_ins_pt = type_insert_point;
117 void TypeResolver::visit(VariableDeclaration &var)
119 resolve_type(var.type_declaration, var.type, var.array);
121 var.block_declaration = 0;
122 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(get_ultimate_base_type(var.type_declaration)))
123 if(!strct->block_name.empty())
125 var.block_declaration = strct;
126 strct->block_declaration = &var;
127 strct->extended_alignment = true;
129 SetForScope<NodeList<Statement>::iterator> set_ins_pt(type_insert_point, block_member_type_ins_pt);
130 SetForScope<VariableDeclaration *> set_iface(iface_block, &var);
131 TraversingVisitor::visit(*strct);
136 if(var.interface==iface_block->interface)
137 var.interface.clear();
138 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(var.type_declaration))
139 strct->extended_alignment = true;
143 void TypeResolver::visit(FunctionDeclaration &func)
145 resolve_type(func.return_type_declaration, func.return_type, false);
146 TraversingVisitor::visit(func);
150 bool VariableResolver::apply(Stage &s)
153 s.interface_blocks.clear();
154 r_any_resolved = false;
155 s.content.visit(*this);
156 for(Statement *b: redeclared_builtins)
157 b->source = GENERATED_SOURCE;
158 NodeRemover().apply(s, nodes_to_remove);
159 return r_any_resolved;
162 void VariableResolver::enter(Block &block)
164 block.variables.clear();
167 void VariableResolver::visit(RefPtr<Expression> &expr)
169 r_replacement_expr = 0;
171 if(r_replacement_expr)
173 expr = r_replacement_expr;
174 /* Don't record assignment target when doing a replacement, because chain
175 information won't be correct. */
176 r_assignment_target.declaration = 0;
177 r_any_resolved = true;
179 r_replacement_expr = 0;
182 void VariableResolver::check_assignment_target(Statement *declaration)
186 if(r_assignment_target.declaration)
188 /* More than one reference found in assignment target. Unable to
189 determine what the primary target is. */
190 record_target = false;
191 r_assignment_target.declaration = 0;
194 r_assignment_target.declaration = declaration;
196 // TODO This check is overly broad and may prevent some optimizations.
197 else if(declaration && declaration==r_assignment_target.declaration)
198 r_self_referencing = true;
201 void VariableResolver::visit(VariableReference &var)
203 VariableDeclaration *declaration = 0;
205 /* Look for variable declarations in the block hierarchy first. Interface
206 blocks are always defined in the top level so we can't accidentally skip
208 for(Block *block=current_block; (!declaration && block); block=block->parent)
210 auto i = block->variables.find(var.name);
211 if(i!=block->variables.end())
212 declaration = i->second;
217 for(const auto &kvp: stage->interface_blocks)
218 if(kvp.second->name.find(' ')!=string::npos && kvp.second->block_declaration->members.variables.count(var.name))
220 /* The name refers a member of an anonymous interface block. Prepare
221 new syntax tree nodes accordingly. */
222 VariableReference *iface_ref = new VariableReference;
223 iface_ref->name = kvp.first;
224 iface_ref->source = var.source;
225 iface_ref->line = var.line;
226 iface_ref->declaration = kvp.second;
228 MemberAccess *memacc = new MemberAccess;
229 memacc->source = var.source;
230 memacc->line = var.line;
231 memacc->left = iface_ref;
232 memacc->member = var.name;
234 r_replacement_expr = memacc;
239 r_any_resolved |= (declaration!=var.declaration);
240 var.declaration = declaration;
242 check_assignment_target(var.declaration);
245 void VariableResolver::visit(MemberAccess &memacc)
247 TraversingVisitor::visit(memacc);
249 VariableDeclaration *declaration = 0;
251 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
253 auto i = strct->members.variables.find(memacc.member);
254 if(i!=strct->members.variables.end())
256 declaration = i->second;
258 for(auto j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
262 add_to_chain(r_assignment_target, Assignment::Target::MEMBER, index);
265 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
267 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
268 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
269 if(scalar_swizzle || vector_swizzle)
271 static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
274 uint8_t components[4] = { };
275 for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
276 ok = ((components[i] = (std::find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
280 Swizzle *swizzle = new Swizzle;
281 swizzle->source = memacc.source;
282 swizzle->line = memacc.line;
283 swizzle->oper = memacc.oper;
284 swizzle->left = memacc.left;
285 swizzle->component_group = memacc.member;
286 swizzle->count = memacc.member.size();
287 copy(components, components+memacc.member.size(), swizzle->components);
288 r_replacement_expr = swizzle;
293 r_any_resolved |= (declaration!=memacc.declaration || index!=memacc.index);
294 memacc.declaration = declaration;
295 memacc.index = index;
298 void VariableResolver::visit(Swizzle &swizzle)
300 TraversingVisitor::visit(swizzle);
305 for(unsigned i=0; i<swizzle.count; ++i)
306 mask |= 1<<swizzle.components[i];
307 add_to_chain(r_assignment_target, Assignment::Target::SWIZZLE, mask);
311 void VariableResolver::visit(BinaryExpression &binary)
313 if(binary.oper->token[0]=='[')
316 /* The subscript expression is not a part of the primary assignment
318 SetFlag set(record_target, false);
325 unsigned index = 0x3F;
326 if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
327 if(literal_subscript->value.check_type<int>())
328 index = literal_subscript->value.value<int>();
329 add_to_chain(r_assignment_target, Assignment::Target::ARRAY, index);
333 TraversingVisitor::visit(binary);
336 void VariableResolver::visit(Assignment &assign)
339 SetFlag set(record_target);
340 r_assignment_target = Assignment::Target();
342 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
343 assign.target = r_assignment_target;
346 r_self_referencing = false;
348 assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
351 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
353 for(const Layout::Qualifier &q: from_layout.qualifiers)
355 auto i = find_member(to_layout.qualifiers, q.name, &Layout::Qualifier::name);
356 if(i!=to_layout.qualifiers.end())
358 i->has_value = q.value;
362 to_layout.qualifiers.push_back(q);
366 void VariableResolver::redeclare_builtin(VariableDeclaration &existing, VariableDeclaration &var)
371 merge_layouts(*existing.layout, *var.layout);
373 existing.layout = var.layout;
376 existing.array_size = var.array_size;
378 redeclared_builtins.push_back(&existing);
381 void VariableResolver::visit(VariableDeclaration &var)
383 TraversingVisitor::visit(var);
385 auto i = current_block->variables.find(var.name);
386 VariableDeclaration *existing = 0;
387 VariableDeclaration *block = 0;
388 if(i!=current_block->variables.end())
389 existing = i->second;
390 else if(!current_block->parent)
392 const map<string, VariableDeclaration *> &blocks = stage->interface_blocks;
393 for(auto j=blocks.begin(); j!=blocks.end(); ++j)
394 if(j->second->name.find(' ')!=string::npos)
396 const map<string, VariableDeclaration *> &block_vars = j->second->block_declaration->members.variables;
397 auto k = block_vars.find(var.name);
398 if(k!=block_vars.end())
400 existing = k->second;
409 current_block->variables.insert(make_pair(var.name, &var));
410 if(var.block_declaration)
412 stage->interface_blocks.insert(make_pair(format("%s %s", var.interface, var.block_declaration->block_name), &var));
413 if(var.name.find(' ')==string::npos)
414 stage->interface_blocks.insert(make_pair(var.name, &var));
417 else if(!current_block->parent && (block ? block->interface : existing->interface)==var.interface && existing->array==var.array)
419 if(existing->source==BUILTIN_SOURCE)
421 if(var.block_declaration && existing->block_declaration && var.block_declaration->block_name==existing->block_declaration->block_name)
423 const map<string, VariableDeclaration *> &vars = var.block_declaration->members.variables;
424 const map<string, VariableDeclaration *> &existing_vars = existing->block_declaration->members.variables;
426 bool found_all = true;
427 for(const auto &kvp: vars)
429 auto j = existing_vars.find(kvp.first);
430 if(j!=existing_vars.end() && j->second->type==kvp.second->type && j->second->array==kvp.second->array)
431 redeclare_builtin(*j->second, *kvp.second);
438 redeclared_builtins.push_back(existing);
439 nodes_to_remove.insert(&var);
440 // The block struct will be removed during unused type removal
441 //nodes_to_remove.insert(var.block_declaration);
444 else if(!var.block_declaration && !existing->block_declaration && var.type==existing->type)
446 redeclare_builtin(*existing, var);
450 /* Cause the block and its members to be marked as not builtin
451 so it will be emitted in output */
452 redeclared_builtins.push_back(block);
453 for(const auto &kvp: block->block_declaration->members.variables)
454 redeclared_builtins.push_back(kvp.second);
457 nodes_to_remove.insert(&var);
458 r_any_resolved = true;
461 else if(existing->array && !existing->array_size && var.type==existing->type && !var.layout && !var.init_expression)
463 existing->array_size = var.array_size;
464 nodes_to_remove.insert(&var);
465 r_any_resolved = true;
471 bool ExpressionResolver::apply(Stage &s)
474 r_any_resolved = false;
475 s.content.visit(*this);
476 return r_any_resolved;
479 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
483 else if(can_convert(left, right))
484 return LEFT_CONVERTIBLE;
485 else if(can_convert(right, left))
486 return RIGHT_CONVERTIBLE;
488 return NOT_COMPATIBLE;
491 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
493 auto i = find_if(basic_types,
494 [kind, size, sign](const BasicTypeDeclaration *t){ return t->kind==kind && t->size==size && t->sign==sign; });
495 return (i!=basic_types.end() ? *i : 0);
498 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
500 auto i = find_if(basic_types,
501 [&elem_type, kind, size](BasicTypeDeclaration *t){ return get_element_type(*t)==&elem_type && t->kind==kind && t->size==size; });
502 return (i!=basic_types.end() ? *i : 0);
505 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
507 RefPtr<FunctionCall> call = new FunctionCall;
508 call->name = type.name;
509 call->constructor = true;
510 call->arguments.push_back_nocopy(expr);
515 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
517 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
519 BasicTypeDeclaration *to_type = &elem_type;
520 if(is_vector_or_matrix(*expr_basic))
521 to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
524 convert_to(expr, *to_type);
532 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
534 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
535 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
537 RefPtr<Swizzle> swizzle = new Swizzle;
538 swizzle->left = expr;
539 swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
540 swizzle->component_group = string("xyzw", size);
541 swizzle->count = size;
542 for(unsigned i=0; i<size; ++i)
543 swizzle->components[i] = i;
545 swizzle->type = expr_elem;
547 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
556 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
558 r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
560 expr.lvalue = lvalue;
563 void ExpressionResolver::visit(Block &block)
565 SetForScope<Block *> set_block(current_block, &block);
566 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
573 void ExpressionResolver::visit(Literal &literal)
575 if(literal.value.check_type<bool>())
576 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
577 else if(literal.value.check_type<int>())
578 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, true), false);
579 else if(literal.value.check_type<unsigned>())
580 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, false), false);
581 else if(literal.value.check_type<float>())
582 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
585 void ExpressionResolver::visit(VariableReference &var)
588 resolve(var, var.declaration->type_declaration, true);
591 void ExpressionResolver::visit(MemberAccess &memacc)
593 TraversingVisitor::visit(memacc);
595 if(memacc.declaration)
596 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
599 void ExpressionResolver::visit(Swizzle &swizzle)
601 TraversingVisitor::visit(swizzle);
603 if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
605 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
607 resolve(swizzle, left_elem, swizzle.left->lvalue);
608 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
609 resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
613 void ExpressionResolver::visit(UnaryExpression &unary)
615 TraversingVisitor::visit(unary);
617 BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
621 char oper = unary.oper->token[0];
624 if(basic->kind!=BasicTypeDeclaration::BOOL)
629 if(basic->kind!=BasicTypeDeclaration::INT)
632 else if(oper=='+' || oper=='-')
634 BasicTypeDeclaration *elem = get_element_type(*basic);
635 if(!elem || !is_scalar(*elem))
638 resolve(unary, basic, unary.expression->lvalue);
641 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
643 /* Binary operators are only defined for basic types (not for image or
645 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
646 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
647 if(!basic_left || !basic_right)
650 char oper = binary.oper->token[0];
653 /* Subscripting operates on vectors, matrices and arrays, and the right
654 operand must be an integer. */
655 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
658 resolve(binary, basic_left->base_type, binary.left->lvalue);
661 else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
662 // No other binary operator can be used with arrays.
665 BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
666 BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
667 if(!elem_left || !elem_right)
670 Compatibility compat = get_compatibility(*basic_left, *basic_right);
671 Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
672 if(elem_compat==NOT_COMPATIBLE)
674 if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
677 TypeDeclaration *type = 0;
678 char oper2 = binary.oper->token[1];
679 if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
681 /* Relational operators compare two scalar integer or floating-point
683 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
686 type = find_type(BasicTypeDeclaration::BOOL, 1);
688 else if((oper=='=' || oper=='!') && oper2=='=')
690 // Equality comparison can be done on any compatible types.
691 if(compat==NOT_COMPATIBLE)
694 type = find_type(BasicTypeDeclaration::BOOL, 1);
696 else if(oper2=='&' || oper2=='|' || oper2=='^')
698 // Logical operators can only be applied to booleans.
699 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
704 else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
706 // Bitwise operators and modulo can only be applied to integers.
707 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
710 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
712 else if((oper=='<' || oper=='>') && oper2==oper)
714 // Shifts apply to integer scalars and vectors, with some restrictions.
715 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
717 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
718 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
719 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
722 /* If the left operand is a vector and right is scalar, convert the right
723 operand to a vector too. */
724 if(left_size>1 && right_size==1)
726 BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
730 convert_to(binary.right, *vec_right);
734 // Don't perform conversion even if the operands are of different sizes.
737 else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
739 // Arithmetic operators require scalar elements.
740 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
743 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
744 (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
746 /* Multiplication has special rules when at least one operand is a
747 matrix and the other is a vector or a matrix. */
748 unsigned left_columns = basic_left->size&0xFFFF;
749 unsigned right_rows = basic_right->size;
750 if(basic_right->kind==BasicTypeDeclaration::MATRIX)
752 if(left_columns!=right_rows)
755 BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
757 if(basic_left->kind==BasicTypeDeclaration::VECTOR)
758 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
759 else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
760 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
762 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
764 else if(compat==NOT_COMPATIBLE)
766 // Arithmetic between scalars and matrices or vectors is supported.
767 if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
768 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
769 else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
770 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
774 else if(compat==LEFT_CONVERTIBLE)
782 if(assign && type!=basic_left)
785 bool converted = true;
786 if(compat==LEFT_CONVERTIBLE)
787 convert_to(binary.left, *basic_right);
788 else if(compat==RIGHT_CONVERTIBLE)
789 convert_to(binary.right, *basic_left);
790 else if(elem_compat==LEFT_CONVERTIBLE)
791 converted = convert_to_element(binary.left, *elem_right);
792 else if(elem_compat==RIGHT_CONVERTIBLE)
793 converted = convert_to_element(binary.right, *elem_left);
798 resolve(binary, type, assign);
801 void ExpressionResolver::visit(BinaryExpression &binary)
803 TraversingVisitor::visit(binary);
804 visit(binary, false);
807 void ExpressionResolver::visit(Assignment &assign)
809 TraversingVisitor::visit(assign);
811 if(assign.oper->token[0]!='=')
812 return visit(assign, true);
813 else if(assign.left->type!=assign.right->type)
815 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
816 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
817 if(!basic_left || !basic_right)
820 Compatibility compat = get_compatibility(*basic_left, *basic_right);
821 if(compat==RIGHT_CONVERTIBLE)
822 convert_to(assign.right, *basic_left);
823 else if(compat!=SAME_TYPE)
827 resolve(assign, assign.left->type, true);
830 void ExpressionResolver::visit(TernaryExpression &ternary)
832 TraversingVisitor::visit(ternary);
834 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
835 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
838 TypeDeclaration *type = 0;
839 if(ternary.true_expr->type==ternary.false_expr->type)
840 type = ternary.true_expr->type;
843 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
844 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
845 if(!basic_true || !basic_false)
848 Compatibility compat = get_compatibility(*basic_true, *basic_false);
849 if(compat==NOT_COMPATIBLE)
852 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
854 if(compat==LEFT_CONVERTIBLE)
855 convert_to(ternary.true_expr, *basic_false);
856 else if(compat==RIGHT_CONVERTIBLE)
857 convert_to(ternary.false_expr, *basic_true);
860 resolve(ternary, type, false);
863 void ExpressionResolver::visit_constructor(FunctionCall &call)
865 if(call.arguments.empty())
868 auto i = stage->types.find(call.name);
869 if(i==stage->types.end())
871 else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
873 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
875 BasicTypeDeclaration *elem = get_element_type(*basic);
879 vector<ArgumentInfo> args;
880 args.reserve(call.arguments.size());
881 unsigned arg_component_total = 0;
882 bool has_matrices = false;
883 for(const RefPtr<Expression> &a: call.arguments)
886 if(!(info.type=dynamic_cast<BasicTypeDeclaration *>(a->type)))
888 if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
889 info.component_count = 1;
890 else if(info.type->kind==BasicTypeDeclaration::VECTOR)
891 info.component_count = info.type->size;
892 else if(info.type->kind==BasicTypeDeclaration::MATRIX)
894 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
899 arg_component_total += info.component_count;
900 args.push_back(info);
903 bool convert_args = false;
904 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
906 if(arg_component_total>1)
907 truncate_vector(call.arguments.front(), 1);
909 /* Single-element type constructors never need to convert their
910 arguments because the constructor *is* the conversion. */
912 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
914 /* Vector constructors need either a single scalar argument or
915 enough components to fill out the vector. */
916 if(arg_component_total!=1 && arg_component_total<basic->size)
919 /* A vector of same size can be converted directly. For other
920 combinations the individual arguments need to be converted. */
921 if(call.arguments.size()==1)
923 if(arg_component_total==1)
925 else if(arg_component_total>basic->size)
926 truncate_vector(call.arguments.front(), basic->size);
928 else if(arg_component_total==basic->size)
933 else if(basic->kind==BasicTypeDeclaration::MATRIX)
935 unsigned column_count = basic->size&0xFFFF;
936 unsigned row_count = basic->size>>16;
938 vector<RefPtr<Expression> > columns;
939 columns.reserve(column_count);
940 bool changed_columns = false;
942 if(call.arguments.size()==1)
944 /* A matrix can be constructed from a single element or another
945 matrix of sufficient size. */
946 if(arg_component_total==1)
948 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
950 unsigned arg_columns = args.front().type->size&0xFFFF;
951 unsigned arg_rows = args.front().type->size>>16;
952 if(arg_columns<column_count || arg_rows<row_count)
955 /* Always generate a temporary here and let the optimization
956 stage inline it if that's reasonable. */
957 RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
958 temporary->type = args.front().type->name;
959 temporary->name = get_unused_variable_name(*current_block, "_temp");
960 temporary->init_expression = call.arguments.front();
961 current_block->body.insert(insert_point, temporary);
963 // Create expressions to build each column.
964 for(unsigned j=0; j<column_count; ++j)
966 RefPtr<VariableReference> ref = new VariableReference;
967 ref->name = temporary->name;
969 RefPtr<Literal> index = new Literal;
970 index->token = lexical_cast<string>(j);
971 index->value = static_cast<int>(j);
973 RefPtr<BinaryExpression> subscript = new BinaryExpression;
974 subscript->left = ref;
975 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
976 subscript->right = index;
977 subscript->type = args.front().type->base_type;
979 columns.push_back(subscript);
980 if(arg_rows>row_count)
981 truncate_vector(columns.back(), row_count);
984 changed_columns = true;
989 else if(arg_component_total==column_count*row_count && !has_matrices)
991 /* Construct a matrix from individual components in column-major
992 order. Arguments must align at column boundaries. */
993 vector<RefPtr<Expression> > column_args;
994 column_args.reserve(row_count);
995 unsigned column_component_count = 0;
997 for(unsigned j=0; j<call.arguments.size(); ++j)
999 const ArgumentInfo &info = args[j];
1000 if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
1001 // A vector filling the entire column can be used as is.
1002 columns.push_back(call.arguments[j]);
1005 column_args.push_back(call.arguments[j]);
1006 column_component_count += info.component_count;
1007 if(column_component_count==row_count)
1009 /* The column has filled up. Create a vector constructor
1011 RefPtr<FunctionCall> column_call = new FunctionCall;
1012 column_call->name = basic->base_type->name;
1013 column_call->constructor = true;
1014 column_call->arguments.resize(column_args.size());
1015 copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1016 column_call->type = basic->base_type;
1017 visit_constructor(*column_call);
1018 columns.push_back(column_call);
1020 column_args.clear();
1021 column_component_count = 0;
1023 else if(column_component_count>row_count)
1024 // Argument alignment mismatch.
1027 changed_columns = true;
1036 call.arguments.resize(column_count);
1037 copy(columns.begin(), columns.end(), call.arguments.begin());
1039 /* Let VariableResolver process the new nodes and finish
1040 resolving the constructor on the next pass. */
1041 r_any_resolved = true;
1050 // The argument list may have changed so can't rely on args.
1051 for(RefPtr<Expression> &a: call.arguments)
1052 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1054 BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1056 convert_to_element(a, *elem);
1060 else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1062 if(call.arguments.size()!=strct->members.body.size())
1065 auto j = call.arguments.begin();
1066 for(const RefPtr<Statement> &s: strct->members.body)
1068 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(s.get()))
1070 if(!(*j)->type || (*j)->type!=var->type_declaration)
1079 resolve(call, i->second, false);
1082 void ExpressionResolver::visit(FunctionCall &call)
1084 TraversingVisitor::visit(call);
1086 if(call.declaration)
1088 for(unsigned i=0; i<call.arguments.size(); ++i)
1090 TypeDeclaration *arg_type = call.arguments[i]->type;
1091 TypeDeclaration *param_type = call.declaration->parameters[i]->type_declaration;
1092 BasicTypeDeclaration *arg_basic = dynamic_cast<BasicTypeDeclaration *>(arg_type);
1093 BasicTypeDeclaration *param_basic = dynamic_cast<BasicTypeDeclaration *>(param_type);
1094 if(arg_basic && param_basic)
1096 Compatibility compat = get_compatibility(*param_basic, *arg_basic);
1097 if(compat==RIGHT_CONVERTIBLE)
1098 convert_to(call.arguments[i], *param_basic);
1100 else if(!arg_type || !param_type || arg_type!=param_type)
1103 resolve(call, call.declaration->return_type_declaration, false);
1105 else if(call.constructor)
1106 visit_constructor(call);
1109 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1111 basic_types.push_back(&type);
1114 void ExpressionResolver::visit(VariableDeclaration &var)
1116 TraversingVisitor::visit(var);
1117 if(!var.init_expression)
1120 BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1121 BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1122 if(!var_basic || !init_basic)
1125 Compatibility compat = get_compatibility(*var_basic, *init_basic);
1126 if(compat==RIGHT_CONVERTIBLE)
1127 convert_to(var.init_expression, *var_basic);
1130 void ExpressionResolver::visit(FunctionDeclaration &func)
1132 SetForScope<const FunctionDeclaration *> set_func(current_function, &func);
1133 TraversingVisitor::visit(func);
1136 void ExpressionResolver::visit(Return &ret)
1138 TraversingVisitor::visit(ret);
1139 if(!current_function || !ret.expression)
1142 BasicTypeDeclaration *ret_basic = dynamic_cast<BasicTypeDeclaration *>(current_function->return_type_declaration);
1143 BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(ret.expression->type);
1144 if(!ret_basic || !expr_basic)
1147 Compatibility compat = get_compatibility(*ret_basic, *expr_basic);
1148 if(compat==RIGHT_CONVERTIBLE)
1149 convert_to(ret.expression, *ret_basic);
1153 bool FunctionResolver::apply(Stage &s)
1156 s.functions.clear();
1157 r_any_resolved = false;
1158 s.content.visit(*this);
1159 return r_any_resolved;
1162 bool FunctionResolver::can_convert_arguments(const FunctionCall &call, const FunctionDeclaration &decl)
1164 if(decl.parameters.size()!=call.arguments.size())
1167 for(unsigned j=0; j<call.arguments.size(); ++j)
1169 const TypeDeclaration *arg_type = call.arguments[j]->type;
1170 const TypeDeclaration *param_type = decl.parameters[j]->type_declaration;
1171 if(arg_type==param_type)
1174 const BasicTypeDeclaration *arg_basic = dynamic_cast<const BasicTypeDeclaration *>(arg_type);
1175 const BasicTypeDeclaration *param_basic = dynamic_cast<const BasicTypeDeclaration *>(param_type);
1176 if(arg_basic && param_basic && can_convert(*arg_basic, *param_basic))
1185 void FunctionResolver::visit(FunctionCall &call)
1187 FunctionDeclaration *declaration = 0;
1188 if(stage->types.count(call.name))
1189 call.constructor = true;
1193 bool has_signature = true;
1194 for(auto i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1197 append(arg_types, ",", (*i)->type->name);
1199 has_signature = false;
1204 auto i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1205 declaration = (i!=stage->functions.end() ? i->second : 0);
1209 for(i=stage->functions.lower_bound(call.name+"("); (i!=stage->functions.end() && i->second->name==call.name); ++i)
1210 if(can_convert_arguments(call, *i->second))
1218 declaration = i->second;
1224 r_any_resolved |= (declaration!=call.declaration);
1225 call.declaration = declaration;
1227 TraversingVisitor::visit(call);
1230 void FunctionResolver::visit(FunctionDeclaration &func)
1232 if(func.signature.empty())
1235 for(const RefPtr<VariableDeclaration> &p: func.parameters)
1237 if(p->type_declaration)
1238 append(param_types, ",", p->type_declaration->name);
1242 func.signature = format("(%s)", param_types);
1243 r_any_resolved = true;
1246 string key = func.name+func.signature;
1247 FunctionDeclaration *&stage_decl = stage->functions[key];
1248 vector<FunctionDeclaration *> &decls = declarations[key];
1249 if(func.definition==&func)
1251 if(stage_decl && stage_decl->definition)
1254 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1255 format("Overriding function '%s' without the override keyword is deprecated", key)));
1256 if(!stage_decl->definition->virtua)
1257 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1258 format("Overriding function '%s' not declared as virtual is deprecated", key)));
1262 // Set all previous declarations to use this definition.
1263 for(FunctionDeclaration *f: decls)
1265 r_any_resolved |= (func.definition!=f->definition);
1266 f->definition = func.definition;
1267 f->body.body.clear();
1272 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1273 r_any_resolved |= (definition!=func.definition);
1274 func.definition = definition;
1279 decls.push_back(&func);
1281 TraversingVisitor::visit(func);