ir_reader: Convert to a class.
[profile/ivi/mesa.git] / src / glsl / ir_reader.cpp
1 /*
2  * Copyright © 2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23
24 extern "C" {
25 #include <talloc.h>
26 }
27
28 #include "ir_reader.h"
29 #include "glsl_parser_extras.h"
30 #include "glsl_types.h"
31 #include "s_expression.h"
32
33 const static bool debug = false;
34
35 class ir_reader {
36 public:
37    ir_reader(_mesa_glsl_parse_state *);
38
39    void read(exec_list *instructions, const char *src, bool scan_for_protos);
40
41 private:
42    void *mem_ctx;
43    _mesa_glsl_parse_state *state;
44
45    void ir_read_error(s_expression *, const char *fmt, ...);
46
47    const glsl_type *read_type(s_expression *);
48
49    void scan_for_prototypes(exec_list *, s_expression *);
50    ir_function *read_function(s_expression *, bool skip_body);
51    void read_function_sig(ir_function *, s_expression *, bool skip_body);
52
53    void read_instructions(exec_list *, s_expression *, ir_loop *);
54    ir_instruction *read_instruction(s_expression *, ir_loop *);
55    ir_variable *read_declaration(s_expression *);
56    ir_if *read_if(s_expression *, ir_loop *);
57    ir_loop *read_loop(s_expression *);
58    ir_return *read_return(s_expression *);
59    ir_rvalue *read_rvalue(s_expression *);
60    ir_assignment *read_assignment(s_expression *);
61    ir_expression *read_expression(s_expression *);
62    ir_call *read_call(s_expression *);
63    ir_swizzle *read_swizzle(s_expression *);
64    ir_constant *read_constant(s_expression *);
65    ir_texture *read_texture(s_expression *);
66
67    ir_dereference *read_dereference(s_expression *);
68 };
69
70 ir_reader::ir_reader(_mesa_glsl_parse_state *state) : state(state)
71 {
72    this->mem_ctx = state;
73 }
74
75 void
76 _mesa_glsl_read_ir(_mesa_glsl_parse_state *state, exec_list *instructions,
77                    const char *src, bool scan_for_protos)
78 {
79    ir_reader r(state);
80    r.read(instructions, src, scan_for_protos);
81 }
82
83 void
84 ir_reader::read(exec_list *instructions, const char *src, bool scan_for_protos)
85 {
86    s_expression *expr = s_expression::read_expression(mem_ctx, src);
87    if (expr == NULL) {
88       ir_read_error(NULL, "couldn't parse S-Expression.");
89       return;
90    }
91    
92    if (scan_for_protos) {
93       scan_for_prototypes(instructions, expr);
94       if (state->error)
95          return;
96    }
97
98    read_instructions(instructions, expr, NULL);
99    talloc_free(expr);
100
101    if (debug)
102       validate_ir_tree(instructions);
103 }
104
105 void
106 ir_reader::ir_read_error(s_expression *expr, const char *fmt, ...)
107 {
108    va_list ap;
109
110    state->error = true;
111
112    if (state->current_function != NULL)
113       state->info_log = talloc_asprintf_append(state->info_log,
114                            "In function %s:\n",
115                            state->current_function->function_name());
116    state->info_log = talloc_strdup_append(state->info_log, "error: ");
117
118    va_start(ap, fmt);
119    state->info_log = talloc_vasprintf_append(state->info_log, fmt, ap);
120    va_end(ap);
121    state->info_log = talloc_strdup_append(state->info_log, "\n");
122
123    if (expr != NULL) {
124       state->info_log = talloc_strdup_append(state->info_log,
125                                              "...in this context:\n   ");
126       expr->print();
127       state->info_log = talloc_strdup_append(state->info_log, "\n\n");
128    }
129 }
130
131 const glsl_type *
132 ir_reader::read_type(s_expression *expr)
133 {
134    s_expression *s_base_type;
135    s_int *s_size;
136
137    s_pattern pat[] = { "array", s_base_type, s_size };
138    if (MATCH(expr, pat)) {
139       const glsl_type *base_type = read_type(s_base_type);
140       if (base_type == NULL) {
141          ir_read_error(NULL, "when reading base type of array type");
142          return NULL;
143       }
144
145       return glsl_type::get_array_instance(base_type, s_size->value());
146    }
147    
148    s_symbol *type_sym = SX_AS_SYMBOL(expr);
149    if (type_sym == NULL) {
150       ir_read_error(expr, "expected <type>");
151       return NULL;
152    }
153
154    const glsl_type *type = state->symbols->get_type(type_sym->value());
155    if (type == NULL)
156       ir_read_error(expr, "invalid type: %s", type_sym->value());
157
158    return type;
159 }
160
161
162 void
163 ir_reader::scan_for_prototypes(exec_list *instructions, s_expression *expr)
164 {
165    s_list *list = SX_AS_LIST(expr);
166    if (list == NULL) {
167       ir_read_error(expr, "Expected (<instruction> ...); found an atom.");
168       return;
169    }
170
171    foreach_iter(exec_list_iterator, it, list->subexpressions) {
172       s_list *sub = SX_AS_LIST(it.get());
173       if (sub == NULL)
174          continue; // not a (function ...); ignore it.
175
176       s_symbol *tag = SX_AS_SYMBOL(sub->subexpressions.get_head());
177       if (tag == NULL || strcmp(tag->value(), "function") != 0)
178          continue; // not a (function ...); ignore it.
179
180       ir_function *f = read_function(sub, true);
181       if (f == NULL)
182          return;
183       instructions->push_tail(f);
184    }
185 }
186
187 ir_function *
188 ir_reader::read_function(s_expression *expr, bool skip_body)
189 {
190    bool added = false;
191    s_symbol *name;
192
193    s_pattern pat[] = { "function", name };
194    if (!PARTIAL_MATCH(expr, pat)) {
195       ir_read_error(expr, "Expected (function <name> (signature ...) ...)");
196       return NULL;
197    }
198
199    ir_function *f = state->symbols->get_function(name->value());
200    if (f == NULL) {
201       f = new(mem_ctx) ir_function(name->value());
202       added = state->symbols->add_function(f);
203       assert(added);
204    }
205
206    exec_list_iterator it = ((s_list *) expr)->subexpressions.iterator();
207    it.next(); // skip "function" tag
208    it.next(); // skip function name
209    for (/* nothing */; it.has_next(); it.next()) {
210       s_expression *s_sig = (s_expression *) it.get();
211       read_function_sig(f, s_sig, skip_body);
212    }
213    return added ? f : NULL;
214 }
215
216 void
217 ir_reader::read_function_sig(ir_function *f, s_expression *expr, bool skip_body)
218 {
219    s_expression *type_expr;
220    s_list *paramlist;
221    s_list *body_list;
222
223    s_pattern pat[] = { "signature", type_expr, paramlist, body_list };
224    if (!MATCH(expr, pat)) {
225       ir_read_error(expr, "Expected (signature <type> (parameters ...) "
226                           "(<instruction> ...))");
227       return;
228    }
229
230    const glsl_type *return_type = read_type(type_expr);
231    if (return_type == NULL)
232       return;
233
234    s_symbol *paramtag = SX_AS_SYMBOL(paramlist->subexpressions.get_head());
235    if (paramtag == NULL || strcmp(paramtag->value(), "parameters") != 0) {
236       ir_read_error(paramlist, "Expected (parameters ...)");
237       return;
238    }
239
240    // Read the parameters list into a temporary place.
241    exec_list hir_parameters;
242    state->symbols->push_scope();
243
244    exec_list_iterator it = paramlist->subexpressions.iterator();
245    for (it.next() /* skip "parameters" */; it.has_next(); it.next()) {
246       ir_variable *var = read_declaration((s_expression *) it.get());
247       if (var == NULL)
248          return;
249
250       hir_parameters.push_tail(var);
251    }
252
253    ir_function_signature *sig = f->exact_matching_signature(&hir_parameters);
254    if (sig == NULL && skip_body) {
255       /* If scanning for prototypes, generate a new signature. */
256       sig = new(mem_ctx) ir_function_signature(return_type);
257       sig->is_builtin = true;
258       f->add_signature(sig);
259    } else if (sig != NULL) {
260       const char *badvar = sig->qualifiers_match(&hir_parameters);
261       if (badvar != NULL) {
262          ir_read_error(expr, "function `%s' parameter `%s' qualifiers "
263                        "don't match prototype", f->name, badvar);
264          return;
265       }
266
267       if (sig->return_type != return_type) {
268          ir_read_error(expr, "function `%s' return type doesn't "
269                        "match prototype", f->name);
270          return;
271       }
272    } else {
273       /* No prototype for this body exists - skip it. */
274       state->symbols->pop_scope();
275       return;
276    }
277    assert(sig != NULL);
278
279    sig->replace_parameters(&hir_parameters);
280
281    if (!skip_body && !body_list->subexpressions.is_empty()) {
282       if (sig->is_defined) {
283          ir_read_error(expr, "function %s redefined", f->name);
284          return;
285       }
286       state->current_function = sig;
287       read_instructions(&sig->body, body_list, NULL);
288       state->current_function = NULL;
289       sig->is_defined = true;
290    }
291
292    state->symbols->pop_scope();
293 }
294
295 void
296 ir_reader::read_instructions(exec_list *instructions, s_expression *expr,
297                              ir_loop *loop_ctx)
298 {
299    // Read in a list of instructions
300    s_list *list = SX_AS_LIST(expr);
301    if (list == NULL) {
302       ir_read_error(expr, "Expected (<instruction> ...); found an atom.");
303       return;
304    }
305
306    foreach_iter(exec_list_iterator, it, list->subexpressions) {
307       s_expression *sub = (s_expression*) it.get();
308       ir_instruction *ir = read_instruction(sub, loop_ctx);
309       if (ir != NULL) {
310          /* Global variable declarations should be moved to the top, before
311           * any functions that might use them.  Functions are added to the
312           * instruction stream when scanning for prototypes, so without this
313           * hack, they always appear before variable declarations.
314           */
315          if (state->current_function == NULL && ir->as_variable() != NULL)
316             instructions->push_head(ir);
317          else
318             instructions->push_tail(ir);
319       }
320    }
321 }
322
323
324 ir_instruction *
325 ir_reader::read_instruction(s_expression *expr, ir_loop *loop_ctx)
326 {
327    s_symbol *symbol = SX_AS_SYMBOL(expr);
328    if (symbol != NULL) {
329       if (strcmp(symbol->value(), "break") == 0 && loop_ctx != NULL)
330          return new(mem_ctx) ir_loop_jump(ir_loop_jump::jump_break);
331       if (strcmp(symbol->value(), "continue") == 0 && loop_ctx != NULL)
332          return new(mem_ctx) ir_loop_jump(ir_loop_jump::jump_continue);
333    }
334
335    s_list *list = SX_AS_LIST(expr);
336    if (list == NULL || list->subexpressions.is_empty()) {
337       ir_read_error(expr, "Invalid instruction.\n");
338       return NULL;
339    }
340
341    s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
342    if (tag == NULL) {
343       ir_read_error(expr, "expected instruction tag");
344       return NULL;
345    }
346
347    ir_instruction *inst = NULL;
348    if (strcmp(tag->value(), "declare") == 0) {
349       inst = read_declaration(list);
350    } else if (strcmp(tag->value(), "assign") == 0) {
351       inst = read_assignment(list);
352    } else if (strcmp(tag->value(), "if") == 0) {
353       inst = read_if(list, loop_ctx);
354    } else if (strcmp(tag->value(), "loop") == 0) {
355       inst = read_loop(list);
356    } else if (strcmp(tag->value(), "return") == 0) {
357       inst = read_return(list);
358    } else if (strcmp(tag->value(), "function") == 0) {
359       inst = read_function(list, false);
360    } else {
361       inst = read_rvalue(list);
362       if (inst == NULL)
363          ir_read_error(NULL, "when reading instruction");
364    }
365    return inst;
366 }
367
368 ir_variable *
369 ir_reader::read_declaration(s_expression *expr)
370 {
371    s_list *s_quals;
372    s_expression *s_type;
373    s_symbol *s_name;
374
375    s_pattern pat[] = { "declare", s_quals, s_type, s_name };
376    if (!MATCH(expr, pat)) {
377       ir_read_error(expr, "expected (declare (<qualifiers>) <type> <name>)");
378       return NULL;
379    }
380
381    const glsl_type *type = read_type(s_type);
382    if (type == NULL)
383       return NULL;
384
385    ir_variable *var = new(mem_ctx) ir_variable(type, s_name->value(),
386                                                ir_var_auto);
387
388    foreach_iter(exec_list_iterator, it, s_quals->subexpressions) {
389       s_symbol *qualifier = SX_AS_SYMBOL(it.get());
390       if (qualifier == NULL) {
391          ir_read_error(expr, "qualifier list must contain only symbols");
392          return NULL;
393       }
394
395       // FINISHME: Check for duplicate/conflicting qualifiers.
396       if (strcmp(qualifier->value(), "centroid") == 0) {
397          var->centroid = 1;
398       } else if (strcmp(qualifier->value(), "invariant") == 0) {
399          var->invariant = 1;
400       } else if (strcmp(qualifier->value(), "uniform") == 0) {
401          var->mode = ir_var_uniform;
402       } else if (strcmp(qualifier->value(), "auto") == 0) {
403          var->mode = ir_var_auto;
404       } else if (strcmp(qualifier->value(), "in") == 0) {
405          var->mode = ir_var_in;
406       } else if (strcmp(qualifier->value(), "out") == 0) {
407          var->mode = ir_var_out;
408       } else if (strcmp(qualifier->value(), "inout") == 0) {
409          var->mode = ir_var_inout;
410       } else if (strcmp(qualifier->value(), "smooth") == 0) {
411          var->interpolation = ir_var_smooth;
412       } else if (strcmp(qualifier->value(), "flat") == 0) {
413          var->interpolation = ir_var_flat;
414       } else if (strcmp(qualifier->value(), "noperspective") == 0) {
415          var->interpolation = ir_var_noperspective;
416       } else {
417          ir_read_error(expr, "unknown qualifier: %s", qualifier->value());
418          return NULL;
419       }
420    }
421
422    // Add the variable to the symbol table
423    state->symbols->add_variable(var);
424
425    return var;
426 }
427
428
429 ir_if *
430 ir_reader::read_if(s_expression *expr, ir_loop *loop_ctx)
431 {
432    s_expression *s_cond;
433    s_expression *s_then;
434    s_expression *s_else;
435
436    s_pattern pat[] = { "if", s_cond, s_then, s_else };
437    if (!MATCH(expr, pat)) {
438       ir_read_error(expr, "expected (if <condition> (<then>...) (<else>...))");
439       return NULL;
440    }
441
442    ir_rvalue *condition = read_rvalue(s_cond);
443    if (condition == NULL) {
444       ir_read_error(NULL, "when reading condition of (if ...)");
445       return NULL;
446    }
447
448    ir_if *iff = new(mem_ctx) ir_if(condition);
449
450    read_instructions(&iff->then_instructions, s_then, loop_ctx);
451    read_instructions(&iff->else_instructions, s_else, loop_ctx);
452    if (state->error) {
453       delete iff;
454       iff = NULL;
455    }
456    return iff;
457 }
458
459
460 ir_loop *
461 ir_reader::read_loop(s_expression *expr)
462 {
463    s_expression *s_counter, *s_from, *s_to, *s_inc, *s_body;
464
465    s_pattern pat[] = { "loop", s_counter, s_from, s_to, s_inc, s_body };
466    if (!MATCH(expr, pat)) {
467       ir_read_error(expr, "expected (loop <counter> <from> <to> "
468                           "<increment> <body>)");
469       return NULL;
470    }
471
472    // FINISHME: actually read the count/from/to fields.
473
474    ir_loop *loop = new(mem_ctx) ir_loop;
475    read_instructions(&loop->body_instructions, s_body, loop);
476    if (state->error) {
477       delete loop;
478       loop = NULL;
479    }
480    return loop;
481 }
482
483
484 ir_return *
485 ir_reader::read_return(s_expression *expr)
486 {
487    s_expression *s_retval;
488
489    s_pattern pat[] = { "return", s_retval};
490    if (!MATCH(expr, pat)) {
491       ir_read_error(expr, "expected (return <rvalue>)");
492       return NULL;
493    }
494
495    ir_rvalue *retval = read_rvalue(s_retval);
496    if (retval == NULL) {
497       ir_read_error(NULL, "when reading return value");
498       return NULL;
499    }
500
501    return new(mem_ctx) ir_return(retval);
502 }
503
504
505 ir_rvalue *
506 ir_reader::read_rvalue(s_expression *expr)
507 {
508    s_list *list = SX_AS_LIST(expr);
509    if (list == NULL || list->subexpressions.is_empty())
510       return NULL;
511
512    s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
513    if (tag == NULL) {
514       ir_read_error(expr, "expected rvalue tag");
515       return NULL;
516    }
517
518    ir_rvalue *rvalue = read_dereference(list);
519    if (rvalue != NULL || state->error)
520       return rvalue;
521    else if (strcmp(tag->value(), "swiz") == 0) {
522       rvalue = read_swizzle(list);
523    } else if (strcmp(tag->value(), "expression") == 0) {
524       rvalue = read_expression(list);
525    } else if (strcmp(tag->value(), "call") == 0) {
526       rvalue = read_call(list);
527    } else if (strcmp(tag->value(), "constant") == 0) {
528       rvalue = read_constant(list);
529    } else {
530       rvalue = read_texture(list);
531       if (rvalue == NULL && !state->error)
532          ir_read_error(expr, "unrecognized rvalue tag: %s", tag->value());
533    }
534
535    return rvalue;
536 }
537
538 ir_assignment *
539 ir_reader::read_assignment(s_expression *expr)
540 {
541    s_expression *cond_expr, *lhs_expr, *rhs_expr;
542    s_list       *mask_list;
543
544    s_pattern pat[] = { "assign", cond_expr, mask_list, lhs_expr, rhs_expr };
545    if (!MATCH(expr, pat)) {
546       ir_read_error(expr, "expected (assign <condition> (<write mask>) "
547                           "<lhs> <rhs>)");
548       return NULL;
549    }
550
551    ir_rvalue *condition = read_rvalue(cond_expr);
552    if (condition == NULL) {
553       ir_read_error(NULL, "when reading condition of assignment");
554       return NULL;
555    }
556
557    unsigned mask = 0;
558
559    s_symbol *mask_symbol;
560    s_pattern mask_pat[] = { mask_symbol };
561    if (MATCH(mask_list, mask_pat)) {
562       const char *mask_str = mask_symbol->value();
563       unsigned mask_length = strlen(mask_str);
564       if (mask_length > 4) {
565          ir_read_error(expr, "invalid write mask: %s", mask_str);
566          return NULL;
567       }
568
569       const unsigned idx_map[] = { 3, 0, 1, 2 }; /* w=bit 3, x=0, y=1, z=2 */
570
571       for (unsigned i = 0; i < mask_length; i++) {
572          if (mask_str[i] < 'w' || mask_str[i] > 'z') {
573             ir_read_error(expr, "write mask contains invalid character: %c",
574                           mask_str[i]);
575             return NULL;
576          }
577          mask |= 1 << idx_map[mask_str[i] - 'w'];
578       }
579    } else if (!mask_list->subexpressions.is_empty()) {
580       ir_read_error(mask_list, "expected () or (<write mask>)");
581       return NULL;
582    }
583
584    ir_dereference *lhs = read_dereference(lhs_expr);
585    if (lhs == NULL) {
586       ir_read_error(NULL, "when reading left-hand side of assignment");
587       return NULL;
588    }
589
590    ir_rvalue *rhs = read_rvalue(rhs_expr);
591    if (rhs == NULL) {
592       ir_read_error(NULL, "when reading right-hand side of assignment");
593       return NULL;
594    }
595
596    if (mask == 0 && (lhs->type->is_vector() || lhs->type->is_scalar())) {
597       ir_read_error(expr, "non-zero write mask required.");
598       return NULL;
599    }
600
601    return new(mem_ctx) ir_assignment(lhs, rhs, condition, mask);
602 }
603
604 ir_call *
605 ir_reader::read_call(s_expression *expr)
606 {
607    s_symbol *name;
608    s_list *params;
609
610    s_pattern pat[] = { "call", name, params };
611    if (!MATCH(expr, pat)) {
612       ir_read_error(expr, "expected (call <name> (<param> ...))");
613       return NULL;
614    }
615
616    exec_list parameters;
617
618    foreach_iter(exec_list_iterator, it, params->subexpressions) {
619       s_expression *expr = (s_expression*) it.get();
620       ir_rvalue *param = read_rvalue(expr);
621       if (param == NULL) {
622          ir_read_error(expr, "when reading parameter to function call");
623          return NULL;
624       }
625       parameters.push_tail(param);
626    }
627
628    ir_function *f = state->symbols->get_function(name->value());
629    if (f == NULL) {
630       ir_read_error(expr, "found call to undefined function %s",
631                     name->value());
632       return NULL;
633    }
634
635    ir_function_signature *callee = f->matching_signature(&parameters);
636    if (callee == NULL) {
637       ir_read_error(expr, "couldn't find matching signature for function "
638                     "%s", name->value());
639       return NULL;
640    }
641
642    return new(mem_ctx) ir_call(callee, &parameters);
643 }
644
645 ir_expression *
646 ir_reader::read_expression(s_expression *expr)
647 {
648    s_expression *s_type;
649    s_symbol *s_op;
650    s_expression *s_arg1;
651
652    s_pattern pat[] = { "expression", s_type, s_op, s_arg1 };
653    if (!PARTIAL_MATCH(expr, pat)) {
654       ir_read_error(expr, "expected (expression <type> <operator> "
655                           "<operand> [<operand>])");
656       return NULL;
657    }
658    s_expression *s_arg2 = (s_expression *) s_arg1->next; // may be tail sentinel
659
660    const glsl_type *type = read_type(s_type);
661    if (type == NULL)
662       return NULL;
663
664    /* Read the operator */
665    ir_expression_operation op = ir_expression::get_operator(s_op->value());
666    if (op == (ir_expression_operation) -1) {
667       ir_read_error(expr, "invalid operator: %s", s_op->value());
668       return NULL;
669    }
670     
671    unsigned num_operands = ir_expression::get_num_operands(op);
672    if (num_operands == 1 && !s_arg1->next->is_tail_sentinel()) {
673       ir_read_error(expr, "expected (expression <type> %s <operand>)",
674                     s_op->value());
675       return NULL;
676    }
677
678    ir_rvalue *arg1 = read_rvalue(s_arg1);
679    ir_rvalue *arg2 = NULL;
680    if (arg1 == NULL) {
681       ir_read_error(NULL, "when reading first operand of %s", s_op->value());
682       return NULL;
683    }
684
685    if (num_operands == 2) {
686       if (s_arg2->is_tail_sentinel() || !s_arg2->next->is_tail_sentinel()) {
687          ir_read_error(expr, "expected (expression <type> %s <operand> "
688                              "<operand>)", s_op->value());
689          return NULL;
690       }
691       arg2 = read_rvalue(s_arg2);
692       if (arg2 == NULL) {
693          ir_read_error(NULL, "when reading second operand of %s",
694                        s_op->value());
695          return NULL;
696       }
697    }
698
699    return new(mem_ctx) ir_expression(op, type, arg1, arg2);
700 }
701
702 ir_swizzle *
703 ir_reader::read_swizzle(s_expression *expr)
704 {
705    s_symbol *swiz;
706    s_expression *sub;
707
708    s_pattern pat[] = { "swiz", swiz, sub };
709    if (!MATCH(expr, pat)) {
710       ir_read_error(expr, "expected (swiz <swizzle> <rvalue>)");
711       return NULL;
712    }
713
714    if (strlen(swiz->value()) > 4) {
715       ir_read_error(expr, "expected a valid swizzle; found %s", swiz->value());
716       return NULL;
717    }
718
719    ir_rvalue *rvalue = read_rvalue(sub);
720    if (rvalue == NULL)
721       return NULL;
722
723    ir_swizzle *ir = ir_swizzle::create(rvalue, swiz->value(),
724                                        rvalue->type->vector_elements);
725    if (ir == NULL)
726       ir_read_error(expr, "invalid swizzle");
727
728    return ir;
729 }
730
731 ir_constant *
732 ir_reader::read_constant(s_expression *expr)
733 {
734    s_expression *type_expr;
735    s_list *values;
736
737    s_pattern pat[] = { "constant", type_expr, values };
738    if (!MATCH(expr, pat)) {
739       ir_read_error(expr, "expected (constant <type> (...))");
740       return NULL;
741    }
742
743    const glsl_type *type = read_type(type_expr);
744    if (type == NULL)
745       return NULL;
746
747    if (values == NULL) {
748       ir_read_error(expr, "expected (constant <type> (...))");
749       return NULL;
750    }
751
752    if (type->is_array()) {
753       unsigned elements_supplied = 0;
754       exec_list elements;
755       foreach_iter(exec_list_iterator, it, values->subexpressions) {
756          s_expression *elt = (s_expression *) it.get();
757          ir_constant *ir_elt = read_constant(elt);
758          if (ir_elt == NULL)
759             return NULL;
760          elements.push_tail(ir_elt);
761          elements_supplied++;
762       }
763
764       if (elements_supplied != type->length) {
765          ir_read_error(values, "expected exactly %u array elements, "
766                        "given %u", type->length, elements_supplied);
767          return NULL;
768       }
769       return new(mem_ctx) ir_constant(type, &elements);
770    }
771
772    const glsl_type *const base_type = type->get_base_type();
773
774    ir_constant_data data = { { 0 } };
775
776    // Read in list of values (at most 16).
777    int k = 0;
778    foreach_iter(exec_list_iterator, it, values->subexpressions) {
779       if (k >= 16) {
780          ir_read_error(values, "expected at most 16 numbers");
781          return NULL;
782       }
783
784       s_expression *expr = (s_expression*) it.get();
785
786       if (base_type->base_type == GLSL_TYPE_FLOAT) {
787          s_number *value = SX_AS_NUMBER(expr);
788          if (value == NULL) {
789             ir_read_error(values, "expected numbers");
790             return NULL;
791          }
792          data.f[k] = value->fvalue();
793       } else {
794          s_int *value = SX_AS_INT(expr);
795          if (value == NULL) {
796             ir_read_error(values, "expected integers");
797             return NULL;
798          }
799
800          switch (base_type->base_type) {
801          case GLSL_TYPE_UINT: {
802             data.u[k] = value->value();
803             break;
804          }
805          case GLSL_TYPE_INT: {
806             data.i[k] = value->value();
807             break;
808          }
809          case GLSL_TYPE_BOOL: {
810             data.b[k] = value->value();
811             break;
812          }
813          default:
814             ir_read_error(values, "unsupported constant type");
815             return NULL;
816          }
817       }
818       ++k;
819    }
820
821    return new(mem_ctx) ir_constant(type, &data);
822 }
823
824 ir_dereference *
825 ir_reader::read_dereference(s_expression *expr)
826 {
827    s_symbol *s_var;
828    s_expression *s_subject;
829    s_expression *s_index;
830    s_symbol *s_field;
831
832    s_pattern var_pat[] = { "var_ref", s_var };
833    s_pattern array_pat[] = { "array_ref", s_subject, s_index };
834    s_pattern record_pat[] = { "record_ref", s_subject, s_field };
835
836    if (MATCH(expr, var_pat)) {
837       ir_variable *var = state->symbols->get_variable(s_var->value());
838       if (var == NULL) {
839          ir_read_error(expr, "undeclared variable: %s", s_var->value());
840          return NULL;
841       }
842       return new(mem_ctx) ir_dereference_variable(var);
843    } else if (MATCH(expr, array_pat)) {
844       ir_rvalue *subject = read_rvalue(s_subject);
845       if (subject == NULL) {
846          ir_read_error(NULL, "when reading the subject of an array_ref");
847          return NULL;
848       }
849
850       ir_rvalue *idx = read_rvalue(s_index);
851       if (subject == NULL) {
852          ir_read_error(NULL, "when reading the index of an array_ref");
853          return NULL;
854       }
855       return new(mem_ctx) ir_dereference_array(subject, idx);
856    } else if (MATCH(expr, record_pat)) {
857       ir_rvalue *subject = read_rvalue(s_subject);
858       if (subject == NULL) {
859          ir_read_error(NULL, "when reading the subject of a record_ref");
860          return NULL;
861       }
862       return new(mem_ctx) ir_dereference_record(subject, s_field->value());
863    }
864    return NULL;
865 }
866
867 ir_texture *
868 ir_reader::read_texture(s_expression *expr)
869 {
870    s_symbol *tag = NULL;
871    s_expression *s_sampler = NULL;
872    s_expression *s_coord = NULL;
873    s_list *s_offset = NULL;
874    s_expression *s_proj = NULL;
875    s_list *s_shadow = NULL;
876    s_expression *s_lod = NULL;
877
878    ir_texture_opcode op;
879
880    s_pattern tex_pattern[] =
881       { "tex", s_sampler, s_coord, s_offset, s_proj, s_shadow };
882    s_pattern txf_pattern[] =
883       { "txf", s_sampler, s_coord, s_offset, s_lod };
884    s_pattern other_pattern[] =
885       { tag, s_sampler, s_coord, s_offset, s_proj, s_shadow, s_lod };
886
887    if (MATCH(expr, tex_pattern)) {
888       op = ir_tex;
889    } else if (MATCH(expr, txf_pattern)) {
890       op = ir_txf;
891    } else if (MATCH(expr, other_pattern)) {
892       op = ir_texture::get_opcode(tag->value());
893       if (op == -1)
894          return NULL;
895    }
896
897    ir_texture *tex = new(mem_ctx) ir_texture(op);
898
899    // Read sampler (must be a deref)
900    ir_dereference *sampler = read_dereference(s_sampler);
901    if (sampler == NULL) {
902       ir_read_error(NULL, "when reading sampler in (%s ...)",
903                     tex->opcode_string());
904       return NULL;
905    }
906    tex->set_sampler(sampler);
907
908    // Read coordinate (any rvalue)
909    tex->coordinate = read_rvalue(s_coord);
910    if (tex->coordinate == NULL) {
911       ir_read_error(NULL, "when reading coordinate in (%s ...)",
912                     tex->opcode_string());
913       return NULL;
914    }
915
916    // Read texel offset, i.e. (0 0 0)
917    s_int *offset_x;
918    s_int *offset_y;
919    s_int *offset_z;
920    s_pattern offset_pat[] = { offset_x, offset_y, offset_z };
921    if (!MATCH(s_offset, offset_pat)) {
922       ir_read_error(s_offset, "expected (<int> <int> <int>)");
923       return NULL;
924    }
925    tex->offsets[0] = offset_x->value();
926    tex->offsets[1] = offset_y->value();
927    tex->offsets[2] = offset_z->value();
928
929    if (op != ir_txf) {
930       s_int *proj_as_int = SX_AS_INT(s_proj);
931       if (proj_as_int && proj_as_int->value() == 1) {
932          tex->projector = NULL;
933       } else {
934          tex->projector = read_rvalue(s_proj);
935          if (tex->projector == NULL) {
936             ir_read_error(NULL, "when reading projective divide in (%s ..)",
937                           tex->opcode_string());
938             return NULL;
939          }
940       }
941
942       if (s_shadow->subexpressions.is_empty()) {
943          tex->shadow_comparitor = NULL;
944       } else {
945          tex->shadow_comparitor = read_rvalue(s_shadow);
946          if (tex->shadow_comparitor == NULL) {
947             ir_read_error(NULL, "when reading shadow comparitor in (%s ..)",
948                           tex->opcode_string());
949             return NULL;
950          }
951       }
952    }
953
954    switch (op) {
955    case ir_txb:
956       tex->lod_info.bias = read_rvalue(s_lod);
957       if (tex->lod_info.bias == NULL) {
958          ir_read_error(NULL, "when reading LOD bias in (txb ...)");
959          return NULL;
960       }
961       break;
962    case ir_txl:
963    case ir_txf:
964       tex->lod_info.lod = read_rvalue(s_lod);
965       if (tex->lod_info.lod == NULL) {
966          ir_read_error(NULL, "when reading LOD in (%s ...)",
967                        tex->opcode_string());
968          return NULL;
969       }
970       break;
971    case ir_txd: {
972       s_expression *s_dx, *s_dy;
973       s_pattern dxdy_pat[] = { s_dx, s_dy };
974       if (!MATCH(s_lod, dxdy_pat)) {
975          ir_read_error(s_lod, "expected (dPdx dPdy) in (txd ...)");
976          return NULL;
977       }
978       tex->lod_info.grad.dPdx = read_rvalue(s_dx);
979       if (tex->lod_info.grad.dPdx == NULL) {
980          ir_read_error(NULL, "when reading dPdx in (txd ...)");
981          return NULL;
982       }
983       tex->lod_info.grad.dPdy = read_rvalue(s_dy);
984       if (tex->lod_info.grad.dPdy == NULL) {
985          ir_read_error(NULL, "when reading dPdy in (txd ...)");
986          return NULL;
987       }
988       break;
989    }
990    default:
991       // tex doesn't have any extra parameters.
992       break;
993    };
994    return tex;
995 }