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