Clean up some minor white space issues in trans-decl.c and trans-expr.c
[official-gcc.git] / gcc / genmatch.c
blob19218fdaf2ecd7f4654bee65a7e33d94711735f8
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2016 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 (line_table, 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 (line_table, 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 (line_table, 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 (line_table, 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 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
234 enum internal_fn {
235 #include "internal-fn.def"
236 IFN_LAST
239 /* Return true if CODE represents a commutative tree code. Otherwise
240 return false. */
241 bool
242 commutative_tree_code (enum tree_code code)
244 switch (code)
246 case PLUS_EXPR:
247 case MULT_EXPR:
248 case MULT_HIGHPART_EXPR:
249 case MIN_EXPR:
250 case MAX_EXPR:
251 case BIT_IOR_EXPR:
252 case BIT_XOR_EXPR:
253 case BIT_AND_EXPR:
254 case NE_EXPR:
255 case EQ_EXPR:
256 case UNORDERED_EXPR:
257 case ORDERED_EXPR:
258 case UNEQ_EXPR:
259 case LTGT_EXPR:
260 case TRUTH_AND_EXPR:
261 case TRUTH_XOR_EXPR:
262 case TRUTH_OR_EXPR:
263 case WIDEN_MULT_EXPR:
264 case VEC_WIDEN_MULT_HI_EXPR:
265 case VEC_WIDEN_MULT_LO_EXPR:
266 case VEC_WIDEN_MULT_EVEN_EXPR:
267 case VEC_WIDEN_MULT_ODD_EXPR:
268 return true;
270 default:
271 break;
273 return false;
276 /* Return true if CODE represents a ternary tree code for which the
277 first two operands are commutative. Otherwise return false. */
278 bool
279 commutative_ternary_tree_code (enum tree_code code)
281 switch (code)
283 case WIDEN_MULT_PLUS_EXPR:
284 case WIDEN_MULT_MINUS_EXPR:
285 case DOT_PROD_EXPR:
286 case FMA_EXPR:
287 return true;
289 default:
290 break;
292 return false;
296 /* Base class for all identifiers the parser knows. */
298 struct id_base : nofree_ptr_hash<id_base>
300 enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
302 id_base (id_kind, const char *, int = -1);
304 hashval_t hashval;
305 int nargs;
306 const char *id;
308 /* hash_table support. */
309 static inline hashval_t hash (const id_base *);
310 static inline int equal (const id_base *, const id_base *);
313 inline hashval_t
314 id_base::hash (const id_base *op)
316 return op->hashval;
319 inline int
320 id_base::equal (const id_base *op1,
321 const id_base *op2)
323 return (op1->hashval == op2->hashval
324 && strcmp (op1->id, op2->id) == 0);
327 /* The special id "null", which matches nothing. */
328 static id_base *null_id;
330 /* Hashtable of known pattern operators. This is pre-seeded from
331 all known tree codes and all known builtin function ids. */
332 static hash_table<id_base> *operators;
334 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
336 kind = kind_;
337 id = id_;
338 nargs = nargs_;
339 hashval = htab_hash_string (id);
342 /* Identifier that maps to a tree code. */
344 struct operator_id : public id_base
346 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
347 const char *tcc_)
348 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
349 enum tree_code code;
350 const char *tcc;
353 /* Identifier that maps to a builtin or internal function code. */
355 struct fn_id : public id_base
357 fn_id (enum built_in_function fn_, const char *id_)
358 : id_base (id_base::FN, id_), fn (fn_) {}
359 fn_id (enum internal_fn fn_, const char *id_)
360 : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
361 unsigned int fn;
364 struct simplify;
366 /* Identifier that maps to a user-defined predicate. */
368 struct predicate_id : public id_base
370 predicate_id (const char *id_)
371 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
372 vec<simplify *> matchers;
375 /* Identifier that maps to a operator defined by a 'for' directive. */
377 struct user_id : public id_base
379 user_id (const char *id_, bool is_oper_list_ = false)
380 : id_base (id_base::USER, id_), substitutes (vNULL),
381 used (false), is_oper_list (is_oper_list_) {}
382 vec<id_base *> substitutes;
383 bool used;
384 bool is_oper_list;
387 template<>
388 template<>
389 inline bool
390 is_a_helper <fn_id *>::test (id_base *id)
392 return id->kind == id_base::FN;
395 template<>
396 template<>
397 inline bool
398 is_a_helper <operator_id *>::test (id_base *id)
400 return id->kind == id_base::CODE;
403 template<>
404 template<>
405 inline bool
406 is_a_helper <predicate_id *>::test (id_base *id)
408 return id->kind == id_base::PREDICATE;
411 template<>
412 template<>
413 inline bool
414 is_a_helper <user_id *>::test (id_base *id)
416 return id->kind == id_base::USER;
419 /* Add a predicate identifier to the hash. */
421 static predicate_id *
422 add_predicate (const char *id)
424 predicate_id *p = new predicate_id (id);
425 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
426 if (*slot)
427 fatal ("duplicate id definition");
428 *slot = p;
429 return p;
432 /* Add a tree code identifier to the hash. */
434 static void
435 add_operator (enum tree_code code, const char *id,
436 const char *tcc, unsigned nargs)
438 if (strcmp (tcc, "tcc_unary") != 0
439 && strcmp (tcc, "tcc_binary") != 0
440 && strcmp (tcc, "tcc_comparison") != 0
441 && strcmp (tcc, "tcc_expression") != 0
442 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
443 && strcmp (tcc, "tcc_reference") != 0
444 /* To have INTEGER_CST and friends as "predicate operators". */
445 && strcmp (tcc, "tcc_constant") != 0
446 /* And allow CONSTRUCTOR for vector initializers. */
447 && !(code == CONSTRUCTOR)
448 /* Allow SSA_NAME as predicate operator. */
449 && !(code == SSA_NAME))
450 return;
451 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
452 if (code == ADDR_EXPR)
453 nargs = 0;
454 operator_id *op = new operator_id (code, id, nargs, tcc);
455 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
456 if (*slot)
457 fatal ("duplicate id definition");
458 *slot = op;
461 /* Add a built-in or internal function identifier to the hash. ID is
462 the name of its CFN_* enumeration value. */
464 template <typename T>
465 static void
466 add_function (T code, const char *id)
468 fn_id *fn = new fn_id (code, id);
469 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
470 if (*slot)
471 fatal ("duplicate id definition");
472 *slot = fn;
475 /* Helper for easy comparing ID with tree code CODE. */
477 static bool
478 operator==(id_base &id, enum tree_code code)
480 if (operator_id *oid = dyn_cast <operator_id *> (&id))
481 return oid->code == code;
482 return false;
485 /* Lookup the identifier ID. Allow "null" if ALLOW_NULL. */
487 id_base *
488 get_operator (const char *id, bool allow_null = false)
490 if (allow_null && strcmp (id, "null") == 0)
491 return null_id;
493 id_base tem (id_base::CODE, id);
495 id_base *op = operators->find_with_hash (&tem, tem.hashval);
496 if (op)
498 /* If this is a user-defined identifier track whether it was used. */
499 if (user_id *uid = dyn_cast<user_id *> (op))
500 uid->used = true;
501 return op;
504 char *id2;
505 bool all_upper = true;
506 bool all_lower = true;
507 for (unsigned int i = 0; id[i]; ++i)
508 if (ISUPPER (id[i]))
509 all_lower = false;
510 else if (ISLOWER (id[i]))
511 all_upper = false;
512 if (all_lower)
514 /* Try in caps with _EXPR appended. */
515 id2 = ACONCAT ((id, "_EXPR", NULL));
516 for (unsigned int i = 0; id2[i]; ++i)
517 id2[i] = TOUPPER (id2[i]);
519 else if (all_upper && strncmp (id, "IFN_", 4) == 0)
520 /* Try CFN_ instead of IFN_. */
521 id2 = ACONCAT (("CFN_", id + 4, NULL));
522 else if (all_upper && strncmp (id, "BUILT_IN_", 9) == 0)
523 /* Try prepending CFN_. */
524 id2 = ACONCAT (("CFN_", id, NULL));
525 else
526 return NULL;
528 new (&tem) id_base (id_base::CODE, id2);
529 return operators->find_with_hash (&tem, tem.hashval);
532 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
535 /* The AST produced by parsing of the pattern definitions. */
537 struct dt_operand;
538 struct capture_info;
540 /* The base class for operands. */
542 struct operand {
543 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
544 operand (enum op_type type_, source_location loc_)
545 : type (type_), location (loc_) {}
546 enum op_type type;
547 source_location location;
548 virtual void gen_transform (FILE *, int, const char *, bool, int,
549 const char *, capture_info *,
550 dt_operand ** = 0,
551 bool = true)
552 { gcc_unreachable (); }
555 /* A predicate operand. Predicates are leafs in the AST. */
557 struct predicate : public operand
559 predicate (predicate_id *p_, source_location loc)
560 : operand (OP_PREDICATE, loc), p (p_) {}
561 predicate_id *p;
564 /* An operand that constitutes an expression. Expressions include
565 function calls and user-defined predicate invocations. */
567 struct expr : public operand
569 expr (id_base *operation_, source_location loc, bool is_commutative_ = false)
570 : operand (OP_EXPR, loc), operation (operation_),
571 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
572 is_generic (false), force_single_use (false) {}
573 expr (expr *e)
574 : operand (OP_EXPR, e->location), operation (e->operation),
575 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
576 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
577 void append_op (operand *op) { ops.safe_push (op); }
578 /* The operator and its operands. */
579 id_base *operation;
580 vec<operand *> ops;
581 /* An explicitely specified type - used exclusively for conversions. */
582 const char *expr_type;
583 /* Whether the operation is to be applied commutatively. This is
584 later lowered to two separate patterns. */
585 bool is_commutative;
586 /* Whether the expression is expected to be in GENERIC form. */
587 bool is_generic;
588 /* Whether pushing any stmt to the sequence should be conditional
589 on this expression having a single-use. */
590 bool force_single_use;
591 virtual void gen_transform (FILE *f, int, const char *, bool, int,
592 const char *, capture_info *,
593 dt_operand ** = 0, bool = true);
596 /* An operator that is represented by native C code. This is always
597 a leaf operand in the AST. This class is also used to represent
598 the code to be generated for 'if' and 'with' expressions. */
600 struct c_expr : public operand
602 /* A mapping of an identifier and its replacement. Used to apply
603 'for' lowering. */
604 struct id_tab {
605 const char *id;
606 const char *oper;
607 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
610 c_expr (cpp_reader *r_, source_location loc,
611 vec<cpp_token> code_, unsigned nr_stmts_,
612 vec<id_tab> ids_, cid_map_t *capture_ids_)
613 : operand (OP_C_EXPR, loc), r (r_), code (code_),
614 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
615 /* cpplib tokens and state to transform this back to source. */
616 cpp_reader *r;
617 vec<cpp_token> code;
618 cid_map_t *capture_ids;
619 /* The number of statements parsed (well, the number of ';'s). */
620 unsigned nr_stmts;
621 /* The identifier replacement vector. */
622 vec<id_tab> ids;
623 virtual void gen_transform (FILE *f, int, const char *, bool, int,
624 const char *, capture_info *,
625 dt_operand ** = 0, bool = true);
628 /* A wrapper around another operand that captures its value. */
630 struct capture : public operand
632 capture (source_location loc, unsigned where_, operand *what_)
633 : operand (OP_CAPTURE, loc), where (where_), what (what_) {}
634 /* Identifier index for the value. */
635 unsigned where;
636 /* The captured value. */
637 operand *what;
638 virtual void gen_transform (FILE *f, int, const char *, bool, int,
639 const char *, capture_info *,
640 dt_operand ** = 0, bool = true);
643 /* if expression. */
645 struct if_expr : public operand
647 if_expr (source_location loc)
648 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
649 c_expr *cond;
650 operand *trueexpr;
651 operand *falseexpr;
654 /* with expression. */
656 struct with_expr : public operand
658 with_expr (source_location loc)
659 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
660 c_expr *with;
661 operand *subexpr;
664 template<>
665 template<>
666 inline bool
667 is_a_helper <capture *>::test (operand *op)
669 return op->type == operand::OP_CAPTURE;
672 template<>
673 template<>
674 inline bool
675 is_a_helper <predicate *>::test (operand *op)
677 return op->type == operand::OP_PREDICATE;
680 template<>
681 template<>
682 inline bool
683 is_a_helper <c_expr *>::test (operand *op)
685 return op->type == operand::OP_C_EXPR;
688 template<>
689 template<>
690 inline bool
691 is_a_helper <expr *>::test (operand *op)
693 return op->type == operand::OP_EXPR;
696 template<>
697 template<>
698 inline bool
699 is_a_helper <if_expr *>::test (operand *op)
701 return op->type == operand::OP_IF;
704 template<>
705 template<>
706 inline bool
707 is_a_helper <with_expr *>::test (operand *op)
709 return op->type == operand::OP_WITH;
712 /* The main class of a pattern and its transform. This is used to
713 represent both (simplify ...) and (match ...) kinds. The AST
714 duplicates all outer 'if' and 'for' expressions here so each
715 simplify can exist in isolation. */
717 struct simplify
719 enum simplify_kind { SIMPLIFY, MATCH };
721 simplify (simplify_kind kind_, operand *match_, operand *result_,
722 vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
723 : kind (kind_), match (match_), result (result_),
724 for_vec (for_vec_), for_subst_vec (vNULL),
725 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
727 simplify_kind kind;
728 /* The expression that is matched against the GENERIC or GIMPLE IL. */
729 operand *match;
730 /* For a (simplify ...) an expression with ifs and withs with the expression
731 produced when the pattern applies in the leafs.
732 For a (match ...) the leafs are either empty if it is a simple predicate
733 or the single expression specifying the matched operands. */
734 struct operand *result;
735 /* Collected 'for' expression operators that have to be replaced
736 in the lowering phase. */
737 vec<vec<user_id *> > for_vec;
738 vec<std::pair<user_id *, id_base *> > for_subst_vec;
739 /* A map of capture identifiers to indexes. */
740 cid_map_t *capture_ids;
741 int capture_max;
744 /* Debugging routines for dumping the AST. */
746 DEBUG_FUNCTION void
747 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
749 if (capture *c = dyn_cast<capture *> (o))
751 if (c->what && flattened == false)
752 print_operand (c->what, f, flattened);
753 fprintf (f, "@%u", c->where);
756 else if (predicate *p = dyn_cast<predicate *> (o))
757 fprintf (f, "%s", p->p->id);
759 else if (is_a<c_expr *> (o))
760 fprintf (f, "c_expr");
762 else if (expr *e = dyn_cast<expr *> (o))
764 if (e->ops.length () == 0)
765 fprintf (f, "%s", e->operation->id);
766 else
768 fprintf (f, "(%s", e->operation->id);
770 if (flattened == false)
772 for (unsigned i = 0; i < e->ops.length (); ++i)
774 putc (' ', f);
775 print_operand (e->ops[i], f, flattened);
778 putc (')', f);
782 else
783 gcc_unreachable ();
786 DEBUG_FUNCTION void
787 print_matches (struct simplify *s, FILE *f = stderr)
789 fprintf (f, "for expression: ");
790 print_operand (s->match, f);
791 putc ('\n', f);
795 /* AST lowering. */
797 /* Lowering of commutative operators. */
799 static void
800 cartesian_product (const vec< vec<operand *> >& ops_vector,
801 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
803 if (n == ops_vector.length ())
805 vec<operand *> xv = v.copy ();
806 result.safe_push (xv);
807 return;
810 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
812 v[n] = ops_vector[n][i];
813 cartesian_product (ops_vector, result, v, n + 1);
817 /* Lower OP to two operands in case it is marked as commutative. */
819 static vec<operand *>
820 commutate (operand *op)
822 vec<operand *> ret = vNULL;
824 if (capture *c = dyn_cast <capture *> (op))
826 if (!c->what)
828 ret.safe_push (op);
829 return ret;
831 vec<operand *> v = commutate (c->what);
832 for (unsigned i = 0; i < v.length (); ++i)
834 capture *nc = new capture (c->location, c->where, v[i]);
835 ret.safe_push (nc);
837 return ret;
840 expr *e = dyn_cast <expr *> (op);
841 if (!e || e->ops.length () == 0)
843 ret.safe_push (op);
844 return ret;
847 vec< vec<operand *> > ops_vector = vNULL;
848 for (unsigned i = 0; i < e->ops.length (); ++i)
849 ops_vector.safe_push (commutate (e->ops[i]));
851 auto_vec< vec<operand *> > result;
852 auto_vec<operand *> v (e->ops.length ());
853 v.quick_grow_cleared (e->ops.length ());
854 cartesian_product (ops_vector, result, v, 0);
857 for (unsigned i = 0; i < result.length (); ++i)
859 expr *ne = new expr (e);
860 ne->is_commutative = false;
861 for (unsigned j = 0; j < result[i].length (); ++j)
862 ne->append_op (result[i][j]);
863 ret.safe_push (ne);
866 if (!e->is_commutative)
867 return ret;
869 for (unsigned i = 0; i < result.length (); ++i)
871 expr *ne = new expr (e);
872 ne->is_commutative = false;
873 // result[i].length () is 2 since e->operation is binary
874 for (unsigned j = result[i].length (); j; --j)
875 ne->append_op (result[i][j-1]);
876 ret.safe_push (ne);
879 return ret;
882 /* Lower operations marked as commutative in the AST of S and push
883 the resulting patterns to SIMPLIFIERS. */
885 static void
886 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
888 vec<operand *> matchers = commutate (s->match);
889 for (unsigned i = 0; i < matchers.length (); ++i)
891 simplify *ns = new simplify (s->kind, matchers[i], s->result,
892 s->for_vec, s->capture_ids);
893 simplifiers.safe_push (ns);
897 /* Strip conditional conversios using operator OPER from O and its
898 children if STRIP, else replace them with an unconditional convert. */
900 operand *
901 lower_opt_convert (operand *o, enum tree_code oper,
902 enum tree_code to_oper, bool strip)
904 if (capture *c = dyn_cast<capture *> (o))
906 if (c->what)
907 return new capture (c->location, c->where,
908 lower_opt_convert (c->what, oper, to_oper, strip));
909 else
910 return c;
913 expr *e = dyn_cast<expr *> (o);
914 if (!e)
915 return o;
917 if (*e->operation == oper)
919 if (strip)
920 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
922 expr *ne = new expr (e);
923 ne->operation = (to_oper == CONVERT_EXPR
924 ? get_operator ("CONVERT_EXPR")
925 : get_operator ("VIEW_CONVERT_EXPR"));
926 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
927 return ne;
930 expr *ne = new expr (e);
931 for (unsigned i = 0; i < e->ops.length (); ++i)
932 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
934 return ne;
937 /* Determine whether O or its children uses the conditional conversion
938 operator OPER. */
940 static bool
941 has_opt_convert (operand *o, enum tree_code oper)
943 if (capture *c = dyn_cast<capture *> (o))
945 if (c->what)
946 return has_opt_convert (c->what, oper);
947 else
948 return false;
951 expr *e = dyn_cast<expr *> (o);
952 if (!e)
953 return false;
955 if (*e->operation == oper)
956 return true;
958 for (unsigned i = 0; i < e->ops.length (); ++i)
959 if (has_opt_convert (e->ops[i], oper))
960 return true;
962 return false;
965 /* Lower conditional convert operators in O, expanding it to a vector
966 if required. */
968 static vec<operand *>
969 lower_opt_convert (operand *o)
971 vec<operand *> v1 = vNULL, v2;
973 v1.safe_push (o);
975 enum tree_code opers[]
976 = { CONVERT0, CONVERT_EXPR,
977 CONVERT1, CONVERT_EXPR,
978 CONVERT2, CONVERT_EXPR,
979 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
980 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
981 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
983 /* Conditional converts are lowered to a pattern with the
984 conversion and one without. The three different conditional
985 convert codes are lowered separately. */
987 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
989 v2 = vNULL;
990 for (unsigned j = 0; j < v1.length (); ++j)
991 if (has_opt_convert (v1[j], opers[i]))
993 v2.safe_push (lower_opt_convert (v1[j],
994 opers[i], opers[i+1], false));
995 v2.safe_push (lower_opt_convert (v1[j],
996 opers[i], opers[i+1], true));
999 if (v2 != vNULL)
1001 v1 = vNULL;
1002 for (unsigned j = 0; j < v2.length (); ++j)
1003 v1.safe_push (v2[j]);
1007 return v1;
1010 /* Lower conditional convert operators in the AST of S and push
1011 the resulting multiple patterns to SIMPLIFIERS. */
1013 static void
1014 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
1016 vec<operand *> matchers = lower_opt_convert (s->match);
1017 for (unsigned i = 0; i < matchers.length (); ++i)
1019 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1020 s->for_vec, s->capture_ids);
1021 simplifiers.safe_push (ns);
1025 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1026 GENERIC and a GIMPLE variant. */
1028 static vec<operand *>
1029 lower_cond (operand *o)
1031 vec<operand *> ro = vNULL;
1033 if (capture *c = dyn_cast<capture *> (o))
1035 if (c->what)
1037 vec<operand *> lop = vNULL;
1038 lop = lower_cond (c->what);
1040 for (unsigned i = 0; i < lop.length (); ++i)
1041 ro.safe_push (new capture (c->location, c->where, lop[i]));
1042 return ro;
1046 expr *e = dyn_cast<expr *> (o);
1047 if (!e || e->ops.length () == 0)
1049 ro.safe_push (o);
1050 return ro;
1053 vec< vec<operand *> > ops_vector = vNULL;
1054 for (unsigned i = 0; i < e->ops.length (); ++i)
1055 ops_vector.safe_push (lower_cond (e->ops[i]));
1057 auto_vec< vec<operand *> > result;
1058 auto_vec<operand *> v (e->ops.length ());
1059 v.quick_grow_cleared (e->ops.length ());
1060 cartesian_product (ops_vector, result, v, 0);
1062 for (unsigned i = 0; i < result.length (); ++i)
1064 expr *ne = new expr (e);
1065 for (unsigned j = 0; j < result[i].length (); ++j)
1066 ne->append_op (result[i][j]);
1067 ro.safe_push (ne);
1068 /* If this is a COND with a captured expression or an
1069 expression with two operands then also match a GENERIC
1070 form on the compare. */
1071 if ((*e->operation == COND_EXPR
1072 || *e->operation == VEC_COND_EXPR)
1073 && ((is_a <capture *> (e->ops[0])
1074 && as_a <capture *> (e->ops[0])->what
1075 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1076 && as_a <expr *>
1077 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1078 || (is_a <expr *> (e->ops[0])
1079 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1081 expr *ne = new expr (e);
1082 for (unsigned j = 0; j < result[i].length (); ++j)
1083 ne->append_op (result[i][j]);
1084 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1086 expr *ocmp = as_a <expr *> (c->what);
1087 expr *cmp = new expr (ocmp);
1088 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1089 cmp->append_op (ocmp->ops[j]);
1090 cmp->is_generic = true;
1091 ne->ops[0] = new capture (c->location, c->where, cmp);
1093 else
1095 expr *ocmp = as_a <expr *> (ne->ops[0]);
1096 expr *cmp = new expr (ocmp);
1097 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1098 cmp->append_op (ocmp->ops[j]);
1099 cmp->is_generic = true;
1100 ne->ops[0] = cmp;
1102 ro.safe_push (ne);
1106 return ro;
1109 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1110 GENERIC and a GIMPLE variant. */
1112 static void
1113 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1115 vec<operand *> matchers = lower_cond (s->match);
1116 for (unsigned i = 0; i < matchers.length (); ++i)
1118 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1119 s->for_vec, s->capture_ids);
1120 simplifiers.safe_push (ns);
1124 /* Return true if O refers to ID. */
1126 bool
1127 contains_id (operand *o, user_id *id)
1129 if (capture *c = dyn_cast<capture *> (o))
1130 return c->what && contains_id (c->what, id);
1132 if (expr *e = dyn_cast<expr *> (o))
1134 if (e->operation == id)
1135 return true;
1136 for (unsigned i = 0; i < e->ops.length (); ++i)
1137 if (contains_id (e->ops[i], id))
1138 return true;
1139 return false;
1142 if (with_expr *w = dyn_cast <with_expr *> (o))
1143 return (contains_id (w->with, id)
1144 || contains_id (w->subexpr, id));
1146 if (if_expr *ife = dyn_cast <if_expr *> (o))
1147 return (contains_id (ife->cond, id)
1148 || contains_id (ife->trueexpr, id)
1149 || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1151 if (c_expr *ce = dyn_cast<c_expr *> (o))
1152 return ce->capture_ids && ce->capture_ids->get (id->id);
1154 return false;
1158 /* In AST operand O replace operator ID with operator WITH. */
1160 operand *
1161 replace_id (operand *o, user_id *id, id_base *with)
1163 /* Deep-copy captures and expressions, replacing operations as
1164 needed. */
1165 if (capture *c = dyn_cast<capture *> (o))
1167 if (!c->what)
1168 return c;
1169 return new capture (c->location, c->where,
1170 replace_id (c->what, id, with));
1172 else if (expr *e = dyn_cast<expr *> (o))
1174 expr *ne = new expr (e);
1175 if (e->operation == id)
1176 ne->operation = with;
1177 for (unsigned i = 0; i < e->ops.length (); ++i)
1178 ne->append_op (replace_id (e->ops[i], id, with));
1179 return ne;
1181 else if (with_expr *w = dyn_cast <with_expr *> (o))
1183 with_expr *nw = new with_expr (w->location);
1184 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1185 nw->subexpr = replace_id (w->subexpr, id, with);
1186 return nw;
1188 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1190 if_expr *nife = new if_expr (ife->location);
1191 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1192 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1193 if (ife->falseexpr)
1194 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1195 return nife;
1198 /* For c_expr we simply record a string replacement table which is
1199 applied at code-generation time. */
1200 if (c_expr *ce = dyn_cast<c_expr *> (o))
1202 vec<c_expr::id_tab> ids = ce->ids.copy ();
1203 ids.safe_push (c_expr::id_tab (id->id, with->id));
1204 return new c_expr (ce->r, ce->location,
1205 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1208 return o;
1211 /* Return true if the binary operator OP is ok for delayed substitution
1212 during for lowering. */
1214 static bool
1215 binary_ok (operator_id *op)
1217 switch (op->code)
1219 case PLUS_EXPR:
1220 case MINUS_EXPR:
1221 case MULT_EXPR:
1222 case TRUNC_DIV_EXPR:
1223 case CEIL_DIV_EXPR:
1224 case FLOOR_DIV_EXPR:
1225 case ROUND_DIV_EXPR:
1226 case TRUNC_MOD_EXPR:
1227 case CEIL_MOD_EXPR:
1228 case FLOOR_MOD_EXPR:
1229 case ROUND_MOD_EXPR:
1230 case RDIV_EXPR:
1231 case EXACT_DIV_EXPR:
1232 case MIN_EXPR:
1233 case MAX_EXPR:
1234 case BIT_IOR_EXPR:
1235 case BIT_XOR_EXPR:
1236 case BIT_AND_EXPR:
1237 return true;
1238 default:
1239 return false;
1243 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1245 static void
1246 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1248 vec<vec<user_id *> >& for_vec = sin->for_vec;
1249 unsigned worklist_start = 0;
1250 auto_vec<simplify *> worklist;
1251 worklist.safe_push (sin);
1253 /* Lower each recorded for separately, operating on the
1254 set of simplifiers created by the previous one.
1255 Lower inner-to-outer so inner for substitutes can refer
1256 to operators replaced by outer fors. */
1257 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1259 vec<user_id *>& ids = for_vec[fi];
1260 unsigned n_ids = ids.length ();
1261 unsigned max_n_opers = 0;
1262 bool can_delay_subst = (sin->kind == simplify::SIMPLIFY);
1263 for (unsigned i = 0; i < n_ids; ++i)
1265 if (ids[i]->substitutes.length () > max_n_opers)
1266 max_n_opers = ids[i]->substitutes.length ();
1267 /* Require that all substitutes are of the same kind so that
1268 if we delay substitution to the result op code generation
1269 can look at the first substitute for deciding things like
1270 types of operands. */
1271 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1272 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1273 if (ids[i]->substitutes[j]->kind != kind)
1274 can_delay_subst = false;
1275 else if (operator_id *op
1276 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1278 operator_id *op0
1279 = as_a <operator_id *> (ids[i]->substitutes[0]);
1280 if (strcmp (op->tcc, "tcc_comparison") == 0
1281 && strcmp (op0->tcc, "tcc_comparison") == 0)
1283 /* Unfortunately we can't just allow all tcc_binary. */
1284 else if (strcmp (op->tcc, "tcc_binary") == 0
1285 && strcmp (op0->tcc, "tcc_binary") == 0
1286 && binary_ok (op)
1287 && binary_ok (op0))
1289 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1290 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1291 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1292 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1294 else
1295 can_delay_subst = false;
1297 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1299 else
1300 can_delay_subst = false;
1303 unsigned worklist_end = worklist.length ();
1304 for (unsigned si = worklist_start; si < worklist_end; ++si)
1306 simplify *s = worklist[si];
1307 for (unsigned j = 0; j < max_n_opers; ++j)
1309 operand *match_op = s->match;
1310 operand *result_op = s->result;
1311 vec<std::pair<user_id *, id_base *> > subst;
1312 subst.create (n_ids);
1313 bool skip = false;
1314 for (unsigned i = 0; i < n_ids; ++i)
1316 user_id *id = ids[i];
1317 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1318 if (oper == null_id
1319 && (contains_id (match_op, id)
1320 || contains_id (result_op, id)))
1322 skip = true;
1323 break;
1325 subst.quick_push (std::make_pair (id, oper));
1326 match_op = replace_id (match_op, id, oper);
1327 if (result_op
1328 && !can_delay_subst)
1329 result_op = replace_id (result_op, id, oper);
1331 if (skip)
1333 subst.release ();
1334 continue;
1336 simplify *ns = new simplify (s->kind, match_op, result_op,
1337 vNULL, s->capture_ids);
1338 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1339 if (result_op
1340 && can_delay_subst)
1341 ns->for_subst_vec.safe_splice (subst);
1342 else
1343 subst.release ();
1344 worklist.safe_push (ns);
1347 worklist_start = worklist_end;
1350 /* Copy out the result from the last for lowering. */
1351 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1352 simplifiers.safe_push (worklist[i]);
1355 /* Lower the AST for everything in SIMPLIFIERS. */
1357 static void
1358 lower (vec<simplify *>& simplifiers, bool gimple)
1360 auto_vec<simplify *> out_simplifiers;
1361 for (unsigned i = 0; i < simplifiers.length (); ++i)
1362 lower_opt_convert (simplifiers[i], out_simplifiers);
1364 simplifiers.truncate (0);
1365 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1366 lower_commutative (out_simplifiers[i], simplifiers);
1368 out_simplifiers.truncate (0);
1369 if (gimple)
1370 for (unsigned i = 0; i < simplifiers.length (); ++i)
1371 lower_cond (simplifiers[i], out_simplifiers);
1372 else
1373 out_simplifiers.safe_splice (simplifiers);
1376 simplifiers.truncate (0);
1377 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1378 lower_for (out_simplifiers[i], simplifiers);
1384 /* The decision tree built for generating GIMPLE and GENERIC pattern
1385 matching code. It represents the 'match' expression of all
1386 simplifies and has those as its leafs. */
1388 struct dt_simplify;
1390 /* A hash-map collecting semantically equivalent leafs in the decision
1391 tree for splitting out to separate functions. */
1392 struct sinfo
1394 dt_simplify *s;
1396 const char *fname;
1397 unsigned cnt;
1400 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1401 sinfo *>
1403 static inline hashval_t hash (const key_type &);
1404 static inline bool equal_keys (const key_type &, const key_type &);
1405 template <typename T> static inline void remove (T &) {}
1408 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1409 sinfo_map_t;
1412 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1414 struct dt_node
1416 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1418 enum dt_type type;
1419 unsigned level;
1420 vec<dt_node *> kids;
1422 /* Statistics. */
1423 unsigned num_leafs;
1424 unsigned total_size;
1425 unsigned max_level;
1427 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1429 dt_node *append_node (dt_node *);
1430 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1431 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1432 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1433 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1435 virtual void gen (FILE *, int, bool) {}
1437 void gen_kids (FILE *, int, bool);
1438 void gen_kids_1 (FILE *, int, bool,
1439 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1440 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1442 void analyze (sinfo_map_t &);
1445 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1447 struct dt_operand : public dt_node
1449 operand *op;
1450 dt_operand *match_dop;
1451 dt_operand *parent;
1452 unsigned pos;
1454 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1455 dt_operand *parent_ = 0, unsigned pos_ = 0)
1456 : dt_node (type), op (op_), match_dop (match_dop_),
1457 parent (parent_), pos (pos_) {}
1459 void gen (FILE *, int, bool);
1460 unsigned gen_predicate (FILE *, int, const char *, bool);
1461 unsigned gen_match_op (FILE *, int, const char *);
1463 unsigned gen_gimple_expr (FILE *, int);
1464 unsigned gen_generic_expr (FILE *, int, const char *);
1466 char *get_name (char *);
1467 void gen_opname (char *, unsigned);
1470 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1472 struct dt_simplify : public dt_node
1474 simplify *s;
1475 unsigned pattern_no;
1476 dt_operand **indexes;
1477 sinfo *info;
1479 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1480 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1481 indexes (indexes_), info (NULL) {}
1483 void gen_1 (FILE *, int, bool, operand *);
1484 void gen (FILE *f, int, bool);
1487 template<>
1488 template<>
1489 inline bool
1490 is_a_helper <dt_operand *>::test (dt_node *n)
1492 return (n->type == dt_node::DT_OPERAND
1493 || n->type == dt_node::DT_MATCH);
1496 template<>
1497 template<>
1498 inline bool
1499 is_a_helper <dt_simplify *>::test (dt_node *n)
1501 return n->type == dt_node::DT_SIMPLIFY;
1506 /* A container for the actual decision tree. */
1508 struct decision_tree
1510 dt_node *root;
1512 void insert (struct simplify *, unsigned);
1513 void gen (FILE *f, bool gimple);
1514 void print (FILE *f = stderr);
1516 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1518 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1519 unsigned pos = 0, dt_node *parent = 0);
1520 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1521 static bool cmp_node (dt_node *, dt_node *);
1522 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1525 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1527 bool
1528 cmp_operand (operand *o1, operand *o2)
1530 if (!o1 || !o2 || o1->type != o2->type)
1531 return false;
1533 if (o1->type == operand::OP_PREDICATE)
1535 predicate *p1 = as_a<predicate *>(o1);
1536 predicate *p2 = as_a<predicate *>(o2);
1537 return p1->p == p2->p;
1539 else if (o1->type == operand::OP_EXPR)
1541 expr *e1 = static_cast<expr *>(o1);
1542 expr *e2 = static_cast<expr *>(o2);
1543 return (e1->operation == e2->operation
1544 && e1->is_generic == e2->is_generic);
1546 else
1547 return false;
1550 /* Compare two decision tree nodes N1 and N2 and return true if they
1551 are equal. */
1553 bool
1554 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1556 if (!n1 || !n2 || n1->type != n2->type)
1557 return false;
1559 if (n1 == n2)
1560 return true;
1562 if (n1->type == dt_node::DT_TRUE)
1563 return false;
1565 if (n1->type == dt_node::DT_OPERAND)
1566 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1567 (as_a<dt_operand *> (n2))->op);
1568 else if (n1->type == dt_node::DT_MATCH)
1569 return ((as_a<dt_operand *> (n1))->match_dop
1570 == (as_a<dt_operand *> (n2))->match_dop);
1571 return false;
1574 /* Search OPS for a decision tree node like P and return it if found. */
1576 dt_node *
1577 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1579 /* We can merge adjacent DT_TRUE. */
1580 if (p->type == dt_node::DT_TRUE
1581 && !ops.is_empty ()
1582 && ops.last ()->type == dt_node::DT_TRUE)
1583 return ops.last ();
1584 for (int i = ops.length () - 1; i >= 0; --i)
1586 /* But we can't merge across DT_TRUE nodes as they serve as
1587 pattern order barriers to make sure that patterns apply
1588 in order of appearance in case multiple matches are possible. */
1589 if (ops[i]->type == dt_node::DT_TRUE)
1590 return NULL;
1591 if (decision_tree::cmp_node (ops[i], p))
1592 return ops[i];
1594 return NULL;
1597 /* Append N to the decision tree if it there is not already an existing
1598 identical child. */
1600 dt_node *
1601 dt_node::append_node (dt_node *n)
1603 dt_node *kid;
1605 kid = decision_tree::find_node (kids, n);
1606 if (kid)
1607 return kid;
1609 kids.safe_push (n);
1610 n->level = this->level + 1;
1612 return n;
1615 /* Append OP to the decision tree. */
1617 dt_node *
1618 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1620 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1621 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1622 return append_node (n);
1625 /* Append a DT_TRUE decision tree node. */
1627 dt_node *
1628 dt_node::append_true_op (dt_node *parent, unsigned pos)
1630 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1631 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1632 return append_node (n);
1635 /* Append a DT_MATCH decision tree node. */
1637 dt_node *
1638 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1640 dt_operand *parent_ = as_a<dt_operand *> (parent);
1641 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1642 return append_node (n);
1645 /* Append S to the decision tree. */
1647 dt_node *
1648 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1649 dt_operand **indexes)
1651 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1652 for (unsigned i = 0; i < kids.length (); ++i)
1653 if (dt_simplify *s2 = dyn_cast <dt_simplify *> (kids[i]))
1655 warning_at (s->match->location, "duplicate pattern");
1656 warning_at (s2->s->match->location, "previous pattern defined here");
1657 print_operand (s->match, stderr);
1658 fprintf (stderr, "\n");
1660 return append_node (n);
1663 /* Analyze the node and its children. */
1665 void
1666 dt_node::analyze (sinfo_map_t &map)
1668 num_leafs = 0;
1669 total_size = 1;
1670 max_level = level;
1672 if (type == DT_SIMPLIFY)
1674 /* Populate the map of equivalent simplifies. */
1675 dt_simplify *s = as_a <dt_simplify *> (this);
1676 bool existed;
1677 sinfo *&si = map.get_or_insert (s, &existed);
1678 if (!existed)
1680 si = new sinfo;
1681 si->s = s;
1682 si->cnt = 1;
1683 si->fname = NULL;
1685 else
1686 si->cnt++;
1687 s->info = si;
1688 num_leafs = 1;
1689 return;
1692 for (unsigned i = 0; i < kids.length (); ++i)
1694 kids[i]->analyze (map);
1695 num_leafs += kids[i]->num_leafs;
1696 total_size += kids[i]->total_size;
1697 max_level = MAX (max_level, kids[i]->max_level);
1701 /* Insert O into the decision tree and return the decision tree node found
1702 or created. */
1704 dt_node *
1705 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1706 unsigned pos, dt_node *parent)
1708 dt_node *q, *elm = 0;
1710 if (capture *c = dyn_cast<capture *> (o))
1712 unsigned capt_index = c->where;
1714 if (indexes[capt_index] == 0)
1716 if (c->what)
1717 q = insert_operand (p, c->what, indexes, pos, parent);
1718 else
1720 q = elm = p->append_true_op (parent, pos);
1721 goto at_assert_elm;
1723 // get to the last capture
1724 for (operand *what = c->what;
1725 what && is_a<capture *> (what);
1726 c = as_a<capture *> (what), what = c->what)
1729 if (!c->what)
1731 unsigned cc_index = c->where;
1732 dt_operand *match_op = indexes[cc_index];
1734 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1735 elm = decision_tree::find_node (p->kids, &temp);
1737 if (elm == 0)
1739 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1740 elm = decision_tree::find_node (p->kids, &temp);
1743 else
1745 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1746 elm = decision_tree::find_node (p->kids, &temp);
1749 at_assert_elm:
1750 gcc_assert (elm->type == dt_node::DT_TRUE
1751 || elm->type == dt_node::DT_OPERAND
1752 || elm->type == dt_node::DT_MATCH);
1753 indexes[capt_index] = static_cast<dt_operand *> (elm);
1754 return q;
1756 else
1758 p = p->append_match_op (indexes[capt_index], parent, pos);
1759 if (c->what)
1760 return insert_operand (p, c->what, indexes, 0, p);
1761 else
1762 return p;
1765 p = p->append_op (o, parent, pos);
1766 q = p;
1768 if (expr *e = dyn_cast <expr *>(o))
1770 for (unsigned i = 0; i < e->ops.length (); ++i)
1771 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1774 return q;
1777 /* Insert S into the decision tree. */
1779 void
1780 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1782 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1783 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1784 p->append_simplify (s, pattern_no, indexes);
1787 /* Debug functions to dump the decision tree. */
1789 DEBUG_FUNCTION void
1790 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1792 if (p->type == dt_node::DT_NODE)
1793 fprintf (f, "root");
1794 else
1796 fprintf (f, "|");
1797 for (unsigned i = 0; i < indent; i++)
1798 fprintf (f, "-");
1800 if (p->type == dt_node::DT_OPERAND)
1802 dt_operand *dop = static_cast<dt_operand *>(p);
1803 print_operand (dop->op, f, true);
1805 else if (p->type == dt_node::DT_TRUE)
1806 fprintf (f, "true");
1807 else if (p->type == dt_node::DT_MATCH)
1808 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1809 else if (p->type == dt_node::DT_SIMPLIFY)
1811 dt_simplify *s = static_cast<dt_simplify *> (p);
1812 fprintf (f, "simplify_%u { ", s->pattern_no);
1813 for (int i = 0; i <= s->s->capture_max; ++i)
1814 fprintf (f, "%p, ", (void *) s->indexes[i]);
1815 fprintf (f, " } ");
1819 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1821 for (unsigned i = 0; i < p->kids.length (); ++i)
1822 decision_tree::print_node (p->kids[i], f, indent + 2);
1825 DEBUG_FUNCTION void
1826 decision_tree::print (FILE *f)
1828 return decision_tree::print_node (root, f);
1832 /* For GENERIC we have to take care of wrapping multiple-used
1833 expressions with side-effects in save_expr and preserve side-effects
1834 of expressions with omit_one_operand. Analyze captures in
1835 match, result and with expressions and perform early-outs
1836 on the outermost match expression operands for cases we cannot
1837 handle. */
1839 struct capture_info
1841 capture_info (simplify *s, operand *, bool);
1842 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1843 bool walk_result (operand *o, bool, operand *);
1844 void walk_c_expr (c_expr *);
1846 struct cinfo
1848 bool expr_p;
1849 bool cse_p;
1850 bool force_no_side_effects_p;
1851 bool force_single_use;
1852 bool cond_expr_cond_p;
1853 unsigned long toplevel_msk;
1854 unsigned match_use_count;
1855 unsigned result_use_count;
1856 unsigned same_as;
1857 capture *c;
1860 auto_vec<cinfo> info;
1861 unsigned long force_no_side_effects;
1862 bool gimple;
1865 /* Analyze captures in S. */
1867 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
1869 gimple = gimple_;
1871 expr *e;
1872 if (s->kind == simplify::MATCH)
1874 force_no_side_effects = -1;
1875 return;
1878 force_no_side_effects = 0;
1879 info.safe_grow_cleared (s->capture_max + 1);
1880 for (int i = 0; i <= s->capture_max; ++i)
1881 info[i].same_as = i;
1883 e = as_a <expr *> (s->match);
1884 for (unsigned i = 0; i < e->ops.length (); ++i)
1885 walk_match (e->ops[i], i,
1886 (i != 0 && *e->operation == COND_EXPR)
1887 || *e->operation == TRUTH_ANDIF_EXPR
1888 || *e->operation == TRUTH_ORIF_EXPR,
1889 i == 0
1890 && (*e->operation == COND_EXPR
1891 || *e->operation == VEC_COND_EXPR));
1893 walk_result (s->result, false, result);
1896 /* Analyze captures in the match expression piece O. */
1898 void
1899 capture_info::walk_match (operand *o, unsigned toplevel_arg,
1900 bool conditional_p, bool cond_expr_cond_p)
1902 if (capture *c = dyn_cast <capture *> (o))
1904 unsigned where = c->where;
1905 info[where].match_use_count++;
1906 info[where].toplevel_msk |= 1 << toplevel_arg;
1907 info[where].force_no_side_effects_p |= conditional_p;
1908 info[where].cond_expr_cond_p |= cond_expr_cond_p;
1909 if (!info[where].c)
1910 info[where].c = c;
1911 if (!c->what)
1912 return;
1913 /* Recurse to exprs and captures. */
1914 if (is_a <capture *> (c->what)
1915 || is_a <expr *> (c->what))
1916 walk_match (c->what, toplevel_arg, conditional_p, false);
1917 /* We need to look past multiple captures to find a captured
1918 expression as with conditional converts two captures
1919 can be collapsed onto the same expression. Also collect
1920 what captures capture the same thing. */
1921 while (c->what && is_a <capture *> (c->what))
1923 c = as_a <capture *> (c->what);
1924 if (info[c->where].same_as != c->where
1925 && info[c->where].same_as != info[where].same_as)
1926 fatal_at (c->location, "cannot handle this collapsed capture");
1927 info[c->where].same_as = info[where].same_as;
1929 /* Mark expr (non-leaf) captures and forced single-use exprs. */
1930 expr *e;
1931 if (c->what
1932 && (e = dyn_cast <expr *> (c->what)))
1934 info[where].expr_p = true;
1935 info[where].force_single_use |= e->force_single_use;
1938 else if (expr *e = dyn_cast <expr *> (o))
1940 for (unsigned i = 0; i < e->ops.length (); ++i)
1942 bool cond_p = conditional_p;
1943 bool cond_expr_cond_p = false;
1944 if (i != 0 && *e->operation == COND_EXPR)
1945 cond_p = true;
1946 else if (*e->operation == TRUTH_ANDIF_EXPR
1947 || *e->operation == TRUTH_ORIF_EXPR)
1948 cond_p = true;
1949 if (i == 0
1950 && (*e->operation == COND_EXPR
1951 || *e->operation == VEC_COND_EXPR))
1952 cond_expr_cond_p = true;
1953 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1956 else if (is_a <predicate *> (o))
1958 /* Mark non-captured leafs toplevel arg for checking. */
1959 force_no_side_effects |= 1 << toplevel_arg;
1960 if (verbose >= 1
1961 && !gimple)
1962 warning_at (o->location,
1963 "forcing no side-effects on possibly lost leaf");
1965 else
1966 gcc_unreachable ();
1969 /* Analyze captures in the result expression piece O. Return true
1970 if RESULT was visited in one of the children. Only visit
1971 non-if/with children if they are rooted on RESULT. */
1973 bool
1974 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
1976 if (capture *c = dyn_cast <capture *> (o))
1978 unsigned where = info[c->where].same_as;
1979 info[where].result_use_count++;
1980 /* If we substitute an expression capture we don't know
1981 which captures this will end up using (well, we don't
1982 compute that). Force the uses to be side-effect free
1983 which means forcing the toplevels that reach the
1984 expression side-effect free. */
1985 if (info[where].expr_p)
1986 force_no_side_effects |= info[where].toplevel_msk;
1987 /* Mark CSE capture uses as forced to have no side-effects. */
1988 if (c->what
1989 && is_a <expr *> (c->what))
1991 info[where].cse_p = true;
1992 walk_result (c->what, true, result);
1995 else if (expr *e = dyn_cast <expr *> (o))
1997 id_base *opr = e->operation;
1998 if (user_id *uid = dyn_cast <user_id *> (opr))
1999 opr = uid->substitutes[0];
2000 for (unsigned i = 0; i < e->ops.length (); ++i)
2002 bool cond_p = conditional_p;
2003 if (i != 0 && *e->operation == COND_EXPR)
2004 cond_p = true;
2005 else if (*e->operation == TRUTH_ANDIF_EXPR
2006 || *e->operation == TRUTH_ORIF_EXPR)
2007 cond_p = true;
2008 walk_result (e->ops[i], cond_p, result);
2011 else if (if_expr *e = dyn_cast <if_expr *> (o))
2013 /* 'if' conditions should be all fine. */
2014 if (e->trueexpr == result)
2016 walk_result (e->trueexpr, false, result);
2017 return true;
2019 if (e->falseexpr == result)
2021 walk_result (e->falseexpr, false, result);
2022 return true;
2024 bool res = false;
2025 if (is_a <if_expr *> (e->trueexpr)
2026 || is_a <with_expr *> (e->trueexpr))
2027 res |= walk_result (e->trueexpr, false, result);
2028 if (e->falseexpr
2029 && (is_a <if_expr *> (e->falseexpr)
2030 || is_a <with_expr *> (e->falseexpr)))
2031 res |= walk_result (e->falseexpr, false, result);
2032 return res;
2034 else if (with_expr *e = dyn_cast <with_expr *> (o))
2036 bool res = (e->subexpr == result);
2037 if (res
2038 || is_a <if_expr *> (e->subexpr)
2039 || is_a <with_expr *> (e->subexpr))
2040 res |= walk_result (e->subexpr, false, result);
2041 if (res)
2042 walk_c_expr (e->with);
2043 return res;
2045 else if (c_expr *e = dyn_cast <c_expr *> (o))
2046 walk_c_expr (e);
2047 else
2048 gcc_unreachable ();
2050 return false;
2053 /* Look for captures in the C expr E. */
2055 void
2056 capture_info::walk_c_expr (c_expr *e)
2058 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2059 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2060 really escape through. */
2061 unsigned p_depth = 0;
2062 for (unsigned i = 0; i < e->code.length (); ++i)
2064 const cpp_token *t = &e->code[i];
2065 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2066 id_base *id;
2067 if (t->type == CPP_NAME
2068 && (strcmp ((const char *)CPP_HASHNODE
2069 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2070 || strcmp ((const char *)CPP_HASHNODE
2071 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2072 || strcmp ((const char *)CPP_HASHNODE
2073 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2074 || ((id = get_operator ((const char *)CPP_HASHNODE
2075 (t->val.node.node)->ident.str))
2076 && is_a <predicate_id *> (id)))
2077 && n->type == CPP_OPEN_PAREN)
2078 p_depth++;
2079 else if (t->type == CPP_CLOSE_PAREN
2080 && p_depth > 0)
2081 p_depth--;
2082 else if (p_depth == 0
2083 && t->type == CPP_ATSIGN
2084 && (n->type == CPP_NUMBER
2085 || n->type == CPP_NAME)
2086 && !(n->flags & PREV_WHITE))
2088 const char *id;
2089 if (n->type == CPP_NUMBER)
2090 id = (const char *)n->val.str.text;
2091 else
2092 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2093 unsigned where = *e->capture_ids->get(id);
2094 info[info[where].same_as].force_no_side_effects_p = true;
2095 if (verbose >= 1
2096 && !gimple)
2097 warning_at (t, "capture escapes");
2103 /* Code generation off the decision tree and the refered AST nodes. */
2105 bool
2106 is_conversion (id_base *op)
2108 return (*op == CONVERT_EXPR
2109 || *op == NOP_EXPR
2110 || *op == FLOAT_EXPR
2111 || *op == FIX_TRUNC_EXPR
2112 || *op == VIEW_CONVERT_EXPR);
2115 /* Get the type to be used for generating operands of OP from the
2116 various sources. */
2118 static const char *
2119 get_operand_type (id_base *op, const char *in_type,
2120 const char *expr_type,
2121 const char *other_oprnd_type)
2123 /* Generally operands whose type does not match the type of the
2124 expression generated need to know their types but match and
2125 thus can fall back to 'other_oprnd_type'. */
2126 if (is_conversion (op))
2127 return other_oprnd_type;
2128 else if (*op == REALPART_EXPR
2129 || *op == IMAGPART_EXPR)
2130 return other_oprnd_type;
2131 else if (is_a <operator_id *> (op)
2132 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2133 return other_oprnd_type;
2134 else
2136 /* Otherwise all types should match - choose one in order of
2137 preference. */
2138 if (expr_type)
2139 return expr_type;
2140 else if (in_type)
2141 return in_type;
2142 else
2143 return other_oprnd_type;
2147 /* Generate transform code for an expression. */
2149 void
2150 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2151 int depth, const char *in_type, capture_info *cinfo,
2152 dt_operand **indexes, bool)
2154 id_base *opr = operation;
2155 /* When we delay operator substituting during lowering of fors we
2156 make sure that for code-gen purposes the effects of each substitute
2157 are the same. Thus just look at that. */
2158 if (user_id *uid = dyn_cast <user_id *> (opr))
2159 opr = uid->substitutes[0];
2161 bool conversion_p = is_conversion (opr);
2162 const char *type = expr_type;
2163 char optype[64];
2164 if (type)
2165 /* If there was a type specification in the pattern use it. */
2167 else if (conversion_p)
2168 /* For conversions we need to build the expression using the
2169 outer type passed in. */
2170 type = in_type;
2171 else if (*opr == REALPART_EXPR
2172 || *opr == IMAGPART_EXPR)
2174 /* __real and __imag use the component type of its operand. */
2175 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
2176 type = optype;
2178 else if (is_a <operator_id *> (opr)
2179 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2181 /* comparisons use boolean_type_node (or what gets in), but
2182 their operands need to figure out the types themselves. */
2183 sprintf (optype, "boolean_type_node");
2184 type = optype;
2186 else if (*opr == COND_EXPR
2187 || *opr == VEC_COND_EXPR)
2189 /* Conditions are of the same type as their first alternative. */
2190 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
2191 type = optype;
2193 else
2195 /* Other operations are of the same type as their first operand. */
2196 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
2197 type = optype;
2199 if (!type)
2200 fatal_at (location, "cannot determine type of operand");
2202 fprintf_indent (f, indent, "{\n");
2203 indent += 2;
2204 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
2205 char op0type[64];
2206 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
2207 for (unsigned i = 0; i < ops.length (); ++i)
2209 char dest[32];
2210 snprintf (dest, 32, "ops%d[%u]", depth, i);
2211 const char *optype
2212 = get_operand_type (opr, in_type, expr_type,
2213 i == 0 ? NULL : op0type);
2214 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
2215 cinfo, indexes,
2216 ((!(*opr == COND_EXPR)
2217 && !(*opr == VEC_COND_EXPR))
2218 || i != 0));
2221 const char *opr_name;
2222 if (*operation == CONVERT_EXPR)
2223 opr_name = "NOP_EXPR";
2224 else
2225 opr_name = operation->id;
2227 if (gimple)
2229 if (*opr == CONVERT_EXPR)
2231 fprintf_indent (f, indent,
2232 "if (%s != TREE_TYPE (ops%d[0])\n",
2233 type, depth);
2234 fprintf_indent (f, indent,
2235 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
2236 type, depth);
2237 fprintf_indent (f, indent + 2, "{\n");
2238 indent += 4;
2240 /* ??? Building a stmt can fail for various reasons here, seq being
2241 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2242 So if we fail here we should continue matching other patterns. */
2243 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr_name);
2244 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
2245 for (unsigned i = 0; i < ops.length (); ++i)
2246 fprintf (f, "ops%d[%u]%s", depth, i,
2247 i == ops.length () - 1 ? " };\n" : ", ");
2248 fprintf_indent (f, indent,
2249 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
2250 ops.length (), type);
2251 fprintf_indent (f, indent,
2252 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
2253 type);
2254 fprintf_indent (f, indent,
2255 "if (!res) return false;\n");
2256 if (*opr == CONVERT_EXPR)
2258 indent -= 4;
2259 fprintf_indent (f, indent, " }\n");
2260 fprintf_indent (f, indent, "else\n");
2261 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2264 else
2266 if (*opr == CONVERT_EXPR)
2268 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
2269 depth, type);
2270 indent += 2;
2272 if (opr->kind == id_base::CODE)
2273 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
2274 ops.length(), opr_name, type);
2275 else
2277 fprintf_indent (f, indent, "{\n");
2278 fprintf_indent (f, indent, " res = maybe_build_call_expr_loc (loc, "
2279 "%s, %s, %d", opr_name, type, ops.length());
2281 for (unsigned i = 0; i < ops.length (); ++i)
2282 fprintf (f, ", ops%d[%u]", depth, i);
2283 fprintf (f, ");\n");
2284 if (opr->kind != id_base::CODE)
2286 fprintf_indent (f, indent, " if (!res)\n");
2287 fprintf_indent (f, indent, " return NULL_TREE;\n");
2288 fprintf_indent (f, indent, "}\n");
2290 if (*opr == CONVERT_EXPR)
2292 indent -= 2;
2293 fprintf_indent (f, indent, "else\n");
2294 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2297 fprintf_indent (f, indent, "%s = res;\n", dest);
2298 indent -= 2;
2299 fprintf_indent (f, indent, "}\n");
2302 /* Generate code for a c_expr which is either the expression inside
2303 an if statement or a sequence of statements which computes a
2304 result to be stored to DEST. */
2306 void
2307 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2308 bool, int, const char *, capture_info *,
2309 dt_operand **, bool)
2311 if (dest && nr_stmts == 1)
2312 fprintf_indent (f, indent, "%s = ", dest);
2314 unsigned stmt_nr = 1;
2315 for (unsigned i = 0; i < code.length (); ++i)
2317 const cpp_token *token = &code[i];
2319 /* Replace captures for code-gen. */
2320 if (token->type == CPP_ATSIGN)
2322 const cpp_token *n = &code[i+1];
2323 if ((n->type == CPP_NUMBER
2324 || n->type == CPP_NAME)
2325 && !(n->flags & PREV_WHITE))
2327 if (token->flags & PREV_WHITE)
2328 fputc (' ', f);
2329 const char *id;
2330 if (n->type == CPP_NUMBER)
2331 id = (const char *)n->val.str.text;
2332 else
2333 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2334 unsigned *cid = capture_ids->get (id);
2335 if (!cid)
2336 fatal_at (token, "unknown capture id");
2337 fprintf (f, "captures[%u]", *cid);
2338 ++i;
2339 continue;
2343 if (token->flags & PREV_WHITE)
2344 fputc (' ', f);
2346 if (token->type == CPP_NAME)
2348 const char *id = (const char *) NODE_NAME (token->val.node.node);
2349 unsigned j;
2350 for (j = 0; j < ids.length (); ++j)
2352 if (strcmp (id, ids[j].id) == 0)
2354 fprintf (f, "%s", ids[j].oper);
2355 break;
2358 if (j < ids.length ())
2359 continue;
2362 /* Output the token as string. */
2363 char *tk = (char *)cpp_token_as_text (r, token);
2364 fputs (tk, f);
2366 if (token->type == CPP_SEMICOLON)
2368 stmt_nr++;
2369 fputc ('\n', f);
2370 if (dest && stmt_nr == nr_stmts)
2371 fprintf_indent (f, indent, "%s = ", dest);
2376 /* Generate transform code for a capture. */
2378 void
2379 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2380 int depth, const char *in_type, capture_info *cinfo,
2381 dt_operand **indexes, bool expand_compares)
2383 if (what && is_a<expr *> (what))
2385 if (indexes[where] == 0)
2387 char buf[20];
2388 sprintf (buf, "captures[%u]", where);
2389 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2390 cinfo, NULL);
2394 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2396 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2397 with substituting a capture of that.
2398 ??? Returning false here will also not allow any other patterns
2399 to match. */
2400 if (gimple && expand_compares
2401 && cinfo->info[where].cond_expr_cond_p)
2403 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2404 fprintf_indent (f, indent, " {\n");
2405 fprintf_indent (f, indent, " if (!seq) return false;\n");
2406 fprintf_indent (f, indent, " %s = gimple_build (seq, TREE_CODE (%s),"
2407 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2408 " TREE_OPERAND (%s, 1));\n",
2409 dest, dest, dest, dest, dest);
2410 fprintf_indent (f, indent, " }\n");
2414 /* Return the name of the operand representing the decision tree node.
2415 Use NAME as space to generate it. */
2417 char *
2418 dt_operand::get_name (char *name)
2420 if (!parent)
2421 sprintf (name, "t");
2422 else if (parent->level == 1)
2423 sprintf (name, "op%u", pos);
2424 else if (parent->type == dt_node::DT_MATCH)
2425 return parent->get_name (name);
2426 else
2427 sprintf (name, "o%u%u", parent->level, pos);
2428 return name;
2431 /* Fill NAME with the operand name at position POS. */
2433 void
2434 dt_operand::gen_opname (char *name, unsigned pos)
2436 if (!parent)
2437 sprintf (name, "op%u", pos);
2438 else
2439 sprintf (name, "o%u%u", level, pos);
2442 /* Generate matching code for the decision tree operand which is
2443 a predicate. */
2445 unsigned
2446 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2448 predicate *p = as_a <predicate *> (op);
2450 if (p->p->matchers.exists ())
2452 /* If this is a predicate generated from a pattern mangle its
2453 name and pass on the valueize hook. */
2454 if (gimple)
2455 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2456 p->p->id, opname);
2457 else
2458 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2460 else
2461 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2462 fprintf_indent (f, indent + 2, "{\n");
2463 return 1;
2466 /* Generate matching code for the decision tree operand which is
2467 a capture-match. */
2469 unsigned
2470 dt_operand::gen_match_op (FILE *f, int indent, const char *opname)
2472 char match_opname[20];
2473 match_dop->get_name (match_opname);
2474 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2475 opname, match_opname, opname, match_opname);
2476 fprintf_indent (f, indent + 2, "{\n");
2477 return 1;
2480 /* Generate GIMPLE matching code for the decision tree operand. */
2482 unsigned
2483 dt_operand::gen_gimple_expr (FILE *f, int indent)
2485 expr *e = static_cast<expr *> (op);
2486 id_base *id = e->operation;
2487 unsigned n_ops = e->ops.length ();
2489 for (unsigned i = 0; i < n_ops; ++i)
2491 char child_opname[20];
2492 gen_opname (child_opname, i);
2494 if (id->kind == id_base::CODE)
2496 if (e->is_generic
2497 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2498 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2500 /* ??? If this is a memory operation we can't (and should not)
2501 match this. The only sensible operand types are
2502 SSA names and invariants. */
2503 fprintf_indent (f, indent,
2504 "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def), %i);\n",
2505 child_opname, i);
2506 fprintf_indent (f, indent,
2507 "if ((TREE_CODE (%s) == SSA_NAME\n",
2508 child_opname);
2509 fprintf_indent (f, indent,
2510 " || is_gimple_min_invariant (%s))\n",
2511 child_opname);
2512 fprintf_indent (f, indent,
2513 " && (%s = do_valueize (valueize, %s)))\n",
2514 child_opname, child_opname);
2515 fprintf_indent (f, indent,
2516 " {\n");
2517 indent += 4;
2518 continue;
2520 else
2521 fprintf_indent (f, indent,
2522 "tree %s = gimple_assign_rhs%u (def);\n",
2523 child_opname, i + 1);
2525 else
2526 fprintf_indent (f, indent,
2527 "tree %s = gimple_call_arg (def, %u);\n",
2528 child_opname, i);
2529 fprintf_indent (f, indent,
2530 "if ((%s = do_valueize (valueize, %s)))\n",
2531 child_opname, child_opname);
2532 fprintf_indent (f, indent, " {\n");
2533 indent += 4;
2535 /* While the toplevel operands are canonicalized by the caller
2536 after valueizing operands of sub-expressions we have to
2537 re-canonicalize operand order. */
2538 if (operator_id *code = dyn_cast <operator_id *> (id))
2540 /* ??? We can't canonicalize tcc_comparison operands here
2541 because that requires changing the comparison code which
2542 we already matched... */
2543 if (commutative_tree_code (code->code)
2544 || commutative_ternary_tree_code (code->code))
2546 char child_opname0[20], child_opname1[20];
2547 gen_opname (child_opname0, 0);
2548 gen_opname (child_opname1, 1);
2549 fprintf_indent (f, indent,
2550 "if (tree_swap_operands_p (%s, %s, false))\n",
2551 child_opname0, child_opname1);
2552 fprintf_indent (f, indent,
2553 " std::swap (%s, %s);\n",
2554 child_opname0, child_opname1);
2558 return n_ops;
2561 /* Generate GENERIC matching code for the decision tree operand. */
2563 unsigned
2564 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2566 expr *e = static_cast<expr *> (op);
2567 unsigned n_ops = e->ops.length ();
2569 for (unsigned i = 0; i < n_ops; ++i)
2571 char child_opname[20];
2572 gen_opname (child_opname, i);
2574 if (e->operation->kind == id_base::CODE)
2575 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2576 child_opname, opname, i);
2577 else
2578 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2579 child_opname, opname, i);
2582 return 0;
2585 /* Generate matching code for the children of the decision tree node. */
2587 void
2588 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2590 auto_vec<dt_operand *> gimple_exprs;
2591 auto_vec<dt_operand *> generic_exprs;
2592 auto_vec<dt_operand *> fns;
2593 auto_vec<dt_operand *> generic_fns;
2594 auto_vec<dt_operand *> preds;
2595 auto_vec<dt_node *> others;
2597 for (unsigned i = 0; i < kids.length (); ++i)
2599 if (kids[i]->type == dt_node::DT_OPERAND)
2601 dt_operand *op = as_a<dt_operand *> (kids[i]);
2602 if (expr *e = dyn_cast <expr *> (op->op))
2604 if (e->ops.length () == 0
2605 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2606 generic_exprs.safe_push (op);
2607 else if (e->operation->kind == id_base::FN)
2609 if (gimple)
2610 fns.safe_push (op);
2611 else
2612 generic_fns.safe_push (op);
2614 else if (e->operation->kind == id_base::PREDICATE)
2615 preds.safe_push (op);
2616 else
2618 if (gimple)
2619 gimple_exprs.safe_push (op);
2620 else
2621 generic_exprs.safe_push (op);
2624 else if (op->op->type == operand::OP_PREDICATE)
2625 others.safe_push (kids[i]);
2626 else
2627 gcc_unreachable ();
2629 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
2630 others.safe_push (kids[i]);
2631 else if (kids[i]->type == dt_node::DT_MATCH
2632 || kids[i]->type == dt_node::DT_TRUE)
2634 /* A DT_TRUE operand serves as a barrier - generate code now
2635 for what we have collected sofar.
2636 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
2637 dependent matches to get out-of-order. Generate code now
2638 for what we have collected sofar. */
2639 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2640 fns, generic_fns, preds, others);
2641 /* And output the true operand itself. */
2642 kids[i]->gen (f, indent, gimple);
2643 gimple_exprs.truncate (0);
2644 generic_exprs.truncate (0);
2645 fns.truncate (0);
2646 generic_fns.truncate (0);
2647 preds.truncate (0);
2648 others.truncate (0);
2650 else
2651 gcc_unreachable ();
2654 /* Generate code for the remains. */
2655 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2656 fns, generic_fns, preds, others);
2659 /* Generate matching code for the children of the decision tree node. */
2661 void
2662 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2663 vec<dt_operand *> gimple_exprs,
2664 vec<dt_operand *> generic_exprs,
2665 vec<dt_operand *> fns,
2666 vec<dt_operand *> generic_fns,
2667 vec<dt_operand *> preds,
2668 vec<dt_node *> others)
2670 char buf[128];
2671 char *kid_opname = buf;
2673 unsigned exprs_len = gimple_exprs.length ();
2674 unsigned gexprs_len = generic_exprs.length ();
2675 unsigned fns_len = fns.length ();
2676 unsigned gfns_len = generic_fns.length ();
2678 if (exprs_len || fns_len || gexprs_len || gfns_len)
2680 if (exprs_len)
2681 gimple_exprs[0]->get_name (kid_opname);
2682 else if (fns_len)
2683 fns[0]->get_name (kid_opname);
2684 else if (gfns_len)
2685 generic_fns[0]->get_name (kid_opname);
2686 else
2687 generic_exprs[0]->get_name (kid_opname);
2689 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2690 fprintf_indent (f, indent, " {\n");
2691 indent += 2;
2694 if (exprs_len || fns_len)
2696 fprintf_indent (f, indent,
2697 "case SSA_NAME:\n");
2698 fprintf_indent (f, indent,
2699 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2700 kid_opname);
2701 fprintf_indent (f, indent,
2702 " {\n");
2703 fprintf_indent (f, indent,
2704 " gimple *def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2705 kid_opname);
2707 indent += 6;
2708 if (exprs_len)
2710 fprintf_indent (f, indent,
2711 "if (gassign *def = dyn_cast <gassign *> (def_stmt))\n");
2712 fprintf_indent (f, indent,
2713 " switch (gimple_assign_rhs_code (def))\n");
2714 indent += 4;
2715 fprintf_indent (f, indent, "{\n");
2716 for (unsigned i = 0; i < exprs_len; ++i)
2718 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2719 id_base *op = e->operation;
2720 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2721 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2722 else
2723 fprintf_indent (f, indent, "case %s:\n", op->id);
2724 fprintf_indent (f, indent, " {\n");
2725 gimple_exprs[i]->gen (f, indent + 4, true);
2726 fprintf_indent (f, indent, " break;\n");
2727 fprintf_indent (f, indent, " }\n");
2729 fprintf_indent (f, indent, "default:;\n");
2730 fprintf_indent (f, indent, "}\n");
2731 indent -= 4;
2734 if (fns_len)
2736 fprintf_indent (f, indent,
2737 "%sif (gcall *def = dyn_cast <gcall *>"
2738 " (def_stmt))\n",
2739 exprs_len ? "else " : "");
2740 fprintf_indent (f, indent,
2741 " switch (gimple_call_combined_fn (def))\n");
2743 indent += 4;
2744 fprintf_indent (f, indent, "{\n");
2745 for (unsigned i = 0; i < fns_len; ++i)
2747 expr *e = as_a <expr *>(fns[i]->op);
2748 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2749 fprintf_indent (f, indent, " {\n");
2750 fns[i]->gen (f, indent + 4, true);
2751 fprintf_indent (f, indent, " break;\n");
2752 fprintf_indent (f, indent, " }\n");
2755 fprintf_indent (f, indent, "default:;\n");
2756 fprintf_indent (f, indent, "}\n");
2757 indent -= 4;
2760 indent -= 6;
2761 fprintf_indent (f, indent, " }\n");
2762 fprintf_indent (f, indent, " break;\n");
2765 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2767 expr *e = as_a <expr *>(generic_exprs[i]->op);
2768 id_base *op = e->operation;
2769 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2770 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2771 else
2772 fprintf_indent (f, indent, "case %s:\n", op->id);
2773 fprintf_indent (f, indent, " {\n");
2774 generic_exprs[i]->gen (f, indent + 4, gimple);
2775 fprintf_indent (f, indent, " break;\n");
2776 fprintf_indent (f, indent, " }\n");
2779 if (gfns_len)
2781 fprintf_indent (f, indent,
2782 "case CALL_EXPR:\n");
2783 fprintf_indent (f, indent,
2784 " switch (get_call_combined_fn (%s))\n",
2785 kid_opname);
2786 fprintf_indent (f, indent,
2787 " {\n");
2788 indent += 4;
2790 for (unsigned j = 0; j < generic_fns.length (); ++j)
2792 expr *e = as_a <expr *>(generic_fns[j]->op);
2793 gcc_assert (e->operation->kind == id_base::FN);
2795 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2796 fprintf_indent (f, indent, " {\n");
2797 generic_fns[j]->gen (f, indent + 4, false);
2798 fprintf_indent (f, indent, " break;\n");
2799 fprintf_indent (f, indent, " }\n");
2801 fprintf_indent (f, indent, "default:;\n");
2803 indent -= 4;
2804 fprintf_indent (f, indent, " }\n");
2805 fprintf_indent (f, indent, " break;\n");
2808 /* Close switch (TREE_CODE ()). */
2809 if (exprs_len || fns_len || gexprs_len || gfns_len)
2811 indent -= 4;
2812 fprintf_indent (f, indent, " default:;\n");
2813 fprintf_indent (f, indent, " }\n");
2816 for (unsigned i = 0; i < preds.length (); ++i)
2818 expr *e = as_a <expr *> (preds[i]->op);
2819 predicate_id *p = as_a <predicate_id *> (e->operation);
2820 preds[i]->get_name (kid_opname);
2821 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2822 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2823 gimple ? "gimple" : "tree",
2824 p->id, kid_opname, kid_opname,
2825 gimple ? ", valueize" : "");
2826 fprintf_indent (f, indent, " {\n");
2827 for (int j = 0; j < p->nargs; ++j)
2829 char child_opname[20];
2830 preds[i]->gen_opname (child_opname, j);
2831 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
2832 child_opname, kid_opname, j);
2834 preds[i]->gen_kids (f, indent + 4, gimple);
2835 fprintf (f, "}\n");
2838 for (unsigned i = 0; i < others.length (); ++i)
2839 others[i]->gen (f, indent, gimple);
2842 /* Generate matching code for the decision tree operand. */
2844 void
2845 dt_operand::gen (FILE *f, int indent, bool gimple)
2847 char opname[20];
2848 get_name (opname);
2850 unsigned n_braces = 0;
2852 if (type == DT_OPERAND)
2853 switch (op->type)
2855 case operand::OP_PREDICATE:
2856 n_braces = gen_predicate (f, indent, opname, gimple);
2857 break;
2859 case operand::OP_EXPR:
2860 if (gimple)
2861 n_braces = gen_gimple_expr (f, indent);
2862 else
2863 n_braces = gen_generic_expr (f, indent, opname);
2864 break;
2866 default:
2867 gcc_unreachable ();
2869 else if (type == DT_TRUE)
2871 else if (type == DT_MATCH)
2872 n_braces = gen_match_op (f, indent, opname);
2873 else
2874 gcc_unreachable ();
2876 indent += 4 * n_braces;
2877 gen_kids (f, indent, gimple);
2879 for (unsigned i = 0; i < n_braces; ++i)
2881 indent -= 4;
2882 if (indent < 0)
2883 indent = 0;
2884 fprintf_indent (f, indent, " }\n");
2889 /* Generate code for the '(if ...)', '(with ..)' and actual transform
2890 step of a '(simplify ...)' or '(match ...)'. This handles everything
2891 that is not part of the decision tree (simplify->match).
2892 Main recursive worker. */
2894 void
2895 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
2897 if (result)
2899 if (with_expr *w = dyn_cast <with_expr *> (result))
2901 fprintf_indent (f, indent, "{\n");
2902 indent += 4;
2903 output_line_directive (f, w->location);
2904 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2905 gen_1 (f, indent, gimple, w->subexpr);
2906 indent -= 4;
2907 fprintf_indent (f, indent, "}\n");
2908 return;
2910 else if (if_expr *ife = dyn_cast <if_expr *> (result))
2912 output_line_directive (f, ife->location);
2913 fprintf_indent (f, indent, "if (");
2914 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
2915 fprintf (f, ")\n");
2916 fprintf_indent (f, indent + 2, "{\n");
2917 indent += 4;
2918 gen_1 (f, indent, gimple, ife->trueexpr);
2919 indent -= 4;
2920 fprintf_indent (f, indent + 2, "}\n");
2921 if (ife->falseexpr)
2923 fprintf_indent (f, indent, "else\n");
2924 fprintf_indent (f, indent + 2, "{\n");
2925 indent += 4;
2926 gen_1 (f, indent, gimple, ife->falseexpr);
2927 indent -= 4;
2928 fprintf_indent (f, indent + 2, "}\n");
2930 return;
2934 /* Analyze captures and perform early-outs on the incoming arguments
2935 that cover cases we cannot handle. */
2936 capture_info cinfo (s, result, gimple);
2937 if (s->kind == simplify::SIMPLIFY)
2939 if (!gimple)
2941 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2942 if (cinfo.force_no_side_effects & (1 << i))
2944 fprintf_indent (f, indent,
2945 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
2947 if (verbose >= 1)
2948 warning_at (as_a <expr *> (s->match)->ops[i]->location,
2949 "forcing toplevel operand to have no "
2950 "side-effects");
2952 for (int i = 0; i <= s->capture_max; ++i)
2953 if (cinfo.info[i].cse_p)
2955 else if (cinfo.info[i].force_no_side_effects_p
2956 && (cinfo.info[i].toplevel_msk
2957 & cinfo.force_no_side_effects) == 0)
2959 fprintf_indent (f, indent,
2960 "if (TREE_SIDE_EFFECTS (captures[%d])) "
2961 "return NULL_TREE;\n", i);
2962 if (verbose >= 1)
2963 warning_at (cinfo.info[i].c->location,
2964 "forcing captured operand to have no "
2965 "side-effects");
2967 else if ((cinfo.info[i].toplevel_msk
2968 & cinfo.force_no_side_effects) != 0)
2969 /* Mark capture as having no side-effects if we had to verify
2970 that via forced toplevel operand checks. */
2971 cinfo.info[i].force_no_side_effects_p = true;
2973 if (gimple)
2975 /* Force single-use restriction by only allowing simple
2976 results via setting seq to NULL. */
2977 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
2978 bool first_p = true;
2979 for (int i = 0; i <= s->capture_max; ++i)
2980 if (cinfo.info[i].force_single_use)
2982 if (first_p)
2984 fprintf_indent (f, indent, "if (lseq\n");
2985 fprintf_indent (f, indent, " && (");
2986 first_p = false;
2988 else
2990 fprintf (f, "\n");
2991 fprintf_indent (f, indent, " || ");
2993 fprintf (f, "!single_use (captures[%d])", i);
2995 if (!first_p)
2997 fprintf (f, "))\n");
2998 fprintf_indent (f, indent, " lseq = NULL;\n");
3003 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
3004 "fprintf (dump_file, \"Applying pattern ");
3005 output_line_directive (f,
3006 result ? result->location : s->match->location, true);
3007 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
3009 if (!result)
3011 /* If there is no result then this is a predicate implementation. */
3012 fprintf_indent (f, indent, "return true;\n");
3014 else if (gimple)
3016 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3017 in outermost position). */
3018 if (result->type == operand::OP_EXPR
3019 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3020 result = as_a <expr *> (result)->ops[0];
3021 if (result->type == operand::OP_EXPR)
3023 expr *e = as_a <expr *> (result);
3024 id_base *opr = e->operation;
3025 bool is_predicate = false;
3026 /* When we delay operator substituting during lowering of fors we
3027 make sure that for code-gen purposes the effects of each substitute
3028 are the same. Thus just look at that. */
3029 if (user_id *uid = dyn_cast <user_id *> (opr))
3030 opr = uid->substitutes[0];
3031 else if (is_a <predicate_id *> (opr))
3032 is_predicate = true;
3033 if (!is_predicate)
3034 fprintf_indent (f, indent, "*res_code = %s;\n",
3035 *e->operation == CONVERT_EXPR
3036 ? "NOP_EXPR" : e->operation->id);
3037 for (unsigned j = 0; j < e->ops.length (); ++j)
3039 char dest[32];
3040 snprintf (dest, 32, "res_ops[%d]", j);
3041 const char *optype
3042 = get_operand_type (opr,
3043 "type", e->expr_type,
3044 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
3045 /* We need to expand GENERIC conditions we captured from
3046 COND_EXPRs. */
3047 bool expand_generic_cond_exprs_p
3048 = (!is_predicate
3049 /* But avoid doing that if the GENERIC condition is
3050 valid - which it is in the first operand of COND_EXPRs
3051 and VEC_COND_EXRPs. */
3052 && ((!(*opr == COND_EXPR)
3053 && !(*opr == VEC_COND_EXPR))
3054 || j != 0));
3055 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3056 &cinfo,
3057 indexes, expand_generic_cond_exprs_p);
3060 /* Re-fold the toplevel result. It's basically an embedded
3061 gimple_build w/o actually building the stmt. */
3062 if (!is_predicate)
3063 fprintf_indent (f, indent,
3064 "gimple_resimplify%d (lseq, res_code, type, "
3065 "res_ops, valueize);\n", e->ops.length ());
3067 else if (result->type == operand::OP_CAPTURE
3068 || result->type == operand::OP_C_EXPR)
3070 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
3071 &cinfo, indexes, false);
3072 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
3073 if (is_a <capture *> (result)
3074 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3076 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3077 with substituting a capture of that. */
3078 fprintf_indent (f, indent,
3079 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
3080 fprintf_indent (f, indent,
3081 " {\n");
3082 fprintf_indent (f, indent,
3083 " tree tem = res_ops[0];\n");
3084 fprintf_indent (f, indent,
3085 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
3086 fprintf_indent (f, indent,
3087 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
3088 fprintf_indent (f, indent,
3089 " }\n");
3092 else
3093 gcc_unreachable ();
3094 fprintf_indent (f, indent, "return true;\n");
3096 else /* GENERIC */
3098 bool is_predicate = false;
3099 if (result->type == operand::OP_EXPR)
3101 expr *e = as_a <expr *> (result);
3102 id_base *opr = e->operation;
3103 /* When we delay operator substituting during lowering of fors we
3104 make sure that for code-gen purposes the effects of each substitute
3105 are the same. Thus just look at that. */
3106 if (user_id *uid = dyn_cast <user_id *> (opr))
3107 opr = uid->substitutes[0];
3108 else if (is_a <predicate_id *> (opr))
3109 is_predicate = true;
3110 /* Search for captures used multiple times in the result expression
3111 and wrap them in a SAVE_EXPR. Allow as many uses as in the
3112 original expression. */
3113 if (!is_predicate)
3114 for (int i = 0; i < s->capture_max + 1; ++i)
3116 if (cinfo.info[i].same_as != (unsigned)i
3117 || cinfo.info[i].cse_p)
3118 continue;
3119 if (cinfo.info[i].result_use_count
3120 > cinfo.info[i].match_use_count)
3121 fprintf_indent (f, indent,
3122 "if (! tree_invariant_p (captures[%d])) "
3123 "return NULL_TREE;\n", i);
3125 for (unsigned j = 0; j < e->ops.length (); ++j)
3127 char dest[32];
3128 if (is_predicate)
3129 snprintf (dest, 32, "res_ops[%d]", j);
3130 else
3132 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3133 snprintf (dest, 32, "res_op%d", j);
3135 const char *optype
3136 = get_operand_type (opr,
3137 "type", e->expr_type,
3138 j == 0
3139 ? NULL : "TREE_TYPE (res_op0)");
3140 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3141 &cinfo, indexes);
3143 if (is_predicate)
3144 fprintf_indent (f, indent, "return true;\n");
3145 else
3147 fprintf_indent (f, indent, "tree res;\n");
3148 /* Re-fold the toplevel result. Use non_lvalue to
3149 build NON_LVALUE_EXPRs so they get properly
3150 ignored when in GIMPLE form. */
3151 if (*opr == NON_LVALUE_EXPR)
3152 fprintf_indent (f, indent,
3153 "res = non_lvalue_loc (loc, res_op0);\n");
3154 else
3156 if (is_a <operator_id *> (opr))
3157 fprintf_indent (f, indent,
3158 "res = fold_build%d_loc (loc, %s, type",
3159 e->ops.length (),
3160 *e->operation == CONVERT_EXPR
3161 ? "NOP_EXPR" : e->operation->id);
3162 else
3163 fprintf_indent (f, indent,
3164 "res = maybe_build_call_expr_loc (loc, "
3165 "%s, type, %d", e->operation->id,
3166 e->ops.length());
3167 for (unsigned j = 0; j < e->ops.length (); ++j)
3168 fprintf (f, ", res_op%d", j);
3169 fprintf (f, ");\n");
3170 if (!is_a <operator_id *> (opr))
3172 fprintf_indent (f, indent, "if (!res)\n");
3173 fprintf_indent (f, indent, " return NULL_TREE;\n");
3178 else if (result->type == operand::OP_CAPTURE
3179 || result->type == operand::OP_C_EXPR)
3182 fprintf_indent (f, indent, "tree res;\n");
3183 result->gen_transform (f, indent, "res", false, 1, "type",
3184 &cinfo, indexes);
3186 else
3187 gcc_unreachable ();
3188 if (!is_predicate)
3190 /* Search for captures not used in the result expression and dependent
3191 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3192 for (int i = 0; i < s->capture_max + 1; ++i)
3194 if (cinfo.info[i].same_as != (unsigned)i)
3195 continue;
3196 if (!cinfo.info[i].force_no_side_effects_p
3197 && !cinfo.info[i].expr_p
3198 && cinfo.info[i].result_use_count == 0)
3200 fprintf_indent (f, indent,
3201 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3203 fprintf_indent (f, indent + 2,
3204 "res = build2_loc (loc, COMPOUND_EXPR, type, "
3205 "fold_ignored_result (captures[%d]), res);\n",
3209 fprintf_indent (f, indent, "return res;\n");
3214 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3215 step of a '(simplify ...)' or '(match ...)'. This handles everything
3216 that is not part of the decision tree (simplify->match). */
3218 void
3219 dt_simplify::gen (FILE *f, int indent, bool gimple)
3221 fprintf_indent (f, indent, "{\n");
3222 indent += 2;
3223 output_line_directive (f,
3224 s->result ? s->result->location : s->match->location);
3225 if (s->capture_max >= 0)
3227 char opname[20];
3228 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3229 s->capture_max + 1, indexes[0]->get_name (opname));
3231 for (int i = 1; i <= s->capture_max; ++i)
3233 if (!indexes[i])
3234 break;
3235 fprintf (f, ", %s", indexes[i]->get_name (opname));
3237 fprintf (f, " };\n");
3240 /* If we have a split-out function for the actual transform, call it. */
3241 if (info && info->fname)
3243 if (gimple)
3245 fprintf_indent (f, indent, "if (%s (res_code, res_ops, seq, "
3246 "valueize, type, captures", info->fname);
3247 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3248 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3249 fprintf (f, "))\n");
3250 fprintf_indent (f, indent, " return true;\n");
3252 else
3254 fprintf_indent (f, indent, "tree res = %s (loc, type",
3255 info->fname);
3256 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3257 fprintf (f, ", op%d", i);
3258 fprintf (f, ", captures");
3259 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3260 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3261 fprintf (f, ");\n");
3262 fprintf_indent (f, indent, "if (res) return res;\n");
3265 else
3267 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3269 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3270 fprintf_indent (f, indent, "enum tree_code %s = %s;\n",
3271 s->for_subst_vec[i].first->id,
3272 s->for_subst_vec[i].second->id);
3273 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3274 fprintf_indent (f, indent, "combined_fn %s = %s;\n",
3275 s->for_subst_vec[i].first->id,
3276 s->for_subst_vec[i].second->id);
3277 else
3278 gcc_unreachable ();
3280 gen_1 (f, indent, gimple, s->result);
3283 indent -= 2;
3284 fprintf_indent (f, indent, "}\n");
3288 /* Hash function for finding equivalent transforms. */
3290 hashval_t
3291 sinfo_hashmap_traits::hash (const key_type &v)
3293 /* Only bother to compare those originating from the same source pattern. */
3294 return v->s->result->location;
3297 /* Compare function for finding equivalent transforms. */
3299 static bool
3300 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3302 if (o1->type != o2->type)
3303 return false;
3305 switch (o1->type)
3307 case operand::OP_IF:
3309 if_expr *if1 = as_a <if_expr *> (o1);
3310 if_expr *if2 = as_a <if_expr *> (o2);
3311 /* ??? Properly compare c-exprs. */
3312 if (if1->cond != if2->cond)
3313 return false;
3314 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3315 return false;
3316 if (if1->falseexpr != if2->falseexpr
3317 || (if1->falseexpr
3318 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3319 return false;
3320 return true;
3322 case operand::OP_WITH:
3324 with_expr *with1 = as_a <with_expr *> (o1);
3325 with_expr *with2 = as_a <with_expr *> (o2);
3326 if (with1->with != with2->with)
3327 return false;
3328 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3330 default:;
3333 /* We've hit a result. Time to compare capture-infos - this is required
3334 in addition to the conservative pointer-equivalency of the result IL. */
3335 capture_info cinfo1 (s1, o1, true);
3336 capture_info cinfo2 (s2, o2, true);
3338 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3339 || cinfo1.info.length () != cinfo2.info.length ())
3340 return false;
3342 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3344 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3345 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3346 || (cinfo1.info[i].force_no_side_effects_p
3347 != cinfo2.info[i].force_no_side_effects_p)
3348 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3349 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3350 /* toplevel_msk is an optimization */
3351 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3352 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3353 /* the pointer back to the capture is for diagnostics only */)
3354 return false;
3357 /* ??? Deep-compare the actual result. */
3358 return o1 == o2;
3361 bool
3362 sinfo_hashmap_traits::equal_keys (const key_type &v,
3363 const key_type &candidate)
3365 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3369 /* Main entry to generate code for matching GIMPLE IL off the decision
3370 tree. */
3372 void
3373 decision_tree::gen (FILE *f, bool gimple)
3375 sinfo_map_t si;
3377 root->analyze (si);
3379 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3380 "a total number of %u nodes\n",
3381 gimple ? "GIMPLE" : "GENERIC",
3382 root->num_leafs, root->max_level, root->total_size);
3384 /* First split out the transform part of equal leafs. */
3385 unsigned rcnt = 0;
3386 unsigned fcnt = 1;
3387 for (sinfo_map_t::iterator iter = si.begin ();
3388 iter != si.end (); ++iter)
3390 sinfo *s = (*iter).second;
3391 /* Do not split out single uses. */
3392 if (s->cnt <= 1)
3393 continue;
3395 rcnt += s->cnt - 1;
3396 if (verbose >= 1)
3398 fprintf (stderr, "found %u uses of", s->cnt);
3399 output_line_directive (stderr, s->s->s->result->location);
3402 /* Generate a split out function with the leaf transform code. */
3403 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3404 fcnt++);
3405 if (gimple)
3406 fprintf (f, "\nstatic bool\n"
3407 "%s (code_helper *res_code, tree *res_ops,\n"
3408 " gimple_seq *seq, tree (*valueize)(tree) "
3409 "ATTRIBUTE_UNUSED,\n"
3410 " tree ARG_UNUSED (type), tree *ARG_UNUSED "
3411 "(captures)\n",
3412 s->fname);
3413 else
3415 fprintf (f, "\nstatic tree\n"
3416 "%s (location_t ARG_UNUSED (loc), tree ARG_UNUSED (type),\n",
3417 (*iter).second->fname);
3418 for (unsigned i = 0;
3419 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3420 fprintf (f, " tree ARG_UNUSED (op%d),", i);
3421 fprintf (f, " tree *captures\n");
3423 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3425 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3426 fprintf (f, ", enum tree_code ARG_UNUSED (%s)",
3427 s->s->s->for_subst_vec[i].first->id);
3428 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3429 fprintf (f, ", combined_fn ARG_UNUSED (%s)",
3430 s->s->s->for_subst_vec[i].first->id);
3433 fprintf (f, ")\n{\n");
3434 s->s->gen_1 (f, 2, gimple, s->s->s->result);
3435 if (gimple)
3436 fprintf (f, " return false;\n");
3437 else
3438 fprintf (f, " return NULL_TREE;\n");
3439 fprintf (f, "}\n");
3441 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3443 for (unsigned n = 1; n <= 3; ++n)
3445 /* First generate split-out functions. */
3446 for (unsigned i = 0; i < root->kids.length (); i++)
3448 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3449 expr *e = static_cast<expr *>(dop->op);
3450 if (e->ops.length () != n
3451 /* Builtin simplifications are somewhat premature on
3452 GENERIC. The following drops patterns with outermost
3453 calls. It's easy to emit overloads for function code
3454 though if necessary. */
3455 || (!gimple
3456 && e->operation->kind != id_base::CODE))
3457 continue;
3459 if (gimple)
3460 fprintf (f, "\nstatic bool\n"
3461 "gimple_simplify_%s (code_helper *res_code, tree *res_ops,\n"
3462 " gimple_seq *seq, tree (*valueize)(tree) "
3463 "ATTRIBUTE_UNUSED,\n"
3464 " code_helper ARG_UNUSED (code), tree "
3465 "ARG_UNUSED (type)\n",
3466 e->operation->id);
3467 else
3468 fprintf (f, "\nstatic tree\n"
3469 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3470 "tree_code ARG_UNUSED (code), tree ARG_UNUSED (type)",
3471 e->operation->id);
3472 for (unsigned i = 0; i < n; ++i)
3473 fprintf (f, ", tree op%d", i);
3474 fprintf (f, ")\n");
3475 fprintf (f, "{\n");
3476 dop->gen_kids (f, 2, gimple);
3477 if (gimple)
3478 fprintf (f, " return false;\n");
3479 else
3480 fprintf (f, " return NULL_TREE;\n");
3481 fprintf (f, "}\n");
3484 /* Then generate the main entry with the outermost switch and
3485 tail-calls to the split-out functions. */
3486 if (gimple)
3487 fprintf (f, "\nstatic bool\n"
3488 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
3489 " gimple_seq *seq, tree (*valueize)(tree),\n"
3490 " code_helper code, tree type");
3491 else
3492 fprintf (f, "\ntree\n"
3493 "generic_simplify (location_t loc, enum tree_code code, "
3494 "tree type ATTRIBUTE_UNUSED");
3495 for (unsigned i = 0; i < n; ++i)
3496 fprintf (f, ", tree op%d", i);
3497 fprintf (f, ")\n");
3498 fprintf (f, "{\n");
3500 if (gimple)
3501 fprintf (f, " switch (code.get_rep())\n"
3502 " {\n");
3503 else
3504 fprintf (f, " switch (code)\n"
3505 " {\n");
3506 for (unsigned i = 0; i < root->kids.length (); i++)
3508 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3509 expr *e = static_cast<expr *>(dop->op);
3510 if (e->ops.length () != n
3511 /* Builtin simplifications are somewhat premature on
3512 GENERIC. The following drops patterns with outermost
3513 calls. It's easy to emit overloads for function code
3514 though if necessary. */
3515 || (!gimple
3516 && e->operation->kind != id_base::CODE))
3517 continue;
3519 if (*e->operation == CONVERT_EXPR
3520 || *e->operation == NOP_EXPR)
3521 fprintf (f, " CASE_CONVERT:\n");
3522 else
3523 fprintf (f, " case %s%s:\n",
3524 is_a <fn_id *> (e->operation) ? "-" : "",
3525 e->operation->id);
3526 if (gimple)
3527 fprintf (f, " return gimple_simplify_%s (res_code, res_ops, "
3528 "seq, valueize, code, type", e->operation->id);
3529 else
3530 fprintf (f, " return generic_simplify_%s (loc, code, type",
3531 e->operation->id);
3532 for (unsigned i = 0; i < n; ++i)
3533 fprintf (f, ", op%d", i);
3534 fprintf (f, ");\n");
3536 fprintf (f, " default:;\n"
3537 " }\n");
3539 if (gimple)
3540 fprintf (f, " return false;\n");
3541 else
3542 fprintf (f, " return NULL_TREE;\n");
3543 fprintf (f, "}\n");
3547 /* Output code to implement the predicate P from the decision tree DT. */
3549 void
3550 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3552 fprintf (f, "\nbool\n"
3553 "%s%s (tree t%s%s)\n"
3554 "{\n", gimple ? "gimple_" : "tree_", p->id,
3555 p->nargs > 0 ? ", tree *res_ops" : "",
3556 gimple ? ", tree (*valueize)(tree)" : "");
3557 /* Conveniently make 'type' available. */
3558 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
3560 if (!gimple)
3561 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3562 dt.root->gen_kids (f, 2, gimple);
3564 fprintf_indent (f, 2, "return false;\n"
3565 "}\n");
3568 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
3570 static void
3571 write_header (FILE *f, const char *head)
3573 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3574 fprintf (f, " a IL pattern matching and simplification description. */\n");
3576 /* Include the header instead of writing it awkwardly quoted here. */
3577 fprintf (f, "\n#include \"%s\"\n", head);
3582 /* AST parsing. */
3584 class parser
3586 public:
3587 parser (cpp_reader *);
3589 private:
3590 const cpp_token *next ();
3591 const cpp_token *peek (unsigned = 1);
3592 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3593 const cpp_token *expect (enum cpp_ttype);
3594 const cpp_token *eat_token (enum cpp_ttype);
3595 const char *get_string ();
3596 const char *get_ident ();
3597 const cpp_token *eat_ident (const char *);
3598 const char *get_number ();
3600 id_base *parse_operation ();
3601 operand *parse_capture (operand *, bool);
3602 operand *parse_expr ();
3603 c_expr *parse_c_expr (cpp_ttype);
3604 operand *parse_op ();
3606 void record_operlist (source_location, user_id *);
3608 void parse_pattern ();
3609 operand *parse_result (operand *, predicate_id *);
3610 void push_simplify (simplify::simplify_kind,
3611 vec<simplify *>&, operand *, operand *);
3612 void parse_simplify (simplify::simplify_kind,
3613 vec<simplify *>&, predicate_id *, operand *);
3614 void parse_for (source_location);
3615 void parse_if (source_location);
3616 void parse_predicates (source_location);
3617 void parse_operator_list (source_location);
3619 cpp_reader *r;
3620 vec<c_expr *> active_ifs;
3621 vec<vec<user_id *> > active_fors;
3622 hash_set<user_id *> *oper_lists_set;
3623 vec<user_id *> oper_lists;
3625 cid_map_t *capture_ids;
3627 public:
3628 vec<simplify *> simplifiers;
3629 vec<predicate_id *> user_predicates;
3630 bool parsing_match_operand;
3633 /* Lexing helpers. */
3635 /* Read the next non-whitespace token from R. */
3637 const cpp_token *
3638 parser::next ()
3640 const cpp_token *token;
3643 token = cpp_get_token (r);
3645 while (token->type == CPP_PADDING
3646 && token->type != CPP_EOF);
3647 return token;
3650 /* Peek at the next non-whitespace token from R. */
3652 const cpp_token *
3653 parser::peek (unsigned num)
3655 const cpp_token *token;
3656 unsigned i = 0;
3659 token = cpp_peek_token (r, i++);
3661 while ((token->type == CPP_PADDING
3662 && token->type != CPP_EOF)
3663 || (--num > 0));
3664 /* If we peek at EOF this is a fatal error as it leaves the
3665 cpp_reader in unusable state. Assume we really wanted a
3666 token and thus this EOF is unexpected. */
3667 if (token->type == CPP_EOF)
3668 fatal_at (token, "unexpected end of file");
3669 return token;
3672 /* Peek at the next identifier token (or return NULL if the next
3673 token is not an identifier or equal to ID if supplied). */
3675 const cpp_token *
3676 parser::peek_ident (const char *id, unsigned num)
3678 const cpp_token *token = peek (num);
3679 if (token->type != CPP_NAME)
3680 return 0;
3682 if (id == 0)
3683 return token;
3685 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3686 if (strcmp (id, t) == 0)
3687 return token;
3689 return 0;
3692 /* Read the next token from R and assert it is of type TK. */
3694 const cpp_token *
3695 parser::expect (enum cpp_ttype tk)
3697 const cpp_token *token = next ();
3698 if (token->type != tk)
3699 fatal_at (token, "expected %s, got %s",
3700 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3702 return token;
3705 /* Consume the next token from R and assert it is of type TK. */
3707 const cpp_token *
3708 parser::eat_token (enum cpp_ttype tk)
3710 return expect (tk);
3713 /* Read the next token from R and assert it is of type CPP_STRING and
3714 return its value. */
3716 const char *
3717 parser::get_string ()
3719 const cpp_token *token = expect (CPP_STRING);
3720 return (const char *)token->val.str.text;
3723 /* Read the next token from R and assert it is of type CPP_NAME and
3724 return its value. */
3726 const char *
3727 parser::get_ident ()
3729 const cpp_token *token = expect (CPP_NAME);
3730 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3733 /* Eat an identifier token with value S from R. */
3735 const cpp_token *
3736 parser::eat_ident (const char *s)
3738 const cpp_token *token = peek ();
3739 const char *t = get_ident ();
3740 if (strcmp (s, t) != 0)
3741 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3742 return token;
3745 /* Read the next token from R and assert it is of type CPP_NUMBER and
3746 return its value. */
3748 const char *
3749 parser::get_number ()
3751 const cpp_token *token = expect (CPP_NUMBER);
3752 return (const char *)token->val.str.text;
3756 /* Record an operator-list use for transparent for handling. */
3758 void
3759 parser::record_operlist (source_location loc, user_id *p)
3761 if (!oper_lists_set->add (p))
3763 if (!oper_lists.is_empty ()
3764 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3765 fatal_at (loc, "User-defined operator list does not have the "
3766 "same number of entries as others used in the pattern");
3767 oper_lists.safe_push (p);
3771 /* Parse the operator ID, special-casing convert?, convert1? and
3772 convert2? */
3774 id_base *
3775 parser::parse_operation ()
3777 const cpp_token *id_tok = peek ();
3778 const char *id = get_ident ();
3779 const cpp_token *token = peek ();
3780 if (strcmp (id, "convert0") == 0)
3781 fatal_at (id_tok, "use 'convert?' here");
3782 else if (strcmp (id, "view_convert0") == 0)
3783 fatal_at (id_tok, "use 'view_convert?' here");
3784 if (token->type == CPP_QUERY
3785 && !(token->flags & PREV_WHITE))
3787 if (strcmp (id, "convert") == 0)
3788 id = "convert0";
3789 else if (strcmp (id, "convert1") == 0)
3791 else if (strcmp (id, "convert2") == 0)
3793 else if (strcmp (id, "view_convert") == 0)
3794 id = "view_convert0";
3795 else if (strcmp (id, "view_convert1") == 0)
3797 else if (strcmp (id, "view_convert2") == 0)
3799 else
3800 fatal_at (id_tok, "non-convert operator conditionalized");
3802 if (!parsing_match_operand)
3803 fatal_at (id_tok, "conditional convert can only be used in "
3804 "match expression");
3805 eat_token (CPP_QUERY);
3807 else if (strcmp (id, "convert1") == 0
3808 || strcmp (id, "convert2") == 0
3809 || strcmp (id, "view_convert1") == 0
3810 || strcmp (id, "view_convert2") == 0)
3811 fatal_at (id_tok, "expected '?' after conditional operator");
3812 id_base *op = get_operator (id);
3813 if (!op)
3814 fatal_at (id_tok, "unknown operator %s", id);
3816 user_id *p = dyn_cast<user_id *> (op);
3817 if (p && p->is_oper_list)
3819 if (active_fors.length() == 0)
3820 record_operlist (id_tok->src_loc, p);
3821 else
3822 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
3824 return op;
3827 /* Parse a capture.
3828 capture = '@'<number> */
3830 struct operand *
3831 parser::parse_capture (operand *op, bool require_existing)
3833 source_location src_loc = eat_token (CPP_ATSIGN)->src_loc;
3834 const cpp_token *token = peek ();
3835 const char *id = NULL;
3836 if (token->type == CPP_NUMBER)
3837 id = get_number ();
3838 else if (token->type == CPP_NAME)
3839 id = get_ident ();
3840 else
3841 fatal_at (token, "expected number or identifier");
3842 unsigned next_id = capture_ids->elements ();
3843 bool existed;
3844 unsigned &num = capture_ids->get_or_insert (id, &existed);
3845 if (!existed)
3847 if (require_existing)
3848 fatal_at (src_loc, "unknown capture id");
3849 num = next_id;
3851 return new capture (src_loc, num, op);
3854 /* Parse an expression
3855 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
3857 struct operand *
3858 parser::parse_expr ()
3860 const cpp_token *token = peek ();
3861 expr *e = new expr (parse_operation (), token->src_loc);
3862 token = peek ();
3863 operand *op;
3864 bool is_commutative = false;
3865 bool force_capture = false;
3866 const char *expr_type = NULL;
3868 if (token->type == CPP_COLON
3869 && !(token->flags & PREV_WHITE))
3871 eat_token (CPP_COLON);
3872 token = peek ();
3873 if (token->type == CPP_NAME
3874 && !(token->flags & PREV_WHITE))
3876 const char *s = get_ident ();
3877 if (!parsing_match_operand)
3878 expr_type = s;
3879 else
3881 const char *sp = s;
3882 while (*sp)
3884 if (*sp == 'c')
3885 is_commutative = true;
3886 else if (*sp == 's')
3888 e->force_single_use = true;
3889 force_capture = true;
3891 else
3892 fatal_at (token, "flag %c not recognized", *sp);
3893 sp++;
3896 token = peek ();
3898 else
3899 fatal_at (token, "expected flag or type specifying identifier");
3902 if (token->type == CPP_ATSIGN
3903 && !(token->flags & PREV_WHITE))
3904 op = parse_capture (e, false);
3905 else if (force_capture)
3907 unsigned num = capture_ids->elements ();
3908 char id[8];
3909 bool existed;
3910 sprintf (id, "__%u", num);
3911 capture_ids->get_or_insert (xstrdup (id), &existed);
3912 if (existed)
3913 fatal_at (token, "reserved capture id '%s' already used", id);
3914 op = new capture (token->src_loc, num, e);
3916 else
3917 op = e;
3920 const cpp_token *token = peek ();
3921 if (token->type == CPP_CLOSE_PAREN)
3923 if (e->operation->nargs != -1
3924 && e->operation->nargs != (int) e->ops.length ())
3925 fatal_at (token, "'%s' expects %u operands, not %u",
3926 e->operation->id, e->operation->nargs, e->ops.length ());
3927 if (is_commutative)
3929 if (e->ops.length () == 2)
3930 e->is_commutative = true;
3931 else
3932 fatal_at (token, "only binary operators or function with "
3933 "two arguments can be marked commutative");
3935 e->expr_type = expr_type;
3936 return op;
3938 else if (!(token->flags & PREV_WHITE))
3939 fatal_at (token, "expected expression operand");
3941 e->append_op (parse_op ());
3943 while (1);
3946 /* Lex native C code delimited by START recording the preprocessing tokens
3947 for later processing.
3948 c_expr = ('{'|'(') <pp token>... ('}'|')') */
3950 c_expr *
3951 parser::parse_c_expr (cpp_ttype start)
3953 const cpp_token *token;
3954 cpp_ttype end;
3955 unsigned opencnt;
3956 vec<cpp_token> code = vNULL;
3957 unsigned nr_stmts = 0;
3958 source_location loc = eat_token (start)->src_loc;
3959 if (start == CPP_OPEN_PAREN)
3960 end = CPP_CLOSE_PAREN;
3961 else if (start == CPP_OPEN_BRACE)
3962 end = CPP_CLOSE_BRACE;
3963 else
3964 gcc_unreachable ();
3965 opencnt = 1;
3968 token = next ();
3970 /* Count brace pairs to find the end of the expr to match. */
3971 if (token->type == start)
3972 opencnt++;
3973 else if (token->type == end
3974 && --opencnt == 0)
3975 break;
3977 /* This is a lame way of counting the number of statements. */
3978 if (token->type == CPP_SEMICOLON)
3979 nr_stmts++;
3981 /* If this is possibly a user-defined identifier mark it used. */
3982 if (token->type == CPP_NAME)
3984 id_base *idb = get_operator ((const char *)CPP_HASHNODE
3985 (token->val.node.node)->ident.str);
3986 user_id *p;
3987 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
3988 record_operlist (token->src_loc, p);
3991 /* Record the token. */
3992 code.safe_push (*token);
3994 while (1);
3995 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
3998 /* Parse an operand which is either an expression, a predicate or
3999 a standalone capture.
4000 op = predicate | expr | c_expr | capture */
4002 struct operand *
4003 parser::parse_op ()
4005 const cpp_token *token = peek ();
4006 struct operand *op = NULL;
4007 if (token->type == CPP_OPEN_PAREN)
4009 eat_token (CPP_OPEN_PAREN);
4010 op = parse_expr ();
4011 eat_token (CPP_CLOSE_PAREN);
4013 else if (token->type == CPP_OPEN_BRACE)
4015 op = parse_c_expr (CPP_OPEN_BRACE);
4017 else
4019 /* Remaining ops are either empty or predicates */
4020 if (token->type == CPP_NAME)
4022 const char *id = get_ident ();
4023 id_base *opr = get_operator (id);
4024 if (!opr)
4025 fatal_at (token, "expected predicate name");
4026 if (operator_id *code = dyn_cast <operator_id *> (opr))
4028 if (code->nargs != 0)
4029 fatal_at (token, "using an operator with operands as predicate");
4030 /* Parse the zero-operand operator "predicates" as
4031 expression. */
4032 op = new expr (opr, token->src_loc);
4034 else if (user_id *code = dyn_cast <user_id *> (opr))
4036 if (code->nargs != 0)
4037 fatal_at (token, "using an operator with operands as predicate");
4038 /* Parse the zero-operand operator "predicates" as
4039 expression. */
4040 op = new expr (opr, token->src_loc);
4042 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4043 op = new predicate (p, token->src_loc);
4044 else
4045 fatal_at (token, "using an unsupported operator as predicate");
4046 if (!parsing_match_operand)
4047 fatal_at (token, "predicates are only allowed in match expression");
4048 token = peek ();
4049 if (token->flags & PREV_WHITE)
4050 return op;
4052 else if (token->type != CPP_COLON
4053 && token->type != CPP_ATSIGN)
4054 fatal_at (token, "expected expression or predicate");
4055 /* optionally followed by a capture and a predicate. */
4056 if (token->type == CPP_COLON)
4057 fatal_at (token, "not implemented: predicate on leaf operand");
4058 if (token->type == CPP_ATSIGN)
4059 op = parse_capture (op, !parsing_match_operand);
4062 return op;
4065 /* Create a new simplify from the current parsing state and MATCH,
4066 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4068 void
4069 parser::push_simplify (simplify::simplify_kind kind,
4070 vec<simplify *>& simplifiers,
4071 operand *match, operand *result)
4073 /* Build and push a temporary for operator list uses in expressions. */
4074 if (!oper_lists.is_empty ())
4075 active_fors.safe_push (oper_lists);
4077 simplifiers.safe_push
4078 (new simplify (kind, match, result,
4079 active_fors.copy (), capture_ids));
4081 if (!oper_lists.is_empty ())
4082 active_fors.pop ();
4085 /* Parse
4086 <result-op> = <op> | <if> | <with>
4087 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4088 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4089 and return it. */
4091 operand *
4092 parser::parse_result (operand *result, predicate_id *matcher)
4094 const cpp_token *token = peek ();
4095 if (token->type != CPP_OPEN_PAREN)
4096 return parse_op ();
4098 eat_token (CPP_OPEN_PAREN);
4099 if (peek_ident ("if"))
4101 eat_ident ("if");
4102 if_expr *ife = new if_expr (token->src_loc);
4103 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4104 if (peek ()->type == CPP_OPEN_PAREN)
4106 ife->trueexpr = parse_result (result, matcher);
4107 if (peek ()->type == CPP_OPEN_PAREN)
4108 ife->falseexpr = parse_result (result, matcher);
4109 else if (peek ()->type != CPP_CLOSE_PAREN)
4110 ife->falseexpr = parse_op ();
4112 else if (peek ()->type != CPP_CLOSE_PAREN)
4114 ife->trueexpr = parse_op ();
4115 if (peek ()->type == CPP_OPEN_PAREN)
4116 ife->falseexpr = parse_result (result, matcher);
4117 else if (peek ()->type != CPP_CLOSE_PAREN)
4118 ife->falseexpr = parse_op ();
4120 /* If this if is immediately closed then it contains a
4121 manual matcher or is part of a predicate definition. */
4122 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4124 if (!matcher)
4125 fatal_at (peek (), "manual transform not implemented");
4126 ife->trueexpr = result;
4128 eat_token (CPP_CLOSE_PAREN);
4129 return ife;
4131 else if (peek_ident ("with"))
4133 eat_ident ("with");
4134 with_expr *withe = new with_expr (token->src_loc);
4135 /* Parse (with c-expr expr) as (if-with (true) expr). */
4136 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4137 withe->with->nr_stmts = 0;
4138 withe->subexpr = parse_result (result, matcher);
4139 eat_token (CPP_CLOSE_PAREN);
4140 return withe;
4142 else if (peek_ident ("switch"))
4144 token = eat_ident ("switch");
4145 source_location ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4146 eat_ident ("if");
4147 if_expr *ife = new if_expr (ifloc);
4148 operand *res = ife;
4149 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4150 if (peek ()->type == CPP_OPEN_PAREN)
4151 ife->trueexpr = parse_result (result, matcher);
4152 else
4153 ife->trueexpr = parse_op ();
4154 eat_token (CPP_CLOSE_PAREN);
4155 if (peek ()->type != CPP_OPEN_PAREN
4156 || !peek_ident ("if", 2))
4157 fatal_at (token, "switch can be implemented with a single if");
4158 while (peek ()->type != CPP_CLOSE_PAREN)
4160 if (peek ()->type == CPP_OPEN_PAREN)
4162 if (peek_ident ("if", 2))
4164 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4165 eat_ident ("if");
4166 ife->falseexpr = new if_expr (ifloc);
4167 ife = as_a <if_expr *> (ife->falseexpr);
4168 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4169 if (peek ()->type == CPP_OPEN_PAREN)
4170 ife->trueexpr = parse_result (result, matcher);
4171 else
4172 ife->trueexpr = parse_op ();
4173 eat_token (CPP_CLOSE_PAREN);
4175 else
4177 /* switch default clause */
4178 ife->falseexpr = parse_result (result, matcher);
4179 eat_token (CPP_CLOSE_PAREN);
4180 return res;
4183 else
4185 /* switch default clause */
4186 ife->falseexpr = parse_op ();
4187 eat_token (CPP_CLOSE_PAREN);
4188 return res;
4191 eat_token (CPP_CLOSE_PAREN);
4192 return res;
4194 else
4196 operand *op = result;
4197 if (!matcher)
4198 op = parse_expr ();
4199 eat_token (CPP_CLOSE_PAREN);
4200 return op;
4204 /* Parse
4205 simplify = 'simplify' <expr> <result-op>
4207 match = 'match' <ident> <expr> [<result-op>]
4208 and fill SIMPLIFIERS with the results. */
4210 void
4211 parser::parse_simplify (simplify::simplify_kind kind,
4212 vec<simplify *>& simplifiers, predicate_id *matcher,
4213 operand *result)
4215 /* Reset the capture map. */
4216 if (!capture_ids)
4217 capture_ids = new cid_map_t;
4218 /* Reset oper_lists and set. */
4219 hash_set <user_id *> olist;
4220 oper_lists_set = &olist;
4221 oper_lists = vNULL;
4223 const cpp_token *loc = peek ();
4224 parsing_match_operand = true;
4225 struct operand *match = parse_op ();
4226 parsing_match_operand = false;
4227 if (match->type == operand::OP_CAPTURE && !matcher)
4228 fatal_at (loc, "outermost expression cannot be captured");
4229 if (match->type == operand::OP_EXPR
4230 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4231 fatal_at (loc, "outermost expression cannot be a predicate");
4233 /* Splice active_ifs onto result and continue parsing the
4234 "then" expr. */
4235 if_expr *active_if = NULL;
4236 for (int i = active_ifs.length (); i > 0; --i)
4238 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4239 ifc->cond = active_ifs[i-1];
4240 ifc->trueexpr = active_if;
4241 active_if = ifc;
4243 if_expr *outermost_if = active_if;
4244 while (active_if && active_if->trueexpr)
4245 active_if = as_a <if_expr *> (active_if->trueexpr);
4247 const cpp_token *token = peek ();
4249 /* If this if is immediately closed then it is part of a predicate
4250 definition. Push it. */
4251 if (token->type == CPP_CLOSE_PAREN)
4253 if (!matcher)
4254 fatal_at (token, "expected transform expression");
4255 if (active_if)
4257 active_if->trueexpr = result;
4258 result = outermost_if;
4260 push_simplify (kind, simplifiers, match, result);
4261 return;
4264 operand *tem = parse_result (result, matcher);
4265 if (active_if)
4267 active_if->trueexpr = tem;
4268 result = outermost_if;
4270 else
4271 result = tem;
4273 push_simplify (kind, simplifiers, match, result);
4276 /* Parsing of the outer control structures. */
4278 /* Parse a for expression
4279 for = '(' 'for' <subst>... <pattern> ')'
4280 subst = <ident> '(' <ident>... ')' */
4282 void
4283 parser::parse_for (source_location)
4285 auto_vec<const cpp_token *> user_id_tokens;
4286 vec<user_id *> user_ids = vNULL;
4287 const cpp_token *token;
4288 unsigned min_n_opers = 0, max_n_opers = 0;
4290 while (1)
4292 token = peek ();
4293 if (token->type != CPP_NAME)
4294 break;
4296 /* Insert the user defined operators into the operator hash. */
4297 const char *id = get_ident ();
4298 if (get_operator (id, true) != NULL)
4299 fatal_at (token, "operator already defined");
4300 user_id *op = new user_id (id);
4301 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4302 *slot = op;
4303 user_ids.safe_push (op);
4304 user_id_tokens.safe_push (token);
4306 eat_token (CPP_OPEN_PAREN);
4308 int arity = -1;
4309 while ((token = peek_ident ()) != 0)
4311 const char *oper = get_ident ();
4312 id_base *idb = get_operator (oper, true);
4313 if (idb == NULL)
4314 fatal_at (token, "no such operator '%s'", oper);
4315 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
4316 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
4317 || *idb == VIEW_CONVERT2)
4318 fatal_at (token, "conditional operators cannot be used inside for");
4320 if (arity == -1)
4321 arity = idb->nargs;
4322 else if (idb->nargs == -1)
4324 else if (idb->nargs != arity)
4325 fatal_at (token, "operator '%s' with arity %d does not match "
4326 "others with arity %d", oper, idb->nargs, arity);
4328 user_id *p = dyn_cast<user_id *> (idb);
4329 if (p)
4331 if (p->is_oper_list)
4332 op->substitutes.safe_splice (p->substitutes);
4333 else
4334 fatal_at (token, "iterator cannot be used as operator-list");
4336 else
4337 op->substitutes.safe_push (idb);
4339 op->nargs = arity;
4340 token = expect (CPP_CLOSE_PAREN);
4342 unsigned nsubstitutes = op->substitutes.length ();
4343 if (nsubstitutes == 0)
4344 fatal_at (token, "A user-defined operator must have at least "
4345 "one substitution");
4346 if (max_n_opers == 0)
4348 min_n_opers = nsubstitutes;
4349 max_n_opers = nsubstitutes;
4351 else
4353 if (nsubstitutes % min_n_opers != 0
4354 && min_n_opers % nsubstitutes != 0)
4355 fatal_at (token, "All user-defined identifiers must have a "
4356 "multiple number of operator substitutions of the "
4357 "smallest number of substitutions");
4358 if (nsubstitutes < min_n_opers)
4359 min_n_opers = nsubstitutes;
4360 else if (nsubstitutes > max_n_opers)
4361 max_n_opers = nsubstitutes;
4365 unsigned n_ids = user_ids.length ();
4366 if (n_ids == 0)
4367 fatal_at (token, "for requires at least one user-defined identifier");
4369 token = peek ();
4370 if (token->type == CPP_CLOSE_PAREN)
4371 fatal_at (token, "no pattern defined in for");
4373 active_fors.safe_push (user_ids);
4374 while (1)
4376 token = peek ();
4377 if (token->type == CPP_CLOSE_PAREN)
4378 break;
4379 parse_pattern ();
4381 active_fors.pop ();
4383 /* Remove user-defined operators from the hash again. */
4384 for (unsigned i = 0; i < user_ids.length (); ++i)
4386 if (!user_ids[i]->used)
4387 warning_at (user_id_tokens[i],
4388 "operator %s defined but not used", user_ids[i]->id);
4389 operators->remove_elt (user_ids[i]);
4393 /* Parse an identifier associated with a list of operators.
4394 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
4396 void
4397 parser::parse_operator_list (source_location)
4399 const cpp_token *token = peek ();
4400 const char *id = get_ident ();
4402 if (get_operator (id, true) != 0)
4403 fatal_at (token, "operator %s already defined", id);
4405 user_id *op = new user_id (id, true);
4406 int arity = -1;
4408 while ((token = peek_ident ()) != 0)
4410 token = peek ();
4411 const char *oper = get_ident ();
4412 id_base *idb = get_operator (oper, true);
4414 if (idb == 0)
4415 fatal_at (token, "no such operator '%s'", oper);
4417 if (arity == -1)
4418 arity = idb->nargs;
4419 else if (idb->nargs == -1)
4421 else if (arity != idb->nargs)
4422 fatal_at (token, "operator '%s' with arity %d does not match "
4423 "others with arity %d", oper, idb->nargs, arity);
4425 /* We allow composition of multiple operator lists. */
4426 if (user_id *p = dyn_cast<user_id *> (idb))
4427 op->substitutes.safe_splice (p->substitutes);
4428 else
4429 op->substitutes.safe_push (idb);
4432 // Check that there is no junk after id-list
4433 token = peek();
4434 if (token->type != CPP_CLOSE_PAREN)
4435 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
4437 if (op->substitutes.length () == 0)
4438 fatal_at (token, "operator-list cannot be empty");
4440 op->nargs = arity;
4441 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4442 *slot = op;
4445 /* Parse an outer if expression.
4446 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
4448 void
4449 parser::parse_if (source_location)
4451 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4453 const cpp_token *token = peek ();
4454 if (token->type == CPP_CLOSE_PAREN)
4455 fatal_at (token, "no pattern defined in if");
4457 active_ifs.safe_push (ifexpr);
4458 while (1)
4460 const cpp_token *token = peek ();
4461 if (token->type == CPP_CLOSE_PAREN)
4462 break;
4464 parse_pattern ();
4466 active_ifs.pop ();
4469 /* Parse a list of predefined predicate identifiers.
4470 preds = '(' 'define_predicates' <ident>... ')' */
4472 void
4473 parser::parse_predicates (source_location)
4477 const cpp_token *token = peek ();
4478 if (token->type != CPP_NAME)
4479 break;
4481 add_predicate (get_ident ());
4483 while (1);
4486 /* Parse outer control structures.
4487 pattern = <preds>|<for>|<if>|<simplify>|<match> */
4489 void
4490 parser::parse_pattern ()
4492 /* All clauses start with '('. */
4493 eat_token (CPP_OPEN_PAREN);
4494 const cpp_token *token = peek ();
4495 const char *id = get_ident ();
4496 if (strcmp (id, "simplify") == 0)
4498 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4499 capture_ids = NULL;
4501 else if (strcmp (id, "match") == 0)
4503 bool with_args = false;
4504 source_location e_loc = peek ()->src_loc;
4505 if (peek ()->type == CPP_OPEN_PAREN)
4507 eat_token (CPP_OPEN_PAREN);
4508 with_args = true;
4510 const char *name = get_ident ();
4511 id_base *id = get_operator (name);
4512 predicate_id *p;
4513 if (!id)
4515 p = add_predicate (name);
4516 user_predicates.safe_push (p);
4518 else if ((p = dyn_cast <predicate_id *> (id)))
4520 else
4521 fatal_at (token, "cannot add a match to a non-predicate ID");
4522 /* Parse (match <id> <arg>... (match-expr)) here. */
4523 expr *e = NULL;
4524 if (with_args)
4526 capture_ids = new cid_map_t;
4527 e = new expr (p, e_loc);
4528 while (peek ()->type == CPP_ATSIGN)
4529 e->append_op (parse_capture (NULL, false));
4530 eat_token (CPP_CLOSE_PAREN);
4532 if (p->nargs != -1
4533 && ((e && e->ops.length () != (unsigned)p->nargs)
4534 || (!e && p->nargs != 0)))
4535 fatal_at (token, "non-matching number of match operands");
4536 p->nargs = e ? e->ops.length () : 0;
4537 parse_simplify (simplify::MATCH, p->matchers, p, e);
4538 capture_ids = NULL;
4540 else if (strcmp (id, "for") == 0)
4541 parse_for (token->src_loc);
4542 else if (strcmp (id, "if") == 0)
4543 parse_if (token->src_loc);
4544 else if (strcmp (id, "define_predicates") == 0)
4546 if (active_ifs.length () > 0
4547 || active_fors.length () > 0)
4548 fatal_at (token, "define_predicates inside if or for is not supported");
4549 parse_predicates (token->src_loc);
4551 else if (strcmp (id, "define_operator_list") == 0)
4553 if (active_ifs.length () > 0
4554 || active_fors.length () > 0)
4555 fatal_at (token, "operator-list inside if or for is not supported");
4556 parse_operator_list (token->src_loc);
4558 else
4559 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4560 active_ifs.length () == 0 && active_fors.length () == 0
4561 ? "'define_predicates', " : "");
4563 eat_token (CPP_CLOSE_PAREN);
4566 /* Main entry of the parser. Repeatedly parse outer control structures. */
4568 parser::parser (cpp_reader *r_)
4570 r = r_;
4571 active_ifs = vNULL;
4572 active_fors = vNULL;
4573 simplifiers = vNULL;
4574 oper_lists_set = NULL;
4575 oper_lists = vNULL;
4576 capture_ids = NULL;
4577 user_predicates = vNULL;
4578 parsing_match_operand = false;
4580 const cpp_token *token = next ();
4581 while (token->type != CPP_EOF)
4583 _cpp_backup_tokens (r, 1);
4584 parse_pattern ();
4585 token = next ();
4590 /* Helper for the linemap code. */
4592 static size_t
4593 round_alloc_size (size_t s)
4595 return s;
4599 /* The genmatch generator progam. It reads from a pattern description
4600 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
4603 main (int argc, char **argv)
4605 cpp_reader *r;
4607 progname = "genmatch";
4609 if (argc < 2)
4610 return 1;
4612 bool gimple = true;
4613 char *input = argv[argc-1];
4614 for (int i = 1; i < argc - 1; ++i)
4616 if (strcmp (argv[i], "--gimple") == 0)
4617 gimple = true;
4618 else if (strcmp (argv[i], "--generic") == 0)
4619 gimple = false;
4620 else if (strcmp (argv[i], "-v") == 0)
4621 verbose = 1;
4622 else if (strcmp (argv[i], "-vv") == 0)
4623 verbose = 2;
4624 else
4626 fprintf (stderr, "Usage: genmatch "
4627 "[--gimple] [--generic] [-v[v]] input\n");
4628 return 1;
4632 line_table = XCNEW (struct line_maps);
4633 linemap_init (line_table, 0);
4634 line_table->reallocator = xrealloc;
4635 line_table->round_alloc_size = round_alloc_size;
4637 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4638 cpp_callbacks *cb = cpp_get_callbacks (r);
4639 cb->error = error_cb;
4641 /* Add the build directory to the #include "" search path. */
4642 cpp_dir *dir = XCNEW (cpp_dir);
4643 dir->name = getpwd ();
4644 if (!dir->name)
4645 dir->name = ASTRDUP (".");
4646 cpp_set_include_chains (r, dir, NULL, false);
4648 if (!cpp_read_main_file (r, input))
4649 return 1;
4650 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4651 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4653 null_id = new id_base (id_base::NULL_ID, "null");
4655 /* Pre-seed operators. */
4656 operators = new hash_table<id_base> (1024);
4657 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4658 add_operator (SYM, # SYM, # TYPE, NARGS);
4659 #define END_OF_BASE_TREE_CODES
4660 #include "tree.def"
4661 add_operator (CONVERT0, "convert0", "tcc_unary", 1);
4662 add_operator (CONVERT1, "convert1", "tcc_unary", 1);
4663 add_operator (CONVERT2, "convert2", "tcc_unary", 1);
4664 add_operator (VIEW_CONVERT0, "view_convert0", "tcc_unary", 1);
4665 add_operator (VIEW_CONVERT1, "view_convert1", "tcc_unary", 1);
4666 add_operator (VIEW_CONVERT2, "view_convert2", "tcc_unary", 1);
4667 #undef END_OF_BASE_TREE_CODES
4668 #undef DEFTREECODE
4670 /* Pre-seed builtin functions.
4671 ??? Cannot use N (name) as that is targetm.emultls.get_address
4672 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4673 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4674 add_function (ENUM, "CFN_" # ENUM);
4675 #include "builtins.def"
4677 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
4678 add_function (IFN_##CODE, "CFN_" #CODE);
4679 #include "internal-fn.def"
4681 /* Parse ahead! */
4682 parser p (r);
4684 if (gimple)
4685 write_header (stdout, "gimple-match-head.c");
4686 else
4687 write_header (stdout, "generic-match-head.c");
4689 /* Go over all predicates defined with patterns and perform
4690 lowering and code generation. */
4691 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
4693 predicate_id *pred = p.user_predicates[i];
4694 lower (pred->matchers, gimple);
4696 if (verbose == 2)
4697 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4698 print_matches (pred->matchers[i]);
4700 decision_tree dt;
4701 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4702 dt.insert (pred->matchers[i], i);
4704 if (verbose == 2)
4705 dt.print (stderr);
4707 write_predicate (stdout, pred, dt, gimple);
4710 /* Lower the main simplifiers and generate code for them. */
4711 lower (p.simplifiers, gimple);
4713 if (verbose == 2)
4714 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4715 print_matches (p.simplifiers[i]);
4717 decision_tree dt;
4718 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
4719 dt.insert (p.simplifiers[i], i);
4721 if (verbose == 2)
4722 dt.print (stderr);
4724 dt.gen (stdout, gimple);
4726 /* Finalize. */
4727 cpp_finish (r, NULL);
4728 cpp_destroy (r);
4730 delete operators;
4732 return 0;