c++: only cache constexpr calls that are constant exprs
[official-gcc.git] / gcc / genmatch.cc
blob2302f2a7ff09954244ae1e83d08a9e1a6bb00fa0
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2023 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 "system.h"
26 #include "coretypes.h"
27 #include <cpplib.h>
28 #include "errors.h"
29 #include "hash-table.h"
30 #include "hash-set.h"
31 #include "is-a.h"
34 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
35 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
36 size_t, size_t MEM_STAT_DECL)
38 return NULL;
40 void ggc_free (void *)
45 /* Global state. */
47 /* Verboseness. 0 is quiet, 1 adds some warnings, 2 is for debugging. */
48 unsigned verbose;
51 /* libccp helpers. */
53 static class line_maps *line_table;
55 /* The rich_location class within libcpp requires a way to expand
56 location_t instances, and relies on the client code
57 providing a symbol named
58 linemap_client_expand_location_to_spelling_point
59 to do this.
61 This is the implementation for genmatch. */
63 expanded_location
64 linemap_client_expand_location_to_spelling_point (location_t loc,
65 enum location_aspect)
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 diagnostic_cb (cpp_reader *, enum cpp_diagnostic_level errtype,
77 enum cpp_warning_reason, rich_location *richloc,
78 const char *msg, va_list *ap)
80 const line_map_ordinary *map;
81 location_t location = richloc->get_loc ();
82 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
83 expanded_location loc = linemap_expand_location (line_table, map, location);
84 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
85 (errtype == CPP_DL_WARNING) ? "warning" : "error");
86 vfprintf (stderr, msg, *ap);
87 fprintf (stderr, "\n");
88 FILE *f = fopen (loc.file, "r");
89 if (f)
91 char buf[128];
92 while (loc.line > 0)
94 if (!fgets (buf, 128, f))
95 goto notfound;
96 if (buf[strlen (buf) - 1] != '\n')
98 if (loc.line > 1)
99 loc.line++;
101 loc.line--;
103 fprintf (stderr, "%s", buf);
104 for (int i = 0; i < loc.column - 1; ++i)
105 fputc (' ', stderr);
106 fputc ('^', stderr);
107 fputc ('\n', stderr);
108 notfound:
109 fclose (f);
112 if (errtype == CPP_DL_FATAL)
113 exit (1);
114 return false;
117 static void
118 #if GCC_VERSION >= 4001
119 __attribute__((format (printf, 2, 3)))
120 #endif
121 fatal_at (const cpp_token *tk, const char *msg, ...)
123 rich_location richloc (line_table, tk->src_loc);
124 va_list ap;
125 va_start (ap, msg);
126 diagnostic_cb (NULL, CPP_DL_FATAL, CPP_W_NONE, &richloc, msg, &ap);
127 va_end (ap);
130 static void
131 #if GCC_VERSION >= 4001
132 __attribute__((format (printf, 2, 3)))
133 #endif
134 fatal_at (location_t loc, const char *msg, ...)
136 rich_location richloc (line_table, loc);
137 va_list ap;
138 va_start (ap, msg);
139 diagnostic_cb (NULL, CPP_DL_FATAL, CPP_W_NONE, &richloc, msg, &ap);
140 va_end (ap);
143 static void
144 #if GCC_VERSION >= 4001
145 __attribute__((format (printf, 2, 3)))
146 #endif
147 warning_at (const cpp_token *tk, const char *msg, ...)
149 rich_location richloc (line_table, tk->src_loc);
150 va_list ap;
151 va_start (ap, msg);
152 diagnostic_cb (NULL, CPP_DL_WARNING, CPP_W_NONE, &richloc, msg, &ap);
153 va_end (ap);
156 static void
157 #if GCC_VERSION >= 4001
158 __attribute__((format (printf, 2, 3)))
159 #endif
160 warning_at (location_t loc, const char *msg, ...)
162 rich_location richloc (line_table, loc);
163 va_list ap;
164 va_start (ap, msg);
165 diagnostic_cb (NULL, CPP_DL_WARNING, CPP_W_NONE, &richloc, msg, &ap);
166 va_end (ap);
169 /* Like fprintf, but print INDENT spaces at the beginning. */
171 static void
172 #if GCC_VERSION >= 4001
173 __attribute__((format (printf, 3, 4)))
174 #endif
175 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
177 va_list ap;
178 for (; indent >= 8; indent -= 8)
179 fputc ('\t', f);
180 fprintf (f, "%*s", indent, "");
181 va_start (ap, format);
182 vfprintf (f, format, ap);
183 va_end (ap);
186 /* Secondary stream for fp_decl. */
187 static FILE *header_file;
189 /* Start or continue emitting a declaration in fprintf-like manner,
190 printing both to F and global header_file, if non-null. */
191 static void
192 #if GCC_VERSION >= 4001
193 __attribute__((format (printf, 2, 3)))
194 #endif
195 fp_decl (FILE *f, const char *format, ...)
197 va_list ap;
198 va_start (ap, format);
199 vfprintf (f, format, ap);
200 va_end (ap);
202 if (!header_file)
203 return;
205 va_start (ap, format);
206 vfprintf (header_file, format, ap);
207 va_end (ap);
210 /* Finish a declaration being emitted by fp_decl. */
211 static void
212 fp_decl_done (FILE *f, const char *trailer)
214 fprintf (f, "%s\n", trailer);
215 if (header_file)
216 fprintf (header_file, "%s;", trailer);
219 static void
220 output_line_directive (FILE *f, location_t location,
221 bool dumpfile = false, bool fnargs = false)
223 const line_map_ordinary *map;
224 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
225 expanded_location loc = linemap_expand_location (line_table, map, location);
226 if (dumpfile)
228 /* When writing to a dumpfile only dump the filename. */
229 const char *file = strrchr (loc.file, DIR_SEPARATOR);
230 #if defined(DIR_SEPARATOR_2)
231 const char *pos2 = strrchr (loc.file, DIR_SEPARATOR_2);
232 if (pos2 && (!file || (pos2 > file)))
233 file = pos2;
234 #endif
235 if (!file)
236 file = loc.file;
237 else
238 ++file;
240 if (fnargs)
241 fprintf (f, "\"%s\", %d", file, loc.line);
242 else
243 fprintf (f, "%s:%d", file, loc.line);
245 else if (verbose >= 2)
246 /* Other gen programs really output line directives here, at least for
247 development it's right now more convenient to have line information
248 from the generated file. Still keep the directives as comment for now
249 to easily back-point to the meta-description. */
250 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
253 /* Find the file to write into next. We try to evenly distribute the contents
254 over the different files. */
256 #define SIZED_BASED_CHUNKS 1
258 static FILE *
259 choose_output (const vec<FILE *> &parts)
261 #ifdef SIZED_BASED_CHUNKS
262 FILE *shortest = NULL;
263 long min = 0;
264 for (FILE *part : parts)
266 long len = ftell (part);
267 if (!shortest || min > len)
268 shortest = part, min = len;
270 return shortest;
271 #else
272 static int current_file;
273 return parts[current_file++ % parts.length ()];
274 #endif
278 /* Pull in tree codes and builtin function codes from their
279 definition files. */
281 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
282 enum tree_code {
283 #include "tree.def"
284 MAX_TREE_CODES
286 #undef DEFTREECODE
288 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
289 enum built_in_function {
290 #include "builtins.def"
291 END_BUILTINS
294 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
295 enum internal_fn {
296 #include "internal-fn.def"
297 IFN_LAST
300 enum combined_fn {
301 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
302 CFN_##ENUM = int (ENUM),
303 #include "builtins.def"
305 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) \
306 CFN_##CODE = int (END_BUILTINS) + int (IFN_##CODE),
307 #include "internal-fn.def"
309 CFN_LAST
312 #include "case-cfn-macros.h"
314 /* Return true if CODE represents a commutative tree code. Otherwise
315 return false. */
316 bool
317 commutative_tree_code (enum tree_code code)
319 switch (code)
321 case PLUS_EXPR:
322 case MULT_EXPR:
323 case MULT_HIGHPART_EXPR:
324 case MIN_EXPR:
325 case MAX_EXPR:
326 case BIT_IOR_EXPR:
327 case BIT_XOR_EXPR:
328 case BIT_AND_EXPR:
329 case NE_EXPR:
330 case EQ_EXPR:
331 case UNORDERED_EXPR:
332 case ORDERED_EXPR:
333 case UNEQ_EXPR:
334 case LTGT_EXPR:
335 case TRUTH_AND_EXPR:
336 case TRUTH_XOR_EXPR:
337 case TRUTH_OR_EXPR:
338 case WIDEN_MULT_EXPR:
339 case VEC_WIDEN_MULT_HI_EXPR:
340 case VEC_WIDEN_MULT_LO_EXPR:
341 case VEC_WIDEN_MULT_EVEN_EXPR:
342 case VEC_WIDEN_MULT_ODD_EXPR:
343 return true;
345 default:
346 break;
348 return false;
351 /* Return true if CODE represents a ternary tree code for which the
352 first two operands are commutative. Otherwise return false. */
353 bool
354 commutative_ternary_tree_code (enum tree_code code)
356 switch (code)
358 case WIDEN_MULT_PLUS_EXPR:
359 case WIDEN_MULT_MINUS_EXPR:
360 case DOT_PROD_EXPR:
361 return true;
363 default:
364 break;
366 return false;
369 /* Return true if CODE is a comparison. */
371 bool
372 comparison_code_p (enum tree_code code)
374 switch (code)
376 case EQ_EXPR:
377 case NE_EXPR:
378 case ORDERED_EXPR:
379 case UNORDERED_EXPR:
380 case LTGT_EXPR:
381 case UNEQ_EXPR:
382 case GT_EXPR:
383 case GE_EXPR:
384 case LT_EXPR:
385 case LE_EXPR:
386 case UNGT_EXPR:
387 case UNGE_EXPR:
388 case UNLT_EXPR:
389 case UNLE_EXPR:
390 return true;
392 default:
393 break;
395 return false;
399 /* Base class for all identifiers the parser knows. */
401 class id_base : public nofree_ptr_hash<id_base>
403 public:
404 enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
406 id_base (id_kind, const char *, int = -1);
408 hashval_t hashval;
409 int nargs;
410 const char *id;
412 /* hash_table support. */
413 static inline hashval_t hash (const id_base *);
414 static inline int equal (const id_base *, const id_base *);
417 inline hashval_t
418 id_base::hash (const id_base *op)
420 return op->hashval;
423 inline int
424 id_base::equal (const id_base *op1,
425 const id_base *op2)
427 return (op1->hashval == op2->hashval
428 && strcmp (op1->id, op2->id) == 0);
431 /* The special id "null", which matches nothing. */
432 static id_base *null_id;
434 /* Hashtable of known pattern operators. This is pre-seeded from
435 all known tree codes and all known builtin function ids. */
436 static hash_table<id_base> *operators;
438 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
440 kind = kind_;
441 id = id_;
442 nargs = nargs_;
443 hashval = htab_hash_string (id);
446 /* Identifier that maps to a tree code. */
448 class operator_id : public id_base
450 public:
451 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
452 const char *tcc_)
453 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
454 enum tree_code code;
455 const char *tcc;
458 /* Identifier that maps to a builtin or internal function code. */
460 class fn_id : public id_base
462 public:
463 fn_id (enum built_in_function fn_, const char *id_)
464 : id_base (id_base::FN, id_), fn (fn_) {}
465 fn_id (enum internal_fn fn_, const char *id_)
466 : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
467 unsigned int fn;
470 class simplify;
472 /* Identifier that maps to a user-defined predicate. */
474 class predicate_id : public id_base
476 public:
477 predicate_id (const char *id_)
478 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
479 vec<simplify *> matchers;
482 /* Identifier that maps to a operator defined by a 'for' directive. */
484 class user_id : public id_base
486 public:
487 user_id (const char *id_, bool is_oper_list_ = false)
488 : id_base (id_base::USER, id_), substitutes (vNULL),
489 used (false), is_oper_list (is_oper_list_) {}
490 vec<id_base *> substitutes;
491 bool used;
492 bool is_oper_list;
495 template<>
496 template<>
497 inline bool
498 is_a_helper <fn_id *>::test (id_base *id)
500 return id->kind == id_base::FN;
503 template<>
504 template<>
505 inline bool
506 is_a_helper <operator_id *>::test (id_base *id)
508 return id->kind == id_base::CODE;
511 template<>
512 template<>
513 inline bool
514 is_a_helper <predicate_id *>::test (id_base *id)
516 return id->kind == id_base::PREDICATE;
519 template<>
520 template<>
521 inline bool
522 is_a_helper <user_id *>::test (id_base *id)
524 return id->kind == id_base::USER;
527 /* If ID has a pair of consecutive, commutative operands, return the
528 index of the first, otherwise return -1. */
530 static int
531 commutative_op (id_base *id)
533 if (operator_id *code = dyn_cast <operator_id *> (id))
535 if (commutative_tree_code (code->code)
536 || commutative_ternary_tree_code (code->code))
537 return 0;
538 return -1;
540 if (fn_id *fn = dyn_cast <fn_id *> (id))
541 switch (fn->fn)
543 CASE_CFN_FMA:
544 case CFN_FMS:
545 case CFN_FNMA:
546 case CFN_FNMS:
547 return 0;
549 case CFN_COND_ADD:
550 case CFN_COND_MUL:
551 case CFN_COND_MIN:
552 case CFN_COND_MAX:
553 case CFN_COND_FMIN:
554 case CFN_COND_FMAX:
555 case CFN_COND_AND:
556 case CFN_COND_IOR:
557 case CFN_COND_XOR:
558 case CFN_COND_FMA:
559 case CFN_COND_FMS:
560 case CFN_COND_FNMA:
561 case CFN_COND_FNMS:
562 case CFN_COND_LEN_ADD:
563 case CFN_COND_LEN_MUL:
564 case CFN_COND_LEN_MIN:
565 case CFN_COND_LEN_MAX:
566 case CFN_COND_LEN_FMIN:
567 case CFN_COND_LEN_FMAX:
568 case CFN_COND_LEN_AND:
569 case CFN_COND_LEN_IOR:
570 case CFN_COND_LEN_XOR:
571 case CFN_COND_LEN_FMA:
572 case CFN_COND_LEN_FMS:
573 case CFN_COND_LEN_FNMA:
574 case CFN_COND_LEN_FNMS:
575 return 1;
577 default:
578 return -1;
580 if (user_id *uid = dyn_cast<user_id *> (id))
582 int res = commutative_op (uid->substitutes[0]);
583 if (res < 0)
584 return -1;
585 for (unsigned i = 1; i < uid->substitutes.length (); ++i)
586 if (res != commutative_op (uid->substitutes[i]))
587 return -1;
588 return res;
590 return -1;
593 /* Add a predicate identifier to the hash. */
595 static predicate_id *
596 add_predicate (const char *id)
598 predicate_id *p = new predicate_id (id);
599 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
600 if (*slot)
601 fatal ("duplicate id definition");
602 *slot = p;
603 return p;
606 /* Add a tree code identifier to the hash. */
608 static void
609 add_operator (enum tree_code code, const char *id,
610 const char *tcc, unsigned nargs)
612 if (strcmp (tcc, "tcc_unary") != 0
613 && strcmp (tcc, "tcc_binary") != 0
614 && strcmp (tcc, "tcc_comparison") != 0
615 && strcmp (tcc, "tcc_expression") != 0
616 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
617 && strcmp (tcc, "tcc_reference") != 0
618 /* To have INTEGER_CST and friends as "predicate operators". */
619 && strcmp (tcc, "tcc_constant") != 0
620 /* And allow CONSTRUCTOR for vector initializers. */
621 && !(code == CONSTRUCTOR)
622 /* Allow SSA_NAME as predicate operator. */
623 && !(code == SSA_NAME))
624 return;
625 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
626 if (code == ADDR_EXPR)
627 nargs = 0;
628 operator_id *op = new operator_id (code, id, nargs, tcc);
629 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
630 if (*slot)
631 fatal ("duplicate id definition");
632 *slot = op;
635 /* Add a built-in or internal function identifier to the hash. ID is
636 the name of its CFN_* enumeration value. */
638 template <typename T>
639 static void
640 add_function (T code, const char *id)
642 fn_id *fn = new fn_id (code, id);
643 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
644 if (*slot)
645 fatal ("duplicate id definition");
646 *slot = fn;
649 /* Helper for easy comparing ID with tree code CODE. */
651 static bool
652 operator==(id_base &id, enum tree_code code)
654 if (operator_id *oid = dyn_cast <operator_id *> (&id))
655 return oid->code == code;
656 return false;
659 /* Lookup the identifier ID. Allow "null" if ALLOW_NULL. */
661 id_base *
662 get_operator (const char *id, bool allow_null = false)
664 if (allow_null && strcmp (id, "null") == 0)
665 return null_id;
667 id_base tem (id_base::CODE, id);
669 id_base *op = operators->find_with_hash (&tem, tem.hashval);
670 if (op)
672 /* If this is a user-defined identifier track whether it was used. */
673 if (user_id *uid = dyn_cast<user_id *> (op))
674 uid->used = true;
675 return op;
678 char *id2;
679 bool all_upper = true;
680 bool all_lower = true;
681 for (unsigned int i = 0; id[i]; ++i)
682 if (ISUPPER (id[i]))
683 all_lower = false;
684 else if (ISLOWER (id[i]))
685 all_upper = false;
686 if (all_lower)
688 /* Try in caps with _EXPR appended. */
689 id2 = ACONCAT ((id, "_EXPR", NULL));
690 for (unsigned int i = 0; id2[i]; ++i)
691 id2[i] = TOUPPER (id2[i]);
693 else if (all_upper && startswith (id, "IFN_"))
694 /* Try CFN_ instead of IFN_. */
695 id2 = ACONCAT (("CFN_", id + 4, NULL));
696 else if (all_upper && startswith (id, "BUILT_IN_"))
697 /* Try prepending CFN_. */
698 id2 = ACONCAT (("CFN_", id, NULL));
699 else
700 return NULL;
702 new (&tem) id_base (id_base::CODE, id2);
703 return operators->find_with_hash (&tem, tem.hashval);
706 /* Return the comparison operators that results if the operands are
707 swapped. This is safe for floating-point. */
709 id_base *
710 swap_tree_comparison (operator_id *p)
712 switch (p->code)
714 case EQ_EXPR:
715 case NE_EXPR:
716 case ORDERED_EXPR:
717 case UNORDERED_EXPR:
718 case LTGT_EXPR:
719 case UNEQ_EXPR:
720 return p;
721 case GT_EXPR:
722 return get_operator ("LT_EXPR");
723 case GE_EXPR:
724 return get_operator ("LE_EXPR");
725 case LT_EXPR:
726 return get_operator ("GT_EXPR");
727 case LE_EXPR:
728 return get_operator ("GE_EXPR");
729 case UNGT_EXPR:
730 return get_operator ("UNLT_EXPR");
731 case UNGE_EXPR:
732 return get_operator ("UNLE_EXPR");
733 case UNLT_EXPR:
734 return get_operator ("UNGT_EXPR");
735 case UNLE_EXPR:
736 return get_operator ("UNGE_EXPR");
737 default:
738 gcc_unreachable ();
742 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
745 /* The AST produced by parsing of the pattern definitions. */
747 class dt_operand;
748 class capture_info;
750 /* The base class for operands. */
752 class operand {
753 public:
754 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
755 operand (enum op_type type_, location_t loc_)
756 : type (type_), location (loc_) {}
757 enum op_type type;
758 location_t location;
759 virtual void gen_transform (FILE *, int, const char *, bool, int,
760 const char *, capture_info *,
761 dt_operand ** = 0,
762 int = 0)
763 { gcc_unreachable (); }
766 /* A predicate operand. Predicates are leafs in the AST. */
768 class predicate : public operand
770 public:
771 predicate (predicate_id *p_, location_t loc)
772 : operand (OP_PREDICATE, loc), p (p_) {}
773 predicate_id *p;
776 /* An operand that constitutes an expression. Expressions include
777 function calls and user-defined predicate invocations. */
779 class expr : public operand
781 public:
782 expr (id_base *operation_, location_t loc, bool is_commutative_ = false)
783 : operand (OP_EXPR, loc), operation (operation_),
784 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
785 is_generic (false), force_single_use (false), force_leaf (false),
786 opt_grp (0) {}
787 expr (expr *e)
788 : operand (OP_EXPR, e->location), operation (e->operation),
789 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
790 is_generic (e->is_generic), force_single_use (e->force_single_use),
791 force_leaf (e->force_leaf), opt_grp (e->opt_grp) {}
792 void append_op (operand *op) { ops.safe_push (op); }
793 /* The operator and its operands. */
794 id_base *operation;
795 vec<operand *> ops;
796 /* An explicitely specified type - used exclusively for conversions. */
797 const char *expr_type;
798 /* Whether the operation is to be applied commutatively. This is
799 later lowered to two separate patterns. */
800 bool is_commutative;
801 /* Whether the expression is expected to be in GENERIC form. */
802 bool is_generic;
803 /* Whether pushing any stmt to the sequence should be conditional
804 on this expression having a single-use. */
805 bool force_single_use;
806 /* Whether in the result expression this should be a leaf node
807 with any children simplified down to simple operands. */
808 bool force_leaf;
809 /* If non-zero, the group for optional handling. */
810 unsigned char opt_grp;
811 void gen_transform (FILE *f, int, const char *, bool, int,
812 const char *, capture_info *,
813 dt_operand ** = 0, int = 0) override;
816 /* An operator that is represented by native C code. This is always
817 a leaf operand in the AST. This class is also used to represent
818 the code to be generated for 'if' and 'with' expressions. */
820 class c_expr : public operand
822 public:
823 /* A mapping of an identifier and its replacement. Used to apply
824 'for' lowering. */
825 class id_tab {
826 public:
827 const char *id;
828 const char *oper;
829 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
832 c_expr (cpp_reader *r_, location_t loc,
833 vec<cpp_token> code_, unsigned nr_stmts_,
834 vec<id_tab> ids_, cid_map_t *capture_ids_)
835 : operand (OP_C_EXPR, loc), r (r_), code (code_),
836 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
837 /* cpplib tokens and state to transform this back to source. */
838 cpp_reader *r;
839 vec<cpp_token> code;
840 cid_map_t *capture_ids;
841 /* The number of statements parsed (well, the number of ';'s). */
842 unsigned nr_stmts;
843 /* The identifier replacement vector. */
844 vec<id_tab> ids;
845 void gen_transform (FILE *f, int, const char *, bool, int,
846 const char *, capture_info *,
847 dt_operand ** = 0, int = 0) final override;
850 /* A wrapper around another operand that captures its value. */
852 class capture : public operand
854 public:
855 capture (location_t loc, unsigned where_, operand *what_, bool value_)
856 : operand (OP_CAPTURE, loc), where (where_), value_match (value_),
857 what (what_) {}
858 /* Identifier index for the value. */
859 unsigned where;
860 /* Whether in a match of two operands the compare should be for
861 equal values rather than equal atoms (boils down to a type
862 check or not). */
863 bool value_match;
864 /* The captured value. */
865 operand *what;
866 void gen_transform (FILE *f, int, const char *, bool, int,
867 const char *, capture_info *,
868 dt_operand ** = 0, int = 0) final override;
871 /* if expression. */
873 class if_expr : public operand
875 public:
876 if_expr (location_t loc)
877 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
878 c_expr *cond;
879 operand *trueexpr;
880 operand *falseexpr;
883 /* with expression. */
885 class with_expr : public operand
887 public:
888 with_expr (location_t loc)
889 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
890 c_expr *with;
891 operand *subexpr;
894 template<>
895 template<>
896 inline bool
897 is_a_helper <capture *>::test (operand *op)
899 return op->type == operand::OP_CAPTURE;
902 template<>
903 template<>
904 inline bool
905 is_a_helper <predicate *>::test (operand *op)
907 return op->type == operand::OP_PREDICATE;
910 template<>
911 template<>
912 inline bool
913 is_a_helper <c_expr *>::test (operand *op)
915 return op->type == operand::OP_C_EXPR;
918 template<>
919 template<>
920 inline bool
921 is_a_helper <expr *>::test (operand *op)
923 return op->type == operand::OP_EXPR;
926 template<>
927 template<>
928 inline bool
929 is_a_helper <if_expr *>::test (operand *op)
931 return op->type == operand::OP_IF;
934 template<>
935 template<>
936 inline bool
937 is_a_helper <with_expr *>::test (operand *op)
939 return op->type == operand::OP_WITH;
942 /* The main class of a pattern and its transform. This is used to
943 represent both (simplify ...) and (match ...) kinds. The AST
944 duplicates all outer 'if' and 'for' expressions here so each
945 simplify can exist in isolation. */
947 class simplify
949 public:
950 enum simplify_kind { SIMPLIFY, MATCH };
952 simplify (simplify_kind kind_, unsigned id_, operand *match_,
953 operand *result_, vec<vec<user_id *> > for_vec_,
954 cid_map_t *capture_ids_)
955 : kind (kind_), id (id_), match (match_), result (result_),
956 for_vec (for_vec_), for_subst_vec (vNULL),
957 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
959 simplify_kind kind;
960 /* ID. This is kept to easily associate related simplifies expanded
961 from the same original one. */
962 unsigned id;
963 /* The expression that is matched against the GENERIC or GIMPLE IL. */
964 operand *match;
965 /* For a (simplify ...) an expression with ifs and withs with the expression
966 produced when the pattern applies in the leafs.
967 For a (match ...) the leafs are either empty if it is a simple predicate
968 or the single expression specifying the matched operands. */
969 class operand *result;
970 /* Collected 'for' expression operators that have to be replaced
971 in the lowering phase. */
972 vec<vec<user_id *> > for_vec;
973 vec<std::pair<user_id *, id_base *> > for_subst_vec;
974 /* A map of capture identifiers to indexes. */
975 cid_map_t *capture_ids;
976 int capture_max;
979 /* Debugging routines for dumping the AST. */
981 DEBUG_FUNCTION void
982 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
984 if (capture *c = dyn_cast<capture *> (o))
986 if (c->what && flattened == false)
987 print_operand (c->what, f, flattened);
988 fprintf (f, "@%u", c->where);
991 else if (predicate *p = dyn_cast<predicate *> (o))
992 fprintf (f, "%s", p->p->id);
994 else if (is_a<c_expr *> (o))
995 fprintf (f, "c_expr");
997 else if (expr *e = dyn_cast<expr *> (o))
999 if (e->ops.length () == 0)
1000 fprintf (f, "%s", e->operation->id);
1001 else
1003 fprintf (f, "(%s", e->operation->id);
1005 if (flattened == false)
1007 for (unsigned i = 0; i < e->ops.length (); ++i)
1009 putc (' ', f);
1010 print_operand (e->ops[i], f, flattened);
1013 putc (')', f);
1017 else
1018 gcc_unreachable ();
1021 DEBUG_FUNCTION void
1022 print_matches (class simplify *s, FILE *f = stderr)
1024 fprintf (f, "for expression: ");
1025 print_operand (s->match, f);
1026 putc ('\n', f);
1030 /* AST lowering. */
1032 /* Lowering of commutative operators. */
1034 static void
1035 cartesian_product (const vec< vec<operand *> >& ops_vector,
1036 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
1038 if (n == ops_vector.length ())
1040 vec<operand *> xv = v.copy ();
1041 result.safe_push (xv);
1042 return;
1045 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
1047 v[n] = ops_vector[n][i];
1048 cartesian_product (ops_vector, result, v, n + 1);
1052 /* Lower OP to two operands in case it is marked as commutative. */
1054 static vec<operand *>
1055 commutate (operand *op, vec<vec<user_id *> > &for_vec)
1057 vec<operand *> ret = vNULL;
1059 if (capture *c = dyn_cast <capture *> (op))
1061 if (!c->what)
1063 ret.safe_push (op);
1064 return ret;
1066 vec<operand *> v = commutate (c->what, for_vec);
1067 for (unsigned i = 0; i < v.length (); ++i)
1069 capture *nc = new capture (c->location, c->where, v[i],
1070 c->value_match);
1071 ret.safe_push (nc);
1073 return ret;
1076 expr *e = dyn_cast <expr *> (op);
1077 if (!e || e->ops.length () == 0)
1079 ret.safe_push (op);
1080 return ret;
1083 vec< vec<operand *> > ops_vector = vNULL;
1084 for (unsigned i = 0; i < e->ops.length (); ++i)
1085 ops_vector.safe_push (commutate (e->ops[i], for_vec));
1087 auto_vec< vec<operand *> > result;
1088 auto_vec<operand *> v (e->ops.length ());
1089 v.quick_grow_cleared (e->ops.length ());
1090 cartesian_product (ops_vector, result, v, 0);
1093 for (unsigned i = 0; i < result.length (); ++i)
1095 expr *ne = new expr (e);
1096 ne->is_commutative = false;
1097 for (unsigned j = 0; j < result[i].length (); ++j)
1098 ne->append_op (result[i][j]);
1099 ret.safe_push (ne);
1102 if (!e->is_commutative)
1103 return ret;
1105 /* The operation is always binary if it isn't inherently commutative. */
1106 int natural_opno = commutative_op (e->operation);
1107 unsigned int opno = natural_opno >= 0 ? natural_opno : 0;
1108 for (unsigned i = 0; i < result.length (); ++i)
1110 expr *ne = new expr (e);
1111 if (operator_id *r = dyn_cast <operator_id *> (ne->operation))
1113 if (comparison_code_p (r->code))
1114 ne->operation = swap_tree_comparison (r);
1116 else if (user_id *p = dyn_cast <user_id *> (ne->operation))
1118 bool found_compare = false;
1119 for (unsigned j = 0; j < p->substitutes.length (); ++j)
1120 if (operator_id *q = dyn_cast <operator_id *> (p->substitutes[j]))
1122 if (comparison_code_p (q->code)
1123 && swap_tree_comparison (q) != q)
1125 found_compare = true;
1126 break;
1129 if (found_compare)
1131 user_id *newop = new user_id ("<internal>");
1132 for (unsigned j = 0; j < p->substitutes.length (); ++j)
1134 id_base *subst = p->substitutes[j];
1135 if (operator_id *q = dyn_cast <operator_id *> (subst))
1137 if (comparison_code_p (q->code))
1138 subst = swap_tree_comparison (q);
1140 newop->substitutes.safe_push (subst);
1142 ne->operation = newop;
1143 /* Search for 'p' inside the for vector and push 'newop'
1144 to the same level. */
1145 for (unsigned j = 0; newop && j < for_vec.length (); ++j)
1146 for (unsigned k = 0; k < for_vec[j].length (); ++k)
1147 if (for_vec[j][k] == p)
1149 for_vec[j].safe_push (newop);
1150 newop = NULL;
1151 break;
1155 ne->is_commutative = false;
1156 for (unsigned j = 0; j < result[i].length (); ++j)
1158 int old_j = (j == opno ? opno + 1 : j == opno + 1 ? opno : j);
1159 ne->append_op (result[i][old_j]);
1161 ret.safe_push (ne);
1164 return ret;
1167 /* Lower operations marked as commutative in the AST of S and push
1168 the resulting patterns to SIMPLIFIERS. */
1170 static void
1171 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
1173 vec<operand *> matchers = commutate (s->match, s->for_vec);
1174 for (unsigned i = 0; i < matchers.length (); ++i)
1176 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1177 s->for_vec, s->capture_ids);
1178 simplifiers.safe_push (ns);
1182 /* Strip conditional operations using group GRP from O and its
1183 children if STRIP, else replace them with an unconditional operation. */
1185 operand *
1186 lower_opt (operand *o, unsigned char grp, bool strip)
1188 if (capture *c = dyn_cast<capture *> (o))
1190 if (c->what)
1191 return new capture (c->location, c->where,
1192 lower_opt (c->what, grp, strip),
1193 c->value_match);
1194 else
1195 return c;
1198 expr *e = dyn_cast<expr *> (o);
1199 if (!e)
1200 return o;
1202 if (e->opt_grp == grp)
1204 if (strip)
1205 return lower_opt (e->ops[0], grp, strip);
1207 expr *ne = new expr (e);
1208 ne->opt_grp = 0;
1209 ne->append_op (lower_opt (e->ops[0], grp, strip));
1210 return ne;
1213 expr *ne = new expr (e);
1214 for (unsigned i = 0; i < e->ops.length (); ++i)
1215 ne->append_op (lower_opt (e->ops[i], grp, strip));
1217 return ne;
1220 /* Determine whether O or its children uses the conditional operation
1221 group GRP. */
1223 static bool
1224 has_opt (operand *o, unsigned char grp)
1226 if (capture *c = dyn_cast<capture *> (o))
1228 if (c->what)
1229 return has_opt (c->what, grp);
1230 else
1231 return false;
1234 expr *e = dyn_cast<expr *> (o);
1235 if (!e)
1236 return false;
1238 if (e->opt_grp == grp)
1239 return true;
1241 for (unsigned i = 0; i < e->ops.length (); ++i)
1242 if (has_opt (e->ops[i], grp))
1243 return true;
1245 return false;
1248 /* Lower conditional convert operators in O, expanding it to a vector
1249 if required. */
1251 static vec<operand *>
1252 lower_opt (operand *o)
1254 vec<operand *> v1 = vNULL, v2;
1256 v1.safe_push (o);
1258 /* Conditional operations are lowered to a pattern with the
1259 operation and one without. All different conditional operation
1260 groups are lowered separately. */
1262 for (unsigned i = 1; i <= 10; ++i)
1264 v2 = vNULL;
1265 for (unsigned j = 0; j < v1.length (); ++j)
1266 if (has_opt (v1[j], i))
1268 v2.safe_push (lower_opt (v1[j], i, false));
1269 v2.safe_push (lower_opt (v1[j], i, true));
1272 if (v2 != vNULL)
1274 v1 = vNULL;
1275 for (unsigned j = 0; j < v2.length (); ++j)
1276 v1.safe_push (v2[j]);
1280 return v1;
1283 /* Lower conditional convert operators in the AST of S and push
1284 the resulting multiple patterns to SIMPLIFIERS. */
1286 static void
1287 lower_opt (simplify *s, vec<simplify *>& simplifiers)
1289 vec<operand *> matchers = lower_opt (s->match);
1290 for (unsigned i = 0; i < matchers.length (); ++i)
1292 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1293 s->for_vec, s->capture_ids);
1294 simplifiers.safe_push (ns);
1298 /* Lower the compare operand of COND_EXPRs to a
1299 GENERIC and a GIMPLE variant. */
1301 static vec<operand *>
1302 lower_cond (operand *o)
1304 vec<operand *> ro = vNULL;
1306 if (capture *c = dyn_cast<capture *> (o))
1308 if (c->what)
1310 vec<operand *> lop = vNULL;
1311 lop = lower_cond (c->what);
1313 for (unsigned i = 0; i < lop.length (); ++i)
1314 ro.safe_push (new capture (c->location, c->where, lop[i],
1315 c->value_match));
1316 return ro;
1320 expr *e = dyn_cast<expr *> (o);
1321 if (!e || e->ops.length () == 0)
1323 ro.safe_push (o);
1324 return ro;
1327 vec< vec<operand *> > ops_vector = vNULL;
1328 for (unsigned i = 0; i < e->ops.length (); ++i)
1329 ops_vector.safe_push (lower_cond (e->ops[i]));
1331 auto_vec< vec<operand *> > result;
1332 auto_vec<operand *> v (e->ops.length ());
1333 v.quick_grow_cleared (e->ops.length ());
1334 cartesian_product (ops_vector, result, v, 0);
1336 for (unsigned i = 0; i < result.length (); ++i)
1338 expr *ne = new expr (e);
1339 for (unsigned j = 0; j < result[i].length (); ++j)
1340 ne->append_op (result[i][j]);
1341 ro.safe_push (ne);
1342 /* If this is a COND with a captured expression or an
1343 expression with two operands then also match a GENERIC
1344 form on the compare. */
1345 if (*e->operation == COND_EXPR
1346 && ((is_a <capture *> (e->ops[0])
1347 && as_a <capture *> (e->ops[0])->what
1348 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1349 && as_a <expr *>
1350 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1351 || (is_a <expr *> (e->ops[0])
1352 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1354 ne = new expr (e);
1355 for (unsigned j = 0; j < result[i].length (); ++j)
1356 ne->append_op (result[i][j]);
1357 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1359 expr *ocmp = as_a <expr *> (c->what);
1360 expr *cmp = new expr (ocmp);
1361 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1362 cmp->append_op (ocmp->ops[j]);
1363 cmp->is_generic = true;
1364 ne->ops[0] = new capture (c->location, c->where, cmp,
1365 c->value_match);
1367 else
1369 expr *ocmp = as_a <expr *> (ne->ops[0]);
1370 expr *cmp = new expr (ocmp);
1371 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1372 cmp->append_op (ocmp->ops[j]);
1373 cmp->is_generic = true;
1374 ne->ops[0] = cmp;
1376 ro.safe_push (ne);
1380 return ro;
1383 /* Lower the compare operand of COND_EXPRs to a
1384 GENERIC and a GIMPLE variant. */
1386 static void
1387 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1389 vec<operand *> matchers = lower_cond (s->match);
1390 for (unsigned i = 0; i < matchers.length (); ++i)
1392 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1393 s->for_vec, s->capture_ids);
1394 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1395 simplifiers.safe_push (ns);
1399 /* Return true if O refers to ID. */
1401 bool
1402 contains_id (operand *o, user_id *id)
1404 if (capture *c = dyn_cast<capture *> (o))
1405 return c->what && contains_id (c->what, id);
1407 if (expr *e = dyn_cast<expr *> (o))
1409 if (e->operation == id)
1410 return true;
1411 for (unsigned i = 0; i < e->ops.length (); ++i)
1412 if (contains_id (e->ops[i], id))
1413 return true;
1414 return false;
1417 if (with_expr *w = dyn_cast <with_expr *> (o))
1418 return (contains_id (w->with, id)
1419 || contains_id (w->subexpr, id));
1421 if (if_expr *ife = dyn_cast <if_expr *> (o))
1422 return (contains_id (ife->cond, id)
1423 || contains_id (ife->trueexpr, id)
1424 || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1426 if (c_expr *ce = dyn_cast<c_expr *> (o))
1427 return ce->capture_ids && ce->capture_ids->get (id->id);
1429 return false;
1433 /* In AST operand O replace operator ID with operator WITH. */
1435 operand *
1436 replace_id (operand *o, user_id *id, id_base *with)
1438 /* Deep-copy captures and expressions, replacing operations as
1439 needed. */
1440 if (capture *c = dyn_cast<capture *> (o))
1442 if (!c->what)
1443 return c;
1444 return new capture (c->location, c->where,
1445 replace_id (c->what, id, with), c->value_match);
1447 else if (expr *e = dyn_cast<expr *> (o))
1449 expr *ne = new expr (e);
1450 if (e->operation == id)
1451 ne->operation = with;
1452 for (unsigned i = 0; i < e->ops.length (); ++i)
1453 ne->append_op (replace_id (e->ops[i], id, with));
1454 return ne;
1456 else if (with_expr *w = dyn_cast <with_expr *> (o))
1458 with_expr *nw = new with_expr (w->location);
1459 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1460 nw->subexpr = replace_id (w->subexpr, id, with);
1461 return nw;
1463 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1465 if_expr *nife = new if_expr (ife->location);
1466 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1467 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1468 if (ife->falseexpr)
1469 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1470 return nife;
1473 /* For c_expr we simply record a string replacement table which is
1474 applied at code-generation time. */
1475 if (c_expr *ce = dyn_cast<c_expr *> (o))
1477 vec<c_expr::id_tab> ids = ce->ids.copy ();
1478 ids.safe_push (c_expr::id_tab (id->id, with->id));
1479 return new c_expr (ce->r, ce->location,
1480 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1483 return o;
1486 /* Return true if the binary operator OP is ok for delayed substitution
1487 during for lowering. */
1489 static bool
1490 binary_ok (operator_id *op)
1492 switch (op->code)
1494 case PLUS_EXPR:
1495 case MINUS_EXPR:
1496 case MULT_EXPR:
1497 case TRUNC_DIV_EXPR:
1498 case CEIL_DIV_EXPR:
1499 case FLOOR_DIV_EXPR:
1500 case ROUND_DIV_EXPR:
1501 case TRUNC_MOD_EXPR:
1502 case CEIL_MOD_EXPR:
1503 case FLOOR_MOD_EXPR:
1504 case ROUND_MOD_EXPR:
1505 case RDIV_EXPR:
1506 case EXACT_DIV_EXPR:
1507 case MIN_EXPR:
1508 case MAX_EXPR:
1509 case BIT_IOR_EXPR:
1510 case BIT_XOR_EXPR:
1511 case BIT_AND_EXPR:
1512 return true;
1513 default:
1514 return false;
1518 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1520 static void
1521 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1523 vec<vec<user_id *> >& for_vec = sin->for_vec;
1524 unsigned worklist_start = 0;
1525 auto_vec<simplify *> worklist;
1526 worklist.safe_push (sin);
1528 /* Lower each recorded for separately, operating on the
1529 set of simplifiers created by the previous one.
1530 Lower inner-to-outer so inner for substitutes can refer
1531 to operators replaced by outer fors. */
1532 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1534 vec<user_id *>& ids = for_vec[fi];
1535 unsigned n_ids = ids.length ();
1536 unsigned max_n_opers = 0;
1537 bool can_delay_subst = true;
1538 for (unsigned i = 0; i < n_ids; ++i)
1540 if (ids[i]->substitutes.length () > max_n_opers)
1541 max_n_opers = ids[i]->substitutes.length ();
1542 /* Require that all substitutes are of the same kind so that
1543 if we delay substitution to the result op code generation
1544 can look at the first substitute for deciding things like
1545 types of operands. */
1546 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1547 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1548 if (ids[i]->substitutes[j]->kind != kind)
1549 can_delay_subst = false;
1550 else if (operator_id *op
1551 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1553 operator_id *op0
1554 = as_a <operator_id *> (ids[i]->substitutes[0]);
1555 if (strcmp (op->tcc, "tcc_comparison") == 0
1556 && strcmp (op0->tcc, "tcc_comparison") == 0)
1558 /* Unfortunately we can't just allow all tcc_binary. */
1559 else if (strcmp (op->tcc, "tcc_binary") == 0
1560 && strcmp (op0->tcc, "tcc_binary") == 0
1561 && binary_ok (op)
1562 && binary_ok (op0))
1564 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1565 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1566 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1567 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1569 else
1570 can_delay_subst = false;
1572 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1574 else
1575 can_delay_subst = false;
1577 if (sin->kind == simplify::MATCH
1578 && can_delay_subst)
1579 continue;
1581 unsigned worklist_end = worklist.length ();
1582 for (unsigned si = worklist_start; si < worklist_end; ++si)
1584 simplify *s = worklist[si];
1585 for (unsigned j = 0; j < max_n_opers; ++j)
1587 operand *match_op = s->match;
1588 operand *result_op = s->result;
1589 auto_vec<std::pair<user_id *, id_base *> > subst (n_ids);
1590 bool skip = false;
1591 for (unsigned i = 0; i < n_ids; ++i)
1593 user_id *id = ids[i];
1594 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1595 if (oper == null_id
1596 && (contains_id (match_op, id)
1597 || contains_id (result_op, id)))
1599 skip = true;
1600 break;
1602 subst.quick_push (std::make_pair (id, oper));
1603 if (sin->kind == simplify::SIMPLIFY
1604 || !can_delay_subst)
1605 match_op = replace_id (match_op, id, oper);
1606 if (result_op
1607 && !can_delay_subst)
1608 result_op = replace_id (result_op, id, oper);
1610 if (skip)
1611 continue;
1613 simplify *ns = new simplify (s->kind, s->id, match_op, result_op,
1614 vNULL, s->capture_ids);
1615 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1616 if (result_op
1617 && can_delay_subst)
1618 ns->for_subst_vec.safe_splice (subst);
1620 worklist.safe_push (ns);
1623 worklist_start = worklist_end;
1626 /* Copy out the result from the last for lowering. */
1627 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1628 simplifiers.safe_push (worklist[i]);
1631 /* Lower the AST for everything in SIMPLIFIERS. */
1633 static void
1634 lower (vec<simplify *>& simplifiers, bool gimple)
1636 auto_vec<simplify *> out_simplifiers;
1637 for (auto s: simplifiers)
1638 lower_opt (s, out_simplifiers);
1640 simplifiers.truncate (0);
1641 for (auto s: out_simplifiers)
1642 lower_commutative (s, simplifiers);
1644 /* Lower for needs to happen before lowering cond
1645 to support (for cnd (cond vec_cond)). This is
1646 safe as substitution delay does not happen for
1647 cond or vec_cond. */
1648 out_simplifiers.truncate (0);
1649 for (auto s: simplifiers)
1650 lower_for (s, out_simplifiers);
1652 simplifiers.truncate (0);
1653 if (gimple)
1654 for (auto s: out_simplifiers)
1655 lower_cond (s, simplifiers);
1656 else
1657 simplifiers.safe_splice (out_simplifiers);
1663 /* The decision tree built for generating GIMPLE and GENERIC pattern
1664 matching code. It represents the 'match' expression of all
1665 simplifies and has those as its leafs. */
1667 class dt_simplify;
1669 /* A hash-map collecting semantically equivalent leafs in the decision
1670 tree for splitting out to separate functions. */
1671 struct sinfo
1673 dt_simplify *s;
1675 const char *fname;
1676 unsigned cnt;
1679 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1680 sinfo *>
1682 static inline hashval_t hash (const key_type &);
1683 static inline bool equal_keys (const key_type &, const key_type &);
1684 template <typename T> static inline void remove (T &) {}
1687 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1688 sinfo_map_t;
1690 /* Current simplifier ID we are processing during insertion into the
1691 decision tree. */
1692 static unsigned current_id;
1694 /* Decision tree base class, used for DT_NODE. */
1696 class dt_node
1698 public:
1699 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1701 enum dt_type type;
1702 unsigned level;
1703 dt_node *parent;
1704 vec<dt_node *> kids;
1706 /* Statistics. */
1707 unsigned num_leafs;
1708 unsigned total_size;
1709 unsigned max_level;
1711 dt_node (enum dt_type type_, dt_node *parent_)
1712 : type (type_), level (0), parent (parent_), kids (vNULL) {}
1714 dt_node *append_node (dt_node *);
1715 dt_node *append_op (operand *, dt_node *parent, unsigned pos);
1716 dt_node *append_true_op (operand *, dt_node *parent, unsigned pos);
1717 dt_node *append_match_op (operand *, dt_operand *, dt_node *parent,
1718 unsigned pos);
1719 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1721 virtual void gen (FILE *, int, bool, int) {}
1723 void gen_kids (FILE *, int, bool, int);
1724 void gen_kids_1 (FILE *, int, bool, int,
1725 const vec<dt_operand *> &, const vec<dt_operand *> &,
1726 const vec<dt_operand *> &, const vec<dt_operand *> &,
1727 const vec<dt_operand *> &, const vec<dt_node *> &);
1729 void analyze (sinfo_map_t &);
1732 /* Generic decision tree node used for DT_OPERAND, DT_MATCH and DT_TRUE. */
1734 class dt_operand : public dt_node
1736 public:
1737 operand *op;
1738 dt_operand *match_dop;
1739 unsigned pos;
1740 bool value_match;
1741 unsigned for_id;
1743 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1744 dt_operand *parent_, unsigned pos_)
1745 : dt_node (type, parent_), op (op_), match_dop (match_dop_),
1746 pos (pos_), value_match (false), for_id (current_id) {}
1748 void gen (FILE *, int, bool, int) final override;
1749 unsigned gen_predicate (FILE *, int, const char *, bool);
1750 unsigned gen_match_op (FILE *, int, const char *, bool);
1752 unsigned gen_gimple_expr (FILE *, int, int);
1753 unsigned gen_generic_expr (FILE *, int, const char *);
1755 char *get_name (char *);
1756 void gen_opname (char *, unsigned);
1759 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1761 class dt_simplify : public dt_node
1763 public:
1764 simplify *s;
1765 unsigned pattern_no;
1766 dt_operand **indexes;
1767 sinfo *info;
1769 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1770 : dt_node (DT_SIMPLIFY, NULL), s (s_), pattern_no (pattern_no_),
1771 indexes (indexes_), info (NULL) {}
1773 void gen_1 (FILE *, int, bool, operand *);
1774 void gen (FILE *f, int, bool, int) final override;
1777 template<>
1778 template<>
1779 inline bool
1780 is_a_helper <dt_operand *>::test (dt_node *n)
1782 return (n->type == dt_node::DT_OPERAND
1783 || n->type == dt_node::DT_MATCH
1784 || n->type == dt_node::DT_TRUE);
1787 template<>
1788 template<>
1789 inline bool
1790 is_a_helper <dt_simplify *>::test (dt_node *n)
1792 return n->type == dt_node::DT_SIMPLIFY;
1797 /* A container for the actual decision tree. */
1799 class decision_tree
1801 public:
1802 dt_node *root;
1804 void insert (class simplify *, unsigned);
1805 void gen (vec <FILE *> &f, bool gimple);
1806 void print (FILE *f = stderr);
1808 decision_tree () { root = new dt_node (dt_node::DT_NODE, NULL); }
1810 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1811 unsigned pos = 0, dt_node *parent = 0);
1812 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1813 static bool cmp_node (dt_node *, dt_node *);
1814 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1817 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1819 bool
1820 cmp_operand (operand *o1, operand *o2)
1822 if (!o1 || !o2 || o1->type != o2->type)
1823 return false;
1825 if (o1->type == operand::OP_PREDICATE)
1827 predicate *p1 = as_a<predicate *>(o1);
1828 predicate *p2 = as_a<predicate *>(o2);
1829 return p1->p == p2->p;
1831 else if (o1->type == operand::OP_EXPR)
1833 expr *e1 = static_cast<expr *>(o1);
1834 expr *e2 = static_cast<expr *>(o2);
1835 return (e1->operation == e2->operation
1836 && e1->is_generic == e2->is_generic);
1838 else
1839 return false;
1842 /* Compare two decision tree nodes N1 and N2 and return true if they
1843 are equal. */
1845 bool
1846 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1848 if (!n1 || !n2 || n1->type != n2->type)
1849 return false;
1851 if (n1 == n2)
1852 return true;
1854 if (n1->type == dt_node::DT_TRUE)
1855 return false;
1857 if (n1->type == dt_node::DT_OPERAND)
1858 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1859 (as_a<dt_operand *> (n2))->op);
1860 else if (n1->type == dt_node::DT_MATCH)
1861 return (((as_a<dt_operand *> (n1))->match_dop
1862 == (as_a<dt_operand *> (n2))->match_dop)
1863 && ((as_a<dt_operand *> (n1))->value_match
1864 == (as_a<dt_operand *> (n2))->value_match));
1865 return false;
1868 /* Search OPS for a decision tree node like P and return it if found. */
1870 dt_node *
1871 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1873 /* We can merge adjacent DT_TRUE. */
1874 if (p->type == dt_node::DT_TRUE
1875 && !ops.is_empty ()
1876 && ops.last ()->type == dt_node::DT_TRUE)
1877 return ops.last ();
1878 dt_operand *true_node = NULL;
1879 for (int i = ops.length () - 1; i >= 0; --i)
1881 /* But we can't merge across DT_TRUE nodes as they serve as
1882 pattern order barriers to make sure that patterns apply
1883 in order of appearance in case multiple matches are possible. */
1884 if (ops[i]->type == dt_node::DT_TRUE)
1886 if (! true_node
1887 || as_a <dt_operand *> (ops[i])->for_id > true_node->for_id)
1888 true_node = as_a <dt_operand *> (ops[i]);
1890 if (decision_tree::cmp_node (ops[i], p))
1892 /* Unless we are processing the same pattern or the blocking
1893 pattern is before the one we are going to merge with. */
1894 if (true_node
1895 && true_node->for_id != current_id
1896 && true_node->for_id > as_a <dt_operand *> (ops[i])->for_id)
1898 if (verbose >= 1)
1900 location_t p_loc = 0;
1901 if (p->type == dt_node::DT_OPERAND)
1902 p_loc = as_a <dt_operand *> (p)->op->location;
1903 location_t op_loc = 0;
1904 if (ops[i]->type == dt_node::DT_OPERAND)
1905 op_loc = as_a <dt_operand *> (ops[i])->op->location;
1906 location_t true_loc = 0;
1907 true_loc = true_node->op->location;
1908 warning_at (p_loc,
1909 "failed to merge decision tree node");
1910 warning_at (op_loc,
1911 "with the following");
1912 warning_at (true_loc,
1913 "because of the following which serves as ordering "
1914 "barrier");
1916 return NULL;
1918 return ops[i];
1921 return NULL;
1924 /* Append N to the decision tree if it there is not already an existing
1925 identical child. */
1927 dt_node *
1928 dt_node::append_node (dt_node *n)
1930 dt_node *kid;
1932 kid = decision_tree::find_node (kids, n);
1933 if (kid)
1934 return kid;
1936 kids.safe_push (n);
1937 n->level = this->level + 1;
1939 return n;
1942 /* Append OP to the decision tree. */
1944 dt_node *
1945 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1947 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1948 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1949 return append_node (n);
1952 /* Append a DT_TRUE decision tree node. */
1954 dt_node *
1955 dt_node::append_true_op (operand *op, dt_node *parent, unsigned pos)
1957 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1958 dt_operand *n = new dt_operand (DT_TRUE, op, 0, parent_, pos);
1959 return append_node (n);
1962 /* Append a DT_MATCH decision tree node. */
1964 dt_node *
1965 dt_node::append_match_op (operand *op, dt_operand *match_dop,
1966 dt_node *parent, unsigned pos)
1968 dt_operand *parent_ = as_a<dt_operand *> (parent);
1969 dt_operand *n = new dt_operand (DT_MATCH, op, match_dop, parent_, pos);
1970 return append_node (n);
1973 /* Append S to the decision tree. */
1975 dt_node *
1976 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1977 dt_operand **indexes)
1979 dt_simplify *s2;
1980 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1981 for (unsigned i = 0; i < kids.length (); ++i)
1982 if ((s2 = dyn_cast <dt_simplify *> (kids[i]))
1983 && (verbose >= 1
1984 || s->match->location != s2->s->match->location))
1986 /* With a nested patters, it's hard to avoid these in order
1987 to keep match.pd rules relatively small. */
1988 warning_at (s->match->location, "duplicate pattern");
1989 warning_at (s2->s->match->location, "previous pattern defined here");
1990 print_operand (s->match, stderr);
1991 fprintf (stderr, "\n");
1993 return append_node (n);
1996 /* Analyze the node and its children. */
1998 void
1999 dt_node::analyze (sinfo_map_t &map)
2001 num_leafs = 0;
2002 total_size = 1;
2003 max_level = level;
2005 if (type == DT_SIMPLIFY)
2007 /* Populate the map of equivalent simplifies. */
2008 dt_simplify *s = as_a <dt_simplify *> (this);
2009 bool existed;
2010 sinfo *&si = map.get_or_insert (s, &existed);
2011 if (!existed)
2013 si = new sinfo;
2014 si->s = s;
2015 si->cnt = 1;
2016 si->fname = NULL;
2018 else
2019 si->cnt++;
2020 s->info = si;
2021 num_leafs = 1;
2022 return;
2025 for (unsigned i = 0; i < kids.length (); ++i)
2027 kids[i]->analyze (map);
2028 num_leafs += kids[i]->num_leafs;
2029 total_size += kids[i]->total_size;
2030 max_level = MAX (max_level, kids[i]->max_level);
2034 /* Insert O into the decision tree and return the decision tree node found
2035 or created. */
2037 dt_node *
2038 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
2039 unsigned pos, dt_node *parent)
2041 dt_node *q, *elm = 0;
2043 if (capture *c = dyn_cast<capture *> (o))
2045 unsigned capt_index = c->where;
2047 if (indexes[capt_index] == 0)
2049 if (c->what)
2050 q = insert_operand (p, c->what, indexes, pos, parent);
2051 else
2053 q = elm = p->append_true_op (o, parent, pos);
2054 goto at_assert_elm;
2056 // get to the last capture
2057 for (operand *what = c->what;
2058 what && is_a<capture *> (what);
2059 c = as_a<capture *> (what), what = c->what)
2062 if (!c->what)
2064 unsigned cc_index = c->where;
2065 dt_operand *match_op = indexes[cc_index];
2067 dt_operand temp (dt_node::DT_TRUE, 0, 0, 0, 0);
2068 elm = decision_tree::find_node (p->kids, &temp);
2070 if (elm == 0)
2072 dt_operand match (dt_node::DT_MATCH, 0, match_op, 0, 0);
2073 match.value_match = c->value_match;
2074 elm = decision_tree::find_node (p->kids, &match);
2077 else
2079 dt_operand temp (dt_node::DT_OPERAND, c->what, 0, 0, 0);
2080 elm = decision_tree::find_node (p->kids, &temp);
2083 at_assert_elm:
2084 gcc_assert (elm->type == dt_node::DT_TRUE
2085 || elm->type == dt_node::DT_OPERAND
2086 || elm->type == dt_node::DT_MATCH);
2087 indexes[capt_index] = static_cast<dt_operand *> (elm);
2088 return q;
2090 else
2092 p = p->append_match_op (o, indexes[capt_index], parent, pos);
2093 as_a <dt_operand *>(p)->value_match = c->value_match;
2094 if (c->what)
2095 return insert_operand (p, c->what, indexes, 0, p);
2096 else
2097 return p;
2100 p = p->append_op (o, parent, pos);
2101 q = p;
2103 if (expr *e = dyn_cast <expr *>(o))
2105 for (unsigned i = 0; i < e->ops.length (); ++i)
2106 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
2109 return q;
2112 /* Insert S into the decision tree. */
2114 void
2115 decision_tree::insert (class simplify *s, unsigned pattern_no)
2117 current_id = s->id;
2118 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
2119 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
2120 p->append_simplify (s, pattern_no, indexes);
2123 /* Debug functions to dump the decision tree. */
2125 DEBUG_FUNCTION void
2126 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
2128 if (p->type == dt_node::DT_NODE)
2129 fprintf (f, "root");
2130 else
2132 fprintf (f, "|");
2133 for (unsigned i = 0; i < indent; i++)
2134 fprintf (f, "-");
2136 if (p->type == dt_node::DT_OPERAND)
2138 dt_operand *dop = static_cast<dt_operand *>(p);
2139 print_operand (dop->op, f, true);
2141 else if (p->type == dt_node::DT_TRUE)
2142 fprintf (f, "true");
2143 else if (p->type == dt_node::DT_MATCH)
2144 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
2145 else if (p->type == dt_node::DT_SIMPLIFY)
2147 dt_simplify *s = static_cast<dt_simplify *> (p);
2148 fprintf (f, "simplify_%u { ", s->pattern_no);
2149 for (int i = 0; i <= s->s->capture_max; ++i)
2150 fprintf (f, "%p, ", (void *) s->indexes[i]);
2151 fprintf (f, " } ");
2153 if (is_a <dt_operand *> (p))
2154 fprintf (f, " [%u]", as_a <dt_operand *> (p)->for_id);
2157 fprintf (stderr, " (%p, %p), %u, %u\n",
2158 (void *) p, (void *) p->parent, p->level, p->kids.length ());
2160 for (unsigned i = 0; i < p->kids.length (); ++i)
2161 decision_tree::print_node (p->kids[i], f, indent + 2);
2164 DEBUG_FUNCTION void
2165 decision_tree::print (FILE *f)
2167 return decision_tree::print_node (root, f);
2171 /* For GENERIC we have to take care of wrapping multiple-used
2172 expressions with side-effects in save_expr and preserve side-effects
2173 of expressions with omit_one_operand. Analyze captures in
2174 match, result and with expressions and perform early-outs
2175 on the outermost match expression operands for cases we cannot
2176 handle. */
2178 class capture_info
2180 public:
2181 capture_info (simplify *s, operand *, bool);
2182 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
2183 bool walk_result (operand *o, bool, operand *);
2184 void walk_c_expr (c_expr *);
2186 struct cinfo
2188 bool expr_p;
2189 bool cse_p;
2190 bool force_no_side_effects_p;
2191 bool force_single_use;
2192 bool cond_expr_cond_p;
2193 unsigned long toplevel_msk;
2194 unsigned match_use_count;
2195 unsigned result_use_count;
2196 unsigned same_as;
2197 capture *c;
2200 auto_vec<cinfo> info;
2201 unsigned long force_no_side_effects;
2202 bool gimple;
2205 /* Analyze captures in S. */
2207 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
2209 gimple = gimple_;
2211 expr *e;
2212 if (s->kind == simplify::MATCH)
2214 force_no_side_effects = -1;
2215 return;
2218 force_no_side_effects = 0;
2219 info.safe_grow_cleared (s->capture_max + 1, true);
2220 for (int i = 0; i <= s->capture_max; ++i)
2221 info[i].same_as = i;
2223 e = as_a <expr *> (s->match);
2224 for (unsigned i = 0; i < e->ops.length (); ++i)
2225 walk_match (e->ops[i], i,
2226 (i != 0 && *e->operation == COND_EXPR)
2227 || *e->operation == TRUTH_ANDIF_EXPR
2228 || *e->operation == TRUTH_ORIF_EXPR,
2229 i == 0 && *e->operation == COND_EXPR);
2231 walk_result (s->result, false, result);
2234 /* Analyze captures in the match expression piece O. */
2236 void
2237 capture_info::walk_match (operand *o, unsigned toplevel_arg,
2238 bool conditional_p, bool cond_expr_cond_p)
2240 if (capture *c = dyn_cast <capture *> (o))
2242 unsigned where = c->where;
2243 info[where].match_use_count++;
2244 info[where].toplevel_msk |= 1 << toplevel_arg;
2245 info[where].force_no_side_effects_p |= conditional_p;
2246 info[where].cond_expr_cond_p |= cond_expr_cond_p;
2247 if (!info[where].c)
2248 info[where].c = c;
2249 if (!c->what)
2250 return;
2251 /* Recurse to exprs and captures. */
2252 if (is_a <capture *> (c->what)
2253 || is_a <expr *> (c->what))
2254 walk_match (c->what, toplevel_arg, conditional_p, false);
2255 /* We need to look past multiple captures to find a captured
2256 expression as with conditional converts two captures
2257 can be collapsed onto the same expression. Also collect
2258 what captures capture the same thing. */
2259 while (c->what && is_a <capture *> (c->what))
2261 c = as_a <capture *> (c->what);
2262 if (info[c->where].same_as != c->where
2263 && info[c->where].same_as != info[where].same_as)
2264 fatal_at (c->location, "cannot handle this collapsed capture");
2265 info[c->where].same_as = info[where].same_as;
2267 /* Mark expr (non-leaf) captures and forced single-use exprs. */
2268 expr *e;
2269 if (c->what
2270 && (e = dyn_cast <expr *> (c->what)))
2272 /* Zero-operand expression captures like ADDR_EXPR@0 are
2273 similar as predicates -- if they are not mentioned in
2274 the result we have to force them to have no side-effects. */
2275 if (e->ops.length () != 0)
2276 info[where].expr_p = true;
2277 info[where].force_single_use |= e->force_single_use;
2280 else if (expr *e = dyn_cast <expr *> (o))
2282 for (unsigned i = 0; i < e->ops.length (); ++i)
2284 bool cond_p = conditional_p;
2285 bool expr_cond_p = false;
2286 if (i != 0 && *e->operation == COND_EXPR)
2287 cond_p = true;
2288 else if (*e->operation == TRUTH_ANDIF_EXPR
2289 || *e->operation == TRUTH_ORIF_EXPR)
2290 cond_p = true;
2291 if (i == 0
2292 && *e->operation == COND_EXPR)
2293 expr_cond_p = true;
2294 walk_match (e->ops[i], toplevel_arg, cond_p, expr_cond_p);
2297 else if (is_a <predicate *> (o))
2299 /* Mark non-captured leafs toplevel arg for checking. */
2300 force_no_side_effects |= 1 << toplevel_arg;
2301 if (verbose >= 1
2302 && !gimple)
2303 warning_at (o->location,
2304 "forcing no side-effects on possibly lost leaf");
2306 else
2307 gcc_unreachable ();
2310 /* Analyze captures in the result expression piece O. Return true
2311 if RESULT was visited in one of the children. Only visit
2312 non-if/with children if they are rooted on RESULT. */
2314 bool
2315 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
2317 if (capture *c = dyn_cast <capture *> (o))
2319 unsigned where = info[c->where].same_as;
2320 info[where].result_use_count++;
2321 /* If we substitute an expression capture we don't know
2322 which captures this will end up using (well, we don't
2323 compute that). Force the uses to be side-effect free
2324 which means forcing the toplevels that reach the
2325 expression side-effect free. */
2326 if (info[where].expr_p)
2327 force_no_side_effects |= info[where].toplevel_msk;
2328 /* Mark CSE capture uses as forced to have no side-effects. */
2329 if (c->what
2330 && is_a <expr *> (c->what))
2332 info[where].cse_p = true;
2333 walk_result (c->what, true, result);
2336 else if (expr *e = dyn_cast <expr *> (o))
2338 id_base *opr = e->operation;
2339 if (user_id *uid = dyn_cast <user_id *> (opr))
2340 opr = uid->substitutes[0];
2341 for (unsigned i = 0; i < e->ops.length (); ++i)
2343 bool cond_p = conditional_p;
2344 if (i != 0 && *e->operation == COND_EXPR)
2345 cond_p = true;
2346 else if (*e->operation == TRUTH_ANDIF_EXPR
2347 || *e->operation == TRUTH_ORIF_EXPR)
2348 cond_p = true;
2349 walk_result (e->ops[i], cond_p, result);
2352 else if (if_expr *ie = dyn_cast <if_expr *> (o))
2354 /* 'if' conditions should be all fine. */
2355 if (ie->trueexpr == result)
2357 walk_result (ie->trueexpr, false, result);
2358 return true;
2360 if (ie->falseexpr == result)
2362 walk_result (ie->falseexpr, false, result);
2363 return true;
2365 bool res = false;
2366 if (is_a <if_expr *> (ie->trueexpr)
2367 || is_a <with_expr *> (ie->trueexpr))
2368 res |= walk_result (ie->trueexpr, false, result);
2369 if (ie->falseexpr
2370 && (is_a <if_expr *> (ie->falseexpr)
2371 || is_a <with_expr *> (ie->falseexpr)))
2372 res |= walk_result (ie->falseexpr, false, result);
2373 return res;
2375 else if (with_expr *we = dyn_cast <with_expr *> (o))
2377 bool res = (we->subexpr == result);
2378 if (res
2379 || is_a <if_expr *> (we->subexpr)
2380 || is_a <with_expr *> (we->subexpr))
2381 res |= walk_result (we->subexpr, false, result);
2382 if (res)
2383 walk_c_expr (we->with);
2384 return res;
2386 else if (c_expr *ce = dyn_cast <c_expr *> (o))
2387 walk_c_expr (ce);
2388 else
2389 gcc_unreachable ();
2391 return false;
2394 /* Look for captures in the C expr E. */
2396 void
2397 capture_info::walk_c_expr (c_expr *e)
2399 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2400 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2401 really escape through. */
2402 unsigned p_depth = 0;
2403 for (unsigned i = 0; i < e->code.length (); ++i)
2405 const cpp_token *t = &e->code[i];
2406 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2407 id_base *id;
2408 if (t->type == CPP_NAME
2409 && (strcmp ((const char *)CPP_HASHNODE
2410 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2411 || strcmp ((const char *)CPP_HASHNODE
2412 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2413 || strcmp ((const char *)CPP_HASHNODE
2414 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2415 || ((id = get_operator ((const char *)CPP_HASHNODE
2416 (t->val.node.node)->ident.str))
2417 && is_a <predicate_id *> (id)))
2418 && n->type == CPP_OPEN_PAREN)
2419 p_depth++;
2420 else if (t->type == CPP_CLOSE_PAREN
2421 && p_depth > 0)
2422 p_depth--;
2423 else if (p_depth == 0
2424 && t->type == CPP_ATSIGN
2425 && (n->type == CPP_NUMBER
2426 || n->type == CPP_NAME)
2427 && !(n->flags & PREV_WHITE))
2429 const char *id1;
2430 if (n->type == CPP_NUMBER)
2431 id1 = (const char *)n->val.str.text;
2432 else
2433 id1 = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2434 unsigned *where = e->capture_ids->get(id1);
2435 if (! where)
2436 fatal_at (n, "unknown capture id '%s'", id1);
2437 info[info[*where].same_as].force_no_side_effects_p = true;
2438 if (verbose >= 1
2439 && !gimple)
2440 warning_at (t, "capture escapes");
2446 /* The current label failing the current matched pattern during
2447 code generation. */
2448 static char *fail_label;
2450 /* Code generation off the decision tree and the refered AST nodes. */
2452 bool
2453 is_conversion (id_base *op)
2455 return (*op == CONVERT_EXPR
2456 || *op == NOP_EXPR
2457 || *op == FLOAT_EXPR
2458 || *op == FIX_TRUNC_EXPR
2459 || *op == VIEW_CONVERT_EXPR);
2462 /* Get the type to be used for generating operand POS of OP from the
2463 various sources. */
2465 static const char *
2466 get_operand_type (id_base *op, unsigned pos,
2467 const char *in_type,
2468 const char *expr_type,
2469 const char *other_oprnd_type)
2471 /* Generally operands whose type does not match the type of the
2472 expression generated need to know their types but match and
2473 thus can fall back to 'other_oprnd_type'. */
2474 if (is_conversion (op))
2475 return other_oprnd_type;
2476 else if (*op == REALPART_EXPR
2477 || *op == IMAGPART_EXPR)
2478 return other_oprnd_type;
2479 else if (is_a <operator_id *> (op)
2480 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2481 return other_oprnd_type;
2482 else if (*op == COND_EXPR
2483 && pos == 0)
2484 return "boolean_type_node";
2485 else if (startswith (op->id, "CFN_COND_"))
2487 /* IFN_COND_* operands 1 and later by default have the same type
2488 as the result. The type of operand 0 needs to be specified
2489 explicitly. */
2490 if (pos > 0 && expr_type)
2491 return expr_type;
2492 else if (pos > 0 && in_type)
2493 return in_type;
2494 else
2495 return NULL;
2497 else
2499 /* Otherwise all types should match - choose one in order of
2500 preference. */
2501 if (expr_type)
2502 return expr_type;
2503 else if (in_type)
2504 return in_type;
2505 else
2506 return other_oprnd_type;
2510 /* Generate transform code for an expression. */
2512 void
2513 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2514 int depth, const char *in_type, capture_info *cinfo,
2515 dt_operand **indexes, int)
2517 id_base *opr = operation;
2518 /* When we delay operator substituting during lowering of fors we
2519 make sure that for code-gen purposes the effects of each substitute
2520 are the same. Thus just look at that. */
2521 if (user_id *uid = dyn_cast <user_id *> (opr))
2522 opr = uid->substitutes[0];
2524 bool conversion_p = is_conversion (opr);
2525 const char *type = expr_type;
2526 char optype[64];
2527 if (type)
2528 /* If there was a type specification in the pattern use it. */
2530 else if (conversion_p)
2531 /* For conversions we need to build the expression using the
2532 outer type passed in. */
2533 type = in_type;
2534 else if (*opr == REALPART_EXPR
2535 || *opr == IMAGPART_EXPR)
2537 /* __real and __imag use the component type of its operand. */
2538 snprintf (optype, sizeof (optype), "TREE_TYPE (TREE_TYPE (_o%d[0]))",
2539 depth);
2540 type = optype;
2542 else if (is_a <operator_id *> (opr)
2543 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2545 /* comparisons use boolean_type_node (or what gets in), but
2546 their operands need to figure out the types themselves. */
2547 if (in_type)
2548 type = in_type;
2549 else
2551 snprintf (optype, sizeof (optype), "boolean_type_node");
2552 type = optype;
2554 in_type = NULL;
2556 else if (*opr == COND_EXPR
2557 || *opr == VEC_COND_EXPR
2558 || startswith (opr->id, "CFN_COND_"))
2560 /* Conditions are of the same type as their first alternative. */
2561 snprintf (optype, sizeof (optype), "TREE_TYPE (_o%d[1])", depth);
2562 type = optype;
2564 else
2566 /* Other operations are of the same type as their first operand. */
2567 snprintf (optype, sizeof (optype), "TREE_TYPE (_o%d[0])", depth);
2568 type = optype;
2570 if (!type)
2571 fatal_at (location, "cannot determine type of operand");
2573 fprintf_indent (f, indent, "{\n");
2574 indent += 2;
2575 fprintf_indent (f, indent,
2576 "tree _o%d[%u], _r%d;\n", depth, ops.length (), depth);
2577 char op0type[64];
2578 snprintf (op0type, sizeof (op0type), "TREE_TYPE (_o%d[0])", depth);
2579 for (unsigned i = 0; i < ops.length (); ++i)
2581 char dest1[32];
2582 snprintf (dest1, sizeof (dest1), "_o%d[%u]", depth, i);
2583 const char *optype1
2584 = get_operand_type (opr, i, in_type, expr_type,
2585 i == 0 ? NULL : op0type);
2586 ops[i]->gen_transform (f, indent, dest1, gimple, depth + 1, optype1,
2587 cinfo, indexes,
2588 *opr == COND_EXPR && i == 0 ? 1 : 2);
2591 const char *opr_name;
2592 if (*operation == CONVERT_EXPR)
2593 opr_name = "NOP_EXPR";
2594 else
2595 opr_name = operation->id;
2597 if (gimple)
2599 if (*opr == CONVERT_EXPR)
2601 fprintf_indent (f, indent,
2602 "if (%s != TREE_TYPE (_o%d[0])\n",
2603 type, depth);
2604 fprintf_indent (f, indent,
2605 " && !useless_type_conversion_p (%s, TREE_TYPE "
2606 "(_o%d[0])))\n",
2607 type, depth);
2608 fprintf_indent (f, indent + 2, "{\n");
2609 indent += 4;
2611 /* ??? Building a stmt can fail for various reasons here, seq being
2612 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2613 So if we fail here we should continue matching other patterns. */
2614 fprintf_indent (f, indent, "gimple_match_op tem_op "
2615 "(res_op->cond.any_else (), %s, %s", opr_name, type);
2616 for (unsigned i = 0; i < ops.length (); ++i)
2617 fprintf (f, ", _o%d[%u]", depth, i);
2618 fprintf (f, ");\n");
2619 fprintf_indent (f, indent, "tem_op.resimplify (%s, valueize);\n",
2620 !force_leaf ? "lseq" : "NULL");
2621 fprintf_indent (f, indent,
2622 "_r%d = maybe_push_res_to_seq (&tem_op, %s);\n", depth,
2623 !force_leaf ? "lseq" : "NULL");
2624 fprintf_indent (f, indent,
2625 "if (!_r%d) goto %s;\n",
2626 depth, fail_label);
2627 if (*opr == CONVERT_EXPR)
2629 indent -= 4;
2630 fprintf_indent (f, indent, " }\n");
2631 fprintf_indent (f, indent, "else\n");
2632 fprintf_indent (f, indent, " _r%d = _o%d[0];\n", depth, depth);
2635 else
2637 if (*opr == CONVERT_EXPR)
2639 fprintf_indent (f, indent, "if (TREE_TYPE (_o%d[0]) != %s)\n",
2640 depth, type);
2641 fprintf_indent (f, indent + 2, "{\n");
2642 indent += 4;
2644 if (opr->kind == id_base::CODE)
2645 fprintf_indent (f, indent, "_r%d = fold_build%d_loc (loc, %s, %s",
2646 depth, ops.length(), opr_name, type);
2647 else
2648 fprintf_indent (f, indent, "_r%d = maybe_build_call_expr_loc (loc, "
2649 "%s, %s, %d", depth, opr_name, type, ops.length());
2650 for (unsigned i = 0; i < ops.length (); ++i)
2651 fprintf (f, ", _o%d[%u]", depth, i);
2652 fprintf (f, ");\n");
2653 if (opr->kind != id_base::CODE)
2655 fprintf_indent (f, indent, "if (!_r%d)\n", depth);
2656 fprintf_indent (f, indent, " goto %s;\n", fail_label);
2658 if (force_leaf)
2660 fprintf_indent (f, indent, "if (EXPR_P (_r%d))\n", depth);
2661 fprintf_indent (f, indent, " goto %s;\n", fail_label);
2663 if (*opr == CONVERT_EXPR)
2665 fprintf_indent (f, indent - 2, "}\n");
2666 indent -= 4;
2667 fprintf_indent (f, indent, "else\n");
2668 fprintf_indent (f, indent, " _r%d = _o%d[0];\n", depth, depth);
2671 fprintf_indent (f, indent, "%s = _r%d;\n", dest, depth);
2672 indent -= 2;
2673 fprintf_indent (f, indent, "}\n");
2676 /* Generate code for a c_expr which is either the expression inside
2677 an if statement or a sequence of statements which computes a
2678 result to be stored to DEST. */
2680 void
2681 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2682 bool, int, const char *, capture_info *,
2683 dt_operand **, int)
2685 if (dest && nr_stmts == 1)
2686 fprintf_indent (f, indent, "%s = ", dest);
2688 unsigned stmt_nr = 1;
2689 int prev_line = -1;
2690 for (unsigned i = 0; i < code.length (); ++i)
2692 const cpp_token *token = &code[i];
2694 /* We can't recover from all lexing losses but we can roughly restore line
2695 breaks from location info. */
2696 const line_map_ordinary *map;
2697 linemap_resolve_location (line_table, token->src_loc,
2698 LRK_SPELLING_LOCATION, &map);
2699 expanded_location loc = linemap_expand_location (line_table, map,
2700 token->src_loc);
2701 if (prev_line != -1 && loc.line != prev_line)
2702 fputc ('\n', f);
2703 prev_line = loc.line;
2705 /* Replace captures for code-gen. */
2706 if (token->type == CPP_ATSIGN)
2708 const cpp_token *n = &code[i+1];
2709 if ((n->type == CPP_NUMBER
2710 || n->type == CPP_NAME)
2711 && !(n->flags & PREV_WHITE))
2713 if (token->flags & PREV_WHITE)
2714 fputc (' ', f);
2715 const char *id;
2716 if (n->type == CPP_NUMBER)
2717 id = (const char *)n->val.str.text;
2718 else
2719 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2720 unsigned *cid = capture_ids->get (id);
2721 if (!cid)
2722 fatal_at (token, "unknown capture id");
2723 fprintf (f, "captures[%u]", *cid);
2724 ++i;
2725 continue;
2729 if (token->flags & PREV_WHITE)
2730 fputc (' ', f);
2732 if (token->type == CPP_NAME)
2734 const char *id = (const char *) NODE_NAME (token->val.node.node);
2735 unsigned j;
2736 for (j = 0; j < ids.length (); ++j)
2738 if (strcmp (id, ids[j].id) == 0)
2740 fprintf (f, "%s", ids[j].oper);
2741 break;
2744 if (j < ids.length ())
2745 continue;
2748 /* Output the token as string. */
2749 char *tk = (char *)cpp_token_as_text (r, token);
2750 fputs (tk, f);
2752 if (token->type == CPP_SEMICOLON)
2754 stmt_nr++;
2755 if (dest && stmt_nr == nr_stmts)
2756 fprintf_indent (f, indent, "%s = ", dest);
2759 fputc ('\n', f);
2762 /* Generate transform code for a capture. */
2764 void
2765 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2766 int depth, const char *in_type, capture_info *cinfo,
2767 dt_operand **indexes, int cond_handling)
2769 if (what && is_a<expr *> (what))
2771 if (indexes[where] == 0)
2773 char buf[20];
2774 snprintf (buf, sizeof (buf), "captures[%u]", where);
2775 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2776 cinfo, NULL);
2780 /* If in GENERIC some capture is used multiple times, unshare it except
2781 when emitting the last use. */
2782 if (!gimple
2783 && cinfo->info.exists ()
2784 && cinfo->info[cinfo->info[where].same_as].result_use_count > 1)
2786 fprintf_indent (f, indent, "%s = unshare_expr (captures[%u]);\n",
2787 dest, where);
2788 cinfo->info[cinfo->info[where].same_as].result_use_count--;
2790 else
2791 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2793 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2794 with substituting a capture of that. */
2795 if (gimple
2796 && cond_handling != 0
2797 && cinfo->info[where].cond_expr_cond_p)
2799 /* If substituting into a cond_expr condition, unshare. */
2800 if (cond_handling == 1)
2801 fprintf_indent (f, indent, "%s = unshare_expr (%s);\n", dest, dest);
2802 /* If substituting elsewhere we might need to decompose it. */
2803 else if (cond_handling == 2)
2805 /* ??? Returning false here will also not allow any other patterns
2806 to match unless this generator was split out. */
2807 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2808 fprintf_indent (f, indent, " {\n");
2809 fprintf_indent (f, indent, " if (!seq) return false;\n");
2810 fprintf_indent (f, indent, " %s = gimple_build (seq,"
2811 " TREE_CODE (%s),"
2812 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2813 " TREE_OPERAND (%s, 1));\n",
2814 dest, dest, dest, dest, dest);
2815 fprintf_indent (f, indent, " }\n");
2820 /* Return the name of the operand representing the decision tree node.
2821 Use NAME as space to generate it. */
2823 char *
2824 dt_operand::get_name (char *name)
2826 if (! parent)
2827 sprintf (name, "t");
2828 else if (parent->level == 1)
2829 sprintf (name, "_p%u", pos);
2830 else if (parent->type == dt_node::DT_MATCH)
2831 return as_a <dt_operand *> (parent)->get_name (name);
2832 else
2833 sprintf (name, "_q%u%u", parent->level, pos);
2834 return name;
2837 /* Fill NAME with the operand name at position POS. */
2839 void
2840 dt_operand::gen_opname (char *name, unsigned pos)
2842 if (! parent)
2843 sprintf (name, "_p%u", pos);
2844 else
2845 sprintf (name, "_q%u%u", level, pos);
2848 /* Generate matching code for the decision tree operand which is
2849 a predicate. */
2851 unsigned
2852 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2854 predicate *p = as_a <predicate *> (op);
2856 if (p->p->matchers.exists ())
2858 /* If this is a predicate generated from a pattern mangle its
2859 name and pass on the valueize hook. */
2860 if (gimple)
2861 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2862 p->p->id, opname);
2863 else
2864 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2866 else
2867 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2868 fprintf_indent (f, indent + 2, "{\n");
2869 return 1;
2872 /* Generate matching code for the decision tree operand which is
2873 a capture-match. */
2875 unsigned
2876 dt_operand::gen_match_op (FILE *f, int indent, const char *opname, bool)
2878 char match_opname[20];
2879 match_dop->get_name (match_opname);
2880 if (value_match)
2881 fprintf_indent (f, indent, "if ((%s == %s && ! TREE_SIDE_EFFECTS (%s)) "
2882 "|| operand_equal_p (%s, %s, 0))\n",
2883 opname, match_opname, opname, opname, match_opname);
2884 else
2885 fprintf_indent (f, indent, "if ((%s == %s && ! TREE_SIDE_EFFECTS (%s)) "
2886 "|| (operand_equal_p (%s, %s, 0) "
2887 "&& types_match (%s, %s)))\n",
2888 opname, match_opname, opname, opname, match_opname,
2889 opname, match_opname);
2890 fprintf_indent (f, indent + 2, "{\n");
2891 return 1;
2894 /* Generate GIMPLE matching code for the decision tree operand. */
2896 unsigned
2897 dt_operand::gen_gimple_expr (FILE *f, int indent, int depth)
2899 expr *e = static_cast<expr *> (op);
2900 id_base *id = e->operation;
2901 unsigned n_ops = e->ops.length ();
2902 unsigned n_braces = 0;
2904 if (user_id *u = dyn_cast <user_id *> (id))
2905 id = u->substitutes[0];
2907 for (unsigned i = 0; i < n_ops; ++i)
2909 char child_opname[20];
2910 gen_opname (child_opname, i);
2912 if (id->kind == id_base::CODE)
2914 if (e->is_generic
2915 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2916 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2918 /* ??? If this is a memory operation we can't (and should not)
2919 match this. The only sensible operand types are
2920 SSA names and invariants. */
2921 if (e->is_generic)
2923 char opname[20];
2924 get_name (opname);
2925 fprintf_indent (f, indent,
2926 "tree %s = TREE_OPERAND (%s, %i);\n",
2927 child_opname, opname, i);
2929 else
2930 fprintf_indent (f, indent,
2931 "tree %s = TREE_OPERAND "
2932 "(gimple_assign_rhs1 (_a%d), %i);\n",
2933 child_opname, depth, i);
2934 fprintf_indent (f, indent,
2935 "if ((TREE_CODE (%s) == SSA_NAME\n",
2936 child_opname);
2937 fprintf_indent (f, indent,
2938 " || is_gimple_min_invariant (%s)))\n",
2939 child_opname);
2940 fprintf_indent (f, indent,
2941 " {\n");
2942 indent += 4;
2943 n_braces++;
2944 fprintf_indent (f, indent,
2945 "%s = do_valueize (valueize, %s);\n",
2946 child_opname, child_opname);
2947 continue;
2949 else
2950 fprintf_indent (f, indent,
2951 "tree %s = gimple_assign_rhs%u (_a%d);\n",
2952 child_opname, i + 1, depth);
2954 else
2955 fprintf_indent (f, indent,
2956 "tree %s = gimple_call_arg (_c%d, %u);\n",
2957 child_opname, depth, i);
2958 fprintf_indent (f, indent,
2959 "%s = do_valueize (valueize, %s);\n",
2960 child_opname, child_opname);
2962 /* While the toplevel operands are canonicalized by the caller
2963 after valueizing operands of sub-expressions we have to
2964 re-canonicalize operand order. */
2965 int opno = commutative_op (id);
2966 if (opno >= 0)
2968 char child_opname0[20], child_opname1[20];
2969 gen_opname (child_opname0, opno);
2970 gen_opname (child_opname1, opno + 1);
2971 fprintf_indent (f, indent,
2972 "if (tree_swap_operands_p (%s, %s))\n",
2973 child_opname0, child_opname1);
2974 fprintf_indent (f, indent,
2975 " std::swap (%s, %s);\n",
2976 child_opname0, child_opname1);
2979 return n_braces;
2982 /* Generate GENERIC matching code for the decision tree operand. */
2984 unsigned
2985 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2987 expr *e = static_cast<expr *> (op);
2988 id_base *id = e->operation;
2989 unsigned n_ops = e->ops.length ();
2991 if (user_id *u = dyn_cast <user_id *> (id))
2992 id = u->substitutes[0];
2994 for (unsigned i = 0; i < n_ops; ++i)
2996 char child_opname[20];
2997 gen_opname (child_opname, i);
2999 if (id->kind == id_base::CODE)
3000 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
3001 child_opname, opname, i);
3002 else
3003 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
3004 child_opname, opname, i);
3007 return 0;
3010 /* Generate matching code for the children of the decision tree node. */
3012 void
3013 dt_node::gen_kids (FILE *f, int indent, bool gimple, int depth)
3015 auto_vec<dt_operand *> gimple_exprs;
3016 auto_vec<dt_operand *> generic_exprs;
3017 auto_vec<dt_operand *> fns;
3018 auto_vec<dt_operand *> generic_fns;
3019 auto_vec<dt_operand *> preds;
3020 auto_vec<dt_node *> others;
3022 for (unsigned i = 0; i < kids.length (); ++i)
3024 if (kids[i]->type == dt_node::DT_OPERAND)
3026 dt_operand *op = as_a<dt_operand *> (kids[i]);
3027 if (expr *e = dyn_cast <expr *> (op->op))
3029 if (e->ops.length () == 0
3030 /* In GIMPLE a CONSTRUCTOR always appears in a
3031 separate definition. */
3032 && (!gimple || !(*e->operation == CONSTRUCTOR)))
3034 generic_exprs.safe_push (op);
3035 /* But ADDR_EXPRs can appear directly when invariant
3036 and in a separate definition when not. */
3037 if (gimple && *e->operation == ADDR_EXPR)
3038 gimple_exprs.safe_push (op);
3040 else if (e->operation->kind == id_base::FN)
3042 if (gimple)
3043 fns.safe_push (op);
3044 else
3045 generic_fns.safe_push (op);
3047 else if (e->operation->kind == id_base::PREDICATE)
3048 preds.safe_push (op);
3049 else
3051 user_id *u = dyn_cast <user_id *> (e->operation);
3052 if (u && u->substitutes[0]->kind == id_base::FN)
3054 if (gimple)
3055 fns.safe_push (op);
3056 else
3057 generic_fns.safe_push (op);
3059 else
3061 if (gimple && !e->is_generic)
3062 gimple_exprs.safe_push (op);
3063 else
3064 generic_exprs.safe_push (op);
3068 else if (op->op->type == operand::OP_PREDICATE)
3069 others.safe_push (kids[i]);
3070 else
3071 gcc_unreachable ();
3073 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
3074 others.safe_push (kids[i]);
3075 else if (kids[i]->type == dt_node::DT_MATCH
3076 || kids[i]->type == dt_node::DT_TRUE)
3078 /* A DT_TRUE operand serves as a barrier - generate code now
3079 for what we have collected sofar.
3080 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
3081 dependent matches to get out-of-order. Generate code now
3082 for what we have collected sofar. */
3083 gen_kids_1 (f, indent, gimple, depth, gimple_exprs, generic_exprs,
3084 fns, generic_fns, preds, others);
3085 /* And output the true operand itself. */
3086 kids[i]->gen (f, indent, gimple, depth);
3087 gimple_exprs.truncate (0);
3088 generic_exprs.truncate (0);
3089 fns.truncate (0);
3090 generic_fns.truncate (0);
3091 preds.truncate (0);
3092 others.truncate (0);
3094 else
3095 gcc_unreachable ();
3098 /* Generate code for the remains. */
3099 gen_kids_1 (f, indent, gimple, depth, gimple_exprs, generic_exprs,
3100 fns, generic_fns, preds, others);
3103 /* Generate matching code for the children of the decision tree node. */
3105 void
3106 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple, int depth,
3107 const vec<dt_operand *> &gimple_exprs,
3108 const vec<dt_operand *> &generic_exprs,
3109 const vec<dt_operand *> &fns,
3110 const vec<dt_operand *> &generic_fns,
3111 const vec<dt_operand *> &preds,
3112 const vec<dt_node *> &others)
3114 char buf[128];
3115 char *kid_opname = buf;
3117 unsigned exprs_len = gimple_exprs.length ();
3118 unsigned gexprs_len = generic_exprs.length ();
3119 unsigned fns_len = fns.length ();
3120 unsigned gfns_len = generic_fns.length ();
3122 if (exprs_len || fns_len || gexprs_len || gfns_len)
3124 if (exprs_len)
3125 gimple_exprs[0]->get_name (kid_opname);
3126 else if (fns_len)
3127 fns[0]->get_name (kid_opname);
3128 else if (gfns_len)
3129 generic_fns[0]->get_name (kid_opname);
3130 else
3131 generic_exprs[0]->get_name (kid_opname);
3133 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
3134 fprintf_indent (f, indent, " {\n");
3135 indent += 2;
3138 if (exprs_len || fns_len)
3140 depth++;
3141 fprintf_indent (f, indent,
3142 "case SSA_NAME:\n");
3143 fprintf_indent (f, indent,
3144 " if (gimple *_d%d = get_def (valueize, %s))\n",
3145 depth, kid_opname);
3146 fprintf_indent (f, indent,
3147 " {\n");
3148 indent += 6;
3149 if (exprs_len)
3151 fprintf_indent (f, indent,
3152 "if (gassign *_a%d = dyn_cast <gassign *> (_d%d))\n",
3153 depth, depth);
3154 fprintf_indent (f, indent,
3155 " switch (gimple_assign_rhs_code (_a%d))\n",
3156 depth);
3157 indent += 4;
3158 fprintf_indent (f, indent, "{\n");
3159 for (unsigned i = 0; i < exprs_len; ++i)
3161 expr *e = as_a <expr *> (gimple_exprs[i]->op);
3162 if (user_id *u = dyn_cast <user_id *> (e->operation))
3164 for (auto id : u->substitutes)
3165 fprintf_indent (f, indent, "case %s:\n", id->id);
3167 else
3169 id_base *op = e->operation;
3170 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
3171 fprintf_indent (f, indent, "CASE_CONVERT:\n");
3172 else
3173 fprintf_indent (f, indent, "case %s:\n", op->id);
3175 fprintf_indent (f, indent, " {\n");
3176 gimple_exprs[i]->gen (f, indent + 4, true, depth);
3177 fprintf_indent (f, indent, " break;\n");
3178 fprintf_indent (f, indent, " }\n");
3180 fprintf_indent (f, indent, "default:;\n");
3181 fprintf_indent (f, indent, "}\n");
3182 indent -= 4;
3185 if (fns_len)
3187 fprintf_indent (f, indent,
3188 "%sif (gcall *_c%d = dyn_cast <gcall *> (_d%d))\n",
3189 exprs_len ? "else " : "", depth, depth);
3190 fprintf_indent (f, indent,
3191 " switch (gimple_call_combined_fn (_c%d))\n",
3192 depth);
3194 indent += 4;
3195 fprintf_indent (f, indent, "{\n");
3196 for (unsigned i = 0; i < fns_len; ++i)
3198 expr *e = as_a <expr *>(fns[i]->op);
3199 if (user_id *u = dyn_cast <user_id *> (e->operation))
3200 for (auto id : u->substitutes)
3201 fprintf_indent (f, indent, "case %s:\n", id->id);
3202 else
3203 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
3204 /* We need to be defensive against bogus prototypes allowing
3205 calls with not enough arguments. */
3206 fprintf_indent (f, indent,
3207 " if (gimple_call_num_args (_c%d) == %d)\n",
3208 depth, e->ops.length ());
3209 fprintf_indent (f, indent, " {\n");
3210 fns[i]->gen (f, indent + 6, true, depth);
3211 fprintf_indent (f, indent, " }\n");
3212 fprintf_indent (f, indent, " break;\n");
3215 fprintf_indent (f, indent, "default:;\n");
3216 fprintf_indent (f, indent, "}\n");
3217 indent -= 4;
3220 indent -= 6;
3221 depth--;
3222 fprintf_indent (f, indent, " }\n");
3223 /* See if there is SSA_NAME among generic_exprs and if yes, emit it
3224 here rather than in the next loop. */
3225 for (unsigned i = 0; i < generic_exprs.length (); ++i)
3227 expr *e = as_a <expr *>(generic_exprs[i]->op);
3228 id_base *op = e->operation;
3229 if (*op == SSA_NAME && (exprs_len || fns_len))
3231 fprintf_indent (f, indent + 4, "{\n");
3232 generic_exprs[i]->gen (f, indent + 6, gimple, depth);
3233 fprintf_indent (f, indent + 4, "}\n");
3237 fprintf_indent (f, indent, " break;\n");
3240 for (unsigned i = 0; i < generic_exprs.length (); ++i)
3242 expr *e = as_a <expr *>(generic_exprs[i]->op);
3243 id_base *op = e->operation;
3244 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
3245 fprintf_indent (f, indent, "CASE_CONVERT:\n");
3246 else if (*op == SSA_NAME && (exprs_len || fns_len))
3247 /* Already handled above. */
3248 continue;
3249 else
3251 if (user_id *u = dyn_cast <user_id *> (op))
3252 for (auto id : u->substitutes)
3253 fprintf_indent (f, indent, "case %s:\n", id->id);
3254 else
3255 fprintf_indent (f, indent, "case %s:\n", op->id);
3257 fprintf_indent (f, indent, " {\n");
3258 generic_exprs[i]->gen (f, indent + 4, gimple, depth);
3259 fprintf_indent (f, indent, " break;\n");
3260 fprintf_indent (f, indent, " }\n");
3263 if (gfns_len)
3265 fprintf_indent (f, indent,
3266 "case CALL_EXPR:\n");
3267 fprintf_indent (f, indent,
3268 " switch (get_call_combined_fn (%s))\n",
3269 kid_opname);
3270 fprintf_indent (f, indent,
3271 " {\n");
3272 indent += 4;
3274 for (unsigned j = 0; j < generic_fns.length (); ++j)
3276 expr *e = as_a <expr *>(generic_fns[j]->op);
3277 gcc_assert (e->operation->kind == id_base::FN);
3279 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
3280 fprintf_indent (f, indent, " if (call_expr_nargs (%s) == %d)\n"
3281 " {\n", kid_opname, e->ops.length ());
3282 generic_fns[j]->gen (f, indent + 6, false, depth);
3283 fprintf_indent (f, indent, " }\n"
3284 " break;\n");
3286 fprintf_indent (f, indent, "default:;\n");
3288 indent -= 4;
3289 fprintf_indent (f, indent, " }\n");
3290 fprintf_indent (f, indent, " break;\n");
3293 /* Close switch (TREE_CODE ()). */
3294 if (exprs_len || fns_len || gexprs_len || gfns_len)
3296 indent -= 4;
3297 fprintf_indent (f, indent, " default:;\n");
3298 fprintf_indent (f, indent, " }\n");
3301 for (unsigned i = 0; i < preds.length (); ++i)
3303 expr *e = as_a <expr *> (preds[i]->op);
3304 predicate_id *p = as_a <predicate_id *> (e->operation);
3305 preds[i]->get_name (kid_opname);
3306 fprintf_indent (f, indent, "{\n");
3307 indent += 2;
3308 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
3309 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
3310 gimple ? "gimple" : "tree",
3311 p->id, kid_opname, kid_opname,
3312 gimple ? ", valueize" : "");
3313 fprintf_indent (f, indent, " {\n");
3314 for (int j = 0; j < p->nargs; ++j)
3316 char child_opname[20];
3317 preds[i]->gen_opname (child_opname, j);
3318 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
3319 child_opname, kid_opname, j);
3321 preds[i]->gen_kids (f, indent + 4, gimple, depth);
3322 fprintf (f, "}\n");
3323 indent -= 2;
3324 fprintf_indent (f, indent, "}\n");
3327 for (unsigned i = 0; i < others.length (); ++i)
3328 others[i]->gen (f, indent, gimple, depth);
3331 /* Generate matching code for the decision tree operand. */
3333 void
3334 dt_operand::gen (FILE *f, int indent, bool gimple, int depth)
3336 char opname[20];
3337 get_name (opname);
3339 unsigned n_braces = 0;
3341 if (type == DT_OPERAND)
3342 switch (op->type)
3344 case operand::OP_PREDICATE:
3345 n_braces = gen_predicate (f, indent, opname, gimple);
3346 break;
3348 case operand::OP_EXPR:
3349 if (gimple)
3350 n_braces = gen_gimple_expr (f, indent, depth);
3351 else
3352 n_braces = gen_generic_expr (f, indent, opname);
3353 break;
3355 default:
3356 gcc_unreachable ();
3358 else if (type == DT_TRUE)
3360 else if (type == DT_MATCH)
3361 n_braces = gen_match_op (f, indent, opname, gimple);
3362 else
3363 gcc_unreachable ();
3365 indent += 4 * n_braces;
3366 gen_kids (f, indent, gimple, depth);
3368 for (unsigned i = 0; i < n_braces; ++i)
3370 indent -= 4;
3371 if (indent < 0)
3372 indent = 0;
3373 fprintf_indent (f, indent, " }\n");
3377 /* Emit a fprintf to the debug file to the file F, with the INDENT from
3378 either the RESULT location or the S's match location if RESULT is null. */
3379 static void
3380 emit_debug_printf (FILE *f, int indent, class simplify *s, operand *result)
3382 fprintf_indent (f, indent, "if (UNLIKELY (debug_dump)) "
3383 "fprintf (dump_file, \"%s ",
3384 s->kind == simplify::SIMPLIFY
3385 ? "Applying pattern" : "Matching expression");
3386 fprintf (f, "%%s:%%d, %%s:%%d\\n\", ");
3387 output_line_directive (f,
3388 result ? result->location : s->match->location, true,
3389 true);
3390 fprintf (f, ", __FILE__, __LINE__);\n");
3393 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3394 step of a '(simplify ...)' or '(match ...)'. This handles everything
3395 that is not part of the decision tree (simplify->match).
3396 Main recursive worker. */
3398 void
3399 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
3401 if (result)
3403 if (with_expr *w = dyn_cast <with_expr *> (result))
3405 fprintf_indent (f, indent, "{\n");
3406 indent += 4;
3407 output_line_directive (f, w->location);
3408 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3409 gen_1 (f, indent, gimple, w->subexpr);
3410 indent -= 4;
3411 fprintf_indent (f, indent, "}\n");
3412 return;
3414 else if (if_expr *ife = dyn_cast <if_expr *> (result))
3416 output_line_directive (f, ife->location);
3417 fprintf_indent (f, indent, "if (");
3418 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3419 fprintf (f, ")\n");
3420 fprintf_indent (f, indent + 2, "{\n");
3421 indent += 4;
3422 gen_1 (f, indent, gimple, ife->trueexpr);
3423 indent -= 4;
3424 fprintf_indent (f, indent + 2, "}\n");
3425 if (ife->falseexpr)
3427 fprintf_indent (f, indent, "else\n");
3428 fprintf_indent (f, indent + 2, "{\n");
3429 indent += 4;
3430 gen_1 (f, indent, gimple, ife->falseexpr);
3431 indent -= 4;
3432 fprintf_indent (f, indent + 2, "}\n");
3434 return;
3438 static unsigned fail_label_cnt;
3439 char local_fail_label[256];
3440 snprintf (local_fail_label, 256, "next_after_fail%u", ++fail_label_cnt);
3441 fail_label = local_fail_label;
3442 bool needs_label = false;
3444 /* Analyze captures and perform early-outs on the incoming arguments
3445 that cover cases we cannot handle. */
3446 capture_info cinfo (s, result, gimple);
3447 if (s->kind == simplify::SIMPLIFY)
3449 if (!gimple)
3451 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3452 if (cinfo.force_no_side_effects & (1 << i))
3454 fprintf_indent (f, indent,
3455 "if (TREE_SIDE_EFFECTS (_p%d)) goto %s;\n",
3456 i, fail_label);
3457 needs_label = true;
3458 if (verbose >= 1)
3459 warning_at (as_a <expr *> (s->match)->ops[i]->location,
3460 "forcing toplevel operand to have no "
3461 "side-effects");
3463 for (int i = 0; i <= s->capture_max; ++i)
3464 if (cinfo.info[i].cse_p)
3466 else if (cinfo.info[i].force_no_side_effects_p
3467 && (cinfo.info[i].toplevel_msk
3468 & cinfo.force_no_side_effects) == 0)
3470 fprintf_indent (f, indent,
3471 "if (TREE_SIDE_EFFECTS (captures[%d])) "
3472 "goto %s;\n", i, fail_label);
3473 needs_label = true;
3474 if (verbose >= 1)
3475 warning_at (cinfo.info[i].c->location,
3476 "forcing captured operand to have no "
3477 "side-effects");
3479 else if ((cinfo.info[i].toplevel_msk
3480 & cinfo.force_no_side_effects) != 0)
3481 /* Mark capture as having no side-effects if we had to verify
3482 that via forced toplevel operand checks. */
3483 cinfo.info[i].force_no_side_effects_p = true;
3485 if (gimple)
3487 /* Force single-use restriction by only allowing simple
3488 results via setting seq to NULL. */
3489 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
3490 bool first_p = true;
3491 for (int i = 0; i <= s->capture_max; ++i)
3492 if (cinfo.info[i].force_single_use)
3494 if (first_p)
3496 fprintf_indent (f, indent, "if (lseq\n");
3497 fprintf_indent (f, indent, " && (");
3498 first_p = false;
3500 else
3502 fprintf (f, "\n");
3503 fprintf_indent (f, indent, " || ");
3505 fprintf (f, "!single_use (captures[%d])", i);
3507 if (!first_p)
3509 fprintf (f, "))\n");
3510 fprintf_indent (f, indent, " lseq = NULL;\n");
3515 if (s->kind == simplify::SIMPLIFY)
3517 fprintf_indent (f, indent, "if (UNLIKELY (!dbg_cnt (match))) goto %s;\n", fail_label);
3518 needs_label = true;
3521 fprintf_indent (f, indent, "{\n");
3522 indent += 2;
3523 if (!result)
3525 /* If there is no result then this is a predicate implementation. */
3526 emit_debug_printf (f, indent, s, result);
3527 fprintf_indent (f, indent, "return true;\n");
3529 else if (gimple)
3531 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3532 in outermost position). */
3533 if (result->type == operand::OP_EXPR
3534 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3535 result = as_a <expr *> (result)->ops[0];
3536 if (result->type == operand::OP_EXPR)
3538 expr *e = as_a <expr *> (result);
3539 id_base *opr = e->operation;
3540 bool is_predicate = false;
3541 /* When we delay operator substituting during lowering of fors we
3542 make sure that for code-gen purposes the effects of each substitute
3543 are the same. Thus just look at that. */
3544 if (user_id *uid = dyn_cast <user_id *> (opr))
3545 opr = uid->substitutes[0];
3546 else if (is_a <predicate_id *> (opr))
3547 is_predicate = true;
3548 if (!is_predicate)
3549 fprintf_indent (f, indent, "res_op->set_op (%s, type, %d);\n",
3550 *e->operation == CONVERT_EXPR
3551 ? "NOP_EXPR" : e->operation->id,
3552 e->ops.length ());
3553 for (unsigned j = 0; j < e->ops.length (); ++j)
3555 char dest[32];
3556 if (is_predicate)
3557 snprintf (dest, sizeof (dest), "res_ops[%d]", j);
3558 else
3559 snprintf (dest, sizeof (dest), "res_op->ops[%d]", j);
3560 const char *optype
3561 = get_operand_type (opr, j,
3562 "type", e->expr_type,
3563 j == 0 ? NULL
3564 : "TREE_TYPE (res_op->ops[0])");
3565 /* We need to expand GENERIC conditions we captured from
3566 COND_EXPRs and we need to unshare them when substituting
3567 into COND_EXPRs. */
3568 int cond_handling = 0;
3569 if (!is_predicate)
3570 cond_handling = (*opr == COND_EXPR && j == 0) ? 1 : 2;
3571 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3572 &cinfo, indexes, cond_handling);
3575 /* Re-fold the toplevel result. It's basically an embedded
3576 gimple_build w/o actually building the stmt. */
3577 if (!is_predicate)
3579 fprintf_indent (f, indent,
3580 "res_op->resimplify (%s, valueize);\n",
3581 !e->force_leaf ? "lseq" : "NULL");
3582 if (e->force_leaf)
3584 fprintf_indent (f, indent,
3585 "if (!maybe_push_res_to_seq (res_op, NULL)) "
3586 "goto %s;\n", fail_label);
3587 needs_label = true;
3591 else if (result->type == operand::OP_CAPTURE
3592 || result->type == operand::OP_C_EXPR)
3594 fprintf_indent (f, indent, "tree tem;\n");
3595 result->gen_transform (f, indent, "tem", true, 1, "type",
3596 &cinfo, indexes);
3597 fprintf_indent (f, indent, "res_op->set_value (tem);\n");
3598 if (is_a <capture *> (result)
3599 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3601 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3602 with substituting a capture of that. */
3603 fprintf_indent (f, indent,
3604 "if (COMPARISON_CLASS_P (tem))\n");
3605 fprintf_indent (f, indent,
3606 " {\n");
3607 fprintf_indent (f, indent,
3608 " res_op->ops[0] = TREE_OPERAND (tem, 0);\n");
3609 fprintf_indent (f, indent,
3610 " res_op->ops[1] = TREE_OPERAND (tem, 1);\n");
3611 fprintf_indent (f, indent,
3612 " }\n");
3615 else
3616 gcc_unreachable ();
3617 emit_debug_printf (f, indent, s, result);
3618 fprintf_indent (f, indent, "return true;\n");
3620 else /* GENERIC */
3622 bool is_predicate = false;
3623 if (result->type == operand::OP_EXPR)
3625 expr *e = as_a <expr *> (result);
3626 id_base *opr = e->operation;
3627 /* When we delay operator substituting during lowering of fors we
3628 make sure that for code-gen purposes the effects of each substitute
3629 are the same. Thus just look at that. */
3630 if (user_id *uid = dyn_cast <user_id *> (opr))
3631 opr = uid->substitutes[0];
3632 else if (is_a <predicate_id *> (opr))
3633 is_predicate = true;
3634 /* Search for captures used multiple times in the result expression
3635 and wrap them in a SAVE_EXPR. Allow as many uses as in the
3636 original expression. */
3637 if (!is_predicate)
3638 for (int i = 0; i < s->capture_max + 1; ++i)
3640 if (cinfo.info[i].same_as != (unsigned)i
3641 || cinfo.info[i].cse_p)
3642 continue;
3643 if (cinfo.info[i].result_use_count
3644 > cinfo.info[i].match_use_count)
3646 fprintf_indent (f, indent,
3647 "if (! tree_invariant_p (captures[%d])) "
3648 "goto %s;\n", i, fail_label);
3649 needs_label = true;
3652 for (unsigned j = 0; j < e->ops.length (); ++j)
3654 char dest[32];
3655 if (is_predicate)
3656 snprintf (dest, sizeof (dest), "res_ops[%d]", j);
3657 else
3659 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3660 snprintf (dest, sizeof (dest), "res_op%d", j);
3662 const char *optype
3663 = get_operand_type (opr, j,
3664 "type", e->expr_type,
3665 j == 0
3666 ? NULL : "TREE_TYPE (res_op0)");
3667 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3668 &cinfo, indexes);
3670 if (is_predicate)
3672 emit_debug_printf (f, indent, s, result);
3673 fprintf_indent (f, indent, "return true;\n");
3675 else
3677 fprintf_indent (f, indent, "tree _r;\n");
3678 /* Re-fold the toplevel result. Use non_lvalue to
3679 build NON_LVALUE_EXPRs so they get properly
3680 ignored when in GIMPLE form. */
3681 if (*opr == NON_LVALUE_EXPR)
3682 fprintf_indent (f, indent,
3683 "_r = non_lvalue_loc (loc, res_op0);\n");
3684 else
3686 if (is_a <operator_id *> (opr))
3687 fprintf_indent (f, indent,
3688 "_r = fold_build%d_loc (loc, %s, type",
3689 e->ops.length (),
3690 *e->operation == CONVERT_EXPR
3691 ? "NOP_EXPR" : e->operation->id);
3692 else
3693 fprintf_indent (f, indent,
3694 "_r = maybe_build_call_expr_loc (loc, "
3695 "%s, type, %d", e->operation->id,
3696 e->ops.length());
3697 for (unsigned j = 0; j < e->ops.length (); ++j)
3698 fprintf (f, ", res_op%d", j);
3699 fprintf (f, ");\n");
3700 if (!is_a <operator_id *> (opr))
3702 fprintf_indent (f, indent, "if (!_r)\n");
3703 fprintf_indent (f, indent, " goto %s;\n", fail_label);
3704 needs_label = true;
3709 else if (result->type == operand::OP_CAPTURE
3710 || result->type == operand::OP_C_EXPR)
3713 fprintf_indent (f, indent, "tree _r;\n");
3714 result->gen_transform (f, indent, "_r", false, 1, "type",
3715 &cinfo, indexes);
3717 else
3718 gcc_unreachable ();
3719 if (!is_predicate)
3721 /* Search for captures not used in the result expression and dependent
3722 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3723 for (int i = 0; i < s->capture_max + 1; ++i)
3725 if (cinfo.info[i].same_as != (unsigned)i)
3726 continue;
3727 if (!cinfo.info[i].force_no_side_effects_p
3728 && !cinfo.info[i].expr_p
3729 && cinfo.info[i].result_use_count == 0)
3731 fprintf_indent (f, indent,
3732 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3734 fprintf_indent (f, indent + 2,
3735 "_r = build2_loc (loc, COMPOUND_EXPR, type, "
3736 "fold_ignored_result (captures[%d]), _r);\n",
3740 emit_debug_printf (f, indent, s, result);
3741 fprintf_indent (f, indent, "return _r;\n");
3744 indent -= 2;
3745 fprintf_indent (f, indent, "}\n");
3746 if (needs_label)
3747 fprintf (f, "%s:;\n", fail_label);
3748 fail_label = NULL;
3751 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3752 step of a '(simplify ...)' or '(match ...)'. This handles everything
3753 that is not part of the decision tree (simplify->match). */
3755 void
3756 dt_simplify::gen (FILE *f, int indent, bool gimple, int depth ATTRIBUTE_UNUSED)
3758 fprintf_indent (f, indent, "{\n");
3759 indent += 2;
3760 output_line_directive (f,
3761 s->result ? s->result->location : s->match->location);
3762 if (s->capture_max >= 0)
3764 char opname[20];
3765 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3766 s->capture_max + 1, indexes[0]->get_name (opname));
3768 for (int i = 1; i <= s->capture_max; ++i)
3770 if (!indexes[i])
3771 break;
3772 fprintf (f, ", %s", indexes[i]->get_name (opname));
3774 fprintf (f, " };\n");
3777 /* If we have a split-out function for the actual transform, call it. */
3778 if (info && info->fname)
3780 if (gimple)
3782 fprintf_indent (f, indent, "if (%s (res_op, seq, "
3783 "valueize, type, captures", info->fname);
3784 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3785 if (s->for_subst_vec[i].first->used)
3786 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3787 fprintf (f, "))\n");
3788 fprintf_indent (f, indent, " return true;\n");
3790 else
3792 fprintf_indent (f, indent, "tree res = %s (loc, type",
3793 info->fname);
3794 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3795 fprintf (f, ", _p%d", i);
3796 fprintf (f, ", captures");
3797 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3799 if (s->for_subst_vec[i].first->used)
3800 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3802 fprintf (f, ");\n");
3803 fprintf_indent (f, indent, "if (res) return res;\n");
3806 else
3808 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3810 if (! s->for_subst_vec[i].first->used)
3811 continue;
3812 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3813 fprintf_indent (f, indent, "const enum tree_code %s = %s;\n",
3814 s->for_subst_vec[i].first->id,
3815 s->for_subst_vec[i].second->id);
3816 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3817 fprintf_indent (f, indent, "const combined_fn %s = %s;\n",
3818 s->for_subst_vec[i].first->id,
3819 s->for_subst_vec[i].second->id);
3820 else
3821 gcc_unreachable ();
3823 gen_1 (f, indent, gimple, s->result);
3826 indent -= 2;
3827 fprintf_indent (f, indent, "}\n");
3831 /* Hash function for finding equivalent transforms. */
3833 hashval_t
3834 sinfo_hashmap_traits::hash (const key_type &v)
3836 /* Only bother to compare those originating from the same source pattern. */
3837 return v->s->result->location;
3840 /* Compare function for finding equivalent transforms. */
3842 static bool
3843 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3845 if (o1->type != o2->type)
3846 return false;
3848 switch (o1->type)
3850 case operand::OP_IF:
3852 if_expr *if1 = as_a <if_expr *> (o1);
3853 if_expr *if2 = as_a <if_expr *> (o2);
3854 /* ??? Properly compare c-exprs. */
3855 if (if1->cond != if2->cond)
3856 return false;
3857 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3858 return false;
3859 if (if1->falseexpr != if2->falseexpr
3860 || (if1->falseexpr
3861 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3862 return false;
3863 return true;
3865 case operand::OP_WITH:
3867 with_expr *with1 = as_a <with_expr *> (o1);
3868 with_expr *with2 = as_a <with_expr *> (o2);
3869 if (with1->with != with2->with)
3870 return false;
3871 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3873 default:;
3876 /* We've hit a result. Time to compare capture-infos - this is required
3877 in addition to the conservative pointer-equivalency of the result IL. */
3878 capture_info cinfo1 (s1, o1, true);
3879 capture_info cinfo2 (s2, o2, true);
3881 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3882 || cinfo1.info.length () != cinfo2.info.length ())
3883 return false;
3885 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3887 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3888 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3889 || (cinfo1.info[i].force_no_side_effects_p
3890 != cinfo2.info[i].force_no_side_effects_p)
3891 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3892 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3893 /* toplevel_msk is an optimization */
3894 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3895 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3896 /* the pointer back to the capture is for diagnostics only */)
3897 return false;
3900 /* ??? Deep-compare the actual result. */
3901 return o1 == o2;
3904 bool
3905 sinfo_hashmap_traits::equal_keys (const key_type &v,
3906 const key_type &candidate)
3908 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3912 /* Main entry to generate code for matching GIMPLE IL off the decision
3913 tree. */
3915 void
3916 decision_tree::gen (vec <FILE *> &files, bool gimple)
3918 sinfo_map_t si;
3920 root->analyze (si);
3922 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3923 "a total number of %u nodes\n",
3924 gimple ? "GIMPLE" : "GENERIC",
3925 root->num_leafs, root->max_level, root->total_size);
3927 /* First split out the transform part of equal leafs. */
3928 unsigned rcnt = 0;
3929 unsigned fcnt = 1;
3930 for (sinfo_map_t::iterator iter = si.begin ();
3931 iter != si.end (); ++iter)
3933 sinfo *s = (*iter).second;
3934 /* Do not split out single uses. */
3935 if (s->cnt <= 1)
3936 continue;
3938 rcnt += s->cnt - 1;
3939 if (verbose >= 1)
3941 fprintf (stderr, "found %u uses of", s->cnt);
3942 output_line_directive (stderr, s->s->s->result->location);
3945 /* Cycle the file buffers. */
3946 FILE *f = choose_output (files);
3948 /* Generate a split out function with the leaf transform code. */
3949 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3950 fcnt++);
3951 if (gimple)
3952 fp_decl (f, "\nbool\n"
3953 "%s (gimple_match_op *res_op, gimple_seq *seq,\n"
3954 " tree (*valueize)(tree) ATTRIBUTE_UNUSED,\n"
3955 " const tree ARG_UNUSED (type), tree *ARG_UNUSED "
3956 "(captures)",
3957 s->fname);
3958 else
3960 fp_decl (f, "\ntree\n"
3961 "%s (location_t ARG_UNUSED (loc), const tree ARG_UNUSED (type),\n",
3962 (*iter).second->fname);
3963 for (unsigned i = 0;
3964 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3965 fp_decl (f, " tree ARG_UNUSED (_p%d),", i);
3966 fp_decl (f, " tree *captures");
3968 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3970 if (! s->s->s->for_subst_vec[i].first->used)
3971 continue;
3972 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3973 fp_decl (f, ",\n const enum tree_code ARG_UNUSED (%s)",
3974 s->s->s->for_subst_vec[i].first->id);
3975 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3976 fp_decl (f, ",\n const combined_fn ARG_UNUSED (%s)",
3977 s->s->s->for_subst_vec[i].first->id);
3980 fp_decl_done (f, ")");
3981 fprintf (f, "{\n");
3982 fprintf_indent (f, 2, "const bool debug_dump = "
3983 "dump_file && (dump_flags & TDF_FOLDING);\n");
3984 s->s->gen_1 (f, 2, gimple, s->s->s->result);
3985 if (gimple)
3986 fprintf (f, " return false;\n");
3987 else
3988 fprintf (f, " return NULL_TREE;\n");
3989 fprintf (f, "}\n");
3991 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3993 for (unsigned n = 1; n <= 5; ++n)
3995 bool has_kids_p = false;
3997 /* First generate split-out functions. */
3998 for (unsigned j = 0; j < root->kids.length (); j++)
4000 dt_operand *dop = static_cast<dt_operand *>(root->kids[j]);
4001 expr *e = static_cast<expr *>(dop->op);
4002 if (e->ops.length () != n
4003 /* Builtin simplifications are somewhat premature on
4004 GENERIC. The following drops patterns with outermost
4005 calls. It's easy to emit overloads for function code
4006 though if necessary. */
4007 || (!gimple
4008 && e->operation->kind != id_base::CODE))
4009 continue;
4012 /* Cycle the file buffers. */
4013 FILE *f = choose_output (files);
4015 if (gimple)
4016 fp_decl (f, "\nbool\n"
4017 "gimple_simplify_%s (gimple_match_op *res_op,"
4018 " gimple_seq *seq,\n"
4019 " tree (*valueize)(tree) "
4020 "ATTRIBUTE_UNUSED,\n"
4021 " code_helper ARG_UNUSED (code), tree "
4022 "ARG_UNUSED (type)",
4023 e->operation->id);
4024 else
4025 fp_decl (f, "\ntree\n"
4026 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
4027 "tree_code ARG_UNUSED (code), const tree ARG_UNUSED (type)",
4028 e->operation->id);
4029 for (unsigned i = 0; i < n; ++i)
4030 fp_decl (f, ", tree _p%d", i);
4031 fp_decl_done (f, ")");
4032 fprintf (f, "{\n");
4033 fprintf_indent (f, 2, "const bool debug_dump = "
4034 "dump_file && (dump_flags & TDF_FOLDING);\n");
4035 dop->gen_kids (f, 2, gimple, 0);
4036 if (gimple)
4037 fprintf (f, " return false;\n");
4038 else
4039 fprintf (f, " return NULL_TREE;\n");
4040 fprintf (f, "}\n");
4041 has_kids_p = true;
4044 /* If this main entry has no children, avoid generating code
4045 with compiler warnings, by generating a simple stub. */
4046 if (! has_kids_p)
4049 /* Cycle the file buffers. */
4050 FILE *f = choose_output (files);
4052 if (gimple)
4053 fp_decl (f, "\nbool\n"
4054 "gimple_simplify (gimple_match_op*, gimple_seq*,\n"
4055 " tree (*)(tree), code_helper,\n"
4056 " const tree");
4057 else
4058 fp_decl (f, "\ntree\n"
4059 "generic_simplify (location_t, enum tree_code,\n"
4060 " const tree");
4061 for (unsigned i = 0; i < n; ++i)
4062 fp_decl (f, ", tree");
4063 fp_decl_done (f, ")");
4064 fprintf (f, "{\n");
4065 if (gimple)
4066 fprintf (f, " return false;\n");
4067 else
4068 fprintf (f, " return NULL_TREE;\n");
4069 fprintf (f, "}\n");
4070 continue;
4074 /* Cycle the file buffers. */
4075 FILE *f = choose_output (files);
4077 /* Then generate the main entry with the outermost switch and
4078 tail-calls to the split-out functions. */
4079 if (gimple)
4080 fp_decl (f, "\nbool\n"
4081 "gimple_simplify (gimple_match_op *res_op, gimple_seq *seq,\n"
4082 " tree (*valueize)(tree) ATTRIBUTE_UNUSED,\n"
4083 " code_helper code, const tree type");
4084 else
4085 fp_decl (f, "\ntree\n"
4086 "generic_simplify (location_t loc, enum tree_code code, "
4087 "const tree type ATTRIBUTE_UNUSED");
4088 for (unsigned i = 0; i < n; ++i)
4089 fp_decl (f, ", tree _p%d", i);
4090 fp_decl_done (f, ")");
4091 fprintf (f, "{\n");
4093 if (gimple)
4094 fprintf (f, " switch (code.get_rep())\n"
4095 " {\n");
4096 else
4097 fprintf (f, " switch (code)\n"
4098 " {\n");
4099 for (unsigned i = 0; i < root->kids.length (); i++)
4101 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
4102 expr *e = static_cast<expr *>(dop->op);
4103 if (e->ops.length () != n
4104 /* Builtin simplifications are somewhat premature on
4105 GENERIC. The following drops patterns with outermost
4106 calls. It's easy to emit overloads for function code
4107 though if necessary. */
4108 || (!gimple
4109 && e->operation->kind != id_base::CODE))
4110 continue;
4112 if (*e->operation == CONVERT_EXPR
4113 || *e->operation == NOP_EXPR)
4114 fprintf (f, " CASE_CONVERT:\n");
4115 else
4116 fprintf (f, " case %s%s:\n",
4117 is_a <fn_id *> (e->operation) ? "-" : "",
4118 e->operation->id);
4119 if (gimple)
4120 fprintf (f, " return gimple_simplify_%s (res_op, "
4121 "seq, valueize, code, type", e->operation->id);
4122 else
4123 fprintf (f, " return generic_simplify_%s (loc, code, type",
4124 e->operation->id);
4125 for (unsigned j = 0; j < n; ++j)
4126 fprintf (f, ", _p%d", j);
4127 fprintf (f, ");\n");
4129 fprintf (f, " default:;\n"
4130 " }\n");
4132 if (gimple)
4133 fprintf (f, " return false;\n");
4134 else
4135 fprintf (f, " return NULL_TREE;\n");
4136 fprintf (f, "}\n");
4140 /* Output code to implement the predicate P from the decision tree DT. */
4142 void
4143 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
4145 fp_decl (f, "\nbool\n%s%s (tree t%s%s)",
4146 gimple ? "gimple_" : "tree_", p->id,
4147 p->nargs > 0 ? ", tree *res_ops" : "",
4148 gimple ? ", tree (*valueize)(tree) ATTRIBUTE_UNUSED" : "");
4149 fp_decl_done (f, "");
4150 fprintf (f, "{\n");
4151 /* Conveniently make 'type' available. */
4152 fprintf_indent (f, 2, "const tree type = TREE_TYPE (t);\n");
4153 fprintf_indent (f, 2, "const bool debug_dump = "
4154 "dump_file && (dump_flags & TDF_FOLDING);\n");
4156 if (!gimple)
4157 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
4158 dt.root->gen_kids (f, 2, gimple, 0);
4160 fprintf_indent (f, 2, "return false;\n"
4161 "}\n");
4164 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
4166 static void
4167 write_header (FILE *f, const char *head)
4169 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
4170 fprintf (f, " a IL pattern matching and simplification description. */\n");
4171 fprintf (f, "#pragma GCC diagnostic push\n");
4172 fprintf (f, "#pragma GCC diagnostic ignored \"-Wunused-variable\"\n");
4173 fprintf (f, "#pragma GCC diagnostic ignored \"-Wunused-function\"\n");
4175 /* Include the header instead of writing it awkwardly quoted here. */
4176 if (head)
4177 fprintf (f, "\n#include \"%s\"\n", head);
4182 /* AST parsing. */
4184 class parser
4186 public:
4187 parser (cpp_reader *, bool gimple);
4189 private:
4190 const cpp_token *next ();
4191 const cpp_token *peek (unsigned = 1);
4192 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
4193 const cpp_token *expect (enum cpp_ttype);
4194 const cpp_token *eat_token (enum cpp_ttype);
4195 const char *get_string ();
4196 const char *get_ident ();
4197 const cpp_token *eat_ident (const char *);
4198 const char *get_number ();
4200 unsigned get_internal_capture_id ();
4202 id_base *parse_operation (unsigned char &);
4203 operand *parse_capture (operand *, bool);
4204 operand *parse_expr ();
4205 c_expr *parse_c_expr (cpp_ttype);
4206 operand *parse_op ();
4208 void record_operlist (location_t, user_id *);
4210 void parse_pattern ();
4211 operand *parse_result (operand *, predicate_id *);
4212 void push_simplify (simplify::simplify_kind,
4213 vec<simplify *>&, operand *, operand *);
4214 void parse_simplify (simplify::simplify_kind,
4215 vec<simplify *>&, predicate_id *, operand *);
4216 void parse_for (location_t);
4217 void parse_if (location_t);
4218 void parse_predicates (location_t);
4219 void parse_operator_list (location_t);
4221 void finish_match_operand (operand *);
4223 cpp_reader *r;
4224 bool gimple;
4225 vec<c_expr *> active_ifs;
4226 vec<vec<user_id *> > active_fors;
4227 hash_set<user_id *> *oper_lists_set;
4228 vec<user_id *> oper_lists;
4230 cid_map_t *capture_ids;
4231 unsigned last_id;
4233 public:
4234 vec<simplify *> simplifiers;
4235 vec<predicate_id *> user_predicates;
4236 bool parsing_match_operand;
4239 /* Lexing helpers. */
4241 /* Read the next non-whitespace token from R. */
4243 const cpp_token *
4244 parser::next ()
4246 const cpp_token *token;
4249 token = cpp_get_token (r);
4251 while (token->type == CPP_PADDING);
4252 return token;
4255 /* Peek at the next non-whitespace token from R. */
4257 const cpp_token *
4258 parser::peek (unsigned num)
4260 const cpp_token *token;
4261 unsigned i = 0;
4264 token = cpp_peek_token (r, i++);
4266 while (token->type == CPP_PADDING
4267 || (--num > 0));
4268 /* If we peek at EOF this is a fatal error as it leaves the
4269 cpp_reader in unusable state. Assume we really wanted a
4270 token and thus this EOF is unexpected. */
4271 if (token->type == CPP_EOF)
4272 fatal_at (token, "unexpected end of file");
4273 return token;
4276 /* Peek at the next identifier token (or return NULL if the next
4277 token is not an identifier or equal to ID if supplied). */
4279 const cpp_token *
4280 parser::peek_ident (const char *id, unsigned num)
4282 const cpp_token *token = peek (num);
4283 if (token->type != CPP_NAME)
4284 return 0;
4286 if (id == 0)
4287 return token;
4289 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
4290 if (strcmp (id, t) == 0)
4291 return token;
4293 return 0;
4296 /* Read the next token from R and assert it is of type TK. */
4298 const cpp_token *
4299 parser::expect (enum cpp_ttype tk)
4301 const cpp_token *token = next ();
4302 if (token->type != tk)
4303 fatal_at (token, "expected %s, got %s",
4304 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
4306 return token;
4309 /* Consume the next token from R and assert it is of type TK. */
4311 const cpp_token *
4312 parser::eat_token (enum cpp_ttype tk)
4314 return expect (tk);
4317 /* Read the next token from R and assert it is of type CPP_STRING and
4318 return its value. */
4320 const char *
4321 parser::get_string ()
4323 const cpp_token *token = expect (CPP_STRING);
4324 return (const char *)token->val.str.text;
4327 /* Read the next token from R and assert it is of type CPP_NAME and
4328 return its value. */
4330 const char *
4331 parser::get_ident ()
4333 const cpp_token *token = expect (CPP_NAME);
4334 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
4337 /* Eat an identifier token with value S from R. */
4339 const cpp_token *
4340 parser::eat_ident (const char *s)
4342 const cpp_token *token = peek ();
4343 const char *t = get_ident ();
4344 if (strcmp (s, t) != 0)
4345 fatal_at (token, "expected '%s' got '%s'\n", s, t);
4346 return token;
4349 /* Read the next token from R and assert it is of type CPP_NUMBER and
4350 return its value. */
4352 const char *
4353 parser::get_number ()
4355 const cpp_token *token = expect (CPP_NUMBER);
4356 return (const char *)token->val.str.text;
4359 /* Return a capture ID that can be used internally. */
4361 unsigned
4362 parser::get_internal_capture_id ()
4364 unsigned newid = capture_ids->elements ();
4365 /* Big enough for a 32-bit UINT_MAX plus prefix. */
4366 char id[13];
4367 bool existed;
4368 snprintf (id, sizeof (id), "__%u", newid);
4369 capture_ids->get_or_insert (xstrdup (id), &existed);
4370 if (existed)
4371 fatal ("reserved capture id '%s' already used", id);
4372 return newid;
4375 /* Record an operator-list use for transparent for handling. */
4377 void
4378 parser::record_operlist (location_t loc, user_id *p)
4380 if (!oper_lists_set->add (p))
4382 if (!oper_lists.is_empty ()
4383 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
4384 fatal_at (loc, "User-defined operator list does not have the "
4385 "same number of entries as others used in the pattern");
4386 oper_lists.safe_push (p);
4390 /* Parse the operator ID, special-casing convert?, convert1? and
4391 convert2? */
4393 id_base *
4394 parser::parse_operation (unsigned char &opt_grp)
4396 const cpp_token *id_tok = peek ();
4397 char *alt_id = NULL;
4398 const char *id = get_ident ();
4399 const cpp_token *token = peek ();
4400 opt_grp = 0;
4401 if (token->type == CPP_QUERY
4402 && !(token->flags & PREV_WHITE))
4404 if (!parsing_match_operand)
4405 fatal_at (id_tok, "conditional convert can only be used in "
4406 "match expression");
4407 if (ISDIGIT (id[strlen (id) - 1]))
4409 opt_grp = id[strlen (id) - 1] - '0' + 1;
4410 alt_id = xstrdup (id);
4411 alt_id[strlen (id) - 1] = '\0';
4412 if (opt_grp == 1)
4413 fatal_at (id_tok, "use '%s?' here", alt_id);
4415 else
4416 opt_grp = 1;
4417 eat_token (CPP_QUERY);
4419 id_base *op = get_operator (alt_id ? alt_id : id);
4420 if (!op)
4421 fatal_at (id_tok, "unknown operator %s", alt_id ? alt_id : id);
4422 if (alt_id)
4423 free (alt_id);
4424 user_id *p = dyn_cast<user_id *> (op);
4425 if (p && p->is_oper_list)
4427 if (active_fors.length() == 0)
4428 record_operlist (id_tok->src_loc, p);
4429 else
4430 fatal_at (id_tok, "operator-list %s cannot be expanded inside 'for'", id);
4432 return op;
4435 /* Parse a capture.
4436 capture = '@'<number> */
4438 class operand *
4439 parser::parse_capture (operand *op, bool require_existing)
4441 location_t src_loc = eat_token (CPP_ATSIGN)->src_loc;
4442 const cpp_token *token = peek ();
4443 const char *id = NULL;
4444 bool value_match = false;
4445 /* For matches parse @@ as a value-match denoting the prevailing operand. */
4446 if (token->type == CPP_ATSIGN
4447 && ! (token->flags & PREV_WHITE)
4448 && parsing_match_operand)
4450 eat_token (CPP_ATSIGN);
4451 token = peek ();
4452 value_match = true;
4454 if (token->type == CPP_NUMBER)
4455 id = get_number ();
4456 else if (token->type == CPP_NAME)
4457 id = get_ident ();
4458 else
4459 fatal_at (token, "expected number or identifier");
4460 unsigned next_id = capture_ids->elements ();
4461 bool existed;
4462 unsigned &num = capture_ids->get_or_insert (id, &existed);
4463 if (!existed)
4465 if (require_existing)
4466 fatal_at (src_loc, "unknown capture id");
4467 num = next_id;
4469 return new capture (src_loc, num, op, value_match);
4472 /* Parse an expression
4473 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
4475 class operand *
4476 parser::parse_expr ()
4478 const cpp_token *token = peek ();
4479 unsigned char opt_grp;
4480 expr *e = new expr (parse_operation (opt_grp), token->src_loc);
4481 token = peek ();
4482 operand *op;
4483 bool is_commutative = false;
4484 bool force_capture = false;
4485 const char *expr_type = NULL;
4487 if (!parsing_match_operand
4488 && token->type == CPP_NOT
4489 && !(token->flags & PREV_WHITE))
4491 eat_token (CPP_NOT);
4492 e->force_leaf = true;
4495 if (token->type == CPP_COLON
4496 && !(token->flags & PREV_WHITE))
4498 eat_token (CPP_COLON);
4499 token = peek ();
4500 if (token->type == CPP_NAME
4501 && !(token->flags & PREV_WHITE))
4503 const char *s = get_ident ();
4504 if (!parsing_match_operand)
4505 expr_type = s;
4506 else
4508 const char *sp = s;
4509 while (*sp)
4511 if (*sp == 'c')
4513 if (operator_id *o
4514 = dyn_cast<operator_id *> (e->operation))
4516 if (!commutative_tree_code (o->code)
4517 && !comparison_code_p (o->code))
4518 fatal_at (token, "operation is not commutative");
4520 else if (user_id *p = dyn_cast<user_id *> (e->operation))
4521 for (unsigned i = 0;
4522 i < p->substitutes.length (); ++i)
4524 if (operator_id *q
4525 = dyn_cast<operator_id *> (p->substitutes[i]))
4527 if (!commutative_tree_code (q->code)
4528 && !comparison_code_p (q->code))
4529 fatal_at (token, "operation %s is not "
4530 "commutative", q->id);
4533 is_commutative = true;
4535 else if (*sp == 'C')
4536 is_commutative = true;
4537 else if (*sp == 's')
4539 e->force_single_use = true;
4540 force_capture = true;
4542 else
4543 fatal_at (token, "flag %c not recognized", *sp);
4544 sp++;
4547 token = peek ();
4549 else
4550 fatal_at (token, "expected flag or type specifying identifier");
4553 if (token->type == CPP_ATSIGN
4554 && !(token->flags & PREV_WHITE))
4555 op = parse_capture (e, false);
4556 else if (force_capture)
4558 unsigned num = get_internal_capture_id ();
4559 op = new capture (token->src_loc, num, e, false);
4561 else
4562 op = e;
4565 token = peek ();
4566 if (token->type == CPP_CLOSE_PAREN)
4568 if (e->operation->nargs != -1
4569 && e->operation->nargs != (int) e->ops.length ())
4570 fatal_at (token, "'%s' expects %u operands, not %u",
4571 e->operation->id, e->operation->nargs, e->ops.length ());
4572 if (is_commutative)
4574 if (e->ops.length () == 2
4575 || commutative_op (e->operation) >= 0)
4576 e->is_commutative = true;
4577 else
4578 fatal_at (token, "only binary operators or functions with "
4579 "two arguments can be marked commutative, "
4580 "unless the operation is known to be inherently "
4581 "commutative");
4583 e->expr_type = expr_type;
4584 if (opt_grp != 0)
4586 if (e->ops.length () != 1)
4587 fatal_at (token, "only unary operations can be conditional");
4588 e->opt_grp = opt_grp;
4590 return op;
4592 else if (!(token->flags & PREV_WHITE))
4593 fatal_at (token, "expected expression operand");
4595 e->append_op (parse_op ());
4597 while (1);
4600 /* Lex native C code delimited by START recording the preprocessing tokens
4601 for later processing.
4602 c_expr = ('{'|'(') <pp token>... ('}'|')') */
4604 c_expr *
4605 parser::parse_c_expr (cpp_ttype start)
4607 const cpp_token *token;
4608 cpp_ttype end;
4609 unsigned opencnt;
4610 vec<cpp_token> code = vNULL;
4611 unsigned nr_stmts = 0;
4612 location_t loc = eat_token (start)->src_loc;
4613 if (start == CPP_OPEN_PAREN)
4614 end = CPP_CLOSE_PAREN;
4615 else if (start == CPP_OPEN_BRACE)
4616 end = CPP_CLOSE_BRACE;
4617 else
4618 gcc_unreachable ();
4619 opencnt = 1;
4622 token = next ();
4624 /* Count brace pairs to find the end of the expr to match. */
4625 if (token->type == start)
4626 opencnt++;
4627 else if (token->type == end
4628 && --opencnt == 0)
4629 break;
4630 else if (token->type == CPP_EOF)
4631 fatal_at (token, "unexpected end of file");
4633 /* This is a lame way of counting the number of statements. */
4634 if (token->type == CPP_SEMICOLON)
4635 nr_stmts++;
4637 /* If this is possibly a user-defined identifier mark it used. */
4638 if (token->type == CPP_NAME)
4640 const char *str
4641 = (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
4642 if (strcmp (str, "return") == 0)
4643 fatal_at (token, "return statement not allowed in C expression");
4644 id_base *idb = get_operator (str);
4645 user_id *p;
4646 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
4647 record_operlist (token->src_loc, p);
4650 /* Record the token. */
4651 code.safe_push (*token);
4653 while (1);
4654 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
4657 /* Parse an operand which is either an expression, a predicate or
4658 a standalone capture.
4659 op = predicate | expr | c_expr | capture */
4661 class operand *
4662 parser::parse_op ()
4664 const cpp_token *token = peek ();
4665 class operand *op = NULL;
4666 if (token->type == CPP_OPEN_PAREN)
4668 eat_token (CPP_OPEN_PAREN);
4669 op = parse_expr ();
4670 eat_token (CPP_CLOSE_PAREN);
4672 else if (token->type == CPP_OPEN_BRACE)
4674 op = parse_c_expr (CPP_OPEN_BRACE);
4676 else
4678 /* Remaining ops are either empty or predicates */
4679 if (token->type == CPP_NAME)
4681 const char *id = get_ident ();
4682 id_base *opr = get_operator (id);
4683 if (!opr)
4684 fatal_at (token, "expected predicate name");
4685 if (operator_id *code1 = dyn_cast <operator_id *> (opr))
4687 if (code1->nargs != 0)
4688 fatal_at (token, "using an operator with operands as predicate");
4689 /* Parse the zero-operand operator "predicates" as
4690 expression. */
4691 op = new expr (opr, token->src_loc);
4693 else if (user_id *code2 = dyn_cast <user_id *> (opr))
4695 if (code2->nargs != 0)
4696 fatal_at (token, "using an operator with operands as predicate");
4697 /* Parse the zero-operand operator "predicates" as
4698 expression. */
4699 op = new expr (opr, token->src_loc);
4701 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4702 op = new predicate (p, token->src_loc);
4703 else
4704 fatal_at (token, "using an unsupported operator as predicate");
4705 if (!parsing_match_operand)
4706 fatal_at (token, "predicates are only allowed in match expression");
4707 token = peek ();
4708 if (token->flags & PREV_WHITE)
4709 return op;
4711 else if (token->type != CPP_COLON
4712 && token->type != CPP_ATSIGN)
4713 fatal_at (token, "expected expression or predicate");
4714 /* optionally followed by a capture and a predicate. */
4715 if (token->type == CPP_COLON)
4716 fatal_at (token, "not implemented: predicate on leaf operand");
4717 if (token->type == CPP_ATSIGN)
4718 op = parse_capture (op, !parsing_match_operand);
4721 return op;
4724 /* Create a new simplify from the current parsing state and MATCH,
4725 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4727 void
4728 parser::push_simplify (simplify::simplify_kind kind,
4729 vec<simplify *>& simplifiers,
4730 operand *match, operand *result)
4732 /* Build and push a temporary for operator list uses in expressions. */
4733 if (!oper_lists.is_empty ())
4734 active_fors.safe_push (oper_lists);
4736 simplifiers.safe_push
4737 (new simplify (kind, last_id++, match, result,
4738 active_fors.copy (), capture_ids));
4740 if (!oper_lists.is_empty ())
4741 active_fors.pop ();
4744 /* Parse
4745 <result-op> = <op> | <if> | <with>
4746 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4747 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4748 and return it. */
4750 operand *
4751 parser::parse_result (operand *result, predicate_id *matcher)
4753 const cpp_token *token = peek ();
4754 if (token->type != CPP_OPEN_PAREN)
4755 return parse_op ();
4757 eat_token (CPP_OPEN_PAREN);
4758 if (peek_ident ("if"))
4760 eat_ident ("if");
4761 if_expr *ife = new if_expr (token->src_loc);
4762 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4763 if (peek ()->type == CPP_OPEN_PAREN)
4765 ife->trueexpr = parse_result (result, matcher);
4766 if (peek ()->type == CPP_OPEN_PAREN)
4767 ife->falseexpr = parse_result (result, matcher);
4768 else if (peek ()->type != CPP_CLOSE_PAREN)
4769 ife->falseexpr = parse_op ();
4771 else if (peek ()->type != CPP_CLOSE_PAREN)
4773 ife->trueexpr = parse_op ();
4774 if (peek ()->type == CPP_OPEN_PAREN)
4775 ife->falseexpr = parse_result (result, matcher);
4776 else if (peek ()->type != CPP_CLOSE_PAREN)
4777 ife->falseexpr = parse_op ();
4779 /* If this if is immediately closed then it contains a
4780 manual matcher or is part of a predicate definition. */
4781 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4783 if (!matcher)
4784 fatal_at (peek (), "manual transform not implemented");
4785 ife->trueexpr = result;
4787 eat_token (CPP_CLOSE_PAREN);
4788 return ife;
4790 else if (peek_ident ("with"))
4792 eat_ident ("with");
4793 with_expr *withe = new with_expr (token->src_loc);
4794 /* Parse (with c-expr expr) as (if-with (true) expr). */
4795 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4796 withe->with->nr_stmts = 0;
4797 withe->subexpr = parse_result (result, matcher);
4798 eat_token (CPP_CLOSE_PAREN);
4799 return withe;
4801 else if (peek_ident ("switch"))
4803 token = eat_ident ("switch");
4804 location_t ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4805 eat_ident ("if");
4806 if_expr *ife = new if_expr (ifloc);
4807 operand *res = ife;
4808 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4809 if (peek ()->type == CPP_OPEN_PAREN)
4810 ife->trueexpr = parse_result (result, matcher);
4811 else
4812 ife->trueexpr = parse_op ();
4813 eat_token (CPP_CLOSE_PAREN);
4814 if (peek ()->type != CPP_OPEN_PAREN
4815 || !peek_ident ("if", 2))
4816 fatal_at (token, "switch can be implemented with a single if");
4817 while (peek ()->type != CPP_CLOSE_PAREN)
4819 if (peek ()->type == CPP_OPEN_PAREN)
4821 if (peek_ident ("if", 2))
4823 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4824 eat_ident ("if");
4825 ife->falseexpr = new if_expr (ifloc);
4826 ife = as_a <if_expr *> (ife->falseexpr);
4827 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4828 if (peek ()->type == CPP_OPEN_PAREN)
4829 ife->trueexpr = parse_result (result, matcher);
4830 else
4831 ife->trueexpr = parse_op ();
4832 eat_token (CPP_CLOSE_PAREN);
4834 else
4836 /* switch default clause */
4837 ife->falseexpr = parse_result (result, matcher);
4838 eat_token (CPP_CLOSE_PAREN);
4839 return res;
4842 else
4844 /* switch default clause */
4845 ife->falseexpr = parse_op ();
4846 eat_token (CPP_CLOSE_PAREN);
4847 return res;
4850 eat_token (CPP_CLOSE_PAREN);
4851 return res;
4853 else
4855 operand *op = result;
4856 if (!matcher)
4857 op = parse_expr ();
4858 eat_token (CPP_CLOSE_PAREN);
4859 return op;
4863 /* Parse
4864 simplify = 'simplify' <expr> <result-op>
4866 match = 'match' <ident> <expr> [<result-op>]
4867 and fill SIMPLIFIERS with the results. */
4869 void
4870 parser::parse_simplify (simplify::simplify_kind kind,
4871 vec<simplify *>& simplifiers, predicate_id *matcher,
4872 operand *result)
4874 /* Reset the capture map. */
4875 if (!capture_ids)
4876 capture_ids = new cid_map_t;
4877 /* Reset oper_lists and set. */
4878 hash_set <user_id *> olist;
4879 oper_lists_set = &olist;
4880 oper_lists = vNULL;
4882 const cpp_token *loc = peek ();
4883 parsing_match_operand = true;
4884 class operand *match = parse_op ();
4885 finish_match_operand (match);
4886 parsing_match_operand = false;
4887 if (match->type == operand::OP_CAPTURE && !matcher)
4888 fatal_at (loc, "outermost expression cannot be captured");
4889 if (match->type == operand::OP_EXPR
4890 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4891 fatal_at (loc, "outermost expression cannot be a predicate");
4893 /* Splice active_ifs onto result and continue parsing the
4894 "then" expr. */
4895 if_expr *active_if = NULL;
4896 for (int i = active_ifs.length (); i > 0; --i)
4898 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4899 ifc->cond = active_ifs[i-1];
4900 ifc->trueexpr = active_if;
4901 active_if = ifc;
4903 if_expr *outermost_if = active_if;
4904 while (active_if && active_if->trueexpr)
4905 active_if = as_a <if_expr *> (active_if->trueexpr);
4907 const cpp_token *token = peek ();
4909 /* If this if is immediately closed then it is part of a predicate
4910 definition. Push it. */
4911 if (token->type == CPP_CLOSE_PAREN)
4913 if (!matcher)
4914 fatal_at (token, "expected transform expression");
4915 if (active_if)
4917 active_if->trueexpr = result;
4918 result = outermost_if;
4920 push_simplify (kind, simplifiers, match, result);
4921 return;
4924 operand *tem = parse_result (result, matcher);
4925 if (active_if)
4927 active_if->trueexpr = tem;
4928 result = outermost_if;
4930 else
4931 result = tem;
4933 push_simplify (kind, simplifiers, match, result);
4936 /* Parsing of the outer control structures. */
4938 /* Parse a for expression
4939 for = '(' 'for' <subst>... <pattern> ')'
4940 subst = <ident> '(' <ident>... ')' */
4942 void
4943 parser::parse_for (location_t)
4945 auto_vec<const cpp_token *> user_id_tokens;
4946 vec<user_id *> user_ids = vNULL;
4947 const cpp_token *token;
4948 unsigned min_n_opers = 0, max_n_opers = 0;
4950 while (1)
4952 token = peek ();
4953 if (token->type != CPP_NAME)
4954 break;
4956 /* Insert the user defined operators into the operator hash. */
4957 const char *id = get_ident ();
4958 if (get_operator (id, true) != NULL)
4959 fatal_at (token, "operator already defined");
4960 user_id *op = new user_id (id);
4961 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4962 *slot = op;
4963 user_ids.safe_push (op);
4964 user_id_tokens.safe_push (token);
4966 eat_token (CPP_OPEN_PAREN);
4968 int arity = -1;
4969 while ((token = peek_ident ()) != 0)
4971 const char *oper = get_ident ();
4972 id_base *idb = get_operator (oper, true);
4973 if (idb == NULL)
4974 fatal_at (token, "no such operator '%s'", oper);
4976 if (arity == -1)
4977 arity = idb->nargs;
4978 else if (idb->nargs == -1)
4980 else if (idb->nargs != arity)
4981 fatal_at (token, "operator '%s' with arity %d does not match "
4982 "others with arity %d", oper, idb->nargs, arity);
4984 user_id *p = dyn_cast<user_id *> (idb);
4985 if (p)
4987 if (p->is_oper_list)
4988 op->substitutes.safe_splice (p->substitutes);
4989 else
4990 fatal_at (token, "iterator cannot be used as operator-list");
4992 else
4993 op->substitutes.safe_push (idb);
4995 op->nargs = arity;
4996 token = expect (CPP_CLOSE_PAREN);
4998 unsigned nsubstitutes = op->substitutes.length ();
4999 if (nsubstitutes == 0)
5000 fatal_at (token, "A user-defined operator must have at least "
5001 "one substitution");
5002 if (max_n_opers == 0)
5004 min_n_opers = nsubstitutes;
5005 max_n_opers = nsubstitutes;
5007 else
5009 if (nsubstitutes % min_n_opers != 0
5010 && min_n_opers % nsubstitutes != 0)
5011 fatal_at (token, "All user-defined identifiers must have a "
5012 "multiple number of operator substitutions of the "
5013 "smallest number of substitutions");
5014 if (nsubstitutes < min_n_opers)
5015 min_n_opers = nsubstitutes;
5016 else if (nsubstitutes > max_n_opers)
5017 max_n_opers = nsubstitutes;
5021 unsigned n_ids = user_ids.length ();
5022 if (n_ids == 0)
5023 fatal_at (token, "for requires at least one user-defined identifier");
5025 token = peek ();
5026 if (token->type == CPP_CLOSE_PAREN)
5027 fatal_at (token, "no pattern defined in for");
5029 active_fors.safe_push (user_ids);
5030 while (1)
5032 token = peek ();
5033 if (token->type == CPP_CLOSE_PAREN)
5034 break;
5035 parse_pattern ();
5037 active_fors.pop ();
5039 /* Remove user-defined operators from the hash again. */
5040 for (unsigned i = 0; i < user_ids.length (); ++i)
5042 if (!user_ids[i]->used)
5043 warning_at (user_id_tokens[i],
5044 "operator %s defined but not used", user_ids[i]->id);
5045 operators->remove_elt (user_ids[i]);
5049 /* Parse an identifier associated with a list of operators.
5050 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
5052 void
5053 parser::parse_operator_list (location_t)
5055 const cpp_token *token = peek ();
5056 const char *id = get_ident ();
5058 if (get_operator (id, true) != 0)
5059 fatal_at (token, "operator %s already defined", id);
5061 user_id *op = new user_id (id, true);
5062 int arity = -1;
5064 while ((token = peek_ident ()) != 0)
5066 token = peek ();
5067 const char *oper = get_ident ();
5068 id_base *idb = get_operator (oper, true);
5070 if (idb == 0)
5071 fatal_at (token, "no such operator '%s'", oper);
5073 if (arity == -1)
5074 arity = idb->nargs;
5075 else if (idb->nargs == -1)
5077 else if (arity != idb->nargs)
5078 fatal_at (token, "operator '%s' with arity %d does not match "
5079 "others with arity %d", oper, idb->nargs, arity);
5081 /* We allow composition of multiple operator lists. */
5082 if (user_id *p = dyn_cast<user_id *> (idb))
5083 op->substitutes.safe_splice (p->substitutes);
5084 else
5085 op->substitutes.safe_push (idb);
5088 // Check that there is no junk after id-list
5089 token = peek();
5090 if (token->type != CPP_CLOSE_PAREN)
5091 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
5093 if (op->substitutes.length () == 0)
5094 fatal_at (token, "operator-list cannot be empty");
5096 op->nargs = arity;
5097 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
5098 *slot = op;
5101 /* Parse an outer if expression.
5102 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
5104 void
5105 parser::parse_if (location_t)
5107 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
5109 const cpp_token *token = peek ();
5110 if (token->type == CPP_CLOSE_PAREN)
5111 fatal_at (token, "no pattern defined in if");
5113 active_ifs.safe_push (ifexpr);
5114 while (1)
5116 token = peek ();
5117 if (token->type == CPP_CLOSE_PAREN)
5118 break;
5120 parse_pattern ();
5122 active_ifs.pop ();
5125 /* Parse a list of predefined predicate identifiers.
5126 preds = '(' 'define_predicates' <ident>... ')' */
5128 void
5129 parser::parse_predicates (location_t)
5133 const cpp_token *token = peek ();
5134 if (token->type != CPP_NAME)
5135 break;
5137 add_predicate (get_ident ());
5139 while (1);
5142 /* Parse outer control structures.
5143 pattern = <preds>|<for>|<if>|<simplify>|<match> */
5145 void
5146 parser::parse_pattern ()
5148 /* All clauses start with '('. */
5149 eat_token (CPP_OPEN_PAREN);
5150 const cpp_token *token = peek ();
5151 const char *id = get_ident ();
5152 if (strcmp (id, "simplify") == 0)
5154 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
5155 capture_ids = NULL;
5157 else if (strcmp (id, "match") == 0)
5159 bool with_args = false;
5160 location_t e_loc = peek ()->src_loc;
5161 if (peek ()->type == CPP_OPEN_PAREN)
5163 eat_token (CPP_OPEN_PAREN);
5164 with_args = true;
5166 const char *name = get_ident ();
5167 id_base *id1 = get_operator (name);
5168 predicate_id *p;
5169 if (!id1)
5171 p = add_predicate (name);
5172 user_predicates.safe_push (p);
5174 else if ((p = dyn_cast <predicate_id *> (id1)))
5176 else
5177 fatal_at (token, "cannot add a match to a non-predicate ID");
5178 /* Parse (match <id> <arg>... (match-expr)) here. */
5179 expr *e = NULL;
5180 if (with_args)
5182 capture_ids = new cid_map_t;
5183 e = new expr (p, e_loc);
5184 while (peek ()->type == CPP_ATSIGN)
5185 e->append_op (parse_capture (NULL, false));
5186 eat_token (CPP_CLOSE_PAREN);
5188 if (p->nargs != -1
5189 && ((e && e->ops.length () != (unsigned)p->nargs)
5190 || (!e && p->nargs != 0)))
5191 fatal_at (token, "non-matching number of match operands");
5192 p->nargs = e ? e->ops.length () : 0;
5193 parse_simplify (simplify::MATCH, p->matchers, p, e);
5194 capture_ids = NULL;
5196 else if (strcmp (id, "for") == 0)
5197 parse_for (token->src_loc);
5198 else if (strcmp (id, "if") == 0)
5199 parse_if (token->src_loc);
5200 else if (strcmp (id, "define_predicates") == 0)
5202 if (active_ifs.length () > 0
5203 || active_fors.length () > 0)
5204 fatal_at (token, "define_predicates inside if or for is not supported");
5205 parse_predicates (token->src_loc);
5207 else if (strcmp (id, "define_operator_list") == 0)
5209 if (active_ifs.length () > 0
5210 || active_fors.length () > 0)
5211 fatal_at (token, "operator-list inside if or for is not supported");
5212 parse_operator_list (token->src_loc);
5214 else
5215 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
5216 active_ifs.length () == 0 && active_fors.length () == 0
5217 ? "'define_predicates', " : "");
5219 eat_token (CPP_CLOSE_PAREN);
5222 /* Helper for finish_match_operand, collecting captures of OP in CPTS
5223 recursively. */
5225 static void
5226 walk_captures (operand *op, vec<vec<capture *> > &cpts)
5228 if (! op)
5229 return;
5231 if (capture *c = dyn_cast <capture *> (op))
5233 cpts[c->where].safe_push (c);
5234 walk_captures (c->what, cpts);
5236 else if (expr *e = dyn_cast <expr *> (op))
5237 for (unsigned i = 0; i < e->ops.length (); ++i)
5238 walk_captures (e->ops[i], cpts);
5241 /* Finish up OP which is a match operand. */
5243 void
5244 parser::finish_match_operand (operand *op)
5246 /* Look for matching captures, diagnose mis-uses of @@ and apply
5247 early lowering and distribution of value_match. */
5248 auto_vec<vec<capture *> > cpts;
5249 cpts.safe_grow_cleared (capture_ids->elements (), true);
5250 walk_captures (op, cpts);
5251 for (unsigned i = 0; i < cpts.length (); ++i)
5253 capture *value_match = NULL;
5254 for (unsigned j = 0; j < cpts[i].length (); ++j)
5256 if (cpts[i][j]->value_match)
5258 if (value_match)
5259 fatal_at (cpts[i][j]->location, "duplicate @@");
5260 value_match = cpts[i][j];
5263 if (cpts[i].length () == 1 && value_match)
5264 fatal_at (value_match->location, "@@ without a matching capture");
5265 if (value_match)
5267 /* Duplicate prevailing capture with the existing ID, create
5268 a fake ID and rewrite all captures to use it. This turns
5269 @@1 into @__<newid>@1 and @1 into @__<newid>. */
5270 value_match->what = new capture (value_match->location,
5271 value_match->where,
5272 value_match->what, false);
5273 /* Create a fake ID and rewrite all captures to use it. */
5274 unsigned newid = get_internal_capture_id ();
5275 for (unsigned j = 0; j < cpts[i].length (); ++j)
5277 cpts[i][j]->where = newid;
5278 cpts[i][j]->value_match = true;
5281 cpts[i].release ();
5285 /* Main entry of the parser. Repeatedly parse outer control structures. */
5287 parser::parser (cpp_reader *r_, bool gimple_)
5289 r = r_;
5290 gimple = gimple_;
5291 active_ifs = vNULL;
5292 active_fors = vNULL;
5293 simplifiers = vNULL;
5294 oper_lists_set = NULL;
5295 oper_lists = vNULL;
5296 capture_ids = NULL;
5297 user_predicates = vNULL;
5298 parsing_match_operand = false;
5299 last_id = 0;
5301 const cpp_token *token = next ();
5302 while (token->type != CPP_EOF)
5304 _cpp_backup_tokens (r, 1);
5305 parse_pattern ();
5306 token = next ();
5311 /* Helper for the linemap code. */
5313 static size_t
5314 round_alloc_size (size_t s)
5316 return s;
5320 /* Construct and display the help menu. */
5322 static void
5323 usage ()
5325 const char *usage = "Usage:\n"
5326 " %s [--gimple|--generic] [-v[v]] <input>\n"
5327 " %s [options] [--include=FILE] --header=FILE <input> <output>...\n";
5328 fprintf (stderr, usage, progname, progname);
5331 /* Write out the correct include to the match-head fle containing the helper
5332 files. */
5334 static void
5335 write_header_includes (bool gimple, FILE *header_file)
5337 if (gimple)
5338 fprintf (header_file, "#include \"gimple-match-head.cc\"\n");
5339 else
5340 fprintf (header_file, "#include \"generic-match-head.cc\"\n");
5343 /* The genmatch generator program. It reads from a pattern description
5344 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
5347 main (int argc, char **argv)
5349 cpp_reader *r;
5351 progname = "genmatch";
5353 bool gimple = true;
5354 char *s_header_file = NULL;
5355 char *s_include_file = NULL;
5356 auto_vec <char *> files;
5357 char *input = NULL;
5358 int last_file = argc - 1;
5359 for (int i = argc - 1; i >= 1; --i)
5361 if (strcmp (argv[i], "--gimple") == 0)
5362 gimple = true;
5363 else if (strcmp (argv[i], "--generic") == 0)
5364 gimple = false;
5365 else if (strncmp (argv[i], "--header=", 9) == 0)
5366 s_header_file = &argv[i][9];
5367 else if (strncmp (argv[i], "--include=", 10) == 0)
5368 s_include_file = &argv[i][10];
5369 else if (strcmp (argv[i], "-v") == 0)
5370 verbose = 1;
5371 else if (strcmp (argv[i], "-vv") == 0)
5372 verbose = 2;
5373 else if (strncmp (argv[i], "--", 2) != 0 && last_file-- == i)
5374 files.safe_push (argv[i]);
5375 else
5377 usage ();
5378 return 1;
5382 /* Validate if the combinations are valid. */
5383 if ((files.length () > 1 && !s_header_file) || files.is_empty ())
5385 usage ();
5386 return 1;
5389 if (!s_include_file)
5390 s_include_file = s_header_file;
5392 /* Input file is the last in the reverse list. */
5393 input = files.pop ();
5395 line_table = XCNEW (class line_maps);
5396 linemap_init (line_table, 0);
5397 line_table->reallocator = xrealloc;
5398 line_table->round_alloc_size = round_alloc_size;
5400 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
5401 cpp_callbacks *cb = cpp_get_callbacks (r);
5402 cb->diagnostic = diagnostic_cb;
5404 /* Add the build directory to the #include "" search path. */
5405 cpp_dir *dir = XCNEW (cpp_dir);
5406 dir->name = getpwd ();
5407 if (!dir->name)
5408 dir->name = ASTRDUP (".");
5409 cpp_set_include_chains (r, dir, NULL, false);
5411 if (!cpp_read_main_file (r, input))
5412 return 1;
5413 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
5414 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
5416 null_id = new id_base (id_base::NULL_ID, "null");
5418 /* Pre-seed operators. */
5419 operators = new hash_table<id_base> (1024);
5420 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
5421 add_operator (SYM, # SYM, # TYPE, NARGS);
5422 #define END_OF_BASE_TREE_CODES
5423 #include "tree.def"
5424 #undef END_OF_BASE_TREE_CODES
5425 #undef DEFTREECODE
5427 /* Pre-seed builtin functions.
5428 ??? Cannot use N (name) as that is targetm.emultls.get_address
5429 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
5430 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
5431 add_function (ENUM, "CFN_" # ENUM);
5432 #include "builtins.def"
5434 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
5435 add_function (IFN_##CODE, "CFN_" #CODE);
5436 #include "internal-fn.def"
5438 /* Parse ahead! */
5439 parser p (r, gimple);
5441 /* Create file buffers. */
5442 int n_parts = files.is_empty () ? 1 : files.length ();
5443 auto_vec <FILE *> parts (n_parts);
5444 if (files.is_empty ())
5446 parts.quick_push (stdout);
5447 write_header (stdout, s_include_file);
5448 write_header_includes (gimple, stdout);
5450 else
5452 for (char *s_file : files)
5454 parts.quick_push (fopen (s_file, "w"));
5455 write_header (parts.last (), s_include_file);
5458 header_file = fopen (s_header_file, "w");
5459 fprintf (header_file, "#ifndef GCC_GIMPLE_MATCH_AUTO_H\n"
5460 "#define GCC_GIMPLE_MATCH_AUTO_H\n");
5461 write_header_includes (gimple, header_file);
5464 /* Go over all predicates defined with patterns and perform
5465 lowering and code generation. */
5466 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
5468 predicate_id *pred = p.user_predicates[i];
5469 lower (pred->matchers, gimple);
5471 if (verbose == 2)
5472 for (unsigned j = 0; j < pred->matchers.length (); ++j)
5473 print_matches (pred->matchers[j]);
5475 decision_tree dt;
5476 for (unsigned j = 0; j < pred->matchers.length (); ++j)
5477 dt.insert (pred->matchers[j], j);
5479 if (verbose == 2)
5480 dt.print (stderr);
5482 /* Cycle the file buffers. */
5483 FILE *f = choose_output (parts);
5485 write_predicate (f, pred, dt, gimple);
5488 /* Lower the main simplifiers and generate code for them. */
5489 lower (p.simplifiers, gimple);
5491 if (verbose == 2)
5492 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5493 print_matches (p.simplifiers[i]);
5495 decision_tree dt;
5496 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5497 dt.insert (p.simplifiers[i], i);
5499 if (verbose == 2)
5500 dt.print (stderr);
5502 dt.gen (parts, gimple);
5504 for (FILE *f : parts)
5506 fprintf (f, "#pragma GCC diagnostic pop\n");
5507 fclose (f);
5510 if (header_file)
5512 fprintf (header_file, "\n#endif /* GCC_GIMPLE_MATCH_AUTO_H. */\n");
5513 fclose (header_file);
5516 /* Finalize. */
5517 cpp_finish (r, NULL);
5518 cpp_destroy (r);
5520 delete operators;
5522 return 0;