Configury changes for obstack optimization
[official-gcc.git] / gcc / genmatch.c
blob1eb8c24da7d4e673c877ed46b79e48df45bf3f26
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 /* Global state. */
48 /* Verboseness. 0 is quiet, 1 adds some warnings, 2 is for debugging. */
49 unsigned verbose;
52 /* libccp helpers. */
54 static struct line_maps *line_table;
56 /* The rich_location class within libcpp requires a way to expand
57 source_location instances, and relies on the client code
58 providing a symbol named
59 linemap_client_expand_location_to_spelling_point
60 to do this.
62 This is the implementation for genmatch. */
64 expanded_location
65 linemap_client_expand_location_to_spelling_point (source_location loc)
67 const struct line_map_ordinary *map;
68 loc = linemap_resolve_location (line_table, loc, LRK_SPELLING_LOCATION, &map);
69 return linemap_expand_location (line_table, map, loc);
72 static bool
73 #if GCC_VERSION >= 4001
74 __attribute__((format (printf, 5, 0)))
75 #endif
76 error_cb (cpp_reader *, int errtype, int, rich_location *richloc,
77 const char *msg, va_list *ap)
79 const line_map_ordinary *map;
80 source_location location = richloc->get_loc ();
81 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
82 expanded_location loc = linemap_expand_location (line_table, map, location);
83 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
84 (errtype == CPP_DL_WARNING) ? "warning" : "error");
85 vfprintf (stderr, msg, *ap);
86 fprintf (stderr, "\n");
87 FILE *f = fopen (loc.file, "r");
88 if (f)
90 char buf[128];
91 while (loc.line > 0)
93 if (!fgets (buf, 128, f))
94 goto notfound;
95 if (buf[strlen (buf) - 1] != '\n')
97 if (loc.line > 1)
98 loc.line++;
100 loc.line--;
102 fprintf (stderr, "%s", buf);
103 for (int i = 0; i < loc.column - 1; ++i)
104 fputc (' ', stderr);
105 fputc ('^', stderr);
106 fputc ('\n', stderr);
107 notfound:
108 fclose (f);
111 if (errtype == CPP_DL_FATAL)
112 exit (1);
113 return false;
116 static void
117 #if GCC_VERSION >= 4001
118 __attribute__((format (printf, 2, 3)))
119 #endif
120 fatal_at (const cpp_token *tk, const char *msg, ...)
122 rich_location richloc (tk->src_loc);
123 va_list ap;
124 va_start (ap, msg);
125 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
126 va_end (ap);
129 static void
130 #if GCC_VERSION >= 4001
131 __attribute__((format (printf, 2, 3)))
132 #endif
133 fatal_at (source_location loc, const char *msg, ...)
135 rich_location richloc (loc);
136 va_list ap;
137 va_start (ap, msg);
138 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
139 va_end (ap);
142 static void
143 #if GCC_VERSION >= 4001
144 __attribute__((format (printf, 2, 3)))
145 #endif
146 warning_at (const cpp_token *tk, const char *msg, ...)
148 rich_location richloc (tk->src_loc);
149 va_list ap;
150 va_start (ap, msg);
151 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
152 va_end (ap);
155 static void
156 #if GCC_VERSION >= 4001
157 __attribute__((format (printf, 2, 3)))
158 #endif
159 warning_at (source_location loc, const char *msg, ...)
161 rich_location richloc (loc);
162 va_list ap;
163 va_start (ap, msg);
164 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
165 va_end (ap);
168 /* Like fprintf, but print INDENT spaces at the beginning. */
170 static void
171 #if GCC_VERSION >= 4001
172 __attribute__((format (printf, 3, 4)))
173 #endif
174 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
176 va_list ap;
177 for (; indent >= 8; indent -= 8)
178 fputc ('\t', f);
179 fprintf (f, "%*s", indent, "");
180 va_start (ap, format);
181 vfprintf (f, format, ap);
182 va_end (ap);
185 static void
186 output_line_directive (FILE *f, source_location location,
187 bool dumpfile = false)
189 const line_map_ordinary *map;
190 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
191 expanded_location loc = linemap_expand_location (line_table, map, location);
192 if (dumpfile)
194 /* When writing to a dumpfile only dump the filename. */
195 const char *file = strrchr (loc.file, DIR_SEPARATOR);
196 if (!file)
197 file = loc.file;
198 else
199 ++file;
200 fprintf (f, "%s:%d", file, loc.line);
202 else
203 /* Other gen programs really output line directives here, at least for
204 development it's right now more convenient to have line information
205 from the generated file. Still keep the directives as comment for now
206 to easily back-point to the meta-description. */
207 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
211 /* Pull in tree codes and builtin function codes from their
212 definition files. */
214 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
215 enum tree_code {
216 #include "tree.def"
217 CONVERT0,
218 CONVERT1,
219 CONVERT2,
220 VIEW_CONVERT0,
221 VIEW_CONVERT1,
222 VIEW_CONVERT2,
223 MAX_TREE_CODES
225 #undef DEFTREECODE
227 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
228 enum built_in_function {
229 #include "builtins.def"
230 END_BUILTINS
233 /* Return true if CODE represents a commutative tree code. Otherwise
234 return false. */
235 bool
236 commutative_tree_code (enum tree_code code)
238 switch (code)
240 case PLUS_EXPR:
241 case MULT_EXPR:
242 case MULT_HIGHPART_EXPR:
243 case MIN_EXPR:
244 case MAX_EXPR:
245 case BIT_IOR_EXPR:
246 case BIT_XOR_EXPR:
247 case BIT_AND_EXPR:
248 case NE_EXPR:
249 case EQ_EXPR:
250 case UNORDERED_EXPR:
251 case ORDERED_EXPR:
252 case UNEQ_EXPR:
253 case LTGT_EXPR:
254 case TRUTH_AND_EXPR:
255 case TRUTH_XOR_EXPR:
256 case TRUTH_OR_EXPR:
257 case WIDEN_MULT_EXPR:
258 case VEC_WIDEN_MULT_HI_EXPR:
259 case VEC_WIDEN_MULT_LO_EXPR:
260 case VEC_WIDEN_MULT_EVEN_EXPR:
261 case VEC_WIDEN_MULT_ODD_EXPR:
262 return true;
264 default:
265 break;
267 return false;
270 /* Return true if CODE represents a ternary tree code for which the
271 first two operands are commutative. Otherwise return false. */
272 bool
273 commutative_ternary_tree_code (enum tree_code code)
275 switch (code)
277 case WIDEN_MULT_PLUS_EXPR:
278 case WIDEN_MULT_MINUS_EXPR:
279 case DOT_PROD_EXPR:
280 case FMA_EXPR:
281 return true;
283 default:
284 break;
286 return false;
290 /* Base class for all identifiers the parser knows. */
292 struct id_base : nofree_ptr_hash<id_base>
294 enum id_kind { CODE, FN, PREDICATE, USER } kind;
296 id_base (id_kind, const char *, int = -1);
298 hashval_t hashval;
299 int nargs;
300 const char *id;
302 /* hash_table support. */
303 static inline hashval_t hash (const id_base *);
304 static inline int equal (const id_base *, const id_base *);
307 inline hashval_t
308 id_base::hash (const id_base *op)
310 return op->hashval;
313 inline int
314 id_base::equal (const id_base *op1,
315 const id_base *op2)
317 return (op1->hashval == op2->hashval
318 && strcmp (op1->id, op2->id) == 0);
321 /* Hashtable of known pattern operators. This is pre-seeded from
322 all known tree codes and all known builtin function ids. */
323 static hash_table<id_base> *operators;
325 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
327 kind = kind_;
328 id = id_;
329 nargs = nargs_;
330 hashval = htab_hash_string (id);
333 /* Identifier that maps to a tree code. */
335 struct operator_id : public id_base
337 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
338 const char *tcc_)
339 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
340 enum tree_code code;
341 const char *tcc;
344 /* Identifier that maps to a builtin function code. */
346 struct fn_id : public id_base
348 fn_id (enum built_in_function fn_, const char *id_)
349 : id_base (id_base::FN, id_), fn (fn_) {}
350 enum built_in_function fn;
353 struct simplify;
355 /* Identifier that maps to a user-defined predicate. */
357 struct predicate_id : public id_base
359 predicate_id (const char *id_)
360 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
361 vec<simplify *> matchers;
364 /* Identifier that maps to a operator defined by a 'for' directive. */
366 struct user_id : public id_base
368 user_id (const char *id_, bool is_oper_list_ = false)
369 : id_base (id_base::USER, id_), substitutes (vNULL),
370 used (false), is_oper_list (is_oper_list_) {}
371 vec<id_base *> substitutes;
372 bool used;
373 bool is_oper_list;
376 template<>
377 template<>
378 inline bool
379 is_a_helper <fn_id *>::test (id_base *id)
381 return id->kind == id_base::FN;
384 template<>
385 template<>
386 inline bool
387 is_a_helper <operator_id *>::test (id_base *id)
389 return id->kind == id_base::CODE;
392 template<>
393 template<>
394 inline bool
395 is_a_helper <predicate_id *>::test (id_base *id)
397 return id->kind == id_base::PREDICATE;
400 template<>
401 template<>
402 inline bool
403 is_a_helper <user_id *>::test (id_base *id)
405 return id->kind == id_base::USER;
408 /* Add a predicate identifier to the hash. */
410 static predicate_id *
411 add_predicate (const char *id)
413 predicate_id *p = new predicate_id (id);
414 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
415 if (*slot)
416 fatal ("duplicate id definition");
417 *slot = p;
418 return p;
421 /* Add a tree code identifier to the hash. */
423 static void
424 add_operator (enum tree_code code, const char *id,
425 const char *tcc, unsigned nargs)
427 if (strcmp (tcc, "tcc_unary") != 0
428 && strcmp (tcc, "tcc_binary") != 0
429 && strcmp (tcc, "tcc_comparison") != 0
430 && strcmp (tcc, "tcc_expression") != 0
431 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
432 && strcmp (tcc, "tcc_reference") != 0
433 /* To have INTEGER_CST and friends as "predicate operators". */
434 && strcmp (tcc, "tcc_constant") != 0
435 /* And allow CONSTRUCTOR for vector initializers. */
436 && !(code == CONSTRUCTOR)
437 /* Allow SSA_NAME as predicate operator. */
438 && !(code == SSA_NAME))
439 return;
440 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
441 if (code == ADDR_EXPR)
442 nargs = 0;
443 operator_id *op = new operator_id (code, id, nargs, tcc);
444 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
445 if (*slot)
446 fatal ("duplicate id definition");
447 *slot = op;
450 /* Add a builtin identifier to the hash. */
452 static void
453 add_builtin (enum built_in_function code, const char *id)
455 fn_id *fn = new fn_id (code, id);
456 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
457 if (*slot)
458 fatal ("duplicate id definition");
459 *slot = fn;
462 /* Helper for easy comparing ID with tree code CODE. */
464 static bool
465 operator==(id_base &id, enum tree_code code)
467 if (operator_id *oid = dyn_cast <operator_id *> (&id))
468 return oid->code == code;
469 return false;
472 /* Lookup the identifier ID. */
474 id_base *
475 get_operator (const char *id)
477 id_base tem (id_base::CODE, id);
479 id_base *op = operators->find_with_hash (&tem, tem.hashval);
480 if (op)
482 /* If this is a user-defined identifier track whether it was used. */
483 if (user_id *uid = dyn_cast<user_id *> (op))
484 uid->used = true;
485 return op;
488 /* Try all-uppercase. */
489 char *id2 = xstrdup (id);
490 for (unsigned i = 0; i < strlen (id2); ++i)
491 id2[i] = TOUPPER (id2[i]);
492 new (&tem) id_base (id_base::CODE, id2);
493 op = operators->find_with_hash (&tem, tem.hashval);
494 if (op)
496 free (id2);
497 return op;
500 /* Try _EXPR appended. */
501 id2 = (char *)xrealloc (id2, strlen (id2) + sizeof ("_EXPR") + 1);
502 strcat (id2, "_EXPR");
503 new (&tem) id_base (id_base::CODE, id2);
504 op = operators->find_with_hash (&tem, tem.hashval);
505 if (op)
507 free (id2);
508 return op;
511 return 0;
514 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
517 /* The AST produced by parsing of the pattern definitions. */
519 struct dt_operand;
520 struct capture_info;
522 /* The base class for operands. */
524 struct operand {
525 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
526 operand (enum op_type type_, source_location loc_)
527 : type (type_), location (loc_) {}
528 enum op_type type;
529 source_location location;
530 virtual void gen_transform (FILE *, int, const char *, bool, int,
531 const char *, capture_info *,
532 dt_operand ** = 0,
533 bool = true)
534 { gcc_unreachable (); }
537 /* A predicate operand. Predicates are leafs in the AST. */
539 struct predicate : public operand
541 predicate (predicate_id *p_, source_location loc)
542 : operand (OP_PREDICATE, loc), p (p_) {}
543 predicate_id *p;
546 /* An operand that constitutes an expression. Expressions include
547 function calls and user-defined predicate invocations. */
549 struct expr : public operand
551 expr (id_base *operation_, source_location loc, bool is_commutative_ = false)
552 : operand (OP_EXPR, loc), operation (operation_),
553 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
554 is_generic (false), force_single_use (false) {}
555 expr (expr *e)
556 : operand (OP_EXPR, e->location), operation (e->operation),
557 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
558 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
559 void append_op (operand *op) { ops.safe_push (op); }
560 /* The operator and its operands. */
561 id_base *operation;
562 vec<operand *> ops;
563 /* An explicitely specified type - used exclusively for conversions. */
564 const char *expr_type;
565 /* Whether the operation is to be applied commutatively. This is
566 later lowered to two separate patterns. */
567 bool is_commutative;
568 /* Whether the expression is expected to be in GENERIC form. */
569 bool is_generic;
570 /* Whether pushing any stmt to the sequence should be conditional
571 on this expression having a single-use. */
572 bool force_single_use;
573 virtual void gen_transform (FILE *f, int, const char *, bool, int,
574 const char *, capture_info *,
575 dt_operand ** = 0, bool = true);
578 /* An operator that is represented by native C code. This is always
579 a leaf operand in the AST. This class is also used to represent
580 the code to be generated for 'if' and 'with' expressions. */
582 struct c_expr : public operand
584 /* A mapping of an identifier and its replacement. Used to apply
585 'for' lowering. */
586 struct id_tab {
587 const char *id;
588 const char *oper;
589 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
592 c_expr (cpp_reader *r_, source_location loc,
593 vec<cpp_token> code_, unsigned nr_stmts_,
594 vec<id_tab> ids_, cid_map_t *capture_ids_)
595 : operand (OP_C_EXPR, loc), r (r_), code (code_),
596 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
597 /* cpplib tokens and state to transform this back to source. */
598 cpp_reader *r;
599 vec<cpp_token> code;
600 cid_map_t *capture_ids;
601 /* The number of statements parsed (well, the number of ';'s). */
602 unsigned nr_stmts;
603 /* The identifier replacement vector. */
604 vec<id_tab> ids;
605 virtual void gen_transform (FILE *f, int, const char *, bool, int,
606 const char *, capture_info *,
607 dt_operand ** = 0, bool = true);
610 /* A wrapper around another operand that captures its value. */
612 struct capture : public operand
614 capture (source_location loc, unsigned where_, operand *what_)
615 : operand (OP_CAPTURE, loc), where (where_), what (what_) {}
616 /* Identifier index for the value. */
617 unsigned where;
618 /* The captured value. */
619 operand *what;
620 virtual void gen_transform (FILE *f, int, const char *, bool, int,
621 const char *, capture_info *,
622 dt_operand ** = 0, bool = true);
625 /* if expression. */
627 struct if_expr : public operand
629 if_expr (source_location loc)
630 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
631 c_expr *cond;
632 operand *trueexpr;
633 operand *falseexpr;
636 /* with expression. */
638 struct with_expr : public operand
640 with_expr (source_location loc)
641 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
642 c_expr *with;
643 operand *subexpr;
646 template<>
647 template<>
648 inline bool
649 is_a_helper <capture *>::test (operand *op)
651 return op->type == operand::OP_CAPTURE;
654 template<>
655 template<>
656 inline bool
657 is_a_helper <predicate *>::test (operand *op)
659 return op->type == operand::OP_PREDICATE;
662 template<>
663 template<>
664 inline bool
665 is_a_helper <c_expr *>::test (operand *op)
667 return op->type == operand::OP_C_EXPR;
670 template<>
671 template<>
672 inline bool
673 is_a_helper <expr *>::test (operand *op)
675 return op->type == operand::OP_EXPR;
678 template<>
679 template<>
680 inline bool
681 is_a_helper <if_expr *>::test (operand *op)
683 return op->type == operand::OP_IF;
686 template<>
687 template<>
688 inline bool
689 is_a_helper <with_expr *>::test (operand *op)
691 return op->type == operand::OP_WITH;
694 /* The main class of a pattern and its transform. This is used to
695 represent both (simplify ...) and (match ...) kinds. The AST
696 duplicates all outer 'if' and 'for' expressions here so each
697 simplify can exist in isolation. */
699 struct simplify
701 enum simplify_kind { SIMPLIFY, MATCH };
703 simplify (simplify_kind kind_, operand *match_, operand *result_,
704 vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
705 : kind (kind_), match (match_), result (result_),
706 for_vec (for_vec_), for_subst_vec (vNULL),
707 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
709 simplify_kind kind;
710 /* The expression that is matched against the GENERIC or GIMPLE IL. */
711 operand *match;
712 /* For a (simplify ...) an expression with ifs and withs with the expression
713 produced when the pattern applies in the leafs.
714 For a (match ...) the leafs are either empty if it is a simple predicate
715 or the single expression specifying the matched operands. */
716 struct operand *result;
717 /* Collected 'for' expression operators that have to be replaced
718 in the lowering phase. */
719 vec<vec<user_id *> > for_vec;
720 vec<std::pair<user_id *, id_base *> > for_subst_vec;
721 /* A map of capture identifiers to indexes. */
722 cid_map_t *capture_ids;
723 int capture_max;
726 /* Debugging routines for dumping the AST. */
728 DEBUG_FUNCTION void
729 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
731 if (capture *c = dyn_cast<capture *> (o))
733 if (c->what && flattened == false)
734 print_operand (c->what, f, flattened);
735 fprintf (f, "@%u", c->where);
738 else if (predicate *p = dyn_cast<predicate *> (o))
739 fprintf (f, "%s", p->p->id);
741 else if (is_a<c_expr *> (o))
742 fprintf (f, "c_expr");
744 else if (expr *e = dyn_cast<expr *> (o))
746 if (e->ops.length () == 0)
747 fprintf (f, "%s", e->operation->id);
748 else
750 fprintf (f, "(%s", e->operation->id);
752 if (flattened == false)
754 for (unsigned i = 0; i < e->ops.length (); ++i)
756 putc (' ', f);
757 print_operand (e->ops[i], f, flattened);
760 putc (')', f);
764 else
765 gcc_unreachable ();
768 DEBUG_FUNCTION void
769 print_matches (struct simplify *s, FILE *f = stderr)
771 fprintf (f, "for expression: ");
772 print_operand (s->match, f);
773 putc ('\n', f);
777 /* AST lowering. */
779 /* Lowering of commutative operators. */
781 static void
782 cartesian_product (const vec< vec<operand *> >& ops_vector,
783 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
785 if (n == ops_vector.length ())
787 vec<operand *> xv = v.copy ();
788 result.safe_push (xv);
789 return;
792 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
794 v[n] = ops_vector[n][i];
795 cartesian_product (ops_vector, result, v, n + 1);
799 /* Lower OP to two operands in case it is marked as commutative. */
801 static vec<operand *>
802 commutate (operand *op)
804 vec<operand *> ret = vNULL;
806 if (capture *c = dyn_cast <capture *> (op))
808 if (!c->what)
810 ret.safe_push (op);
811 return ret;
813 vec<operand *> v = commutate (c->what);
814 for (unsigned i = 0; i < v.length (); ++i)
816 capture *nc = new capture (c->location, c->where, v[i]);
817 ret.safe_push (nc);
819 return ret;
822 expr *e = dyn_cast <expr *> (op);
823 if (!e || e->ops.length () == 0)
825 ret.safe_push (op);
826 return ret;
829 vec< vec<operand *> > ops_vector = vNULL;
830 for (unsigned i = 0; i < e->ops.length (); ++i)
831 ops_vector.safe_push (commutate (e->ops[i]));
833 auto_vec< vec<operand *> > result;
834 auto_vec<operand *> v (e->ops.length ());
835 v.quick_grow_cleared (e->ops.length ());
836 cartesian_product (ops_vector, result, v, 0);
839 for (unsigned i = 0; i < result.length (); ++i)
841 expr *ne = new expr (e);
842 ne->is_commutative = false;
843 for (unsigned j = 0; j < result[i].length (); ++j)
844 ne->append_op (result[i][j]);
845 ret.safe_push (ne);
848 if (!e->is_commutative)
849 return ret;
851 for (unsigned i = 0; i < result.length (); ++i)
853 expr *ne = new expr (e);
854 ne->is_commutative = false;
855 // result[i].length () is 2 since e->operation is binary
856 for (unsigned j = result[i].length (); j; --j)
857 ne->append_op (result[i][j-1]);
858 ret.safe_push (ne);
861 return ret;
864 /* Lower operations marked as commutative in the AST of S and push
865 the resulting patterns to SIMPLIFIERS. */
867 static void
868 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
870 vec<operand *> matchers = commutate (s->match);
871 for (unsigned i = 0; i < matchers.length (); ++i)
873 simplify *ns = new simplify (s->kind, matchers[i], s->result,
874 s->for_vec, s->capture_ids);
875 simplifiers.safe_push (ns);
879 /* Strip conditional conversios using operator OPER from O and its
880 children if STRIP, else replace them with an unconditional convert. */
882 operand *
883 lower_opt_convert (operand *o, enum tree_code oper,
884 enum tree_code to_oper, bool strip)
886 if (capture *c = dyn_cast<capture *> (o))
888 if (c->what)
889 return new capture (c->location, c->where,
890 lower_opt_convert (c->what, oper, to_oper, strip));
891 else
892 return c;
895 expr *e = dyn_cast<expr *> (o);
896 if (!e)
897 return o;
899 if (*e->operation == oper)
901 if (strip)
902 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
904 expr *ne = new expr (e);
905 ne->operation = (to_oper == CONVERT_EXPR
906 ? get_operator ("CONVERT_EXPR")
907 : get_operator ("VIEW_CONVERT_EXPR"));
908 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
909 return ne;
912 expr *ne = new expr (e);
913 for (unsigned i = 0; i < e->ops.length (); ++i)
914 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
916 return ne;
919 /* Determine whether O or its children uses the conditional conversion
920 operator OPER. */
922 static bool
923 has_opt_convert (operand *o, enum tree_code oper)
925 if (capture *c = dyn_cast<capture *> (o))
927 if (c->what)
928 return has_opt_convert (c->what, oper);
929 else
930 return false;
933 expr *e = dyn_cast<expr *> (o);
934 if (!e)
935 return false;
937 if (*e->operation == oper)
938 return true;
940 for (unsigned i = 0; i < e->ops.length (); ++i)
941 if (has_opt_convert (e->ops[i], oper))
942 return true;
944 return false;
947 /* Lower conditional convert operators in O, expanding it to a vector
948 if required. */
950 static vec<operand *>
951 lower_opt_convert (operand *o)
953 vec<operand *> v1 = vNULL, v2;
955 v1.safe_push (o);
957 enum tree_code opers[]
958 = { CONVERT0, CONVERT_EXPR,
959 CONVERT1, CONVERT_EXPR,
960 CONVERT2, CONVERT_EXPR,
961 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
962 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
963 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
965 /* Conditional converts are lowered to a pattern with the
966 conversion and one without. The three different conditional
967 convert codes are lowered separately. */
969 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
971 v2 = vNULL;
972 for (unsigned j = 0; j < v1.length (); ++j)
973 if (has_opt_convert (v1[j], opers[i]))
975 v2.safe_push (lower_opt_convert (v1[j],
976 opers[i], opers[i+1], false));
977 v2.safe_push (lower_opt_convert (v1[j],
978 opers[i], opers[i+1], true));
981 if (v2 != vNULL)
983 v1 = vNULL;
984 for (unsigned j = 0; j < v2.length (); ++j)
985 v1.safe_push (v2[j]);
989 return v1;
992 /* Lower conditional convert operators in the AST of S and push
993 the resulting multiple patterns to SIMPLIFIERS. */
995 static void
996 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
998 vec<operand *> matchers = lower_opt_convert (s->match);
999 for (unsigned i = 0; i < matchers.length (); ++i)
1001 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1002 s->for_vec, s->capture_ids);
1003 simplifiers.safe_push (ns);
1007 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1008 GENERIC and a GIMPLE variant. */
1010 static vec<operand *>
1011 lower_cond (operand *o)
1013 vec<operand *> ro = vNULL;
1015 if (capture *c = dyn_cast<capture *> (o))
1017 if (c->what)
1019 vec<operand *> lop = vNULL;
1020 lop = lower_cond (c->what);
1022 for (unsigned i = 0; i < lop.length (); ++i)
1023 ro.safe_push (new capture (c->location, c->where, lop[i]));
1024 return ro;
1028 expr *e = dyn_cast<expr *> (o);
1029 if (!e || e->ops.length () == 0)
1031 ro.safe_push (o);
1032 return ro;
1035 vec< vec<operand *> > ops_vector = vNULL;
1036 for (unsigned i = 0; i < e->ops.length (); ++i)
1037 ops_vector.safe_push (lower_cond (e->ops[i]));
1039 auto_vec< vec<operand *> > result;
1040 auto_vec<operand *> v (e->ops.length ());
1041 v.quick_grow_cleared (e->ops.length ());
1042 cartesian_product (ops_vector, result, v, 0);
1044 for (unsigned i = 0; i < result.length (); ++i)
1046 expr *ne = new expr (e);
1047 for (unsigned j = 0; j < result[i].length (); ++j)
1048 ne->append_op (result[i][j]);
1049 ro.safe_push (ne);
1050 /* If this is a COND with a captured expression or an
1051 expression with two operands then also match a GENERIC
1052 form on the compare. */
1053 if ((*e->operation == COND_EXPR
1054 || *e->operation == VEC_COND_EXPR)
1055 && ((is_a <capture *> (e->ops[0])
1056 && as_a <capture *> (e->ops[0])->what
1057 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1058 && as_a <expr *>
1059 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1060 || (is_a <expr *> (e->ops[0])
1061 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1063 expr *ne = new expr (e);
1064 for (unsigned j = 0; j < result[i].length (); ++j)
1065 ne->append_op (result[i][j]);
1066 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1068 expr *ocmp = as_a <expr *> (c->what);
1069 expr *cmp = new expr (ocmp);
1070 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1071 cmp->append_op (ocmp->ops[j]);
1072 cmp->is_generic = true;
1073 ne->ops[0] = new capture (c->location, c->where, cmp);
1075 else
1077 expr *ocmp = as_a <expr *> (ne->ops[0]);
1078 expr *cmp = new expr (ocmp);
1079 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1080 cmp->append_op (ocmp->ops[j]);
1081 cmp->is_generic = true;
1082 ne->ops[0] = cmp;
1084 ro.safe_push (ne);
1088 return ro;
1091 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1092 GENERIC and a GIMPLE variant. */
1094 static void
1095 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1097 vec<operand *> matchers = lower_cond (s->match);
1098 for (unsigned i = 0; i < matchers.length (); ++i)
1100 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1101 s->for_vec, s->capture_ids);
1102 simplifiers.safe_push (ns);
1106 /* In AST operand O replace operator ID with operator WITH. */
1108 operand *
1109 replace_id (operand *o, user_id *id, id_base *with)
1111 /* Deep-copy captures and expressions, replacing operations as
1112 needed. */
1113 if (capture *c = dyn_cast<capture *> (o))
1115 if (!c->what)
1116 return c;
1117 return new capture (c->location, c->where,
1118 replace_id (c->what, id, with));
1120 else if (expr *e = dyn_cast<expr *> (o))
1122 expr *ne = new expr (e);
1123 if (e->operation == id)
1124 ne->operation = with;
1125 for (unsigned i = 0; i < e->ops.length (); ++i)
1126 ne->append_op (replace_id (e->ops[i], id, with));
1127 return ne;
1129 else if (with_expr *w = dyn_cast <with_expr *> (o))
1131 with_expr *nw = new with_expr (w->location);
1132 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1133 nw->subexpr = replace_id (w->subexpr, id, with);
1134 return nw;
1136 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1138 if_expr *nife = new if_expr (ife->location);
1139 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1140 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1141 if (ife->falseexpr)
1142 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1143 return nife;
1146 /* For c_expr we simply record a string replacement table which is
1147 applied at code-generation time. */
1148 if (c_expr *ce = dyn_cast<c_expr *> (o))
1150 vec<c_expr::id_tab> ids = ce->ids.copy ();
1151 ids.safe_push (c_expr::id_tab (id->id, with->id));
1152 return new c_expr (ce->r, ce->location,
1153 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1156 return o;
1159 /* Return true if the binary operator OP is ok for delayed substitution
1160 during for lowering. */
1162 static bool
1163 binary_ok (operator_id *op)
1165 switch (op->code)
1167 case PLUS_EXPR:
1168 case MINUS_EXPR:
1169 case MULT_EXPR:
1170 case TRUNC_DIV_EXPR:
1171 case CEIL_DIV_EXPR:
1172 case FLOOR_DIV_EXPR:
1173 case ROUND_DIV_EXPR:
1174 case TRUNC_MOD_EXPR:
1175 case CEIL_MOD_EXPR:
1176 case FLOOR_MOD_EXPR:
1177 case ROUND_MOD_EXPR:
1178 case RDIV_EXPR:
1179 case EXACT_DIV_EXPR:
1180 case MIN_EXPR:
1181 case MAX_EXPR:
1182 case BIT_IOR_EXPR:
1183 case BIT_XOR_EXPR:
1184 case BIT_AND_EXPR:
1185 return true;
1186 default:
1187 return false;
1191 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1193 static void
1194 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1196 vec<vec<user_id *> >& for_vec = sin->for_vec;
1197 unsigned worklist_start = 0;
1198 auto_vec<simplify *> worklist;
1199 worklist.safe_push (sin);
1201 /* Lower each recorded for separately, operating on the
1202 set of simplifiers created by the previous one.
1203 Lower inner-to-outer so inner for substitutes can refer
1204 to operators replaced by outer fors. */
1205 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1207 vec<user_id *>& ids = for_vec[fi];
1208 unsigned n_ids = ids.length ();
1209 unsigned max_n_opers = 0;
1210 bool can_delay_subst = (sin->kind == simplify::SIMPLIFY);
1211 for (unsigned i = 0; i < n_ids; ++i)
1213 if (ids[i]->substitutes.length () > max_n_opers)
1214 max_n_opers = ids[i]->substitutes.length ();
1215 /* Require that all substitutes are of the same kind so that
1216 if we delay substitution to the result op code generation
1217 can look at the first substitute for deciding things like
1218 types of operands. */
1219 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1220 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1221 if (ids[i]->substitutes[j]->kind != kind)
1222 can_delay_subst = false;
1223 else if (operator_id *op
1224 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1226 operator_id *op0
1227 = as_a <operator_id *> (ids[i]->substitutes[0]);
1228 if (strcmp (op->tcc, "tcc_comparison") == 0
1229 && strcmp (op0->tcc, "tcc_comparison") == 0)
1231 /* Unfortunately we can't just allow all tcc_binary. */
1232 else if (strcmp (op->tcc, "tcc_binary") == 0
1233 && strcmp (op0->tcc, "tcc_binary") == 0
1234 && binary_ok (op)
1235 && binary_ok (op0))
1237 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1238 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1239 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1240 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1242 else
1243 can_delay_subst = false;
1245 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1247 else
1248 can_delay_subst = false;
1251 unsigned worklist_end = worklist.length ();
1252 for (unsigned si = worklist_start; si < worklist_end; ++si)
1254 simplify *s = worklist[si];
1255 for (unsigned j = 0; j < max_n_opers; ++j)
1257 operand *match_op = s->match;
1258 operand *result_op = s->result;
1259 vec<std::pair<user_id *, id_base *> > subst;
1260 subst.create (n_ids);
1261 for (unsigned i = 0; i < n_ids; ++i)
1263 user_id *id = ids[i];
1264 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1265 subst.quick_push (std::make_pair (id, oper));
1266 match_op = replace_id (match_op, id, oper);
1267 if (result_op
1268 && !can_delay_subst)
1269 result_op = replace_id (result_op, id, oper);
1271 simplify *ns = new simplify (s->kind, match_op, result_op,
1272 vNULL, s->capture_ids);
1273 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1274 if (result_op
1275 && can_delay_subst)
1276 ns->for_subst_vec.safe_splice (subst);
1277 else
1278 subst.release ();
1279 worklist.safe_push (ns);
1282 worklist_start = worklist_end;
1285 /* Copy out the result from the last for lowering. */
1286 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1287 simplifiers.safe_push (worklist[i]);
1290 /* Lower the AST for everything in SIMPLIFIERS. */
1292 static void
1293 lower (vec<simplify *>& simplifiers, bool gimple)
1295 auto_vec<simplify *> out_simplifiers;
1296 for (unsigned i = 0; i < simplifiers.length (); ++i)
1297 lower_opt_convert (simplifiers[i], out_simplifiers);
1299 simplifiers.truncate (0);
1300 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1301 lower_commutative (out_simplifiers[i], simplifiers);
1303 out_simplifiers.truncate (0);
1304 if (gimple)
1305 for (unsigned i = 0; i < simplifiers.length (); ++i)
1306 lower_cond (simplifiers[i], out_simplifiers);
1307 else
1308 out_simplifiers.safe_splice (simplifiers);
1311 simplifiers.truncate (0);
1312 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1313 lower_for (out_simplifiers[i], simplifiers);
1319 /* The decision tree built for generating GIMPLE and GENERIC pattern
1320 matching code. It represents the 'match' expression of all
1321 simplifies and has those as its leafs. */
1323 struct dt_simplify;
1325 /* A hash-map collecting semantically equivalent leafs in the decision
1326 tree for splitting out to separate functions. */
1327 struct sinfo
1329 dt_simplify *s;
1331 const char *fname;
1332 unsigned cnt;
1335 struct sinfo_hashmap_traits : simple_hashmap_traits <pointer_hash <dt_simplify> >
1337 static inline hashval_t hash (const key_type &);
1338 static inline bool equal_keys (const key_type &, const key_type &);
1339 template <typename T> static inline void remove (T &) {}
1342 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1343 sinfo_map_t;
1346 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1348 struct dt_node
1350 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1352 enum dt_type type;
1353 unsigned level;
1354 vec<dt_node *> kids;
1356 /* Statistics. */
1357 unsigned num_leafs;
1358 unsigned total_size;
1359 unsigned max_level;
1361 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1363 dt_node *append_node (dt_node *);
1364 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1365 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1366 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1367 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1369 virtual void gen (FILE *, int, bool) {}
1371 void gen_kids (FILE *, int, bool);
1372 void gen_kids_1 (FILE *, int, bool,
1373 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1374 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1376 void analyze (sinfo_map_t &);
1379 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1381 struct dt_operand : public dt_node
1383 operand *op;
1384 dt_operand *match_dop;
1385 dt_operand *parent;
1386 unsigned pos;
1388 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1389 dt_operand *parent_ = 0, unsigned pos_ = 0)
1390 : dt_node (type), op (op_), match_dop (match_dop_),
1391 parent (parent_), pos (pos_) {}
1393 void gen (FILE *, int, bool);
1394 unsigned gen_predicate (FILE *, int, const char *, bool);
1395 unsigned gen_match_op (FILE *, int, const char *);
1397 unsigned gen_gimple_expr (FILE *, int);
1398 unsigned gen_generic_expr (FILE *, int, const char *);
1400 char *get_name (char *);
1401 void gen_opname (char *, unsigned);
1404 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1406 struct dt_simplify : public dt_node
1408 simplify *s;
1409 unsigned pattern_no;
1410 dt_operand **indexes;
1411 sinfo *info;
1413 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1414 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1415 indexes (indexes_), info (NULL) {}
1417 void gen_1 (FILE *, int, bool, operand *);
1418 void gen (FILE *f, int, bool);
1421 template<>
1422 template<>
1423 inline bool
1424 is_a_helper <dt_operand *>::test (dt_node *n)
1426 return (n->type == dt_node::DT_OPERAND
1427 || n->type == dt_node::DT_MATCH);
1430 template<>
1431 template<>
1432 inline bool
1433 is_a_helper <dt_simplify *>::test (dt_node *n)
1435 return n->type == dt_node::DT_SIMPLIFY;
1440 /* A container for the actual decision tree. */
1442 struct decision_tree
1444 dt_node *root;
1446 void insert (struct simplify *, unsigned);
1447 void gen (FILE *f, bool gimple);
1448 void print (FILE *f = stderr);
1450 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1452 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1453 unsigned pos = 0, dt_node *parent = 0);
1454 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1455 static bool cmp_node (dt_node *, dt_node *);
1456 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1459 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1461 bool
1462 cmp_operand (operand *o1, operand *o2)
1464 if (!o1 || !o2 || o1->type != o2->type)
1465 return false;
1467 if (o1->type == operand::OP_PREDICATE)
1469 predicate *p1 = as_a<predicate *>(o1);
1470 predicate *p2 = as_a<predicate *>(o2);
1471 return p1->p == p2->p;
1473 else if (o1->type == operand::OP_EXPR)
1475 expr *e1 = static_cast<expr *>(o1);
1476 expr *e2 = static_cast<expr *>(o2);
1477 return (e1->operation == e2->operation
1478 && e1->is_generic == e2->is_generic);
1480 else
1481 return false;
1484 /* Compare two decision tree nodes N1 and N2 and return true if they
1485 are equal. */
1487 bool
1488 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1490 if (!n1 || !n2 || n1->type != n2->type)
1491 return false;
1493 if (n1 == n2)
1494 return true;
1496 if (n1->type == dt_node::DT_TRUE)
1497 return false;
1499 if (n1->type == dt_node::DT_OPERAND)
1500 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1501 (as_a<dt_operand *> (n2))->op);
1502 else if (n1->type == dt_node::DT_MATCH)
1503 return ((as_a<dt_operand *> (n1))->match_dop
1504 == (as_a<dt_operand *> (n2))->match_dop);
1505 return false;
1508 /* Search OPS for a decision tree node like P and return it if found. */
1510 dt_node *
1511 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1513 /* We can merge adjacent DT_TRUE. */
1514 if (p->type == dt_node::DT_TRUE
1515 && !ops.is_empty ()
1516 && ops.last ()->type == dt_node::DT_TRUE)
1517 return ops.last ();
1518 for (int i = ops.length () - 1; i >= 0; --i)
1520 /* But we can't merge across DT_TRUE nodes as they serve as
1521 pattern order barriers to make sure that patterns apply
1522 in order of appearance in case multiple matches are possible. */
1523 if (ops[i]->type == dt_node::DT_TRUE)
1524 return NULL;
1525 if (decision_tree::cmp_node (ops[i], p))
1526 return ops[i];
1528 return NULL;
1531 /* Append N to the decision tree if it there is not already an existing
1532 identical child. */
1534 dt_node *
1535 dt_node::append_node (dt_node *n)
1537 dt_node *kid;
1539 kid = decision_tree::find_node (kids, n);
1540 if (kid)
1541 return kid;
1543 kids.safe_push (n);
1544 n->level = this->level + 1;
1546 return n;
1549 /* Append OP to the decision tree. */
1551 dt_node *
1552 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1554 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1555 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1556 return append_node (n);
1559 /* Append a DT_TRUE decision tree node. */
1561 dt_node *
1562 dt_node::append_true_op (dt_node *parent, unsigned pos)
1564 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1565 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1566 return append_node (n);
1569 /* Append a DT_MATCH decision tree node. */
1571 dt_node *
1572 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1574 dt_operand *parent_ = as_a<dt_operand *> (parent);
1575 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1576 return append_node (n);
1579 /* Append S to the decision tree. */
1581 dt_node *
1582 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1583 dt_operand **indexes)
1585 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1586 for (unsigned i = 0; i < kids.length (); ++i)
1587 if (dt_simplify *s2 = dyn_cast <dt_simplify *> (kids[i]))
1589 warning_at (s->match->location, "duplicate pattern");
1590 warning_at (s2->s->match->location, "previous pattern defined here");
1591 print_operand (s->match, stderr);
1592 fprintf (stderr, "\n");
1594 return append_node (n);
1597 /* Analyze the node and its children. */
1599 void
1600 dt_node::analyze (sinfo_map_t &map)
1602 num_leafs = 0;
1603 total_size = 1;
1604 max_level = level;
1606 if (type == DT_SIMPLIFY)
1608 /* Populate the map of equivalent simplifies. */
1609 dt_simplify *s = as_a <dt_simplify *> (this);
1610 bool existed;
1611 sinfo *&si = map.get_or_insert (s, &existed);
1612 if (!existed)
1614 si = new sinfo;
1615 si->s = s;
1616 si->cnt = 1;
1617 si->fname = NULL;
1619 else
1620 si->cnt++;
1621 s->info = si;
1622 num_leafs = 1;
1623 return;
1626 for (unsigned i = 0; i < kids.length (); ++i)
1628 kids[i]->analyze (map);
1629 num_leafs += kids[i]->num_leafs;
1630 total_size += kids[i]->total_size;
1631 max_level = MAX (max_level, kids[i]->max_level);
1635 /* Insert O into the decision tree and return the decision tree node found
1636 or created. */
1638 dt_node *
1639 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1640 unsigned pos, dt_node *parent)
1642 dt_node *q, *elm = 0;
1644 if (capture *c = dyn_cast<capture *> (o))
1646 unsigned capt_index = c->where;
1648 if (indexes[capt_index] == 0)
1650 if (c->what)
1651 q = insert_operand (p, c->what, indexes, pos, parent);
1652 else
1654 q = elm = p->append_true_op (parent, pos);
1655 goto at_assert_elm;
1657 // get to the last capture
1658 for (operand *what = c->what;
1659 what && is_a<capture *> (what);
1660 c = as_a<capture *> (what), what = c->what)
1663 if (!c->what)
1665 unsigned cc_index = c->where;
1666 dt_operand *match_op = indexes[cc_index];
1668 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1669 elm = decision_tree::find_node (p->kids, &temp);
1671 if (elm == 0)
1673 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1674 elm = decision_tree::find_node (p->kids, &temp);
1677 else
1679 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1680 elm = decision_tree::find_node (p->kids, &temp);
1683 at_assert_elm:
1684 gcc_assert (elm->type == dt_node::DT_TRUE
1685 || elm->type == dt_node::DT_OPERAND
1686 || elm->type == dt_node::DT_MATCH);
1687 indexes[capt_index] = static_cast<dt_operand *> (elm);
1688 return q;
1690 else
1692 p = p->append_match_op (indexes[capt_index], parent, pos);
1693 if (c->what)
1694 return insert_operand (p, c->what, indexes, 0, p);
1695 else
1696 return p;
1699 p = p->append_op (o, parent, pos);
1700 q = p;
1702 if (expr *e = dyn_cast <expr *>(o))
1704 for (unsigned i = 0; i < e->ops.length (); ++i)
1705 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1708 return q;
1711 /* Insert S into the decision tree. */
1713 void
1714 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1716 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1717 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1718 p->append_simplify (s, pattern_no, indexes);
1721 /* Debug functions to dump the decision tree. */
1723 DEBUG_FUNCTION void
1724 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1726 if (p->type == dt_node::DT_NODE)
1727 fprintf (f, "root");
1728 else
1730 fprintf (f, "|");
1731 for (unsigned i = 0; i < indent; i++)
1732 fprintf (f, "-");
1734 if (p->type == dt_node::DT_OPERAND)
1736 dt_operand *dop = static_cast<dt_operand *>(p);
1737 print_operand (dop->op, f, true);
1739 else if (p->type == dt_node::DT_TRUE)
1740 fprintf (f, "true");
1741 else if (p->type == dt_node::DT_MATCH)
1742 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1743 else if (p->type == dt_node::DT_SIMPLIFY)
1745 dt_simplify *s = static_cast<dt_simplify *> (p);
1746 fprintf (f, "simplify_%u { ", s->pattern_no);
1747 for (int i = 0; i <= s->s->capture_max; ++i)
1748 fprintf (f, "%p, ", (void *) s->indexes[i]);
1749 fprintf (f, " } ");
1753 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1755 for (unsigned i = 0; i < p->kids.length (); ++i)
1756 decision_tree::print_node (p->kids[i], f, indent + 2);
1759 DEBUG_FUNCTION void
1760 decision_tree::print (FILE *f)
1762 return decision_tree::print_node (root, f);
1766 /* For GENERIC we have to take care of wrapping multiple-used
1767 expressions with side-effects in save_expr and preserve side-effects
1768 of expressions with omit_one_operand. Analyze captures in
1769 match, result and with expressions and perform early-outs
1770 on the outermost match expression operands for cases we cannot
1771 handle. */
1773 struct capture_info
1775 capture_info (simplify *s, operand *, bool);
1776 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1777 bool walk_result (operand *o, bool, operand *);
1778 void walk_c_expr (c_expr *);
1780 struct cinfo
1782 bool expr_p;
1783 bool cse_p;
1784 bool force_no_side_effects_p;
1785 bool force_single_use;
1786 bool cond_expr_cond_p;
1787 unsigned long toplevel_msk;
1788 int result_use_count;
1789 unsigned same_as;
1790 capture *c;
1793 auto_vec<cinfo> info;
1794 unsigned long force_no_side_effects;
1795 bool gimple;
1798 /* Analyze captures in S. */
1800 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
1802 gimple = gimple_;
1804 expr *e;
1805 if (s->kind == simplify::MATCH)
1807 force_no_side_effects = -1;
1808 return;
1811 force_no_side_effects = 0;
1812 info.safe_grow_cleared (s->capture_max + 1);
1813 for (int i = 0; i <= s->capture_max; ++i)
1814 info[i].same_as = i;
1816 e = as_a <expr *> (s->match);
1817 for (unsigned i = 0; i < e->ops.length (); ++i)
1818 walk_match (e->ops[i], i,
1819 (i != 0 && *e->operation == COND_EXPR)
1820 || *e->operation == TRUTH_ANDIF_EXPR
1821 || *e->operation == TRUTH_ORIF_EXPR,
1822 i == 0
1823 && (*e->operation == COND_EXPR
1824 || *e->operation == VEC_COND_EXPR));
1826 walk_result (s->result, false, result);
1829 /* Analyze captures in the match expression piece O. */
1831 void
1832 capture_info::walk_match (operand *o, unsigned toplevel_arg,
1833 bool conditional_p, bool cond_expr_cond_p)
1835 if (capture *c = dyn_cast <capture *> (o))
1837 unsigned where = c->where;
1838 info[where].toplevel_msk |= 1 << toplevel_arg;
1839 info[where].force_no_side_effects_p |= conditional_p;
1840 info[where].cond_expr_cond_p |= cond_expr_cond_p;
1841 if (!info[where].c)
1842 info[where].c = c;
1843 if (!c->what)
1844 return;
1845 /* Recurse to exprs and captures. */
1846 if (is_a <capture *> (c->what)
1847 || is_a <expr *> (c->what))
1848 walk_match (c->what, toplevel_arg, conditional_p, false);
1849 /* We need to look past multiple captures to find a captured
1850 expression as with conditional converts two captures
1851 can be collapsed onto the same expression. Also collect
1852 what captures capture the same thing. */
1853 while (c->what && is_a <capture *> (c->what))
1855 c = as_a <capture *> (c->what);
1856 if (info[c->where].same_as != c->where
1857 && info[c->where].same_as != info[where].same_as)
1858 fatal_at (c->location, "cannot handle this collapsed capture");
1859 info[c->where].same_as = info[where].same_as;
1861 /* Mark expr (non-leaf) captures and forced single-use exprs. */
1862 expr *e;
1863 if (c->what
1864 && (e = dyn_cast <expr *> (c->what)))
1866 info[where].expr_p = true;
1867 info[where].force_single_use |= e->force_single_use;
1870 else if (expr *e = dyn_cast <expr *> (o))
1872 for (unsigned i = 0; i < e->ops.length (); ++i)
1874 bool cond_p = conditional_p;
1875 bool cond_expr_cond_p = false;
1876 if (i != 0 && *e->operation == COND_EXPR)
1877 cond_p = true;
1878 else if (*e->operation == TRUTH_ANDIF_EXPR
1879 || *e->operation == TRUTH_ORIF_EXPR)
1880 cond_p = true;
1881 if (i == 0
1882 && (*e->operation == COND_EXPR
1883 || *e->operation == VEC_COND_EXPR))
1884 cond_expr_cond_p = true;
1885 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1888 else if (is_a <predicate *> (o))
1890 /* Mark non-captured leafs toplevel arg for checking. */
1891 force_no_side_effects |= 1 << toplevel_arg;
1892 if (verbose >= 1
1893 && !gimple)
1894 warning_at (o->location,
1895 "forcing no side-effects on possibly lost leaf");
1897 else
1898 gcc_unreachable ();
1901 /* Analyze captures in the result expression piece O. Return true
1902 if RESULT was visited in one of the children. Only visit
1903 non-if/with children if they are rooted on RESULT. */
1905 bool
1906 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
1908 if (capture *c = dyn_cast <capture *> (o))
1910 unsigned where = info[c->where].same_as;
1911 info[where].result_use_count++;
1912 /* If we substitute an expression capture we don't know
1913 which captures this will end up using (well, we don't
1914 compute that). Force the uses to be side-effect free
1915 which means forcing the toplevels that reach the
1916 expression side-effect free. */
1917 if (info[where].expr_p)
1918 force_no_side_effects |= info[where].toplevel_msk;
1919 /* Mark CSE capture uses as forced to have no side-effects. */
1920 if (c->what
1921 && is_a <expr *> (c->what))
1923 info[where].cse_p = true;
1924 walk_result (c->what, true, result);
1927 else if (expr *e = dyn_cast <expr *> (o))
1929 id_base *opr = e->operation;
1930 if (user_id *uid = dyn_cast <user_id *> (opr))
1931 opr = uid->substitutes[0];
1932 for (unsigned i = 0; i < e->ops.length (); ++i)
1934 bool cond_p = conditional_p;
1935 if (i != 0 && *e->operation == COND_EXPR)
1936 cond_p = true;
1937 else if (*e->operation == TRUTH_ANDIF_EXPR
1938 || *e->operation == TRUTH_ORIF_EXPR)
1939 cond_p = true;
1940 walk_result (e->ops[i], cond_p, result);
1943 else if (if_expr *e = dyn_cast <if_expr *> (o))
1945 /* 'if' conditions should be all fine. */
1946 if (e->trueexpr == result)
1948 walk_result (e->trueexpr, false, result);
1949 return true;
1951 if (e->falseexpr == result)
1953 walk_result (e->falseexpr, false, result);
1954 return true;
1956 bool res = false;
1957 if (is_a <if_expr *> (e->trueexpr)
1958 || is_a <with_expr *> (e->trueexpr))
1959 res |= walk_result (e->trueexpr, false, result);
1960 if (e->falseexpr
1961 && (is_a <if_expr *> (e->falseexpr)
1962 || is_a <with_expr *> (e->falseexpr)))
1963 res |= walk_result (e->falseexpr, false, result);
1964 return res;
1966 else if (with_expr *e = dyn_cast <with_expr *> (o))
1968 bool res = (e->subexpr == result);
1969 if (res
1970 || is_a <if_expr *> (e->subexpr)
1971 || is_a <with_expr *> (e->subexpr))
1972 res |= walk_result (e->subexpr, false, result);
1973 if (res)
1974 walk_c_expr (e->with);
1975 return res;
1977 else if (c_expr *e = dyn_cast <c_expr *> (o))
1978 walk_c_expr (e);
1979 else
1980 gcc_unreachable ();
1982 return false;
1985 /* Look for captures in the C expr E. */
1987 void
1988 capture_info::walk_c_expr (c_expr *e)
1990 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
1991 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
1992 really escape through. */
1993 unsigned p_depth = 0;
1994 for (unsigned i = 0; i < e->code.length (); ++i)
1996 const cpp_token *t = &e->code[i];
1997 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
1998 id_base *id;
1999 if (t->type == CPP_NAME
2000 && (strcmp ((const char *)CPP_HASHNODE
2001 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2002 || strcmp ((const char *)CPP_HASHNODE
2003 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2004 || strcmp ((const char *)CPP_HASHNODE
2005 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2006 || ((id = get_operator ((const char *)CPP_HASHNODE
2007 (t->val.node.node)->ident.str))
2008 && is_a <predicate_id *> (id)))
2009 && n->type == CPP_OPEN_PAREN)
2010 p_depth++;
2011 else if (t->type == CPP_CLOSE_PAREN
2012 && p_depth > 0)
2013 p_depth--;
2014 else if (p_depth == 0
2015 && t->type == CPP_ATSIGN
2016 && (n->type == CPP_NUMBER
2017 || n->type == CPP_NAME)
2018 && !(n->flags & PREV_WHITE))
2020 const char *id;
2021 if (n->type == CPP_NUMBER)
2022 id = (const char *)n->val.str.text;
2023 else
2024 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2025 unsigned where = *e->capture_ids->get(id);
2026 info[info[where].same_as].force_no_side_effects_p = true;
2027 if (verbose >= 1
2028 && !gimple)
2029 warning_at (t, "capture escapes");
2035 /* Code generation off the decision tree and the refered AST nodes. */
2037 bool
2038 is_conversion (id_base *op)
2040 return (*op == CONVERT_EXPR
2041 || *op == NOP_EXPR
2042 || *op == FLOAT_EXPR
2043 || *op == FIX_TRUNC_EXPR
2044 || *op == VIEW_CONVERT_EXPR);
2047 /* Get the type to be used for generating operands of OP from the
2048 various sources. */
2050 static const char *
2051 get_operand_type (id_base *op, const char *in_type,
2052 const char *expr_type,
2053 const char *other_oprnd_type)
2055 /* Generally operands whose type does not match the type of the
2056 expression generated need to know their types but match and
2057 thus can fall back to 'other_oprnd_type'. */
2058 if (is_conversion (op))
2059 return other_oprnd_type;
2060 else if (*op == REALPART_EXPR
2061 || *op == IMAGPART_EXPR)
2062 return other_oprnd_type;
2063 else if (is_a <operator_id *> (op)
2064 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2065 return other_oprnd_type;
2066 else
2068 /* Otherwise all types should match - choose one in order of
2069 preference. */
2070 if (expr_type)
2071 return expr_type;
2072 else if (in_type)
2073 return in_type;
2074 else
2075 return other_oprnd_type;
2079 /* Generate transform code for an expression. */
2081 void
2082 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2083 int depth, const char *in_type, capture_info *cinfo,
2084 dt_operand **indexes, bool)
2086 id_base *opr = operation;
2087 /* When we delay operator substituting during lowering of fors we
2088 make sure that for code-gen purposes the effects of each substitute
2089 are the same. Thus just look at that. */
2090 if (user_id *uid = dyn_cast <user_id *> (opr))
2091 opr = uid->substitutes[0];
2093 bool conversion_p = is_conversion (opr);
2094 const char *type = expr_type;
2095 char optype[64];
2096 if (type)
2097 /* If there was a type specification in the pattern use it. */
2099 else if (conversion_p)
2100 /* For conversions we need to build the expression using the
2101 outer type passed in. */
2102 type = in_type;
2103 else if (*opr == REALPART_EXPR
2104 || *opr == IMAGPART_EXPR)
2106 /* __real and __imag use the component type of its operand. */
2107 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
2108 type = optype;
2110 else if (is_a <operator_id *> (opr)
2111 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2113 /* comparisons use boolean_type_node (or what gets in), but
2114 their operands need to figure out the types themselves. */
2115 sprintf (optype, "boolean_type_node");
2116 type = optype;
2118 else if (*opr == COND_EXPR
2119 || *opr == VEC_COND_EXPR)
2121 /* Conditions are of the same type as their first alternative. */
2122 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
2123 type = optype;
2125 else
2127 /* Other operations are of the same type as their first operand. */
2128 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
2129 type = optype;
2131 if (!type)
2132 fatal_at (location, "cannot determine type of operand");
2134 fprintf_indent (f, indent, "{\n");
2135 indent += 2;
2136 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
2137 char op0type[64];
2138 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
2139 for (unsigned i = 0; i < ops.length (); ++i)
2141 char dest[32];
2142 snprintf (dest, 32, "ops%d[%u]", depth, i);
2143 const char *optype
2144 = get_operand_type (opr, in_type, expr_type,
2145 i == 0 ? NULL : op0type);
2146 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
2147 cinfo, indexes,
2148 ((!(*opr == COND_EXPR)
2149 && !(*opr == VEC_COND_EXPR))
2150 || i != 0));
2153 const char *opr_name;
2154 if (*operation == CONVERT_EXPR)
2155 opr_name = "NOP_EXPR";
2156 else
2157 opr_name = operation->id;
2159 if (gimple)
2161 if (*opr == CONVERT_EXPR)
2163 fprintf_indent (f, indent,
2164 "if (%s != TREE_TYPE (ops%d[0])\n",
2165 type, depth);
2166 fprintf_indent (f, indent,
2167 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
2168 type, depth);
2169 fprintf_indent (f, indent + 2, "{\n");
2170 indent += 4;
2172 /* ??? Building a stmt can fail for various reasons here, seq being
2173 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2174 So if we fail here we should continue matching other patterns. */
2175 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr_name);
2176 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
2177 for (unsigned i = 0; i < ops.length (); ++i)
2178 fprintf (f, "ops%d[%u]%s", depth, i,
2179 i == ops.length () - 1 ? " };\n" : ", ");
2180 fprintf_indent (f, indent,
2181 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
2182 ops.length (), type);
2183 fprintf_indent (f, indent,
2184 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
2185 type);
2186 fprintf_indent (f, indent,
2187 "if (!res) return false;\n");
2188 if (*opr == CONVERT_EXPR)
2190 indent -= 4;
2191 fprintf_indent (f, indent, " }\n");
2192 fprintf_indent (f, indent, "else\n");
2193 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2196 else
2198 if (*opr == CONVERT_EXPR)
2200 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
2201 depth, type);
2202 indent += 2;
2204 if (opr->kind == id_base::CODE)
2205 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
2206 ops.length(), opr_name, type);
2207 else
2209 fprintf_indent (f, indent, "{\n");
2210 fprintf_indent (f, indent, " tree decl = builtin_decl_implicit (%s);\n",
2211 opr_name);
2212 fprintf_indent (f, indent, " if (!decl) return NULL_TREE;\n");
2213 fprintf_indent (f, indent, " res = build_call_expr_loc (loc, "
2214 "decl, %d", ops.length());
2216 for (unsigned i = 0; i < ops.length (); ++i)
2217 fprintf (f, ", ops%d[%u]", depth, i);
2218 fprintf (f, ");\n");
2219 if (opr->kind != id_base::CODE)
2220 fprintf_indent (f, indent, "}\n");
2221 if (*opr == CONVERT_EXPR)
2223 indent -= 2;
2224 fprintf_indent (f, indent, "else\n");
2225 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2228 fprintf_indent (f, indent, "%s = res;\n", dest);
2229 indent -= 2;
2230 fprintf_indent (f, indent, "}\n");
2233 /* Generate code for a c_expr which is either the expression inside
2234 an if statement or a sequence of statements which computes a
2235 result to be stored to DEST. */
2237 void
2238 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2239 bool, int, const char *, capture_info *,
2240 dt_operand **, bool)
2242 if (dest && nr_stmts == 1)
2243 fprintf_indent (f, indent, "%s = ", dest);
2245 unsigned stmt_nr = 1;
2246 for (unsigned i = 0; i < code.length (); ++i)
2248 const cpp_token *token = &code[i];
2250 /* Replace captures for code-gen. */
2251 if (token->type == CPP_ATSIGN)
2253 const cpp_token *n = &code[i+1];
2254 if ((n->type == CPP_NUMBER
2255 || n->type == CPP_NAME)
2256 && !(n->flags & PREV_WHITE))
2258 if (token->flags & PREV_WHITE)
2259 fputc (' ', f);
2260 const char *id;
2261 if (n->type == CPP_NUMBER)
2262 id = (const char *)n->val.str.text;
2263 else
2264 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2265 unsigned *cid = capture_ids->get (id);
2266 if (!cid)
2267 fatal_at (token, "unknown capture id");
2268 fprintf (f, "captures[%u]", *cid);
2269 ++i;
2270 continue;
2274 if (token->flags & PREV_WHITE)
2275 fputc (' ', f);
2277 if (token->type == CPP_NAME)
2279 const char *id = (const char *) NODE_NAME (token->val.node.node);
2280 unsigned j;
2281 for (j = 0; j < ids.length (); ++j)
2283 if (strcmp (id, ids[j].id) == 0)
2285 fprintf (f, "%s", ids[j].oper);
2286 break;
2289 if (j < ids.length ())
2290 continue;
2293 /* Output the token as string. */
2294 char *tk = (char *)cpp_token_as_text (r, token);
2295 fputs (tk, f);
2297 if (token->type == CPP_SEMICOLON)
2299 stmt_nr++;
2300 fputc ('\n', f);
2301 if (dest && stmt_nr == nr_stmts)
2302 fprintf_indent (f, indent, "%s = ", dest);
2307 /* Generate transform code for a capture. */
2309 void
2310 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2311 int depth, const char *in_type, capture_info *cinfo,
2312 dt_operand **indexes, bool expand_compares)
2314 if (what && is_a<expr *> (what))
2316 if (indexes[where] == 0)
2318 char buf[20];
2319 sprintf (buf, "captures[%u]", where);
2320 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2321 cinfo, NULL);
2325 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2327 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2328 with substituting a capture of that.
2329 ??? Returning false here will also not allow any other patterns
2330 to match. */
2331 if (gimple && expand_compares
2332 && cinfo->info[where].cond_expr_cond_p)
2334 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2335 fprintf_indent (f, indent, " {\n");
2336 fprintf_indent (f, indent, " if (!seq) return false;\n");
2337 fprintf_indent (f, indent, " %s = gimple_build (seq, TREE_CODE (%s),"
2338 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2339 " TREE_OPERAND (%s, 1));\n",
2340 dest, dest, dest, dest, dest);
2341 fprintf_indent (f, indent, " }\n");
2345 /* Return the name of the operand representing the decision tree node.
2346 Use NAME as space to generate it. */
2348 char *
2349 dt_operand::get_name (char *name)
2351 if (!parent)
2352 sprintf (name, "t");
2353 else if (parent->level == 1)
2354 sprintf (name, "op%u", pos);
2355 else if (parent->type == dt_node::DT_MATCH)
2356 return parent->get_name (name);
2357 else
2358 sprintf (name, "o%u%u", parent->level, pos);
2359 return name;
2362 /* Fill NAME with the operand name at position POS. */
2364 void
2365 dt_operand::gen_opname (char *name, unsigned pos)
2367 if (!parent)
2368 sprintf (name, "op%u", pos);
2369 else
2370 sprintf (name, "o%u%u", level, pos);
2373 /* Generate matching code for the decision tree operand which is
2374 a predicate. */
2376 unsigned
2377 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2379 predicate *p = as_a <predicate *> (op);
2381 if (p->p->matchers.exists ())
2383 /* If this is a predicate generated from a pattern mangle its
2384 name and pass on the valueize hook. */
2385 if (gimple)
2386 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2387 p->p->id, opname);
2388 else
2389 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2391 else
2392 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2393 fprintf_indent (f, indent + 2, "{\n");
2394 return 1;
2397 /* Generate matching code for the decision tree operand which is
2398 a capture-match. */
2400 unsigned
2401 dt_operand::gen_match_op (FILE *f, int indent, const char *opname)
2403 char match_opname[20];
2404 match_dop->get_name (match_opname);
2405 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2406 opname, match_opname, opname, match_opname);
2407 fprintf_indent (f, indent + 2, "{\n");
2408 return 1;
2411 /* Generate GIMPLE matching code for the decision tree operand. */
2413 unsigned
2414 dt_operand::gen_gimple_expr (FILE *f, int indent)
2416 expr *e = static_cast<expr *> (op);
2417 id_base *id = e->operation;
2418 unsigned n_ops = e->ops.length ();
2420 for (unsigned i = 0; i < n_ops; ++i)
2422 char child_opname[20];
2423 gen_opname (child_opname, i);
2425 if (id->kind == id_base::CODE)
2427 if (e->is_generic
2428 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2429 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2431 /* ??? If this is a memory operation we can't (and should not)
2432 match this. The only sensible operand types are
2433 SSA names and invariants. */
2434 fprintf_indent (f, indent,
2435 "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def), %i);\n",
2436 child_opname, i);
2437 fprintf_indent (f, indent,
2438 "if ((TREE_CODE (%s) == SSA_NAME\n",
2439 child_opname);
2440 fprintf_indent (f, indent,
2441 " || is_gimple_min_invariant (%s))\n",
2442 child_opname);
2443 fprintf_indent (f, indent,
2444 " && (%s = do_valueize (valueize, %s)))\n",
2445 child_opname, child_opname);
2446 fprintf_indent (f, indent,
2447 " {\n");
2448 indent += 4;
2449 continue;
2451 else
2452 fprintf_indent (f, indent,
2453 "tree %s = gimple_assign_rhs%u (def);\n",
2454 child_opname, i + 1);
2456 else
2457 fprintf_indent (f, indent,
2458 "tree %s = gimple_call_arg (def, %u);\n",
2459 child_opname, i);
2460 fprintf_indent (f, indent,
2461 "if ((%s = do_valueize (valueize, %s)))\n",
2462 child_opname, child_opname);
2463 fprintf_indent (f, indent, " {\n");
2464 indent += 4;
2466 /* While the toplevel operands are canonicalized by the caller
2467 after valueizing operands of sub-expressions we have to
2468 re-canonicalize operand order. */
2469 if (operator_id *code = dyn_cast <operator_id *> (id))
2471 /* ??? We can't canonicalize tcc_comparison operands here
2472 because that requires changing the comparison code which
2473 we already matched... */
2474 if (commutative_tree_code (code->code)
2475 || commutative_ternary_tree_code (code->code))
2477 char child_opname0[20], child_opname1[20];
2478 gen_opname (child_opname0, 0);
2479 gen_opname (child_opname1, 1);
2480 fprintf_indent (f, indent,
2481 "if (tree_swap_operands_p (%s, %s, false))\n",
2482 child_opname0, child_opname1);
2483 fprintf_indent (f, indent,
2484 " std::swap (%s, %s);\n",
2485 child_opname0, child_opname1);
2489 return n_ops;
2492 /* Generate GENERIC matching code for the decision tree operand. */
2494 unsigned
2495 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2497 expr *e = static_cast<expr *> (op);
2498 unsigned n_ops = e->ops.length ();
2500 for (unsigned i = 0; i < n_ops; ++i)
2502 char child_opname[20];
2503 gen_opname (child_opname, i);
2505 if (e->operation->kind == id_base::CODE)
2506 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2507 child_opname, opname, i);
2508 else
2509 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2510 child_opname, opname, i);
2513 return 0;
2516 /* Generate matching code for the children of the decision tree node. */
2518 void
2519 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2521 auto_vec<dt_operand *> gimple_exprs;
2522 auto_vec<dt_operand *> generic_exprs;
2523 auto_vec<dt_operand *> fns;
2524 auto_vec<dt_operand *> generic_fns;
2525 auto_vec<dt_operand *> preds;
2526 auto_vec<dt_node *> others;
2528 for (unsigned i = 0; i < kids.length (); ++i)
2530 if (kids[i]->type == dt_node::DT_OPERAND)
2532 dt_operand *op = as_a<dt_operand *> (kids[i]);
2533 if (expr *e = dyn_cast <expr *> (op->op))
2535 if (e->ops.length () == 0
2536 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2537 generic_exprs.safe_push (op);
2538 else if (e->operation->kind == id_base::FN)
2540 if (gimple)
2541 fns.safe_push (op);
2542 else
2543 generic_fns.safe_push (op);
2545 else if (e->operation->kind == id_base::PREDICATE)
2546 preds.safe_push (op);
2547 else
2549 if (gimple)
2550 gimple_exprs.safe_push (op);
2551 else
2552 generic_exprs.safe_push (op);
2555 else if (op->op->type == operand::OP_PREDICATE)
2556 others.safe_push (kids[i]);
2557 else
2558 gcc_unreachable ();
2560 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
2561 others.safe_push (kids[i]);
2562 else if (kids[i]->type == dt_node::DT_MATCH
2563 || kids[i]->type == dt_node::DT_TRUE)
2565 /* A DT_TRUE operand serves as a barrier - generate code now
2566 for what we have collected sofar.
2567 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
2568 dependent matches to get out-of-order. Generate code now
2569 for what we have collected sofar. */
2570 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2571 fns, generic_fns, preds, others);
2572 /* And output the true operand itself. */
2573 kids[i]->gen (f, indent, gimple);
2574 gimple_exprs.truncate (0);
2575 generic_exprs.truncate (0);
2576 fns.truncate (0);
2577 generic_fns.truncate (0);
2578 preds.truncate (0);
2579 others.truncate (0);
2581 else
2582 gcc_unreachable ();
2585 /* Generate code for the remains. */
2586 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2587 fns, generic_fns, preds, others);
2590 /* Generate matching code for the children of the decision tree node. */
2592 void
2593 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2594 vec<dt_operand *> gimple_exprs,
2595 vec<dt_operand *> generic_exprs,
2596 vec<dt_operand *> fns,
2597 vec<dt_operand *> generic_fns,
2598 vec<dt_operand *> preds,
2599 vec<dt_node *> others)
2601 char buf[128];
2602 char *kid_opname = buf;
2604 unsigned exprs_len = gimple_exprs.length ();
2605 unsigned gexprs_len = generic_exprs.length ();
2606 unsigned fns_len = fns.length ();
2607 unsigned gfns_len = generic_fns.length ();
2609 if (exprs_len || fns_len || gexprs_len || gfns_len)
2611 if (exprs_len)
2612 gimple_exprs[0]->get_name (kid_opname);
2613 else if (fns_len)
2614 fns[0]->get_name (kid_opname);
2615 else if (gfns_len)
2616 generic_fns[0]->get_name (kid_opname);
2617 else
2618 generic_exprs[0]->get_name (kid_opname);
2620 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2621 fprintf_indent (f, indent, " {\n");
2622 indent += 2;
2625 if (exprs_len || fns_len)
2627 fprintf_indent (f, indent,
2628 "case SSA_NAME:\n");
2629 fprintf_indent (f, indent,
2630 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2631 kid_opname);
2632 fprintf_indent (f, indent,
2633 " {\n");
2634 fprintf_indent (f, indent,
2635 " gimple *def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2636 kid_opname);
2638 indent += 6;
2639 if (exprs_len)
2641 fprintf_indent (f, indent,
2642 "if (gassign *def = dyn_cast <gassign *> (def_stmt))\n");
2643 fprintf_indent (f, indent,
2644 " switch (gimple_assign_rhs_code (def))\n");
2645 indent += 4;
2646 fprintf_indent (f, indent, "{\n");
2647 for (unsigned i = 0; i < exprs_len; ++i)
2649 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2650 id_base *op = e->operation;
2651 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2652 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2653 else
2654 fprintf_indent (f, indent, "case %s:\n", op->id);
2655 fprintf_indent (f, indent, " {\n");
2656 gimple_exprs[i]->gen (f, indent + 4, true);
2657 fprintf_indent (f, indent, " break;\n");
2658 fprintf_indent (f, indent, " }\n");
2660 fprintf_indent (f, indent, "default:;\n");
2661 fprintf_indent (f, indent, "}\n");
2662 indent -= 4;
2665 if (fns_len)
2667 fprintf_indent (f, indent,
2668 "%sif (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))\n",
2669 exprs_len ? "else " : "");
2670 fprintf_indent (f, indent,
2671 " {\n");
2672 fprintf_indent (f, indent,
2673 " gcall *def = as_a <gcall *> (def_stmt);\n");
2674 fprintf_indent (f, indent,
2675 " tree fndecl = gimple_call_fndecl (def);\n");
2676 fprintf_indent (f, indent,
2677 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2678 fprintf_indent (f, indent,
2679 " {\n");
2681 indent += 6;
2682 for (unsigned i = 0; i < fns_len; ++i)
2684 expr *e = as_a <expr *>(fns[i]->op);
2685 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2686 fprintf_indent (f, indent, " {\n");
2687 fns[i]->gen (f, indent + 4, true);
2688 fprintf_indent (f, indent, " break;\n");
2689 fprintf_indent (f, indent, " }\n");
2692 fprintf_indent (f, indent, "default:;\n");
2693 fprintf_indent (f, indent, "}\n");
2694 indent -= 6;
2695 fprintf_indent (f, indent, " }\n");
2698 indent -= 6;
2699 fprintf_indent (f, indent, " }\n");
2700 fprintf_indent (f, indent, " break;\n");
2703 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2705 expr *e = as_a <expr *>(generic_exprs[i]->op);
2706 id_base *op = e->operation;
2707 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2708 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2709 else
2710 fprintf_indent (f, indent, "case %s:\n", op->id);
2711 fprintf_indent (f, indent, " {\n");
2712 generic_exprs[i]->gen (f, indent + 4, gimple);
2713 fprintf_indent (f, indent, " break;\n");
2714 fprintf_indent (f, indent, " }\n");
2717 if (gfns_len)
2719 fprintf_indent (f, indent,
2720 "case CALL_EXPR:\n");
2721 fprintf_indent (f, indent,
2722 " {\n");
2723 fprintf_indent (f, indent,
2724 " tree fndecl = get_callee_fndecl (%s);\n",
2725 kid_opname);
2726 fprintf_indent (f, indent,
2727 " if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)\n");
2728 fprintf_indent (f, indent,
2729 " switch (DECL_FUNCTION_CODE (fndecl))\n");
2730 fprintf_indent (f, indent,
2731 " {\n");
2732 indent += 8;
2734 for (unsigned j = 0; j < generic_fns.length (); ++j)
2736 expr *e = as_a <expr *>(generic_fns[j]->op);
2737 gcc_assert (e->operation->kind == id_base::FN);
2739 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2740 fprintf_indent (f, indent, " {\n");
2741 generic_fns[j]->gen (f, indent + 4, false);
2742 fprintf_indent (f, indent, " break;\n");
2743 fprintf_indent (f, indent, " }\n");
2746 indent -= 8;
2747 fprintf_indent (f, indent, " default:;\n");
2748 fprintf_indent (f, indent, " }\n");
2749 fprintf_indent (f, indent, " break;\n");
2750 fprintf_indent (f, indent, " }\n");
2753 /* Close switch (TREE_CODE ()). */
2754 if (exprs_len || fns_len || gexprs_len || gfns_len)
2756 indent -= 4;
2757 fprintf_indent (f, indent, " default:;\n");
2758 fprintf_indent (f, indent, " }\n");
2761 for (unsigned i = 0; i < preds.length (); ++i)
2763 expr *e = as_a <expr *> (preds[i]->op);
2764 predicate_id *p = as_a <predicate_id *> (e->operation);
2765 preds[i]->get_name (kid_opname);
2766 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2767 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2768 gimple ? "gimple" : "tree",
2769 p->id, kid_opname, kid_opname,
2770 gimple ? ", valueize" : "");
2771 fprintf_indent (f, indent, " {\n");
2772 for (int j = 0; j < p->nargs; ++j)
2774 char child_opname[20];
2775 preds[i]->gen_opname (child_opname, j);
2776 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
2777 child_opname, kid_opname, j);
2779 preds[i]->gen_kids (f, indent + 4, gimple);
2780 fprintf (f, "}\n");
2783 for (unsigned i = 0; i < others.length (); ++i)
2784 others[i]->gen (f, indent, gimple);
2787 /* Generate matching code for the decision tree operand. */
2789 void
2790 dt_operand::gen (FILE *f, int indent, bool gimple)
2792 char opname[20];
2793 get_name (opname);
2795 unsigned n_braces = 0;
2797 if (type == DT_OPERAND)
2798 switch (op->type)
2800 case operand::OP_PREDICATE:
2801 n_braces = gen_predicate (f, indent, opname, gimple);
2802 break;
2804 case operand::OP_EXPR:
2805 if (gimple)
2806 n_braces = gen_gimple_expr (f, indent);
2807 else
2808 n_braces = gen_generic_expr (f, indent, opname);
2809 break;
2811 default:
2812 gcc_unreachable ();
2814 else if (type == DT_TRUE)
2816 else if (type == DT_MATCH)
2817 n_braces = gen_match_op (f, indent, opname);
2818 else
2819 gcc_unreachable ();
2821 indent += 4 * n_braces;
2822 gen_kids (f, indent, gimple);
2824 for (unsigned i = 0; i < n_braces; ++i)
2826 indent -= 4;
2827 if (indent < 0)
2828 indent = 0;
2829 fprintf_indent (f, indent, " }\n");
2834 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2835 step of a '(simplify ...)' or '(match ...)'. This handles everything
2836 that is not part of the decision tree (simplify->match).
2837 Main recursive worker. */
2839 void
2840 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
2842 if (result)
2844 if (with_expr *w = dyn_cast <with_expr *> (result))
2846 fprintf_indent (f, indent, "{\n");
2847 indent += 4;
2848 output_line_directive (f, w->location);
2849 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2850 gen_1 (f, indent, gimple, w->subexpr);
2851 indent -= 4;
2852 fprintf_indent (f, indent, "}\n");
2853 return;
2855 else if (if_expr *ife = dyn_cast <if_expr *> (result))
2857 output_line_directive (f, ife->location);
2858 fprintf_indent (f, indent, "if (");
2859 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2860 fprintf (f, ")\n");
2861 fprintf_indent (f, indent + 2, "{\n");
2862 indent += 4;
2863 gen_1 (f, indent, gimple, ife->trueexpr);
2864 indent -= 4;
2865 fprintf_indent (f, indent + 2, "}\n");
2866 if (ife->falseexpr)
2868 fprintf_indent (f, indent, "else\n");
2869 fprintf_indent (f, indent + 2, "{\n");
2870 indent += 4;
2871 gen_1 (f, indent, gimple, ife->falseexpr);
2872 indent -= 4;
2873 fprintf_indent (f, indent + 2, "}\n");
2875 return;
2879 /* Analyze captures and perform early-outs on the incoming arguments
2880 that cover cases we cannot handle. */
2881 capture_info cinfo (s, result, gimple);
2882 if (s->kind == simplify::SIMPLIFY)
2884 if (!gimple)
2886 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2887 if (cinfo.force_no_side_effects & (1 << i))
2889 fprintf_indent (f, indent,
2890 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
2892 if (verbose >= 1)
2893 warning_at (as_a <expr *> (s->match)->ops[i]->location,
2894 "forcing toplevel operand to have no "
2895 "side-effects");
2897 for (int i = 0; i <= s->capture_max; ++i)
2898 if (cinfo.info[i].cse_p)
2900 else if (cinfo.info[i].force_no_side_effects_p
2901 && (cinfo.info[i].toplevel_msk
2902 & cinfo.force_no_side_effects) == 0)
2904 fprintf_indent (f, indent,
2905 "if (TREE_SIDE_EFFECTS (captures[%d])) "
2906 "return NULL_TREE;\n", i);
2907 if (verbose >= 1)
2908 warning_at (cinfo.info[i].c->location,
2909 "forcing captured operand to have no "
2910 "side-effects");
2912 else if ((cinfo.info[i].toplevel_msk
2913 & cinfo.force_no_side_effects) != 0)
2914 /* Mark capture as having no side-effects if we had to verify
2915 that via forced toplevel operand checks. */
2916 cinfo.info[i].force_no_side_effects_p = true;
2918 if (gimple)
2920 /* Force single-use restriction by only allowing simple
2921 results via setting seq to NULL. */
2922 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
2923 bool first_p = true;
2924 for (int i = 0; i <= s->capture_max; ++i)
2925 if (cinfo.info[i].force_single_use)
2927 if (first_p)
2929 fprintf_indent (f, indent, "if (lseq\n");
2930 fprintf_indent (f, indent, " && (");
2931 first_p = false;
2933 else
2935 fprintf (f, "\n");
2936 fprintf_indent (f, indent, " || ");
2938 fprintf (f, "!single_use (captures[%d])", i);
2940 if (!first_p)
2942 fprintf (f, "))\n");
2943 fprintf_indent (f, indent, " lseq = NULL;\n");
2948 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
2949 "fprintf (dump_file, \"Applying pattern ");
2950 output_line_directive (f,
2951 result ? result->location : s->match->location, true);
2952 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
2954 if (!result)
2956 /* If there is no result then this is a predicate implementation. */
2957 fprintf_indent (f, indent, "return true;\n");
2959 else if (gimple)
2961 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
2962 in outermost position). */
2963 if (result->type == operand::OP_EXPR
2964 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
2965 result = as_a <expr *> (result)->ops[0];
2966 if (result->type == operand::OP_EXPR)
2968 expr *e = as_a <expr *> (result);
2969 id_base *opr = e->operation;
2970 bool is_predicate = false;
2971 /* When we delay operator substituting during lowering of fors we
2972 make sure that for code-gen purposes the effects of each substitute
2973 are the same. Thus just look at that. */
2974 if (user_id *uid = dyn_cast <user_id *> (opr))
2975 opr = uid->substitutes[0];
2976 else if (is_a <predicate_id *> (opr))
2977 is_predicate = true;
2978 if (!is_predicate)
2979 fprintf_indent (f, indent, "*res_code = %s;\n",
2980 *e->operation == CONVERT_EXPR
2981 ? "NOP_EXPR" : e->operation->id);
2982 for (unsigned j = 0; j < e->ops.length (); ++j)
2984 char dest[32];
2985 snprintf (dest, 32, "res_ops[%d]", j);
2986 const char *optype
2987 = get_operand_type (opr,
2988 "type", e->expr_type,
2989 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
2990 /* We need to expand GENERIC conditions we captured from
2991 COND_EXPRs. */
2992 bool expand_generic_cond_exprs_p
2993 = (!is_predicate
2994 /* But avoid doing that if the GENERIC condition is
2995 valid - which it is in the first operand of COND_EXPRs
2996 and VEC_COND_EXRPs. */
2997 && ((!(*opr == COND_EXPR)
2998 && !(*opr == VEC_COND_EXPR))
2999 || j != 0));
3000 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3001 &cinfo,
3002 indexes, expand_generic_cond_exprs_p);
3005 /* Re-fold the toplevel result. It's basically an embedded
3006 gimple_build w/o actually building the stmt. */
3007 if (!is_predicate)
3008 fprintf_indent (f, indent,
3009 "gimple_resimplify%d (lseq, res_code, type, "
3010 "res_ops, valueize);\n", e->ops.length ());
3012 else if (result->type == operand::OP_CAPTURE
3013 || result->type == operand::OP_C_EXPR)
3015 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
3016 &cinfo, indexes, false);
3017 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
3018 if (is_a <capture *> (result)
3019 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3021 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3022 with substituting a capture of that. */
3023 fprintf_indent (f, indent,
3024 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
3025 fprintf_indent (f, indent,
3026 " {\n");
3027 fprintf_indent (f, indent,
3028 " tree tem = res_ops[0];\n");
3029 fprintf_indent (f, indent,
3030 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
3031 fprintf_indent (f, indent,
3032 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
3033 fprintf_indent (f, indent,
3034 " }\n");
3037 else
3038 gcc_unreachable ();
3039 fprintf_indent (f, indent, "return true;\n");
3041 else /* GENERIC */
3043 bool is_predicate = false;
3044 if (result->type == operand::OP_EXPR)
3046 expr *e = as_a <expr *> (result);
3047 id_base *opr = e->operation;
3048 /* When we delay operator substituting during lowering of fors we
3049 make sure that for code-gen purposes the effects of each substitute
3050 are the same. Thus just look at that. */
3051 if (user_id *uid = dyn_cast <user_id *> (opr))
3052 opr = uid->substitutes[0];
3053 else if (is_a <predicate_id *> (opr))
3054 is_predicate = true;
3055 /* Search for captures used multiple times in the result expression
3056 and dependent on TREE_SIDE_EFFECTS emit a SAVE_EXPR. */
3057 if (!is_predicate)
3058 for (int i = 0; i < s->capture_max + 1; ++i)
3060 if (cinfo.info[i].same_as != (unsigned)i)
3061 continue;
3062 if (!cinfo.info[i].force_no_side_effects_p
3063 && cinfo.info[i].result_use_count > 1)
3065 fprintf_indent (f, indent,
3066 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3068 fprintf_indent (f, indent,
3069 " captures[%d] = save_expr (captures[%d]);\n",
3070 i, i);
3073 for (unsigned j = 0; j < e->ops.length (); ++j)
3075 char dest[32];
3076 if (is_predicate)
3077 snprintf (dest, 32, "res_ops[%d]", j);
3078 else
3080 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3081 snprintf (dest, 32, "res_op%d", j);
3083 const char *optype
3084 = get_operand_type (opr,
3085 "type", e->expr_type,
3086 j == 0
3087 ? NULL : "TREE_TYPE (res_op0)");
3088 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3089 &cinfo, indexes);
3091 if (is_predicate)
3092 fprintf_indent (f, indent, "return true;\n");
3093 else
3095 fprintf_indent (f, indent, "tree res;\n");
3096 /* Re-fold the toplevel result. Use non_lvalue to
3097 build NON_LVALUE_EXPRs so they get properly
3098 ignored when in GIMPLE form. */
3099 if (*opr == NON_LVALUE_EXPR)
3100 fprintf_indent (f, indent,
3101 "res = non_lvalue_loc (loc, res_op0);\n");
3102 else
3104 if (is_a <operator_id *> (opr))
3105 fprintf_indent (f, indent,
3106 "res = fold_build%d_loc (loc, %s, type",
3107 e->ops.length (),
3108 *e->operation == CONVERT_EXPR
3109 ? "NOP_EXPR" : e->operation->id);
3110 else
3112 fprintf_indent (f, indent,
3113 "{\n");
3114 fprintf_indent (f, indent,
3115 " tree decl = builtin_decl_implicit (%s);\n",
3116 e->operation->id);
3117 fprintf_indent (f, indent,
3118 " if (!decl) return NULL_TREE;\n");
3119 fprintf_indent (f, indent,
3120 " res = build_call_expr_loc "
3121 "(loc, decl, %d",
3122 e->ops.length());
3124 for (unsigned j = 0; j < e->ops.length (); ++j)
3125 fprintf (f, ", res_op%d", j);
3126 fprintf (f, ");\n");
3127 if (!is_a <operator_id *> (opr))
3128 fprintf_indent (f, indent, "}\n");
3132 else if (result->type == operand::OP_CAPTURE
3133 || result->type == operand::OP_C_EXPR)
3136 fprintf_indent (f, indent, "tree res;\n");
3137 result->gen_transform (f, indent, "res", false, 1, "type",
3138 &cinfo, indexes);
3140 else
3141 gcc_unreachable ();
3142 if (!is_predicate)
3144 /* Search for captures not used in the result expression and dependent
3145 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3146 for (int i = 0; i < s->capture_max + 1; ++i)
3148 if (cinfo.info[i].same_as != (unsigned)i)
3149 continue;
3150 if (!cinfo.info[i].force_no_side_effects_p
3151 && !cinfo.info[i].expr_p
3152 && cinfo.info[i].result_use_count == 0)
3154 fprintf_indent (f, indent,
3155 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3157 fprintf_indent (f, indent + 2,
3158 "res = build2_loc (loc, COMPOUND_EXPR, type, "
3159 "fold_ignored_result (captures[%d]), res);\n",
3163 fprintf_indent (f, indent, "return res;\n");
3168 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3169 step of a '(simplify ...)' or '(match ...)'. This handles everything
3170 that is not part of the decision tree (simplify->match). */
3172 void
3173 dt_simplify::gen (FILE *f, int indent, bool gimple)
3175 fprintf_indent (f, indent, "{\n");
3176 indent += 2;
3177 output_line_directive (f,
3178 s->result ? s->result->location : s->match->location);
3179 if (s->capture_max >= 0)
3181 char opname[20];
3182 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3183 s->capture_max + 1, indexes[0]->get_name (opname));
3185 for (int i = 1; i <= s->capture_max; ++i)
3187 if (!indexes[i])
3188 break;
3189 fprintf (f, ", %s", indexes[i]->get_name (opname));
3191 fprintf (f, " };\n");
3194 /* If we have a split-out function for the actual transform, call it. */
3195 if (info && info->fname)
3197 if (gimple)
3199 fprintf_indent (f, indent, "if (%s (res_code, res_ops, seq, "
3200 "valueize, type, captures", info->fname);
3201 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3202 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3203 fprintf (f, "))\n");
3204 fprintf_indent (f, indent, " return true;\n");
3206 else
3208 fprintf_indent (f, indent, "tree res = %s (loc, type",
3209 info->fname);
3210 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3211 fprintf (f, ", op%d", i);
3212 fprintf (f, ", captures");
3213 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3214 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3215 fprintf (f, ");\n");
3216 fprintf_indent (f, indent, "if (res) return res;\n");
3219 else
3221 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3223 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3224 fprintf_indent (f, indent, "enum tree_code %s = %s;\n",
3225 s->for_subst_vec[i].first->id,
3226 s->for_subst_vec[i].second->id);
3227 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3228 fprintf_indent (f, indent, "enum built_in_function %s = %s;\n",
3229 s->for_subst_vec[i].first->id,
3230 s->for_subst_vec[i].second->id);
3231 else
3232 gcc_unreachable ();
3234 gen_1 (f, indent, gimple, s->result);
3237 indent -= 2;
3238 fprintf_indent (f, indent, "}\n");
3242 /* Hash function for finding equivalent transforms. */
3244 hashval_t
3245 sinfo_hashmap_traits::hash (const key_type &v)
3247 /* Only bother to compare those originating from the same source pattern. */
3248 return v->s->result->location;
3251 /* Compare function for finding equivalent transforms. */
3253 static bool
3254 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3256 if (o1->type != o2->type)
3257 return false;
3259 switch (o1->type)
3261 case operand::OP_IF:
3263 if_expr *if1 = as_a <if_expr *> (o1);
3264 if_expr *if2 = as_a <if_expr *> (o2);
3265 /* ??? Properly compare c-exprs. */
3266 if (if1->cond != if2->cond)
3267 return false;
3268 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3269 return false;
3270 if (if1->falseexpr != if2->falseexpr
3271 || (if1->falseexpr
3272 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3273 return false;
3274 return true;
3276 case operand::OP_WITH:
3278 with_expr *with1 = as_a <with_expr *> (o1);
3279 with_expr *with2 = as_a <with_expr *> (o2);
3280 if (with1->with != with2->with)
3281 return false;
3282 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3284 default:;
3287 /* We've hit a result. Time to compare capture-infos - this is required
3288 in addition to the conservative pointer-equivalency of the result IL. */
3289 capture_info cinfo1 (s1, o1, true);
3290 capture_info cinfo2 (s2, o2, true);
3292 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3293 || cinfo1.info.length () != cinfo2.info.length ())
3294 return false;
3296 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3298 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3299 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3300 || (cinfo1.info[i].force_no_side_effects_p
3301 != cinfo2.info[i].force_no_side_effects_p)
3302 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3303 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3304 /* toplevel_msk is an optimization */
3305 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3306 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3307 /* the pointer back to the capture is for diagnostics only */)
3308 return false;
3311 /* ??? Deep-compare the actual result. */
3312 return o1 == o2;
3315 bool
3316 sinfo_hashmap_traits::equal_keys (const key_type &v,
3317 const key_type &candidate)
3319 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3323 /* Main entry to generate code for matching GIMPLE IL off the decision
3324 tree. */
3326 void
3327 decision_tree::gen (FILE *f, bool gimple)
3329 sinfo_map_t si;
3331 root->analyze (si);
3333 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3334 "a total number of %u nodes\n",
3335 gimple ? "GIMPLE" : "GENERIC",
3336 root->num_leafs, root->max_level, root->total_size);
3338 /* First split out the transform part of equal leafs. */
3339 unsigned rcnt = 0;
3340 unsigned fcnt = 1;
3341 for (sinfo_map_t::iterator iter = si.begin ();
3342 iter != si.end (); ++iter)
3344 sinfo *s = (*iter).second;
3345 /* Do not split out single uses. */
3346 if (s->cnt <= 1)
3347 continue;
3349 rcnt += s->cnt - 1;
3350 if (verbose >= 1)
3352 fprintf (stderr, "found %u uses of", s->cnt);
3353 output_line_directive (stderr, s->s->s->result->location);
3356 /* Generate a split out function with the leaf transform code. */
3357 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3358 fcnt++);
3359 if (gimple)
3360 fprintf (f, "\nstatic bool\n"
3361 "%s (code_helper *res_code, tree *res_ops,\n"
3362 " gimple_seq *seq, tree (*valueize)(tree) "
3363 "ATTRIBUTE_UNUSED,\n"
3364 " tree ARG_UNUSED (type), tree *ARG_UNUSED "
3365 "(captures)\n",
3366 s->fname);
3367 else
3369 fprintf (f, "\nstatic tree\n"
3370 "%s (location_t ARG_UNUSED (loc), tree ARG_UNUSED (type),\n",
3371 (*iter).second->fname);
3372 for (unsigned i = 0;
3373 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3374 fprintf (f, " tree ARG_UNUSED (op%d),", i);
3375 fprintf (f, " tree *captures\n");
3377 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3379 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3380 fprintf (f, ", enum tree_code ARG_UNUSED (%s)",
3381 s->s->s->for_subst_vec[i].first->id);
3382 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3383 fprintf (f, ", enum built_in_function ARG_UNUSED (%s)",
3384 s->s->s->for_subst_vec[i].first->id);
3387 fprintf (f, ")\n{\n");
3388 s->s->gen_1 (f, 2, gimple, s->s->s->result);
3389 if (gimple)
3390 fprintf (f, " return false;\n");
3391 else
3392 fprintf (f, " return NULL_TREE;\n");
3393 fprintf (f, "}\n");
3395 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3397 for (unsigned n = 1; n <= 3; ++n)
3399 /* First generate split-out functions. */
3400 for (unsigned i = 0; i < root->kids.length (); i++)
3402 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3403 expr *e = static_cast<expr *>(dop->op);
3404 if (e->ops.length () != n
3405 /* Builtin simplifications are somewhat premature on
3406 GENERIC. The following drops patterns with outermost
3407 calls. It's easy to emit overloads for function code
3408 though if necessary. */
3409 || (!gimple
3410 && e->operation->kind != id_base::CODE))
3411 continue;
3413 if (gimple)
3414 fprintf (f, "\nstatic bool\n"
3415 "gimple_simplify_%s (code_helper *res_code, tree *res_ops,\n"
3416 " gimple_seq *seq, tree (*valueize)(tree) "
3417 "ATTRIBUTE_UNUSED,\n"
3418 " code_helper ARG_UNUSED (code), tree "
3419 "ARG_UNUSED (type)\n",
3420 e->operation->id);
3421 else
3422 fprintf (f, "\nstatic tree\n"
3423 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3424 "tree_code ARG_UNUSED (code), tree ARG_UNUSED (type)",
3425 e->operation->id);
3426 for (unsigned i = 0; i < n; ++i)
3427 fprintf (f, ", tree op%d", i);
3428 fprintf (f, ")\n");
3429 fprintf (f, "{\n");
3430 dop->gen_kids (f, 2, gimple);
3431 if (gimple)
3432 fprintf (f, " return false;\n");
3433 else
3434 fprintf (f, " return NULL_TREE;\n");
3435 fprintf (f, "}\n");
3438 /* Then generate the main entry with the outermost switch and
3439 tail-calls to the split-out functions. */
3440 if (gimple)
3441 fprintf (f, "\nstatic bool\n"
3442 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
3443 " gimple_seq *seq, tree (*valueize)(tree),\n"
3444 " code_helper code, tree type");
3445 else
3446 fprintf (f, "\ntree\n"
3447 "generic_simplify (location_t loc, enum tree_code code, "
3448 "tree type ATTRIBUTE_UNUSED");
3449 for (unsigned i = 0; i < n; ++i)
3450 fprintf (f, ", tree op%d", i);
3451 fprintf (f, ")\n");
3452 fprintf (f, "{\n");
3454 if (gimple)
3455 fprintf (f, " switch (code.get_rep())\n"
3456 " {\n");
3457 else
3458 fprintf (f, " switch (code)\n"
3459 " {\n");
3460 for (unsigned i = 0; i < root->kids.length (); i++)
3462 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3463 expr *e = static_cast<expr *>(dop->op);
3464 if (e->ops.length () != n
3465 /* Builtin simplifications are somewhat premature on
3466 GENERIC. The following drops patterns with outermost
3467 calls. It's easy to emit overloads for function code
3468 though if necessary. */
3469 || (!gimple
3470 && e->operation->kind != id_base::CODE))
3471 continue;
3473 if (*e->operation == CONVERT_EXPR
3474 || *e->operation == NOP_EXPR)
3475 fprintf (f, " CASE_CONVERT:\n");
3476 else
3477 fprintf (f, " case %s%s:\n",
3478 is_a <fn_id *> (e->operation) ? "-" : "",
3479 e->operation->id);
3480 if (gimple)
3481 fprintf (f, " return gimple_simplify_%s (res_code, res_ops, "
3482 "seq, valueize, code, type", e->operation->id);
3483 else
3484 fprintf (f, " return generic_simplify_%s (loc, code, type",
3485 e->operation->id);
3486 for (unsigned i = 0; i < n; ++i)
3487 fprintf (f, ", op%d", i);
3488 fprintf (f, ");\n");
3490 fprintf (f, " default:;\n"
3491 " }\n");
3493 if (gimple)
3494 fprintf (f, " return false;\n");
3495 else
3496 fprintf (f, " return NULL_TREE;\n");
3497 fprintf (f, "}\n");
3501 /* Output code to implement the predicate P from the decision tree DT. */
3503 void
3504 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3506 fprintf (f, "\nbool\n"
3507 "%s%s (tree t%s%s)\n"
3508 "{\n", gimple ? "gimple_" : "tree_", p->id,
3509 p->nargs > 0 ? ", tree *res_ops" : "",
3510 gimple ? ", tree (*valueize)(tree)" : "");
3511 /* Conveniently make 'type' available. */
3512 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
3514 if (!gimple)
3515 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3516 dt.root->gen_kids (f, 2, gimple);
3518 fprintf_indent (f, 2, "return false;\n"
3519 "}\n");
3522 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
3524 static void
3525 write_header (FILE *f, const char *head)
3527 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3528 fprintf (f, " a IL pattern matching and simplification description. */\n");
3530 /* Include the header instead of writing it awkwardly quoted here. */
3531 fprintf (f, "\n#include \"%s\"\n", head);
3536 /* AST parsing. */
3538 class parser
3540 public:
3541 parser (cpp_reader *);
3543 private:
3544 const cpp_token *next ();
3545 const cpp_token *peek (unsigned = 1);
3546 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3547 const cpp_token *expect (enum cpp_ttype);
3548 const cpp_token *eat_token (enum cpp_ttype);
3549 const char *get_string ();
3550 const char *get_ident ();
3551 const cpp_token *eat_ident (const char *);
3552 const char *get_number ();
3554 id_base *parse_operation ();
3555 operand *parse_capture (operand *, bool);
3556 operand *parse_expr ();
3557 c_expr *parse_c_expr (cpp_ttype);
3558 operand *parse_op ();
3560 void record_operlist (source_location, user_id *);
3562 void parse_pattern ();
3563 operand *parse_result (operand *, predicate_id *);
3564 void push_simplify (simplify::simplify_kind,
3565 vec<simplify *>&, operand *, operand *);
3566 void parse_simplify (simplify::simplify_kind,
3567 vec<simplify *>&, predicate_id *, operand *);
3568 void parse_for (source_location);
3569 void parse_if (source_location);
3570 void parse_predicates (source_location);
3571 void parse_operator_list (source_location);
3573 cpp_reader *r;
3574 vec<c_expr *> active_ifs;
3575 vec<vec<user_id *> > active_fors;
3576 hash_set<user_id *> *oper_lists_set;
3577 vec<user_id *> oper_lists;
3579 cid_map_t *capture_ids;
3581 public:
3582 vec<simplify *> simplifiers;
3583 vec<predicate_id *> user_predicates;
3584 bool parsing_match_operand;
3587 /* Lexing helpers. */
3589 /* Read the next non-whitespace token from R. */
3591 const cpp_token *
3592 parser::next ()
3594 const cpp_token *token;
3597 token = cpp_get_token (r);
3599 while (token->type == CPP_PADDING
3600 && token->type != CPP_EOF);
3601 return token;
3604 /* Peek at the next non-whitespace token from R. */
3606 const cpp_token *
3607 parser::peek (unsigned num)
3609 const cpp_token *token;
3610 unsigned i = 0;
3613 token = cpp_peek_token (r, i++);
3615 while ((token->type == CPP_PADDING
3616 && token->type != CPP_EOF)
3617 || (--num > 0));
3618 /* If we peek at EOF this is a fatal error as it leaves the
3619 cpp_reader in unusable state. Assume we really wanted a
3620 token and thus this EOF is unexpected. */
3621 if (token->type == CPP_EOF)
3622 fatal_at (token, "unexpected end of file");
3623 return token;
3626 /* Peek at the next identifier token (or return NULL if the next
3627 token is not an identifier or equal to ID if supplied). */
3629 const cpp_token *
3630 parser::peek_ident (const char *id, unsigned num)
3632 const cpp_token *token = peek (num);
3633 if (token->type != CPP_NAME)
3634 return 0;
3636 if (id == 0)
3637 return token;
3639 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3640 if (strcmp (id, t) == 0)
3641 return token;
3643 return 0;
3646 /* Read the next token from R and assert it is of type TK. */
3648 const cpp_token *
3649 parser::expect (enum cpp_ttype tk)
3651 const cpp_token *token = next ();
3652 if (token->type != tk)
3653 fatal_at (token, "expected %s, got %s",
3654 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3656 return token;
3659 /* Consume the next token from R and assert it is of type TK. */
3661 const cpp_token *
3662 parser::eat_token (enum cpp_ttype tk)
3664 return expect (tk);
3667 /* Read the next token from R and assert it is of type CPP_STRING and
3668 return its value. */
3670 const char *
3671 parser::get_string ()
3673 const cpp_token *token = expect (CPP_STRING);
3674 return (const char *)token->val.str.text;
3677 /* Read the next token from R and assert it is of type CPP_NAME and
3678 return its value. */
3680 const char *
3681 parser::get_ident ()
3683 const cpp_token *token = expect (CPP_NAME);
3684 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3687 /* Eat an identifier token with value S from R. */
3689 const cpp_token *
3690 parser::eat_ident (const char *s)
3692 const cpp_token *token = peek ();
3693 const char *t = get_ident ();
3694 if (strcmp (s, t) != 0)
3695 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3696 return token;
3699 /* Read the next token from R and assert it is of type CPP_NUMBER and
3700 return its value. */
3702 const char *
3703 parser::get_number ()
3705 const cpp_token *token = expect (CPP_NUMBER);
3706 return (const char *)token->val.str.text;
3710 /* Record an operator-list use for transparent for handling. */
3712 void
3713 parser::record_operlist (source_location loc, user_id *p)
3715 if (!oper_lists_set->add (p))
3717 if (!oper_lists.is_empty ()
3718 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3719 fatal_at (loc, "User-defined operator list does not have the "
3720 "same number of entries as others used in the pattern");
3721 oper_lists.safe_push (p);
3725 /* Parse the operator ID, special-casing convert?, convert1? and
3726 convert2? */
3728 id_base *
3729 parser::parse_operation ()
3731 const cpp_token *id_tok = peek ();
3732 const char *id = get_ident ();
3733 const cpp_token *token = peek ();
3734 if (strcmp (id, "convert0") == 0)
3735 fatal_at (id_tok, "use 'convert?' here");
3736 else if (strcmp (id, "view_convert0") == 0)
3737 fatal_at (id_tok, "use 'view_convert?' here");
3738 if (token->type == CPP_QUERY
3739 && !(token->flags & PREV_WHITE))
3741 if (strcmp (id, "convert") == 0)
3742 id = "convert0";
3743 else if (strcmp (id, "convert1") == 0)
3745 else if (strcmp (id, "convert2") == 0)
3747 else if (strcmp (id, "view_convert") == 0)
3748 id = "view_convert0";
3749 else if (strcmp (id, "view_convert1") == 0)
3751 else if (strcmp (id, "view_convert2") == 0)
3753 else
3754 fatal_at (id_tok, "non-convert operator conditionalized");
3756 if (!parsing_match_operand)
3757 fatal_at (id_tok, "conditional convert can only be used in "
3758 "match expression");
3759 eat_token (CPP_QUERY);
3761 else if (strcmp (id, "convert1") == 0
3762 || strcmp (id, "convert2") == 0
3763 || strcmp (id, "view_convert1") == 0
3764 || strcmp (id, "view_convert2") == 0)
3765 fatal_at (id_tok, "expected '?' after conditional operator");
3766 id_base *op = get_operator (id);
3767 if (!op)
3768 fatal_at (id_tok, "unknown operator %s", id);
3770 user_id *p = dyn_cast<user_id *> (op);
3771 if (p && p->is_oper_list)
3773 if (active_fors.length() == 0)
3774 record_operlist (id_tok->src_loc, p);
3775 else
3776 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
3778 return op;
3781 /* Parse a capture.
3782 capture = '@'<number> */
3784 struct operand *
3785 parser::parse_capture (operand *op, bool require_existing)
3787 source_location src_loc = eat_token (CPP_ATSIGN)->src_loc;
3788 const cpp_token *token = peek ();
3789 const char *id = NULL;
3790 if (token->type == CPP_NUMBER)
3791 id = get_number ();
3792 else if (token->type == CPP_NAME)
3793 id = get_ident ();
3794 else
3795 fatal_at (token, "expected number or identifier");
3796 unsigned next_id = capture_ids->elements ();
3797 bool existed;
3798 unsigned &num = capture_ids->get_or_insert (id, &existed);
3799 if (!existed)
3801 if (require_existing)
3802 fatal_at (src_loc, "unknown capture id");
3803 num = next_id;
3805 return new capture (src_loc, num, op);
3808 /* Parse an expression
3809 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
3811 struct operand *
3812 parser::parse_expr ()
3814 const cpp_token *token = peek ();
3815 expr *e = new expr (parse_operation (), token->src_loc);
3816 token = peek ();
3817 operand *op;
3818 bool is_commutative = false;
3819 bool force_capture = false;
3820 const char *expr_type = NULL;
3822 if (token->type == CPP_COLON
3823 && !(token->flags & PREV_WHITE))
3825 eat_token (CPP_COLON);
3826 token = peek ();
3827 if (token->type == CPP_NAME
3828 && !(token->flags & PREV_WHITE))
3830 const char *s = get_ident ();
3831 if (!parsing_match_operand)
3832 expr_type = s;
3833 else
3835 const char *sp = s;
3836 while (*sp)
3838 if (*sp == 'c')
3839 is_commutative = true;
3840 else if (*sp == 's')
3842 e->force_single_use = true;
3843 force_capture = true;
3845 else
3846 fatal_at (token, "flag %c not recognized", *sp);
3847 sp++;
3850 token = peek ();
3852 else
3853 fatal_at (token, "expected flag or type specifying identifier");
3856 if (token->type == CPP_ATSIGN
3857 && !(token->flags & PREV_WHITE))
3858 op = parse_capture (e, false);
3859 else if (force_capture)
3861 unsigned num = capture_ids->elements ();
3862 char id[8];
3863 bool existed;
3864 sprintf (id, "__%u", num);
3865 capture_ids->get_or_insert (xstrdup (id), &existed);
3866 if (existed)
3867 fatal_at (token, "reserved capture id '%s' already used", id);
3868 op = new capture (token->src_loc, num, e);
3870 else
3871 op = e;
3874 const cpp_token *token = peek ();
3875 if (token->type == CPP_CLOSE_PAREN)
3877 if (e->operation->nargs != -1
3878 && e->operation->nargs != (int) e->ops.length ())
3879 fatal_at (token, "'%s' expects %u operands, not %u",
3880 e->operation->id, e->operation->nargs, e->ops.length ());
3881 if (is_commutative)
3883 if (e->ops.length () == 2)
3884 e->is_commutative = true;
3885 else
3886 fatal_at (token, "only binary operators or function with "
3887 "two arguments can be marked commutative");
3889 e->expr_type = expr_type;
3890 return op;
3892 else if (!(token->flags & PREV_WHITE))
3893 fatal_at (token, "expected expression operand");
3895 e->append_op (parse_op ());
3897 while (1);
3900 /* Lex native C code delimited by START recording the preprocessing tokens
3901 for later processing.
3902 c_expr = ('{'|'(') <pp token>... ('}'|')') */
3904 c_expr *
3905 parser::parse_c_expr (cpp_ttype start)
3907 const cpp_token *token;
3908 cpp_ttype end;
3909 unsigned opencnt;
3910 vec<cpp_token> code = vNULL;
3911 unsigned nr_stmts = 0;
3912 source_location loc = eat_token (start)->src_loc;
3913 if (start == CPP_OPEN_PAREN)
3914 end = CPP_CLOSE_PAREN;
3915 else if (start == CPP_OPEN_BRACE)
3916 end = CPP_CLOSE_BRACE;
3917 else
3918 gcc_unreachable ();
3919 opencnt = 1;
3922 token = next ();
3924 /* Count brace pairs to find the end of the expr to match. */
3925 if (token->type == start)
3926 opencnt++;
3927 else if (token->type == end
3928 && --opencnt == 0)
3929 break;
3931 /* This is a lame way of counting the number of statements. */
3932 if (token->type == CPP_SEMICOLON)
3933 nr_stmts++;
3935 /* If this is possibly a user-defined identifier mark it used. */
3936 if (token->type == CPP_NAME)
3938 id_base *idb = get_operator ((const char *)CPP_HASHNODE
3939 (token->val.node.node)->ident.str);
3940 user_id *p;
3941 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
3942 record_operlist (token->src_loc, p);
3945 /* Record the token. */
3946 code.safe_push (*token);
3948 while (1);
3949 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
3952 /* Parse an operand which is either an expression, a predicate or
3953 a standalone capture.
3954 op = predicate | expr | c_expr | capture */
3956 struct operand *
3957 parser::parse_op ()
3959 const cpp_token *token = peek ();
3960 struct operand *op = NULL;
3961 if (token->type == CPP_OPEN_PAREN)
3963 eat_token (CPP_OPEN_PAREN);
3964 op = parse_expr ();
3965 eat_token (CPP_CLOSE_PAREN);
3967 else if (token->type == CPP_OPEN_BRACE)
3969 op = parse_c_expr (CPP_OPEN_BRACE);
3971 else
3973 /* Remaining ops are either empty or predicates */
3974 if (token->type == CPP_NAME)
3976 const char *id = get_ident ();
3977 id_base *opr = get_operator (id);
3978 if (!opr)
3979 fatal_at (token, "expected predicate name");
3980 if (operator_id *code = dyn_cast <operator_id *> (opr))
3982 if (code->nargs != 0)
3983 fatal_at (token, "using an operator with operands as predicate");
3984 /* Parse the zero-operand operator "predicates" as
3985 expression. */
3986 op = new expr (opr, token->src_loc);
3988 else if (user_id *code = dyn_cast <user_id *> (opr))
3990 if (code->nargs != 0)
3991 fatal_at (token, "using an operator with operands as predicate");
3992 /* Parse the zero-operand operator "predicates" as
3993 expression. */
3994 op = new expr (opr, token->src_loc);
3996 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
3997 op = new predicate (p, token->src_loc);
3998 else
3999 fatal_at (token, "using an unsupported operator as predicate");
4000 if (!parsing_match_operand)
4001 fatal_at (token, "predicates are only allowed in match expression");
4002 token = peek ();
4003 if (token->flags & PREV_WHITE)
4004 return op;
4006 else if (token->type != CPP_COLON
4007 && token->type != CPP_ATSIGN)
4008 fatal_at (token, "expected expression or predicate");
4009 /* optionally followed by a capture and a predicate. */
4010 if (token->type == CPP_COLON)
4011 fatal_at (token, "not implemented: predicate on leaf operand");
4012 if (token->type == CPP_ATSIGN)
4013 op = parse_capture (op, !parsing_match_operand);
4016 return op;
4019 /* Create a new simplify from the current parsing state and MATCH,
4020 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4022 void
4023 parser::push_simplify (simplify::simplify_kind kind,
4024 vec<simplify *>& simplifiers,
4025 operand *match, operand *result)
4027 /* Build and push a temporary for operator list uses in expressions. */
4028 if (!oper_lists.is_empty ())
4029 active_fors.safe_push (oper_lists);
4031 simplifiers.safe_push
4032 (new simplify (kind, match, result,
4033 active_fors.copy (), capture_ids));
4035 if (!oper_lists.is_empty ())
4036 active_fors.pop ();
4039 /* Parse
4040 <result-op> = <op> | <if> | <with>
4041 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4042 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4043 and return it. */
4045 operand *
4046 parser::parse_result (operand *result, predicate_id *matcher)
4048 const cpp_token *token = peek ();
4049 if (token->type != CPP_OPEN_PAREN)
4050 return parse_op ();
4052 eat_token (CPP_OPEN_PAREN);
4053 if (peek_ident ("if"))
4055 eat_ident ("if");
4056 if_expr *ife = new if_expr (token->src_loc);
4057 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4058 if (peek ()->type == CPP_OPEN_PAREN)
4060 ife->trueexpr = parse_result (result, matcher);
4061 if (peek ()->type == CPP_OPEN_PAREN)
4062 ife->falseexpr = parse_result (result, matcher);
4063 else if (peek ()->type != CPP_CLOSE_PAREN)
4064 ife->falseexpr = parse_op ();
4066 else if (peek ()->type != CPP_CLOSE_PAREN)
4068 ife->trueexpr = parse_op ();
4069 if (peek ()->type == CPP_OPEN_PAREN)
4070 ife->falseexpr = parse_result (result, matcher);
4071 else if (peek ()->type != CPP_CLOSE_PAREN)
4072 ife->falseexpr = parse_op ();
4074 /* If this if is immediately closed then it contains a
4075 manual matcher or is part of a predicate definition. */
4076 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4078 if (!matcher)
4079 fatal_at (peek (), "manual transform not implemented");
4080 ife->trueexpr = result;
4082 eat_token (CPP_CLOSE_PAREN);
4083 return ife;
4085 else if (peek_ident ("with"))
4087 eat_ident ("with");
4088 with_expr *withe = new with_expr (token->src_loc);
4089 /* Parse (with c-expr expr) as (if-with (true) expr). */
4090 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4091 withe->with->nr_stmts = 0;
4092 withe->subexpr = parse_result (result, matcher);
4093 eat_token (CPP_CLOSE_PAREN);
4094 return withe;
4096 else if (peek_ident ("switch"))
4098 token = eat_ident ("switch");
4099 source_location ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4100 eat_ident ("if");
4101 if_expr *ife = new if_expr (ifloc);
4102 operand *res = ife;
4103 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4104 if (peek ()->type == CPP_OPEN_PAREN)
4105 ife->trueexpr = parse_result (result, matcher);
4106 else
4107 ife->trueexpr = parse_op ();
4108 eat_token (CPP_CLOSE_PAREN);
4109 if (peek ()->type != CPP_OPEN_PAREN
4110 || !peek_ident ("if", 2))
4111 fatal_at (token, "switch can be implemented with a single if");
4112 while (peek ()->type != CPP_CLOSE_PAREN)
4114 if (peek ()->type == CPP_OPEN_PAREN)
4116 if (peek_ident ("if", 2))
4118 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4119 eat_ident ("if");
4120 ife->falseexpr = new if_expr (ifloc);
4121 ife = as_a <if_expr *> (ife->falseexpr);
4122 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4123 if (peek ()->type == CPP_OPEN_PAREN)
4124 ife->trueexpr = parse_result (result, matcher);
4125 else
4126 ife->trueexpr = parse_op ();
4127 eat_token (CPP_CLOSE_PAREN);
4129 else
4131 /* switch default clause */
4132 ife->falseexpr = parse_result (result, matcher);
4133 eat_token (CPP_CLOSE_PAREN);
4134 return res;
4137 else
4139 /* switch default clause */
4140 ife->falseexpr = parse_op ();
4141 eat_token (CPP_CLOSE_PAREN);
4142 return res;
4145 eat_token (CPP_CLOSE_PAREN);
4146 return res;
4148 else
4150 operand *op = result;
4151 if (!matcher)
4152 op = parse_expr ();
4153 eat_token (CPP_CLOSE_PAREN);
4154 return op;
4158 /* Parse
4159 simplify = 'simplify' <expr> <result-op>
4161 match = 'match' <ident> <expr> [<result-op>]
4162 and fill SIMPLIFIERS with the results. */
4164 void
4165 parser::parse_simplify (simplify::simplify_kind kind,
4166 vec<simplify *>& simplifiers, predicate_id *matcher,
4167 operand *result)
4169 /* Reset the capture map. */
4170 if (!capture_ids)
4171 capture_ids = new cid_map_t;
4172 /* Reset oper_lists and set. */
4173 hash_set <user_id *> olist;
4174 oper_lists_set = &olist;
4175 oper_lists = vNULL;
4177 const cpp_token *loc = peek ();
4178 parsing_match_operand = true;
4179 struct operand *match = parse_op ();
4180 parsing_match_operand = false;
4181 if (match->type == operand::OP_CAPTURE && !matcher)
4182 fatal_at (loc, "outermost expression cannot be captured");
4183 if (match->type == operand::OP_EXPR
4184 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4185 fatal_at (loc, "outermost expression cannot be a predicate");
4187 /* Splice active_ifs onto result and continue parsing the
4188 "then" expr. */
4189 if_expr *active_if = NULL;
4190 for (int i = active_ifs.length (); i > 0; --i)
4192 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4193 ifc->cond = active_ifs[i-1];
4194 ifc->trueexpr = active_if;
4195 active_if = ifc;
4197 if_expr *outermost_if = active_if;
4198 while (active_if && active_if->trueexpr)
4199 active_if = as_a <if_expr *> (active_if->trueexpr);
4201 const cpp_token *token = peek ();
4203 /* If this if is immediately closed then it is part of a predicate
4204 definition. Push it. */
4205 if (token->type == CPP_CLOSE_PAREN)
4207 if (!matcher)
4208 fatal_at (token, "expected transform expression");
4209 if (active_if)
4211 active_if->trueexpr = result;
4212 result = outermost_if;
4214 push_simplify (kind, simplifiers, match, result);
4215 return;
4218 operand *tem = parse_result (result, matcher);
4219 if (active_if)
4221 active_if->trueexpr = tem;
4222 result = outermost_if;
4224 else
4225 result = tem;
4227 push_simplify (kind, simplifiers, match, result);
4230 /* Parsing of the outer control structures. */
4232 /* Parse a for expression
4233 for = '(' 'for' <subst>... <pattern> ')'
4234 subst = <ident> '(' <ident>... ')' */
4236 void
4237 parser::parse_for (source_location)
4239 auto_vec<const cpp_token *> user_id_tokens;
4240 vec<user_id *> user_ids = vNULL;
4241 const cpp_token *token;
4242 unsigned min_n_opers = 0, max_n_opers = 0;
4244 while (1)
4246 token = peek ();
4247 if (token->type != CPP_NAME)
4248 break;
4250 /* Insert the user defined operators into the operator hash. */
4251 const char *id = get_ident ();
4252 if (get_operator (id) != NULL)
4253 fatal_at (token, "operator already defined");
4254 user_id *op = new user_id (id);
4255 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4256 *slot = op;
4257 user_ids.safe_push (op);
4258 user_id_tokens.safe_push (token);
4260 eat_token (CPP_OPEN_PAREN);
4262 int arity = -1;
4263 while ((token = peek_ident ()) != 0)
4265 const char *oper = get_ident ();
4266 id_base *idb = get_operator (oper);
4267 if (idb == NULL)
4268 fatal_at (token, "no such operator '%s'", oper);
4269 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
4270 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
4271 || *idb == VIEW_CONVERT2)
4272 fatal_at (token, "conditional operators cannot be used inside for");
4274 if (arity == -1)
4275 arity = idb->nargs;
4276 else if (idb->nargs == -1)
4278 else if (idb->nargs != arity)
4279 fatal_at (token, "operator '%s' with arity %d does not match "
4280 "others with arity %d", oper, idb->nargs, arity);
4282 user_id *p = dyn_cast<user_id *> (idb);
4283 if (p)
4285 if (p->is_oper_list)
4286 op->substitutes.safe_splice (p->substitutes);
4287 else
4288 fatal_at (token, "iterator cannot be used as operator-list");
4290 else
4291 op->substitutes.safe_push (idb);
4293 op->nargs = arity;
4294 token = expect (CPP_CLOSE_PAREN);
4296 unsigned nsubstitutes = op->substitutes.length ();
4297 if (nsubstitutes == 0)
4298 fatal_at (token, "A user-defined operator must have at least "
4299 "one substitution");
4300 if (max_n_opers == 0)
4302 min_n_opers = nsubstitutes;
4303 max_n_opers = nsubstitutes;
4305 else
4307 if (nsubstitutes % min_n_opers != 0
4308 && min_n_opers % nsubstitutes != 0)
4309 fatal_at (token, "All user-defined identifiers must have a "
4310 "multiple number of operator substitutions of the "
4311 "smallest number of substitutions");
4312 if (nsubstitutes < min_n_opers)
4313 min_n_opers = nsubstitutes;
4314 else if (nsubstitutes > max_n_opers)
4315 max_n_opers = nsubstitutes;
4319 unsigned n_ids = user_ids.length ();
4320 if (n_ids == 0)
4321 fatal_at (token, "for requires at least one user-defined identifier");
4323 token = peek ();
4324 if (token->type == CPP_CLOSE_PAREN)
4325 fatal_at (token, "no pattern defined in for");
4327 active_fors.safe_push (user_ids);
4328 while (1)
4330 token = peek ();
4331 if (token->type == CPP_CLOSE_PAREN)
4332 break;
4333 parse_pattern ();
4335 active_fors.pop ();
4337 /* Remove user-defined operators from the hash again. */
4338 for (unsigned i = 0; i < user_ids.length (); ++i)
4340 if (!user_ids[i]->used)
4341 warning_at (user_id_tokens[i],
4342 "operator %s defined but not used", user_ids[i]->id);
4343 operators->remove_elt (user_ids[i]);
4347 /* Parse an identifier associated with a list of operators.
4348 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
4350 void
4351 parser::parse_operator_list (source_location)
4353 const cpp_token *token = peek ();
4354 const char *id = get_ident ();
4356 if (get_operator (id) != 0)
4357 fatal_at (token, "operator %s already defined", id);
4359 user_id *op = new user_id (id, true);
4360 int arity = -1;
4362 while ((token = peek_ident ()) != 0)
4364 token = peek ();
4365 const char *oper = get_ident ();
4366 id_base *idb = get_operator (oper);
4368 if (idb == 0)
4369 fatal_at (token, "no such operator '%s'", oper);
4371 if (arity == -1)
4372 arity = idb->nargs;
4373 else if (idb->nargs == -1)
4375 else if (arity != idb->nargs)
4376 fatal_at (token, "operator '%s' with arity %d does not match "
4377 "others with arity %d", oper, idb->nargs, arity);
4379 /* We allow composition of multiple operator lists. */
4380 if (user_id *p = dyn_cast<user_id *> (idb))
4381 op->substitutes.safe_splice (p->substitutes);
4382 else
4383 op->substitutes.safe_push (idb);
4386 // Check that there is no junk after id-list
4387 token = peek();
4388 if (token->type != CPP_CLOSE_PAREN)
4389 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
4391 if (op->substitutes.length () == 0)
4392 fatal_at (token, "operator-list cannot be empty");
4394 op->nargs = arity;
4395 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4396 *slot = op;
4399 /* Parse an outer if expression.
4400 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
4402 void
4403 parser::parse_if (source_location)
4405 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4407 const cpp_token *token = peek ();
4408 if (token->type == CPP_CLOSE_PAREN)
4409 fatal_at (token, "no pattern defined in if");
4411 active_ifs.safe_push (ifexpr);
4412 while (1)
4414 const cpp_token *token = peek ();
4415 if (token->type == CPP_CLOSE_PAREN)
4416 break;
4418 parse_pattern ();
4420 active_ifs.pop ();
4423 /* Parse a list of predefined predicate identifiers.
4424 preds = '(' 'define_predicates' <ident>... ')' */
4426 void
4427 parser::parse_predicates (source_location)
4431 const cpp_token *token = peek ();
4432 if (token->type != CPP_NAME)
4433 break;
4435 add_predicate (get_ident ());
4437 while (1);
4440 /* Parse outer control structures.
4441 pattern = <preds>|<for>|<if>|<simplify>|<match> */
4443 void
4444 parser::parse_pattern ()
4446 /* All clauses start with '('. */
4447 eat_token (CPP_OPEN_PAREN);
4448 const cpp_token *token = peek ();
4449 const char *id = get_ident ();
4450 if (strcmp (id, "simplify") == 0)
4452 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4453 capture_ids = NULL;
4455 else if (strcmp (id, "match") == 0)
4457 bool with_args = false;
4458 source_location e_loc = peek ()->src_loc;
4459 if (peek ()->type == CPP_OPEN_PAREN)
4461 eat_token (CPP_OPEN_PAREN);
4462 with_args = true;
4464 const char *name = get_ident ();
4465 id_base *id = get_operator (name);
4466 predicate_id *p;
4467 if (!id)
4469 p = add_predicate (name);
4470 user_predicates.safe_push (p);
4472 else if ((p = dyn_cast <predicate_id *> (id)))
4474 else
4475 fatal_at (token, "cannot add a match to a non-predicate ID");
4476 /* Parse (match <id> <arg>... (match-expr)) here. */
4477 expr *e = NULL;
4478 if (with_args)
4480 capture_ids = new cid_map_t;
4481 e = new expr (p, e_loc);
4482 while (peek ()->type == CPP_ATSIGN)
4483 e->append_op (parse_capture (NULL, false));
4484 eat_token (CPP_CLOSE_PAREN);
4486 if (p->nargs != -1
4487 && ((e && e->ops.length () != (unsigned)p->nargs)
4488 || (!e && p->nargs != 0)))
4489 fatal_at (token, "non-matching number of match operands");
4490 p->nargs = e ? e->ops.length () : 0;
4491 parse_simplify (simplify::MATCH, p->matchers, p, e);
4492 capture_ids = NULL;
4494 else if (strcmp (id, "for") == 0)
4495 parse_for (token->src_loc);
4496 else if (strcmp (id, "if") == 0)
4497 parse_if (token->src_loc);
4498 else if (strcmp (id, "define_predicates") == 0)
4500 if (active_ifs.length () > 0
4501 || active_fors.length () > 0)
4502 fatal_at (token, "define_predicates inside if or for is not supported");
4503 parse_predicates (token->src_loc);
4505 else if (strcmp (id, "define_operator_list") == 0)
4507 if (active_ifs.length () > 0
4508 || active_fors.length () > 0)
4509 fatal_at (token, "operator-list inside if or for is not supported");
4510 parse_operator_list (token->src_loc);
4512 else
4513 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4514 active_ifs.length () == 0 && active_fors.length () == 0
4515 ? "'define_predicates', " : "");
4517 eat_token (CPP_CLOSE_PAREN);
4520 /* Main entry of the parser. Repeatedly parse outer control structures. */
4522 parser::parser (cpp_reader *r_)
4524 r = r_;
4525 active_ifs = vNULL;
4526 active_fors = vNULL;
4527 simplifiers = vNULL;
4528 oper_lists_set = NULL;
4529 oper_lists = vNULL;
4530 capture_ids = NULL;
4531 user_predicates = vNULL;
4532 parsing_match_operand = false;
4534 const cpp_token *token = next ();
4535 while (token->type != CPP_EOF)
4537 _cpp_backup_tokens (r, 1);
4538 parse_pattern ();
4539 token = next ();
4544 /* Helper for the linemap code. */
4546 static size_t
4547 round_alloc_size (size_t s)
4549 return s;
4553 /* The genmatch generator progam. It reads from a pattern description
4554 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
4557 main (int argc, char **argv)
4559 cpp_reader *r;
4561 progname = "genmatch";
4563 if (argc < 2)
4564 return 1;
4566 bool gimple = true;
4567 char *input = argv[argc-1];
4568 for (int i = 1; i < argc - 1; ++i)
4570 if (strcmp (argv[i], "--gimple") == 0)
4571 gimple = true;
4572 else if (strcmp (argv[i], "--generic") == 0)
4573 gimple = false;
4574 else if (strcmp (argv[i], "-v") == 0)
4575 verbose = 1;
4576 else if (strcmp (argv[i], "-vv") == 0)
4577 verbose = 2;
4578 else
4580 fprintf (stderr, "Usage: genmatch "
4581 "[--gimple] [--generic] [-v[v]] input\n");
4582 return 1;
4586 line_table = XCNEW (struct line_maps);
4587 linemap_init (line_table, 0);
4588 line_table->reallocator = xrealloc;
4589 line_table->round_alloc_size = round_alloc_size;
4591 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4592 cpp_callbacks *cb = cpp_get_callbacks (r);
4593 cb->error = error_cb;
4595 if (!cpp_read_main_file (r, input))
4596 return 1;
4597 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4598 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4600 /* Pre-seed operators. */
4601 operators = new hash_table<id_base> (1024);
4602 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4603 add_operator (SYM, # SYM, # TYPE, NARGS);
4604 #define END_OF_BASE_TREE_CODES
4605 #include "tree.def"
4606 add_operator (CONVERT0, "CONVERT0", "tcc_unary", 1);
4607 add_operator (CONVERT1, "CONVERT1", "tcc_unary", 1);
4608 add_operator (CONVERT2, "CONVERT2", "tcc_unary", 1);
4609 add_operator (VIEW_CONVERT0, "VIEW_CONVERT0", "tcc_unary", 1);
4610 add_operator (VIEW_CONVERT1, "VIEW_CONVERT1", "tcc_unary", 1);
4611 add_operator (VIEW_CONVERT2, "VIEW_CONVERT2", "tcc_unary", 1);
4612 #undef END_OF_BASE_TREE_CODES
4613 #undef DEFTREECODE
4615 /* Pre-seed builtin functions.
4616 ??? Cannot use N (name) as that is targetm.emultls.get_address
4617 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4618 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4619 add_builtin (ENUM, # ENUM);
4620 #include "builtins.def"
4622 /* Parse ahead! */
4623 parser p (r);
4625 if (gimple)
4626 write_header (stdout, "gimple-match-head.c");
4627 else
4628 write_header (stdout, "generic-match-head.c");
4630 /* Go over all predicates defined with patterns and perform
4631 lowering and code generation. */
4632 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
4634 predicate_id *pred = p.user_predicates[i];
4635 lower (pred->matchers, gimple);
4637 if (verbose == 2)
4638 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4639 print_matches (pred->matchers[i]);
4641 decision_tree dt;
4642 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4643 dt.insert (pred->matchers[i], i);
4645 if (verbose == 2)
4646 dt.print (stderr);
4648 write_predicate (stdout, pred, dt, gimple);
4651 /* Lower the main simplifiers and generate code for them. */
4652 lower (p.simplifiers, gimple);
4654 if (verbose == 2)
4655 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4656 print_matches (p.simplifiers[i]);
4658 decision_tree dt;
4659 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4660 dt.insert (p.simplifiers[i], i);
4662 if (verbose == 2)
4663 dt.print (stderr);
4665 dt.gen (stdout, gimple);
4667 /* Finalize. */
4668 cpp_finish (r, NULL);
4669 cpp_destroy (r);
4671 delete operators;
4673 return 0;