]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/generate.cpp
Check that the types of ternary branches exist before accessing them
[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 <msp/strings/utils.h>
6 #include "builtin.h"
7 #include "generate.h"
8
9 using namespace std;
10
11 namespace Msp {
12 namespace GL {
13 namespace SL {
14
15 ConstantSpecializer::ConstantSpecializer():
16         values(0)
17 { }
18
19 void ConstantSpecializer::apply(Stage &stage, const map<string, int> *v)
20 {
21         values = v;
22         stage.content.visit(*this);
23 }
24
25 void ConstantSpecializer::visit(VariableDeclaration &var)
26 {
27         bool specializable = false;
28         if(var.layout)
29         {
30                 vector<Layout::Qualifier> &qualifiers = var.layout->qualifiers;
31                 for(vector<Layout::Qualifier>::iterator i=qualifiers.begin(); i!=qualifiers.end(); ++i)
32                         if(i->name=="constant_id")
33                         {
34                                 specializable = true;
35                                 if(values)
36                                         qualifiers.erase(i);
37                                 else if(i->value==-1)
38                                         i->value = hash32(var.name)&0x7FFFFFFF;
39                                 break;
40                         }
41
42                 if(qualifiers.empty())
43                         var.layout = 0;
44         }
45
46         if(specializable && values)
47         {
48                 map<string, int>::const_iterator i = values->find(var.name);
49                 if(i!=values->end())
50                 {
51                         RefPtr<Literal> literal = new Literal;
52                         if(var.type=="bool")
53                         {
54                                 literal->token = (i->second ? "true" : "false");
55                                 literal->value = static_cast<bool>(i->second);
56                         }
57                         else if(var.type=="int")
58                         {
59                                 literal->token = lexical_cast<string>(i->second);
60                                 literal->value = i->second;
61                         }
62                         var.init_expression = literal;
63                 }
64         }
65 }
66
67
68 void BlockHierarchyResolver::enter(Block &block)
69 {
70         r_any_resolved |= (current_block!=block.parent);
71         block.parent = current_block;
72 }
73
74
75 TypeResolver::TypeResolver():
76         stage(0),
77         iface_block(0),
78         r_any_resolved(false)
79 { }
80
81 bool TypeResolver::apply(Stage &s)
82 {
83         stage = &s;
84         s.types.clear();
85         r_any_resolved = false;
86         s.content.visit(*this);
87         return r_any_resolved;
88 }
89
90 TypeDeclaration *TypeResolver::get_or_create_array_type(TypeDeclaration &type)
91 {
92         map<TypeDeclaration *, TypeDeclaration *>::iterator i = array_types.find(&type);
93         if(i!=array_types.end())
94                 return i->second;
95
96         BasicTypeDeclaration *array = new BasicTypeDeclaration;
97         array->source = BUILTIN_SOURCE;
98         array->name = type.name+"[]";
99         array->kind = BasicTypeDeclaration::ARRAY;
100         array->base = type.name;
101         array->base_type = &type;
102         stage->content.body.insert(type_insert_point, array);
103         array_types[&type] = array;
104         return array;
105 }
106
107 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array)
108 {
109         TypeDeclaration *resolved = 0;
110         map<string, TypeDeclaration *>::iterator i = stage->types.find(name);
111         if(i!=stage->types.end())
112         {
113                 map<TypeDeclaration *, TypeDeclaration *>::iterator j = alias_map.find(i->second);
114                 resolved = (j!=alias_map.end() ? j->second : i->second);
115         }
116
117         if(resolved && array)
118                 resolved = get_or_create_array_type(*resolved);
119
120         r_any_resolved |= (resolved!=type);
121         type=resolved;
122 }
123
124 void TypeResolver::visit(Block &block)
125 {
126         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
127         {
128                 if(!block.parent)
129                         type_insert_point = i;
130                 (*i)->visit(*this);
131         }
132 }
133
134 void TypeResolver::visit(BasicTypeDeclaration &type)
135 {
136         resolve_type(type.base_type, type.base, false);
137
138         if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
139                 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
140                         if(basic_base->kind==BasicTypeDeclaration::VECTOR)
141                         {
142                                 type.kind = BasicTypeDeclaration::MATRIX;
143                                 /* A matrix's base type is its column vector type.  This will put
144                                 the column vector's size, i.e. the matrix's row count, in the high
145                                 half of the size. */
146                                 type.size |= basic_base->size<<16;
147                         }
148
149         if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
150                 alias_map[&type] = type.base_type;
151         else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
152                 array_types[type.base_type] = &type;
153
154         stage->types.insert(make_pair(type.name, &type));
155 }
156
157 void TypeResolver::visit(ImageTypeDeclaration &type)
158 {
159         resolve_type(type.base_type, type.base, false);
160         stage->types.insert(make_pair(type.name, &type));
161 }
162
163 void TypeResolver::visit(StructDeclaration &strct)
164 {
165         stage->types.insert(make_pair(strct.name, &strct));
166         TraversingVisitor::visit(strct);
167 }
168
169 void TypeResolver::visit(VariableDeclaration &var)
170 {
171         resolve_type(var.type_declaration, var.type, var.array);
172         if(iface_block && var.interface==iface_block->interface)
173                 var.interface.clear();
174 }
175
176 void TypeResolver::visit(InterfaceBlock &iface)
177 {
178         if(iface.members)
179         {
180                 SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
181                 iface.members->visit(*this);
182
183                 StructDeclaration *strct = new StructDeclaration;
184                 strct->source = INTERNAL_SOURCE;
185                 strct->name = format("_%s_%s", iface.interface, iface.name);
186                 strct->members.body.splice(strct->members.body.begin(), iface.members->body);
187                 stage->content.body.insert(type_insert_point, strct);
188                 stage->types.insert(make_pair(strct->name, strct));
189
190                 iface.members = 0;
191                 strct->interface_block = &iface;
192                 iface.struct_declaration = strct;
193         }
194
195         TypeDeclaration *type = iface.struct_declaration;
196         if(type && iface.array)
197                 type = get_or_create_array_type(*type);
198         r_any_resolved = (type!=iface.type_declaration);
199         iface.type_declaration = type;
200 }
201
202 void TypeResolver::visit(FunctionDeclaration &func)
203 {
204         resolve_type(func.return_type_declaration, func.return_type, false);
205         TraversingVisitor::visit(func);
206 }
207
208
209 VariableResolver::VariableResolver():
210         stage(0),
211         r_any_resolved(false),
212         record_target(false),
213         r_self_referencing(false)
214 { }
215
216 bool VariableResolver::apply(Stage &s)
217 {
218         stage = &s;
219         s.interface_blocks.clear();
220         r_any_resolved = false;
221         s.content.visit(*this);
222         for(vector<VariableDeclaration *>::const_iterator i=redeclared_builtins.begin(); i!=redeclared_builtins.end(); ++i)
223                 (*i)->source = GENERATED_SOURCE;
224         NodeRemover().apply(s, nodes_to_remove);
225         return r_any_resolved;
226 }
227
228 void VariableResolver::enter(Block &block)
229 {
230         block.variables.clear();
231 }
232
233 void VariableResolver::visit(RefPtr<Expression> &expr)
234 {
235         r_replacement_expr = 0;
236         expr->visit(*this);
237         if(r_replacement_expr)
238         {
239                 expr = r_replacement_expr;
240                 /* Don't record assignment target when doing a replacement, because chain
241                 information won't be correct. */
242                 r_assignment_target.declaration = 0;
243                 r_any_resolved = true;
244         }
245         r_replacement_expr = 0;
246 }
247
248 void VariableResolver::check_assignment_target(Statement *declaration)
249 {
250         if(record_target)
251         {
252                 if(r_assignment_target.declaration)
253                 {
254                         /* More than one reference found in assignment target.  Unable to
255                         determine what the primary target is. */
256                         record_target = false;
257                         r_assignment_target.declaration = 0;
258                 }
259                 else
260                         r_assignment_target.declaration = declaration;
261         }
262         // TODO This check is overly broad and may prevent some optimizations.
263         else if(declaration && declaration==r_assignment_target.declaration)
264                 r_self_referencing = true;
265 }
266
267 void VariableResolver::visit(VariableReference &var)
268 {
269         VariableDeclaration *declaration = 0;
270
271         /* Look for variable declarations in the block hierarchy first.  Interface
272         blocks are always defined in the top level so we can't accidentally skip
273         one. */
274         for(Block *block=current_block; (!declaration && block); block=block->parent)
275         {
276                 map<string, VariableDeclaration *>::iterator i = block->variables.find(var.name);
277                 if(i!=block->variables.end())
278                         declaration = i->second;
279         }
280
281         if(!declaration)
282         {
283                 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
284                 map<string, InterfaceBlock *>::const_iterator i = blocks.find("_"+var.name);
285                 if(i!=blocks.end())
286                 {
287                         /* The name refers to an interface block with an instance name rather
288                         than a variable.  Prepare a new syntax tree node accordingly. */
289                         InterfaceBlockReference *iface_ref = new InterfaceBlockReference;
290                         iface_ref->source = var.source;
291                         iface_ref->line = var.line;
292                         iface_ref->name = var.name;
293                         iface_ref->declaration = i->second;
294                         r_replacement_expr = iface_ref;
295                 }
296                 else
297                 {
298                         // Look for the variable in anonymous interface blocks.
299                         for(i=blocks.begin(); (!declaration && i!=blocks.end()); ++i)
300                                 if(i->second->instance_name.empty() && i->second->struct_declaration)
301                                 {
302                                         const map<string, VariableDeclaration *> &iface_vars = i->second->struct_declaration->members.variables;
303                                         map<string, VariableDeclaration *>::const_iterator j = iface_vars.find(var.name);
304                                         if(j!=iface_vars.end())
305                                                 declaration = j->second;
306                                 }
307                 }
308         }
309
310         r_any_resolved |= (declaration!=var.declaration);
311         var.declaration = declaration;
312
313         check_assignment_target(var.declaration);
314 }
315
316 void VariableResolver::visit(InterfaceBlockReference &iface)
317 {
318         map<string, InterfaceBlock *>::iterator i = stage->interface_blocks.find("_"+iface.name);
319         InterfaceBlock *declaration = (i!=stage->interface_blocks.end() ? i->second : 0);
320         r_any_resolved |= (declaration!=iface.declaration);
321         iface.declaration = declaration;
322
323         check_assignment_target(iface.declaration);
324 }
325
326 void VariableResolver::add_to_chain(Assignment::Target::ChainType type, unsigned index)
327 {
328         if(r_assignment_target.chain_len<7)
329                 r_assignment_target.chain[r_assignment_target.chain_len] = type | min<unsigned>(index, 0x3F);
330         ++r_assignment_target.chain_len;
331 }
332
333 void VariableResolver::visit(MemberAccess &memacc)
334 {
335         TraversingVisitor::visit(memacc);
336
337         VariableDeclaration *declaration = 0;
338         if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
339         {
340                 map<string, VariableDeclaration *>::iterator i = strct->members.variables.find(memacc.member);
341                 if(i!=strct->members.variables.end())
342                 {
343                         declaration = i->second;
344
345                         if(record_target)
346                         {
347                                 unsigned index = 0;
348                                 for(NodeList<Statement>::const_iterator j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
349                                         ++index;
350
351                                 add_to_chain(Assignment::Target::MEMBER, index);
352                         }
353                 }
354         }
355         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
356         {
357                 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
358                 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
359                 if(scalar_swizzle || vector_swizzle)
360                 {
361                         static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
362
363                         bool ok = true;
364                         UInt8 components[4] = { };
365                         for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
366                                 ok = ((components[i] = (find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
367
368                         if(ok)
369                         {
370                                 Swizzle *swizzle = new Swizzle;
371                                 swizzle->source = memacc.source;
372                                 swizzle->line = memacc.line;
373                                 swizzle->oper = memacc.oper;
374                                 swizzle->left = memacc.left;
375                                 swizzle->component_group = memacc.member;
376                                 swizzle->count = memacc.member.size();
377                                 copy(components, components+memacc.member.size(), swizzle->components);
378                                 r_replacement_expr = swizzle;
379                         }
380                 }
381         }
382
383         r_any_resolved |= (declaration!=memacc.declaration);
384         memacc.declaration = declaration;
385 }
386
387 void VariableResolver::visit(Swizzle &swizzle)
388 {
389         TraversingVisitor::visit(swizzle);
390
391         if(record_target)
392         {
393                 unsigned mask = 0;
394                 for(unsigned i=0; i<swizzle.count; ++i)
395                         mask |= 1<<swizzle.components[i];
396                 add_to_chain(Assignment::Target::SWIZZLE, mask);
397         }
398 }
399
400 void VariableResolver::visit(BinaryExpression &binary)
401 {
402         if(binary.oper->token[0]=='[')
403         {
404                 {
405                         /* The subscript expression is not a part of the primary assignment
406                         target. */
407                         SetFlag set(record_target, false);
408                         visit(binary.right);
409                 }
410                 visit(binary.left);
411
412                 if(record_target)
413                 {
414                         unsigned index = 0x3F;
415                         if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
416                                 if(literal_subscript->value.check_type<int>())
417                                         index = literal_subscript->value.value<int>();
418                         add_to_chain(Assignment::Target::ARRAY, index);
419                 }
420         }
421         else
422                 TraversingVisitor::visit(binary);
423 }
424
425 void VariableResolver::visit(Assignment &assign)
426 {
427         {
428                 SetFlag set(record_target);
429                 r_assignment_target = Assignment::Target();
430                 visit(assign.left);
431                 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
432                 assign.target = r_assignment_target;
433         }
434
435         r_self_referencing = false;
436         visit(assign.right);
437         assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
438 }
439
440 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
441 {
442         for(vector<Layout::Qualifier>::const_iterator i=from_layout.qualifiers.begin(); i!=from_layout.qualifiers.end(); ++i)
443         {
444                 bool found = false;
445                 for(vector<Layout::Qualifier>::iterator j=to_layout.qualifiers.begin(); (!found && j!=to_layout.qualifiers.end()); ++j)
446                         if(j->name==i->name)
447                         {
448                                 j->has_value = i->value;
449                                 j->value = i->value;
450                                 found = true;
451                         }
452
453                 if(!found)
454                         to_layout.qualifiers.push_back(*i);
455         }
456 }
457
458 void VariableResolver::visit(VariableDeclaration &var)
459 {
460         TraversingVisitor::visit(var);
461         VariableDeclaration *&ptr = current_block->variables[var.name];
462         if(!ptr)
463                 ptr = &var;
464         else if(!current_block->parent && ptr->interface==var.interface && ptr->type==var.type)
465         {
466                 if(ptr->source==BUILTIN_SOURCE)
467                         redeclared_builtins.push_back(&var);
468                 else
469                         stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, var.source, var.line,
470                                 format("Redeclaring non-builtin variable '%s' is deprecated", var.name)));
471
472                 if(var.init_expression)
473                         ptr->init_expression = var.init_expression;
474                 if(var.layout)
475                 {
476                         if(ptr->layout)
477                                 merge_layouts(*ptr->layout, *var.layout);
478                         else
479                                 ptr->layout = var.layout;
480                 }
481                 nodes_to_remove.insert(&var);
482
483                 r_any_resolved = true;
484         }
485 }
486
487 void VariableResolver::visit(InterfaceBlock &iface)
488 {
489         /* Block names can be reused in different interfaces.  Prefix the name with
490         the first character of the interface to avoid conflicts. */
491         stage->interface_blocks.insert(make_pair(iface.interface+iface.name, &iface));
492         if(!iface.instance_name.empty())
493                 stage->interface_blocks.insert(make_pair("_"+iface.instance_name, &iface));
494
495         TraversingVisitor::visit(iface);
496 }
497
498
499 ExpressionResolver::ExpressionResolver():
500         stage(0),
501         r_any_resolved(false)
502 { }
503
504 bool ExpressionResolver::apply(Stage &s)
505 {
506         stage = &s;
507         r_any_resolved = false;
508         s.content.visit(*this);
509         return r_any_resolved;
510 }
511
512 bool ExpressionResolver::is_scalar(BasicTypeDeclaration &type)
513 {
514         return (type.kind==BasicTypeDeclaration::INT || type.kind==BasicTypeDeclaration::FLOAT);
515 }
516
517 bool ExpressionResolver::is_vector_or_matrix(BasicTypeDeclaration &type)
518 {
519         return (type.kind==BasicTypeDeclaration::VECTOR || type.kind==BasicTypeDeclaration::MATRIX);
520 }
521
522 BasicTypeDeclaration *ExpressionResolver::get_element_type(BasicTypeDeclaration &type)
523 {
524         if(is_vector_or_matrix(type) || type.kind==BasicTypeDeclaration::ARRAY)
525         {
526                 BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type);
527                 return (basic_base ? get_element_type(*basic_base) : 0);
528         }
529         else
530                 return &type;
531 }
532
533 bool ExpressionResolver::can_convert(BasicTypeDeclaration &from, BasicTypeDeclaration &to)
534 {
535         if(from.kind==BasicTypeDeclaration::INT && to.kind==BasicTypeDeclaration::FLOAT)
536                 return from.size<=to.size;
537         else if(from.kind!=to.kind)
538                 return false;
539         else if((from.kind==BasicTypeDeclaration::VECTOR || from.kind==BasicTypeDeclaration::MATRIX) && from.size==to.size)
540         {
541                 BasicTypeDeclaration *from_base = dynamic_cast<BasicTypeDeclaration *>(from.base_type);
542                 BasicTypeDeclaration *to_base = dynamic_cast<BasicTypeDeclaration *>(to.base_type);
543                 return (from_base && to_base && can_convert(*from_base, *to_base));
544         }
545         else
546                 return false;
547 }
548
549 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
550 {
551         if(&left==&right)
552                 return SAME_TYPE;
553         else if(can_convert(left, right))
554                 return LEFT_CONVERTIBLE;
555         else if(can_convert(right, left))
556                 return RIGHT_CONVERTIBLE;
557         else
558                 return NOT_COMPATIBLE;
559 }
560
561 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size)
562 {
563         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
564                 if((*i)->kind==kind && (*i)->size==size)
565                         return *i;
566         return 0;
567 }
568
569 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
570 {
571         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
572                 if(get_element_type(**i)==&elem_type && (*i)->kind==kind && (*i)->size==size)
573                         return *i;
574         return 0;
575 }
576
577 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
578 {
579         RefPtr<FunctionCall> call = new FunctionCall;
580         call->name = type.name;
581         call->constructor = true;
582         call->arguments.push_back(0);
583         call->arguments.back() = expr;
584         call->type = &type;
585         expr = call;
586 }
587
588 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
589 {
590         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
591         {
592                 BasicTypeDeclaration *to_type = &elem_type;
593                 if(is_vector_or_matrix(*expr_basic))
594                         to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
595                 if(to_type)
596                 {
597                         convert_to(expr, *to_type);
598                         return true;
599                 }
600         }
601
602         return false;
603 }
604
605 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
606 {
607         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
608                 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
609                 {
610                         RefPtr<Swizzle> swizzle = new Swizzle;
611                         swizzle->left = expr;
612                         swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
613                         swizzle->component_group = string("xyzw", size);
614                         swizzle->count = size;
615                         for(unsigned i=0; i<size; ++i)
616                                 swizzle->components[i] = i;
617                         if(size==1)
618                                 swizzle->type = expr_elem;
619                         else
620                                 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
621                         expr = swizzle;
622
623                         return true;
624                 }
625
626         return false;
627 }
628
629 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
630 {
631         r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
632         expr.type = type;
633         expr.lvalue = lvalue;
634 }
635
636 void ExpressionResolver::visit(Block &block)
637 {
638         SetForScope<Block *> set_block(current_block, &block);
639         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
640         {
641                 insert_point = i;
642                 (*i)->visit(*this);
643         }
644 }
645
646 void ExpressionResolver::visit(Literal &literal)
647 {
648         if(literal.value.check_type<bool>())
649                 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
650         else if(literal.value.check_type<int>())
651                 resolve(literal, find_type(BasicTypeDeclaration::INT, 32), false);
652         else if(literal.value.check_type<float>())
653                 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
654 }
655
656 void ExpressionResolver::visit(VariableReference &var)
657 {
658         if(var.declaration)
659                 resolve(var, var.declaration->type_declaration, true);
660 }
661
662 void ExpressionResolver::visit(InterfaceBlockReference &iface)
663 {
664         if(iface.declaration)
665                 resolve(iface, iface.declaration->type_declaration, true);
666 }
667
668 void ExpressionResolver::visit(MemberAccess &memacc)
669 {
670         TraversingVisitor::visit(memacc);
671
672         if(memacc.declaration)
673                 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
674 }
675
676 void ExpressionResolver::visit(Swizzle &swizzle)
677 {
678         TraversingVisitor::visit(swizzle);
679
680         if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
681         {
682                 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
683                 if(swizzle.count==1)
684                         resolve(swizzle, left_elem, swizzle.left->lvalue);
685                 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
686                         resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
687         }
688 }
689
690 void ExpressionResolver::visit(UnaryExpression &unary)
691 {
692         TraversingVisitor::visit(unary);
693
694         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
695         if(!basic)
696                 return;
697
698         char oper = unary.oper->token[0];
699         if(oper=='!')
700         {
701                 if(basic->kind!=BasicTypeDeclaration::BOOL)
702                         return;
703         }
704         else if(oper=='~')
705         {
706                 if(basic->kind!=BasicTypeDeclaration::INT)
707                         return;
708         }
709         else if(oper=='+' || oper=='-')
710         {
711                 BasicTypeDeclaration *elem = get_element_type(*basic);
712                 if(!elem || !is_scalar(*elem))
713                         return;
714         }
715         resolve(unary, basic, unary.expression->lvalue);
716 }
717
718 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
719 {
720         /* Binary operators are only defined for basic types (not for image or
721         structure types). */
722         BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
723         BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
724         if(!basic_left || !basic_right)
725                 return;
726
727         char oper = binary.oper->token[0];
728         if(oper=='[')
729         {
730                 /* Subscripting operates on vectors, matrices and arrays, and the right
731                 operand must be an integer. */
732                 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
733                         return;
734
735                 resolve(binary, basic_left->base_type, binary.left->lvalue);
736                 return;
737         }
738         else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
739                 // No other binary operator can be used with arrays.
740                 return;
741
742         BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
743         BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
744         if(!elem_left || !elem_right)
745                 return;
746
747         Compatibility compat = get_compatibility(*basic_left, *basic_right);
748         Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
749         if(elem_compat==NOT_COMPATIBLE)
750                 return;
751         if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
752                 return;
753
754         TypeDeclaration *type = 0;
755         char oper2 = binary.oper->token[1];
756         if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
757         {
758                 /* Relational operators compare two scalar integer or floating-point
759                 values. */
760                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
761                         return;
762
763                 type = find_type(BasicTypeDeclaration::BOOL, 1);
764         }
765         else if((oper=='=' || oper=='!') && oper2=='=')
766         {
767                 // Equality comparison can be done on any compatible types.
768                 if(compat==NOT_COMPATIBLE)
769                         return;
770
771                 type = find_type(BasicTypeDeclaration::BOOL, 1);
772         }
773         else if(oper2=='&' || oper2=='|' || oper2=='^')
774         {
775                 // Logical operators can only be applied to booleans.
776                 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
777                         return;
778
779                 type = basic_left;
780         }
781         else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
782         {
783                 // Bitwise operators and modulo can only be applied to integers.
784                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
785                         return;
786
787                 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
788         }
789         else if((oper=='<' || oper=='>') && oper2==oper)
790         {
791                 // Shifts apply to integer scalars and vectors, with some restrictions.
792                 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
793                         return;
794                 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
795                 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
796                 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
797                         return;
798
799                 type = basic_left;
800                 // Don't perform conversion even if the operands are of different sizes.
801                 compat = SAME_TYPE;
802         }
803         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
804         {
805                 // Arithmetic operators require scalar elements.
806                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
807                         return;
808
809                 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
810                         (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
811                 {
812                         /* Multiplication has special rules when at least one operand is a
813                         matrix and the other is a vector or a matrix. */
814                         unsigned left_columns = basic_left->size&0xFFFF;
815                         unsigned right_rows = basic_right->size;
816                         if(basic_right->kind==BasicTypeDeclaration::MATRIX)
817                                 right_rows >>= 16;
818                         if(left_columns!=right_rows)
819                                 return;
820
821                         BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
822
823                         if(basic_left->kind==BasicTypeDeclaration::VECTOR)
824                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
825                         else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
826                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
827                         else
828                                 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
829                 }
830                 else if(compat==NOT_COMPATIBLE)
831                 {
832                         // Arithmetic between scalars and matrices or vectors is supported.
833                         if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
834                                 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
835                         else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
836                                 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
837                         else
838                                 return;
839                 }
840                 else if(compat==LEFT_CONVERTIBLE)
841                         type = basic_right;
842                 else
843                         type = basic_left;
844         }
845         else
846                 return;
847
848         if(assign && type!=basic_left)
849                 return;
850
851         bool converted = true;
852         if(compat==LEFT_CONVERTIBLE)
853                 convert_to(binary.left, *basic_right);
854         else if(compat==RIGHT_CONVERTIBLE)
855                 convert_to(binary.right, *basic_left);
856         else if(elem_compat==LEFT_CONVERTIBLE)
857                 converted = convert_to_element(binary.left, *elem_right);
858         else if(elem_compat==RIGHT_CONVERTIBLE)
859                 converted = convert_to_element(binary.right, *elem_left);
860
861         if(!converted)
862                 type = 0;
863
864         resolve(binary, type, assign);
865 }
866
867 void ExpressionResolver::visit(BinaryExpression &binary)
868 {
869         TraversingVisitor::visit(binary);
870         visit(binary, false);
871 }
872
873 void ExpressionResolver::visit(Assignment &assign)
874 {
875         TraversingVisitor::visit(assign);
876
877         if(assign.oper->token[0]!='=')
878                 return visit(assign, true);
879         else if(assign.left->type!=assign.right->type)
880         {
881                 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
882                 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
883                 if(!basic_left || !basic_right)
884                         return;
885
886                 Compatibility compat = get_compatibility(*basic_left, *basic_right);
887                 if(compat==RIGHT_CONVERTIBLE)
888                         convert_to(assign.right, *basic_left);
889                 else if(compat!=SAME_TYPE)
890                         return;
891         }
892
893         resolve(assign, assign.left->type, true);
894 }
895
896 void ExpressionResolver::visit(TernaryExpression &ternary)
897 {
898         TraversingVisitor::visit(ternary);
899
900         BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
901         if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
902                 return;
903
904         TypeDeclaration *type = 0;
905         if(ternary.true_expr->type==ternary.false_expr->type)
906                 type = ternary.true_expr->type;
907         else
908         {
909                 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
910                 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
911                 if(!basic_true || !basic_false)
912                         return;
913
914                 Compatibility compat = get_compatibility(*basic_true, *basic_false);
915                 if(compat==NOT_COMPATIBLE)
916                         return;
917
918                 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
919
920                 if(compat==LEFT_CONVERTIBLE)
921                         convert_to(ternary.true_expr, *basic_false);
922                 else if(compat==RIGHT_CONVERTIBLE)
923                         convert_to(ternary.false_expr, *basic_true);
924         }
925
926         resolve(ternary, type, false);
927 }
928
929 void ExpressionResolver::visit_constructor(FunctionCall &call)
930 {
931         if(call.arguments.empty())
932                 return;
933
934         map<string, TypeDeclaration *>::const_iterator i = stage->types.find(call.name);
935         if(i==stage->types.end())
936                 return;
937         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
938         {
939                 BasicTypeDeclaration *elem = get_element_type(*basic);
940                 if(!elem)
941                         return;
942
943                 vector<ArgumentInfo> args;
944                 args.reserve(call.arguments.size());
945                 unsigned arg_component_total = 0;
946                 bool has_matrices = false;
947                 for(NodeArray<Expression>::const_iterator j=call.arguments.begin(); j!=call.arguments.end(); ++j)
948                 {
949                         ArgumentInfo info;
950                         if(!(info.type=dynamic_cast<BasicTypeDeclaration *>((*j)->type)))
951                                 return;
952                         if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
953                                 info.component_count = 1;
954                         else if(info.type->kind==BasicTypeDeclaration::VECTOR)
955                                 info.component_count = info.type->size;
956                         else if(info.type->kind==BasicTypeDeclaration::MATRIX)
957                         {
958                                 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
959                                 has_matrices = true;
960                         }
961                         else
962                                 return;
963                         arg_component_total += info.component_count;
964                         args.push_back(info);
965                 }
966
967                 bool convert_args = false;
968                 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
969                 {
970                         if(arg_component_total>1)
971                                 truncate_vector(call.arguments.front(), 1);
972
973                         /* Single-element type constructors never need to convert their
974                         arguments because the constructor *is* the conversion. */
975                 }
976                 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
977                 {
978                         /* Vector constructors need either a single scalar argument or
979                         enough components to fill out the vector. */
980                         if(arg_component_total!=1 && arg_component_total<basic->size)
981                                 return;
982
983                         /* A vector of same size can be converted directly.  For other
984                         combinations the individual arguments need to be converted. */
985                         if(call.arguments.size()==1)
986                         {
987                                 if(arg_component_total==1)
988                                         convert_args = true;
989                                 else if(arg_component_total>basic->size)
990                                         truncate_vector(call.arguments.front(), basic->size);
991                         }
992                         else if(arg_component_total==basic->size)
993                                 convert_args = true;
994                         else
995                                 return;
996                 }
997                 else if(basic->kind==BasicTypeDeclaration::MATRIX)
998                 {
999                         unsigned column_count = basic->size&0xFFFF;
1000                         unsigned row_count = basic->size>>16;
1001                         if(call.arguments.size()==1)
1002                         {
1003                                 /* A matrix can be constructed from a single element or another
1004                                 matrix of sufficient size. */
1005                                 if(arg_component_total==1)
1006                                         convert_args = true;
1007                                 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
1008                                 {
1009                                         unsigned arg_columns = args.front().type->size&0xFFFF;
1010                                         unsigned arg_rows = args.front().type->size>>16;
1011                                         if(arg_columns<column_count || arg_rows<row_count)
1012                                                 return;
1013
1014                                         /* Always generate a temporary here and let the optimization
1015                                         stage inline it if that's reasonable. */
1016                                         RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
1017                                         temporary->type = args.front().type->name;
1018                                         temporary->name = get_unused_variable_name(*current_block, "_temp", string());
1019                                         temporary->init_expression = call.arguments.front();
1020                                         current_block->body.insert(insert_point, temporary);
1021
1022                                         // Create expressions to build each column.
1023                                         vector<RefPtr<Expression> > columns;
1024                                         columns.reserve(column_count);
1025                                         for(unsigned j=0; j<column_count; ++j)
1026                                         {
1027                                                 RefPtr<VariableReference> ref = new VariableReference;
1028                                                 ref->name = temporary->name;
1029
1030                                                 RefPtr<Literal> index = new Literal;
1031                                                 index->token = lexical_cast<string>(j);
1032                                                 index->value = static_cast<int>(j);
1033
1034                                                 RefPtr<BinaryExpression> subscript = new BinaryExpression;
1035                                                 subscript->left = ref;
1036                                                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1037                                                 subscript->right = index;
1038                                                 subscript->type = args.front().type->base_type;
1039
1040                                                 columns.push_back(subscript);
1041                                                 if(arg_rows>row_count)
1042                                                         truncate_vector(columns.back(), row_count);
1043                                         }
1044
1045                                         call.arguments.resize(column_count);
1046                                         copy(columns.begin(), columns.end(), call.arguments.begin());
1047
1048                                         /* Let VariableResolver process the new nodes and finish
1049                                         resolving the constructor on the next pass. */
1050                                         r_any_resolved = true;
1051                                         return;
1052                                 }
1053                                 else
1054                                         return;
1055                         }
1056                         else if(arg_component_total==column_count*row_count && !has_matrices)
1057                         {
1058                                 /* Construct a matrix from individual components in column-major
1059                                 order.  Arguments must align at column boundaries. */
1060                                 vector<RefPtr<Expression> > columns;
1061                                 columns.reserve(column_count);
1062
1063                                 vector<RefPtr<Expression> > column_args;
1064                                 column_args.reserve(row_count);
1065                                 unsigned column_component_count = 0;
1066
1067                                 for(unsigned j=0; j<call.arguments.size(); ++j)
1068                                 {
1069                                         const ArgumentInfo &info = args[j];
1070                                         if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
1071                                                 // A vector filling the entire column can be used as is.
1072                                                 columns.push_back(call.arguments[j]);
1073                                         else
1074                                         {
1075                                                 column_args.push_back(call.arguments[j]);
1076                                                 column_component_count += info.component_count;
1077                                                 if(column_component_count==row_count)
1078                                                 {
1079                                                         /* The column has filled up.  Create a vector constructor
1080                                                         for it.*/
1081                                                         RefPtr<FunctionCall> column_call = new FunctionCall;
1082                                                         column_call->name = basic->base_type->name;
1083                                                         column_call->constructor = true;
1084                                                         column_call->arguments.resize(column_args.size());
1085                                                         copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1086                                                         column_call->type = basic->base_type;
1087                                                         visit_constructor(*column_call);
1088                                                         columns.push_back(column_call);
1089
1090                                                         column_args.clear();
1091                                                         column_component_count = 0;
1092                                                 }
1093                                                 else if(column_component_count>row_count)
1094                                                         // Argument alignment mismatch.
1095                                                         return;
1096                                         }
1097                                 }
1098                         }
1099                         else
1100                                 return;
1101                 }
1102                 else
1103                         return;
1104
1105                 if(convert_args)
1106                 {
1107                         // The argument list may have changed so can't rely on args.
1108                         for(NodeArray<Expression>::iterator j=call.arguments.begin(); j!=call.arguments.end(); ++j)
1109                                 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>((*j)->type))
1110                                 {
1111                                         BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1112                                         if(elem_arg!=elem)
1113                                                 convert_to_element(*j, *elem);
1114                                 }
1115                 }
1116         }
1117         else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1118         {
1119                 if(call.arguments.size()!=strct->members.body.size())
1120                         return;
1121
1122                 unsigned k = 0;
1123                 for(NodeList<Statement>::const_iterator j=strct->members.body.begin(); j!=strct->members.body.end(); ++j, ++k)
1124                 {
1125                         if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(j->get()))
1126                         {
1127                                 if(!call.arguments[k]->type || call.arguments[k]->type!=var->type_declaration)
1128                                         return;
1129                         }
1130                         else
1131                                 return;
1132                 }
1133         }
1134
1135         resolve(call, i->second, false);
1136 }
1137
1138 void ExpressionResolver::visit(FunctionCall &call)
1139 {
1140         TraversingVisitor::visit(call);
1141
1142         if(call.declaration)
1143                 resolve(call, call.declaration->return_type_declaration, false);
1144         else if(call.constructor)
1145                 visit_constructor(call);
1146 }
1147
1148 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1149 {
1150         basic_types.push_back(&type);
1151 }
1152
1153 void ExpressionResolver::visit(VariableDeclaration &var)
1154 {
1155         TraversingVisitor::visit(var);
1156         if(!var.init_expression)
1157                 return;
1158
1159         BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1160         BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1161         if(!var_basic || !init_basic)
1162                 return;
1163
1164         Compatibility compat = get_compatibility(*var_basic, *init_basic);
1165         if(compat==RIGHT_CONVERTIBLE)
1166                 convert_to(var.init_expression, *var_basic);
1167 }
1168
1169
1170 bool FunctionResolver::apply(Stage &s)
1171 {
1172         stage = &s;
1173         s.functions.clear();
1174         r_any_resolved = false;
1175         s.content.visit(*this);
1176         return r_any_resolved;
1177 }
1178
1179 void FunctionResolver::visit(FunctionCall &call)
1180 {
1181         FunctionDeclaration *declaration = 0;
1182         if(stage->types.count(call.name))
1183                 call.constructor = true;
1184         else
1185         {
1186                 string arg_types;
1187                 bool has_signature = true;
1188                 for(NodeArray<Expression>::const_iterator i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1189                 {
1190                         if((*i)->type)
1191                                 append(arg_types, ",", (*i)->type->name);
1192                         else
1193                                 has_signature = false;
1194                 }
1195
1196                 if(has_signature)
1197                 {
1198                         map<string, FunctionDeclaration *>::iterator i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1199                         declaration = (i!=stage->functions.end() ? i->second : 0);
1200                 }
1201         }
1202
1203         r_any_resolved |= (declaration!=call.declaration);
1204         call.declaration = declaration;
1205
1206         TraversingVisitor::visit(call);
1207 }
1208
1209 void FunctionResolver::visit(FunctionDeclaration &func)
1210 {
1211         if(func.signature.empty())
1212         {
1213                 string param_types;
1214                 for(NodeArray<VariableDeclaration>::const_iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
1215                 {
1216                         if((*i)->type_declaration)
1217                                 append(param_types, ",", (*i)->type_declaration->name);
1218                         else
1219                                 return;
1220                 }
1221                 func.signature = format("(%s)", param_types);
1222                 r_any_resolved = true;
1223         }
1224
1225         string key = func.name+func.signature;
1226         FunctionDeclaration *&stage_decl = stage->functions[key];
1227         vector<FunctionDeclaration *> &decls = declarations[key];
1228         if(func.definition==&func)
1229         {
1230                 if(stage_decl && stage_decl->definition)
1231                 {
1232                         if(!func.overrd)
1233                                 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1234                                         format("Overriding function '%s' without the override keyword is deprecated", key)));
1235                         if(!stage_decl->definition->virtua)
1236                                 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1237                                         format("Overriding function '%s' not declared as virtual is deprecated", key)));
1238                 }
1239                 stage_decl = &func;
1240
1241                 // Set all previous declarations to use this definition.
1242                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
1243                 {
1244                         r_any_resolved |= (func.definition!=(*i)->definition);
1245                         (*i)->definition = func.definition;
1246                         (*i)->body.body.clear();
1247                 }
1248         }
1249         else
1250         {
1251                 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1252                 r_any_resolved |= (definition!=func.definition);
1253                 func.definition = definition;
1254
1255                 if(!stage_decl)
1256                         stage_decl = &func;
1257         }
1258         decls.push_back(&func);
1259
1260         TraversingVisitor::visit(func);
1261 }
1262
1263
1264 InterfaceGenerator::InterfaceGenerator():
1265         stage(0),
1266         function_scope(false),
1267         copy_block(false),
1268         iface_target_block(0)
1269 { }
1270
1271 string InterfaceGenerator::get_out_prefix(Stage::Type type)
1272 {
1273         if(type==Stage::VERTEX)
1274                 return "_vs_out_";
1275         else if(type==Stage::GEOMETRY)
1276                 return "_gs_out_";
1277         else
1278                 return string();
1279 }
1280
1281 void InterfaceGenerator::apply(Stage &s)
1282 {
1283         stage = &s;
1284         iface_target_block = &stage->content;
1285         if(stage->previous)
1286                 in_prefix = get_out_prefix(stage->previous->type);
1287         out_prefix = get_out_prefix(stage->type);
1288         s.content.visit(*this);
1289         NodeRemover().apply(s, nodes_to_remove);
1290 }
1291
1292 void InterfaceGenerator::visit(Block &block)
1293 {
1294         SetForScope<Block *> set_block(current_block, &block);
1295         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
1296         {
1297                 assignment_insert_point = i;
1298                 if(&block==&stage->content)
1299                         iface_insert_point = i;
1300
1301                 (*i)->visit(*this);
1302         }
1303 }
1304
1305 string InterfaceGenerator::change_prefix(const string &name, const string &prefix) const
1306 {
1307         unsigned offset = (name.compare(0, in_prefix.size(), in_prefix) ? 0 : in_prefix.size());
1308         return prefix+name.substr(offset);
1309 }
1310
1311 VariableDeclaration *InterfaceGenerator::generate_interface(VariableDeclaration &var, const string &iface, const string &name)
1312 {
1313         if(stage->content.variables.count(name))
1314                 return 0;
1315
1316         if(stage->type==Stage::GEOMETRY && !copy_block && var.interface=="out" && var.array)
1317                 return 0;
1318
1319         VariableDeclaration* iface_var = new VariableDeclaration;
1320         iface_var->sampling = var.sampling;
1321         iface_var->interface = iface;
1322         iface_var->type = var.type;
1323         iface_var->name = name;
1324         /* Geometry shader inputs are always arrays.  But if we're bringing in an
1325         entire block, the array is on the block and not individual variables. */
1326         if(stage->type==Stage::GEOMETRY && !copy_block)
1327                 iface_var->array = ((var.array && var.interface!="in") || iface=="in");
1328         else
1329                 iface_var->array = var.array;
1330         if(iface_var->array)
1331                 iface_var->array_size = var.array_size;
1332         if(iface=="in")
1333         {
1334                 iface_var->layout = var.layout;
1335                 iface_var->linked_declaration = &var;
1336                 var.linked_declaration = iface_var;
1337         }
1338
1339         iface_target_block->body.insert(iface_insert_point, iface_var);
1340         iface_target_block->variables.insert(make_pair(name, iface_var));
1341         if(iface_target_block==&stage->content && iface=="in")
1342                 declared_inputs.push_back(iface_var);
1343
1344         return iface_var;
1345 }
1346
1347 InterfaceBlock *InterfaceGenerator::generate_interface(InterfaceBlock &out_block)
1348 {
1349         if(stage->interface_blocks.count("in"+out_block.name))
1350                 return 0;
1351
1352         InterfaceBlock *in_block = new InterfaceBlock;
1353         in_block->interface = "in";
1354         in_block->name = out_block.name;
1355         in_block->members = new Block;
1356         in_block->instance_name = out_block.instance_name;
1357         if(stage->type==Stage::GEOMETRY)
1358                 in_block->array = true;
1359         else
1360                 in_block->array = out_block.array;
1361         in_block->linked_block = &out_block;
1362         out_block.linked_block = in_block;
1363
1364         {
1365                 SetFlag set_copy(copy_block, true);
1366                 SetForScope<Block *> set_target(iface_target_block, in_block->members.get());
1367                 SetForScope<NodeList<Statement>::iterator> set_ins_pt(iface_insert_point, in_block->members->body.end());
1368                 if(out_block.struct_declaration)
1369                         out_block.struct_declaration->members.visit(*this);
1370                 else if(out_block.members)
1371                         out_block.members->visit(*this);
1372         }
1373
1374         iface_target_block->body.insert(iface_insert_point, in_block);
1375         stage->interface_blocks.insert(make_pair("in"+in_block->name, in_block));
1376         if(!in_block->instance_name.empty())
1377                 stage->interface_blocks.insert(make_pair("_"+in_block->instance_name, in_block));
1378
1379         SetFlag set_scope(function_scope, false);
1380         SetForScope<Block *> set_block(current_block, &stage->content);
1381         in_block->visit(*this);
1382
1383         return in_block;
1384 }
1385
1386 ExpressionStatement &InterfaceGenerator::insert_assignment(const string &left, Expression *right)
1387 {
1388         Assignment *assign = new Assignment;
1389         VariableReference *ref = new VariableReference;
1390         ref->name = left;
1391         assign->left = ref;
1392         assign->oper = &Operator::get_operator("=", Operator::BINARY);
1393         assign->right = right;
1394
1395         ExpressionStatement *stmt = new ExpressionStatement;
1396         stmt->expression = assign;
1397         current_block->body.insert(assignment_insert_point, stmt);
1398         stmt->visit(*this);
1399
1400         return *stmt;
1401 }
1402
1403 void InterfaceGenerator::visit(VariableReference &var)
1404 {
1405         if(var.declaration || !stage->previous)
1406                 return;
1407         /* Don't pull a variable from previous stage if we just generated an output
1408         interface in this stage */
1409         if(stage->content.variables.count(var.name))
1410                 return;
1411
1412         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1413         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
1414         if(i==prev_vars.end() || i->second->interface!="out")
1415                 i = prev_vars.find(in_prefix+var.name);
1416         if(i!=prev_vars.end() && i->second->interface=="out")
1417         {
1418                 if(stage->type==Stage::GEOMETRY && i->second->array)
1419                         stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, var.source, var.line,
1420                                 format("Can't access '%s' through automatic interface because it's an array", var.name)));
1421                 else
1422                 {
1423                         generate_interface(*i->second, "in", i->second->name);
1424                         var.name = i->second->name;
1425                 }
1426                 return;
1427         }
1428
1429         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
1430         map<string, InterfaceBlock *>::const_iterator j = prev_blocks.find("_"+var.name);
1431         if(j!=prev_blocks.end() && j->second->interface=="out")
1432         {
1433                 generate_interface(*j->second);
1434                 /* Let VariableResolver convert the variable reference into an interface
1435                 block reference. */
1436                 return;
1437         }
1438
1439         for(j=prev_blocks.begin(); j!=prev_blocks.end(); ++j)
1440                 if(j->second->instance_name.empty() && j->second->struct_declaration)
1441                 {
1442                         const map<string, VariableDeclaration *> &iface_vars = j->second->struct_declaration->members.variables;
1443                         i = iface_vars.find(var.name);
1444                         if(i!=iface_vars.end())
1445                         {
1446                                 generate_interface(*j->second);
1447                                 return;
1448                         }
1449                 }
1450 }
1451
1452 void InterfaceGenerator::visit(VariableDeclaration &var)
1453 {
1454         if(copy_block)
1455                 generate_interface(var, "in", var.name);
1456         else if(var.interface=="out")
1457         {
1458                 /* For output variables in function scope, generate a global interface
1459                 and replace the local declaration with an assignment. */
1460                 VariableDeclaration *out_var = 0;
1461                 if(function_scope && (out_var=generate_interface(var, "out", var.name)))
1462                 {
1463                         out_var->source = var.source;
1464                         out_var->line = var.line;
1465                         nodes_to_remove.insert(&var);
1466                         if(var.init_expression)
1467                         {
1468                                 ExpressionStatement &stmt = insert_assignment(var.name, var.init_expression->clone());
1469                                 stmt.source = var.source;
1470                                 stmt.line = var.line;
1471                                 return;
1472                         }
1473                 }
1474         }
1475         else if(var.interface=="in" && current_block==&stage->content)
1476         {
1477                 if(var.name.compare(0, 3, "gl_"))
1478                         declared_inputs.push_back(&var);
1479
1480                 /* Try to link input variables in global scope with output variables from
1481                 previous stage. */
1482                 if(!var.linked_declaration && stage->previous)
1483                 {
1484                         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1485                         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
1486                         if(i!=prev_vars.end() && i->second->interface=="out")
1487                         {
1488                                 var.linked_declaration = i->second;
1489                                 i->second->linked_declaration = &var;
1490                         }
1491                 }
1492         }
1493
1494         TraversingVisitor::visit(var);
1495 }
1496
1497 void InterfaceGenerator::visit(InterfaceBlock &iface)
1498 {
1499         if(iface.interface=="in")
1500         {
1501                 /* Try to link input blocks with output blocks sharing the same block
1502                 name from previous stage. */
1503                 if(!iface.linked_block && stage->previous)
1504                 {
1505                         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
1506                         map<string, InterfaceBlock *>::const_iterator i = prev_blocks.find("out"+iface.name);
1507                         if(i!=prev_blocks.end())
1508                         {
1509                                 iface.linked_block = i->second;
1510                                 i->second->linked_block = &iface;
1511                         }
1512                 }
1513         }
1514
1515         TraversingVisitor::visit(iface);
1516 }
1517
1518 void InterfaceGenerator::visit(FunctionDeclaration &func)
1519 {
1520         SetFlag set_scope(function_scope, true);
1521         // Skip parameters because they're not useful here
1522         func.body.visit(*this);
1523 }
1524
1525 void InterfaceGenerator::visit(Passthrough &pass)
1526 {
1527         // Pass through all input variables declared so far.
1528         vector<VariableDeclaration *> pass_vars = declared_inputs;
1529
1530         if(stage->previous)
1531         {
1532                 const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1533                 for(map<string, VariableDeclaration *>::const_iterator i=prev_vars.begin(); i!=prev_vars.end(); ++i)
1534                 {
1535                         if(i->second->interface!="out")
1536                                 continue;
1537
1538                         /* Pass through output variables from the previous stage, but only
1539                         those which are not already linked to an input here. */
1540                         if(!i->second->linked_declaration && generate_interface(*i->second, "in", i->second->name))
1541                                 pass_vars.push_back(i->second);
1542                 }
1543         }
1544
1545         if(stage->type==Stage::GEOMETRY)
1546         {
1547                 /* Special case for geometry shader: copy gl_Position from input to
1548                 output. */
1549                 InterfaceBlockReference *ref = new InterfaceBlockReference;
1550                 ref->name = "gl_in";
1551
1552                 BinaryExpression *subscript = new BinaryExpression;
1553                 subscript->left = ref;
1554                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1555                 subscript->right = pass.subscript;
1556
1557                 MemberAccess *memacc = new MemberAccess;
1558                 memacc->left = subscript;
1559                 memacc->member = "gl_Position";
1560
1561                 insert_assignment("gl_Position", memacc);
1562         }
1563
1564         for(vector<VariableDeclaration *>::const_iterator i=pass_vars.begin(); i!=pass_vars.end(); ++i)
1565         {
1566                 string out_name = change_prefix((*i)->name, out_prefix);
1567                 generate_interface(**i, "out", out_name);
1568
1569                 VariableReference *ref = new VariableReference;
1570                 ref->name = (*i)->name;
1571                 if(pass.subscript)
1572                 {
1573                         BinaryExpression *subscript = new BinaryExpression;
1574                         subscript->left = ref;
1575                         subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1576                         subscript->right = pass.subscript;
1577                         insert_assignment(out_name, subscript);
1578                 }
1579                 else
1580                         insert_assignment(out_name, ref);
1581         }
1582
1583         nodes_to_remove.insert(&pass);
1584 }
1585
1586 } // namespace SL
1587 } // namespace GL
1588 } // namespace Msp