2015-07-14 Sandra Loosemore <sandra@codesourcery.com>
[official-gcc.git] / gcc / genmatch.c
blobfa140dfe158ba97411f78267e846cb01672711f8
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2015 Free Software Foundation, Inc.
5 Contributed by Richard Biener <rguenther@suse.de>
6 and Prathamesh Kulkarni <bilbotheelffriend@gmail.com>
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 for more details.
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3. If not see
22 <http://www.gnu.org/licenses/>. */
24 #include "bconfig.h"
25 #include <new>
26 #include "system.h"
27 #include "coretypes.h"
28 #include <cpplib.h>
29 #include "errors.h"
30 #include "hash-table.h"
31 #include "hash-set.h"
32 #include "is-a.h"
35 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
36 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
37 size_t, size_t MEM_STAT_DECL)
39 return NULL;
41 void ggc_free (void *)
46 /* libccp helpers. */
48 static struct line_maps *line_table;
50 static bool
51 #if GCC_VERSION >= 4001
52 __attribute__((format (printf, 6, 0)))
53 #endif
54 error_cb (cpp_reader *, int errtype, int, source_location location,
55 unsigned int, const char *msg, va_list *ap)
57 const line_map_ordinary *map;
58 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
59 expanded_location loc = linemap_expand_location (line_table, map, location);
60 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
61 (errtype == CPP_DL_WARNING) ? "warning" : "error");
62 vfprintf (stderr, msg, *ap);
63 fprintf (stderr, "\n");
64 FILE *f = fopen (loc.file, "r");
65 if (f)
67 char buf[128];
68 while (loc.line > 0)
70 if (!fgets (buf, 128, f))
71 goto notfound;
72 if (buf[strlen (buf) - 1] != '\n')
74 if (loc.line > 1)
75 loc.line++;
77 loc.line--;
79 fprintf (stderr, "%s", buf);
80 for (int i = 0; i < loc.column - 1; ++i)
81 fputc (' ', stderr);
82 fputc ('^', stderr);
83 fputc ('\n', stderr);
84 notfound:
85 fclose (f);
88 if (errtype == CPP_DL_FATAL)
89 exit (1);
90 return false;
93 static void
94 #if GCC_VERSION >= 4001
95 __attribute__((format (printf, 2, 3)))
96 #endif
97 fatal_at (const cpp_token *tk, const char *msg, ...)
99 va_list ap;
100 va_start (ap, msg);
101 error_cb (NULL, CPP_DL_FATAL, 0, tk->src_loc, 0, msg, &ap);
102 va_end (ap);
105 static void
106 #if GCC_VERSION >= 4001
107 __attribute__((format (printf, 2, 3)))
108 #endif
109 fatal_at (source_location loc, const char *msg, ...)
111 va_list ap;
112 va_start (ap, msg);
113 error_cb (NULL, CPP_DL_FATAL, 0, loc, 0, msg, &ap);
114 va_end (ap);
117 static void
118 #if GCC_VERSION >= 4001
119 __attribute__((format (printf, 2, 3)))
120 #endif
121 warning_at (const cpp_token *tk, const char *msg, ...)
123 va_list ap;
124 va_start (ap, msg);
125 error_cb (NULL, CPP_DL_WARNING, 0, tk->src_loc, 0, msg, &ap);
126 va_end (ap);
129 /* Like fprintf, but print INDENT spaces at the beginning. */
131 static void
132 #if GCC_VERSION >= 4001
133 __attribute__((format (printf, 3, 4)))
134 #endif
135 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
137 va_list ap;
138 for (; indent >= 8; indent -= 8)
139 fputc ('\t', f);
140 fprintf (f, "%*s", indent, "");
141 va_start (ap, format);
142 vfprintf (f, format, ap);
143 va_end (ap);
146 static void
147 output_line_directive (FILE *f, source_location location,
148 bool dumpfile = false)
150 const line_map_ordinary *map;
151 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
152 expanded_location loc = linemap_expand_location (line_table, map, location);
153 if (dumpfile)
155 /* When writing to a dumpfile only dump the filename. */
156 const char *file = strrchr (loc.file, DIR_SEPARATOR);
157 if (!file)
158 file = loc.file;
159 else
160 ++file;
161 fprintf (f, "%s:%d", file, loc.line);
163 else
164 /* Other gen programs really output line directives here, at least for
165 development it's right now more convenient to have line information
166 from the generated file. Still keep the directives as comment for now
167 to easily back-point to the meta-description. */
168 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
172 /* Pull in tree codes and builtin function codes from their
173 definition files. */
175 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
176 enum tree_code {
177 #include "tree.def"
178 CONVERT0,
179 CONVERT1,
180 CONVERT2,
181 VIEW_CONVERT0,
182 VIEW_CONVERT1,
183 VIEW_CONVERT2,
184 MAX_TREE_CODES
186 #undef DEFTREECODE
188 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
189 enum built_in_function {
190 #include "builtins.def"
191 END_BUILTINS
193 #undef DEF_BUILTIN
195 /* Return true if CODE represents a commutative tree code. Otherwise
196 return false. */
197 bool
198 commutative_tree_code (enum tree_code code)
200 switch (code)
202 case PLUS_EXPR:
203 case MULT_EXPR:
204 case MULT_HIGHPART_EXPR:
205 case MIN_EXPR:
206 case MAX_EXPR:
207 case BIT_IOR_EXPR:
208 case BIT_XOR_EXPR:
209 case BIT_AND_EXPR:
210 case NE_EXPR:
211 case EQ_EXPR:
212 case UNORDERED_EXPR:
213 case ORDERED_EXPR:
214 case UNEQ_EXPR:
215 case LTGT_EXPR:
216 case TRUTH_AND_EXPR:
217 case TRUTH_XOR_EXPR:
218 case TRUTH_OR_EXPR:
219 case WIDEN_MULT_EXPR:
220 case VEC_WIDEN_MULT_HI_EXPR:
221 case VEC_WIDEN_MULT_LO_EXPR:
222 case VEC_WIDEN_MULT_EVEN_EXPR:
223 case VEC_WIDEN_MULT_ODD_EXPR:
224 return true;
226 default:
227 break;
229 return false;
232 /* Return true if CODE represents a ternary tree code for which the
233 first two operands are commutative. Otherwise return false. */
234 bool
235 commutative_ternary_tree_code (enum tree_code code)
237 switch (code)
239 case WIDEN_MULT_PLUS_EXPR:
240 case WIDEN_MULT_MINUS_EXPR:
241 case DOT_PROD_EXPR:
242 case FMA_EXPR:
243 return true;
245 default:
246 break;
248 return false;
252 /* Base class for all identifiers the parser knows. */
254 struct id_base : nofree_ptr_hash<id_base>
256 enum id_kind { CODE, FN, PREDICATE, USER } kind;
258 id_base (id_kind, const char *, int = -1);
260 hashval_t hashval;
261 int nargs;
262 const char *id;
264 /* hash_table support. */
265 static inline hashval_t hash (const id_base *);
266 static inline int equal (const id_base *, const id_base *);
269 inline hashval_t
270 id_base::hash (const id_base *op)
272 return op->hashval;
275 inline int
276 id_base::equal (const id_base *op1,
277 const id_base *op2)
279 return (op1->hashval == op2->hashval
280 && strcmp (op1->id, op2->id) == 0);
283 /* Hashtable of known pattern operators. This is pre-seeded from
284 all known tree codes and all known builtin function ids. */
285 static hash_table<id_base> *operators;
287 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
289 kind = kind_;
290 id = id_;
291 nargs = nargs_;
292 hashval = htab_hash_string (id);
295 /* Identifier that maps to a tree code. */
297 struct operator_id : public id_base
299 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
300 const char *tcc_)
301 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
302 enum tree_code code;
303 const char *tcc;
306 /* Identifier that maps to a builtin function code. */
308 struct fn_id : public id_base
310 fn_id (enum built_in_function fn_, const char *id_)
311 : id_base (id_base::FN, id_), fn (fn_) {}
312 enum built_in_function fn;
315 struct simplify;
317 /* Identifier that maps to a user-defined predicate. */
319 struct predicate_id : public id_base
321 predicate_id (const char *id_)
322 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
323 vec<simplify *> matchers;
326 /* Identifier that maps to a operator defined by a 'for' directive. */
328 struct user_id : public id_base
330 user_id (const char *id_, bool is_oper_list_ = false)
331 : id_base (id_base::USER, id_), substitutes (vNULL),
332 used (false), is_oper_list (is_oper_list_) {}
333 vec<id_base *> substitutes;
334 bool used;
335 bool is_oper_list;
338 template<>
339 template<>
340 inline bool
341 is_a_helper <fn_id *>::test (id_base *id)
343 return id->kind == id_base::FN;
346 template<>
347 template<>
348 inline bool
349 is_a_helper <operator_id *>::test (id_base *id)
351 return id->kind == id_base::CODE;
354 template<>
355 template<>
356 inline bool
357 is_a_helper <predicate_id *>::test (id_base *id)
359 return id->kind == id_base::PREDICATE;
362 template<>
363 template<>
364 inline bool
365 is_a_helper <user_id *>::test (id_base *id)
367 return id->kind == id_base::USER;
370 /* Add a predicate identifier to the hash. */
372 static predicate_id *
373 add_predicate (const char *id)
375 predicate_id *p = new predicate_id (id);
376 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
377 if (*slot)
378 fatal ("duplicate id definition");
379 *slot = p;
380 return p;
383 /* Add a tree code identifier to the hash. */
385 static void
386 add_operator (enum tree_code code, const char *id,
387 const char *tcc, unsigned nargs)
389 if (strcmp (tcc, "tcc_unary") != 0
390 && strcmp (tcc, "tcc_binary") != 0
391 && strcmp (tcc, "tcc_comparison") != 0
392 && strcmp (tcc, "tcc_expression") != 0
393 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
394 && strcmp (tcc, "tcc_reference") != 0
395 /* To have INTEGER_CST and friends as "predicate operators". */
396 && strcmp (tcc, "tcc_constant") != 0
397 /* And allow CONSTRUCTOR for vector initializers. */
398 && !(code == CONSTRUCTOR))
399 return;
400 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
401 if (code == ADDR_EXPR)
402 nargs = 0;
403 operator_id *op = new operator_id (code, id, nargs, tcc);
404 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
405 if (*slot)
406 fatal ("duplicate id definition");
407 *slot = op;
410 /* Add a builtin identifier to the hash. */
412 static void
413 add_builtin (enum built_in_function code, const char *id)
415 fn_id *fn = new fn_id (code, id);
416 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
417 if (*slot)
418 fatal ("duplicate id definition");
419 *slot = fn;
422 /* Helper for easy comparing ID with tree code CODE. */
424 static bool
425 operator==(id_base &id, enum tree_code code)
427 if (operator_id *oid = dyn_cast <operator_id *> (&id))
428 return oid->code == code;
429 return false;
432 /* Lookup the identifier ID. */
434 id_base *
435 get_operator (const char *id)
437 id_base tem (id_base::CODE, id);
439 id_base *op = operators->find_with_hash (&tem, tem.hashval);
440 if (op)
442 /* If this is a user-defined identifier track whether it was used. */
443 if (user_id *uid = dyn_cast<user_id *> (op))
444 uid->used = true;
445 return op;
448 /* Try all-uppercase. */
449 char *id2 = xstrdup (id);
450 for (unsigned i = 0; i < strlen (id2); ++i)
451 id2[i] = TOUPPER (id2[i]);
452 new (&tem) id_base (id_base::CODE, id2);
453 op = operators->find_with_hash (&tem, tem.hashval);
454 if (op)
456 free (id2);
457 return op;
460 /* Try _EXPR appended. */
461 id2 = (char *)xrealloc (id2, strlen (id2) + sizeof ("_EXPR") + 1);
462 strcat (id2, "_EXPR");
463 new (&tem) id_base (id_base::CODE, id2);
464 op = operators->find_with_hash (&tem, tem.hashval);
465 if (op)
467 free (id2);
468 return op;
471 return 0;
474 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
477 /* The AST produced by parsing of the pattern definitions. */
479 struct dt_operand;
480 struct capture_info;
482 /* The base class for operands. */
484 struct operand {
485 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
486 operand (enum op_type type_) : type (type_) {}
487 enum op_type type;
488 virtual void gen_transform (FILE *, int, const char *, bool, int,
489 const char *, capture_info *,
490 dt_operand ** = 0,
491 bool = true)
492 { gcc_unreachable (); }
495 /* A predicate operand. Predicates are leafs in the AST. */
497 struct predicate : public operand
499 predicate (predicate_id *p_) : operand (OP_PREDICATE), p (p_) {}
500 predicate_id *p;
503 /* An operand that constitutes an expression. Expressions include
504 function calls and user-defined predicate invocations. */
506 struct expr : public operand
508 expr (id_base *operation_, bool is_commutative_ = false)
509 : operand (OP_EXPR), operation (operation_),
510 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
511 is_generic (false), force_single_use (false) {}
512 expr (expr *e)
513 : operand (OP_EXPR), operation (e->operation),
514 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
515 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
516 void append_op (operand *op) { ops.safe_push (op); }
517 /* The operator and its operands. */
518 id_base *operation;
519 vec<operand *> ops;
520 /* An explicitely specified type - used exclusively for conversions. */
521 const char *expr_type;
522 /* Whether the operation is to be applied commutatively. This is
523 later lowered to two separate patterns. */
524 bool is_commutative;
525 /* Whether the expression is expected to be in GENERIC form. */
526 bool is_generic;
527 /* Whether pushing any stmt to the sequence should be conditional
528 on this expression having a single-use. */
529 bool force_single_use;
530 virtual void gen_transform (FILE *f, int, const char *, bool, int,
531 const char *, capture_info *,
532 dt_operand ** = 0, bool = true);
535 /* An operator that is represented by native C code. This is always
536 a leaf operand in the AST. This class is also used to represent
537 the code to be generated for 'if' and 'with' expressions. */
539 struct c_expr : public operand
541 /* A mapping of an identifier and its replacement. Used to apply
542 'for' lowering. */
543 struct id_tab {
544 const char *id;
545 const char *oper;
546 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
549 c_expr (cpp_reader *r_, vec<cpp_token> code_, unsigned nr_stmts_,
550 vec<id_tab> ids_, cid_map_t *capture_ids_)
551 : operand (OP_C_EXPR), r (r_), code (code_), capture_ids (capture_ids_),
552 nr_stmts (nr_stmts_), ids (ids_) {}
553 /* cpplib tokens and state to transform this back to source. */
554 cpp_reader *r;
555 vec<cpp_token> code;
556 cid_map_t *capture_ids;
557 /* The number of statements parsed (well, the number of ';'s). */
558 unsigned nr_stmts;
559 /* The identifier replacement vector. */
560 vec<id_tab> ids;
561 virtual void gen_transform (FILE *f, int, const char *, bool, int,
562 const char *, capture_info *,
563 dt_operand ** = 0, bool = true);
566 /* A wrapper around another operand that captures its value. */
568 struct capture : public operand
570 capture (unsigned where_, operand *what_)
571 : operand (OP_CAPTURE), where (where_), what (what_) {}
572 /* Identifier index for the value. */
573 unsigned where;
574 /* The captured value. */
575 operand *what;
576 virtual void gen_transform (FILE *f, int, const char *, bool, int,
577 const char *, capture_info *,
578 dt_operand ** = 0, bool = true);
581 /* if expression. */
583 struct if_expr : public operand
585 if_expr () : operand (OP_IF), cond (NULL), trueexpr (NULL),
586 falseexpr (NULL) {}
587 c_expr *cond;
588 operand *trueexpr;
589 operand *falseexpr;
592 /* with expression. */
594 struct with_expr : public operand
596 with_expr () : operand (OP_WITH), with (NULL), subexpr (NULL) {}
597 c_expr *with;
598 operand *subexpr;
601 template<>
602 template<>
603 inline bool
604 is_a_helper <capture *>::test (operand *op)
606 return op->type == operand::OP_CAPTURE;
609 template<>
610 template<>
611 inline bool
612 is_a_helper <predicate *>::test (operand *op)
614 return op->type == operand::OP_PREDICATE;
617 template<>
618 template<>
619 inline bool
620 is_a_helper <c_expr *>::test (operand *op)
622 return op->type == operand::OP_C_EXPR;
625 template<>
626 template<>
627 inline bool
628 is_a_helper <expr *>::test (operand *op)
630 return op->type == operand::OP_EXPR;
633 template<>
634 template<>
635 inline bool
636 is_a_helper <if_expr *>::test (operand *op)
638 return op->type == operand::OP_IF;
641 template<>
642 template<>
643 inline bool
644 is_a_helper <with_expr *>::test (operand *op)
646 return op->type == operand::OP_WITH;
649 /* The main class of a pattern and its transform. This is used to
650 represent both (simplify ...) and (match ...) kinds. The AST
651 duplicates all outer 'if' and 'for' expressions here so each
652 simplify can exist in isolation. */
654 struct simplify
656 enum simplify_kind { SIMPLIFY, MATCH };
658 simplify (simplify_kind kind_,
659 operand *match_, source_location match_location_,
660 struct operand *result_, source_location result_location_,
661 vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
662 : kind (kind_), match (match_), match_location (match_location_),
663 result (result_), result_location (result_location_),
664 for_vec (for_vec_),
665 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
667 simplify_kind kind;
668 /* The expression that is matched against the GENERIC or GIMPLE IL. */
669 operand *match;
670 source_location match_location;
671 /* For a (simplify ...) an expression with ifs and withs with the expression
672 produced when the pattern applies in the leafs.
673 For a (match ...) the leafs are either empty if it is a simple predicate
674 or the single expression specifying the matched operands. */
675 struct operand *result;
676 source_location result_location;
677 /* Collected 'for' expression operators that have to be replaced
678 in the lowering phase. */
679 vec<vec<user_id *> > for_vec;
680 /* A map of capture identifiers to indexes. */
681 cid_map_t *capture_ids;
682 int capture_max;
685 /* Debugging routines for dumping the AST. */
687 DEBUG_FUNCTION void
688 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
690 if (capture *c = dyn_cast<capture *> (o))
692 fprintf (f, "@%u", c->where);
693 if (c->what && flattened == false)
695 putc (':', f);
696 print_operand (c->what, f, flattened);
697 putc (' ', f);
701 else if (predicate *p = dyn_cast<predicate *> (o))
702 fprintf (f, "%s", p->p->id);
704 else if (is_a<c_expr *> (o))
705 fprintf (f, "c_expr");
707 else if (expr *e = dyn_cast<expr *> (o))
709 fprintf (f, "(%s", e->operation->id);
711 if (flattened == false)
713 putc (' ', f);
714 for (unsigned i = 0; i < e->ops.length (); ++i)
716 print_operand (e->ops[i], f, flattened);
717 putc (' ', f);
720 putc (')', f);
723 else
724 gcc_unreachable ();
727 DEBUG_FUNCTION void
728 print_matches (struct simplify *s, FILE *f = stderr)
730 fprintf (f, "for expression: ");
731 print_operand (s->match, f);
732 putc ('\n', f);
736 /* AST lowering. */
738 /* Lowering of commutative operators. */
740 static void
741 cartesian_product (const vec< vec<operand *> >& ops_vector,
742 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
744 if (n == ops_vector.length ())
746 vec<operand *> xv = v.copy ();
747 result.safe_push (xv);
748 return;
751 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
753 v[n] = ops_vector[n][i];
754 cartesian_product (ops_vector, result, v, n + 1);
758 /* Lower OP to two operands in case it is marked as commutative. */
760 static vec<operand *>
761 commutate (operand *op)
763 vec<operand *> ret = vNULL;
765 if (capture *c = dyn_cast <capture *> (op))
767 if (!c->what)
769 ret.safe_push (op);
770 return ret;
772 vec<operand *> v = commutate (c->what);
773 for (unsigned i = 0; i < v.length (); ++i)
775 capture *nc = new capture (c->where, v[i]);
776 ret.safe_push (nc);
778 return ret;
781 expr *e = dyn_cast <expr *> (op);
782 if (!e || e->ops.length () == 0)
784 ret.safe_push (op);
785 return ret;
788 vec< vec<operand *> > ops_vector = vNULL;
789 for (unsigned i = 0; i < e->ops.length (); ++i)
790 ops_vector.safe_push (commutate (e->ops[i]));
792 auto_vec< vec<operand *> > result;
793 auto_vec<operand *> v (e->ops.length ());
794 v.quick_grow_cleared (e->ops.length ());
795 cartesian_product (ops_vector, result, v, 0);
798 for (unsigned i = 0; i < result.length (); ++i)
800 expr *ne = new expr (e);
801 ne->is_commutative = false;
802 for (unsigned j = 0; j < result[i].length (); ++j)
803 ne->append_op (result[i][j]);
804 ret.safe_push (ne);
807 if (!e->is_commutative)
808 return ret;
810 for (unsigned i = 0; i < result.length (); ++i)
812 expr *ne = new expr (e);
813 ne->is_commutative = false;
814 // result[i].length () is 2 since e->operation is binary
815 for (unsigned j = result[i].length (); j; --j)
816 ne->append_op (result[i][j-1]);
817 ret.safe_push (ne);
820 return ret;
823 /* Lower operations marked as commutative in the AST of S and push
824 the resulting patterns to SIMPLIFIERS. */
826 static void
827 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
829 vec<operand *> matchers = commutate (s->match);
830 for (unsigned i = 0; i < matchers.length (); ++i)
832 simplify *ns = new simplify (s->kind, matchers[i], s->match_location,
833 s->result, s->result_location,
834 s->for_vec, s->capture_ids);
835 simplifiers.safe_push (ns);
839 /* Strip conditional conversios using operator OPER from O and its
840 children if STRIP, else replace them with an unconditional convert. */
842 operand *
843 lower_opt_convert (operand *o, enum tree_code oper,
844 enum tree_code to_oper, bool strip)
846 if (capture *c = dyn_cast<capture *> (o))
848 if (c->what)
849 return new capture (c->where,
850 lower_opt_convert (c->what, oper, to_oper, strip));
851 else
852 return c;
855 expr *e = dyn_cast<expr *> (o);
856 if (!e)
857 return o;
859 if (*e->operation == oper)
861 if (strip)
862 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
864 expr *ne = new expr (e);
865 ne->operation = (to_oper == CONVERT_EXPR
866 ? get_operator ("CONVERT_EXPR")
867 : get_operator ("VIEW_CONVERT_EXPR"));
868 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
869 return ne;
872 expr *ne = new expr (e);
873 for (unsigned i = 0; i < e->ops.length (); ++i)
874 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
876 return ne;
879 /* Determine whether O or its children uses the conditional conversion
880 operator OPER. */
882 static bool
883 has_opt_convert (operand *o, enum tree_code oper)
885 if (capture *c = dyn_cast<capture *> (o))
887 if (c->what)
888 return has_opt_convert (c->what, oper);
889 else
890 return false;
893 expr *e = dyn_cast<expr *> (o);
894 if (!e)
895 return false;
897 if (*e->operation == oper)
898 return true;
900 for (unsigned i = 0; i < e->ops.length (); ++i)
901 if (has_opt_convert (e->ops[i], oper))
902 return true;
904 return false;
907 /* Lower conditional convert operators in O, expanding it to a vector
908 if required. */
910 static vec<operand *>
911 lower_opt_convert (operand *o)
913 vec<operand *> v1 = vNULL, v2;
915 v1.safe_push (o);
917 enum tree_code opers[]
918 = { CONVERT0, CONVERT_EXPR,
919 CONVERT1, CONVERT_EXPR,
920 CONVERT2, CONVERT_EXPR,
921 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
922 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
923 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
925 /* Conditional converts are lowered to a pattern with the
926 conversion and one without. The three different conditional
927 convert codes are lowered separately. */
929 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
931 v2 = vNULL;
932 for (unsigned j = 0; j < v1.length (); ++j)
933 if (has_opt_convert (v1[j], opers[i]))
935 v2.safe_push (lower_opt_convert (v1[j],
936 opers[i], opers[i+1], false));
937 v2.safe_push (lower_opt_convert (v1[j],
938 opers[i], opers[i+1], true));
941 if (v2 != vNULL)
943 v1 = vNULL;
944 for (unsigned j = 0; j < v2.length (); ++j)
945 v1.safe_push (v2[j]);
949 return v1;
952 /* Lower conditional convert operators in the AST of S and push
953 the resulting multiple patterns to SIMPLIFIERS. */
955 static void
956 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
958 vec<operand *> matchers = lower_opt_convert (s->match);
959 for (unsigned i = 0; i < matchers.length (); ++i)
961 simplify *ns = new simplify (s->kind, matchers[i], s->match_location,
962 s->result, s->result_location,
963 s->for_vec, s->capture_ids);
964 simplifiers.safe_push (ns);
968 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
969 GENERIC and a GIMPLE variant. */
971 static vec<operand *>
972 lower_cond (operand *o)
974 vec<operand *> ro = vNULL;
976 if (capture *c = dyn_cast<capture *> (o))
978 if (c->what)
980 vec<operand *> lop = vNULL;
981 lop = lower_cond (c->what);
983 for (unsigned i = 0; i < lop.length (); ++i)
984 ro.safe_push (new capture (c->where, lop[i]));
985 return ro;
989 expr *e = dyn_cast<expr *> (o);
990 if (!e || e->ops.length () == 0)
992 ro.safe_push (o);
993 return ro;
996 vec< vec<operand *> > ops_vector = vNULL;
997 for (unsigned i = 0; i < e->ops.length (); ++i)
998 ops_vector.safe_push (lower_cond (e->ops[i]));
1000 auto_vec< vec<operand *> > result;
1001 auto_vec<operand *> v (e->ops.length ());
1002 v.quick_grow_cleared (e->ops.length ());
1003 cartesian_product (ops_vector, result, v, 0);
1005 for (unsigned i = 0; i < result.length (); ++i)
1007 expr *ne = new expr (e);
1008 for (unsigned j = 0; j < result[i].length (); ++j)
1009 ne->append_op (result[i][j]);
1010 ro.safe_push (ne);
1011 /* If this is a COND with a captured expression or an
1012 expression with two operands then also match a GENERIC
1013 form on the compare. */
1014 if ((*e->operation == COND_EXPR
1015 || *e->operation == VEC_COND_EXPR)
1016 && ((is_a <capture *> (e->ops[0])
1017 && as_a <capture *> (e->ops[0])->what
1018 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1019 && as_a <expr *>
1020 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1021 || (is_a <expr *> (e->ops[0])
1022 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1024 expr *ne = new expr (e);
1025 for (unsigned j = 0; j < result[i].length (); ++j)
1026 ne->append_op (result[i][j]);
1027 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1029 expr *ocmp = as_a <expr *> (c->what);
1030 expr *cmp = new expr (ocmp);
1031 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1032 cmp->append_op (ocmp->ops[j]);
1033 cmp->is_generic = true;
1034 ne->ops[0] = new capture (c->where, cmp);
1036 else
1038 expr *ocmp = as_a <expr *> (ne->ops[0]);
1039 expr *cmp = new expr (ocmp);
1040 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1041 cmp->append_op (ocmp->ops[j]);
1042 cmp->is_generic = true;
1043 ne->ops[0] = cmp;
1045 ro.safe_push (ne);
1049 return ro;
1052 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1053 GENERIC and a GIMPLE variant. */
1055 static void
1056 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1058 vec<operand *> matchers = lower_cond (s->match);
1059 for (unsigned i = 0; i < matchers.length (); ++i)
1061 simplify *ns = new simplify (s->kind, matchers[i], s->match_location,
1062 s->result, s->result_location,
1063 s->for_vec, s->capture_ids);
1064 simplifiers.safe_push (ns);
1068 /* In AST operand O replace operator ID with operator WITH. */
1070 operand *
1071 replace_id (operand *o, user_id *id, id_base *with)
1073 /* Deep-copy captures and expressions, replacing operations as
1074 needed. */
1075 if (capture *c = dyn_cast<capture *> (o))
1077 if (!c->what)
1078 return c;
1079 return new capture (c->where, replace_id (c->what, id, with));
1081 else if (expr *e = dyn_cast<expr *> (o))
1083 expr *ne = new expr (e);
1084 if (e->operation == id)
1085 ne->operation = with;
1086 for (unsigned i = 0; i < e->ops.length (); ++i)
1087 ne->append_op (replace_id (e->ops[i], id, with));
1088 return ne;
1090 else if (with_expr *w = dyn_cast <with_expr *> (o))
1092 with_expr *nw = new with_expr ();
1093 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1094 nw->subexpr = replace_id (w->subexpr, id, with);
1095 return nw;
1097 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1099 if_expr *nife = new if_expr ();
1100 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1101 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1102 if (ife->falseexpr)
1103 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1104 return nife;
1107 /* For c_expr we simply record a string replacement table which is
1108 applied at code-generation time. */
1109 if (c_expr *ce = dyn_cast<c_expr *> (o))
1111 vec<c_expr::id_tab> ids = ce->ids.copy ();
1112 ids.safe_push (c_expr::id_tab (id->id, with->id));
1113 return new c_expr (ce->r, ce->code, ce->nr_stmts, ids, ce->capture_ids);
1116 return o;
1119 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1121 static void
1122 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1124 vec<vec<user_id *> >& for_vec = sin->for_vec;
1125 unsigned worklist_start = 0;
1126 auto_vec<simplify *> worklist;
1127 worklist.safe_push (sin);
1129 /* Lower each recorded for separately, operating on the
1130 set of simplifiers created by the previous one.
1131 Lower inner-to-outer so inner for substitutes can refer
1132 to operators replaced by outer fors. */
1133 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1135 vec<user_id *>& ids = for_vec[fi];
1136 unsigned n_ids = ids.length ();
1137 unsigned max_n_opers = 0;
1138 for (unsigned i = 0; i < n_ids; ++i)
1139 if (ids[i]->substitutes.length () > max_n_opers)
1140 max_n_opers = ids[i]->substitutes.length ();
1142 unsigned worklist_end = worklist.length ();
1143 for (unsigned si = worklist_start; si < worklist_end; ++si)
1145 simplify *s = worklist[si];
1146 for (unsigned j = 0; j < max_n_opers; ++j)
1148 operand *match_op = s->match;
1149 operand *result_op = s->result;
1150 for (unsigned i = 0; i < n_ids; ++i)
1152 user_id *id = ids[i];
1153 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1154 match_op = replace_id (match_op, id, oper);
1155 if (result_op)
1156 result_op = replace_id (result_op, id, oper);
1158 simplify *ns = new simplify (s->kind, match_op, s->match_location,
1159 result_op, s->result_location,
1160 vNULL, s->capture_ids);
1161 worklist.safe_push (ns);
1164 worklist_start = worklist_end;
1167 /* Copy out the result from the last for lowering. */
1168 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1169 simplifiers.safe_push (worklist[i]);
1172 /* Lower the AST for everything in SIMPLIFIERS. */
1174 static void
1175 lower (vec<simplify *>& simplifiers, bool gimple)
1177 auto_vec<simplify *> out_simplifiers;
1178 for (unsigned i = 0; i < simplifiers.length (); ++i)
1179 lower_opt_convert (simplifiers[i], out_simplifiers);
1181 simplifiers.truncate (0);
1182 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1183 lower_commutative (out_simplifiers[i], simplifiers);
1185 out_simplifiers.truncate (0);
1186 if (gimple)
1187 for (unsigned i = 0; i < simplifiers.length (); ++i)
1188 lower_cond (simplifiers[i], out_simplifiers);
1189 else
1190 out_simplifiers.safe_splice (simplifiers);
1193 simplifiers.truncate (0);
1194 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1195 lower_for (out_simplifiers[i], simplifiers);
1201 /* The decision tree built for generating GIMPLE and GENERIC pattern
1202 matching code. It represents the 'match' expression of all
1203 simplifies and has those as its leafs. */
1205 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1207 struct dt_node
1209 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1211 enum dt_type type;
1212 unsigned level;
1213 vec<dt_node *> kids;
1215 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1217 dt_node *append_node (dt_node *);
1218 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1219 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1220 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1221 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1223 virtual void gen (FILE *, int, bool) {}
1225 void gen_kids (FILE *, int, bool);
1226 void gen_kids_1 (FILE *, int, bool,
1227 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1228 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1231 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1233 struct dt_operand : public dt_node
1235 operand *op;
1236 dt_operand *match_dop;
1237 dt_operand *parent;
1238 unsigned pos;
1240 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1241 dt_operand *parent_ = 0, unsigned pos_ = 0)
1242 : dt_node (type), op (op_), match_dop (match_dop_),
1243 parent (parent_), pos (pos_) {}
1245 void gen (FILE *, int, bool);
1246 unsigned gen_predicate (FILE *, int, const char *, bool);
1247 unsigned gen_match_op (FILE *, int, const char *);
1249 unsigned gen_gimple_expr (FILE *, int);
1250 unsigned gen_generic_expr (FILE *, int, const char *);
1252 char *get_name (char *);
1253 void gen_opname (char *, unsigned);
1256 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1258 struct dt_simplify : public dt_node
1260 simplify *s;
1261 unsigned pattern_no;
1262 dt_operand **indexes;
1264 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1265 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1266 indexes (indexes_) {}
1268 void gen_1 (FILE *, int, bool, operand *);
1269 void gen (FILE *f, int, bool);
1272 template<>
1273 template<>
1274 inline bool
1275 is_a_helper <dt_operand *>::test (dt_node *n)
1277 return (n->type == dt_node::DT_OPERAND
1278 || n->type == dt_node::DT_MATCH);
1281 /* A container for the actual decision tree. */
1283 struct decision_tree
1285 dt_node *root;
1287 void insert (struct simplify *, unsigned);
1288 void gen_gimple (FILE *f = stderr);
1289 void gen_generic (FILE *f = stderr);
1290 void print (FILE *f = stderr);
1292 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1294 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1295 unsigned pos = 0, dt_node *parent = 0);
1296 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1297 static bool cmp_node (dt_node *, dt_node *);
1298 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1301 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1303 bool
1304 cmp_operand (operand *o1, operand *o2)
1306 if (!o1 || !o2 || o1->type != o2->type)
1307 return false;
1309 if (o1->type == operand::OP_PREDICATE)
1311 predicate *p1 = as_a<predicate *>(o1);
1312 predicate *p2 = as_a<predicate *>(o2);
1313 return p1->p == p2->p;
1315 else if (o1->type == operand::OP_EXPR)
1317 expr *e1 = static_cast<expr *>(o1);
1318 expr *e2 = static_cast<expr *>(o2);
1319 return (e1->operation == e2->operation
1320 && e1->is_generic == e2->is_generic);
1322 else
1323 return false;
1326 /* Compare two decision tree nodes N1 and N2 and return true if they
1327 are equal. */
1329 bool
1330 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1332 if (!n1 || !n2 || n1->type != n2->type)
1333 return false;
1335 if (n1 == n2)
1336 return true;
1338 if (n1->type == dt_node::DT_TRUE)
1339 return false;
1341 if (n1->type == dt_node::DT_OPERAND)
1342 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1343 (as_a<dt_operand *> (n2))->op);
1344 else if (n1->type == dt_node::DT_MATCH)
1345 return ((as_a<dt_operand *> (n1))->match_dop
1346 == (as_a<dt_operand *> (n2))->match_dop);
1347 return false;
1350 /* Search OPS for a decision tree node like P and return it if found. */
1352 dt_node *
1353 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1355 /* We can merge adjacent DT_TRUE. */
1356 if (p->type == dt_node::DT_TRUE
1357 && !ops.is_empty ()
1358 && ops.last ()->type == dt_node::DT_TRUE)
1359 return ops.last ();
1360 for (int i = ops.length () - 1; i >= 0; --i)
1362 /* But we can't merge across DT_TRUE nodes as they serve as
1363 pattern order barriers to make sure that patterns apply
1364 in order of appearance in case multiple matches are possible. */
1365 if (ops[i]->type == dt_node::DT_TRUE)
1366 return NULL;
1367 if (decision_tree::cmp_node (ops[i], p))
1368 return ops[i];
1370 return NULL;
1373 /* Append N to the decision tree if it there is not already an existing
1374 identical child. */
1376 dt_node *
1377 dt_node::append_node (dt_node *n)
1379 dt_node *kid;
1381 kid = decision_tree::find_node (kids, n);
1382 if (kid)
1383 return kid;
1385 kids.safe_push (n);
1386 n->level = this->level + 1;
1388 return n;
1391 /* Append OP to the decision tree. */
1393 dt_node *
1394 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1396 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1397 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1398 return append_node (n);
1401 /* Append a DT_TRUE decision tree node. */
1403 dt_node *
1404 dt_node::append_true_op (dt_node *parent, unsigned pos)
1406 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1407 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1408 return append_node (n);
1411 /* Append a DT_MATCH decision tree node. */
1413 dt_node *
1414 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1416 dt_operand *parent_ = as_a<dt_operand *> (parent);
1417 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1418 return append_node (n);
1421 /* Append S to the decision tree. */
1423 dt_node *
1424 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1425 dt_operand **indexes)
1427 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1428 return append_node (n);
1431 /* Insert O into the decision tree and return the decision tree node found
1432 or created. */
1434 dt_node *
1435 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1436 unsigned pos, dt_node *parent)
1438 dt_node *q, *elm = 0;
1440 if (capture *c = dyn_cast<capture *> (o))
1442 unsigned capt_index = c->where;
1444 if (indexes[capt_index] == 0)
1446 if (c->what)
1447 q = insert_operand (p, c->what, indexes, pos, parent);
1448 else
1450 q = elm = p->append_true_op (parent, pos);
1451 goto at_assert_elm;
1453 // get to the last capture
1454 for (operand *what = c->what;
1455 what && is_a<capture *> (what);
1456 c = as_a<capture *> (what), what = c->what)
1459 if (!c->what)
1461 unsigned cc_index = c->where;
1462 dt_operand *match_op = indexes[cc_index];
1464 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1465 elm = decision_tree::find_node (p->kids, &temp);
1467 if (elm == 0)
1469 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1470 elm = decision_tree::find_node (p->kids, &temp);
1473 else
1475 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1476 elm = decision_tree::find_node (p->kids, &temp);
1479 at_assert_elm:
1480 gcc_assert (elm->type == dt_node::DT_TRUE
1481 || elm->type == dt_node::DT_OPERAND
1482 || elm->type == dt_node::DT_MATCH);
1483 indexes[capt_index] = static_cast<dt_operand *> (elm);
1484 return q;
1486 else
1488 p = p->append_match_op (indexes[capt_index], parent, pos);
1489 if (c->what)
1490 return insert_operand (p, c->what, indexes, 0, p);
1491 else
1492 return p;
1495 p = p->append_op (o, parent, pos);
1496 q = p;
1498 if (expr *e = dyn_cast <expr *>(o))
1500 for (unsigned i = 0; i < e->ops.length (); ++i)
1501 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1504 return q;
1507 /* Insert S into the decision tree. */
1509 void
1510 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1512 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1513 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1514 p->append_simplify (s, pattern_no, indexes);
1517 /* Debug functions to dump the decision tree. */
1519 DEBUG_FUNCTION void
1520 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1522 if (p->type == dt_node::DT_NODE)
1523 fprintf (f, "root");
1524 else
1526 fprintf (f, "|");
1527 for (unsigned i = 0; i < indent; i++)
1528 fprintf (f, "-");
1530 if (p->type == dt_node::DT_OPERAND)
1532 dt_operand *dop = static_cast<dt_operand *>(p);
1533 print_operand (dop->op, f, true);
1535 else if (p->type == dt_node::DT_TRUE)
1536 fprintf (f, "true");
1537 else if (p->type == dt_node::DT_MATCH)
1538 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1539 else if (p->type == dt_node::DT_SIMPLIFY)
1541 dt_simplify *s = static_cast<dt_simplify *> (p);
1542 fprintf (f, "simplify_%u { ", s->pattern_no);
1543 for (int i = 0; i <= s->s->capture_max; ++i)
1544 fprintf (f, "%p, ", (void *) s->indexes[i]);
1545 fprintf (f, " } ");
1549 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1551 for (unsigned i = 0; i < p->kids.length (); ++i)
1552 decision_tree::print_node (p->kids[i], f, indent + 2);
1555 DEBUG_FUNCTION void
1556 decision_tree::print (FILE *f)
1558 return decision_tree::print_node (root, f);
1562 /* For GENERIC we have to take care of wrapping multiple-used
1563 expressions with side-effects in save_expr and preserve side-effects
1564 of expressions with omit_one_operand. Analyze captures in
1565 match, result and with expressions and perform early-outs
1566 on the outermost match expression operands for cases we cannot
1567 handle. */
1569 struct capture_info
1571 capture_info (simplify *s, operand *);
1572 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1573 bool walk_result (operand *o, bool, operand *);
1574 void walk_c_expr (c_expr *);
1576 struct cinfo
1578 bool expr_p;
1579 bool cse_p;
1580 bool force_no_side_effects_p;
1581 bool force_single_use;
1582 bool cond_expr_cond_p;
1583 unsigned long toplevel_msk;
1584 int result_use_count;
1587 auto_vec<cinfo> info;
1588 unsigned long force_no_side_effects;
1591 /* Analyze captures in S. */
1593 capture_info::capture_info (simplify *s, operand *result)
1595 expr *e;
1596 if (s->kind == simplify::MATCH)
1598 force_no_side_effects = -1;
1599 return;
1602 force_no_side_effects = 0;
1603 info.safe_grow_cleared (s->capture_max + 1);
1604 e = as_a <expr *> (s->match);
1605 for (unsigned i = 0; i < e->ops.length (); ++i)
1606 walk_match (e->ops[i], i,
1607 (i != 0 && *e->operation == COND_EXPR)
1608 || *e->operation == TRUTH_ANDIF_EXPR
1609 || *e->operation == TRUTH_ORIF_EXPR,
1610 i == 0
1611 && (*e->operation == COND_EXPR
1612 || *e->operation == VEC_COND_EXPR));
1614 walk_result (s->result, false, result);
1617 /* Analyze captures in the match expression piece O. */
1619 void
1620 capture_info::walk_match (operand *o, unsigned toplevel_arg,
1621 bool conditional_p, bool cond_expr_cond_p)
1623 if (capture *c = dyn_cast <capture *> (o))
1625 info[c->where].toplevel_msk |= 1 << toplevel_arg;
1626 info[c->where].force_no_side_effects_p |= conditional_p;
1627 info[c->where].cond_expr_cond_p |= cond_expr_cond_p;
1628 /* Mark expr (non-leaf) captures and recurse. */
1629 expr *e;
1630 if (c->what
1631 && (e = dyn_cast <expr *> (c->what)))
1633 info[c->where].expr_p = true;
1634 info[c->where].force_single_use |= e->force_single_use;
1635 walk_match (c->what, toplevel_arg, conditional_p, false);
1638 else if (expr *e = dyn_cast <expr *> (o))
1640 for (unsigned i = 0; i < e->ops.length (); ++i)
1642 bool cond_p = conditional_p;
1643 bool cond_expr_cond_p = false;
1644 if (i != 0 && *e->operation == COND_EXPR)
1645 cond_p = true;
1646 else if (*e->operation == TRUTH_ANDIF_EXPR
1647 || *e->operation == TRUTH_ORIF_EXPR)
1648 cond_p = true;
1649 if (i == 0
1650 && (*e->operation == COND_EXPR
1651 || *e->operation == VEC_COND_EXPR))
1652 cond_expr_cond_p = true;
1653 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1656 else if (is_a <predicate *> (o))
1658 /* Mark non-captured leafs toplevel arg for checking. */
1659 force_no_side_effects |= 1 << toplevel_arg;
1661 else
1662 gcc_unreachable ();
1665 /* Analyze captures in the result expression piece O. Return true
1666 if RESULT was visited in one of the children. Only visit
1667 non-if/with children if they are rooted on RESULT. */
1669 bool
1670 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
1672 if (capture *c = dyn_cast <capture *> (o))
1674 info[c->where].result_use_count++;
1675 /* If we substitute an expression capture we don't know
1676 which captures this will end up using (well, we don't
1677 compute that). Force the uses to be side-effect free
1678 which means forcing the toplevels that reach the
1679 expression side-effect free. */
1680 if (info[c->where].expr_p)
1681 force_no_side_effects |= info[c->where].toplevel_msk;
1682 /* Mark CSE capture uses as forced to have no side-effects. */
1683 if (c->what
1684 && is_a <expr *> (c->what))
1686 info[c->where].cse_p = true;
1687 walk_result (c->what, true, result);
1690 else if (expr *e = dyn_cast <expr *> (o))
1692 for (unsigned i = 0; i < e->ops.length (); ++i)
1694 bool cond_p = conditional_p;
1695 if (i != 0 && *e->operation == COND_EXPR)
1696 cond_p = true;
1697 else if (*e->operation == TRUTH_ANDIF_EXPR
1698 || *e->operation == TRUTH_ORIF_EXPR)
1699 cond_p = true;
1700 walk_result (e->ops[i], cond_p, result);
1703 else if (if_expr *e = dyn_cast <if_expr *> (o))
1705 /* 'if' conditions should be all fine. */
1706 if (e->trueexpr == result)
1708 walk_result (e->trueexpr, false, result);
1709 return true;
1711 if (e->falseexpr == result)
1713 walk_result (e->falseexpr, false, result);
1714 return true;
1716 bool res = false;
1717 if (is_a <if_expr *> (e->trueexpr)
1718 || is_a <with_expr *> (e->trueexpr))
1719 res |= walk_result (e->trueexpr, false, result);
1720 if (e->falseexpr
1721 && (is_a <if_expr *> (e->falseexpr)
1722 || is_a <with_expr *> (e->falseexpr)))
1723 res |= walk_result (e->falseexpr, false, result);
1724 return res;
1726 else if (with_expr *e = dyn_cast <with_expr *> (o))
1728 bool res = (e->subexpr == result);
1729 if (res
1730 || is_a <if_expr *> (e->subexpr)
1731 || is_a <with_expr *> (e->subexpr))
1732 res |= walk_result (e->subexpr, false, result);
1733 if (res)
1734 walk_c_expr (e->with);
1735 return res;
1737 else if (c_expr *e = dyn_cast <c_expr *> (o))
1738 walk_c_expr (e);
1739 else
1740 gcc_unreachable ();
1742 return false;
1745 /* Look for captures in the C expr E. */
1747 void
1748 capture_info::walk_c_expr (c_expr *e)
1750 /* Give up for C exprs mentioning captures not inside TREE_TYPE (). */
1751 unsigned p_depth = 0;
1752 for (unsigned i = 0; i < e->code.length (); ++i)
1754 const cpp_token *t = &e->code[i];
1755 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
1756 if (t->type == CPP_NAME
1757 && strcmp ((const char *)CPP_HASHNODE
1758 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
1759 && n->type == CPP_OPEN_PAREN)
1760 p_depth++;
1761 else if (t->type == CPP_CLOSE_PAREN
1762 && p_depth > 0)
1763 p_depth--;
1764 else if (p_depth == 0
1765 && t->type == CPP_ATSIGN
1766 && (n->type == CPP_NUMBER
1767 || n->type == CPP_NAME)
1768 && !(n->flags & PREV_WHITE))
1770 const char *id;
1771 if (n->type == CPP_NUMBER)
1772 id = (const char *)n->val.str.text;
1773 else
1774 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1775 info[*e->capture_ids->get(id)].force_no_side_effects_p = true;
1781 /* Code generation off the decision tree and the refered AST nodes. */
1783 bool
1784 is_conversion (id_base *op)
1786 return (*op == CONVERT_EXPR
1787 || *op == NOP_EXPR
1788 || *op == FLOAT_EXPR
1789 || *op == FIX_TRUNC_EXPR
1790 || *op == VIEW_CONVERT_EXPR);
1793 /* Get the type to be used for generating operands of OP from the
1794 various sources. */
1796 static const char *
1797 get_operand_type (id_base *op, const char *in_type,
1798 const char *expr_type,
1799 const char *other_oprnd_type)
1801 /* Generally operands whose type does not match the type of the
1802 expression generated need to know their types but match and
1803 thus can fall back to 'other_oprnd_type'. */
1804 if (is_conversion (op))
1805 return other_oprnd_type;
1806 else if (*op == REALPART_EXPR
1807 || *op == IMAGPART_EXPR)
1808 return other_oprnd_type;
1809 else if (is_a <operator_id *> (op)
1810 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
1811 return other_oprnd_type;
1812 else
1814 /* Otherwise all types should match - choose one in order of
1815 preference. */
1816 if (expr_type)
1817 return expr_type;
1818 else if (in_type)
1819 return in_type;
1820 else
1821 return other_oprnd_type;
1825 /* Generate transform code for an expression. */
1827 void
1828 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
1829 int depth, const char *in_type, capture_info *cinfo,
1830 dt_operand **indexes, bool)
1832 bool conversion_p = is_conversion (operation);
1833 const char *type = expr_type;
1834 char optype[64];
1835 if (type)
1836 /* If there was a type specification in the pattern use it. */
1838 else if (conversion_p)
1839 /* For conversions we need to build the expression using the
1840 outer type passed in. */
1841 type = in_type;
1842 else if (*operation == REALPART_EXPR
1843 || *operation == IMAGPART_EXPR)
1845 /* __real and __imag use the component type of its operand. */
1846 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
1847 type = optype;
1849 else if (is_a <operator_id *> (operation)
1850 && !strcmp (as_a <operator_id *> (operation)->tcc, "tcc_comparison"))
1852 /* comparisons use boolean_type_node (or what gets in), but
1853 their operands need to figure out the types themselves. */
1854 sprintf (optype, "boolean_type_node");
1855 type = optype;
1857 else if (*operation == COND_EXPR
1858 || *operation == VEC_COND_EXPR)
1860 /* Conditions are of the same type as their first alternative. */
1861 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
1862 type = optype;
1864 else
1866 /* Other operations are of the same type as their first operand. */
1867 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
1868 type = optype;
1870 if (!type)
1871 fatal ("two conversions in a row");
1873 fprintf_indent (f, indent, "{\n");
1874 indent += 2;
1875 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
1876 char op0type[64];
1877 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
1878 for (unsigned i = 0; i < ops.length (); ++i)
1880 char dest[32];
1881 snprintf (dest, 32, "ops%d[%u]", depth, i);
1882 const char *optype
1883 = get_operand_type (operation, in_type, expr_type,
1884 i == 0 ? NULL : op0type);
1885 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
1886 cinfo, indexes,
1887 ((!(*operation == COND_EXPR)
1888 && !(*operation == VEC_COND_EXPR))
1889 || i != 0));
1892 const char *opr;
1893 if (*operation == CONVERT_EXPR)
1894 opr = "NOP_EXPR";
1895 else
1896 opr = operation->id;
1898 if (gimple)
1900 if (*operation == CONVERT_EXPR)
1902 fprintf_indent (f, indent,
1903 "if (%s != TREE_TYPE (ops%d[0])\n",
1904 type, depth);
1905 fprintf_indent (f, indent,
1906 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
1907 type, depth);
1908 fprintf_indent (f, indent + 2, "{\n");
1909 indent += 4;
1911 /* ??? Building a stmt can fail for various reasons here, seq being
1912 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
1913 So if we fail here we should continue matching other patterns. */
1914 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr);
1915 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
1916 for (unsigned i = 0; i < ops.length (); ++i)
1917 fprintf (f, "ops%d[%u]%s", depth, i,
1918 i == ops.length () - 1 ? " };\n" : ", ");
1919 fprintf_indent (f, indent,
1920 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
1921 ops.length (), type);
1922 fprintf_indent (f, indent,
1923 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
1924 type);
1925 fprintf_indent (f, indent,
1926 "if (!res) return false;\n");
1927 if (*operation == CONVERT_EXPR)
1929 indent -= 4;
1930 fprintf_indent (f, indent, " }\n");
1931 fprintf_indent (f, indent, "else\n");
1932 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
1935 else
1937 if (*operation == CONVERT_EXPR)
1939 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
1940 depth, type);
1941 indent += 2;
1943 if (operation->kind == id_base::CODE)
1944 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
1945 ops.length(), opr, type);
1946 else
1947 fprintf_indent (f, indent, "res = build_call_expr_loc (loc, "
1948 "builtin_decl_implicit (%s), %d", opr, ops.length());
1949 for (unsigned i = 0; i < ops.length (); ++i)
1950 fprintf (f, ", ops%d[%u]", depth, i);
1951 fprintf (f, ");\n");
1952 if (*operation == CONVERT_EXPR)
1954 indent -= 2;
1955 fprintf_indent (f, indent, "else\n");
1956 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
1959 fprintf_indent (f, indent, "%s = res;\n", dest);
1960 indent -= 2;
1961 fprintf_indent (f, indent, "}\n");
1964 /* Generate code for a c_expr which is either the expression inside
1965 an if statement or a sequence of statements which computes a
1966 result to be stored to DEST. */
1968 void
1969 c_expr::gen_transform (FILE *f, int indent, const char *dest,
1970 bool, int, const char *, capture_info *,
1971 dt_operand **, bool)
1973 if (dest && nr_stmts == 1)
1974 fprintf_indent (f, indent, "%s = ", dest);
1976 unsigned stmt_nr = 1;
1977 for (unsigned i = 0; i < code.length (); ++i)
1979 const cpp_token *token = &code[i];
1981 /* Replace captures for code-gen. */
1982 if (token->type == CPP_ATSIGN)
1984 const cpp_token *n = &code[i+1];
1985 if ((n->type == CPP_NUMBER
1986 || n->type == CPP_NAME)
1987 && !(n->flags & PREV_WHITE))
1989 if (token->flags & PREV_WHITE)
1990 fputc (' ', f);
1991 const char *id;
1992 if (n->type == CPP_NUMBER)
1993 id = (const char *)n->val.str.text;
1994 else
1995 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1996 fprintf (f, "captures[%u]", *capture_ids->get(id));
1997 ++i;
1998 continue;
2002 if (token->flags & PREV_WHITE)
2003 fputc (' ', f);
2005 if (token->type == CPP_NAME)
2007 const char *id = (const char *) NODE_NAME (token->val.node.node);
2008 unsigned j;
2009 for (j = 0; j < ids.length (); ++j)
2011 if (strcmp (id, ids[j].id) == 0)
2013 fprintf (f, "%s", ids[j].oper);
2014 break;
2017 if (j < ids.length ())
2018 continue;
2021 /* Output the token as string. */
2022 char *tk = (char *)cpp_token_as_text (r, token);
2023 fputs (tk, f);
2025 if (token->type == CPP_SEMICOLON)
2027 stmt_nr++;
2028 fputc ('\n', f);
2029 if (dest && stmt_nr == nr_stmts)
2030 fprintf_indent (f, indent, "%s = ", dest);
2035 /* Generate transform code for a capture. */
2037 void
2038 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2039 int depth, const char *in_type, capture_info *cinfo,
2040 dt_operand **indexes, bool expand_compares)
2042 if (what && is_a<expr *> (what))
2044 if (indexes[where] == 0)
2046 char buf[20];
2047 sprintf (buf, "captures[%u]", where);
2048 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2049 cinfo, NULL);
2053 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2055 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2056 with substituting a capture of that.
2057 ??? Returning false here will also not allow any other patterns
2058 to match. */
2059 if (gimple && expand_compares
2060 && cinfo->info[where].cond_expr_cond_p)
2062 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2063 fprintf_indent (f, indent, " {\n");
2064 fprintf_indent (f, indent, " if (!seq) return false;\n");
2065 fprintf_indent (f, indent, " %s = gimple_build (seq, TREE_CODE (%s),"
2066 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2067 " TREE_OPERAND (%s, 1));\n",
2068 dest, dest, dest, dest, dest);
2069 fprintf_indent (f, indent, " }\n");
2073 /* Return the name of the operand representing the decision tree node.
2074 Use NAME as space to generate it. */
2076 char *
2077 dt_operand::get_name (char *name)
2079 if (!parent)
2080 sprintf (name, "t");
2081 else if (parent->level == 1)
2082 sprintf (name, "op%u", pos);
2083 else if (parent->type == dt_node::DT_MATCH)
2084 return parent->get_name (name);
2085 else
2086 sprintf (name, "o%u%u", parent->level, pos);
2087 return name;
2090 /* Fill NAME with the operand name at position POS. */
2092 void
2093 dt_operand::gen_opname (char *name, unsigned pos)
2095 if (!parent)
2096 sprintf (name, "op%u", pos);
2097 else
2098 sprintf (name, "o%u%u", level, pos);
2101 /* Generate matching code for the decision tree operand which is
2102 a predicate. */
2104 unsigned
2105 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2107 predicate *p = as_a <predicate *> (op);
2109 if (p->p->matchers.exists ())
2111 /* If this is a predicate generated from a pattern mangle its
2112 name and pass on the valueize hook. */
2113 if (gimple)
2114 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2115 p->p->id, opname);
2116 else
2117 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2119 else
2120 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2121 fprintf_indent (f, indent + 2, "{\n");
2122 return 1;
2125 /* Generate matching code for the decision tree operand which is
2126 a capture-match. */
2128 unsigned
2129 dt_operand::gen_match_op (FILE *f, int indent, const char *opname)
2131 char match_opname[20];
2132 match_dop->get_name (match_opname);
2133 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2134 opname, match_opname, opname, match_opname);
2135 fprintf_indent (f, indent + 2, "{\n");
2136 return 1;
2139 /* Generate GIMPLE matching code for the decision tree operand. */
2141 unsigned
2142 dt_operand::gen_gimple_expr (FILE *f, int indent)
2144 expr *e = static_cast<expr *> (op);
2145 id_base *id = e->operation;
2146 unsigned n_ops = e->ops.length ();
2148 for (unsigned i = 0; i < n_ops; ++i)
2150 char child_opname[20];
2151 gen_opname (child_opname, i);
2153 if (id->kind == id_base::CODE)
2155 if (e->is_generic
2156 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2157 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2159 /* ??? If this is a memory operation we can't (and should not)
2160 match this. The only sensible operand types are
2161 SSA names and invariants. */
2162 fprintf_indent (f, indent,
2163 "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), %i);\n",
2164 child_opname, i);
2165 fprintf_indent (f, indent,
2166 "if ((TREE_CODE (%s) == SSA_NAME\n",
2167 child_opname);
2168 fprintf_indent (f, indent,
2169 " || is_gimple_min_invariant (%s))\n",
2170 child_opname);
2171 fprintf_indent (f, indent,
2172 " && (%s = do_valueize (valueize, %s)))\n",
2173 child_opname, child_opname);
2174 fprintf_indent (f, indent,
2175 " {\n");
2176 indent += 4;
2177 continue;
2179 else
2180 fprintf_indent (f, indent,
2181 "tree %s = gimple_assign_rhs%u (def_stmt);\n",
2182 child_opname, i + 1);
2184 else
2185 fprintf_indent (f, indent,
2186 "tree %s = gimple_call_arg (def_stmt, %u);\n",
2187 child_opname, i);
2188 fprintf_indent (f, indent,
2189 "if ((%s = do_valueize (valueize, %s)))\n",
2190 child_opname, child_opname);
2191 fprintf_indent (f, indent, " {\n");
2192 indent += 4;
2194 /* While the toplevel operands are canonicalized by the caller
2195 after valueizing operands of sub-expressions we have to
2196 re-canonicalize operand order. */
2197 if (operator_id *code = dyn_cast <operator_id *> (id))
2199 /* ??? We can't canonicalize tcc_comparison operands here
2200 because that requires changing the comparison code which
2201 we already matched... */
2202 if (commutative_tree_code (code->code)
2203 || commutative_ternary_tree_code (code->code))
2205 char child_opname0[20], child_opname1[20];
2206 gen_opname (child_opname0, 0);
2207 gen_opname (child_opname1, 1);
2208 fprintf_indent (f, indent,
2209 "if (tree_swap_operands_p (%s, %s, false))\n",
2210 child_opname0, child_opname1);
2211 fprintf_indent (f, indent,
2212 " std::swap (%s, %s);\n",
2213 child_opname0, child_opname1);
2217 return n_ops;
2220 /* Generate GENERIC matching code for the decision tree operand. */
2222 unsigned
2223 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2225 expr *e = static_cast<expr *> (op);
2226 unsigned n_ops = e->ops.length ();
2228 for (unsigned i = 0; i < n_ops; ++i)
2230 char child_opname[20];
2231 gen_opname (child_opname, i);
2233 if (e->operation->kind == id_base::CODE)
2234 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2235 child_opname, opname, i);
2236 else
2237 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2238 child_opname, opname, i);
2241 return 0;
2244 /* Generate matching code for the children of the decision tree node. */
2246 void
2247 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2249 auto_vec<dt_operand *> gimple_exprs;
2250 auto_vec<dt_operand *> generic_exprs;
2251 auto_vec<dt_operand *> fns;
2252 auto_vec<dt_operand *> generic_fns;
2253 auto_vec<dt_operand *> preds;
2254 auto_vec<dt_node *> others;
2256 for (unsigned i = 0; i < kids.length (); ++i)
2258 if (kids[i]->type == dt_node::DT_OPERAND)
2260 dt_operand *op = as_a<dt_operand *> (kids[i]);
2261 if (expr *e = dyn_cast <expr *> (op->op))
2263 if (e->ops.length () == 0
2264 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2265 generic_exprs.safe_push (op);
2266 else if (e->operation->kind == id_base::FN)
2268 if (gimple)
2269 fns.safe_push (op);
2270 else
2271 generic_fns.safe_push (op);
2273 else if (e->operation->kind == id_base::PREDICATE)
2274 preds.safe_push (op);
2275 else
2277 if (gimple)
2278 gimple_exprs.safe_push (op);
2279 else
2280 generic_exprs.safe_push (op);
2283 else if (op->op->type == operand::OP_PREDICATE)
2284 others.safe_push (kids[i]);
2285 else
2286 gcc_unreachable ();
2288 else if (kids[i]->type == dt_node::DT_MATCH
2289 || kids[i]->type == dt_node::DT_SIMPLIFY)
2290 others.safe_push (kids[i]);
2291 else if (kids[i]->type == dt_node::DT_TRUE)
2293 /* A DT_TRUE operand serves as a barrier - generate code now
2294 for what we have collected sofar. */
2295 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2296 fns, generic_fns, preds, others);
2297 /* And output the true operand itself. */
2298 kids[i]->gen (f, indent, gimple);
2299 gimple_exprs.truncate (0);
2300 generic_exprs.truncate (0);
2301 fns.truncate (0);
2302 generic_fns.truncate (0);
2303 preds.truncate (0);
2304 others.truncate (0);
2306 else
2307 gcc_unreachable ();
2310 /* Generate code for the remains. */
2311 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2312 fns, generic_fns, preds, others);
2315 /* Generate matching code for the children of the decision tree node. */
2317 void
2318 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2319 vec<dt_operand *> gimple_exprs,
2320 vec<dt_operand *> generic_exprs,
2321 vec<dt_operand *> fns,
2322 vec<dt_operand *> generic_fns,
2323 vec<dt_operand *> preds,
2324 vec<dt_node *> others)
2326 char buf[128];
2327 char *kid_opname = buf;
2329 unsigned exprs_len = gimple_exprs.length ();
2330 unsigned gexprs_len = generic_exprs.length ();
2331 unsigned fns_len = fns.length ();
2332 unsigned gfns_len = generic_fns.length ();
2334 if (exprs_len || fns_len || gexprs_len || gfns_len)
2336 if (exprs_len)
2337 gimple_exprs[0]->get_name (kid_opname);
2338 else if (fns_len)
2339 fns[0]->get_name (kid_opname);
2340 else if (gfns_len)
2341 generic_fns[0]->get_name (kid_opname);
2342 else
2343 generic_exprs[0]->get_name (kid_opname);
2345 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2346 fprintf_indent (f, indent, " {\n");
2347 indent += 2;
2350 if (exprs_len || fns_len)
2352 fprintf_indent (f, indent,
2353 "case SSA_NAME:\n");
2354 fprintf_indent (f, indent,
2355 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2356 kid_opname);
2357 fprintf_indent (f, indent,
2358 " {\n");
2359 fprintf_indent (f, indent,
2360 " gimple def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2361 kid_opname);
2363 indent += 6;
2364 if (exprs_len)
2366 fprintf_indent (f, indent,
2367 "if (is_gimple_assign (def_stmt))\n");
2368 fprintf_indent (f, indent,
2369 " switch (gimple_assign_rhs_code (def_stmt))\n");
2370 indent += 4;
2371 fprintf_indent (f, indent, "{\n");
2372 for (unsigned i = 0; i < exprs_len; ++i)
2374 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2375 id_base *op = e->operation;
2376 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2377 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2378 else
2379 fprintf_indent (f, indent, "case %s:\n", op->id);
2380 fprintf_indent (f, indent, " {\n");
2381 gimple_exprs[i]->gen (f, indent + 4, true);
2382 fprintf_indent (f, indent, " break;\n");
2383 fprintf_indent (f, indent, " }\n");
2385 fprintf_indent (f, indent, "default:;\n");
2386 fprintf_indent (f, indent, "}\n");
2387 indent -= 4;
2390 if (fns_len)
2392 if (exprs_len)
2393 fprintf_indent (f, indent, "else ");
2394 else
2395 fprintf_indent (f, indent, " ");
2397 fprintf (f, "if (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))\n");
2398 fprintf_indent (f, indent,
2399 " {\n");
2400 fprintf_indent (f, indent,
2401 " tree fndecl = gimple_call_fndecl (def_stmt);\n");
2402 fprintf_indent (f, indent,
2403 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2404 fprintf_indent (f, indent,
2405 " {\n");
2407 indent += 6;
2408 for (unsigned i = 0; i < fns_len; ++i)
2410 expr *e = as_a <expr *>(fns[i]->op);
2411 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2412 fprintf_indent (f, indent, " {\n");
2413 fns[i]->gen (f, indent + 4, true);
2414 fprintf_indent (f, indent, " break;\n");
2415 fprintf_indent (f, indent, " }\n");
2418 fprintf_indent (f, indent, "default:;\n");
2419 fprintf_indent (f, indent, "}\n");
2420 indent -= 6;
2421 fprintf_indent (f, indent, " }\n");
2424 indent -= 6;
2425 fprintf_indent (f, indent, " }\n");
2426 fprintf_indent (f, indent, " break;\n");
2429 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2431 expr *e = as_a <expr *>(generic_exprs[i]->op);
2432 id_base *op = e->operation;
2433 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2434 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2435 else
2436 fprintf_indent (f, indent, "case %s:\n", op->id);
2437 fprintf_indent (f, indent, " {\n");
2438 generic_exprs[i]->gen (f, indent + 4, gimple);
2439 fprintf_indent (f, indent, " break;\n");
2440 fprintf_indent (f, indent, " }\n");
2443 if (gfns_len)
2445 fprintf_indent (f, indent,
2446 "case CALL_EXPR:\n");
2447 fprintf_indent (f, indent,
2448 " {\n");
2449 fprintf_indent (f, indent,
2450 " tree fndecl = get_callee_fndecl (%s);\n",
2451 kid_opname);
2452 fprintf_indent (f, indent,
2453 " if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)\n");
2454 fprintf_indent (f, indent,
2455 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2456 fprintf_indent (f, indent,
2457 " {\n");
2458 indent += 8;
2460 for (unsigned j = 0; j < generic_fns.length (); ++j)
2462 expr *e = as_a <expr *>(generic_fns[j]->op);
2463 gcc_assert (e->operation->kind == id_base::FN);
2465 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2466 fprintf_indent (f, indent, " {\n");
2467 generic_fns[j]->gen (f, indent + 4, false);
2468 fprintf_indent (f, indent, " break;\n");
2469 fprintf_indent (f, indent, " }\n");
2472 indent -= 8;
2473 fprintf_indent (f, indent, " default:;\n");
2474 fprintf_indent (f, indent, " }\n");
2475 fprintf_indent (f, indent, " break;\n");
2476 fprintf_indent (f, indent, " }\n");
2479 /* Close switch (TREE_CODE ()). */
2480 if (exprs_len || fns_len || gexprs_len || gfns_len)
2482 indent -= 4;
2483 fprintf_indent (f, indent, " default:;\n");
2484 fprintf_indent (f, indent, " }\n");
2487 for (unsigned i = 0; i < preds.length (); ++i)
2489 expr *e = as_a <expr *> (preds[i]->op);
2490 predicate_id *p = as_a <predicate_id *> (e->operation);
2491 preds[i]->get_name (kid_opname);
2492 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2493 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2494 gimple ? "gimple" : "tree",
2495 p->id, kid_opname, kid_opname,
2496 gimple ? ", valueize" : "");
2497 fprintf_indent (f, indent, " {\n");
2498 for (int j = 0; j < p->nargs; ++j)
2500 char child_opname[20];
2501 preds[i]->gen_opname (child_opname, j);
2502 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
2503 child_opname, kid_opname, j);
2505 preds[i]->gen_kids (f, indent + 4, gimple);
2506 fprintf (f, "}\n");
2509 for (unsigned i = 0; i < others.length (); ++i)
2510 others[i]->gen (f, indent, gimple);
2513 /* Generate matching code for the decision tree operand. */
2515 void
2516 dt_operand::gen (FILE *f, int indent, bool gimple)
2518 char opname[20];
2519 get_name (opname);
2521 unsigned n_braces = 0;
2523 if (type == DT_OPERAND)
2524 switch (op->type)
2526 case operand::OP_PREDICATE:
2527 n_braces = gen_predicate (f, indent, opname, gimple);
2528 break;
2530 case operand::OP_EXPR:
2531 if (gimple)
2532 n_braces = gen_gimple_expr (f, indent);
2533 else
2534 n_braces = gen_generic_expr (f, indent, opname);
2535 break;
2537 default:
2538 gcc_unreachable ();
2540 else if (type == DT_TRUE)
2542 else if (type == DT_MATCH)
2543 n_braces = gen_match_op (f, indent, opname);
2544 else
2545 gcc_unreachable ();
2547 indent += 4 * n_braces;
2548 gen_kids (f, indent, gimple);
2550 for (unsigned i = 0; i < n_braces; ++i)
2552 indent -= 4;
2553 if (indent < 0)
2554 indent = 0;
2555 fprintf_indent (f, indent, " }\n");
2560 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2561 step of a '(simplify ...)' or '(match ...)'. This handles everything
2562 that is not part of the decision tree (simplify->match).
2563 Main recursive worker. */
2565 void
2566 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
2568 if (result)
2570 if (with_expr *w = dyn_cast <with_expr *> (result))
2572 fprintf_indent (f, indent, "{\n");
2573 indent += 4;
2574 output_line_directive (f, w->with->code[0].src_loc);
2575 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2576 gen_1 (f, indent, gimple, w->subexpr);
2577 indent -= 4;
2578 fprintf_indent (f, indent, "}\n");
2579 return;
2581 else if (if_expr *ife = dyn_cast <if_expr *> (result))
2583 output_line_directive (f, ife->cond->code[0].src_loc);
2584 fprintf_indent (f, indent, "if (");
2585 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2586 fprintf (f, ")\n");
2587 fprintf_indent (f, indent + 2, "{\n");
2588 indent += 4;
2589 gen_1 (f, indent, gimple, ife->trueexpr);
2590 indent -= 4;
2591 fprintf_indent (f, indent + 2, "}\n");
2592 if (ife->falseexpr)
2594 fprintf_indent (f, indent, "else\n");
2595 fprintf_indent (f, indent + 2, "{\n");
2596 indent += 4;
2597 gen_1 (f, indent, gimple, ife->falseexpr);
2598 indent -= 4;
2599 fprintf_indent (f, indent + 2, "}\n");
2601 return;
2605 /* Analyze captures and perform early-outs on the incoming arguments
2606 that cover cases we cannot handle. */
2607 capture_info cinfo (s, result);
2608 if (s->kind == simplify::SIMPLIFY)
2610 if (!gimple)
2612 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2613 if (cinfo.force_no_side_effects & (1 << i))
2614 fprintf_indent (f, indent,
2615 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
2617 for (int i = 0; i <= s->capture_max; ++i)
2618 if (cinfo.info[i].cse_p)
2620 else if (cinfo.info[i].force_no_side_effects_p
2621 && (cinfo.info[i].toplevel_msk
2622 & cinfo.force_no_side_effects) == 0)
2623 fprintf_indent (f, indent,
2624 "if (TREE_SIDE_EFFECTS (captures[%d])) "
2625 "return NULL_TREE;\n", i);
2626 else if ((cinfo.info[i].toplevel_msk
2627 & cinfo.force_no_side_effects) != 0)
2628 /* Mark capture as having no side-effects if we had to verify
2629 that via forced toplevel operand checks. */
2630 cinfo.info[i].force_no_side_effects_p = true;
2632 if (gimple)
2634 /* Force single-use restriction by only allowing simple
2635 results via setting seq to NULL. */
2636 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
2637 bool first_p = true;
2638 for (int i = 0; i <= s->capture_max; ++i)
2639 if (cinfo.info[i].force_single_use)
2641 if (first_p)
2643 fprintf_indent (f, indent, "if (lseq\n");
2644 fprintf_indent (f, indent, " && (");
2645 first_p = false;
2647 else
2649 fprintf (f, "\n");
2650 fprintf_indent (f, indent, " || ");
2652 fprintf (f, "!single_use (captures[%d])", i);
2654 if (!first_p)
2656 fprintf (f, "))\n");
2657 fprintf_indent (f, indent, " lseq = NULL;\n");
2662 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
2663 "fprintf (dump_file, \"Applying pattern ");
2664 output_line_directive (f, s->result_location, true);
2665 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
2667 if (!result)
2669 /* If there is no result then this is a predicate implementation. */
2670 fprintf_indent (f, indent, "return true;\n");
2672 else if (gimple)
2674 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
2675 in outermost position). */
2676 if (result->type == operand::OP_EXPR
2677 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
2678 result = as_a <expr *> (result)->ops[0];
2679 if (result->type == operand::OP_EXPR)
2681 expr *e = as_a <expr *> (result);
2682 bool is_predicate = is_a <predicate_id *> (e->operation);
2683 if (!is_predicate)
2684 fprintf_indent (f, indent, "*res_code = %s;\n",
2685 *e->operation == CONVERT_EXPR
2686 ? "NOP_EXPR" : e->operation->id);
2687 for (unsigned j = 0; j < e->ops.length (); ++j)
2689 char dest[32];
2690 snprintf (dest, 32, "res_ops[%d]", j);
2691 const char *optype
2692 = get_operand_type (e->operation,
2693 "type", e->expr_type,
2694 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
2695 /* We need to expand GENERIC conditions we captured from
2696 COND_EXPRs. */
2697 bool expand_generic_cond_exprs_p
2698 = (!is_predicate
2699 /* But avoid doing that if the GENERIC condition is
2700 valid - which it is in the first operand of COND_EXPRs
2701 and VEC_COND_EXRPs. */
2702 && ((!(*e->operation == COND_EXPR)
2703 && !(*e->operation == VEC_COND_EXPR))
2704 || j != 0));
2705 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
2706 &cinfo,
2707 indexes, expand_generic_cond_exprs_p);
2710 /* Re-fold the toplevel result. It's basically an embedded
2711 gimple_build w/o actually building the stmt. */
2712 if (!is_predicate)
2713 fprintf_indent (f, indent,
2714 "gimple_resimplify%d (lseq, res_code, type, "
2715 "res_ops, valueize);\n", e->ops.length ());
2717 else if (result->type == operand::OP_CAPTURE
2718 || result->type == operand::OP_C_EXPR)
2720 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
2721 &cinfo, indexes, false);
2722 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
2723 if (is_a <capture *> (result)
2724 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
2726 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2727 with substituting a capture of that. */
2728 fprintf_indent (f, indent,
2729 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
2730 fprintf_indent (f, indent,
2731 " {\n");
2732 fprintf_indent (f, indent,
2733 " tree tem = res_ops[0];\n");
2734 fprintf_indent (f, indent,
2735 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
2736 fprintf_indent (f, indent,
2737 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
2738 fprintf_indent (f, indent,
2739 " }\n");
2742 else
2743 gcc_unreachable ();
2744 fprintf_indent (f, indent, "return true;\n");
2746 else /* GENERIC */
2748 bool is_predicate = false;
2749 if (result->type == operand::OP_EXPR)
2751 expr *e = as_a <expr *> (result);
2752 is_predicate = is_a <predicate_id *> (e->operation);
2753 /* Search for captures used multiple times in the result expression
2754 and dependent on TREE_SIDE_EFFECTS emit a SAVE_EXPR. */
2755 if (!is_predicate)
2756 for (int i = 0; i < s->capture_max + 1; ++i)
2758 if (!cinfo.info[i].force_no_side_effects_p
2759 && cinfo.info[i].result_use_count > 1)
2761 fprintf_indent (f, indent,
2762 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
2764 fprintf_indent (f, indent,
2765 " captures[%d] = save_expr (captures[%d]);\n",
2766 i, i);
2769 for (unsigned j = 0; j < e->ops.length (); ++j)
2771 char dest[32];
2772 if (is_predicate)
2773 snprintf (dest, 32, "res_ops[%d]", j);
2774 else
2776 fprintf_indent (f, indent, "tree res_op%d;\n", j);
2777 snprintf (dest, 32, "res_op%d", j);
2779 const char *optype
2780 = get_operand_type (e->operation,
2781 "type", e->expr_type,
2782 j == 0
2783 ? NULL : "TREE_TYPE (res_op0)");
2784 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
2785 &cinfo, indexes);
2787 if (is_predicate)
2788 fprintf_indent (f, indent, "return true;\n");
2789 else
2791 fprintf_indent (f, indent, "tree res;\n");
2792 /* Re-fold the toplevel result. Use non_lvalue to
2793 build NON_LVALUE_EXPRs so they get properly
2794 ignored when in GIMPLE form. */
2795 if (*e->operation == NON_LVALUE_EXPR)
2796 fprintf_indent (f, indent,
2797 "res = non_lvalue_loc (loc, res_op0);\n");
2798 else
2800 if (e->operation->kind == id_base::CODE)
2801 fprintf_indent (f, indent,
2802 "res = fold_build%d_loc (loc, %s, type",
2803 e->ops.length (),
2804 *e->operation == CONVERT_EXPR
2805 ? "NOP_EXPR" : e->operation->id);
2806 else
2807 fprintf_indent (f, indent,
2808 "res = build_call_expr_loc "
2809 "(loc, builtin_decl_implicit (%s), %d",
2810 e->operation->id, e->ops.length());
2811 for (unsigned j = 0; j < e->ops.length (); ++j)
2812 fprintf (f, ", res_op%d", j);
2813 fprintf (f, ");\n");
2817 else if (result->type == operand::OP_CAPTURE
2818 || result->type == operand::OP_C_EXPR)
2821 fprintf_indent (f, indent, "tree res;\n");
2822 result->gen_transform (f, indent, "res", false, 1, "type",
2823 &cinfo, indexes);
2825 else
2826 gcc_unreachable ();
2827 if (!is_predicate)
2829 /* Search for captures not used in the result expression and dependent
2830 on TREE_SIDE_EFFECTS emit omit_one_operand. */
2831 for (int i = 0; i < s->capture_max + 1; ++i)
2833 if (!cinfo.info[i].force_no_side_effects_p
2834 && !cinfo.info[i].expr_p
2835 && cinfo.info[i].result_use_count == 0)
2837 fprintf_indent (f, indent,
2838 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
2840 fprintf_indent (f, indent + 2,
2841 "res = build2_loc (loc, COMPOUND_EXPR, type, "
2842 "fold_ignored_result (captures[%d]), res);\n",
2846 fprintf_indent (f, indent, "return res;\n");
2851 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2852 step of a '(simplify ...)' or '(match ...)'. This handles everything
2853 that is not part of the decision tree (simplify->match). */
2855 void
2856 dt_simplify::gen (FILE *f, int indent, bool gimple)
2858 fprintf_indent (f, indent, "{\n");
2859 indent += 2;
2860 output_line_directive (f, s->result_location);
2861 if (s->capture_max >= 0)
2862 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = {};\n",
2863 s->capture_max + 1);
2865 for (int i = 0; i <= s->capture_max; ++i)
2866 if (indexes[i])
2868 char opname[20];
2869 fprintf_indent (f, indent, "captures[%u] = %s;\n",
2870 i, indexes[i]->get_name (opname));
2873 gen_1 (f, indent, gimple, s->result);
2875 indent -= 2;
2876 fprintf_indent (f, indent, "}\n");
2879 /* Main entry to generate code for matching GIMPLE IL off the decision
2880 tree. */
2882 void
2883 decision_tree::gen_gimple (FILE *f)
2885 for (unsigned n = 1; n <= 3; ++n)
2887 fprintf (f, "\nstatic bool\n"
2888 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
2889 " gimple_seq *seq, tree (*valueize)(tree),\n"
2890 " code_helper code, tree type");
2891 for (unsigned i = 0; i < n; ++i)
2892 fprintf (f, ", tree op%d", i);
2893 fprintf (f, ")\n");
2894 fprintf (f, "{\n");
2896 fprintf (f, " switch (code.get_rep())\n"
2897 " {\n");
2898 for (unsigned i = 0; i < root->kids.length (); i++)
2900 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2901 expr *e = static_cast<expr *>(dop->op);
2902 if (e->ops.length () != n)
2903 continue;
2905 if (*e->operation == CONVERT_EXPR
2906 || *e->operation == NOP_EXPR)
2907 fprintf (f, " CASE_CONVERT:\n");
2908 else
2909 fprintf (f, " case %s%s:\n",
2910 is_a <fn_id *> (e->operation) ? "-" : "",
2911 e->operation->id);
2912 fprintf (f, " {\n");
2913 dop->gen_kids (f, 8, true);
2914 fprintf (f, " break;\n");
2915 fprintf (f, " }\n");
2917 fprintf (f, " default:;\n"
2918 " }\n");
2920 fprintf (f, " return false;\n");
2921 fprintf (f, "}\n");
2925 /* Main entry to generate code for matching GENERIC IL off the decision
2926 tree. */
2928 void
2929 decision_tree::gen_generic (FILE *f)
2931 for (unsigned n = 1; n <= 3; ++n)
2933 fprintf (f, "\ntree\n"
2934 "generic_simplify (location_t loc, enum tree_code code, "
2935 "tree type ATTRIBUTE_UNUSED");
2936 for (unsigned i = 0; i < n; ++i)
2937 fprintf (f, ", tree op%d", i);
2938 fprintf (f, ")\n");
2939 fprintf (f, "{\n");
2941 fprintf (f, " switch (code)\n"
2942 " {\n");
2943 for (unsigned i = 0; i < root->kids.length (); i++)
2945 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2946 expr *e = static_cast<expr *>(dop->op);
2947 if (e->ops.length () != n
2948 /* Builtin simplifications are somewhat premature on
2949 GENERIC. The following drops patterns with outermost
2950 calls. It's easy to emit overloads for function code
2951 though if necessary. */
2952 || e->operation->kind != id_base::CODE)
2953 continue;
2955 operator_id *op_id = static_cast <operator_id *> (e->operation);
2956 if (op_id->code == NOP_EXPR || op_id->code == CONVERT_EXPR)
2957 fprintf (f, " CASE_CONVERT:\n");
2958 else
2959 fprintf (f, " case %s:\n", e->operation->id);
2960 fprintf (f, " {\n");
2961 dop->gen_kids (f, 8, false);
2962 fprintf (f, " break;\n"
2963 " }\n");
2965 fprintf (f, " default:;\n"
2966 " }\n");
2968 fprintf (f, " return NULL_TREE;\n");
2969 fprintf (f, "}\n");
2973 /* Output code to implement the predicate P from the decision tree DT. */
2975 void
2976 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
2978 fprintf (f, "\nbool\n"
2979 "%s%s (tree t%s%s)\n"
2980 "{\n", gimple ? "gimple_" : "tree_", p->id,
2981 p->nargs > 0 ? ", tree *res_ops" : "",
2982 gimple ? ", tree (*valueize)(tree)" : "");
2983 /* Conveniently make 'type' available. */
2984 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
2986 if (!gimple)
2987 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
2988 dt.root->gen_kids (f, 2, gimple);
2990 fprintf_indent (f, 2, "return false;\n"
2991 "}\n");
2994 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
2996 static void
2997 write_header (FILE *f, const char *head)
2999 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3000 fprintf (f, " a IL pattern matching and simplification description. */\n");
3002 /* Include the header instead of writing it awkwardly quoted here. */
3003 fprintf (f, "\n#include \"%s\"\n", head);
3008 /* AST parsing. */
3010 class parser
3012 public:
3013 parser (cpp_reader *);
3015 private:
3016 const cpp_token *next ();
3017 const cpp_token *peek ();
3018 const cpp_token *peek_ident (const char * = NULL);
3019 const cpp_token *expect (enum cpp_ttype);
3020 void eat_token (enum cpp_ttype);
3021 const char *get_string ();
3022 const char *get_ident ();
3023 void eat_ident (const char *);
3024 const char *get_number ();
3026 id_base *parse_operation ();
3027 operand *parse_capture (operand *);
3028 operand *parse_expr ();
3029 c_expr *parse_c_expr (cpp_ttype);
3030 operand *parse_op ();
3032 void record_operlist (source_location, user_id *);
3034 void parse_pattern ();
3035 operand *parse_result (operand *, predicate_id *);
3036 void push_simplify (simplify::simplify_kind,
3037 vec<simplify *>&, operand *, source_location,
3038 operand *, source_location);
3039 void parse_simplify (simplify::simplify_kind,
3040 source_location, vec<simplify *>&, predicate_id *,
3041 operand *);
3042 void parse_for (source_location);
3043 void parse_if (source_location);
3044 void parse_predicates (source_location);
3045 void parse_operator_list (source_location);
3047 cpp_reader *r;
3048 vec<c_expr *> active_ifs;
3049 vec<vec<user_id *> > active_fors;
3050 hash_set<user_id *> *oper_lists_set;
3051 vec<user_id *> oper_lists;
3053 cid_map_t *capture_ids;
3055 public:
3056 vec<simplify *> simplifiers;
3057 vec<predicate_id *> user_predicates;
3058 bool parsing_match_operand;
3061 /* Lexing helpers. */
3063 /* Read the next non-whitespace token from R. */
3065 const cpp_token *
3066 parser::next ()
3068 const cpp_token *token;
3071 token = cpp_get_token (r);
3073 while (token->type == CPP_PADDING
3074 && token->type != CPP_EOF);
3075 return token;
3078 /* Peek at the next non-whitespace token from R. */
3080 const cpp_token *
3081 parser::peek ()
3083 const cpp_token *token;
3084 unsigned i = 0;
3087 token = cpp_peek_token (r, i++);
3089 while (token->type == CPP_PADDING
3090 && token->type != CPP_EOF);
3091 /* If we peek at EOF this is a fatal error as it leaves the
3092 cpp_reader in unusable state. Assume we really wanted a
3093 token and thus this EOF is unexpected. */
3094 if (token->type == CPP_EOF)
3095 fatal_at (token, "unexpected end of file");
3096 return token;
3099 /* Peek at the next identifier token (or return NULL if the next
3100 token is not an identifier or equal to ID if supplied). */
3102 const cpp_token *
3103 parser::peek_ident (const char *id)
3105 const cpp_token *token = peek ();
3106 if (token->type != CPP_NAME)
3107 return 0;
3109 if (id == 0)
3110 return token;
3112 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3113 if (strcmp (id, t) == 0)
3114 return token;
3116 return 0;
3119 /* Read the next token from R and assert it is of type TK. */
3121 const cpp_token *
3122 parser::expect (enum cpp_ttype tk)
3124 const cpp_token *token = next ();
3125 if (token->type != tk)
3126 fatal_at (token, "expected %s, got %s",
3127 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3129 return token;
3132 /* Consume the next token from R and assert it is of type TK. */
3134 void
3135 parser::eat_token (enum cpp_ttype tk)
3137 expect (tk);
3140 /* Read the next token from R and assert it is of type CPP_STRING and
3141 return its value. */
3143 const char *
3144 parser::get_string ()
3146 const cpp_token *token = expect (CPP_STRING);
3147 return (const char *)token->val.str.text;
3150 /* Read the next token from R and assert it is of type CPP_NAME and
3151 return its value. */
3153 const char *
3154 parser::get_ident ()
3156 const cpp_token *token = expect (CPP_NAME);
3157 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3160 /* Eat an identifier token with value S from R. */
3162 void
3163 parser::eat_ident (const char *s)
3165 const cpp_token *token = peek ();
3166 const char *t = get_ident ();
3167 if (strcmp (s, t) != 0)
3168 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3171 /* Read the next token from R and assert it is of type CPP_NUMBER and
3172 return its value. */
3174 const char *
3175 parser::get_number ()
3177 const cpp_token *token = expect (CPP_NUMBER);
3178 return (const char *)token->val.str.text;
3182 /* Record an operator-list use for transparent for handling. */
3184 void
3185 parser::record_operlist (source_location loc, user_id *p)
3187 if (!oper_lists_set->add (p))
3189 if (!oper_lists.is_empty ()
3190 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3191 fatal_at (loc, "User-defined operator list does not have the "
3192 "same number of entries as others used in the pattern");
3193 oper_lists.safe_push (p);
3197 /* Parse the operator ID, special-casing convert?, convert1? and
3198 convert2? */
3200 id_base *
3201 parser::parse_operation ()
3203 const cpp_token *id_tok = peek ();
3204 const char *id = get_ident ();
3205 const cpp_token *token = peek ();
3206 if (strcmp (id, "convert0") == 0)
3207 fatal_at (id_tok, "use 'convert?' here");
3208 else if (strcmp (id, "view_convert0") == 0)
3209 fatal_at (id_tok, "use 'view_convert?' here");
3210 if (token->type == CPP_QUERY
3211 && !(token->flags & PREV_WHITE))
3213 if (strcmp (id, "convert") == 0)
3214 id = "convert0";
3215 else if (strcmp (id, "convert1") == 0)
3217 else if (strcmp (id, "convert2") == 0)
3219 else if (strcmp (id, "view_convert") == 0)
3220 id = "view_convert0";
3221 else if (strcmp (id, "view_convert1") == 0)
3223 else if (strcmp (id, "view_convert2") == 0)
3225 else
3226 fatal_at (id_tok, "non-convert operator conditionalized");
3228 if (!parsing_match_operand)
3229 fatal_at (id_tok, "conditional convert can only be used in "
3230 "match expression");
3231 eat_token (CPP_QUERY);
3233 else if (strcmp (id, "convert1") == 0
3234 || strcmp (id, "convert2") == 0
3235 || strcmp (id, "view_convert1") == 0
3236 || strcmp (id, "view_convert2") == 0)
3237 fatal_at (id_tok, "expected '?' after conditional operator");
3238 id_base *op = get_operator (id);
3239 if (!op)
3240 fatal_at (id_tok, "unknown operator %s", id);
3242 user_id *p = dyn_cast<user_id *> (op);
3243 if (p && p->is_oper_list)
3245 if (active_fors.length() == 0)
3246 record_operlist (id_tok->src_loc, p);
3247 else
3248 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
3250 return op;
3253 /* Parse a capture.
3254 capture = '@'<number> */
3256 struct operand *
3257 parser::parse_capture (operand *op)
3259 eat_token (CPP_ATSIGN);
3260 const cpp_token *token = peek ();
3261 const char *id = NULL;
3262 if (token->type == CPP_NUMBER)
3263 id = get_number ();
3264 else if (token->type == CPP_NAME)
3265 id = get_ident ();
3266 else
3267 fatal_at (token, "expected number or identifier");
3268 unsigned next_id = capture_ids->elements ();
3269 bool existed;
3270 unsigned &num = capture_ids->get_or_insert (id, &existed);
3271 if (!existed)
3272 num = next_id;
3273 return new capture (num, op);
3276 /* Parse an expression
3277 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
3279 struct operand *
3280 parser::parse_expr ()
3282 expr *e = new expr (parse_operation ());
3283 const cpp_token *token = peek ();
3284 operand *op;
3285 bool is_commutative = false;
3286 bool force_capture = false;
3287 const char *expr_type = NULL;
3289 if (token->type == CPP_COLON
3290 && !(token->flags & PREV_WHITE))
3292 eat_token (CPP_COLON);
3293 token = peek ();
3294 if (token->type == CPP_NAME
3295 && !(token->flags & PREV_WHITE))
3297 const char *s = get_ident ();
3298 if (!parsing_match_operand)
3299 expr_type = s;
3300 else
3302 const char *sp = s;
3303 while (*sp)
3305 if (*sp == 'c')
3306 is_commutative = true;
3307 else if (*sp == 's')
3309 e->force_single_use = true;
3310 force_capture = true;
3312 else
3313 fatal_at (token, "flag %c not recognized", *sp);
3314 sp++;
3317 token = peek ();
3319 else
3320 fatal_at (token, "expected flag or type specifying identifier");
3323 if (token->type == CPP_ATSIGN
3324 && !(token->flags & PREV_WHITE))
3325 op = parse_capture (e);
3326 else if (force_capture)
3328 unsigned num = capture_ids->elements ();
3329 char id[8];
3330 bool existed;
3331 sprintf (id, "__%u", num);
3332 capture_ids->get_or_insert (xstrdup (id), &existed);
3333 if (existed)
3334 fatal_at (token, "reserved capture id '%s' already used", id);
3335 op = new capture (num, e);
3337 else
3338 op = e;
3341 const cpp_token *token = peek ();
3342 if (token->type == CPP_CLOSE_PAREN)
3344 if (e->operation->nargs != -1
3345 && e->operation->nargs != (int) e->ops.length ())
3346 fatal_at (token, "'%s' expects %u operands, not %u",
3347 e->operation->id, e->operation->nargs, e->ops.length ());
3348 if (is_commutative)
3350 if (e->ops.length () == 2)
3351 e->is_commutative = true;
3352 else
3353 fatal_at (token, "only binary operators or function with "
3354 "two arguments can be marked commutative");
3356 e->expr_type = expr_type;
3357 return op;
3359 e->append_op (parse_op ());
3361 while (1);
3364 /* Lex native C code delimited by START recording the preprocessing tokens
3365 for later processing.
3366 c_expr = ('{'|'(') <pp token>... ('}'|')') */
3368 c_expr *
3369 parser::parse_c_expr (cpp_ttype start)
3371 const cpp_token *token;
3372 cpp_ttype end;
3373 unsigned opencnt;
3374 vec<cpp_token> code = vNULL;
3375 unsigned nr_stmts = 0;
3376 eat_token (start);
3377 if (start == CPP_OPEN_PAREN)
3378 end = CPP_CLOSE_PAREN;
3379 else if (start == CPP_OPEN_BRACE)
3380 end = CPP_CLOSE_BRACE;
3381 else
3382 gcc_unreachable ();
3383 opencnt = 1;
3386 token = next ();
3388 /* Count brace pairs to find the end of the expr to match. */
3389 if (token->type == start)
3390 opencnt++;
3391 else if (token->type == end
3392 && --opencnt == 0)
3393 break;
3395 /* This is a lame way of counting the number of statements. */
3396 if (token->type == CPP_SEMICOLON)
3397 nr_stmts++;
3399 /* If this is possibly a user-defined identifier mark it used. */
3400 if (token->type == CPP_NAME)
3402 id_base *idb = get_operator ((const char *)CPP_HASHNODE
3403 (token->val.node.node)->ident.str);
3404 user_id *p;
3405 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
3406 record_operlist (token->src_loc, p);
3409 /* Record the token. */
3410 code.safe_push (*token);
3412 while (1);
3413 return new c_expr (r, code, nr_stmts, vNULL, capture_ids);
3416 /* Parse an operand which is either an expression, a predicate or
3417 a standalone capture.
3418 op = predicate | expr | c_expr | capture */
3420 struct operand *
3421 parser::parse_op ()
3423 const cpp_token *token = peek ();
3424 struct operand *op = NULL;
3425 if (token->type == CPP_OPEN_PAREN)
3427 eat_token (CPP_OPEN_PAREN);
3428 op = parse_expr ();
3429 eat_token (CPP_CLOSE_PAREN);
3431 else if (token->type == CPP_OPEN_BRACE)
3433 op = parse_c_expr (CPP_OPEN_BRACE);
3435 else
3437 /* Remaining ops are either empty or predicates */
3438 if (token->type == CPP_NAME)
3440 const char *id = get_ident ();
3441 id_base *opr = get_operator (id);
3442 if (!opr)
3443 fatal_at (token, "expected predicate name");
3444 if (operator_id *code = dyn_cast <operator_id *> (opr))
3446 if (code->nargs != 0)
3447 fatal_at (token, "using an operator with operands as predicate");
3448 /* Parse the zero-operand operator "predicates" as
3449 expression. */
3450 op = new expr (opr);
3452 else if (user_id *code = dyn_cast <user_id *> (opr))
3454 if (code->nargs != 0)
3455 fatal_at (token, "using an operator with operands as predicate");
3456 /* Parse the zero-operand operator "predicates" as
3457 expression. */
3458 op = new expr (opr);
3460 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
3461 op = new predicate (p);
3462 else
3463 fatal_at (token, "using an unsupported operator as predicate");
3464 if (!parsing_match_operand)
3465 fatal_at (token, "predicates are only allowed in match expression");
3466 token = peek ();
3467 if (token->flags & PREV_WHITE)
3468 return op;
3470 else if (token->type != CPP_COLON
3471 && token->type != CPP_ATSIGN)
3472 fatal_at (token, "expected expression or predicate");
3473 /* optionally followed by a capture and a predicate. */
3474 if (token->type == CPP_COLON)
3475 fatal_at (token, "not implemented: predicate on leaf operand");
3476 if (token->type == CPP_ATSIGN)
3477 op = parse_capture (op);
3480 return op;
3483 /* Create a new simplify from the current parsing state and MATCH,
3484 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
3486 void
3487 parser::push_simplify (simplify::simplify_kind kind,
3488 vec<simplify *>& simplifiers,
3489 operand *match, source_location match_loc,
3490 operand *result, source_location result_loc)
3492 /* Build and push a temporary for operator list uses in expressions. */
3493 if (!oper_lists.is_empty ())
3494 active_fors.safe_push (oper_lists);
3496 simplifiers.safe_push
3497 (new simplify (kind, match, match_loc, result, result_loc,
3498 active_fors.copy (), capture_ids));
3500 if (!oper_lists.is_empty ())
3501 active_fors.pop ();
3504 /* Parse
3505 <result-op> = <op> | <if> | <with>
3506 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
3507 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
3508 and return it. */
3510 operand *
3511 parser::parse_result (operand *result, predicate_id *matcher)
3513 const cpp_token *token = peek ();
3514 if (token->type != CPP_OPEN_PAREN)
3515 return parse_op ();
3517 eat_token (CPP_OPEN_PAREN);
3518 if (peek_ident ("if"))
3520 eat_ident ("if");
3521 if_expr *ife = new if_expr ();
3522 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
3523 if (peek ()->type == CPP_OPEN_PAREN)
3525 ife->trueexpr = parse_result (result, matcher);
3526 if (peek ()->type == CPP_OPEN_PAREN)
3527 ife->falseexpr = parse_result (result, matcher);
3528 else if (peek ()->type != CPP_CLOSE_PAREN)
3529 ife->falseexpr = parse_op ();
3531 else if (peek ()->type != CPP_CLOSE_PAREN)
3533 ife->trueexpr = parse_op ();
3534 if (peek ()->type == CPP_OPEN_PAREN)
3535 ife->falseexpr = parse_result (result, matcher);
3536 else if (peek ()->type != CPP_CLOSE_PAREN)
3537 ife->falseexpr = parse_op ();
3539 /* If this if is immediately closed then it contains a
3540 manual matcher or is part of a predicate definition. */
3541 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
3543 if (!matcher)
3544 fatal_at (peek (), "manual transform not implemented");
3546 eat_token (CPP_CLOSE_PAREN);
3547 return ife;
3549 else if (peek_ident ("with"))
3551 eat_ident ("with");
3552 with_expr *withe = new with_expr ();
3553 /* Parse (with c-expr expr) as (if-with (true) expr). */
3554 withe->with = parse_c_expr (CPP_OPEN_BRACE);
3555 withe->with->nr_stmts = 0;
3556 withe->subexpr = parse_result (result, matcher);
3557 eat_token (CPP_CLOSE_PAREN);
3558 return withe;
3560 else
3562 operand *op = result;
3563 if (!matcher)
3564 op = parse_expr ();
3565 eat_token (CPP_CLOSE_PAREN);
3566 return op;
3570 /* Parse
3571 simplify = 'simplify' <expr> <result-op>
3573 match = 'match' <ident> <expr> [<result-op>]
3574 and fill SIMPLIFIERS with the results. */
3576 void
3577 parser::parse_simplify (simplify::simplify_kind kind,
3578 source_location match_location,
3579 vec<simplify *>& simplifiers, predicate_id *matcher,
3580 operand *result)
3582 /* Reset the capture map. */
3583 if (!capture_ids)
3584 capture_ids = new cid_map_t;
3585 /* Reset oper_lists and set. */
3586 hash_set <user_id *> olist;
3587 oper_lists_set = &olist;
3588 oper_lists = vNULL;
3590 const cpp_token *loc = peek ();
3591 parsing_match_operand = true;
3592 struct operand *match = parse_op ();
3593 parsing_match_operand = false;
3594 if (match->type == operand::OP_CAPTURE && !matcher)
3595 fatal_at (loc, "outermost expression cannot be captured");
3596 if (match->type == operand::OP_EXPR
3597 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
3598 fatal_at (loc, "outermost expression cannot be a predicate");
3600 /* Splice active_ifs onto result and continue parsing the
3601 "then" expr. */
3602 if_expr *active_if = NULL;
3603 for (int i = active_ifs.length (); i > 0; --i)
3605 if_expr *ifc = new if_expr ();
3606 ifc->cond = active_ifs[i-1];
3607 ifc->trueexpr = active_if;
3608 active_if = ifc;
3610 if_expr *outermost_if = active_if;
3611 while (active_if && active_if->trueexpr)
3612 active_if = as_a <if_expr *> (active_if->trueexpr);
3614 const cpp_token *token = peek ();
3616 /* If this if is immediately closed then it is part of a predicate
3617 definition. Push it. */
3618 if (token->type == CPP_CLOSE_PAREN)
3620 if (!matcher)
3621 fatal_at (token, "expected transform expression");
3622 if (active_if)
3624 active_if->trueexpr = result;
3625 result = outermost_if;
3627 push_simplify (kind, simplifiers, match, match_location,
3628 result, token->src_loc);
3629 return;
3632 operand *tem = parse_result (result, matcher);
3633 if (active_if)
3635 active_if->trueexpr = tem;
3636 result = outermost_if;
3638 else
3639 result = tem;
3641 push_simplify (kind, simplifiers, match, match_location,
3642 result, token->src_loc);
3645 /* Parsing of the outer control structures. */
3647 /* Parse a for expression
3648 for = '(' 'for' <subst>... <pattern> ')'
3649 subst = <ident> '(' <ident>... ')' */
3651 void
3652 parser::parse_for (source_location)
3654 auto_vec<const cpp_token *> user_id_tokens;
3655 vec<user_id *> user_ids = vNULL;
3656 const cpp_token *token;
3657 unsigned min_n_opers = 0, max_n_opers = 0;
3659 while (1)
3661 token = peek ();
3662 if (token->type != CPP_NAME)
3663 break;
3665 /* Insert the user defined operators into the operator hash. */
3666 const char *id = get_ident ();
3667 if (get_operator (id) != NULL)
3668 fatal_at (token, "operator already defined");
3669 user_id *op = new user_id (id);
3670 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3671 *slot = op;
3672 user_ids.safe_push (op);
3673 user_id_tokens.safe_push (token);
3675 eat_token (CPP_OPEN_PAREN);
3677 int arity = -1;
3678 while ((token = peek_ident ()) != 0)
3680 const char *oper = get_ident ();
3681 id_base *idb = get_operator (oper);
3682 if (idb == NULL)
3683 fatal_at (token, "no such operator '%s'", oper);
3684 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
3685 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
3686 || *idb == VIEW_CONVERT2)
3687 fatal_at (token, "conditional operators cannot be used inside for");
3689 if (arity == -1)
3690 arity = idb->nargs;
3691 else if (idb->nargs == -1)
3693 else if (idb->nargs != arity)
3694 fatal_at (token, "operator '%s' with arity %d does not match "
3695 "others with arity %d", oper, idb->nargs, arity);
3697 user_id *p = dyn_cast<user_id *> (idb);
3698 if (p)
3700 if (p->is_oper_list)
3701 op->substitutes.safe_splice (p->substitutes);
3702 else
3703 fatal_at (token, "iterator cannot be used as operator-list");
3705 else
3706 op->substitutes.safe_push (idb);
3708 op->nargs = arity;
3709 token = expect (CPP_CLOSE_PAREN);
3711 unsigned nsubstitutes = op->substitutes.length ();
3712 if (nsubstitutes == 0)
3713 fatal_at (token, "A user-defined operator must have at least "
3714 "one substitution");
3715 if (max_n_opers == 0)
3717 min_n_opers = nsubstitutes;
3718 max_n_opers = nsubstitutes;
3720 else
3722 if (nsubstitutes % min_n_opers != 0
3723 && min_n_opers % nsubstitutes != 0)
3724 fatal_at (token, "All user-defined identifiers must have a "
3725 "multiple number of operator substitutions of the "
3726 "smallest number of substitutions");
3727 if (nsubstitutes < min_n_opers)
3728 min_n_opers = nsubstitutes;
3729 else if (nsubstitutes > max_n_opers)
3730 max_n_opers = nsubstitutes;
3734 unsigned n_ids = user_ids.length ();
3735 if (n_ids == 0)
3736 fatal_at (token, "for requires at least one user-defined identifier");
3738 token = peek ();
3739 if (token->type == CPP_CLOSE_PAREN)
3740 fatal_at (token, "no pattern defined in for");
3742 active_fors.safe_push (user_ids);
3743 while (1)
3745 token = peek ();
3746 if (token->type == CPP_CLOSE_PAREN)
3747 break;
3748 parse_pattern ();
3750 active_fors.pop ();
3752 /* Remove user-defined operators from the hash again. */
3753 for (unsigned i = 0; i < user_ids.length (); ++i)
3755 if (!user_ids[i]->used)
3756 warning_at (user_id_tokens[i],
3757 "operator %s defined but not used", user_ids[i]->id);
3758 operators->remove_elt (user_ids[i]);
3762 /* Parse an identifier associated with a list of operators.
3763 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
3765 void
3766 parser::parse_operator_list (source_location)
3768 const cpp_token *token = peek ();
3769 const char *id = get_ident ();
3771 if (get_operator (id) != 0)
3772 fatal_at (token, "operator %s already defined", id);
3774 user_id *op = new user_id (id, true);
3775 int arity = -1;
3777 while ((token = peek_ident ()) != 0)
3779 token = peek ();
3780 const char *oper = get_ident ();
3781 id_base *idb = get_operator (oper);
3783 if (idb == 0)
3784 fatal_at (token, "no such operator '%s'", oper);
3786 if (arity == -1)
3787 arity = idb->nargs;
3788 else if (idb->nargs == -1)
3790 else if (arity != idb->nargs)
3791 fatal_at (token, "operator '%s' with arity %d does not match "
3792 "others with arity %d", oper, idb->nargs, arity);
3794 /* We allow composition of multiple operator lists. */
3795 if (user_id *p = dyn_cast<user_id *> (idb))
3796 op->substitutes.safe_splice (p->substitutes);
3797 else
3798 op->substitutes.safe_push (idb);
3801 // Check that there is no junk after id-list
3802 token = peek();
3803 if (token->type != CPP_CLOSE_PAREN)
3804 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
3806 if (op->substitutes.length () == 0)
3807 fatal_at (token, "operator-list cannot be empty");
3809 op->nargs = arity;
3810 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3811 *slot = op;
3814 /* Parse an outer if expression.
3815 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
3817 void
3818 parser::parse_if (source_location)
3820 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
3822 const cpp_token *token = peek ();
3823 if (token->type == CPP_CLOSE_PAREN)
3824 fatal_at (token, "no pattern defined in if");
3826 active_ifs.safe_push (ifexpr);
3827 while (1)
3829 const cpp_token *token = peek ();
3830 if (token->type == CPP_CLOSE_PAREN)
3831 break;
3833 parse_pattern ();
3835 active_ifs.pop ();
3838 /* Parse a list of predefined predicate identifiers.
3839 preds = '(' 'define_predicates' <ident>... ')' */
3841 void
3842 parser::parse_predicates (source_location)
3846 const cpp_token *token = peek ();
3847 if (token->type != CPP_NAME)
3848 break;
3850 add_predicate (get_ident ());
3852 while (1);
3855 /* Parse outer control structures.
3856 pattern = <preds>|<for>|<if>|<simplify>|<match> */
3858 void
3859 parser::parse_pattern ()
3861 /* All clauses start with '('. */
3862 eat_token (CPP_OPEN_PAREN);
3863 const cpp_token *token = peek ();
3864 const char *id = get_ident ();
3865 if (strcmp (id, "simplify") == 0)
3867 parse_simplify (simplify::SIMPLIFY,
3868 token->src_loc, simplifiers, NULL, NULL);
3869 capture_ids = NULL;
3871 else if (strcmp (id, "match") == 0)
3873 bool with_args = false;
3874 if (peek ()->type == CPP_OPEN_PAREN)
3876 eat_token (CPP_OPEN_PAREN);
3877 with_args = true;
3879 const char *name = get_ident ();
3880 id_base *id = get_operator (name);
3881 predicate_id *p;
3882 if (!id)
3884 p = add_predicate (name);
3885 user_predicates.safe_push (p);
3887 else if ((p = dyn_cast <predicate_id *> (id)))
3889 else
3890 fatal_at (token, "cannot add a match to a non-predicate ID");
3891 /* Parse (match <id> <arg>... (match-expr)) here. */
3892 expr *e = NULL;
3893 if (with_args)
3895 capture_ids = new cid_map_t;
3896 e = new expr (p);
3897 while (peek ()->type == CPP_ATSIGN)
3898 e->append_op (parse_capture (NULL));
3899 eat_token (CPP_CLOSE_PAREN);
3901 if (p->nargs != -1
3902 && ((e && e->ops.length () != (unsigned)p->nargs)
3903 || (!e && p->nargs != 0)))
3904 fatal_at (token, "non-matching number of match operands");
3905 p->nargs = e ? e->ops.length () : 0;
3906 parse_simplify (simplify::MATCH, token->src_loc, p->matchers, p, e);
3907 capture_ids = NULL;
3909 else if (strcmp (id, "for") == 0)
3910 parse_for (token->src_loc);
3911 else if (strcmp (id, "if") == 0)
3912 parse_if (token->src_loc);
3913 else if (strcmp (id, "define_predicates") == 0)
3915 if (active_ifs.length () > 0
3916 || active_fors.length () > 0)
3917 fatal_at (token, "define_predicates inside if or for is not supported");
3918 parse_predicates (token->src_loc);
3920 else if (strcmp (id, "define_operator_list") == 0)
3922 if (active_ifs.length () > 0
3923 || active_fors.length () > 0)
3924 fatal_at (token, "operator-list inside if or for is not supported");
3925 parse_operator_list (token->src_loc);
3927 else
3928 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
3929 active_ifs.length () == 0 && active_fors.length () == 0
3930 ? "'define_predicates', " : "");
3932 eat_token (CPP_CLOSE_PAREN);
3935 /* Main entry of the parser. Repeatedly parse outer control structures. */
3937 parser::parser (cpp_reader *r_)
3939 r = r_;
3940 active_ifs = vNULL;
3941 active_fors = vNULL;
3942 simplifiers = vNULL;
3943 oper_lists_set = NULL;
3944 oper_lists = vNULL;
3945 capture_ids = NULL;
3946 user_predicates = vNULL;
3947 parsing_match_operand = false;
3949 const cpp_token *token = next ();
3950 while (token->type != CPP_EOF)
3952 _cpp_backup_tokens (r, 1);
3953 parse_pattern ();
3954 token = next ();
3959 /* Helper for the linemap code. */
3961 static size_t
3962 round_alloc_size (size_t s)
3964 return s;
3968 /* The genmatch generator progam. It reads from a pattern description
3969 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
3972 main (int argc, char **argv)
3974 cpp_reader *r;
3976 progname = "genmatch";
3978 if (argc < 2)
3979 return 1;
3981 bool gimple = true;
3982 bool verbose = false;
3983 char *input = argv[argc-1];
3984 for (int i = 1; i < argc - 1; ++i)
3986 if (strcmp (argv[i], "--gimple") == 0)
3987 gimple = true;
3988 else if (strcmp (argv[i], "--generic") == 0)
3989 gimple = false;
3990 else if (strcmp (argv[i], "-v") == 0)
3991 verbose = true;
3992 else
3994 fprintf (stderr, "Usage: genmatch "
3995 "[--gimple] [--generic] [-v] input\n");
3996 return 1;
4000 line_table = XCNEW (struct line_maps);
4001 linemap_init (line_table, 0);
4002 line_table->reallocator = xrealloc;
4003 line_table->round_alloc_size = round_alloc_size;
4005 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4006 cpp_callbacks *cb = cpp_get_callbacks (r);
4007 cb->error = error_cb;
4009 if (!cpp_read_main_file (r, input))
4010 return 1;
4011 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4012 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4014 /* Pre-seed operators. */
4015 operators = new hash_table<id_base> (1024);
4016 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4017 add_operator (SYM, # SYM, # TYPE, NARGS);
4018 #define END_OF_BASE_TREE_CODES
4019 #include "tree.def"
4020 add_operator (CONVERT0, "CONVERT0", "tcc_unary", 1);
4021 add_operator (CONVERT1, "CONVERT1", "tcc_unary", 1);
4022 add_operator (CONVERT2, "CONVERT2", "tcc_unary", 1);
4023 add_operator (VIEW_CONVERT0, "VIEW_CONVERT0", "tcc_unary", 1);
4024 add_operator (VIEW_CONVERT1, "VIEW_CONVERT1", "tcc_unary", 1);
4025 add_operator (VIEW_CONVERT2, "VIEW_CONVERT2", "tcc_unary", 1);
4026 #undef END_OF_BASE_TREE_CODES
4027 #undef DEFTREECODE
4029 /* Pre-seed builtin functions.
4030 ??? Cannot use N (name) as that is targetm.emultls.get_address
4031 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4032 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4033 add_builtin (ENUM, # ENUM);
4034 #include "builtins.def"
4035 #undef DEF_BUILTIN
4037 /* Parse ahead! */
4038 parser p (r);
4040 if (gimple)
4041 write_header (stdout, "gimple-match-head.c");
4042 else
4043 write_header (stdout, "generic-match-head.c");
4045 /* Go over all predicates defined with patterns and perform
4046 lowering and code generation. */
4047 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
4049 predicate_id *pred = p.user_predicates[i];
4050 lower (pred->matchers, gimple);
4052 if (verbose)
4053 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4054 print_matches (pred->matchers[i]);
4056 decision_tree dt;
4057 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4058 dt.insert (pred->matchers[i], i);
4060 if (verbose)
4061 dt.print (stderr);
4063 write_predicate (stdout, pred, dt, gimple);
4066 /* Lower the main simplifiers and generate code for them. */
4067 lower (p.simplifiers, gimple);
4069 if (verbose)
4070 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4071 print_matches (p.simplifiers[i]);
4073 decision_tree dt;
4074 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4075 dt.insert (p.simplifiers[i], i);
4077 if (verbose)
4078 dt.print (stderr);
4080 if (gimple)
4081 dt.gen_gimple (stdout);
4082 else
4083 dt.gen_generic (stdout);
4085 /* Finalize. */
4086 cpp_finish (r, NULL);
4087 cpp_destroy (r);
4089 delete operators;
4091 return 0;